arrayff 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- arrayff/__init__.py +29 -0
- arrayff/electrostatics/__init__.py +20 -0
- arrayff/electrostatics/calculator.py +18 -0
- arrayff/electrostatics/placeholders.py +23 -0
- arrayff/electrostatics/qeq.py +498 -0
- arrayff/neighbors/__init__.py +9 -0
- arrayff/neighbors/_list.py +649 -0
- arrayff/neighbors/_table.py +388 -0
- arrayff/potentials/__init__.py +76 -0
- arrayff/potentials/_torch.py +44 -0
- arrayff/potentials/base.py +720 -0
- arrayff/potentials/calculator.py +146 -0
- arrayff/potentials/composite.py +142 -0
- arrayff/potentials/eam/__init__.py +1 -0
- arrayff/potentials/eam/_torch.py +31 -0
- arrayff/potentials/eam/calculator.py +20 -0
- arrayff/potentials/eam/eam.py +233 -0
- arrayff/potentials/eam/io/__init__.py +8 -0
- arrayff/potentials/eam/io/eam.py +115 -0
- arrayff/potentials/emt/__init__.py +1 -0
- arrayff/potentials/emt/_torch.py +38 -0
- arrayff/potentials/emt/calculator.py +18 -0
- arrayff/potentials/emt/emt.py +353 -0
- arrayff/potentials/pairwise/__init__.py +21 -0
- arrayff/potentials/pairwise/_pairs.py +36 -0
- arrayff/potentials/pairwise/_torch.py +181 -0
- arrayff/potentials/pairwise/base.py +346 -0
- arrayff/potentials/pairwise/calculator.py +43 -0
- arrayff/potentials/pairwise/forms.py +147 -0
- arrayff/potentials/pairwise/lj.py +134 -0
- arrayff/potentials/pairwise/lj93.py +85 -0
- arrayff/potentials/pairwise/lj_kim.py +138 -0
- arrayff/potentials/pairwise/morse.py +100 -0
- arrayff/potentials/pairwise/params.py +50 -0
- arrayff/potentials/placeholders.py +37 -0
- arrayff/potentials/registry.py +49 -0
- arrayff/py.typed +0 -0
- arrayff/utils/__init__.py +50 -0
- arrayff/utils/ad.py +272 -0
- arrayff/utils/ase.py +68 -0
- arrayff/utils/backend.py +101 -0
- arrayff/utils/dispatch.py +118 -0
- arrayff/utils/exceptions.py +19 -0
- arrayff/utils/interp.py +77 -0
- arrayff/utils/jit.py +51 -0
- arrayff/utils/optional.py +38 -0
- arrayff-0.0.1.dist-info/METADATA +142 -0
- arrayff-0.0.1.dist-info/RECORD +50 -0
- arrayff-0.0.1.dist-info/WHEEL +4 -0
- arrayff-0.0.1.dist-info/licenses/src/LICENSE +674 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""EMT potential."""
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Optional torch wrapper for the effective medium theory potential."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import torch
|
|
8
|
+
from torch import nn
|
|
9
|
+
|
|
10
|
+
from arrayff.potentials._torch import TorchPotential
|
|
11
|
+
from arrayff.potentials.emt.emt import EMT
|
|
12
|
+
|
|
13
|
+
__all__ = ["EMTTorch"]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class EMTTorch(EMT, TorchPotential):
|
|
17
|
+
"""Torch module version of :class:`arrayff.potentials.EMT`.
|
|
18
|
+
|
|
19
|
+
The EMT parameters are tabulated per element and kept frozen; the module
|
|
20
|
+
exists so EMT energies and forces can participate in torch graphs (e.g.
|
|
21
|
+
as a reference model in a training loss).
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
def __init__(
|
|
25
|
+
self,
|
|
26
|
+
*,
|
|
27
|
+
max_neighbors: int | None = None,
|
|
28
|
+
dtype: torch.dtype = torch.float64,
|
|
29
|
+
**kwargs: Any,
|
|
30
|
+
) -> None:
|
|
31
|
+
nn.Module.__init__(self)
|
|
32
|
+
EMT.__init__(
|
|
33
|
+
self,
|
|
34
|
+
backend="torch",
|
|
35
|
+
dtype=dtype,
|
|
36
|
+
max_neighbors=max_neighbors,
|
|
37
|
+
**kwargs,
|
|
38
|
+
)
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""ASE calculator for the effective medium theory potential."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from arrayff.potentials.calculator import ArrayFFCalculator, split_kwargs
|
|
8
|
+
from arrayff.potentials.emt.emt import EMT
|
|
9
|
+
|
|
10
|
+
__all__ = ["EMTCalculator"]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class EMTCalculator(ArrayFFCalculator):
|
|
14
|
+
"""Effective medium theory calculator."""
|
|
15
|
+
|
|
16
|
+
def __init__(self, **kwargs: Any) -> None:
|
|
17
|
+
potential_kwargs, calculator_kwargs = split_kwargs(kwargs, EMT)
|
|
18
|
+
super().__init__(EMT(**potential_kwargs), **calculator_kwargs)
|
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
"""Effective medium theory potential.
|
|
2
|
+
|
|
3
|
+
Follows the implementation in :mod:`ase.calculators.emt` (Jacobsen, Stoltze
|
|
4
|
+
and Norskov, Surf. Sci. 366, 394 (1996)), rewritten as a vectorised kernel over
|
|
5
|
+
the padded neighbour table. The energy matches ASE; forces are obtained by
|
|
6
|
+
automatic differentiation instead of hand coded derivatives.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from math import log, sqrt
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
from ase.data import chemical_symbols
|
|
16
|
+
from ase.units import Bohr
|
|
17
|
+
|
|
18
|
+
from arrayff.potentials.pairwise._pairs import pair_distances, pair_vectors
|
|
19
|
+
from arrayff.potentials.base import Potential
|
|
20
|
+
from arrayff.potentials.registry import register_potential
|
|
21
|
+
from arrayff.utils.dispatch import do, to_backend
|
|
22
|
+
from arrayff.neighbors._table import NeighborPaddedTable
|
|
23
|
+
|
|
24
|
+
__all__ = ["EMT", "EMT_PARAMETERS", "beta"]
|
|
25
|
+
|
|
26
|
+
#: (E0 [eV], s0 [bohr], V0 [eV], eta2 [1/bohr], kappa [1/bohr],
|
|
27
|
+
#: lambda [1/bohr], n0 [1/bohr^3])
|
|
28
|
+
EMT_PARAMETERS: dict[
|
|
29
|
+
str, tuple[float, float, float, float, float, float, float]
|
|
30
|
+
] = {
|
|
31
|
+
"Al": (-3.28, 3.00, 1.493, 1.240, 2.000, 1.169, 0.00700),
|
|
32
|
+
"Cu": (-3.51, 2.67, 2.476, 1.652, 2.740, 1.906, 0.00910),
|
|
33
|
+
"Ag": (-2.96, 3.01, 2.132, 1.652, 2.790, 1.892, 0.00547),
|
|
34
|
+
"Au": (-3.80, 3.00, 2.321, 1.674, 2.873, 2.182, 0.00703),
|
|
35
|
+
"Ni": (-4.44, 2.60, 3.673, 1.669, 2.757, 1.948, 0.01030),
|
|
36
|
+
"Pd": (-3.90, 2.87, 2.773, 1.818, 3.107, 2.155, 0.00688),
|
|
37
|
+
"Pt": (-5.85, 2.90, 4.067, 1.812, 3.145, 2.192, 0.00802),
|
|
38
|
+
"H": (-3.21, 1.31, 0.132, 2.652, 2.790, 3.892, 0.00547),
|
|
39
|
+
"C": (-3.50, 1.81, 0.332, 1.652, 2.790, 1.892, 0.01322),
|
|
40
|
+
"N": (-5.10, 1.88, 0.132, 1.652, 2.790, 1.892, 0.01222),
|
|
41
|
+
"O": (-4.60, 1.95, 0.332, 1.652, 2.790, 1.892, 0.00850),
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
#: ``(16 * pi / 3) ** (1/3) / sqrt(2)`` with the historical rounding.
|
|
45
|
+
beta = 1.809
|
|
46
|
+
|
|
47
|
+
#: Parameters at which the logistic cutoff is ``1e-4``.
|
|
48
|
+
_CUTOFF_EPS = 1e-4
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _gamma1_gamma2(
|
|
52
|
+
s0: float, eta2: float, kappa: float, rc: float, acut: float
|
|
53
|
+
):
|
|
54
|
+
"""Return the two fcc lattice sums used by EMT (ASE convention)."""
|
|
55
|
+
n = np.array([12.0, 6.0, 24.0])
|
|
56
|
+
r = beta * s0 * np.sqrt([1.0, 2.0, 3.0])
|
|
57
|
+
w = 1.0 / (1.0 + np.exp(acut * (r - rc)))
|
|
58
|
+
x = n * w / 12.0
|
|
59
|
+
gamma1 = float(x @ np.exp(-eta2 * (r - beta * s0)))
|
|
60
|
+
gamma2 = float(x @ np.exp(-kappa / beta * (r - beta * s0)))
|
|
61
|
+
return gamma1, gamma2
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _cutoff(
|
|
65
|
+
asap_cutoff: bool, numbers: np.ndarray | None
|
|
66
|
+
) -> tuple[float, float, float]:
|
|
67
|
+
"""Return ``(rc, rc_list)`` of the logistic cutoff."""
|
|
68
|
+
if asap_cutoff and numbers is not None:
|
|
69
|
+
symbols = {chemical_symbols[int(z)] for z in np.unique(numbers)}
|
|
70
|
+
s0_max = max(EMT_PARAMETERS[s][1] for s in symbols) * Bohr
|
|
71
|
+
else:
|
|
72
|
+
s0_max = max(p[1] for p in EMT_PARAMETERS.values()) * Bohr
|
|
73
|
+
r1nn = beta * s0_max
|
|
74
|
+
rc = r1nn * 0.5 * (sqrt(3.0) + 2.0)
|
|
75
|
+
r4nn = 2.0 * r1nn
|
|
76
|
+
acut = log(1.0 / _CUTOFF_EPS - 1.0) / (r4nn - rc)
|
|
77
|
+
rc_list = rc * 1.045 if asap_cutoff else rc + 0.5
|
|
78
|
+
return rc, rc_list, acut
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@register_potential("emt")
|
|
82
|
+
class EMT(Potential):
|
|
83
|
+
"""Effective medium theory for Al, Cu, Ag, Au, Ni, Pd, Pt (plus H/C/N/O)."""
|
|
84
|
+
|
|
85
|
+
name = "emt"
|
|
86
|
+
|
|
87
|
+
def __init__(
|
|
88
|
+
self,
|
|
89
|
+
cutoff: float | None = None,
|
|
90
|
+
*,
|
|
91
|
+
asap_cutoff: bool = False,
|
|
92
|
+
backend: str = "numpy",
|
|
93
|
+
dtype: Any = None,
|
|
94
|
+
max_neighbors: int | None = None,
|
|
95
|
+
builder: str = "sklearn",
|
|
96
|
+
skin: float = 0.0,
|
|
97
|
+
jit: bool = False,
|
|
98
|
+
method: str = "analytic",
|
|
99
|
+
) -> None:
|
|
100
|
+
self.asap_cutoff = bool(asap_cutoff)
|
|
101
|
+
self._param_cache: dict[tuple[int, ...], dict[str, Any]] = {}
|
|
102
|
+
self.rc, rc_list, self.acut = _cutoff(self.asap_cutoff, None)
|
|
103
|
+
super().__init__(
|
|
104
|
+
cutoff or rc_list,
|
|
105
|
+
backend=backend,
|
|
106
|
+
dtype=dtype,
|
|
107
|
+
max_neighbors=max_neighbors,
|
|
108
|
+
builder=builder,
|
|
109
|
+
skin=skin,
|
|
110
|
+
jit=jit,
|
|
111
|
+
method=method,
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
def _cutoff_for(self, atoms) -> float:
|
|
115
|
+
if not self.asap_cutoff:
|
|
116
|
+
return self.cutoff
|
|
117
|
+
return _cutoff(True, np.asarray(atoms.numbers))[1]
|
|
118
|
+
|
|
119
|
+
def element_parameters(self, elements: np.ndarray) -> dict[str, Any]:
|
|
120
|
+
key = tuple(int(z) for z in elements)
|
|
121
|
+
cached = self._param_cache.get(key)
|
|
122
|
+
if cached is not None:
|
|
123
|
+
return cached
|
|
124
|
+
rows = []
|
|
125
|
+
for z in elements:
|
|
126
|
+
symbol = chemical_symbols[int(z)]
|
|
127
|
+
if symbol not in EMT_PARAMETERS:
|
|
128
|
+
raise NotImplementedError(
|
|
129
|
+
f"No EMT potential for {symbol} (Z={int(z)})"
|
|
130
|
+
)
|
|
131
|
+
rows.append(EMT_PARAMETERS[symbol])
|
|
132
|
+
table = np.array(rows, dtype=float)
|
|
133
|
+
rc, rc_list, acut = _cutoff(self.asap_cutoff, elements)
|
|
134
|
+
s0 = table[:, 1] * Bohr
|
|
135
|
+
eta2 = table[:, 3] / Bohr
|
|
136
|
+
kappa = table[:, 4] / Bohr
|
|
137
|
+
gamma1 = np.empty(len(rows))
|
|
138
|
+
gamma2 = np.empty(len(rows))
|
|
139
|
+
for i, (s0_i, eta2_i, kappa_i) in enumerate(zip(s0, eta2, kappa)):
|
|
140
|
+
gamma1[i], gamma2[i] = _gamma1_gamma2(
|
|
141
|
+
float(s0_i), float(eta2_i), float(kappa_i), rc, acut
|
|
142
|
+
)
|
|
143
|
+
data = {
|
|
144
|
+
"E0": table[:, 0],
|
|
145
|
+
"s0": s0,
|
|
146
|
+
"V0": table[:, 2],
|
|
147
|
+
"eta2": eta2,
|
|
148
|
+
"kappa": kappa,
|
|
149
|
+
"lambda": table[:, 5] / Bohr,
|
|
150
|
+
"n0": table[:, 6] / Bohr**3,
|
|
151
|
+
"inv12gamma1": 1.0 / (12.0 * gamma1),
|
|
152
|
+
"neghalfv0overgamma2": -0.5 * table[:, 2] / gamma2,
|
|
153
|
+
"rc": rc,
|
|
154
|
+
"acut": acut,
|
|
155
|
+
"cutoff": rc_list,
|
|
156
|
+
}
|
|
157
|
+
result = {
|
|
158
|
+
name: to_backend(value, self.backend)
|
|
159
|
+
for name, value in data.items()
|
|
160
|
+
}
|
|
161
|
+
self._param_cache[key] = result
|
|
162
|
+
return result
|
|
163
|
+
|
|
164
|
+
def _emt_terms(
|
|
165
|
+
self,
|
|
166
|
+
positions: Any,
|
|
167
|
+
species: Any,
|
|
168
|
+
table: NeighborPaddedTable,
|
|
169
|
+
cell: Any,
|
|
170
|
+
params: dict[str, Any],
|
|
171
|
+
*,
|
|
172
|
+
with_derivatives: bool,
|
|
173
|
+
) -> tuple[Any, Any, Any]:
|
|
174
|
+
index = table.index
|
|
175
|
+
mask = table.mask
|
|
176
|
+
if index.shape[1] == 0:
|
|
177
|
+
energy = -do("sum", params["E0"][species])
|
|
178
|
+
if not with_derivatives:
|
|
179
|
+
return energy, None, None
|
|
180
|
+
zeros = do("zeros_like", positions)
|
|
181
|
+
return energy, zeros, do("zeros", (3, 3), like=positions)
|
|
182
|
+
|
|
183
|
+
cutoff = params["cutoff"]
|
|
184
|
+
rc = params["rc"]
|
|
185
|
+
acut = params["acut"]
|
|
186
|
+
species_j = species[index]
|
|
187
|
+
|
|
188
|
+
s0_i = params["s0"][species][:, None]
|
|
189
|
+
eta2_i = params["eta2"][species][:, None]
|
|
190
|
+
kappa_i = params["kappa"][species][:, None]
|
|
191
|
+
lam_i = params["lambda"][species][:, None]
|
|
192
|
+
e0_i = params["E0"][species][:, None]
|
|
193
|
+
v0_i = params["V0"][species][:, None]
|
|
194
|
+
|
|
195
|
+
s0_j = params["s0"][species_j]
|
|
196
|
+
eta2_j = params["eta2"][species_j]
|
|
197
|
+
kappa_j = params["kappa"][species_j]
|
|
198
|
+
n0_i = params["n0"][species][:, None]
|
|
199
|
+
n0_j = params["n0"][species_j]
|
|
200
|
+
chi = n0_j / n0_i
|
|
201
|
+
|
|
202
|
+
distance = pair_distances(positions, table, cell)
|
|
203
|
+
distance = do("where", mask, distance, 1.0)
|
|
204
|
+
inside = do("logical_and", mask, distance < cutoff)
|
|
205
|
+
weight = 1.0 / (1.0 + do("exp", acut * (distance - rc)))
|
|
206
|
+
weight = do("where", inside, weight, 0.0)
|
|
207
|
+
|
|
208
|
+
exp_eta_j = do("exp", -eta2_j * (distance - beta * s0_j))
|
|
209
|
+
sigma1 = do("sum", exp_eta_j * chi * weight, axis=-1)
|
|
210
|
+
has_neighbor = do("any", inside, axis=-1)
|
|
211
|
+
inv12gamma1 = params["inv12gamma1"][species]
|
|
212
|
+
sigma1_safe = do("where", has_neighbor, sigma1, 1.0)
|
|
213
|
+
ds = -do("log", sigma1_safe * inv12gamma1) / (
|
|
214
|
+
beta * eta2_i[:, 0]
|
|
215
|
+
)
|
|
216
|
+
ds = ds[:, None]
|
|
217
|
+
|
|
218
|
+
exp_lam = do("exp", -lam_i * ds)
|
|
219
|
+
exp_kappa = do("exp", -kappa_i * ds)
|
|
220
|
+
e_embedding = e0_i * (1.0 + lam_i * ds) * exp_lam + (
|
|
221
|
+
6.0 * v0_i * exp_kappa
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
nhalf_i = params["neghalfv0overgamma2"][species][:, None]
|
|
225
|
+
nhalf_j = params["neghalfv0overgamma2"][species_j]
|
|
226
|
+
es = nhalf_i * do(
|
|
227
|
+
"exp", -kappa_j * (distance / beta - s0_j)
|
|
228
|
+
) * chi * weight
|
|
229
|
+
eo = nhalf_j * do(
|
|
230
|
+
"exp", -kappa_i * (distance / beta - s0_i)
|
|
231
|
+
) / chi * weight
|
|
232
|
+
e_pair = 0.5 * do("sum", es + eo, axis=-1)
|
|
233
|
+
|
|
234
|
+
energy = do(
|
|
235
|
+
"where",
|
|
236
|
+
has_neighbor,
|
|
237
|
+
e_embedding[:, 0] + e_pair - e0_i[:, 0],
|
|
238
|
+
-e0_i[:, 0],
|
|
239
|
+
)
|
|
240
|
+
energy = do("sum", energy)
|
|
241
|
+
if not with_derivatives:
|
|
242
|
+
return energy, None, None
|
|
243
|
+
|
|
244
|
+
dw_dr_over_w = acut * (weight - 1.0)
|
|
245
|
+
dw_dr_over_w = do("where", inside, dw_dr_over_w, 0.0)
|
|
246
|
+
exp_eta_i = do("exp", -eta2_i * (distance - beta * s0_i))
|
|
247
|
+
dsigma1s = exp_eta_j * chi * weight * (
|
|
248
|
+
dw_dr_over_w - eta2_j
|
|
249
|
+
)
|
|
250
|
+
dsigma1o = exp_eta_i / chi * weight * (
|
|
251
|
+
dw_dr_over_w - eta2_i
|
|
252
|
+
)
|
|
253
|
+
dE_dds = -e0_i * lam_i * lam_i * ds * exp_lam - (
|
|
254
|
+
6.0 * v0_i * kappa_i * exp_kappa
|
|
255
|
+
)
|
|
256
|
+
dE_dsigma1 = dE_dds / (
|
|
257
|
+
-beta * eta2_i * sigma1_safe[:, None]
|
|
258
|
+
)
|
|
259
|
+
dE_dsigma1_i = dE_dsigma1[:, 0]
|
|
260
|
+
dE_dsigma1_j = dE_dsigma1_i[index]
|
|
261
|
+
embedding_derivative = (
|
|
262
|
+
dE_dsigma1_i[:, None] * dsigma1s
|
|
263
|
+
+ dE_dsigma1_j * dsigma1o
|
|
264
|
+
)
|
|
265
|
+
pair_derivative = es * (dw_dr_over_w - kappa_j / beta) + eo * (
|
|
266
|
+
dw_dr_over_w - kappa_i / beta
|
|
267
|
+
)
|
|
268
|
+
derivative = do(
|
|
269
|
+
"where", inside, embedding_derivative + pair_derivative, 0.0
|
|
270
|
+
)
|
|
271
|
+
coefficient = do("where", inside, derivative / distance, 0.0)
|
|
272
|
+
vectors = pair_vectors(positions, table, cell)
|
|
273
|
+
forces = do("sum", coefficient[:, :, None] * vectors, axis=1)
|
|
274
|
+
virial = 0.5 * do(
|
|
275
|
+
"einsum", "nm,nmi,nmj->ij", coefficient, vectors, vectors
|
|
276
|
+
)
|
|
277
|
+
# ``cell`` is only used for periodic stress; the caller validates it.
|
|
278
|
+
volume = do("abs", do("linalg.det", cell))
|
|
279
|
+
stress = virial / volume
|
|
280
|
+
return energy, forces, stress
|
|
281
|
+
|
|
282
|
+
def energy_arrays(
|
|
283
|
+
self,
|
|
284
|
+
positions: Any,
|
|
285
|
+
species: Any,
|
|
286
|
+
table: NeighborPaddedTable,
|
|
287
|
+
cell: Any,
|
|
288
|
+
pbc: Any,
|
|
289
|
+
params: dict[str, Any],
|
|
290
|
+
) -> Any:
|
|
291
|
+
energy, _, _ = self._emt_terms(
|
|
292
|
+
positions,
|
|
293
|
+
species,
|
|
294
|
+
table,
|
|
295
|
+
cell,
|
|
296
|
+
params,
|
|
297
|
+
with_derivatives=False,
|
|
298
|
+
)
|
|
299
|
+
return energy
|
|
300
|
+
|
|
301
|
+
def evaluate_arrays( # type: ignore[override]
|
|
302
|
+
self,
|
|
303
|
+
positions: Any,
|
|
304
|
+
species: Any,
|
|
305
|
+
table: NeighborPaddedTable,
|
|
306
|
+
cell: Any,
|
|
307
|
+
pbc: Any,
|
|
308
|
+
params: dict[str, Any],
|
|
309
|
+
*,
|
|
310
|
+
want: tuple[str, ...] = ("energy", "forces", "stress"),
|
|
311
|
+
) -> dict[str, Any]:
|
|
312
|
+
energy, forces, stress = self._emt_terms(
|
|
313
|
+
positions,
|
|
314
|
+
species,
|
|
315
|
+
table,
|
|
316
|
+
cell,
|
|
317
|
+
params,
|
|
318
|
+
with_derivatives=True,
|
|
319
|
+
)
|
|
320
|
+
out: dict[str, Any] = {}
|
|
321
|
+
if "energy" in want:
|
|
322
|
+
out["energy"] = energy
|
|
323
|
+
if "forces" in want:
|
|
324
|
+
out["forces"] = forces
|
|
325
|
+
if "stress" in want:
|
|
326
|
+
out["stress"] = stress
|
|
327
|
+
return out
|
|
328
|
+
|
|
329
|
+
def forces_arrays( # type: ignore[override]
|
|
330
|
+
self,
|
|
331
|
+
positions: Any,
|
|
332
|
+
species: Any,
|
|
333
|
+
table: NeighborPaddedTable,
|
|
334
|
+
cell: Any,
|
|
335
|
+
pbc: Any,
|
|
336
|
+
params: dict[str, Any],
|
|
337
|
+
) -> Any:
|
|
338
|
+
return self.evaluate_arrays(
|
|
339
|
+
positions, species, table, cell, pbc, params, want=("forces",)
|
|
340
|
+
)["forces"]
|
|
341
|
+
|
|
342
|
+
def stress_arrays( # type: ignore[override]
|
|
343
|
+
self,
|
|
344
|
+
positions: Any,
|
|
345
|
+
species: Any,
|
|
346
|
+
table: NeighborPaddedTable,
|
|
347
|
+
cell: Any,
|
|
348
|
+
pbc: Any,
|
|
349
|
+
params: dict[str, Any],
|
|
350
|
+
) -> Any:
|
|
351
|
+
return self.evaluate_arrays(
|
|
352
|
+
positions, species, table, cell, pbc, params, want=("stress",)
|
|
353
|
+
)["stress"]
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Pairwise potentials built on a shared form + parameter layer."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from arrayff.potentials.pairwise.base import PairwisePotential
|
|
6
|
+
from arrayff.potentials.pairwise.forms import GeneralizedLJ
|
|
7
|
+
from arrayff.potentials.pairwise.forms import Morse as MorseForm
|
|
8
|
+
from arrayff.potentials.pairwise.lj import LennardJones
|
|
9
|
+
from arrayff.potentials.pairwise.lj93 import LennardJones93 as LJ93
|
|
10
|
+
from arrayff.potentials.pairwise.morse import Morse
|
|
11
|
+
from arrayff.potentials.pairwise.params import PairParameters
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"GeneralizedLJ",
|
|
15
|
+
"LJ93",
|
|
16
|
+
"LennardJones",
|
|
17
|
+
"Morse",
|
|
18
|
+
"MorseForm",
|
|
19
|
+
"PairParameters",
|
|
20
|
+
"PairwisePotential",
|
|
21
|
+
]
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Vectorised pair geometry shared by the short ranged potentials."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from arrayff.utils.dispatch import do, dtype_of
|
|
8
|
+
from arrayff.neighbors._table import NeighborPaddedTable
|
|
9
|
+
|
|
10
|
+
__all__ = ["pair_distances", "pair_vectors"]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def pair_vectors(positions: Any, table: NeighborPaddedTable, cell: Any) -> Any:
|
|
14
|
+
"""Return the ``(N, M, 3)`` pair vectors ``r_j - r_i + S @ cell``.
|
|
15
|
+
|
|
16
|
+
The shift term is skipped when ``cell`` is ``None``.
|
|
17
|
+
"""
|
|
18
|
+
vectors = positions[table.index] - positions[:, None, :]
|
|
19
|
+
if cell is not None:
|
|
20
|
+
shift = do("astype", table.shift, dtype_of(positions))
|
|
21
|
+
vectors = vectors + do("einsum", "nmk,kl->nml", shift, cell)
|
|
22
|
+
return vectors
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def pair_distances(
|
|
26
|
+
positions: Any, table: NeighborPaddedTable, cell: Any
|
|
27
|
+
) -> Any:
|
|
28
|
+
"""Return the ``(N, M)`` pair distances.
|
|
29
|
+
|
|
30
|
+
Padding entries are replaced by ``1.0`` *before* the square root so that
|
|
31
|
+
autodiff never evaluates ``1 / sqrt(0)`` (which would give ``0 * inf``).
|
|
32
|
+
"""
|
|
33
|
+
vectors = pair_vectors(positions, table, cell)
|
|
34
|
+
squared = do("sum", vectors * vectors, axis=-1)
|
|
35
|
+
squared = do("where", table.mask, squared, 1.0)
|
|
36
|
+
return do("sqrt", squared)
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"""Optional trainable torch wrappers for pairwise potentials."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
import torch
|
|
9
|
+
from torch import nn
|
|
10
|
+
|
|
11
|
+
from arrayff.potentials._torch import TorchPotential
|
|
12
|
+
from arrayff.potentials.pairwise.lj import (
|
|
13
|
+
KIM_LJ_PARAMETERS,
|
|
14
|
+
SIGMA_TO_R0,
|
|
15
|
+
LennardJones,
|
|
16
|
+
)
|
|
17
|
+
from arrayff.potentials.pairwise.lj93 import LennardJones93
|
|
18
|
+
from arrayff.potentials.pairwise.morse import Morse
|
|
19
|
+
from arrayff.potentials.pairwise.params import PairParameters
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"LJ93Torch",
|
|
23
|
+
"LJTorch",
|
|
24
|
+
"MorseTorch",
|
|
25
|
+
"PairwiseTorch",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class PairwiseTorch(nn.Module):
|
|
30
|
+
"""Trainable pairwise potential.
|
|
31
|
+
|
|
32
|
+
Composes a :class:`PairwisePotential` (built on the torch backend) with
|
|
33
|
+
log-space ``nn.Parameter`` per element parameters, so any form works
|
|
34
|
+
without duplicating the energy expression.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
potential_cls: type
|
|
38
|
+
potential_kwargs: dict[str, Any] = {}
|
|
39
|
+
|
|
40
|
+
def __init__(
|
|
41
|
+
self,
|
|
42
|
+
species: list[int] | tuple[int, ...],
|
|
43
|
+
initial: dict[int, dict[str, float]],
|
|
44
|
+
*,
|
|
45
|
+
cutoff: float = 10.0,
|
|
46
|
+
dtype: torch.dtype = torch.float64,
|
|
47
|
+
) -> None:
|
|
48
|
+
nn.Module.__init__(self)
|
|
49
|
+
self.elements = sorted(int(z) for z in species)
|
|
50
|
+
self.potential = self.potential_cls(
|
|
51
|
+
**self.potential_kwargs,
|
|
52
|
+
cutoff=cutoff,
|
|
53
|
+
backend="torch",
|
|
54
|
+
dtype=dtype,
|
|
55
|
+
)
|
|
56
|
+
names = self.potential.form.param_names
|
|
57
|
+
missing = [
|
|
58
|
+
(z, name)
|
|
59
|
+
for z in self.elements
|
|
60
|
+
for name in names
|
|
61
|
+
if name not in initial.get(z, {})
|
|
62
|
+
]
|
|
63
|
+
if missing:
|
|
64
|
+
raise KeyError(f"Missing initial parameters: {missing}")
|
|
65
|
+
self.raw = nn.ParameterDict(
|
|
66
|
+
{
|
|
67
|
+
name: nn.Parameter(
|
|
68
|
+
torch.log(
|
|
69
|
+
torch.as_tensor(
|
|
70
|
+
[initial[z][name] for z in self.elements],
|
|
71
|
+
dtype=dtype,
|
|
72
|
+
)
|
|
73
|
+
)
|
|
74
|
+
)
|
|
75
|
+
for name in names
|
|
76
|
+
}
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
def parameters_for_pairs(self) -> PairParameters:
|
|
80
|
+
return PairParameters(
|
|
81
|
+
elements=np.asarray(self.elements, dtype=np.int64),
|
|
82
|
+
values={name: torch.exp(value) for name, value in self.raw.items()},
|
|
83
|
+
mixing=self.potential.mixing,
|
|
84
|
+
cutoff=None,
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
def energy_tensor(self, atoms: Any) -> torch.Tensor:
|
|
88
|
+
positions, species, table, cell, pbc, _ = self.potential._context(atoms)
|
|
89
|
+
return self.potential.energy_arrays(
|
|
90
|
+
positions, species, table, cell, pbc, self.parameters_for_pairs()
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
def forces_tensor(
|
|
94
|
+
self, atoms: Any, *, method: str = "autodiff"
|
|
95
|
+
) -> torch.Tensor:
|
|
96
|
+
positions, species, table, cell, pbc, _ = self.potential._context(atoms)
|
|
97
|
+
if method == "analytic":
|
|
98
|
+
return self.potential.forces_arrays(
|
|
99
|
+
positions, species, table, cell, pbc,
|
|
100
|
+
self.parameters_for_pairs(),
|
|
101
|
+
)
|
|
102
|
+
positions = positions.detach().clone().requires_grad_(True)
|
|
103
|
+
energy = self.potential.energy_arrays(
|
|
104
|
+
positions, species, table, cell, pbc, self.parameters_for_pairs()
|
|
105
|
+
)
|
|
106
|
+
(gradient,) = torch.autograd.grad(
|
|
107
|
+
energy, positions, create_graph=self.training
|
|
108
|
+
)
|
|
109
|
+
return -gradient
|
|
110
|
+
|
|
111
|
+
def forward(self, atoms: Any) -> torch.Tensor:
|
|
112
|
+
return self.energy_tensor(atoms)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class MorseTorch(PairwiseTorch):
|
|
116
|
+
"""Trainable Morse potential."""
|
|
117
|
+
|
|
118
|
+
potential_cls = Morse # type: ignore[override]
|
|
119
|
+
potential_kwargs = {"r0": 1.0, "depth": 1.0, "a": 1.0}
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class LJ93Torch(PairwiseTorch):
|
|
123
|
+
"""Trainable Lennard-Jones 9-3 potential."""
|
|
124
|
+
|
|
125
|
+
potential_cls = LennardJones93 # type: ignore[override]
|
|
126
|
+
potential_kwargs = {"r0": 1.0, "depth": 1.0}
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class LJTorch(LennardJones, TorchPotential):
|
|
130
|
+
"""Lennard-Jones with trainable per element ``epsilon``/``sigma``.
|
|
131
|
+
|
|
132
|
+
Parameters are stored in log space so an optimizer can never drive them
|
|
133
|
+
negative; the initial values reproduce the OpenKIM universal model.
|
|
134
|
+
"""
|
|
135
|
+
|
|
136
|
+
def __init__(
|
|
137
|
+
self,
|
|
138
|
+
species: list[int] | tuple[int, ...],
|
|
139
|
+
*,
|
|
140
|
+
max_neighbors: int | None = None,
|
|
141
|
+
dtype: torch.dtype = torch.float64,
|
|
142
|
+
) -> None:
|
|
143
|
+
nn.Module.__init__(self)
|
|
144
|
+
LennardJones.__init__(
|
|
145
|
+
self,
|
|
146
|
+
backend="torch",
|
|
147
|
+
dtype=dtype,
|
|
148
|
+
max_neighbors=max_neighbors,
|
|
149
|
+
)
|
|
150
|
+
self.elements = sorted(int(z) for z in species)
|
|
151
|
+
epsilon = np.array([KIM_LJ_PARAMETERS[z][1] for z in self.elements])
|
|
152
|
+
sigma = np.array([KIM_LJ_PARAMETERS[z][2] for z in self.elements])
|
|
153
|
+
cutoff = np.array([KIM_LJ_PARAMETERS[z][0] for z in self.elements])
|
|
154
|
+
self.raw_epsilon = nn.Parameter(
|
|
155
|
+
torch.log(torch.as_tensor(epsilon, dtype=dtype))
|
|
156
|
+
)
|
|
157
|
+
self.raw_sigma = nn.Parameter(
|
|
158
|
+
torch.log(torch.as_tensor(sigma, dtype=dtype))
|
|
159
|
+
)
|
|
160
|
+
self.register_buffer(
|
|
161
|
+
"cutoff_table", torch.as_tensor(cutoff, dtype=dtype)
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
def element_parameters(self, elements: np.ndarray) -> PairParameters:
|
|
165
|
+
found = [int(z) for z in elements]
|
|
166
|
+
if found != self.elements:
|
|
167
|
+
raise ValueError(
|
|
168
|
+
f"LJTorch was built for elements {self.elements}, got {found}"
|
|
169
|
+
)
|
|
170
|
+
return PairParameters(
|
|
171
|
+
elements=np.asarray(elements, dtype=np.int64),
|
|
172
|
+
values={
|
|
173
|
+
"r0": SIGMA_TO_R0 * torch.exp(self.raw_sigma),
|
|
174
|
+
"depth": torch.exp(self.raw_epsilon),
|
|
175
|
+
},
|
|
176
|
+
mixing=self.mixing,
|
|
177
|
+
cutoff=self.cutoff_table,
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
def forward(self, atoms: Any) -> torch.Tensor:
|
|
181
|
+
return self.energy_tensor(atoms)
|