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,388 @@
|
|
|
1
|
+
"""Neighbour tables in a backend friendly, statically shaped form.
|
|
2
|
+
|
|
3
|
+
Kernels need fixed shape neighbour arrays so that JAX can trace them, while
|
|
4
|
+
:mod:`arrayff.neighborlist` (sklearn backend by default) returns the usual
|
|
5
|
+
flat ``(i, j, S)`` edge list. This module converts one into the other with
|
|
6
|
+
vectorised numpy operations only: no Python loop over atoms or pairs.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import dataclasses as dc
|
|
12
|
+
from abc import ABC, abstractmethod
|
|
13
|
+
from functools import cached_property
|
|
14
|
+
from typing import Literal, Self, override
|
|
15
|
+
|
|
16
|
+
import numpy as np
|
|
17
|
+
from ase import Atoms
|
|
18
|
+
from numpy.typing import DTypeLike
|
|
19
|
+
|
|
20
|
+
from arrayff.neighbors._list import NeighborListBackendType, neighbor_list
|
|
21
|
+
from arrayff.utils.backend import infer_backend
|
|
22
|
+
from arrayff.utils.dispatch import do, to_backend, to_numpy
|
|
23
|
+
|
|
24
|
+
__all__ = ["NeighborPaddedTable", "NeighborEdgeList"]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dc.dataclass(frozen=True)
|
|
28
|
+
class NeighborListABC(ABC):
|
|
29
|
+
"""Base class for neighbour tables."""
|
|
30
|
+
|
|
31
|
+
def _first_array(self) -> np.ndarray:
|
|
32
|
+
"""Return the first stored array (used for backend detection)."""
|
|
33
|
+
return getattr(self, next(iter(self.__dataclass_fields__)))
|
|
34
|
+
|
|
35
|
+
def astype(self, dtype: DTypeLike = int) -> Self:
|
|
36
|
+
"""Return a copy whose arrays have the specified dtype.
|
|
37
|
+
|
|
38
|
+
Only defined for numpy backed tables; convert to a backend *after*
|
|
39
|
+
fixing the dtype (:meth:`to_backend` does this for you).
|
|
40
|
+
"""
|
|
41
|
+
if infer_backend(self._first_array()) != "numpy":
|
|
42
|
+
raise TypeError(
|
|
43
|
+
"astype() is only defined for numpy backed tables; "
|
|
44
|
+
"call it before to_backend()."
|
|
45
|
+
)
|
|
46
|
+
values: dict[str, np.ndarray] = {}
|
|
47
|
+
for name in self.__dataclass_fields__:
|
|
48
|
+
array = np.asarray(getattr(self, name))
|
|
49
|
+
values[name] = array.astype(bool if name == "mask" else dtype)
|
|
50
|
+
return self.__class__(**values)
|
|
51
|
+
|
|
52
|
+
def to_backend(self, backend: str, dtype: DTypeLike = int) -> Self:
|
|
53
|
+
"""Return a copy whose arrays live on `backend`."""
|
|
54
|
+
current = infer_backend(self._first_array())
|
|
55
|
+
if current == backend:
|
|
56
|
+
return self
|
|
57
|
+
if current != "numpy":
|
|
58
|
+
# Detach from the current backend first (torch/jax -> numpy).
|
|
59
|
+
detached = self.__class__(
|
|
60
|
+
**{
|
|
61
|
+
name: to_numpy(getattr(self, name))
|
|
62
|
+
for name in self.__dataclass_fields__
|
|
63
|
+
}
|
|
64
|
+
)
|
|
65
|
+
if backend == "numpy":
|
|
66
|
+
return detached
|
|
67
|
+
return detached.to_backend(backend, dtype=dtype)
|
|
68
|
+
obj = self.astype(dtype=dtype)
|
|
69
|
+
if backend == "numpy":
|
|
70
|
+
return obj
|
|
71
|
+
return self.__class__(
|
|
72
|
+
**{
|
|
73
|
+
name: to_backend(getattr(obj, name), backend)
|
|
74
|
+
for name in self.__dataclass_fields__
|
|
75
|
+
}
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
@classmethod
|
|
79
|
+
@abstractmethod
|
|
80
|
+
def empty(cls, *args, **kwargs) -> Self:
|
|
81
|
+
pass
|
|
82
|
+
|
|
83
|
+
@classmethod
|
|
84
|
+
@abstractmethod
|
|
85
|
+
def from_ase(
|
|
86
|
+
cls,
|
|
87
|
+
atoms: Atoms,
|
|
88
|
+
cutoff: float,
|
|
89
|
+
*,
|
|
90
|
+
backend: str | Literal["numpy", "jax", "torch"] = "numpy",
|
|
91
|
+
builder: NeighborListBackendType = "sklearn",
|
|
92
|
+
**kwargs,
|
|
93
|
+
) -> Self:
|
|
94
|
+
pass
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@dc.dataclass(frozen=True)
|
|
98
|
+
class NeighborEdgeList(NeighborListABC):
|
|
99
|
+
source: np.ndarray
|
|
100
|
+
target: np.ndarray
|
|
101
|
+
shift_x: np.ndarray
|
|
102
|
+
shift_y: np.ndarray
|
|
103
|
+
shift_z: np.ndarray
|
|
104
|
+
|
|
105
|
+
@cached_property
|
|
106
|
+
def shift(self) -> np.ndarray:
|
|
107
|
+
"""Return the combined ``(E, 3)`` shift array.
|
|
108
|
+
|
|
109
|
+
Stays on the table backend: ``np.column_stack`` would silently detach
|
|
110
|
+
(or fail on) torch/jax tensors.
|
|
111
|
+
"""
|
|
112
|
+
parts = [self.shift_x, self.shift_y, self.shift_z]
|
|
113
|
+
if infer_backend(self.shift_x) == "numpy":
|
|
114
|
+
return np.column_stack(parts).astype(np.int64)
|
|
115
|
+
return do("stack", parts, axis=-1)
|
|
116
|
+
|
|
117
|
+
def __post_init__(self) -> None:
|
|
118
|
+
msg = r"The shape of {} must be {}, but got {}."
|
|
119
|
+
for v, shape, name in [
|
|
120
|
+
(self.source, (len(self),), "source"),
|
|
121
|
+
(self.target, (len(self),), "target"),
|
|
122
|
+
(self.shift_x, (len(self),), "shift_x"),
|
|
123
|
+
(self.shift_y, (len(self),), "shift_y"),
|
|
124
|
+
(self.shift_z, (len(self),), "shift_z"),
|
|
125
|
+
]:
|
|
126
|
+
assert v.shape == shape, msg.format(name, shape, v.shape)
|
|
127
|
+
|
|
128
|
+
def __len__(self) -> int:
|
|
129
|
+
return int(self.source.shape[0])
|
|
130
|
+
|
|
131
|
+
@classmethod
|
|
132
|
+
@override
|
|
133
|
+
def empty(cls) -> Self:
|
|
134
|
+
return cls(
|
|
135
|
+
source=np.empty((0,), dtype=int),
|
|
136
|
+
target=np.empty((0,), dtype=int),
|
|
137
|
+
shift_x=np.empty((0,), dtype=int),
|
|
138
|
+
shift_y=np.empty((0,), dtype=int),
|
|
139
|
+
shift_z=np.empty((0,), dtype=int),
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
@classmethod
|
|
143
|
+
@override
|
|
144
|
+
def from_ase(
|
|
145
|
+
cls,
|
|
146
|
+
atoms: Atoms,
|
|
147
|
+
cutoff: float,
|
|
148
|
+
*,
|
|
149
|
+
backend: str | Literal["numpy", "jax", "torch"] = "numpy",
|
|
150
|
+
builder: NeighborListBackendType = "sklearn",
|
|
151
|
+
**kwargs,
|
|
152
|
+
) -> Self:
|
|
153
|
+
"""Build a padded neighbour table for ``atoms``.
|
|
154
|
+
|
|
155
|
+
Parameters
|
|
156
|
+
----------
|
|
157
|
+
cutoff:
|
|
158
|
+
Global cutoff radius in Angstrom.
|
|
159
|
+
backend:
|
|
160
|
+
Backend to use for the table. Defaults to ``"numpy"``.
|
|
161
|
+
builder:
|
|
162
|
+
Neighbour list implementation, ``"sklearn"`` (default) or any other
|
|
163
|
+
backend supported by :func:`arrayff.neighborlist.neighbor_list`.
|
|
164
|
+
"""
|
|
165
|
+
if not isinstance(atoms, Atoms):
|
|
166
|
+
raise TypeError(
|
|
167
|
+
f"Expected an ase.Atoms instance," #
|
|
168
|
+
f" but got {type(atoms).__name__}."
|
|
169
|
+
)
|
|
170
|
+
n_atoms = len(atoms)
|
|
171
|
+
if n_atoms == 0 or cutoff <= 0.0:
|
|
172
|
+
return cls.empty().to_backend(backend)
|
|
173
|
+
i, j, shift = neighbor_list(
|
|
174
|
+
"ijS",
|
|
175
|
+
a=atoms,
|
|
176
|
+
backend=builder,
|
|
177
|
+
cutoff=float(cutoff),
|
|
178
|
+
self_interaction=False,
|
|
179
|
+
bothways=True,
|
|
180
|
+
sorted=False,
|
|
181
|
+
)
|
|
182
|
+
x, y, z = shift.T
|
|
183
|
+
return (
|
|
184
|
+
cls(
|
|
185
|
+
source=i,
|
|
186
|
+
target=j,
|
|
187
|
+
shift_x=x,
|
|
188
|
+
shift_y=y,
|
|
189
|
+
shift_z=z,
|
|
190
|
+
)
|
|
191
|
+
.astype(int)
|
|
192
|
+
.to_backend(backend)
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
def to_padded(
|
|
196
|
+
self,
|
|
197
|
+
n_atoms: int,
|
|
198
|
+
*,
|
|
199
|
+
max_neighbors: int | None = None,
|
|
200
|
+
) -> NeighborPaddedTable:
|
|
201
|
+
"""Return a padded view of this edge list.
|
|
202
|
+
|
|
203
|
+
The conversion is a pure table operation (integer indices only);
|
|
204
|
+
values are copied to the current backend afterwards.
|
|
205
|
+
"""
|
|
206
|
+
backend = infer_backend(self.source)
|
|
207
|
+
source = np.asarray(to_numpy(self.source), dtype=np.int64)
|
|
208
|
+
target = np.asarray(to_numpy(self.target), dtype=np.int64)
|
|
209
|
+
shift = np.asarray(to_numpy(self.shift), dtype=np.int64)
|
|
210
|
+
if len(source) == 0:
|
|
211
|
+
return NeighborPaddedTable.empty(n_atoms).to_backend(backend)
|
|
212
|
+
|
|
213
|
+
counts = np.bincount(source, minlength=n_atoms)
|
|
214
|
+
width = int(np.max(counts, initial=0))
|
|
215
|
+
if max_neighbors is not None:
|
|
216
|
+
if int(max_neighbors) < width:
|
|
217
|
+
raise ValueError(
|
|
218
|
+
f"max_neighbors={max_neighbors} is smaller than the "
|
|
219
|
+
f"largest neighbour count ({width})."
|
|
220
|
+
)
|
|
221
|
+
width = int(max_neighbors)
|
|
222
|
+
|
|
223
|
+
order = np.argsort(source, kind="stable")
|
|
224
|
+
rows = source[order]
|
|
225
|
+
offsets = np.concatenate(([0], np.cumsum(counts)[:-1]))
|
|
226
|
+
cols = np.arange(len(order), dtype=np.int64) - offsets[rows]
|
|
227
|
+
|
|
228
|
+
index = np.zeros((n_atoms, width), dtype=np.int64)
|
|
229
|
+
table_shift = np.zeros((n_atoms, width, 3), dtype=np.int64)
|
|
230
|
+
mask = np.zeros((n_atoms, width), dtype=bool)
|
|
231
|
+
index[rows, cols] = target[order]
|
|
232
|
+
table_shift[rows, cols] = shift[order]
|
|
233
|
+
mask[rows, cols] = True
|
|
234
|
+
table = NeighborPaddedTable(index=index, shift=table_shift, mask=mask)
|
|
235
|
+
return table.to_backend(backend)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
@dc.dataclass(frozen=True)
|
|
239
|
+
class NeighborPaddedTable(NeighborListABC):
|
|
240
|
+
"""Padded neighbour table for each atom.
|
|
241
|
+
|
|
242
|
+
Attributes
|
|
243
|
+
----------
|
|
244
|
+
index:
|
|
245
|
+
``(N, M)`` int array of neighbour indices; padding entries point at
|
|
246
|
+
atom 0 and must be ignored via ``mask``.
|
|
247
|
+
shift:
|
|
248
|
+
``(N, M, 3)`` int array of periodic image shifts ``S`` such that
|
|
249
|
+
``d_ij = r_j - r_i + S @ cell``.
|
|
250
|
+
mask:
|
|
251
|
+
``(N, M)`` bool array, ``True`` for real neighbours.
|
|
252
|
+
"""
|
|
253
|
+
|
|
254
|
+
index: np.ndarray
|
|
255
|
+
shift: np.ndarray
|
|
256
|
+
mask: np.ndarray
|
|
257
|
+
|
|
258
|
+
def __post_init__(self) -> None:
|
|
259
|
+
msg = r"The shape of `{}` must be {}, but got {}."
|
|
260
|
+
assert self.index.ndim == 2, "The `index` must be 2D array."
|
|
261
|
+
for v, shape, name in [
|
|
262
|
+
(self.shift, self.index.shape + (3,), "shift"),
|
|
263
|
+
(self.mask, self.index.shape, "mask"),
|
|
264
|
+
]:
|
|
265
|
+
assert v.shape == shape, msg.format(name, shape, v.shape)
|
|
266
|
+
|
|
267
|
+
def __len__(self) -> int:
|
|
268
|
+
return int(self.index.shape[0])
|
|
269
|
+
|
|
270
|
+
@property
|
|
271
|
+
def n_atoms(self) -> int:
|
|
272
|
+
return self.__len__()
|
|
273
|
+
|
|
274
|
+
@property
|
|
275
|
+
def max_neighbors(self) -> int:
|
|
276
|
+
return int(self.index.shape[1])
|
|
277
|
+
|
|
278
|
+
@property
|
|
279
|
+
def n_neighbors_total(self) -> int:
|
|
280
|
+
return int(np.asarray(to_numpy(self.mask)).sum())
|
|
281
|
+
|
|
282
|
+
@classmethod
|
|
283
|
+
@override
|
|
284
|
+
def empty(cls, n_atoms: int) -> Self:
|
|
285
|
+
return cls(
|
|
286
|
+
index=np.empty((n_atoms, 0), dtype=int),
|
|
287
|
+
shift=np.empty((n_atoms, 0, 3), dtype=int),
|
|
288
|
+
mask=np.zeros((n_atoms, 0), dtype=bool),
|
|
289
|
+
)
|
|
290
|
+
|
|
291
|
+
@classmethod
|
|
292
|
+
@override
|
|
293
|
+
def from_ase(
|
|
294
|
+
cls,
|
|
295
|
+
atoms: Atoms,
|
|
296
|
+
cutoff: float,
|
|
297
|
+
*,
|
|
298
|
+
backend: str | Literal["numpy", "jax", "torch"] = "numpy",
|
|
299
|
+
builder: NeighborListBackendType = "sklearn",
|
|
300
|
+
max_neighbors: int | None = None,
|
|
301
|
+
**kwargs,
|
|
302
|
+
) -> Self:
|
|
303
|
+
"""Build a padded neighbour table for ``atoms``.
|
|
304
|
+
|
|
305
|
+
Parameters
|
|
306
|
+
----------
|
|
307
|
+
cutoff:
|
|
308
|
+
Global cutoff radius in Angstrom.
|
|
309
|
+
backend:
|
|
310
|
+
Backend to use for the table. Defaults to ``"numpy"``.
|
|
311
|
+
builder:
|
|
312
|
+
Neighbour list implementation, ``"sklearn"`` (default) or any other
|
|
313
|
+
backend supported by :func:`arrayff.neighborlist.neighbor_list`.
|
|
314
|
+
max_neighbors:
|
|
315
|
+
Fixed second dimension of the table. Required for JAX when the shape
|
|
316
|
+
must stay constant between calls; defaults to the largest neighbour
|
|
317
|
+
count found.
|
|
318
|
+
"""
|
|
319
|
+
if not isinstance(atoms, Atoms):
|
|
320
|
+
raise TypeError(
|
|
321
|
+
f"Expected an ase.Atoms instance," #
|
|
322
|
+
f" but got {type(atoms).__name__}."
|
|
323
|
+
)
|
|
324
|
+
n_atoms = len(atoms)
|
|
325
|
+
if n_atoms == 0 or cutoff <= 0.0:
|
|
326
|
+
return cls.empty(n_atoms).to_backend(backend)
|
|
327
|
+
i, j, shift = neighbor_list(
|
|
328
|
+
"ijS",
|
|
329
|
+
a=atoms,
|
|
330
|
+
backend=builder,
|
|
331
|
+
cutoff=float(cutoff),
|
|
332
|
+
self_interaction=False,
|
|
333
|
+
bothways=True,
|
|
334
|
+
sorted=False,
|
|
335
|
+
)
|
|
336
|
+
i = np.asarray(i, dtype=np.int64)
|
|
337
|
+
j = np.asarray(j, dtype=np.int64)
|
|
338
|
+
shift = np.asarray(shift, dtype=np.int64)
|
|
339
|
+
if len(i) == 0:
|
|
340
|
+
return cls.empty(n_atoms).to_backend(backend)
|
|
341
|
+
|
|
342
|
+
counts = np.bincount(i, minlength=n_atoms)
|
|
343
|
+
width = int(np.max(counts, initial=0))
|
|
344
|
+
if max_neighbors is not None:
|
|
345
|
+
if int(max_neighbors) < width:
|
|
346
|
+
raise ValueError(
|
|
347
|
+
f"max_neighbors={max_neighbors} is smaller than the "
|
|
348
|
+
f"largest "
|
|
349
|
+
f"neighbour count ({width})."
|
|
350
|
+
)
|
|
351
|
+
width = int(max_neighbors)
|
|
352
|
+
|
|
353
|
+
# Vectorised grouping: sort by centre atom, then compute each entry's
|
|
354
|
+
# column inside its row from the running offsets.
|
|
355
|
+
order = np.argsort(i, kind="stable")
|
|
356
|
+
rows = i[order]
|
|
357
|
+
offsets = np.concatenate(([0], np.cumsum(counts)[:-1]))
|
|
358
|
+
cols = np.arange(len(order), dtype=np.int64) - offsets[rows]
|
|
359
|
+
|
|
360
|
+
index = np.zeros((n_atoms, width), dtype=np.int64)
|
|
361
|
+
table_shift = np.zeros((n_atoms, width, 3), dtype=np.int64)
|
|
362
|
+
mask = np.zeros((n_atoms, width), dtype=bool)
|
|
363
|
+
index[rows, cols] = j[order]
|
|
364
|
+
table_shift[rows, cols] = shift[order]
|
|
365
|
+
mask[rows, cols] = True
|
|
366
|
+
table = cls(index=index, shift=table_shift, mask=mask)
|
|
367
|
+
return table.to_backend(backend)
|
|
368
|
+
|
|
369
|
+
def to_edgelist(self) -> NeighborEdgeList:
|
|
370
|
+
"""Flatten the padded table into an edge list (numpy tables only)."""
|
|
371
|
+
if infer_backend(self.index) != "numpy":
|
|
372
|
+
raise TypeError(
|
|
373
|
+
"to_edgelist() requires a numpy backed table; convert the "
|
|
374
|
+
"result afterwards."
|
|
375
|
+
)
|
|
376
|
+
n_atoms, width = self.index.shape
|
|
377
|
+
mask = np.asarray(self.mask, dtype=bool)
|
|
378
|
+
rows = np.broadcast_to(np.arange(n_atoms)[:, None], (n_atoms, width))
|
|
379
|
+
source = rows[mask].astype(np.int64)
|
|
380
|
+
target = np.asarray(self.index)[mask].astype(np.int64)
|
|
381
|
+
shift = np.asarray(self.shift)[mask].astype(np.int64)
|
|
382
|
+
return NeighborEdgeList(
|
|
383
|
+
source=source,
|
|
384
|
+
target=target,
|
|
385
|
+
shift_x=shift[:, 0],
|
|
386
|
+
shift_y=shift[:, 1],
|
|
387
|
+
shift_z=shift[:, 2],
|
|
388
|
+
)
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Short ranged potentials and their optional adapters.
|
|
2
|
+
|
|
3
|
+
The core potential classes are imported eagerly. ASE calculators and torch
|
|
4
|
+
wrappers are exposed lazily: importing ``arrayff.potentials`` must not import
|
|
5
|
+
``torch`` or ``ase.calculators`` on their behalf.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import importlib
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from arrayff.potentials.base import Potential, PotentialBase
|
|
14
|
+
from arrayff.potentials.composite import CompositePotential
|
|
15
|
+
from arrayff.potentials.eam.eam import EAM
|
|
16
|
+
from arrayff.potentials.emt.emt import EMT
|
|
17
|
+
from arrayff.potentials.pairwise.lj import LennardJones
|
|
18
|
+
from arrayff.potentials.pairwise.lj93 import LennardJones93 as LJ93
|
|
19
|
+
from arrayff.potentials.pairwise.morse import Morse
|
|
20
|
+
from arrayff.potentials.placeholders import MEAM, UF3
|
|
21
|
+
from arrayff.potentials.registry import (
|
|
22
|
+
available_potentials,
|
|
23
|
+
get_potential,
|
|
24
|
+
register_potential,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
"EAM",
|
|
29
|
+
"EMT",
|
|
30
|
+
"LJ93",
|
|
31
|
+
"MEAM",
|
|
32
|
+
"UF3",
|
|
33
|
+
"ArrayFFCalculator",
|
|
34
|
+
"CompositePotential",
|
|
35
|
+
"EAMCalculator",
|
|
36
|
+
"EMTCalculator",
|
|
37
|
+
"LJ93Calculator",
|
|
38
|
+
"LJ93Torch",
|
|
39
|
+
"LJCalculator",
|
|
40
|
+
"LJTorch",
|
|
41
|
+
"LennardJones",
|
|
42
|
+
"Morse",
|
|
43
|
+
"MorseCalculator",
|
|
44
|
+
"MorseTorch",
|
|
45
|
+
"PairwiseTorch",
|
|
46
|
+
"Potential",
|
|
47
|
+
"PotentialBase",
|
|
48
|
+
"available_potentials",
|
|
49
|
+
"get_potential",
|
|
50
|
+
"register_potential",
|
|
51
|
+
]
|
|
52
|
+
|
|
53
|
+
_LAZY: dict[str, str] = {
|
|
54
|
+
"ArrayFFCalculator": "arrayff.potentials.calculator",
|
|
55
|
+
"LJCalculator": "arrayff.potentials.pairwise.calculator",
|
|
56
|
+
"MorseCalculator": "arrayff.potentials.pairwise.calculator",
|
|
57
|
+
"LJ93Calculator": "arrayff.potentials.pairwise.calculator",
|
|
58
|
+
"EMTCalculator": "arrayff.potentials.emt.calculator",
|
|
59
|
+
"EAMCalculator": "arrayff.potentials.eam.calculator",
|
|
60
|
+
"LJTorch": "arrayff.potentials.pairwise._torch",
|
|
61
|
+
"MorseTorch": "arrayff.potentials.pairwise._torch",
|
|
62
|
+
"LJ93Torch": "arrayff.potentials.pairwise._torch",
|
|
63
|
+
"PairwiseTorch": "arrayff.potentials.pairwise._torch",
|
|
64
|
+
"EMTTorch": "arrayff.potentials.emt._torch",
|
|
65
|
+
"EAMTorch": "arrayff.potentials.eam._torch",
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def __getattr__(name: str) -> Any:
|
|
70
|
+
module_name = _LAZY.get(name)
|
|
71
|
+
if module_name is None:
|
|
72
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
73
|
+
module = importlib.import_module(module_name)
|
|
74
|
+
value = getattr(module, name)
|
|
75
|
+
globals()[name] = value
|
|
76
|
+
return value
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Shared tensor level API for the optional torch wrappers.
|
|
2
|
+
|
|
3
|
+
Importing this module is the opt-in point for PyTorch: ``arrayff.potentials``
|
|
4
|
+
itself never imports it.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import torch
|
|
12
|
+
from torch import nn
|
|
13
|
+
|
|
14
|
+
__all__ = ["TorchPotential"]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class TorchPotential(nn.Module):
|
|
18
|
+
"""Mixin adding tensor energy/forces on top of a :class:`Potential`."""
|
|
19
|
+
|
|
20
|
+
def energy_tensor(self, atoms: Any) -> torch.Tensor:
|
|
21
|
+
"""Return the energy as a scalar tensor (graph attached)."""
|
|
22
|
+
positions, species, table, cell, pbc, params = self._context(atoms)
|
|
23
|
+
return self.energy_arrays(positions, species, table, cell, pbc, params)
|
|
24
|
+
|
|
25
|
+
def forces_tensor(
|
|
26
|
+
self, atoms: Any, *, method: str = "autodiff"
|
|
27
|
+
) -> torch.Tensor:
|
|
28
|
+
"""Return forces (eV/Angstrom) as a tensor."""
|
|
29
|
+
positions, species, table, cell, pbc, params = self._context(atoms)
|
|
30
|
+
if method == "analytic":
|
|
31
|
+
return self.forces_arrays(
|
|
32
|
+
positions, species, table, cell, pbc, params
|
|
33
|
+
)
|
|
34
|
+
positions = positions.detach().clone().requires_grad_(True)
|
|
35
|
+
energy = self.energy_arrays(
|
|
36
|
+
positions, species, table, cell, pbc, params
|
|
37
|
+
)
|
|
38
|
+
(gradient,) = torch.autograd.grad(
|
|
39
|
+
energy, positions, create_graph=self.training
|
|
40
|
+
)
|
|
41
|
+
return -gradient
|
|
42
|
+
|
|
43
|
+
def forward(self, atoms: Any) -> torch.Tensor:
|
|
44
|
+
return self.energy_tensor(atoms)
|