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,720 @@
|
|
|
1
|
+
"""Base classes shared by all potentials.
|
|
2
|
+
|
|
3
|
+
A potential is defined by array level functions written with
|
|
4
|
+
:func:`arrayff.utils.dispatch.do`. :class:`PotentialBase` is the minimal
|
|
5
|
+
protocol shared by table-driven potentials, QEq and composite potentials;
|
|
6
|
+
:class:`Potential` adds the neighbour-table machinery and the analytic/AD
|
|
7
|
+
evaluation pipeline.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import abc
|
|
13
|
+
import hashlib
|
|
14
|
+
import warnings
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
import numpy as np
|
|
18
|
+
from ase import Atoms
|
|
19
|
+
|
|
20
|
+
from arrayff.neighbors._table import NeighborEdgeList, NeighborPaddedTable
|
|
21
|
+
from arrayff.utils import ad
|
|
22
|
+
from arrayff.utils.ase import atoms_to_arrays, species_of
|
|
23
|
+
from arrayff.utils.dispatch import do, to_backend, to_numpy
|
|
24
|
+
from arrayff.utils.exceptions import ScopeError
|
|
25
|
+
from arrayff.utils.jit import autojit
|
|
26
|
+
|
|
27
|
+
__all__ = ["Potential", "PotentialBase"]
|
|
28
|
+
|
|
29
|
+
_METHODS = ("analytic", "autodiff", "finite-difference")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class PotentialBase(abc.ABC):
|
|
33
|
+
"""Minimal protocol for anything that can be added to a potential."""
|
|
34
|
+
|
|
35
|
+
backend: str
|
|
36
|
+
dtype: Any
|
|
37
|
+
supports_charges: bool = False
|
|
38
|
+
|
|
39
|
+
def __init__(
|
|
40
|
+
self,
|
|
41
|
+
*,
|
|
42
|
+
backend: str = "numpy",
|
|
43
|
+
dtype: Any = None,
|
|
44
|
+
jit: bool = False,
|
|
45
|
+
method: str = "analytic",
|
|
46
|
+
) -> None:
|
|
47
|
+
self.backend = backend
|
|
48
|
+
self.dtype = dtype
|
|
49
|
+
self.jit = bool(jit)
|
|
50
|
+
if method not in _METHODS:
|
|
51
|
+
raise ValueError(
|
|
52
|
+
f"method must be one of {_METHODS}, got {method!r}"
|
|
53
|
+
)
|
|
54
|
+
self.method = method
|
|
55
|
+
|
|
56
|
+
# -- evaluation ----------------------------------------------------------
|
|
57
|
+
@abc.abstractmethod
|
|
58
|
+
def evaluate(
|
|
59
|
+
self,
|
|
60
|
+
atoms: Atoms,
|
|
61
|
+
*,
|
|
62
|
+
properties: tuple[str, ...] = ("energy",),
|
|
63
|
+
method: str | None = None,
|
|
64
|
+
) -> dict[str, Any]:
|
|
65
|
+
"""Return the requested properties as a dictionary."""
|
|
66
|
+
|
|
67
|
+
def _resolve_method(self, method: str | None) -> str:
|
|
68
|
+
resolved = self.method if method is None else method
|
|
69
|
+
if resolved not in _METHODS:
|
|
70
|
+
raise ValueError(
|
|
71
|
+
f"method must be one of {_METHODS}, got {resolved!r}"
|
|
72
|
+
)
|
|
73
|
+
return resolved
|
|
74
|
+
|
|
75
|
+
def energy(self, atoms: Atoms, *, method: str | None = None) -> float:
|
|
76
|
+
result = self.evaluate(atoms, properties=("energy",), method=method)
|
|
77
|
+
return float(result["energy"])
|
|
78
|
+
|
|
79
|
+
def energy_and_forces(
|
|
80
|
+
self, atoms: Atoms, *, method: str | None = None
|
|
81
|
+
) -> tuple[float, np.ndarray]:
|
|
82
|
+
result = self.evaluate(
|
|
83
|
+
atoms, properties=("energy", "forces"), method=method
|
|
84
|
+
)
|
|
85
|
+
return float(result["energy"]), np.asarray(result["forces"])
|
|
86
|
+
|
|
87
|
+
def stress(
|
|
88
|
+
self, atoms: Atoms, *, method: str | None = None
|
|
89
|
+
) -> np.ndarray:
|
|
90
|
+
result = self.evaluate(atoms, properties=("stress",), method=method)
|
|
91
|
+
return np.asarray(result["stress"])
|
|
92
|
+
|
|
93
|
+
def charges(self, atoms: Atoms) -> np.ndarray:
|
|
94
|
+
raise ScopeError(
|
|
95
|
+
f"{type(self).__name__} does not provide atomic charges"
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
def clear_cache(self) -> None:
|
|
99
|
+
"""Drop cached neighbour tables / compiled kernels."""
|
|
100
|
+
|
|
101
|
+
# -- composition ---------------------------------------------------------
|
|
102
|
+
def __add__(self, other: Any) -> Any:
|
|
103
|
+
if not isinstance(other, PotentialBase):
|
|
104
|
+
return NotImplemented
|
|
105
|
+
from arrayff.potentials.composite import CompositePotential
|
|
106
|
+
|
|
107
|
+
return CompositePotential((self, other))
|
|
108
|
+
|
|
109
|
+
def __radd__(self, other: Any) -> Any:
|
|
110
|
+
if isinstance(other, (int, float)) and other == 0:
|
|
111
|
+
return self
|
|
112
|
+
return NotImplemented
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class Potential(PotentialBase):
|
|
116
|
+
"""Energy/force evaluator bound to one array backend.
|
|
117
|
+
|
|
118
|
+
Parameters
|
|
119
|
+
----------
|
|
120
|
+
cutoff:
|
|
121
|
+
Global cutoff radius in Angstrom used to build the neighbour table.
|
|
122
|
+
backend:
|
|
123
|
+
``"numpy"`` (default), ``"torch"`` or ``"jax"``.
|
|
124
|
+
dtype:
|
|
125
|
+
Floating point dtype used when converting the ``Atoms`` positions.
|
|
126
|
+
max_neighbors:
|
|
127
|
+
Fixed neighbour-table width; required to keep shapes static for JAX.
|
|
128
|
+
builder:
|
|
129
|
+
Neighbour list implementation: ``"sklearn"`` (default), ``"vesin"``,
|
|
130
|
+
``"matscipy"``, ``"pymatgen"`` or ``"ase_kdtree"``.
|
|
131
|
+
jit:
|
|
132
|
+
Compile the array level kernels with :func:`arrayff.utils.jit`.
|
|
133
|
+
method:
|
|
134
|
+
Default evaluation method: ``"analytic"``, ``"autodiff"`` or
|
|
135
|
+
``"finite-difference"`` (diagnostic only).
|
|
136
|
+
"""
|
|
137
|
+
|
|
138
|
+
name: str = "potential"
|
|
139
|
+
|
|
140
|
+
def __init__(
|
|
141
|
+
self,
|
|
142
|
+
cutoff: float,
|
|
143
|
+
*,
|
|
144
|
+
backend: str = "numpy",
|
|
145
|
+
dtype: Any = None,
|
|
146
|
+
max_neighbors: int | None = None,
|
|
147
|
+
builder: str = "sklearn",
|
|
148
|
+
skin: float = 0.0,
|
|
149
|
+
jit: bool = False,
|
|
150
|
+
method: str = "analytic",
|
|
151
|
+
) -> None:
|
|
152
|
+
super().__init__(
|
|
153
|
+
backend=backend, dtype=dtype, jit=jit, method=method
|
|
154
|
+
)
|
|
155
|
+
self.cutoff = float(cutoff)
|
|
156
|
+
self.max_neighbors = max_neighbors
|
|
157
|
+
self.builder = builder
|
|
158
|
+
self.skin = float(skin)
|
|
159
|
+
if self.skin < 0.0:
|
|
160
|
+
raise ValueError("skin must be non-negative")
|
|
161
|
+
self._table_static: tuple | None = None
|
|
162
|
+
self._table_positions: np.ndarray | None = None
|
|
163
|
+
self._table_cache: NeighborPaddedTable | NeighborEdgeList | None = None
|
|
164
|
+
self._jit_cache: dict[tuple, Any] = {}
|
|
165
|
+
|
|
166
|
+
# -- to be implemented by subclasses ---------------------------------------
|
|
167
|
+
@abc.abstractmethod
|
|
168
|
+
def element_parameters(self, elements: np.ndarray) -> Any:
|
|
169
|
+
"""Return backend arrays of the parameters for ``elements``."""
|
|
170
|
+
|
|
171
|
+
@abc.abstractmethod
|
|
172
|
+
def energy_arrays(
|
|
173
|
+
self,
|
|
174
|
+
positions: Any,
|
|
175
|
+
species: Any,
|
|
176
|
+
table: Any,
|
|
177
|
+
cell: Any,
|
|
178
|
+
pbc: Any,
|
|
179
|
+
params: Any,
|
|
180
|
+
) -> Any:
|
|
181
|
+
"""Return the total energy as a scalar array."""
|
|
182
|
+
|
|
183
|
+
def forces_arrays(
|
|
184
|
+
self,
|
|
185
|
+
positions: Any,
|
|
186
|
+
species: Any,
|
|
187
|
+
table: Any,
|
|
188
|
+
cell: Any,
|
|
189
|
+
pbc: Any,
|
|
190
|
+
params: Any,
|
|
191
|
+
) -> Any:
|
|
192
|
+
raise NotImplementedError(
|
|
193
|
+
f"{type(self).__name__} does not implement analytic forces"
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
def stress_arrays(
|
|
197
|
+
self,
|
|
198
|
+
positions: Any,
|
|
199
|
+
species: Any,
|
|
200
|
+
table: Any,
|
|
201
|
+
cell: Any,
|
|
202
|
+
pbc: Any,
|
|
203
|
+
params: Any,
|
|
204
|
+
) -> Any:
|
|
205
|
+
raise NotImplementedError(
|
|
206
|
+
f"{type(self).__name__} does not implement analytic stress"
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
def evaluate_arrays(
|
|
210
|
+
self,
|
|
211
|
+
positions: Any,
|
|
212
|
+
species: Any,
|
|
213
|
+
table: Any,
|
|
214
|
+
cell: Any,
|
|
215
|
+
pbc: Any,
|
|
216
|
+
params: Any,
|
|
217
|
+
*,
|
|
218
|
+
want: tuple[str, ...] = ("energy", "forces", "stress"),
|
|
219
|
+
) -> dict[str, Any]:
|
|
220
|
+
"""Analytic array-level evaluation.
|
|
221
|
+
|
|
222
|
+
Subclasses that can share intermediates between energy, forces and
|
|
223
|
+
stress override this method; the default keeps the three kernels
|
|
224
|
+
separate.
|
|
225
|
+
"""
|
|
226
|
+
out: dict[str, Any] = {}
|
|
227
|
+
if "energy" in want:
|
|
228
|
+
out["energy"] = self.energy_arrays(
|
|
229
|
+
positions, species, table, cell, pbc, params
|
|
230
|
+
)
|
|
231
|
+
if "forces" in want:
|
|
232
|
+
out["forces"] = self.forces_arrays(
|
|
233
|
+
positions, species, table, cell, pbc, params
|
|
234
|
+
)
|
|
235
|
+
if "stress" in want:
|
|
236
|
+
out["stress"] = self.stress_arrays(
|
|
237
|
+
positions, species, table, cell, pbc, params
|
|
238
|
+
)
|
|
239
|
+
return out
|
|
240
|
+
|
|
241
|
+
# -- pipeline -----------------------------------------------------------
|
|
242
|
+
def _cutoff_for(self, atoms: Atoms) -> float:
|
|
243
|
+
"""Return the neighbour table cutoff for ``atoms``."""
|
|
244
|
+
return self.cutoff
|
|
245
|
+
|
|
246
|
+
def _context(self, atoms: Atoms) -> tuple:
|
|
247
|
+
elements, species_np = species_of(atoms.numbers)
|
|
248
|
+
positions, _, cell, pbc = atoms_to_arrays(
|
|
249
|
+
atoms, self.backend, self.dtype
|
|
250
|
+
)
|
|
251
|
+
species = to_backend(species_np, self.backend)
|
|
252
|
+
table = self._table(atoms)
|
|
253
|
+
return (
|
|
254
|
+
positions,
|
|
255
|
+
species,
|
|
256
|
+
table,
|
|
257
|
+
cell,
|
|
258
|
+
pbc,
|
|
259
|
+
self.element_parameters(elements),
|
|
260
|
+
)
|
|
261
|
+
|
|
262
|
+
def _table_static_key(self, atoms: Atoms) -> tuple:
|
|
263
|
+
digest = hashlib.blake2b(digest_size=16)
|
|
264
|
+
digest.update(np.asarray(atoms.cell.array, dtype=np.float64).tobytes())
|
|
265
|
+
digest.update(np.asarray(atoms.pbc, dtype=bool).tobytes())
|
|
266
|
+
digest.update(np.asarray(atoms.numbers, dtype=np.int64).tobytes())
|
|
267
|
+
return (
|
|
268
|
+
digest.hexdigest(),
|
|
269
|
+
self._cutoff_for(atoms),
|
|
270
|
+
self.max_neighbors,
|
|
271
|
+
self.builder,
|
|
272
|
+
self.backend,
|
|
273
|
+
self.skin,
|
|
274
|
+
)
|
|
275
|
+
|
|
276
|
+
def _table(self, atoms: Atoms) -> NeighborPaddedTable | NeighborEdgeList:
|
|
277
|
+
"""Return the neighbour table, cached according to ``skin``.
|
|
278
|
+
|
|
279
|
+
* ``skin == 0``: reuse only when the geometry is bitwise unchanged.
|
|
280
|
+
* ``skin > 0``: build with ``cutoff + skin`` and reuse while no atom
|
|
281
|
+
moved more than ``skin / 2`` (the standard rebuild criterion).
|
|
282
|
+
"""
|
|
283
|
+
static = self._table_static_key(atoms)
|
|
284
|
+
positions = np.asarray(atoms.positions, dtype=np.float64)
|
|
285
|
+
if (
|
|
286
|
+
self._table_cache is not None
|
|
287
|
+
and self._table_static == static
|
|
288
|
+
and self._table_positions is not None
|
|
289
|
+
):
|
|
290
|
+
displacement = float(
|
|
291
|
+
np.linalg.norm(positions - self._table_positions, axis=1).max(
|
|
292
|
+
initial=0.0
|
|
293
|
+
)
|
|
294
|
+
)
|
|
295
|
+
tolerance = self.skin / 2.0 if self.skin > 0.0 else 0.0
|
|
296
|
+
if displacement <= tolerance:
|
|
297
|
+
return self._table_cache
|
|
298
|
+
|
|
299
|
+
table = self._build_table(atoms, self._cutoff_for(atoms) + self.skin)
|
|
300
|
+
self._table_static = static
|
|
301
|
+
self._table_positions = positions.copy()
|
|
302
|
+
self._table_cache = table
|
|
303
|
+
return table
|
|
304
|
+
|
|
305
|
+
def _build_table(self, atoms: Atoms, cutoff: float) -> NeighborPaddedTable:
|
|
306
|
+
"""Build the neighbour table; pairwise potentials override this."""
|
|
307
|
+
return NeighborPaddedTable.from_ase(
|
|
308
|
+
atoms,
|
|
309
|
+
cutoff,
|
|
310
|
+
max_neighbors=self.max_neighbors,
|
|
311
|
+
backend=self.backend,
|
|
312
|
+
builder=self.builder,
|
|
313
|
+
)
|
|
314
|
+
|
|
315
|
+
def clear_cache(self) -> None:
|
|
316
|
+
"""Drop the cached neighbour table and compiled kernels."""
|
|
317
|
+
self._table_cache = None
|
|
318
|
+
self._table_positions = None
|
|
319
|
+
self._table_static = None
|
|
320
|
+
self._jit_cache.clear()
|
|
321
|
+
|
|
322
|
+
# -- evaluation ----------------------------------------------------------
|
|
323
|
+
def _analytic_table(
|
|
324
|
+
self,
|
|
325
|
+
table: NeighborPaddedTable | NeighborEdgeList,
|
|
326
|
+
n_atoms: int,
|
|
327
|
+
) -> NeighborPaddedTable:
|
|
328
|
+
return table # type: ignore[return-value]
|
|
329
|
+
|
|
330
|
+
# -- jit plumbing --------------------------------------------------------
|
|
331
|
+
def _as_jit_arg(self, value: Any) -> Any:
|
|
332
|
+
if isinstance(value, (np.ndarray,)) or hasattr(value, "shape"):
|
|
333
|
+
return value
|
|
334
|
+
return to_backend(np.asarray(value), self.backend)
|
|
335
|
+
|
|
336
|
+
def _table_arrays(
|
|
337
|
+
self, table: NeighborPaddedTable | NeighborEdgeList
|
|
338
|
+
) -> tuple[str, tuple[Any, ...]]:
|
|
339
|
+
if isinstance(table, NeighborPaddedTable):
|
|
340
|
+
return "padded", (table.index, table.shift, table.mask)
|
|
341
|
+
return "edges", (
|
|
342
|
+
table.source,
|
|
343
|
+
table.target,
|
|
344
|
+
table.shift_x,
|
|
345
|
+
table.shift_y,
|
|
346
|
+
table.shift_z,
|
|
347
|
+
)
|
|
348
|
+
|
|
349
|
+
def _rebuild_table(self, kind: str, arrays: tuple[Any, ...]):
|
|
350
|
+
if kind == "padded":
|
|
351
|
+
return NeighborPaddedTable(*arrays)
|
|
352
|
+
return NeighborEdgeList(*arrays)
|
|
353
|
+
|
|
354
|
+
def _flatten_params(
|
|
355
|
+
self, params: Any
|
|
356
|
+
) -> tuple[tuple[Any, ...], Any]:
|
|
357
|
+
if isinstance(params, dict):
|
|
358
|
+
keys = tuple(sorted(params))
|
|
359
|
+
values = tuple(self._as_jit_arg(params[key]) for key in keys)
|
|
360
|
+
|
|
361
|
+
def rebuild(vals: tuple[Any, ...]) -> dict[str, Any]:
|
|
362
|
+
return dict(zip(keys, vals))
|
|
363
|
+
|
|
364
|
+
return values, rebuild
|
|
365
|
+
raise TypeError(
|
|
366
|
+
f"{type(self).__name__} does not implement jit parameter flattening"
|
|
367
|
+
)
|
|
368
|
+
|
|
369
|
+
def _jit_evaluate(
|
|
370
|
+
self,
|
|
371
|
+
positions: Any,
|
|
372
|
+
species: Any,
|
|
373
|
+
table: NeighborPaddedTable | NeighborEdgeList,
|
|
374
|
+
cell: Any,
|
|
375
|
+
pbc: Any,
|
|
376
|
+
params: Any,
|
|
377
|
+
want: tuple[str, ...],
|
|
378
|
+
) -> dict[str, Any]:
|
|
379
|
+
kind, table_arrays = self._table_arrays(table)
|
|
380
|
+
param_arrays, rebuild = self._flatten_params(params)
|
|
381
|
+
key = (
|
|
382
|
+
kind,
|
|
383
|
+
want,
|
|
384
|
+
tuple(tuple(np.shape(a)) for a in table_arrays),
|
|
385
|
+
tuple(tuple(np.shape(a)) for a in param_arrays),
|
|
386
|
+
tuple(np.asarray(a).dtype.str for a in table_arrays),
|
|
387
|
+
tuple(np.asarray(a).dtype.str for a in param_arrays),
|
|
388
|
+
tuple(np.shape(positions)),
|
|
389
|
+
)
|
|
390
|
+
compiled = self._jit_cache.get(key)
|
|
391
|
+
if compiled is None:
|
|
392
|
+
n_table = len(table_arrays)
|
|
393
|
+
|
|
394
|
+
def kernel(*args: Any) -> tuple[Any, ...]:
|
|
395
|
+
pos, spec, cel, pbc_ = args[:4]
|
|
396
|
+
table_ = self._rebuild_table(
|
|
397
|
+
kind, args[4 : 4 + n_table]
|
|
398
|
+
)
|
|
399
|
+
params_ = rebuild(args[4 + n_table :])
|
|
400
|
+
out = self.evaluate_arrays(
|
|
401
|
+
pos,
|
|
402
|
+
spec,
|
|
403
|
+
table_,
|
|
404
|
+
cel,
|
|
405
|
+
pbc_,
|
|
406
|
+
params_,
|
|
407
|
+
want=want,
|
|
408
|
+
)
|
|
409
|
+
return tuple(out[name] for name in want)
|
|
410
|
+
|
|
411
|
+
compiled = autojit(kernel, backend=self.backend)
|
|
412
|
+
self._jit_cache[key] = compiled
|
|
413
|
+
args = (
|
|
414
|
+
positions,
|
|
415
|
+
species,
|
|
416
|
+
cell,
|
|
417
|
+
pbc,
|
|
418
|
+
*table_arrays,
|
|
419
|
+
*param_arrays,
|
|
420
|
+
)
|
|
421
|
+
try:
|
|
422
|
+
values = compiled(*args)
|
|
423
|
+
except Exception as exc: # pragma: no cover - backend dependent
|
|
424
|
+
warnings.warn(
|
|
425
|
+
f"jit compilation/execution failed for {type(self).__name__} "
|
|
426
|
+
f"on backend {self.backend!r}; falling back to eager: {exc}",
|
|
427
|
+
RuntimeWarning,
|
|
428
|
+
stacklevel=2,
|
|
429
|
+
)
|
|
430
|
+
self._jit_cache[key] = None
|
|
431
|
+
self.jit = False
|
|
432
|
+
return self.evaluate_arrays(
|
|
433
|
+
positions, species, table, cell, pbc, params, want=want
|
|
434
|
+
)
|
|
435
|
+
return dict(zip(want, values))
|
|
436
|
+
|
|
437
|
+
def _jit_evaluate_ad(
|
|
438
|
+
self,
|
|
439
|
+
positions: Any,
|
|
440
|
+
species: Any,
|
|
441
|
+
table: NeighborPaddedTable | NeighborEdgeList,
|
|
442
|
+
cell: Any,
|
|
443
|
+
pbc: Any,
|
|
444
|
+
params: Any,
|
|
445
|
+
want: tuple[str, ...],
|
|
446
|
+
) -> dict[str, Any] | None:
|
|
447
|
+
if self.backend not in ("jax", "torch") or "stress" in want:
|
|
448
|
+
return None
|
|
449
|
+
kind, table_arrays = self._table_arrays(table)
|
|
450
|
+
param_arrays, rebuild = self._flatten_params(params)
|
|
451
|
+
key = (
|
|
452
|
+
"ad",
|
|
453
|
+
self.backend,
|
|
454
|
+
kind,
|
|
455
|
+
want,
|
|
456
|
+
tuple(tuple(np.shape(a)) for a in table_arrays),
|
|
457
|
+
tuple(tuple(np.shape(a)) for a in param_arrays),
|
|
458
|
+
tuple(np.shape(positions)),
|
|
459
|
+
)
|
|
460
|
+
compiled = self._jit_cache.get(key)
|
|
461
|
+
if compiled is None:
|
|
462
|
+
n_table = len(table_arrays)
|
|
463
|
+
|
|
464
|
+
def energy_kernel(*args: Any) -> Any:
|
|
465
|
+
pos, spec, cel, pbc_ = args[:4]
|
|
466
|
+
table_ = self._rebuild_table(
|
|
467
|
+
kind, args[4 : 4 + n_table]
|
|
468
|
+
)
|
|
469
|
+
params_ = rebuild(args[4 + n_table :])
|
|
470
|
+
return self.energy_arrays(
|
|
471
|
+
pos, spec, table_, cel, pbc_, params_
|
|
472
|
+
)
|
|
473
|
+
|
|
474
|
+
if self.backend == "jax":
|
|
475
|
+
|
|
476
|
+
def kernel(*args: Any) -> tuple[Any, ...]:
|
|
477
|
+
pos = args[0]
|
|
478
|
+
energy, gradient = ad.value_and_grad(
|
|
479
|
+
lambda p: energy_kernel(p, *args[1:])
|
|
480
|
+
)(pos)
|
|
481
|
+
return energy, -gradient
|
|
482
|
+
|
|
483
|
+
compiled = autojit(kernel, backend="jax")
|
|
484
|
+
else:
|
|
485
|
+
compiled = autojit(energy_kernel, backend="torch")
|
|
486
|
+
self._jit_cache[key] = compiled
|
|
487
|
+
try:
|
|
488
|
+
if self.backend == "jax":
|
|
489
|
+
values = compiled(
|
|
490
|
+
positions,
|
|
491
|
+
species,
|
|
492
|
+
cell,
|
|
493
|
+
pbc,
|
|
494
|
+
*table_arrays,
|
|
495
|
+
*param_arrays,
|
|
496
|
+
)
|
|
497
|
+
energy, forces = values
|
|
498
|
+
else:
|
|
499
|
+
import torch
|
|
500
|
+
|
|
501
|
+
grad_positions = positions.detach().clone().requires_grad_(True)
|
|
502
|
+
energy = compiled(
|
|
503
|
+
grad_positions,
|
|
504
|
+
species,
|
|
505
|
+
cell,
|
|
506
|
+
pbc,
|
|
507
|
+
*table_arrays,
|
|
508
|
+
*param_arrays,
|
|
509
|
+
)
|
|
510
|
+
if "forces" in want:
|
|
511
|
+
(gradient,) = torch.autograd.grad(
|
|
512
|
+
energy, grad_positions, create_graph=False
|
|
513
|
+
)
|
|
514
|
+
forces = -gradient
|
|
515
|
+
else:
|
|
516
|
+
forces = None
|
|
517
|
+
except Exception as exc: # pragma: no cover - backend dependent
|
|
518
|
+
warnings.warn(
|
|
519
|
+
f"AD jit failed for {type(self).__name__}; falling back to "
|
|
520
|
+
f"eager: {exc}",
|
|
521
|
+
RuntimeWarning,
|
|
522
|
+
stacklevel=2,
|
|
523
|
+
)
|
|
524
|
+
self._jit_cache[key] = None
|
|
525
|
+
return None
|
|
526
|
+
if len(want) == 1 and want[0] == "forces":
|
|
527
|
+
assert forces is not None
|
|
528
|
+
return {"forces": forces}
|
|
529
|
+
result = {"energy": energy}
|
|
530
|
+
if forces is not None:
|
|
531
|
+
result["forces"] = forces
|
|
532
|
+
return result
|
|
533
|
+
|
|
534
|
+
def evaluate(
|
|
535
|
+
self,
|
|
536
|
+
atoms: Atoms,
|
|
537
|
+
*,
|
|
538
|
+
properties: tuple[str, ...] = ("energy",),
|
|
539
|
+
method: str | None = None,
|
|
540
|
+
) -> dict[str, Any]:
|
|
541
|
+
props = tuple(properties)
|
|
542
|
+
unknown = set(props) - {"energy", "forces", "stress"}
|
|
543
|
+
if unknown:
|
|
544
|
+
raise ScopeError(
|
|
545
|
+
f"Unsupported properties for {type(self).__name__}: "
|
|
546
|
+
f"{sorted(unknown)}"
|
|
547
|
+
)
|
|
548
|
+
if "stress" in props and atoms.cell.rank != 3:
|
|
549
|
+
raise ValueError("stress requires a fully periodic cell")
|
|
550
|
+
|
|
551
|
+
resolved = self._resolve_method(method)
|
|
552
|
+
if resolved == "finite-difference":
|
|
553
|
+
return self._evaluate_finite_difference(atoms, props)
|
|
554
|
+
|
|
555
|
+
positions, species, table, cell, pbc, params = self._context(atoms)
|
|
556
|
+
volume = float(atoms.get_volume()) if "stress" in props else 1.0
|
|
557
|
+
|
|
558
|
+
if resolved == "analytic":
|
|
559
|
+
analytic_table = self._analytic_table(table, len(atoms))
|
|
560
|
+
if self.jit:
|
|
561
|
+
result = self._jit_evaluate(
|
|
562
|
+
positions,
|
|
563
|
+
species,
|
|
564
|
+
analytic_table,
|
|
565
|
+
cell,
|
|
566
|
+
pbc,
|
|
567
|
+
params,
|
|
568
|
+
props,
|
|
569
|
+
)
|
|
570
|
+
else:
|
|
571
|
+
result = self.evaluate_arrays(
|
|
572
|
+
positions,
|
|
573
|
+
species,
|
|
574
|
+
analytic_table,
|
|
575
|
+
cell,
|
|
576
|
+
pbc,
|
|
577
|
+
params,
|
|
578
|
+
want=props,
|
|
579
|
+
)
|
|
580
|
+
else: # autodiff
|
|
581
|
+
result = {}
|
|
582
|
+
jitted = (
|
|
583
|
+
self._jit_evaluate_ad(
|
|
584
|
+
positions, species, table, cell, pbc, params, props
|
|
585
|
+
)
|
|
586
|
+
if self.jit
|
|
587
|
+
else None
|
|
588
|
+
)
|
|
589
|
+
if jitted is not None:
|
|
590
|
+
result.update(jitted)
|
|
591
|
+
elif "energy" in props or "forces" in props:
|
|
592
|
+
|
|
593
|
+
def value(p: Any) -> Any:
|
|
594
|
+
return self.energy_arrays(
|
|
595
|
+
p, species, table, cell, pbc, params
|
|
596
|
+
)
|
|
597
|
+
|
|
598
|
+
if "forces" in props:
|
|
599
|
+
energy, gradient = ad.value_and_grad(value)(positions)
|
|
600
|
+
result["energy"] = energy
|
|
601
|
+
result["forces"] = -gradient
|
|
602
|
+
else:
|
|
603
|
+
result["energy"] = self.energy_arrays(
|
|
604
|
+
positions, species, table, cell, pbc, params
|
|
605
|
+
)
|
|
606
|
+
if "stress" in props:
|
|
607
|
+
result["stress"] = self._stress_autodiff(
|
|
608
|
+
positions,
|
|
609
|
+
species,
|
|
610
|
+
table,
|
|
611
|
+
cell,
|
|
612
|
+
pbc,
|
|
613
|
+
params,
|
|
614
|
+
volume,
|
|
615
|
+
)
|
|
616
|
+
|
|
617
|
+
converted: dict[str, Any] = {}
|
|
618
|
+
if "energy" in result:
|
|
619
|
+
converted["energy"] = float(to_numpy(result["energy"]))
|
|
620
|
+
if "forces" in result:
|
|
621
|
+
converted["forces"] = np.asarray(to_numpy(result["forces"]))
|
|
622
|
+
if "stress" in result:
|
|
623
|
+
converted["stress"] = np.asarray(to_numpy(result["stress"]))
|
|
624
|
+
return converted
|
|
625
|
+
|
|
626
|
+
def _stress_autodiff(
|
|
627
|
+
self,
|
|
628
|
+
positions: Any,
|
|
629
|
+
species: Any,
|
|
630
|
+
table: Any,
|
|
631
|
+
cell: Any,
|
|
632
|
+
pbc: Any,
|
|
633
|
+
params: Any,
|
|
634
|
+
volume: float,
|
|
635
|
+
) -> Any:
|
|
636
|
+
"""Differentiate the energy with respect to an affine strain."""
|
|
637
|
+
basis = np.zeros((6, 3, 3), dtype=float)
|
|
638
|
+
basis[0, 0, 0] = 1.0
|
|
639
|
+
basis[1, 1, 1] = 1.0
|
|
640
|
+
basis[2, 2, 2] = 1.0
|
|
641
|
+
for index, (a, b) in enumerate(((1, 2), (0, 2), (0, 1))):
|
|
642
|
+
basis[3 + index, a, b] = 1.0
|
|
643
|
+
basis[3 + index, b, a] = 1.0
|
|
644
|
+
basis_b = to_backend(basis, self.backend)
|
|
645
|
+
zero = do("zeros", (6,), like=positions)
|
|
646
|
+
|
|
647
|
+
def energy(strain_params: Any) -> Any:
|
|
648
|
+
strain = do("einsum", "k,kij->ij", strain_params, basis_b)
|
|
649
|
+
eye = do("eye", 3, like=positions)
|
|
650
|
+
deform = eye + strain
|
|
651
|
+
moved = do("matmul", positions, deform)
|
|
652
|
+
deformed_cell = do("matmul", cell, deform)
|
|
653
|
+
return self.energy_arrays(
|
|
654
|
+
moved, species, table, deformed_cell, pbc, params
|
|
655
|
+
)
|
|
656
|
+
|
|
657
|
+
derivative = to_numpy(ad.jacrev(energy)(zero))
|
|
658
|
+
derivative = np.asarray(derivative, dtype=float)
|
|
659
|
+
factors = np.array([1.0, 1.0, 1.0, 0.5, 0.5, 0.5])
|
|
660
|
+
d = derivative * factors
|
|
661
|
+
sigma = np.array(
|
|
662
|
+
[
|
|
663
|
+
[d[0], d[5], d[4]],
|
|
664
|
+
[d[5], d[1], d[3]],
|
|
665
|
+
[d[4], d[3], d[2]],
|
|
666
|
+
]
|
|
667
|
+
)
|
|
668
|
+
return sigma / volume
|
|
669
|
+
|
|
670
|
+
def _evaluate_finite_difference(
|
|
671
|
+
self, atoms: Atoms, properties: tuple[str, ...]
|
|
672
|
+
) -> dict[str, Any]:
|
|
673
|
+
"""Diagnostic finite-difference stress, analytic other properties."""
|
|
674
|
+
out: dict[str, Any] = {}
|
|
675
|
+
other = tuple(p for p in properties if p != "stress")
|
|
676
|
+
if other:
|
|
677
|
+
out.update(
|
|
678
|
+
self.evaluate(atoms, properties=other, method="analytic")
|
|
679
|
+
)
|
|
680
|
+
if "stress" in properties:
|
|
681
|
+
out["stress"] = self._stress_finite_difference(atoms)
|
|
682
|
+
return out
|
|
683
|
+
|
|
684
|
+
def _stress_finite_difference(
|
|
685
|
+
self, atoms: Atoms, step: float = 1e-5
|
|
686
|
+
) -> np.ndarray:
|
|
687
|
+
volume = float(atoms.get_volume())
|
|
688
|
+
positions = np.asarray(atoms.positions, dtype=np.float64)
|
|
689
|
+
cell = np.asarray(atoms.cell.array, dtype=np.float64)
|
|
690
|
+
identity = np.eye(3)
|
|
691
|
+
voigt = ((0, 0), (1, 1), (2, 2), (1, 2), (0, 2), (0, 1))
|
|
692
|
+
derivative = np.zeros(6)
|
|
693
|
+
try:
|
|
694
|
+
self.clear_cache()
|
|
695
|
+
for index, (a, b) in enumerate(voigt):
|
|
696
|
+
for sign in (1.0, -1.0):
|
|
697
|
+
strain = np.zeros((3, 3))
|
|
698
|
+
strain[a, b] = sign * step
|
|
699
|
+
if a != b:
|
|
700
|
+
strain[b, a] = sign * step
|
|
701
|
+
moved = atoms.copy()
|
|
702
|
+
moved.set_cell(
|
|
703
|
+
cell @ (identity + strain), scale_atoms=False
|
|
704
|
+
)
|
|
705
|
+
moved.positions = positions @ (identity + strain)
|
|
706
|
+
self.clear_cache()
|
|
707
|
+
energy = self.energy(moved, method="analytic")
|
|
708
|
+
derivative[index] += sign * energy / (2.0 * step)
|
|
709
|
+
if a != b:
|
|
710
|
+
derivative[index] *= 0.5
|
|
711
|
+
finally:
|
|
712
|
+
self.clear_cache()
|
|
713
|
+
sigma = derivative / volume
|
|
714
|
+
return np.array(
|
|
715
|
+
[
|
|
716
|
+
[sigma[0], sigma[5], sigma[4]],
|
|
717
|
+
[sigma[5], sigma[1], sigma[3]],
|
|
718
|
+
[sigma[4], sigma[3], sigma[2]],
|
|
719
|
+
]
|
|
720
|
+
)
|