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
arrayff/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""ArrayFF: force fields on multiple array backends.
|
|
2
|
+
|
|
3
|
+
The package is organised as a thin dispatch layer (:mod:`arrayff.utils`),
|
|
4
|
+
backend agnostic autodiff (:mod:`arrayff.utils.ad`) and numerical kernels that
|
|
5
|
+
never import a concrete array library.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from arrayff import utils
|
|
11
|
+
from arrayff.electrostatics import QEq
|
|
12
|
+
from arrayff.potentials import (
|
|
13
|
+
CompositePotential,
|
|
14
|
+
LennardJones,
|
|
15
|
+
available_potentials,
|
|
16
|
+
get_potential,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
__version__ = "0.0.1"
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"CompositePotential",
|
|
23
|
+
"LennardJones",
|
|
24
|
+
"QEq",
|
|
25
|
+
"__version__",
|
|
26
|
+
"available_potentials",
|
|
27
|
+
"get_potential",
|
|
28
|
+
"utils",
|
|
29
|
+
]
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Electrostatic charge models (QEq implemented; EEM/PQEq planned)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from arrayff.electrostatics.placeholders import EEM, PQEq
|
|
9
|
+
from arrayff.electrostatics.qeq import QEq
|
|
10
|
+
|
|
11
|
+
__all__ = ["EEM", "PQEq", "QEq", "QEqCalculator"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def __getattr__(name: str) -> Any:
|
|
15
|
+
if name == "QEqCalculator":
|
|
16
|
+
module = importlib.import_module("arrayff.electrostatics.calculator")
|
|
17
|
+
value = module.QEqCalculator
|
|
18
|
+
globals()[name] = value
|
|
19
|
+
return value
|
|
20
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""ASE calculator for the QEq charge model."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from arrayff.electrostatics.qeq import QEq
|
|
8
|
+
from arrayff.potentials.calculator import ArrayFFCalculator, split_kwargs
|
|
9
|
+
|
|
10
|
+
__all__ = ["QEqCalculator"]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class QEqCalculator(ArrayFFCalculator):
|
|
14
|
+
"""Charge equilibration calculator (exposes ``charges``)."""
|
|
15
|
+
|
|
16
|
+
def __init__(self, **kwargs: Any) -> None:
|
|
17
|
+
potential_kwargs, calculator_kwargs = split_kwargs(kwargs, QEq)
|
|
18
|
+
super().__init__(QEq(**potential_kwargs), **calculator_kwargs)
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Declared but not yet implemented charge models."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from arrayff.utils.exceptions import ScopeError
|
|
6
|
+
|
|
7
|
+
__all__ = ["EEM", "PQEq"]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class _Placeholder:
|
|
11
|
+
def __init__(self, *args, **kwargs) -> None:
|
|
12
|
+
raise ScopeError(
|
|
13
|
+
f"{type(self).__name__} is declared in the API but not implemented "
|
|
14
|
+
"yet; only QEq is available."
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class EEM(_Placeholder):
|
|
19
|
+
"""Electronegativity equalization method (planned)."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class PQEq(_Placeholder):
|
|
23
|
+
"""Polarizable charge equilibration with core/shell (planned)."""
|
|
@@ -0,0 +1,498 @@
|
|
|
1
|
+
"""Charge equilibration (QEq).
|
|
2
|
+
|
|
3
|
+
Implements the Rappe-Goddard charge equilibration model with the algebraic
|
|
4
|
+
shielded Coulomb kernel ``1 / sqrt(r^2 + lambda^2)`` and the extended matrix
|
|
5
|
+
formulation used by DMFF's QEq solver::
|
|
6
|
+
|
|
7
|
+
[ H 1 ] [q ] [ -chi ]
|
|
8
|
+
[ 1T 0 ] [lam ] = [ Q ]
|
|
9
|
+
|
|
10
|
+
``H_ij = k_e / sqrt(r_ij^2 + lambda^2)`` for ``i != j`` and ``H_ii = J_i``.
|
|
11
|
+
|
|
12
|
+
Forces and stress are available in two charge-response modes (Q12=C):
|
|
13
|
+
|
|
14
|
+
* ``charge_response="frozen"``: Hellmann-Feynman truncation, the charges are
|
|
15
|
+
solved once and detached (the historical behaviour).
|
|
16
|
+
* ``charge_response="relaxed"``: the charges are allowed to respond. The AD
|
|
17
|
+
path differentiates through the linear solve; the analytic path uses the
|
|
18
|
+
envelope theorem (the first-order charge-response term vanishes at the QEq
|
|
19
|
+
minimum), so the closed-form virial is the same as the frozen one to solver
|
|
20
|
+
accuracy. Tests compare both.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
from typing import Any
|
|
26
|
+
|
|
27
|
+
import numpy as np
|
|
28
|
+
from ase import Atoms
|
|
29
|
+
|
|
30
|
+
from arrayff.potentials.base import PotentialBase
|
|
31
|
+
from arrayff.utils import ad
|
|
32
|
+
from arrayff.utils.ase import atoms_to_arrays, species_of
|
|
33
|
+
from arrayff.utils.dispatch import do, to_backend, to_numpy
|
|
34
|
+
from arrayff.utils.exceptions import ScopeError
|
|
35
|
+
|
|
36
|
+
__all__ = ["QEq"]
|
|
37
|
+
|
|
38
|
+
#: Coulomb constant in eV * Angstrom / e^2.
|
|
39
|
+
KE = 14.399645
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class QEq(PotentialBase):
|
|
43
|
+
"""Charge equilibration for electronegativity/hardness parameters.
|
|
44
|
+
|
|
45
|
+
Parameters
|
|
46
|
+
----------
|
|
47
|
+
chi, J:
|
|
48
|
+
Electronegativity (eV) and idempotential (eV/e^2), either a scalar or
|
|
49
|
+
a mapping ``{atomic_number: value}``.
|
|
50
|
+
shielding:
|
|
51
|
+
Shielding length ``lambda`` in Angstrom.
|
|
52
|
+
q_total:
|
|
53
|
+
Total charge constraint.
|
|
54
|
+
charge_response:
|
|
55
|
+
``"frozen"`` (default) or ``"relaxed"``.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
supports_charges = True
|
|
59
|
+
name = "qeq"
|
|
60
|
+
|
|
61
|
+
def __init__(
|
|
62
|
+
self,
|
|
63
|
+
chi: float | dict[int, float],
|
|
64
|
+
J: float | dict[int, float],
|
|
65
|
+
shielding: float = 1.0,
|
|
66
|
+
q_total: float = 0.0,
|
|
67
|
+
*,
|
|
68
|
+
charge_response: str = "frozen",
|
|
69
|
+
backend: str = "numpy",
|
|
70
|
+
dtype: Any = None,
|
|
71
|
+
jit: bool = False,
|
|
72
|
+
method: str = "analytic",
|
|
73
|
+
) -> None:
|
|
74
|
+
super().__init__(
|
|
75
|
+
backend=backend, dtype=dtype, jit=jit, method=method
|
|
76
|
+
)
|
|
77
|
+
if charge_response not in ("frozen", "relaxed"):
|
|
78
|
+
raise ValueError(
|
|
79
|
+
"charge_response must be 'frozen' or 'relaxed', got "
|
|
80
|
+
f"{charge_response!r}"
|
|
81
|
+
)
|
|
82
|
+
self.chi = chi
|
|
83
|
+
self.J = J
|
|
84
|
+
self.shielding = float(shielding)
|
|
85
|
+
self.q_total = float(q_total)
|
|
86
|
+
self.charge_response = charge_response
|
|
87
|
+
self._jit_cache: dict[tuple, Any] = {}
|
|
88
|
+
|
|
89
|
+
def _per_element(self, value: float | dict[int, float], elements):
|
|
90
|
+
if isinstance(value, dict):
|
|
91
|
+
missing = [int(z) for z in elements if int(z) not in value]
|
|
92
|
+
if missing:
|
|
93
|
+
raise KeyError(
|
|
94
|
+
f"Missing QEq parameter for Z={missing}; "
|
|
95
|
+
f"available keys: {sorted(value)}"
|
|
96
|
+
)
|
|
97
|
+
return np.array([float(value[int(z)]) for z in elements])
|
|
98
|
+
return np.full(len(elements), float(value))
|
|
99
|
+
|
|
100
|
+
def _setup(self, atoms: Atoms):
|
|
101
|
+
elements, species_np = species_of(atoms.numbers)
|
|
102
|
+
positions, _, cell, _ = atoms_to_arrays(
|
|
103
|
+
atoms, self.backend, self.dtype
|
|
104
|
+
)
|
|
105
|
+
chi = self._per_element(self.chi, elements)[species_np]
|
|
106
|
+
hardness = self._per_element(self.J, elements)[species_np]
|
|
107
|
+
pbc = np.asarray(atoms.pbc, dtype=bool)
|
|
108
|
+
return (
|
|
109
|
+
positions,
|
|
110
|
+
cell,
|
|
111
|
+
pbc,
|
|
112
|
+
to_backend(chi, self.backend),
|
|
113
|
+
to_backend(hardness, self.backend),
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
def _geometry(self, positions: Any, cell: Any, pbc: np.ndarray):
|
|
117
|
+
vectors = positions[None, :, :] - positions[:, None, :]
|
|
118
|
+
if pbc.any():
|
|
119
|
+
pbc_b = to_backend(pbc.astype(bool), self.backend)
|
|
120
|
+
inverse = do("linalg.inv", cell)
|
|
121
|
+
fractional = do("einsum", "ijk,kl->ijl", vectors, inverse)
|
|
122
|
+
fractional = fractional - do("floor", fractional + 0.5) * pbc_b
|
|
123
|
+
vectors = do("einsum", "ijk,kl->ijl", fractional, cell)
|
|
124
|
+
squared = do("sum", vectors * vectors, axis=-1)
|
|
125
|
+
distance = do("sqrt", squared + self.shielding**2)
|
|
126
|
+
return vectors, distance
|
|
127
|
+
|
|
128
|
+
def _matrix(
|
|
129
|
+
self,
|
|
130
|
+
positions: Any,
|
|
131
|
+
cell: Any,
|
|
132
|
+
pbc: np.ndarray,
|
|
133
|
+
chi: Any,
|
|
134
|
+
hardness: Any,
|
|
135
|
+
):
|
|
136
|
+
n = positions.shape[0]
|
|
137
|
+
vectors, distance = self._geometry(positions, cell, pbc)
|
|
138
|
+
eye = do("eye", n, like=positions)
|
|
139
|
+
kernel = KE / distance * (1.0 - eye)
|
|
140
|
+
matrix = kernel + do("diag", hardness)
|
|
141
|
+
top = do(
|
|
142
|
+
"concatenate",
|
|
143
|
+
[matrix, do("ones", (n, 1), like=positions)],
|
|
144
|
+
axis=1,
|
|
145
|
+
)
|
|
146
|
+
bottom = do(
|
|
147
|
+
"concatenate",
|
|
148
|
+
[
|
|
149
|
+
do("ones", (1, n), like=positions),
|
|
150
|
+
do("zeros", (1, 1), like=positions),
|
|
151
|
+
],
|
|
152
|
+
axis=1,
|
|
153
|
+
)
|
|
154
|
+
augmented = do("concatenate", [top, bottom], axis=0)
|
|
155
|
+
rhs = do(
|
|
156
|
+
"concatenate",
|
|
157
|
+
[
|
|
158
|
+
-chi,
|
|
159
|
+
do(
|
|
160
|
+
"reshape",
|
|
161
|
+
to_backend(self.q_total, self.backend),
|
|
162
|
+
(1,),
|
|
163
|
+
),
|
|
164
|
+
],
|
|
165
|
+
axis=0,
|
|
166
|
+
)
|
|
167
|
+
solution = do("linalg.solve", augmented, rhs)
|
|
168
|
+
return solution[:n], vectors, distance, kernel
|
|
169
|
+
|
|
170
|
+
def _energy_from(
|
|
171
|
+
self,
|
|
172
|
+
charges: Any,
|
|
173
|
+
chi: Any,
|
|
174
|
+
hardness: Any,
|
|
175
|
+
kernel: Any,
|
|
176
|
+
) -> Any:
|
|
177
|
+
quadratic = do(
|
|
178
|
+
"sum", (charges[:, None] * kernel) * charges[None, :]
|
|
179
|
+
)
|
|
180
|
+
onsite = do("sum", hardness * charges * charges)
|
|
181
|
+
return do("sum", chi * charges) + 0.5 * (quadratic + onsite)
|
|
182
|
+
|
|
183
|
+
def _analytic_terms(
|
|
184
|
+
self,
|
|
185
|
+
positions: Any,
|
|
186
|
+
cell: Any,
|
|
187
|
+
pbc: np.ndarray,
|
|
188
|
+
chi: Any,
|
|
189
|
+
hardness: Any,
|
|
190
|
+
charges: Any,
|
|
191
|
+
*,
|
|
192
|
+
want_forces: bool,
|
|
193
|
+
want_stress: bool,
|
|
194
|
+
):
|
|
195
|
+
n = positions.shape[0]
|
|
196
|
+
charges, vectors, distance, kernel = self._matrix(
|
|
197
|
+
positions, cell, pbc, chi, hardness
|
|
198
|
+
)
|
|
199
|
+
energy = self._energy_from(charges, chi, hardness, kernel)
|
|
200
|
+
forces = None
|
|
201
|
+
stress = None
|
|
202
|
+
if want_forces or want_stress:
|
|
203
|
+
radius = do("sqrt", do("sum", vectors * vectors, axis=-1))
|
|
204
|
+
radius_safe = do("where", radius > 0.0, radius, 1.0)
|
|
205
|
+
eye = do("eye", n, like=positions)
|
|
206
|
+
dK_dr = -KE * radius_safe / (distance**3)
|
|
207
|
+
dE_dr = charges[:, None] * charges[None, :] * dK_dr
|
|
208
|
+
coefficient = do("where", eye > 0.0, 0.0, dE_dr / radius_safe)
|
|
209
|
+
if want_forces:
|
|
210
|
+
# F_i = -dE/dr_i = +dE/dr * (r_j - r_i) / r
|
|
211
|
+
forces = do("sum", coefficient[:, :, None] * vectors, axis=1)
|
|
212
|
+
if want_stress:
|
|
213
|
+
virial = 0.5 * do(
|
|
214
|
+
"einsum", "ij,ijk,ijl->kl", coefficient, vectors, vectors
|
|
215
|
+
)
|
|
216
|
+
volume = do("abs", do("linalg.det", cell))
|
|
217
|
+
stress = virial / volume
|
|
218
|
+
return energy, forces, stress
|
|
219
|
+
|
|
220
|
+
def _stress_autodiff(
|
|
221
|
+
self,
|
|
222
|
+
positions: Any,
|
|
223
|
+
cell: Any,
|
|
224
|
+
pbc: np.ndarray,
|
|
225
|
+
chi: Any,
|
|
226
|
+
hardness: Any,
|
|
227
|
+
charges: Any,
|
|
228
|
+
volume: float,
|
|
229
|
+
) -> Any:
|
|
230
|
+
basis = np.zeros((6, 3, 3), dtype=float)
|
|
231
|
+
basis[0, 0, 0] = 1.0
|
|
232
|
+
basis[1, 1, 1] = 1.0
|
|
233
|
+
basis[2, 2, 2] = 1.0
|
|
234
|
+
for index, (a, b) in enumerate(((1, 2), (0, 2), (0, 1))):
|
|
235
|
+
basis[3 + index, a, b] = 1.0
|
|
236
|
+
basis[3 + index, b, a] = 1.0
|
|
237
|
+
basis_b = to_backend(basis, self.backend)
|
|
238
|
+
zero = do("zeros", (6,), like=positions)
|
|
239
|
+
|
|
240
|
+
def energy(strain_params: Any) -> Any:
|
|
241
|
+
strain = do("einsum", "k,kij->ij", strain_params, basis_b)
|
|
242
|
+
eye = do("eye", 3, like=positions)
|
|
243
|
+
deform = eye + strain
|
|
244
|
+
moved = do("matmul", positions, deform)
|
|
245
|
+
deformed_cell = do("matmul", cell, deform)
|
|
246
|
+
if self.charge_response == "relaxed":
|
|
247
|
+
q, _, _, kernel = self._matrix(
|
|
248
|
+
moved, deformed_cell, pbc, chi, hardness
|
|
249
|
+
)
|
|
250
|
+
else:
|
|
251
|
+
q = charges
|
|
252
|
+
_, _, _, kernel = self._matrix(
|
|
253
|
+
moved, deformed_cell, pbc, chi, hardness
|
|
254
|
+
)
|
|
255
|
+
return self._energy_from(q, chi, hardness, kernel)
|
|
256
|
+
|
|
257
|
+
derivative = np.asarray(to_numpy(ad.jacrev(energy)(zero)), dtype=float)
|
|
258
|
+
factors = np.array([1.0, 1.0, 1.0, 0.5, 0.5, 0.5])
|
|
259
|
+
d = derivative * factors
|
|
260
|
+
sigma = np.array(
|
|
261
|
+
[
|
|
262
|
+
[d[0], d[5], d[4]],
|
|
263
|
+
[d[5], d[1], d[3]],
|
|
264
|
+
[d[4], d[3], d[2]],
|
|
265
|
+
]
|
|
266
|
+
)
|
|
267
|
+
return sigma / volume
|
|
268
|
+
|
|
269
|
+
def clear_cache(self) -> None:
|
|
270
|
+
self._jit_cache.clear()
|
|
271
|
+
|
|
272
|
+
def _jit_evaluate(
|
|
273
|
+
self,
|
|
274
|
+
positions: Any,
|
|
275
|
+
cell: Any,
|
|
276
|
+
pbc: np.ndarray,
|
|
277
|
+
chi: Any,
|
|
278
|
+
hardness: Any,
|
|
279
|
+
want: tuple[str, ...],
|
|
280
|
+
) -> dict[str, Any]:
|
|
281
|
+
key = (
|
|
282
|
+
"qeq",
|
|
283
|
+
want,
|
|
284
|
+
tuple(np.shape(positions)),
|
|
285
|
+
tuple(np.shape(cell)),
|
|
286
|
+
tuple(np.shape(chi)),
|
|
287
|
+
tuple(np.shape(hardness)),
|
|
288
|
+
tuple(bool(x) for x in pbc),
|
|
289
|
+
)
|
|
290
|
+
compiled = self._jit_cache.get(key)
|
|
291
|
+
if compiled is None:
|
|
292
|
+
|
|
293
|
+
def kernel(*args: Any) -> tuple[Any, ...]:
|
|
294
|
+
pos, cel, chi_, hardness_ = args
|
|
295
|
+
energy, forces, stress = self._analytic_terms(
|
|
296
|
+
pos,
|
|
297
|
+
cel,
|
|
298
|
+
pbc,
|
|
299
|
+
chi_,
|
|
300
|
+
hardness_,
|
|
301
|
+
None,
|
|
302
|
+
want_forces="forces" in want,
|
|
303
|
+
want_stress="stress" in want,
|
|
304
|
+
)
|
|
305
|
+
values = {"energy": energy}
|
|
306
|
+
if forces is not None:
|
|
307
|
+
values["forces"] = forces
|
|
308
|
+
if stress is not None:
|
|
309
|
+
values["stress"] = stress
|
|
310
|
+
return tuple(values[name] for name in want)
|
|
311
|
+
|
|
312
|
+
from arrayff.utils.jit import autojit
|
|
313
|
+
|
|
314
|
+
compiled = autojit(kernel, backend=self.backend)
|
|
315
|
+
self._jit_cache[key] = compiled
|
|
316
|
+
values = compiled(positions, cell, chi, hardness)
|
|
317
|
+
return dict(zip(want, values))
|
|
318
|
+
|
|
319
|
+
def evaluate(
|
|
320
|
+
self,
|
|
321
|
+
atoms: Atoms,
|
|
322
|
+
*,
|
|
323
|
+
properties: tuple[str, ...] = ("energy",),
|
|
324
|
+
method: str | None = None,
|
|
325
|
+
) -> dict[str, Any]:
|
|
326
|
+
props = tuple(properties)
|
|
327
|
+
unknown = set(props) - {"energy", "forces", "stress", "charges"}
|
|
328
|
+
if unknown:
|
|
329
|
+
raise ScopeError(
|
|
330
|
+
f"Unsupported properties for QEq: {sorted(unknown)}"
|
|
331
|
+
)
|
|
332
|
+
if "stress" in props and atoms.cell.rank != 3:
|
|
333
|
+
raise ValueError("stress requires a fully periodic cell")
|
|
334
|
+
|
|
335
|
+
positions, cell, pbc, chi, hardness = self._setup(atoms)
|
|
336
|
+
charges_now, _, _, _ = self._matrix(
|
|
337
|
+
positions, cell, pbc, chi, hardness
|
|
338
|
+
)
|
|
339
|
+
resolved = self._resolve_method(method)
|
|
340
|
+
volume = float(atoms.get_volume()) if "stress" in props else 1.0
|
|
341
|
+
result: dict[str, Any] = {}
|
|
342
|
+
|
|
343
|
+
if resolved == "analytic":
|
|
344
|
+
numeric_want = tuple(p for p in props if p != "charges")
|
|
345
|
+
if self.jit and numeric_want:
|
|
346
|
+
try:
|
|
347
|
+
result.update(
|
|
348
|
+
self._jit_evaluate(
|
|
349
|
+
positions,
|
|
350
|
+
cell,
|
|
351
|
+
pbc,
|
|
352
|
+
chi,
|
|
353
|
+
hardness,
|
|
354
|
+
numeric_want,
|
|
355
|
+
)
|
|
356
|
+
)
|
|
357
|
+
except Exception as exc: # pragma: no cover - backend dependent
|
|
358
|
+
import warnings
|
|
359
|
+
|
|
360
|
+
warnings.warn(
|
|
361
|
+
"QEq jit failed; falling back to eager: " + str(exc),
|
|
362
|
+
RuntimeWarning,
|
|
363
|
+
stacklevel=2,
|
|
364
|
+
)
|
|
365
|
+
self._jit_cache.clear()
|
|
366
|
+
self.jit = False
|
|
367
|
+
energy, forces, stress = self._analytic_terms(
|
|
368
|
+
positions,
|
|
369
|
+
cell,
|
|
370
|
+
pbc,
|
|
371
|
+
chi,
|
|
372
|
+
hardness,
|
|
373
|
+
charges_now,
|
|
374
|
+
want_forces="forces" in props,
|
|
375
|
+
want_stress="stress" in props,
|
|
376
|
+
)
|
|
377
|
+
if "energy" in props or "forces" in props:
|
|
378
|
+
result["energy"] = energy
|
|
379
|
+
if forces is not None:
|
|
380
|
+
result["forces"] = forces
|
|
381
|
+
if stress is not None:
|
|
382
|
+
result["stress"] = stress
|
|
383
|
+
else:
|
|
384
|
+
energy, forces, stress = self._analytic_terms(
|
|
385
|
+
positions,
|
|
386
|
+
cell,
|
|
387
|
+
pbc,
|
|
388
|
+
chi,
|
|
389
|
+
hardness,
|
|
390
|
+
charges_now,
|
|
391
|
+
want_forces="forces" in props,
|
|
392
|
+
want_stress="stress" in props,
|
|
393
|
+
)
|
|
394
|
+
if "energy" in props or "forces" in props:
|
|
395
|
+
result["energy"] = energy
|
|
396
|
+
if forces is not None:
|
|
397
|
+
result["forces"] = forces
|
|
398
|
+
if stress is not None:
|
|
399
|
+
result["stress"] = stress
|
|
400
|
+
elif resolved == "autodiff":
|
|
401
|
+
if "energy" in props or "forces" in props:
|
|
402
|
+
if self.charge_response == "relaxed":
|
|
403
|
+
|
|
404
|
+
def value(p: Any) -> Any:
|
|
405
|
+
q, _, _, kernel = self._matrix(
|
|
406
|
+
p, cell, pbc, chi, hardness
|
|
407
|
+
)
|
|
408
|
+
return self._energy_from(q, chi, hardness, kernel)
|
|
409
|
+
|
|
410
|
+
else:
|
|
411
|
+
fixed = ad.stop_gradient(charges_now)
|
|
412
|
+
|
|
413
|
+
def value(p: Any) -> Any:
|
|
414
|
+
_, _, _, kernel = self._matrix(
|
|
415
|
+
p, cell, pbc, chi, hardness
|
|
416
|
+
)
|
|
417
|
+
return self._energy_from(fixed, chi, hardness, kernel)
|
|
418
|
+
|
|
419
|
+
if "forces" in props:
|
|
420
|
+
energy, gradient = ad.value_and_grad(value)(positions)
|
|
421
|
+
result["energy"] = energy
|
|
422
|
+
result["forces"] = -gradient
|
|
423
|
+
else:
|
|
424
|
+
result["energy"] = value(positions)
|
|
425
|
+
if "stress" in props:
|
|
426
|
+
result["stress"] = self._stress_autodiff(
|
|
427
|
+
positions,
|
|
428
|
+
cell,
|
|
429
|
+
pbc,
|
|
430
|
+
chi,
|
|
431
|
+
hardness,
|
|
432
|
+
charges_now,
|
|
433
|
+
volume,
|
|
434
|
+
)
|
|
435
|
+
else:
|
|
436
|
+
energy, forces, _ = self._analytic_terms(
|
|
437
|
+
positions,
|
|
438
|
+
cell,
|
|
439
|
+
pbc,
|
|
440
|
+
chi,
|
|
441
|
+
hardness,
|
|
442
|
+
charges_now,
|
|
443
|
+
want_forces="forces" in props,
|
|
444
|
+
want_stress=False,
|
|
445
|
+
)
|
|
446
|
+
if "energy" in props or "forces" in props:
|
|
447
|
+
result["energy"] = energy
|
|
448
|
+
if forces is not None:
|
|
449
|
+
result["forces"] = forces
|
|
450
|
+
if "stress" in props:
|
|
451
|
+
result["stress"] = self._stress_finite_difference(atoms)
|
|
452
|
+
if "charges" in props:
|
|
453
|
+
result["charges"] = to_numpy(charges_now)
|
|
454
|
+
|
|
455
|
+
converted: dict[str, Any] = {}
|
|
456
|
+
for key, value in result.items():
|
|
457
|
+
if key == "energy":
|
|
458
|
+
converted[key] = float(to_numpy(value))
|
|
459
|
+
elif key == "charges":
|
|
460
|
+
converted[key] = np.asarray(to_numpy(value))
|
|
461
|
+
else:
|
|
462
|
+
converted[key] = np.asarray(to_numpy(value))
|
|
463
|
+
return converted
|
|
464
|
+
|
|
465
|
+
def charges(self, atoms: Atoms) -> np.ndarray:
|
|
466
|
+
"""Return the equilibrium charges in units of the elementary charge."""
|
|
467
|
+
positions, cell, pbc, chi, hardness = self._setup(atoms)
|
|
468
|
+
charges, _, _, _ = self._matrix(positions, cell, pbc, chi, hardness)
|
|
469
|
+
return np.asarray(to_numpy(charges))
|
|
470
|
+
|
|
471
|
+
def _stress_finite_difference(self, atoms: Atoms, step: float = 1e-5):
|
|
472
|
+
volume = float(atoms.get_volume())
|
|
473
|
+
positions = np.asarray(atoms.positions, dtype=np.float64)
|
|
474
|
+
cell = np.asarray(atoms.cell.array, dtype=np.float64)
|
|
475
|
+
identity = np.eye(3)
|
|
476
|
+
voigt = ((0, 0), (1, 1), (2, 2), (1, 2), (0, 2), (0, 1))
|
|
477
|
+
derivative = np.zeros(6)
|
|
478
|
+
for index, (a, b) in enumerate(voigt):
|
|
479
|
+
for sign in (1.0, -1.0):
|
|
480
|
+
strain = np.zeros((3, 3))
|
|
481
|
+
strain[a, b] = sign * step
|
|
482
|
+
if a != b:
|
|
483
|
+
strain[b, a] = sign * step
|
|
484
|
+
moved = atoms.copy()
|
|
485
|
+
moved.set_cell(cell @ (identity + strain), scale_atoms=False)
|
|
486
|
+
moved.positions = positions @ (identity + strain)
|
|
487
|
+
energy = self.energy(moved, method="analytic")
|
|
488
|
+
derivative[index] += sign * energy / (2.0 * step)
|
|
489
|
+
if a != b:
|
|
490
|
+
derivative[index] *= 0.5
|
|
491
|
+
sigma = derivative / volume
|
|
492
|
+
return np.array(
|
|
493
|
+
[
|
|
494
|
+
[sigma[0], sigma[5], sigma[4]],
|
|
495
|
+
[sigma[5], sigma[1], sigma[3]],
|
|
496
|
+
[sigma[4], sigma[3], sigma[2]],
|
|
497
|
+
]
|
|
498
|
+
)
|