emle-engine 2.0.0__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.
Potentially problematic release.
This version of emle-engine might be problematic. Click here for more details.
- emle/__init__.py +39 -0
- emle/_analyzer.py +337 -0
- emle/_backends/__init__.py +14 -0
- emle/_backends/_ace.py +141 -0
- emle/_backends/_aimnet2.py +136 -0
- emle/_backends/_backend.py +148 -0
- emle/_backends/_deepmd.py +186 -0
- emle/_backends/_omnip2x.py +349 -0
- emle/_backends/_orca.py +322 -0
- emle/_backends/_sander.py +232 -0
- emle/_backends/_sqm.py +230 -0
- emle/_backends/_xtb.py +126 -0
- emle/_compiler.py +279 -0
- emle/_csrc/ops.cpp +350 -0
- emle/_csrc/ops_cuda.cu +454 -0
- emle/_ops.py +173 -0
- emle/_orca_parser.py +331 -0
- emle/_resources.py +32 -0
- emle/_socket.py +211 -0
- emle/_tarball_to_extXYZ.py +236 -0
- emle/_units.py +16 -0
- emle/_utils.py +57 -0
- emle/calculator.py +1974 -0
- emle/models/__init__.py +13 -0
- emle/models/_ani.py +315 -0
- emle/models/_deepmd.py +410 -0
- emle/models/_emle.py +629 -0
- emle/models/_emle_aev_computer.py +616 -0
- emle/models/_emle_base.py +1063 -0
- emle/models/_mace.py +1368 -0
- emle/models/_patches.py +66 -0
- emle/models/_utils.py +279 -0
- emle/train/__init__.py +8 -0
- emle/train/_extxyz.py +63 -0
- emle/train/_gpr.py +205 -0
- emle/train/_ivm.py +126 -0
- emle/train/_loss.py +357 -0
- emle/train/_trainer.py +709 -0
- emle/train/_utils.py +92 -0
- emle_engine-2.0.0.data/scripts/emle-analyze +175 -0
- emle_engine-2.0.0.data/scripts/emle-compile +162 -0
- emle_engine-2.0.0.data/scripts/emle-server +777 -0
- emle_engine-2.0.0.data/scripts/emle-stop +21 -0
- emle_engine-2.0.0.data/scripts/emle-train +127 -0
- emle_engine-2.0.0.data/scripts/orca +95 -0
- emle_engine-2.0.0.data/scripts/tarball-to-extxyz +6 -0
- emle_engine-2.0.0.dist-info/METADATA +49 -0
- emle_engine-2.0.0.dist-info/RECORD +51 -0
- emle_engine-2.0.0.dist-info/WHEEL +5 -0
- emle_engine-2.0.0.dist-info/licenses/LICENSE +21 -0
- emle_engine-2.0.0.dist-info/top_level.txt +1 -0
emle/models/_patches.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Named tuple definitions and TorchANI compatibility patches."""
|
|
3
|
+
|
|
4
|
+
import torch
|
|
5
|
+
from torch import Tensor
|
|
6
|
+
from typing import NamedTuple, Optional, Tuple
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class SpeciesEnergies(NamedTuple):
|
|
10
|
+
species: Tensor
|
|
11
|
+
energies: Tensor
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class SpeciesEnergiesQBC(NamedTuple):
|
|
15
|
+
species: Tensor
|
|
16
|
+
energies: Tensor
|
|
17
|
+
qbcs: Tensor
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class PatchedANI2x(torch.nn.Module):
|
|
21
|
+
"""
|
|
22
|
+
Thin wrapper around a torchani.models.ANI2x model for TorchANI >= 2.7.9.
|
|
23
|
+
|
|
24
|
+
In TorchANI >= 2.7.9 the ANI2x ``aev_computer`` is buried inside a
|
|
25
|
+
``ModuleDict`` and exposed only via a typed ``@property`` on the base
|
|
26
|
+
class. TorchScript turns that property into an ``__aev_computer_getter``
|
|
27
|
+
method on the compiled class; scripting two ANI2x-containing modules in
|
|
28
|
+
the same process then raises "Can't redefine method: __aev_computer_getter".
|
|
29
|
+
|
|
30
|
+
This wrapper extracts ``aev_computer``, ``neural_networks``,
|
|
31
|
+
``energy_shifter``, and ``species_converter`` as *direct* submodule
|
|
32
|
+
attributes and provides a TorchScript-compatible ``forward`` that calls
|
|
33
|
+
``self.aev_computer`` explicitly. That single path means:
|
|
34
|
+
|
|
35
|
+
* Forward hooks on ``aev_computer`` fire and are visible to the caller.
|
|
36
|
+
* ``ANI2xEMLE`` can read ``self._ani2x.aev_computer._aev`` after calling
|
|
37
|
+
``self._ani2x(...)`` without any separate reference or property access.
|
|
38
|
+
* The raw ``arch.ANI`` class is never compiled by TorchScript.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
def __init__(self, model: torch.nn.Module) -> None:
|
|
42
|
+
super().__init__()
|
|
43
|
+
# Direct attributes — TorchScript sees each as a typed submodule,
|
|
44
|
+
# not through the arch._ANI.aev_computer property.
|
|
45
|
+
self.aev_computer = model.potentials["nnp"].aev_computer # type: ignore[index]
|
|
46
|
+
self._neural_networks = model.potentials["nnp"].neural_networks # type: ignore[index]
|
|
47
|
+
self._energy_shifter = model.energy_shifter # type: ignore[union-attr]
|
|
48
|
+
self._species_converter = model.species_converter # type: ignore[union-attr]
|
|
49
|
+
self._periodic_table_index: bool = bool(
|
|
50
|
+
getattr(model, "periodic_table_index", True)
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
def forward(
|
|
54
|
+
self,
|
|
55
|
+
species_coordinates: Tuple[Tensor, Tensor],
|
|
56
|
+
cell: Optional[Tensor] = None,
|
|
57
|
+
pbc: Optional[Tensor] = None,
|
|
58
|
+
) -> SpeciesEnergies:
|
|
59
|
+
species, coords = species_coordinates
|
|
60
|
+
nop: bool = not self._periodic_table_index
|
|
61
|
+
elem_idxs = self._species_converter(species, nop)
|
|
62
|
+
energies = coords.new_zeros(elem_idxs.shape[0])
|
|
63
|
+
aevs = self.aev_computer(elem_idxs, coords, cell, pbc)
|
|
64
|
+
energies = energies + self._neural_networks(elem_idxs, aevs, False, False)
|
|
65
|
+
energies = energies + self._energy_shifter(elem_idxs, False)
|
|
66
|
+
return SpeciesEnergies(elem_idxs, energies)
|
emle/models/_utils.py
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2023-2026 The EMLE-Engine developers
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""Utility functions."""
|
|
5
|
+
|
|
6
|
+
__author__ = "Lester Hedges"
|
|
7
|
+
__email__ = "lester.hedges@gmail.com"
|
|
8
|
+
|
|
9
|
+
from typing import Optional, Tuple
|
|
10
|
+
|
|
11
|
+
import torch as _torch
|
|
12
|
+
from loguru import logger as _logger
|
|
13
|
+
|
|
14
|
+
_DEPRECATED_ALPHA_MODES = {"species": "fixed", "reference": "flexible"}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _sanitize_alpha_mode(alpha_mode, default="fixed"):
|
|
18
|
+
if alpha_mode is None:
|
|
19
|
+
return default
|
|
20
|
+
if not isinstance(alpha_mode, str):
|
|
21
|
+
raise TypeError("'alpha_mode' must be of type 'str'")
|
|
22
|
+
alpha_mode = alpha_mode.lower().replace(" ", "")
|
|
23
|
+
if alpha_mode in _DEPRECATED_ALPHA_MODES:
|
|
24
|
+
new_mode = _DEPRECATED_ALPHA_MODES[alpha_mode]
|
|
25
|
+
_logger.warning(
|
|
26
|
+
f"alpha_mode='{alpha_mode}' is deprecated; use '{new_mode}' instead."
|
|
27
|
+
)
|
|
28
|
+
alpha_mode = new_mode
|
|
29
|
+
if alpha_mode not in ("fixed", "flexible"):
|
|
30
|
+
raise ValueError("'alpha_mode' must be 'fixed' or 'flexible'")
|
|
31
|
+
return alpha_mode
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _get_neighbor_pairs(
|
|
35
|
+
positions: _torch.Tensor,
|
|
36
|
+
cell: Optional[_torch.Tensor],
|
|
37
|
+
cutoff: float,
|
|
38
|
+
dtype: _torch.dtype,
|
|
39
|
+
device: _torch.device,
|
|
40
|
+
) -> Tuple[_torch.Tensor, _torch.Tensor]:
|
|
41
|
+
"""
|
|
42
|
+
Get the edge indices and shifts for all atom pairs within the cutoff.
|
|
43
|
+
"""
|
|
44
|
+
num_atoms = positions.shape[0]
|
|
45
|
+
pairs = _torch.triu_indices(num_atoms, num_atoms, 1, device=positions.device)
|
|
46
|
+
i = pairs[0]
|
|
47
|
+
j = pairs[1]
|
|
48
|
+
deltas = positions[i] - positions[j]
|
|
49
|
+
wrapped_deltas = _minimum_image(deltas, cell)
|
|
50
|
+
mask = _torch.linalg.norm(wrapped_deltas, dim=1) < cutoff
|
|
51
|
+
i = i[mask]
|
|
52
|
+
j = j[mask]
|
|
53
|
+
|
|
54
|
+
edge_index = _torch.stack((_torch.cat((i, j)), _torch.cat((j, i)))).to(
|
|
55
|
+
_torch.int64
|
|
56
|
+
)
|
|
57
|
+
if cell is not None:
|
|
58
|
+
shifts = deltas[mask] - wrapped_deltas[mask]
|
|
59
|
+
shifts = _torch.vstack((shifts, -shifts))
|
|
60
|
+
else:
|
|
61
|
+
shifts = _torch.zeros((edge_index.shape[1], 3), dtype=dtype, device=device)
|
|
62
|
+
|
|
63
|
+
return edge_index, shifts
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _minimum_image(
|
|
67
|
+
delta: _torch.Tensor, cell: Optional[_torch.Tensor]
|
|
68
|
+
) -> _torch.Tensor:
|
|
69
|
+
"""
|
|
70
|
+
Apply the minimum image convention to a batch of displacement vectors.
|
|
71
|
+
|
|
72
|
+
Parameters
|
|
73
|
+
----------
|
|
74
|
+
|
|
75
|
+
delta: torch.Tensor (BATCH, N, 3)
|
|
76
|
+
Displacement vectors.
|
|
77
|
+
|
|
78
|
+
cell: Optional[torch.Tensor] (BATCH, 3, 3)
|
|
79
|
+
The simulation cell vectors. Rows are the lattice vectors. If None,
|
|
80
|
+
the system is treated as non-periodic and 'delta' is returned
|
|
81
|
+
unchanged.
|
|
82
|
+
|
|
83
|
+
Returns
|
|
84
|
+
-------
|
|
85
|
+
|
|
86
|
+
torch.Tensor (BATCH, N, 3)
|
|
87
|
+
The displacement vectors re-imaged so that each lies within half
|
|
88
|
+
a cell width of the origin along each lattice direction.
|
|
89
|
+
"""
|
|
90
|
+
if cell is None:
|
|
91
|
+
return delta
|
|
92
|
+
frac = _torch.matmul(delta, _torch.linalg.inv(cell))
|
|
93
|
+
frac = frac - _torch.round(frac)
|
|
94
|
+
return _torch.matmul(frac, cell)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _make_whole(xyz_qm: _torch.Tensor, cell: Optional[_torch.Tensor]) -> _torch.Tensor:
|
|
98
|
+
"""
|
|
99
|
+
Unwrap the QM region so that it isn't split across periodic boundaries.
|
|
100
|
+
|
|
101
|
+
Parameters
|
|
102
|
+
----------
|
|
103
|
+
|
|
104
|
+
xyz_qm: torch.Tensor (BATCH, N_QM_ATOMS, 3)
|
|
105
|
+
The (possibly wrapped) positions of the QM atoms in Angstrom.
|
|
106
|
+
|
|
107
|
+
cell: Optional[torch.Tensor] (BATCH, 3, 3)
|
|
108
|
+
The simulation cell vectors in Angstrom. If None, the system is
|
|
109
|
+
treated as non-periodic and 'xyz_qm' is returned unchanged.
|
|
110
|
+
|
|
111
|
+
Returns
|
|
112
|
+
-------
|
|
113
|
+
|
|
114
|
+
torch.Tensor (BATCH, N_QM_ATOMS, 3)
|
|
115
|
+
The unwrapped ("whole") positions of the QM atoms.
|
|
116
|
+
"""
|
|
117
|
+
if cell is None:
|
|
118
|
+
return xyz_qm
|
|
119
|
+
# The first atom in each batch is used as the reference.
|
|
120
|
+
# This follows the approach used by Sire.
|
|
121
|
+
reference = xyz_qm[:, :1, :]
|
|
122
|
+
return reference + _minimum_image(xyz_qm - reference, cell)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _switching_function(
|
|
126
|
+
r: _torch.Tensor, cutoff: float, switch_width: float
|
|
127
|
+
) -> _torch.Tensor:
|
|
128
|
+
"""
|
|
129
|
+
Define a quintic switching function.
|
|
130
|
+
|
|
131
|
+
Parameters
|
|
132
|
+
----------
|
|
133
|
+
|
|
134
|
+
r: torch.Tensor
|
|
135
|
+
Distances in Angstrom.
|
|
136
|
+
|
|
137
|
+
cutoff: float
|
|
138
|
+
The cutoff distance in Angstrom.
|
|
139
|
+
|
|
140
|
+
switch_width: float
|
|
141
|
+
The fraction of the cutoff over which the switching function is
|
|
142
|
+
applied, i.e. the switching region is [(1 - switch_width) * cutoff,
|
|
143
|
+
cutoff].
|
|
144
|
+
|
|
145
|
+
Returns
|
|
146
|
+
-------
|
|
147
|
+
|
|
148
|
+
torch.Tensor
|
|
149
|
+
The switching function values, in the range [0, 1].
|
|
150
|
+
"""
|
|
151
|
+
r_switch = (1.0 - switch_width) * cutoff
|
|
152
|
+
x = _torch.clamp((r - r_switch) / (cutoff - r_switch), min=0.0, max=1.0)
|
|
153
|
+
return 1.0 - x * x * x * (6.0 * x * x - 15.0 * x + 10.0)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _preprocess_coordinates(
|
|
157
|
+
atomic_numbers: _torch.Tensor,
|
|
158
|
+
charges_mm: _torch.Tensor,
|
|
159
|
+
xyz_qm: _torch.Tensor,
|
|
160
|
+
xyz_mm: _torch.Tensor,
|
|
161
|
+
cell: Optional[_torch.Tensor],
|
|
162
|
+
cutoff: float,
|
|
163
|
+
) -> Tuple[_torch.Tensor, _torch.Tensor, _torch.Tensor]:
|
|
164
|
+
"""
|
|
165
|
+
Pre-process the coordinates.
|
|
166
|
+
|
|
167
|
+
This makes whole the QM region, re-images the MM atoms to
|
|
168
|
+
their minimum image position with respect to the QM region centre (both
|
|
169
|
+
skipped if 'cell' is None, i.e. for non-periodic systems), and
|
|
170
|
+
applies a hard distance cutoff, zeroing the charges of MM atoms further
|
|
171
|
+
than 'cutoff' from the nearest QM atom.
|
|
172
|
+
|
|
173
|
+
Parameters
|
|
174
|
+
----------
|
|
175
|
+
|
|
176
|
+
atomic_numbers: torch.Tensor (BATCH, N_QM_ATOMS)
|
|
177
|
+
Atomic numbers of the QM atoms. Padding atoms are indicated using
|
|
178
|
+
a value of zero or less.
|
|
179
|
+
|
|
180
|
+
charges_mm: torch.Tensor (BATCH, N_MM_ATOMS)
|
|
181
|
+
MM point charges in atomic units.
|
|
182
|
+
|
|
183
|
+
xyz_qm: torch.Tensor (BATCH, N_QM_ATOMS, 3)
|
|
184
|
+
Positions of the QM atoms in Angstrom.
|
|
185
|
+
|
|
186
|
+
xyz_mm: torch.Tensor (BATCH, N_MM_ATOMS, 3)
|
|
187
|
+
Positions of the MM atoms in Angstrom.
|
|
188
|
+
|
|
189
|
+
cell: Optional[torch.Tensor] (BATCH, 3, 3)
|
|
190
|
+
The simulation cell vectors in Angstrom. Can be None for
|
|
191
|
+
non-periodic systems, in which case no minimum-image wrapping is
|
|
192
|
+
performed.
|
|
193
|
+
|
|
194
|
+
cutoff: float
|
|
195
|
+
The QM/MM cutoff distance in Angstrom.
|
|
196
|
+
|
|
197
|
+
Returns
|
|
198
|
+
-------
|
|
199
|
+
|
|
200
|
+
xyz_qm: torch.Tensor (BATCH, N_QM_ATOMS, 3)
|
|
201
|
+
The unwrapped positions of the QM atoms.
|
|
202
|
+
|
|
203
|
+
xyz_mm: torch.Tensor (BATCH, N_MM_ATOMS, 3)
|
|
204
|
+
The re-imaged positions of the MM atoms.
|
|
205
|
+
|
|
206
|
+
charges_mm: torch.Tensor (BATCH, N_MM_ATOMS)
|
|
207
|
+
The MM charges, with atoms beyond the cutoff zeroed.
|
|
208
|
+
"""
|
|
209
|
+
# Make the QM region whole and find its centre, ignoring padding atoms.
|
|
210
|
+
xyz_qm = _make_whole(xyz_qm, cell)
|
|
211
|
+
|
|
212
|
+
qm_mask = (atomic_numbers > 0).unsqueeze(-1).to(dtype=xyz_qm.dtype)
|
|
213
|
+
center = (xyz_qm * qm_mask).sum(dim=1, keepdim=True) / qm_mask.sum(
|
|
214
|
+
dim=1, keepdim=True
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
# Re-image the MM atoms with respect to the QM region centre.
|
|
218
|
+
xyz_mm = center + _minimum_image(xyz_mm - center, cell)
|
|
219
|
+
|
|
220
|
+
# Find the distance from each MM atom to the nearest QM atom.
|
|
221
|
+
dist = _torch.cdist(xyz_mm, xyz_qm)
|
|
222
|
+
dist = dist.masked_fill(~(atomic_numbers > 0).unsqueeze(1), float("inf"))
|
|
223
|
+
min_dist = dist.min(dim=2).values
|
|
224
|
+
|
|
225
|
+
# Apply a hard cutoff.
|
|
226
|
+
charges_mm = _torch.where(
|
|
227
|
+
min_dist <= cutoff, charges_mm, _torch.zeros_like(charges_mm)
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
return xyz_qm, xyz_mm, charges_mm
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _apply_switching_function(
|
|
234
|
+
atomic_numbers: _torch.Tensor,
|
|
235
|
+
charges_mm: _torch.Tensor,
|
|
236
|
+
xyz_qm: _torch.Tensor,
|
|
237
|
+
xyz_mm: _torch.Tensor,
|
|
238
|
+
cutoff: float,
|
|
239
|
+
switch_width: float,
|
|
240
|
+
) -> _torch.Tensor:
|
|
241
|
+
"""
|
|
242
|
+
Scale the MM charges using a smooth switching function based on the
|
|
243
|
+
distance to the nearest QM atom.
|
|
244
|
+
|
|
245
|
+
Parameters
|
|
246
|
+
----------
|
|
247
|
+
|
|
248
|
+
atomic_numbers: torch.Tensor (BATCH, N_QM_ATOMS)
|
|
249
|
+
Atomic numbers of the QM atoms. Padding atoms are indicated using
|
|
250
|
+
a value of zero or less.
|
|
251
|
+
|
|
252
|
+
charges_mm: torch.Tensor (BATCH, N_MM_ATOMS)
|
|
253
|
+
MM point charges in atomic units.
|
|
254
|
+
|
|
255
|
+
xyz_qm: torch.Tensor (BATCH, N_QM_ATOMS, 3)
|
|
256
|
+
Positions of the QM atoms in Angstrom.
|
|
257
|
+
|
|
258
|
+
xyz_mm: torch.Tensor (BATCH, N_MM_ATOMS, 3)
|
|
259
|
+
Positions of the MM atoms in Angstrom.
|
|
260
|
+
|
|
261
|
+
cutoff: float
|
|
262
|
+
The QM/MM cutoff distance in Angstrom.
|
|
263
|
+
|
|
264
|
+
switch_width: float
|
|
265
|
+
The fraction of the cutoff over which the switching function is
|
|
266
|
+
applied.
|
|
267
|
+
|
|
268
|
+
Returns
|
|
269
|
+
-------
|
|
270
|
+
|
|
271
|
+
charges_mm: torch.Tensor (BATCH, N_MM_ATOMS)
|
|
272
|
+
The MM charges, scaled by the switching function.
|
|
273
|
+
"""
|
|
274
|
+
# Find the distance from each MM atom to the nearest QM atom.
|
|
275
|
+
dist = _torch.cdist(xyz_mm, xyz_qm)
|
|
276
|
+
dist = dist.masked_fill(~(atomic_numbers > 0).unsqueeze(1), float("inf"))
|
|
277
|
+
min_dist = dist.min(dim=2).values
|
|
278
|
+
|
|
279
|
+
return charges_mm * _switching_function(min_dist, cutoff, switch_width)
|
emle/train/__init__.py
ADDED
emle/train/_extxyz.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2023-2026 The EMLE-Engine developers
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""Conversion of extXYZ frames (ASE Atoms) to EMLE training data."""
|
|
5
|
+
|
|
6
|
+
__all__ = ["atoms_to_train_data"]
|
|
7
|
+
|
|
8
|
+
import numpy as _np
|
|
9
|
+
|
|
10
|
+
_ARRAY_KEYS = ("s", "q_core", "q_val")
|
|
11
|
+
_INFO_KEYS = ("alpha",)
|
|
12
|
+
_MAX_CHARGE_RESIDUAL = 0.1
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def atoms_to_train_data(atoms_list):
|
|
16
|
+
"""
|
|
17
|
+
Extract EMLE training data from a list of ASE Atoms.
|
|
18
|
+
|
|
19
|
+
Parameters
|
|
20
|
+
----------
|
|
21
|
+
|
|
22
|
+
atoms_list: List[ase.Atoms]
|
|
23
|
+
Frames with per-atom arrays "s" (Bohr), "q_core", "q_val" (e) and
|
|
24
|
+
"alpha" (3x3, Bohr^3) in info. Optional info "total_charge" (e);
|
|
25
|
+
if absent, the rounded sum of the charges is used. q_val is shifted
|
|
26
|
+
evenly so that the charges sum to the total charge.
|
|
27
|
+
|
|
28
|
+
Returns
|
|
29
|
+
-------
|
|
30
|
+
|
|
31
|
+
dict
|
|
32
|
+
Keyword arguments z, xyz, s, q_core, q_val, alpha for
|
|
33
|
+
EMLETrainer.train.
|
|
34
|
+
"""
|
|
35
|
+
data = {key: [] for key in ("z", "xyz", "s", "q_core", "q_val", "alpha")}
|
|
36
|
+
|
|
37
|
+
for i, atoms in enumerate(atoms_list):
|
|
38
|
+
for key in _ARRAY_KEYS:
|
|
39
|
+
if key not in atoms.arrays:
|
|
40
|
+
raise ValueError(f"Frame {i}: missing per-atom array '{key}'")
|
|
41
|
+
for key in _INFO_KEYS:
|
|
42
|
+
if key not in atoms.info:
|
|
43
|
+
raise ValueError(f"Frame {i}: missing info key '{key}'")
|
|
44
|
+
|
|
45
|
+
q_core = atoms.arrays["q_core"]
|
|
46
|
+
q_val = atoms.arrays["q_val"]
|
|
47
|
+
q_sum = _np.sum(q_core + q_val)
|
|
48
|
+
total_charge = atoms.info.get("total_charge", _np.round(q_sum))
|
|
49
|
+
delta = total_charge - q_sum
|
|
50
|
+
if abs(delta) >= _MAX_CHARGE_RESIDUAL:
|
|
51
|
+
raise ValueError(
|
|
52
|
+
f"Frame {i}: charges sum to {q_sum}, total charge is {total_charge}"
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
data["z"].append(atoms.numbers)
|
|
56
|
+
data["xyz"].append(atoms.positions)
|
|
57
|
+
data["s"].append(atoms.arrays["s"])
|
|
58
|
+
data["q_core"].append(q_core)
|
|
59
|
+
data["q_val"].append(q_val + delta / len(atoms))
|
|
60
|
+
data["alpha"].append(atoms.info["alpha"])
|
|
61
|
+
|
|
62
|
+
data["alpha"] = _np.array(data["alpha"])
|
|
63
|
+
return data
|
emle/train/_gpr.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2023-2026 The EMLE-Engine developers
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""Gaussian Process Regression (GPR) for EMLE training."""
|
|
5
|
+
|
|
6
|
+
import torch as _torch
|
|
7
|
+
|
|
8
|
+
from ._utils import pad_to_max as _pad_to_max
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class GPR:
|
|
12
|
+
"""
|
|
13
|
+
Gaussian Process Regression (GPR) for EMLE training.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
@staticmethod
|
|
17
|
+
def _aev_kernel(a, b):
|
|
18
|
+
"""
|
|
19
|
+
Computes the kernel between two sets of AEV features.
|
|
20
|
+
|
|
21
|
+
Parameters
|
|
22
|
+
----------
|
|
23
|
+
|
|
24
|
+
a: torch.Tensor(N, AEV_DIM)
|
|
25
|
+
First set of AEV features.
|
|
26
|
+
|
|
27
|
+
b: torch.Tensor(M, AEV_DIM)
|
|
28
|
+
Second set of AEV features.
|
|
29
|
+
|
|
30
|
+
Returns
|
|
31
|
+
-------
|
|
32
|
+
|
|
33
|
+
torch.Tensor(N, M)
|
|
34
|
+
Kernel matrix.
|
|
35
|
+
"""
|
|
36
|
+
return (a @ b.T) ** 2
|
|
37
|
+
|
|
38
|
+
@staticmethod
|
|
39
|
+
def _get_K_mols_ref(K_ivm_allz, zid_mols):
|
|
40
|
+
"""
|
|
41
|
+
Get the molecule-reference kernel matrix.
|
|
42
|
+
|
|
43
|
+
Parameters
|
|
44
|
+
----------
|
|
45
|
+
|
|
46
|
+
K_ivm_allz: list of torch.Tensor(N_SPECIES, N_Z, N_IVMZ)
|
|
47
|
+
List of molecule-reference kernel matrices.
|
|
48
|
+
|
|
49
|
+
zid_mols: torch.Tensor(N_MOLS, MAX_N_ATOMS)
|
|
50
|
+
Species IDs for all molecules.
|
|
51
|
+
|
|
52
|
+
Returns
|
|
53
|
+
-------
|
|
54
|
+
|
|
55
|
+
result: torch.Tensor(N_MOLS, MAX_N_ATOMS, MAX_N_IVMZ)
|
|
56
|
+
Molecule-reference kernel matrix.
|
|
57
|
+
"""
|
|
58
|
+
ivm_max = max([K_ivm_z.shape[1] for K_ivm_z in K_ivm_allz])
|
|
59
|
+
result = _torch.zeros(
|
|
60
|
+
(*zid_mols.shape, ivm_max),
|
|
61
|
+
dtype=K_ivm_allz[0].dtype,
|
|
62
|
+
device=K_ivm_allz[0].device,
|
|
63
|
+
)
|
|
64
|
+
for i, K_ivm_z in enumerate(K_ivm_allz):
|
|
65
|
+
pad = (0, ivm_max - K_ivm_z.shape[1])
|
|
66
|
+
result[zid_mols == i] = _torch.nn.functional.pad(K_ivm_z, pad)
|
|
67
|
+
|
|
68
|
+
return result
|
|
69
|
+
|
|
70
|
+
@staticmethod
|
|
71
|
+
def _fit_sparse_gpr(y, K_sample_ref, K_ref_ref, sigma):
|
|
72
|
+
"""
|
|
73
|
+
Fits GPR reference values to given samples
|
|
74
|
+
|
|
75
|
+
y: torch.Tensor (N_SAMPLES,)
|
|
76
|
+
Sample values.
|
|
77
|
+
|
|
78
|
+
K_sample_ref: torch.Tensor (N_SAMPLES, MAX_N_REF)
|
|
79
|
+
Sample-reference kernel matrix.
|
|
80
|
+
|
|
81
|
+
K_ref_ref: torch.Tensor (MAX_N_REF, MAX_N_REF)
|
|
82
|
+
Reference-reference kernel matrix.
|
|
83
|
+
|
|
84
|
+
sigma: float
|
|
85
|
+
GPR sigma value.
|
|
86
|
+
|
|
87
|
+
Returns
|
|
88
|
+
-------
|
|
89
|
+
|
|
90
|
+
torch.Tensor (MAX_N_REF,)
|
|
91
|
+
Fitted reference values.
|
|
92
|
+
"""
|
|
93
|
+
K_ref_ref_sigma = K_ref_ref + sigma**2 * _torch.eye(
|
|
94
|
+
len(K_ref_ref), device=K_ref_ref.device, dtype=K_ref_ref.dtype
|
|
95
|
+
)
|
|
96
|
+
A = _torch.linalg.inv(K_ref_ref_sigma) @ K_sample_ref.T
|
|
97
|
+
B = _torch.linalg.pinv(A.T)
|
|
98
|
+
|
|
99
|
+
By = B @ y
|
|
100
|
+
B1 = _torch.sum(B, dim=1)
|
|
101
|
+
y0 = _torch.sum(By) / _torch.sum(B1)
|
|
102
|
+
y_ref = By - y0 * B1
|
|
103
|
+
|
|
104
|
+
return y_ref + y0
|
|
105
|
+
|
|
106
|
+
@staticmethod
|
|
107
|
+
def get_gpr_kernels(aev_mols, zid_mols, aev_ivm_allz, n_ref):
|
|
108
|
+
"""
|
|
109
|
+
Get kernels for performing GPR.
|
|
110
|
+
|
|
111
|
+
Parameters
|
|
112
|
+
----------
|
|
113
|
+
|
|
114
|
+
aev_mols : torch.Tensor(N_BATCH, MAX_N_ATOMS, AEV_DIM)
|
|
115
|
+
AEV features for all molecules.
|
|
116
|
+
|
|
117
|
+
zid_mols : torch.Tensor(N_BATCH, MAX_N_ATOMS)
|
|
118
|
+
Species IDs for all molecules.
|
|
119
|
+
|
|
120
|
+
aev_ivm_allz : torch.Tensor(N_SPECIES, MAX_N_REF, AEV_DIM)
|
|
121
|
+
AEV features for all reference atoms.
|
|
122
|
+
|
|
123
|
+
species : torch.Tensor(N_SPECIES)
|
|
124
|
+
Unique species in the dataset.
|
|
125
|
+
|
|
126
|
+
n_ref: (N_SPECIES,)
|
|
127
|
+
Number of IVM references for each specie
|
|
128
|
+
|
|
129
|
+
Returns
|
|
130
|
+
-------
|
|
131
|
+
|
|
132
|
+
K_ref_ref_padded: torch.Tensor(N_SPECIES, MAX_N_REF, MAX_N_REF)
|
|
133
|
+
Reference-reference kernel matrices.
|
|
134
|
+
|
|
135
|
+
K_mols_ref: torch.Tensor(N_BATCH, MAX_N_ATOMS, MAX_N_REF)
|
|
136
|
+
Molecules-reference kernel matrices.
|
|
137
|
+
"""
|
|
138
|
+
n_species = len(aev_ivm_allz)
|
|
139
|
+
aev_allz = [aev_mols[zid_mols == i] for i in range(n_species)]
|
|
140
|
+
|
|
141
|
+
K_ref_ref = [
|
|
142
|
+
GPR._aev_kernel(aev_ivm_z[:n_ref_z, :], aev_ivm_z[:n_ref_z, :])
|
|
143
|
+
for aev_ivm_z, n_ref_z in zip(aev_ivm_allz, n_ref)
|
|
144
|
+
]
|
|
145
|
+
|
|
146
|
+
K_ref_ref_padded = _pad_to_max(K_ref_ref)
|
|
147
|
+
|
|
148
|
+
K_ivm_allz = [
|
|
149
|
+
GPR._aev_kernel(aev_z, aev_ivm_z[:n_ref_z, :])
|
|
150
|
+
for aev_z, aev_ivm_z, n_ref_z in zip(aev_allz, aev_ivm_allz, n_ref)
|
|
151
|
+
]
|
|
152
|
+
K_mols_ref = GPR._get_K_mols_ref(K_ivm_allz, zid_mols)
|
|
153
|
+
|
|
154
|
+
return K_ref_ref_padded, K_mols_ref
|
|
155
|
+
|
|
156
|
+
@staticmethod
|
|
157
|
+
def fit_atomic_sparse_gpr(values, K_mols_ref, K_ref_ref, zid, sigma, n_ref):
|
|
158
|
+
"""
|
|
159
|
+
Fits GPR atomic values to given samples.
|
|
160
|
+
|
|
161
|
+
Parameters
|
|
162
|
+
----------
|
|
163
|
+
|
|
164
|
+
values: torch.Tensor(N_BATCH, MAX_N_ATOMS)
|
|
165
|
+
Atomic properties to train on.
|
|
166
|
+
|
|
167
|
+
K_mols_ref: torch.Tensor(N_BATCH, MAX_N_ATOMS, MAX_N_REF)
|
|
168
|
+
Molecules-reference kernel matrices.
|
|
169
|
+
|
|
170
|
+
K_ref_ref: torch.Tensor(N_SPECIES, MAX_N_REF, MAX_N_REF)
|
|
171
|
+
Reference-reference kernel matrices.
|
|
172
|
+
|
|
173
|
+
zid: torch.Tensor(N_BATCH, MAX_N_ATOMS)
|
|
174
|
+
Species IDs.
|
|
175
|
+
|
|
176
|
+
sigma: float
|
|
177
|
+
GPR sigma value.
|
|
178
|
+
|
|
179
|
+
n_ref: torch.Tensor (N_SPECIES,)
|
|
180
|
+
Number of IVM references for each specie
|
|
181
|
+
|
|
182
|
+
Returns
|
|
183
|
+
-------
|
|
184
|
+
|
|
185
|
+
result: torch.Tensor(N_SPECIES, MAX_N_REF)
|
|
186
|
+
Fitted atomic values.
|
|
187
|
+
|
|
188
|
+
Notes
|
|
189
|
+
-----
|
|
190
|
+
|
|
191
|
+
Really only used for s, the rest are predicted by learning.
|
|
192
|
+
"""
|
|
193
|
+
|
|
194
|
+
n_species, max_n_ref = K_ref_ref.shape[:2]
|
|
195
|
+
|
|
196
|
+
result = _torch.zeros((n_species, max_n_ref), dtype=values.dtype)
|
|
197
|
+
for i, n_ref_z in enumerate(n_ref):
|
|
198
|
+
z_mask = zid == i
|
|
199
|
+
result[i, :n_ref_z] = GPR._fit_sparse_gpr(
|
|
200
|
+
values[z_mask],
|
|
201
|
+
K_mols_ref[z_mask][:, :n_ref_z],
|
|
202
|
+
K_ref_ref[i, :n_ref_z, :n_ref_z],
|
|
203
|
+
sigma,
|
|
204
|
+
)
|
|
205
|
+
return result
|