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.
Files changed (50) hide show
  1. arrayff/__init__.py +29 -0
  2. arrayff/electrostatics/__init__.py +20 -0
  3. arrayff/electrostatics/calculator.py +18 -0
  4. arrayff/electrostatics/placeholders.py +23 -0
  5. arrayff/electrostatics/qeq.py +498 -0
  6. arrayff/neighbors/__init__.py +9 -0
  7. arrayff/neighbors/_list.py +649 -0
  8. arrayff/neighbors/_table.py +388 -0
  9. arrayff/potentials/__init__.py +76 -0
  10. arrayff/potentials/_torch.py +44 -0
  11. arrayff/potentials/base.py +720 -0
  12. arrayff/potentials/calculator.py +146 -0
  13. arrayff/potentials/composite.py +142 -0
  14. arrayff/potentials/eam/__init__.py +1 -0
  15. arrayff/potentials/eam/_torch.py +31 -0
  16. arrayff/potentials/eam/calculator.py +20 -0
  17. arrayff/potentials/eam/eam.py +233 -0
  18. arrayff/potentials/eam/io/__init__.py +8 -0
  19. arrayff/potentials/eam/io/eam.py +115 -0
  20. arrayff/potentials/emt/__init__.py +1 -0
  21. arrayff/potentials/emt/_torch.py +38 -0
  22. arrayff/potentials/emt/calculator.py +18 -0
  23. arrayff/potentials/emt/emt.py +353 -0
  24. arrayff/potentials/pairwise/__init__.py +21 -0
  25. arrayff/potentials/pairwise/_pairs.py +36 -0
  26. arrayff/potentials/pairwise/_torch.py +181 -0
  27. arrayff/potentials/pairwise/base.py +346 -0
  28. arrayff/potentials/pairwise/calculator.py +43 -0
  29. arrayff/potentials/pairwise/forms.py +147 -0
  30. arrayff/potentials/pairwise/lj.py +134 -0
  31. arrayff/potentials/pairwise/lj93.py +85 -0
  32. arrayff/potentials/pairwise/lj_kim.py +138 -0
  33. arrayff/potentials/pairwise/morse.py +100 -0
  34. arrayff/potentials/pairwise/params.py +50 -0
  35. arrayff/potentials/placeholders.py +37 -0
  36. arrayff/potentials/registry.py +49 -0
  37. arrayff/py.typed +0 -0
  38. arrayff/utils/__init__.py +50 -0
  39. arrayff/utils/ad.py +272 -0
  40. arrayff/utils/ase.py +68 -0
  41. arrayff/utils/backend.py +101 -0
  42. arrayff/utils/dispatch.py +118 -0
  43. arrayff/utils/exceptions.py +19 -0
  44. arrayff/utils/interp.py +77 -0
  45. arrayff/utils/jit.py +51 -0
  46. arrayff/utils/optional.py +38 -0
  47. arrayff-0.0.1.dist-info/METADATA +142 -0
  48. arrayff-0.0.1.dist-info/RECORD +50 -0
  49. arrayff-0.0.1.dist-info/WHEEL +4 -0
  50. arrayff-0.0.1.dist-info/licenses/src/LICENSE +674 -0
