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,649 @@
|
|
|
1
|
+
import itertools
|
|
2
|
+
from typing import Literal
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
from ase.atoms import Atoms
|
|
6
|
+
from ase.cell import Cell
|
|
7
|
+
from ase.geometry import minkowski_reduce
|
|
8
|
+
from ase.neighborlist import _calc_expansion as __ase_calc_expansion
|
|
9
|
+
from ase.neighborlist import build_neighbor_list as __build_neighbor_list_ase
|
|
10
|
+
from ase.neighborlist import neighbor_list as _ase_neighbor_list_3loop
|
|
11
|
+
from numpy.typing import ArrayLike
|
|
12
|
+
from scipy import sparse as sp
|
|
13
|
+
from sklearn.neighbors import NearestNeighbors
|
|
14
|
+
|
|
15
|
+
from arrayff.utils.exceptions import MissingBackendError
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"neighbor_list",
|
|
19
|
+
"distance_pairs",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
#############################################################
|
|
24
|
+
# sklearn/scipy for `distance_pairs`
|
|
25
|
+
def _sklearn_query_ball_point(
|
|
26
|
+
p1: np.ndarray,
|
|
27
|
+
p2: np.ndarray | None = None,
|
|
28
|
+
max_distance: float = float("inf"),
|
|
29
|
+
return_distance: bool = False,
|
|
30
|
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray | None]:
|
|
31
|
+
"""Query ball point by distance.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
p1 (np.ndarray): The query point or points.
|
|
35
|
+
p2 (np.ndarray): The query point or points.
|
|
36
|
+
max_distance (float): Maximum distance of neighborhoods.
|
|
37
|
+
return_distance (bool, optional): Whether to return distance.
|
|
38
|
+
"""
|
|
39
|
+
p1 = np.asarray(p1, dtype=float)
|
|
40
|
+
if p2 is None:
|
|
41
|
+
p2_: np.ndarray = p1
|
|
42
|
+
else:
|
|
43
|
+
p2_ = np.asarray(p2, dtype=float)
|
|
44
|
+
assert isinstance(p2_, np.ndarray)
|
|
45
|
+
l1, l2 = p1.shape[0], p2_.shape[0]
|
|
46
|
+
if l1 >= l2:
|
|
47
|
+
swap = False
|
|
48
|
+
else:
|
|
49
|
+
swap, p1, p2_ = True, p2_, p1
|
|
50
|
+
assert p1.shape[0] >= p2_.shape[0]
|
|
51
|
+
|
|
52
|
+
nn = NearestNeighbors()
|
|
53
|
+
nn.fit(X=p1, y=None)
|
|
54
|
+
distance = nn.radius_neighbors_graph(
|
|
55
|
+
X=p2_,
|
|
56
|
+
radius=float(max_distance),
|
|
57
|
+
mode="distance" if return_distance else "connectivity",
|
|
58
|
+
)
|
|
59
|
+
m = sp.coo_matrix(distance if swap else distance.T)
|
|
60
|
+
d = distance.data if return_distance else None
|
|
61
|
+
assert m.shape == (l1, l2), (
|
|
62
|
+
f"Invalid shape: {m.shape} " #
|
|
63
|
+
f"(expect {l1, l2})"
|
|
64
|
+
)
|
|
65
|
+
return m.row, m.col, d
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _sklearn_get_distance_pairs(
|
|
69
|
+
p1: np.ndarray,
|
|
70
|
+
p2: np.ndarray | None = None,
|
|
71
|
+
cell: np.ndarray | Cell | None = None,
|
|
72
|
+
max_distance: float = float("inf"),
|
|
73
|
+
return_distance: bool = True,
|
|
74
|
+
pbc: np.ndarray | None = None,
|
|
75
|
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray | None]:
|
|
76
|
+
if not isinstance(cell, Cell):
|
|
77
|
+
cell = Cell.new(cell=cell)
|
|
78
|
+
if pbc is None:
|
|
79
|
+
pbc = np.asarray(getattr(cell, "pbc", np.ones(3, dtype=bool)))
|
|
80
|
+
pbc = np.asarray(pbc, dtype=bool)
|
|
81
|
+
if not pbc.any():
|
|
82
|
+
source, target, dist = _sklearn_query_ball_point(
|
|
83
|
+
p1=p1,
|
|
84
|
+
p2=p2,
|
|
85
|
+
max_distance=max_distance,
|
|
86
|
+
return_distance=bool(return_distance),
|
|
87
|
+
)
|
|
88
|
+
shift = np.zeros((len(source), 3), int)
|
|
89
|
+
return source, target, shift, dist
|
|
90
|
+
if not pbc.all():
|
|
91
|
+
raise NotImplementedError(
|
|
92
|
+
"mixed periodic boundary conditions are not supported by the "
|
|
93
|
+
"sklearn neighbour backend; use backend='ase_3loop'"
|
|
94
|
+
)
|
|
95
|
+
else:
|
|
96
|
+
assert np.isfinite(max_distance), (
|
|
97
|
+
"max_distance must be finite for periodic cell."
|
|
98
|
+
)
|
|
99
|
+
# The Minkowski-reduced cell is used for the periodic expansion,
|
|
100
|
+
# while the returned shift vectors are expressed in the original cell.
|
|
101
|
+
rcell, op = minkowski_reduce(cell)
|
|
102
|
+
rcell = np.asarray(rcell, dtype=float)
|
|
103
|
+
op = np.asarray(op, dtype=int)
|
|
104
|
+
p1 = np.asarray(p1, dtype=float)
|
|
105
|
+
if p2 is None:
|
|
106
|
+
p2 = p1
|
|
107
|
+
else:
|
|
108
|
+
p2 = np.asarray(p2, dtype=float)
|
|
109
|
+
l1 = p1.shape[0]
|
|
110
|
+
# Wrap the points into the reduced cell and record the integer cell
|
|
111
|
+
# offsets, i.e. p_wrapped = p + offset @ rcell.
|
|
112
|
+
inv_rcell = np.linalg.pinv(rcell)
|
|
113
|
+
offset1 = -np.floor(p1 @ inv_rcell).astype(int)
|
|
114
|
+
offset2 = -np.floor(p2 @ inv_rcell).astype(int)
|
|
115
|
+
p1_wrapped = p1 + offset1 @ rcell
|
|
116
|
+
p2_wrapped = p2 + offset2 @ rcell
|
|
117
|
+
# Enumerate all the periodic images of the first points set.
|
|
118
|
+
pbc = np.asarray([True, True, True])
|
|
119
|
+
n = __ase_calc_expansion(rcell, pbc, max_distance / 2)
|
|
120
|
+
nrange3 = [range(-i, i + 1) for i in n]
|
|
121
|
+
shift_vectors = np.array(list(itertools.product(*nrange3)), dtype=int)
|
|
122
|
+
arr_p1 = p1_wrapped[None, :, :] + (shift_vectors @ rcell)[:, None, :]
|
|
123
|
+
arr_p1 = arr_p1.reshape(-1, 3)
|
|
124
|
+
source, target, dist = _sklearn_query_ball_point(
|
|
125
|
+
p1=arr_p1,
|
|
126
|
+
p2=p2_wrapped,
|
|
127
|
+
max_distance=max_distance,
|
|
128
|
+
return_distance=bool(return_distance),
|
|
129
|
+
)
|
|
130
|
+
image_idx, source = np.divmod(source, l1)
|
|
131
|
+
# The distance vector in the reduced cell is
|
|
132
|
+
# D = p2[target] - p1[source] + shift_rcell @ rcell,
|
|
133
|
+
# and it is converted to the original cell by `rcell = op @ cell`,
|
|
134
|
+
# i.e. shift = shift_rcell @ op, so that
|
|
135
|
+
# D = p2[target] - p1[source] + shift @ cell
|
|
136
|
+
shift_rcell = (
|
|
137
|
+
offset2[target] - offset1[source] - shift_vectors[image_idx]
|
|
138
|
+
)
|
|
139
|
+
shift = shift_rcell @ op
|
|
140
|
+
return (
|
|
141
|
+
source.astype(int),
|
|
142
|
+
target.astype(int),
|
|
143
|
+
shift.astype(int),
|
|
144
|
+
dist,
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
#############################################################
|
|
149
|
+
# pymatgen for `distance_pairs`
|
|
150
|
+
def _pymatgen_get_distance_pairs(
|
|
151
|
+
p1: np.ndarray,
|
|
152
|
+
p2: np.ndarray | None = None,
|
|
153
|
+
cell: np.ndarray | Cell | None = None,
|
|
154
|
+
max_distance: float = float("inf"),
|
|
155
|
+
return_distance: bool = True,
|
|
156
|
+
pbc: np.ndarray | None = None,
|
|
157
|
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray | None]:
|
|
158
|
+
if not isinstance(cell, Cell):
|
|
159
|
+
cell = Cell.new(cell=cell)
|
|
160
|
+
p1 = np.asarray(p1, dtype=float)
|
|
161
|
+
if p2 is None:
|
|
162
|
+
p2 = p1
|
|
163
|
+
else:
|
|
164
|
+
p2 = np.asarray(p2, dtype=float)
|
|
165
|
+
assert p1.ndim == p2.ndim == 2
|
|
166
|
+
assert p1.shape[1] == p2.shape[1] == 3
|
|
167
|
+
l1, l2 = p1.shape[0], p2.shape[0]
|
|
168
|
+
max_distance = float(max_distance)
|
|
169
|
+
assert max_distance > 0
|
|
170
|
+
if pbc is None:
|
|
171
|
+
pbc = np.asarray(getattr(cell, "pbc", np.ones(3, dtype=bool)))
|
|
172
|
+
pbc = np.asarray(pbc, dtype=bool)
|
|
173
|
+
|
|
174
|
+
if not pbc.any():
|
|
175
|
+
return _sklearn_get_distance_pairs(
|
|
176
|
+
p1=p1,
|
|
177
|
+
p2=p2,
|
|
178
|
+
cell=cell,
|
|
179
|
+
max_distance=max_distance,
|
|
180
|
+
return_distance=return_distance,
|
|
181
|
+
pbc=pbc,
|
|
182
|
+
)
|
|
183
|
+
if not pbc.all():
|
|
184
|
+
raise NotImplementedError(
|
|
185
|
+
"mixed periodic boundary conditions are not supported by the "
|
|
186
|
+
"pymatgen neighbour backend; use backend='ase_3loop'"
|
|
187
|
+
)
|
|
188
|
+
else:
|
|
189
|
+
try:
|
|
190
|
+
import pymatgen # type: ignore # noqa: F401
|
|
191
|
+
except ImportError:
|
|
192
|
+
raise ImportError(
|
|
193
|
+
"Cannot import `pymatgen` module. Please install it first."
|
|
194
|
+
)
|
|
195
|
+
try:
|
|
196
|
+
from pymatgen.optimization.neighbors import ( # type: ignore
|
|
197
|
+
find_points_in_spheres,
|
|
198
|
+
)
|
|
199
|
+
except ImportError:
|
|
200
|
+
raise ImportError(
|
|
201
|
+
"Cannot import `find_points_in_spheres` from "
|
|
202
|
+
"`pymatgen.optimization.neighbors` module. Please "
|
|
203
|
+
"upgrade your pymatgen to 2022.0.10 or later."
|
|
204
|
+
)
|
|
205
|
+
target, source, shift, distance = find_points_in_spheres(
|
|
206
|
+
np.ascontiguousarray(p1, dtype=float),
|
|
207
|
+
np.ascontiguousarray(p2, dtype=float),
|
|
208
|
+
r=max_distance,
|
|
209
|
+
pbc=np.ascontiguousarray(pbc, dtype=np.int64),
|
|
210
|
+
lattice=np.ascontiguousarray(cell.array, dtype=float),
|
|
211
|
+
tol=1e-8,
|
|
212
|
+
)
|
|
213
|
+
shift = np.asarray(shift, int)
|
|
214
|
+
target = np.asarray(target, int)
|
|
215
|
+
source = np.asarray(source, int)
|
|
216
|
+
distance = np.asarray(distance, float)
|
|
217
|
+
assert distance.shape == (len(source),), "Impossible"
|
|
218
|
+
assert source.shape == (len(source),), "Impossible"
|
|
219
|
+
assert target.shape == (len(target),), "Impossible"
|
|
220
|
+
assert shift.shape == (len(source), 3), "Impossible"
|
|
221
|
+
assert source.max() < l1 and target.max() < l2
|
|
222
|
+
self_pair = (source == target) & (distance <= 1e-5)
|
|
223
|
+
cond = np.logical_not(self_pair) # exclude self pair
|
|
224
|
+
return (
|
|
225
|
+
source[cond],
|
|
226
|
+
target[cond],
|
|
227
|
+
shift[cond] if cell.rank != 0 else None, # type: ignore
|
|
228
|
+
distance[cond] if return_distance else None,
|
|
229
|
+
)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
#############################################################
|
|
233
|
+
# interface for `distance_pairs`
|
|
234
|
+
def distance_pairs(
|
|
235
|
+
quantities: str,
|
|
236
|
+
p1: np.ndarray,
|
|
237
|
+
p2: np.ndarray | None = None,
|
|
238
|
+
cell: np.ndarray | Cell | None = None,
|
|
239
|
+
cutoff: float = 6.0,
|
|
240
|
+
backend: str | Literal["sklearn", "pmg", "pymatgen"] = "sklearn",
|
|
241
|
+
pbc: ArrayLike | None = None,
|
|
242
|
+
) -> tuple[np.ndarray, ...]:
|
|
243
|
+
"""Compute distance pairs for two points set.
|
|
244
|
+
|
|
245
|
+
Parameters
|
|
246
|
+
----------
|
|
247
|
+
quantities: str
|
|
248
|
+
Quantities to compute by the neighbor list algorithm. Each character
|
|
249
|
+
in this string defines a quantity. They are returned in a tuple of
|
|
250
|
+
the same order. Possible quantities are:
|
|
251
|
+
|
|
252
|
+
* 'i' : first atom index
|
|
253
|
+
* 'j' : second atom index
|
|
254
|
+
* 'd' : absolute distance
|
|
255
|
+
* 'D' : distance vector
|
|
256
|
+
* 'S' : shift vector (number of cell boundaries crossed by the bond
|
|
257
|
+
between atom i and j). With the shift vector S, the
|
|
258
|
+
distances D between atoms can be computed from:
|
|
259
|
+
D = p2[j] - p1[i] + S @ a.cell
|
|
260
|
+
p1: np.ndarray
|
|
261
|
+
the first points set.
|
|
262
|
+
p2: np.ndarray | None
|
|
263
|
+
the second points set. if none, p2 is p1.
|
|
264
|
+
cell: np.ndarray | Cell | None
|
|
265
|
+
the periodic lattice.
|
|
266
|
+
cutoff: float
|
|
267
|
+
This is a global cutoff for all points pair.
|
|
268
|
+
backend: str
|
|
269
|
+
The backend for computation.
|
|
270
|
+
|
|
271
|
+
Returns:
|
|
272
|
+
-------
|
|
273
|
+
i, j, ...: array
|
|
274
|
+
Tuple with arrays for each quantity specified above. Indices in `i`
|
|
275
|
+
are returned in ascending order 0..len(a), but the order of (i,j)
|
|
276
|
+
pairs is not guaranteed.
|
|
277
|
+
"""
|
|
278
|
+
p1 = np.asarray(p1, dtype=float)
|
|
279
|
+
if p2 is None:
|
|
280
|
+
p2 = p1
|
|
281
|
+
else:
|
|
282
|
+
p2 = np.asarray(p2, dtype=float)
|
|
283
|
+
assert p1.ndim == p2.ndim == 2
|
|
284
|
+
assert p1.shape[1] == p2.shape[1] == 3
|
|
285
|
+
cell = Cell.new(cell)
|
|
286
|
+
if pbc is None:
|
|
287
|
+
pbc = np.asarray(getattr(cell, "pbc", np.ones(3, dtype=bool)))
|
|
288
|
+
pbc = np.asarray(pbc, dtype=bool)
|
|
289
|
+
if pbc.any() and not np.isfinite(cutoff):
|
|
290
|
+
raise ValueError("cutoff must be finite for a periodic cell")
|
|
291
|
+
|
|
292
|
+
if backend.lower() == "sklearn":
|
|
293
|
+
i, j, S, d = _sklearn_get_distance_pairs(
|
|
294
|
+
p1=p1,
|
|
295
|
+
p2=p2,
|
|
296
|
+
cell=cell,
|
|
297
|
+
max_distance=cutoff,
|
|
298
|
+
return_distance=bool("d" in quantities),
|
|
299
|
+
pbc=pbc,
|
|
300
|
+
)
|
|
301
|
+
elif backend.lower() in ("pmg", "pymatgen"):
|
|
302
|
+
j, i, S, d = _pymatgen_get_distance_pairs(
|
|
303
|
+
p1=p2,
|
|
304
|
+
p2=p1,
|
|
305
|
+
cell=cell,
|
|
306
|
+
max_distance=cutoff,
|
|
307
|
+
return_distance=bool("d" in quantities),
|
|
308
|
+
pbc=pbc,
|
|
309
|
+
)
|
|
310
|
+
# Swap i-j & p1-p2 for that the result match:
|
|
311
|
+
# D = p2[j] - p1[i] + S @ a.cell
|
|
312
|
+
else:
|
|
313
|
+
raise NotImplementedError(
|
|
314
|
+
f"Invalid backend='{backend}', only 'sklearn',"
|
|
315
|
+
" 'pmg' and 'pymatgen' are supported."
|
|
316
|
+
)
|
|
317
|
+
dct = dict(zip("ijS", [i, j, S]))
|
|
318
|
+
if "D" in quantities:
|
|
319
|
+
dct["D"] = p2[j] - p1[i] + S @ cell
|
|
320
|
+
if "d" in quantities:
|
|
321
|
+
assert isinstance(d, np.ndarray)
|
|
322
|
+
dct["d"] = d # absolute distance
|
|
323
|
+
return tuple(dct[q] for q in quantities)
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
#############################################################
|
|
327
|
+
# ASE for `neighbor_list`
|
|
328
|
+
def _ase_neighbor_list_kdtree(
|
|
329
|
+
quantities: str,
|
|
330
|
+
a: Atoms,
|
|
331
|
+
cutoff: float,
|
|
332
|
+
indices: np.ndarray | None = None,
|
|
333
|
+
self_interaction: bool = False,
|
|
334
|
+
bothways: bool = True,
|
|
335
|
+
sorted: bool = True,
|
|
336
|
+
) -> tuple[np.ndarray, ...]:
|
|
337
|
+
if indices is None:
|
|
338
|
+
indices = np.arange(len(a))
|
|
339
|
+
nl = __build_neighbor_list_ase(
|
|
340
|
+
atoms=a,
|
|
341
|
+
cutoffs=[float(cutoff / 2)] * len(a),
|
|
342
|
+
self_interaction=self_interaction,
|
|
343
|
+
bothways=bothways,
|
|
344
|
+
sorted=sorted,
|
|
345
|
+
skin=0,
|
|
346
|
+
)
|
|
347
|
+
i = np.array([], dtype=int)
|
|
348
|
+
j = np.array([], dtype=int)
|
|
349
|
+
S = np.zeros(shape=(0, 3), dtype=int)
|
|
350
|
+
for idx in indices:
|
|
351
|
+
jj, SS = nl.get_neighbors(idx)
|
|
352
|
+
j = np.append(j, jj)
|
|
353
|
+
S = np.vstack([S, SS])
|
|
354
|
+
i = np.append(i, np.full(len(jj), idx))
|
|
355
|
+
dct: dict[str, np.ndarray] = {
|
|
356
|
+
"i": i,
|
|
357
|
+
"j": j,
|
|
358
|
+
"S": S,
|
|
359
|
+
}
|
|
360
|
+
if "d" in quantities.lower():
|
|
361
|
+
v = a.positions[j] - a.positions[i]
|
|
362
|
+
dct["D"] = D = v + S @ a.cell
|
|
363
|
+
if "d" in quantities:
|
|
364
|
+
dct["d"] = np.linalg.norm(D, axis=1)
|
|
365
|
+
return tuple(dct[q] for q in quantities)
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
#############################################################
|
|
369
|
+
# matscipy for `neighbor_list`
|
|
370
|
+
def _matscipy_neighbor_list(
|
|
371
|
+
quantities: str,
|
|
372
|
+
a: Atoms,
|
|
373
|
+
cutoff: float,
|
|
374
|
+
) -> tuple[np.ndarray, ...]:
|
|
375
|
+
try:
|
|
376
|
+
from matscipy.neighbours import ( # type: ignore # noqa: F401
|
|
377
|
+
neighbour_list as _matscipy_neighbour_list,
|
|
378
|
+
)
|
|
379
|
+
except ImportError as exc:
|
|
380
|
+
raise MissingBackendError(
|
|
381
|
+
"matscipy is required for builder='matscipy'; "
|
|
382
|
+
"install it with `pip install arrayff[builders]`"
|
|
383
|
+
) from exc
|
|
384
|
+
if a.cell.rank != 0:
|
|
385
|
+
return tuple(
|
|
386
|
+
_matscipy_neighbour_list(
|
|
387
|
+
quantities=quantities,
|
|
388
|
+
cutoff=cutoff,
|
|
389
|
+
atoms=a,
|
|
390
|
+
)
|
|
391
|
+
)
|
|
392
|
+
else:
|
|
393
|
+
return distance_pairs(
|
|
394
|
+
quantities,
|
|
395
|
+
p1=a.positions,
|
|
396
|
+
p2=a.positions,
|
|
397
|
+
cutoff=float(cutoff),
|
|
398
|
+
backend="sklearn",
|
|
399
|
+
cell=None,
|
|
400
|
+
)
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
#############################################################
|
|
404
|
+
# VESIN for `neighbor_list`
|
|
405
|
+
def _vesin_neighbor_list(
|
|
406
|
+
quantities: str,
|
|
407
|
+
a: Atoms,
|
|
408
|
+
cutoff: float,
|
|
409
|
+
self_interaction: bool = False,
|
|
410
|
+
max_nbins: int = 0,
|
|
411
|
+
) -> tuple[np.ndarray, ...]:
|
|
412
|
+
try:
|
|
413
|
+
from vesin import ase_neighbor_list # type: ignore
|
|
414
|
+
except ImportError as exc:
|
|
415
|
+
raise MissingBackendError(
|
|
416
|
+
"vesin is required for builder='vesin'; "
|
|
417
|
+
"install it with `pip install arrayff[builders]`"
|
|
418
|
+
) from exc
|
|
419
|
+
return tuple(
|
|
420
|
+
ase_neighbor_list(
|
|
421
|
+
quantities=quantities,
|
|
422
|
+
a=a,
|
|
423
|
+
cutoff=cutoff,
|
|
424
|
+
self_interaction=self_interaction,
|
|
425
|
+
max_nbins=max_nbins,
|
|
426
|
+
)
|
|
427
|
+
)
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
#############################################################
|
|
431
|
+
# interface for `neighbor_list`
|
|
432
|
+
type NeighborListBackendType = (
|
|
433
|
+
str
|
|
434
|
+
| Literal[
|
|
435
|
+
"vesin",
|
|
436
|
+
"matscipy",
|
|
437
|
+
"ase_3loop",
|
|
438
|
+
"ase_kdtree",
|
|
439
|
+
"pymatgen",
|
|
440
|
+
"sklearn",
|
|
441
|
+
]
|
|
442
|
+
)
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def neighbor_list(
|
|
446
|
+
quantities: str,
|
|
447
|
+
a: Atoms,
|
|
448
|
+
cutoff: float,
|
|
449
|
+
backend: NeighborListBackendType = "sklearn",
|
|
450
|
+
self_interaction: bool = False,
|
|
451
|
+
bothways: bool = True,
|
|
452
|
+
sorted: bool = True,
|
|
453
|
+
*args,
|
|
454
|
+
max_nbins: int = int(1e6),
|
|
455
|
+
indices: ArrayLike | None = None,
|
|
456
|
+
**kwargs,
|
|
457
|
+
) -> tuple[np.ndarray, ...]:
|
|
458
|
+
"""Compute a neighbor list for an atomic configuration.
|
|
459
|
+
|
|
460
|
+
Atoms outside periodic boundaries are mapped into the box. Atoms
|
|
461
|
+
outside nonperiodic boundaries are included in the neighbor list
|
|
462
|
+
but complexity of neighbor list search for those can become n^2.
|
|
463
|
+
|
|
464
|
+
The neighbor list is sorted by first atom index 'i', but not by second
|
|
465
|
+
atom index 'j'.
|
|
466
|
+
|
|
467
|
+
Parameters
|
|
468
|
+
----------
|
|
469
|
+
quantities: str
|
|
470
|
+
Quantities to compute by the neighbor list algorithm. Each character
|
|
471
|
+
in this string defines a quantity. They are returned in a tuple of
|
|
472
|
+
the same order. Possible quantities are:
|
|
473
|
+
|
|
474
|
+
* 'i' : first atom index
|
|
475
|
+
* 'j' : second atom index
|
|
476
|
+
* 'd' : absolute distance
|
|
477
|
+
* 'D' : distance vector
|
|
478
|
+
* 'S' : shift vector (number of cell boundaries crossed by the bond
|
|
479
|
+
between atom i and j). With the shift vector S, the
|
|
480
|
+
distances D between atoms can be computed from:
|
|
481
|
+
D = a.positions[j] - a.positions[i] + S @ a.cell
|
|
482
|
+
a: :class:`ase.Atoms`
|
|
483
|
+
Atomic configuration.
|
|
484
|
+
cutoff: float or dict
|
|
485
|
+
This is a global cutoff for all elements.
|
|
486
|
+
self_interaction: bool
|
|
487
|
+
Return the atom itself as its own neighbor if set to true.
|
|
488
|
+
Default: False
|
|
489
|
+
bothways: bool
|
|
490
|
+
Return all neighbors. Default is to return only "half" of
|
|
491
|
+
the neighbors.
|
|
492
|
+
sorted: bool
|
|
493
|
+
Sort the neighbor list by first atom index 'i', second atom
|
|
494
|
+
index 'j' and shift vector 'S'. Default: True
|
|
495
|
+
max_nbins: int
|
|
496
|
+
Maximum number of bins used in neighbor search. This is used to limit
|
|
497
|
+
the maximum amount of memory required by the neighbor list.
|
|
498
|
+
indices: np.ndarray | None
|
|
499
|
+
Indices of atoms to use in the neighbor list.
|
|
500
|
+
If None, all atoms are.
|
|
501
|
+
backend: str
|
|
502
|
+
The backend for computation.
|
|
503
|
+
|
|
504
|
+
Returns:
|
|
505
|
+
-------
|
|
506
|
+
i, j, ...: array
|
|
507
|
+
Tuple with arrays for each quantity specified above. Indices in `i`
|
|
508
|
+
are returned in ascending order 0..len(a), but the order of (i,j)
|
|
509
|
+
pairs is not guaranteed.
|
|
510
|
+
"""
|
|
511
|
+
assert isinstance(a, Atoms), (
|
|
512
|
+
f"The `a` must be ase.Atoms, but" #
|
|
513
|
+
f" {a.__class__.__name__} got"
|
|
514
|
+
)
|
|
515
|
+
assert all(i in "ijdDS" for i in quantities), (
|
|
516
|
+
"The `quantities` must be an elements of " #
|
|
517
|
+
f"'ijdDS', but got {quantities},"
|
|
518
|
+
)
|
|
519
|
+
old_quantities = quantities
|
|
520
|
+
for s in "ijS":
|
|
521
|
+
if s not in quantities:
|
|
522
|
+
quantities += s
|
|
523
|
+
|
|
524
|
+
if len(a) <= 1 and not np.asarray(a.pbc, dtype=bool).any():
|
|
525
|
+
empty: list[np.ndarray] = []
|
|
526
|
+
for quantity in old_quantities:
|
|
527
|
+
if quantity in ("i", "j"):
|
|
528
|
+
empty.append(np.empty(0, dtype=np.int64))
|
|
529
|
+
elif quantity == "S":
|
|
530
|
+
empty.append(np.empty((0, 3), dtype=np.int64))
|
|
531
|
+
elif quantity == "D":
|
|
532
|
+
empty.append(np.empty((0, 3), dtype=float))
|
|
533
|
+
else: # "d"
|
|
534
|
+
empty.append(np.empty(0, dtype=float))
|
|
535
|
+
return tuple(empty)
|
|
536
|
+
|
|
537
|
+
if indices is not None:
|
|
538
|
+
indices = np.asarray(indices, dtype=int)
|
|
539
|
+
indices = np.unique(indices.flatten())
|
|
540
|
+
if len(indices) == 0:
|
|
541
|
+
indices = None
|
|
542
|
+
else:
|
|
543
|
+
if not (0 <= indices.min() <= indices.max() < len(a)):
|
|
544
|
+
raise ValueError("indices must be in range [0, len(a))")
|
|
545
|
+
if len(indices) == len(a):
|
|
546
|
+
indices = None
|
|
547
|
+
if indices is not None and bothways is not True:
|
|
548
|
+
raise ValueError("indices is only supported with bothways=True")
|
|
549
|
+
|
|
550
|
+
msg = "The {} backend is not supported for non-empty indices."
|
|
551
|
+
if backend == "ase_kdtree":
|
|
552
|
+
return _ase_neighbor_list_kdtree(
|
|
553
|
+
quantities=quantities,
|
|
554
|
+
a=a,
|
|
555
|
+
cutoff=float(cutoff),
|
|
556
|
+
indices=indices,
|
|
557
|
+
self_interaction=self_interaction,
|
|
558
|
+
bothways=bothways,
|
|
559
|
+
sorted=sorted,
|
|
560
|
+
)
|
|
561
|
+
elif backend == "ase_3loop":
|
|
562
|
+
if indices is not None:
|
|
563
|
+
raise ValueError(msg.format(backend))
|
|
564
|
+
result = _ase_neighbor_list_3loop(
|
|
565
|
+
quantities=quantities,
|
|
566
|
+
a=a,
|
|
567
|
+
cutoff=float(cutoff),
|
|
568
|
+
self_interaction=self_interaction,
|
|
569
|
+
max_nbins=int(max_nbins),
|
|
570
|
+
) # type: ignore
|
|
571
|
+
elif backend in ("sklearn", "pmg", "pymatgen"):
|
|
572
|
+
pbc = np.asarray(a.pbc, dtype=bool)
|
|
573
|
+
if pbc.any() and not pbc.all():
|
|
574
|
+
# The sklearn/pymatgen wrappers only implement all-periodic or
|
|
575
|
+
# non-periodic cells; fall back to ASE for mixed boundary
|
|
576
|
+
# conditions instead of silently treating all axes as periodic.
|
|
577
|
+
if indices is not None:
|
|
578
|
+
raise ValueError(
|
|
579
|
+
"mixed pbc with indices is only supported by "
|
|
580
|
+
"backend='ase_kdtree'"
|
|
581
|
+
)
|
|
582
|
+
result = _ase_neighbor_list_3loop(
|
|
583
|
+
quantities=quantities,
|
|
584
|
+
a=a,
|
|
585
|
+
cutoff=float(cutoff),
|
|
586
|
+
self_interaction=self_interaction,
|
|
587
|
+
max_nbins=int(max_nbins),
|
|
588
|
+
) # type: ignore
|
|
589
|
+
else:
|
|
590
|
+
selected = indices
|
|
591
|
+
p1 = a.positions if selected is None else a.positions[selected]
|
|
592
|
+
result = distance_pairs(
|
|
593
|
+
quantities=quantities,
|
|
594
|
+
p1=p1,
|
|
595
|
+
p2=a.positions,
|
|
596
|
+
cell=a.cell,
|
|
597
|
+
cutoff=cutoff,
|
|
598
|
+
backend=backend,
|
|
599
|
+
pbc=pbc,
|
|
600
|
+
)
|
|
601
|
+
if selected is not None:
|
|
602
|
+
result = list(result)
|
|
603
|
+
i_index = quantities.index("i")
|
|
604
|
+
result[i_index] = selected[result[i_index]]
|
|
605
|
+
result = tuple(result)
|
|
606
|
+
elif backend == "vesin":
|
|
607
|
+
if indices is not None:
|
|
608
|
+
raise ValueError(msg.format(backend))
|
|
609
|
+
result = _vesin_neighbor_list(
|
|
610
|
+
quantities=quantities,
|
|
611
|
+
a=a,
|
|
612
|
+
cutoff=float(cutoff),
|
|
613
|
+
self_interaction=self_interaction,
|
|
614
|
+
max_nbins=int(max_nbins),
|
|
615
|
+
) # type: ignore
|
|
616
|
+
elif backend == "matscipy":
|
|
617
|
+
if indices is not None:
|
|
618
|
+
raise ValueError(msg.format(backend))
|
|
619
|
+
result = _matscipy_neighbor_list(
|
|
620
|
+
quantities=quantities,
|
|
621
|
+
a=a,
|
|
622
|
+
cutoff=float(cutoff),
|
|
623
|
+
)
|
|
624
|
+
else:
|
|
625
|
+
raise RuntimeError(f"Unknown neighbor list backend: {backend}")
|
|
626
|
+
|
|
627
|
+
dct = {k: result[i] for i, k in enumerate(quantities)}
|
|
628
|
+
assert set(dct.keys()) >= set("ijS"), "Impossible."
|
|
629
|
+
i, j, (Sx, Sy, Sz) = dct["i"], dct["j"], dct["S"].T
|
|
630
|
+
cond = np.ones(len(i), dtype=bool)
|
|
631
|
+
if not self_interaction:
|
|
632
|
+
self_interaction_cond = (Sx == 0) & (Sy == 0) & (Sz == 0)
|
|
633
|
+
self_interaction_cond = self_interaction_cond & (i == j)
|
|
634
|
+
cond[self_interaction_cond] = False
|
|
635
|
+
if not bothways:
|
|
636
|
+
bothways_cond_1 = Sx < 0
|
|
637
|
+
bothways_cond_2 = (Sx == 0) & (Sy < 0)
|
|
638
|
+
bothways_cond_3 = (Sx == 0) & (Sy == 0) & (Sz < 0)
|
|
639
|
+
bothways_cond_4 = (Sx == 0) & (Sy == 0) & (Sz == 0) & (i > j)
|
|
640
|
+
cond[bothways_cond_4] = False
|
|
641
|
+
cond[bothways_cond_3] = False
|
|
642
|
+
cond[bothways_cond_2] = False
|
|
643
|
+
cond[bothways_cond_1] = False
|
|
644
|
+
dct = {k: v[cond] for k, v in dct.items()}
|
|
645
|
+
if sorted:
|
|
646
|
+
i, j, (Sx, Sy, Sz) = dct["i"], dct["j"], dct["S"].T
|
|
647
|
+
idx: np.ndarray = np.lexsort((Sx, Sy, Sz, j, i))
|
|
648
|
+
dct = {k: v[idx] for k, v in dct.items()}
|
|
649
|
+
return tuple(dct[k] for k in old_quantities)
|