@@ -0,0 +1,346 @@
1
+ """Generic pairwise potential.
2
+
3
+ Only the functional form and the per element parameters are specific to a
4
+ pairwise potential; everything else (neighbour layout, cutoffs, shifting,
5
+ smoothing, forces, virial stress) lives here.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import abc
11
+ from typing import Any
12
+
13
+ import numpy as np
14
+ from ase import Atoms
15
+
16
+ from arrayff.neighbors._table import NeighborEdgeList, NeighborPaddedTable
17
+ from arrayff.potentials.base import Potential
18
+ from arrayff.potentials.pairwise._pairs import pair_distances, pair_vectors
19
+ from arrayff.potentials.pairwise.forms import MIXERS, PairForm
20
+ from arrayff.potentials.pairwise.params import PairParameters
21
+ from arrayff.utils.dispatch import do
22
+
23
+ __all__ = ["PairwisePotential"]
24
+
25
+
26
+ def _switch(r: Any, cutoff: Any) -> Any:
27
+ """Smooth C1 switch that goes to zero at ``cutoff``.
28
+
29
+ Active over the last 10% of the cutoff; identity elsewhere.
30
+ """
31
+ inner = 0.9 * cutoff
32
+ width = cutoff - inner
33
+ x = (r - inner) / width
34
+ x = do("where", r <= inner, 0.0, x)
35
+ x = do("where", r >= cutoff, 1.0, x)
36
+ return 1.0 - (x * x * x * (10.0 + x * (-15.0 + 6.0 * x)))
37
+
38
+
39
+ def _switch_derivative(r: Any, cutoff: Any) -> Any:
40
+ """Derivative of :func:`_switch` with respect to ``r``."""
41
+ inner = 0.9 * cutoff
42
+ width = cutoff - inner
43
+ x = (r - inner) / width
44
+ x = do("where", r <= inner, 0.0, x)
45
+ x = do("where", r >= cutoff, 1.0, x)
46
+ derivative = -30.0 * x * x * (1.0 - x) * (1.0 - x) / width
47
+ derivative = do("where", r <= inner, 0.0, derivative)
48
+ derivative = do("where", r >= cutoff, 0.0, derivative)
49
+ return derivative
50
+
51
+
52
+ class PairwisePotential(Potential):
53
+ """Base class for pair potentials.
54
+
55
+ Parameters
56
+ ----------
57
+ cutoff:
58
+ Global cutoff radius (Angstrom). Ignored per pair when the parameter
59
+ set carries per element cutoffs (OpenKIM universal model).
60
+ shift:
61
+ Shift each pair energy to zero at its cutoff.
62
+ smooth:
63
+ Multiply by a C1 switch over the last 10% of the cutoff.
64
+ layout:
65
+ ``"edges"`` (default) uses :class:`NeighborEdgeList`; ``"padded"``
66
+ uses :class:`NeighborPaddedTable` for static shapes (JAX jit).
67
+ """
68
+
69
+ form: PairForm
70
+
71
+ def __init__(
72
+ self,
73
+ cutoff: float,
74
+ *,
75
+ shift: bool = True,
76
+ smooth: bool = False,
77
+ layout: str = "edges",
78
+ **kwargs: Any,
79
+ ) -> None:
80
+ super().__init__(cutoff, **kwargs)
81
+ if layout not in ("edges", "padded"):
82
+ raise ValueError("layout must be 'edges' or 'padded'")
83
+ self.shift = bool(shift)
84
+ self.smooth = bool(smooth)
85
+ self.layout = layout
86
+ self._analytic_padded: NeighborPaddedTable | None = None
87
+ self._analytic_source: NeighborEdgeList | None = None
88
+
89
+ # -- hooks ---------------------------------------------------------------
90
+ @abc.abstractmethod
91
+ def element_parameters( # type: ignore[override]
92
+ self,
93
+ elements: np.ndarray,
94
+ ) -> PairParameters:
95
+ """Return the per element parameters of this potential."""
96
+
97
+ def _build_table( # type: ignore[override]
98
+ self,
99
+ atoms: Atoms,
100
+ cutoff: float,
101
+ ) -> NeighborPaddedTable | NeighborEdgeList:
102
+ if self.layout == "padded":
103
+ return NeighborPaddedTable.from_ase(
104
+ atoms,
105
+ cutoff,
106
+ max_neighbors=self.max_neighbors,
107
+ backend=self.backend,
108
+ builder=self.builder,
109
+ )
110
+ return NeighborEdgeList.from_ase(
111
+ atoms, cutoff, backend=self.backend, builder=self.builder
112
+ )
113
+
114
+ # -- distance helpers ----------------------------------------------------
115
+ def _edge_distances(
116
+ self, positions: Any, table: NeighborEdgeList, cell: Any
117
+ ):
118
+ source = table.source
119
+ target = table.target
120
+ vectors = positions[target] - positions[source]
121
+ if cell is not None:
122
+ from arrayff.utils.dispatch import dtype_of
123
+
124
+ shift = do("astype", table.shift, dtype_of(positions))
125
+ vectors = vectors + do("einsum", "ek,kl->el", shift, cell)
126
+ r = do("sqrt", do("sum", vectors * vectors, axis=-1))
127
+ return r, vectors
128
+
129
+ # -- energy (AD path) ----------------------------------------------------
130
+ def _pair_terms(
131
+ self,
132
+ r: Any,
133
+ first: Any,
134
+ second: Any,
135
+ mask: Any,
136
+ params: PairParameters,
137
+ ) -> Any:
138
+ form = self.form
139
+ mixed = form.mix(
140
+ {name: params.values[name][first] for name in form.param_names},
141
+ {name: params.values[name][second] for name in form.param_names},
142
+ params.mixing,
143
+ )
144
+ cutoff = self._pair_cutoff(first, second, params)
145
+
146
+ inside = r < cutoff
147
+ if mask is not None:
148
+ inside = do("logical_and", mask, inside)
149
+ r_safe = do("where", inside, r, cutoff)
150
+ energy = form.energy(r_safe, mixed)
151
+ if self.shift:
152
+ energy = energy - form.cutoff_energy(cutoff, mixed)
153
+ if self.smooth:
154
+ energy = energy * _switch(r_safe, cutoff)
155
+ energy = do("where", inside, energy, 0.0)
156
+ return 0.5 * do("sum", energy)
157
+
158
+ def _pair_cutoff(
159
+ self, first: Any, second: Any, params: PairParameters
160
+ ) -> Any:
161
+ if params.cutoff is None:
162
+ return self.cutoff
163
+ rule = params.mixing.get("cutoff", "geometric")
164
+ return MIXERS[rule](params.cutoff[first], params.cutoff[second])
165
+
166
+ def energy_arrays( # type: ignore[override]
167
+ self,
168
+ positions: Any,
169
+ species: Any,
170
+ table: Any,
171
+ cell: Any,
172
+ pbc: Any,
173
+ params: PairParameters,
174
+ ) -> Any:
175
+ if isinstance(table, NeighborEdgeList):
176
+ r, _ = self._edge_distances(positions, table, cell)
177
+ first = species[table.source]
178
+ second = species[table.target]
179
+ mask = None
180
+ else:
181
+ r = pair_distances(positions, table, cell)
182
+ first = species[:, None]
183
+ second = species[table.index]
184
+ mask = table.mask
185
+ return self._pair_terms(r, first, second, mask, params)
186
+
187
+ # -- analytic path -------------------------------------------------------
188
+ def _flatten_params(
189
+ self, params: PairParameters
190
+ ) -> tuple[tuple[Any, ...], Any]:
191
+ names = self.form.param_names
192
+ values = tuple(params.values[name] for name in names)
193
+ has_cutoff = params.cutoff is not None
194
+ if has_cutoff:
195
+ values = values + (params.cutoff,)
196
+
197
+ def rebuild(vals: tuple[Any, ...]) -> PairParameters:
198
+ names_vals = dict(zip(names, vals[: len(names)]))
199
+ cutoff = vals[-1] if has_cutoff else None
200
+ return PairParameters(
201
+ elements=params.elements,
202
+ values=names_vals,
203
+ mixing=params.mixing,
204
+ cutoff=cutoff,
205
+ )
206
+
207
+ return values, rebuild
208
+
209
+ def _analytic_table(
210
+ self,
211
+ table: NeighborPaddedTable | NeighborEdgeList,
212
+ n_atoms: int,
213
+ ) -> NeighborPaddedTable:
214
+ if isinstance(table, NeighborPaddedTable):
215
+ return table
216
+ if self._analytic_source is not table:
217
+ self._analytic_padded = table.to_padded(
218
+ n_atoms, max_neighbors=self.max_neighbors
219
+ )
220
+ self._analytic_source = table
221
+ assert self._analytic_padded is not None
222
+ return self._analytic_padded
223
+
224
+ def _pair_derivative_terms(
225
+ self,
226
+ positions: Any,
227
+ species: Any,
228
+ table: NeighborPaddedTable,
229
+ cell: Any,
230
+ params: PairParameters,
231
+ *,
232
+ want_forces: bool,
233
+ want_stress: bool,
234
+ ) -> tuple[Any, Any, Any, Any]:
235
+ form = self.form
236
+ r = pair_distances(positions, table, cell)
237
+ vectors = pair_vectors(positions, table, cell)
238
+ first = species[:, None]
239
+ second = species[table.index]
240
+ mixed = form.mix(
241
+ {name: params.values[name][first] for name in form.param_names},
242
+ {name: params.values[name][second] for name in form.param_names},
243
+ params.mixing,
244
+ )
245
+ cutoff = self._pair_cutoff(first, second, params)
246
+ inside = do(
247
+ "logical_and",
248
+ table.mask,
249
+ do("logical_and", r < cutoff, r > 0.0),
250
+ )
251
+ r_safe = do("where", inside, r, cutoff)
252
+
253
+ value = form.energy(r_safe, mixed)
254
+ derivative = form.d_energy_dr(r_safe, mixed)
255
+ cutoff_energy = form.cutoff_energy(cutoff, mixed)
256
+ if self.shift:
257
+ value = value - cutoff_energy
258
+ if self.smooth:
259
+ switch = _switch(r_safe, cutoff)
260
+ switch_derivative = _switch_derivative(r_safe, cutoff)
261
+ # ``value`` already contains the shift subtraction (if any).
262
+ derivative = derivative * switch + value * switch_derivative
263
+ value = value * switch
264
+ value = do("where", inside, value, 0.0)
265
+ derivative = do("where", inside, derivative, 0.0)
266
+ energy = 0.5 * do("sum", value)
267
+ coefficient = do("where", inside, derivative / r_safe, 0.0)
268
+
269
+ forces = None
270
+ if want_forces:
271
+ # F_i = -dV/dr * d r / d r_i = +dV/dr * (r_j - r_i) / r
272
+ forces = do(
273
+ "sum", coefficient[:, :, None] * vectors, axis=1
274
+ )
275
+
276
+ stress = None
277
+ if want_stress:
278
+ virial = 0.5 * do(
279
+ "einsum", "nm,nmi,nmj->ij", coefficient, vectors, vectors
280
+ )
281
+ volume = do("abs", do("linalg.det", cell))
282
+ stress = virial / volume
283
+ return energy, forces, stress, inside
284
+
285
+ def evaluate_arrays( # type: ignore[override]
286
+ self,
287
+ positions: Any,
288
+ species: Any,
289
+ table: Any,
290
+ cell: Any,
291
+ pbc: Any,
292
+ params: PairParameters,
293
+ *,
294
+ want: tuple[str, ...] = ("energy", "forces", "stress"),
295
+ ) -> dict[str, Any]:
296
+ table = self._analytic_table(table, int(positions.shape[0]))
297
+ energy, forces, stress, _ = self._pair_derivative_terms(
298
+ positions,
299
+ species,
300
+ table,
301
+ cell,
302
+ params,
303
+ want_forces="forces" in want,
304
+ want_stress="stress" in want,
305
+ )
306
+ out: dict[str, Any] = {}
307
+ if "energy" in want:
308
+ out["energy"] = energy
309
+ if forces is not None:
310
+ out["forces"] = forces
311
+ if stress is not None:
312
+ out["stress"] = stress
313
+ return out
314
+
315
+ def forces_arrays( # type: ignore[override]
316
+ self,
317
+ positions: Any,
318
+ species: Any,
319
+ table: Any,
320
+ cell: Any,
321
+ pbc: Any,
322
+ params: PairParameters,
323
+ ) -> Any:
324
+ return self.evaluate_arrays(
325
+ positions, species, table, cell, pbc, params,
326
+ want=("forces",),
327
+ )["forces"]
328
+
329
+ def stress_arrays( # type: ignore[override]
330
+ self,
331
+ positions: Any,
332
+ species: Any,
333
+ table: Any,
334
+ cell: Any,
335
+ pbc: Any,
336
+ params: PairParameters,
337
+ ) -> Any:
338
+ return self.evaluate_arrays(
339
+ positions, species, table, cell, pbc, params,
340
+ want=("stress",),
341
+ )["stress"]
342
+
343
+ def clear_cache(self) -> None:
344
+ super().clear_cache()
345
+ self._analytic_padded = None
346
+ self._analytic_source = None
@@ -0,0 +1,43 @@
1
+ """ASE calculators for the pairwise potentials."""
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.pairwise.lj import LennardJones
9
+ from arrayff.potentials.pairwise.lj93 import LennardJones93
10
+ from arrayff.potentials.pairwise.morse import Morse
11
+
12
+ __all__ = ["LJ93Calculator", "LJCalculator", "MorseCalculator"]
13
+
14
+
15
+ class LJCalculator(ArrayFFCalculator):
16
+ """Lennard-Jones calculator (OpenKIM universal parameters by default)."""
17
+
18
+ def __init__(self, **kwargs: Any) -> None:
19
+ potential_kwargs, calculator_kwargs = split_kwargs(kwargs, LennardJones) # type: ignore
20
+ super().__init__(LennardJones(**potential_kwargs), **calculator_kwargs)
21
+ self.parameters = potential_kwargs
22
+
23
+
24
+ class MorseCalculator(ArrayFFCalculator):
25
+ """Morse calculator."""
26
+
27
+ def __init__(self, **kwargs: Any) -> None:
28
+ potential_kwargs, calculator_kwargs = split_kwargs(kwargs, Morse) # type: ignore
29
+ super().__init__(Morse(**potential_kwargs), **calculator_kwargs)
30
+
31
+
32
+ class LJ93Calculator(ArrayFFCalculator):
33
+ """Lennard-Jones 9-3 calculator."""
34
+
35
+ def __init__(self, **kwargs: Any) -> None:
36
+ potential_kwargs, calculator_kwargs = split_kwargs(
37
+ kwargs,
38
+ LennardJones93, # type: ignore
39
+ )
40
+ super().__init__(
41
+ LennardJones93(**potential_kwargs),
42
+ **calculator_kwargs,
43
+ )
@@ -0,0 +1,147 @@
1
+ """Pairwise functional forms.
2
+
3
+ A :class:`PairForm` only knows how to turn a distance (and already mixed
4
+ per-element parameters) into an energy. Cutoffs, shifts, smoothing, table
5
+ handling and forces are handled once by
6
+ :class:`arrayff.potentials.pairwise.base.PairwisePotential`.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import abc
12
+ from collections.abc import Callable
13
+ from typing import Any
14
+
15
+ from arrayff.utils.dispatch import do
16
+
17
+ __all__ = [
18
+ "MIXERS",
19
+ "GeneralizedLJ",
20
+ "Morse",
21
+ "PairForm",
22
+ ]
23
+
24
+
25
+ def _arithmetic(a: Any, b: Any) -> Any:
26
+ return 0.5 * (a + b)
27
+
28
+
29
+ def _geometric(a: Any, b: Any) -> Any:
30
+ return do("sqrt", a * b)
31
+
32
+
33
+ #: Mixing rules usable for any parameter name.
34
+ MIXERS: dict[str, Callable[[Any, Any], Any]] = {
35
+ "arithmetic": _arithmetic,
36
+ "geometric": _geometric,
37
+ "none": lambda a, b: a,
38
+ }
39
+
40
+
41
+ class PairForm(abc.ABC):
42
+ """Functional form of a pair interaction."""
43
+
44
+ name: str = "pair"
45
+ param_names: tuple[str, ...] = ()
46
+ default_mixing: dict[str, str] = {}
47
+
48
+ def mix(
49
+ self,
50
+ first: dict[str, Any],
51
+ second: dict[str, Any],
52
+ rules: dict[str, str] | None = None,
53
+ ) -> dict[str, Any]:
54
+ """Combine per-species parameters into per-pair parameters."""
55
+ rules = rules or {}
56
+ mixed: dict[str, Any] = {}
57
+ for name in self.param_names:
58
+ rule = rules.get(name, self.default_mixing.get(name, "arithmetic"))
59
+ try:
60
+ mixer = MIXERS[rule]
61
+ except KeyError:
62
+ raise KeyError(
63
+ f"Unknown mixing rule {rule!r} for parameter {name!r}"
64
+ ) from None
65
+ mixed[name] = mixer(first[name], second[name])
66
+ return mixed
67
+
68
+ @abc.abstractmethod
69
+ def energy(self, r: Any, params: dict[str, Any]) -> Any:
70
+ """Return the uncut pair energy for distances ``r``."""
71
+
72
+ @abc.abstractmethod
73
+ def d_energy_dr(self, r: Any, params: dict[str, Any]) -> Any:
74
+ """Return the analytic derivative ``d energy / d r``."""
75
+
76
+ def cutoff_energy(self, rc: Any, params: dict[str, Any]) -> Any:
77
+ """Energy at the cutoff, used for the shifted convention."""
78
+ return self.energy(rc, params)
79
+
80
+
81
+ class GeneralizedLJ(PairForm):
82
+ r"""Generalized Lennard-Jones ``(m, n)`` form.
83
+
84
+ .. math::
85
+
86
+ V(r) = \varepsilon \left[
87
+ \frac{n}{m-n}\left(\frac{r_0}{r}\right)^m
88
+ - \frac{m}{m-n}\left(\frac{r_0}{r}\right)^n
89
+ \right]
90
+
91
+ with the minimum at ``r0`` and well depth ``depth``. ``(m, n) = (12, 6)``
92
+ is the usual Lennard-Jones potential and ``(9, 3)`` the surface potential.
93
+ """
94
+
95
+ param_names = ("r0", "depth")
96
+ default_mixing = {"r0": "arithmetic", "depth": "geometric"}
97
+
98
+ def __init__(self, m: int = 12, n: int = 6) -> None:
99
+ if not 0 < n < m:
100
+ raise ValueError("GeneralizedLJ requires 0 < n < m")
101
+ self.m = int(m)
102
+ self.n = int(n)
103
+ self.name = f"lj{m}-{n}"
104
+
105
+ def energy(self, r: Any, params: dict[str, Any]) -> Any:
106
+ x = params["r0"] / r
107
+ prefactor = params["depth"]
108
+ return prefactor * (
109
+ (self.n / (self.m - self.n)) * x**self.m
110
+ - (self.m / (self.m - self.n)) * x**self.n
111
+ )
112
+
113
+ def d_energy_dr(self, r: Any, params: dict[str, Any]) -> Any:
114
+ x = params["r0"] / r
115
+ prefactor = params["depth"]
116
+ factor = self.m * self.n / (self.m - self.n)
117
+ return (
118
+ -prefactor
119
+ * (params["r0"] / (r * r))
120
+ * factor
121
+ * (x ** (self.m - 1) - x ** (self.n - 1))
122
+ )
123
+
124
+
125
+ class Morse(PairForm):
126
+ """Morse potential ``depth * (e^{-2a(r-r0)} - 2 e^{-a(r-r0)})``."""
127
+
128
+ name = "morse"
129
+ param_names = ("r0", "depth", "a")
130
+ default_mixing = {
131
+ "r0": "arithmetic",
132
+ "depth": "geometric",
133
+ "a": "arithmetic",
134
+ }
135
+
136
+ def energy(self, r: Any, params: dict[str, Any]) -> Any:
137
+ exponent = do("exp", -params["a"] * (r - params["r0"]))
138
+ return params["depth"] * (exponent * exponent - 2.0 * exponent)
139
+
140
+ def d_energy_dr(self, r: Any, params: dict[str, Any]) -> Any:
141
+ exponent = do("exp", -params["a"] * (r - params["r0"]))
142
+ return (
143
+ 2.0
144
+ * params["a"]
145
+ * params["depth"]
146
+ * (exponent - exponent * exponent)
147
+ )
@@ -0,0 +1,134 @@
1
+ """Lennard-Jones potential, expressed through the generic pairwise layer."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import numpy as np
8
+
9
+ from arrayff.potentials.pairwise.base import PairwisePotential
10
+ from arrayff.potentials.pairwise.forms import GeneralizedLJ
11
+ from arrayff.potentials.pairwise.lj_kim import KIM_LJ_PARAMETERS
12
+ from arrayff.potentials.pairwise.params import PairParameters
13
+ from arrayff.potentials.registry import register_potential
14
+ from arrayff.utils.dispatch import to_backend
15
+
16
+ __all__ = ["KIM_LJ_PARAMETERS", "LennardJones"]
17
+
18
+ #: ``r0 = 2**(1/6) * sigma`` converts the usual ``(sigma, epsilon)``
19
+ #: parameterisation into the ``(r0, depth)`` one used by GeneralizedLJ.
20
+ SIGMA_TO_R0 = 2.0 ** (1.0 / 6.0)
21
+
22
+
23
+ def _per_element(
24
+ value: float | dict[int, float], elements: np.ndarray
25
+ ) -> np.ndarray:
26
+ if isinstance(value, dict):
27
+ missing = [int(z) for z in elements if int(z) not in value]
28
+ if missing:
29
+ raise KeyError(f"Missing Lennard-Jones parameters for Z={missing}")
30
+ return np.array([float(value[int(z)]) for z in elements])
31
+ return np.full(len(elements), float(value))
32
+
33
+
34
+ @register_potential("lj")
35
+ class LennardJones(PairwisePotential):
36
+ """Lennard-Jones 6-12 potential.
37
+
38
+ With no ``sigma``/``epsilon`` the OpenKIM universal shifted parameters are
39
+ used (per element cutoff, geometric mixing). Passing explicit ``sigma`` /
40
+ ``epsilon`` switches to the ASE convention: global cutoff, arithmetic
41
+ sigma mixing, geometric epsilon mixing.
42
+ """
43
+
44
+ name = "lj"
45
+ form = GeneralizedLJ(12, 6)
46
+
47
+ def __init__(
48
+ self,
49
+ sigma: float | dict[int, float] | None = None,
50
+ epsilon: float | dict[int, float] | None = None,
51
+ cutoff: float | None = None,
52
+ *,
53
+ shift: bool | None = None,
54
+ smooth: bool = False,
55
+ layout: str = "edges",
56
+ backend: str = "numpy",
57
+ dtype: Any = None,
58
+ max_neighbors: int | None = None,
59
+ builder: str = "sklearn",
60
+ skin: float = 0.0,
61
+ jit: bool = False,
62
+ method: str = "analytic",
63
+ ) -> None:
64
+ self.kim = sigma is None and epsilon is None
65
+ if self.kim:
66
+ if cutoff is not None:
67
+ raise ValueError(
68
+ "The KIM universal model fixes the cutoff at 4*sigma; "
69
+ "pass explicit sigma/epsilon to use a global cutoff."
70
+ )
71
+ cutoff = max(c for c, _, _ in KIM_LJ_PARAMETERS.values())
72
+ shift = True if shift is None else shift
73
+ # Lorentz-Berthelot: arithmetic r0/cutoff, geometric depth.
74
+ mixing = {
75
+ "r0": "arithmetic",
76
+ "depth": "geometric",
77
+ "cutoff": "arithmetic",
78
+ }
79
+ else:
80
+ if sigma is None or epsilon is None:
81
+ raise ValueError("Pass both sigma and epsilon, or neither.")
82
+ if cutoff is None:
83
+ raise ValueError("An explicit cutoff is required.")
84
+ shift = False if shift is None else shift
85
+ mixing = {"r0": "arithmetic", "depth": "geometric"}
86
+
87
+ super().__init__(
88
+ cutoff,
89
+ shift=shift,
90
+ smooth=smooth,
91
+ layout=layout,
92
+ backend=backend,
93
+ dtype=dtype,
94
+ max_neighbors=max_neighbors,
95
+ builder=builder,
96
+ skin=skin,
97
+ jit=jit,
98
+ method=method,
99
+ )
100
+ self.sigma = sigma
101
+ self.epsilon = epsilon
102
+ self.mixing = mixing
103
+
104
+ def element_parameters(self, elements: np.ndarray) -> PairParameters:
105
+ if self.kim:
106
+ try:
107
+ rows = [KIM_LJ_PARAMETERS[int(z)] for z in elements]
108
+ except KeyError as exc:
109
+ raise KeyError(
110
+ f"No KIM Lennard-Jones parameters for Z={exc.args[0]}"
111
+ ) from None
112
+ cutoff = np.array([row[0] for row in rows])
113
+ epsilon = np.array([row[1] for row in rows])
114
+ sigma = np.array([row[2] for row in rows])
115
+ else:
116
+ sigma = _per_element(self.sigma, elements) # type: ignore[arg-type]
117
+ epsilon = _per_element(self.epsilon, elements) # type: ignore[arg-type]
118
+ cutoff = None
119
+
120
+ if np.any(sigma <= 0.0):
121
+ raise ValueError("sigma must be positive")
122
+ if np.any(epsilon < 0.0):
123
+ raise ValueError("epsilon must be non-negative")
124
+
125
+ values = {"r0": SIGMA_TO_R0 * sigma, "depth": epsilon}
126
+ return PairParameters(
127
+ elements=np.asarray(elements, dtype=np.int64),
128
+ values={
129
+ name: to_backend(value, self.backend)
130
+ for name, value in values.items()
131
+ },
132
+ mixing=self.mixing,
133
+ cutoff=None if cutoff is None else to_backend(cutoff, self.backend),
134
+ )