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
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2023-2026 The EMLE-Engine developers
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""In-vacuo backend base class."""
|
|
5
|
+
|
|
6
|
+
__all__ = ["Backend"]
|
|
7
|
+
|
|
8
|
+
import inspect as _inspect
|
|
9
|
+
|
|
10
|
+
import numpy as _np
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _check_supported(backend, qm_charge, mult, state):
|
|
14
|
+
"""
|
|
15
|
+
Raise a ValueError if the QM charge, spin multiplicity or electronic
|
|
16
|
+
state, which can be per frame, is not supported by the backend: any
|
|
17
|
+
object with the 'charges', 'mults' and 'states' attributes described in
|
|
18
|
+
Backend.
|
|
19
|
+
"""
|
|
20
|
+
for label, option, supported, value in (
|
|
21
|
+
("charge", "model_charges", backend.charges, qm_charge),
|
|
22
|
+
("spin multiplicity", "model_mults", backend.mults, mult),
|
|
23
|
+
("electronic state", "model_states", backend.states, state),
|
|
24
|
+
):
|
|
25
|
+
values = set(_np.atleast_1d(value).tolist())
|
|
26
|
+
if supported is not None and not values <= set(supported):
|
|
27
|
+
raise ValueError(
|
|
28
|
+
f"unsupported QM {label} {value}, supported: {supported}. "
|
|
29
|
+
f"If the model supports it, declare it with '{option}' "
|
|
30
|
+
f"('--{option.replace('_', '-')}' or 'EMLE_{option.upper()}' "
|
|
31
|
+
"for emle-server)"
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class Backend:
|
|
36
|
+
"""
|
|
37
|
+
Base class for in-vacuo backends.
|
|
38
|
+
|
|
39
|
+
This class should not be instantiated directly, but should be subclassed
|
|
40
|
+
by specific backends.
|
|
41
|
+
|
|
42
|
+
The 'charges', 'mults' and 'states' attributes hold the QM charges, spin
|
|
43
|
+
multiplicities and electronic states (0 is the ground state) that the
|
|
44
|
+
model supports, as a tuple, or None for any value. The default is a
|
|
45
|
+
neutral singlet in the ground state. Of the 'qm_charge', 'mult' and
|
|
46
|
+
'state' arguments, those that 'calculate' takes are passed to it, or all
|
|
47
|
+
of them if it takes '**kwargs'.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
def __init__(self, charges=(0,), mults=(1,), states=(0,)):
|
|
51
|
+
"""
|
|
52
|
+
Constructor.
|
|
53
|
+
|
|
54
|
+
Parameters
|
|
55
|
+
----------
|
|
56
|
+
|
|
57
|
+
charges: tuple of int
|
|
58
|
+
The supported QM charges, or None for any value.
|
|
59
|
+
|
|
60
|
+
mults: tuple of int
|
|
61
|
+
The supported spin multiplicities, or None for any value.
|
|
62
|
+
|
|
63
|
+
states: tuple of int
|
|
64
|
+
The supported electronic states, or None for any value.
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
# Don't allow user to create an instance of the base class.
|
|
68
|
+
if type(self) is Backend:
|
|
69
|
+
raise NotImplementedError(
|
|
70
|
+
"'Backend' is an abstract class and should not be instantiated directly"
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
self.charges = charges
|
|
74
|
+
self.mults = mults
|
|
75
|
+
self.states = states
|
|
76
|
+
|
|
77
|
+
def __call__(
|
|
78
|
+
self, atomic_numbers, xyz, forces=True, qm_charge=0, mult=1, state=0, **kwargs
|
|
79
|
+
):
|
|
80
|
+
"""
|
|
81
|
+
Compute the energy and forces.
|
|
82
|
+
|
|
83
|
+
Parameters
|
|
84
|
+
----------
|
|
85
|
+
|
|
86
|
+
atomic_numbers: numpy.ndarray, (N_BATCH, N_QM_ATOMS,)
|
|
87
|
+
The atomic numbers of the atoms in the QM region.
|
|
88
|
+
|
|
89
|
+
xyz: numpy.ndarray, (N_BATCH, N_QM_ATOMS, 3)
|
|
90
|
+
The coordinates of the atoms in the QM region in Angstrom.
|
|
91
|
+
|
|
92
|
+
forces: bool
|
|
93
|
+
Whether to calculate and return forces.
|
|
94
|
+
|
|
95
|
+
qm_charge: int, numpy.ndarray (N_BATCH,)
|
|
96
|
+
The charge of the QM region.
|
|
97
|
+
|
|
98
|
+
mult: int, numpy.ndarray (N_BATCH,)
|
|
99
|
+
The spin multiplicity of the QM region.
|
|
100
|
+
|
|
101
|
+
state: int, numpy.ndarray (N_BATCH,)
|
|
102
|
+
The electronic state index (0 is the ground state).
|
|
103
|
+
|
|
104
|
+
kwargs: dict
|
|
105
|
+
Other keyword arguments, passed to 'calculate'.
|
|
106
|
+
|
|
107
|
+
Returns
|
|
108
|
+
-------
|
|
109
|
+
|
|
110
|
+
energy: float
|
|
111
|
+
The in-vacuo energy in Eh.
|
|
112
|
+
|
|
113
|
+
forces: numpy.ndarray
|
|
114
|
+
The in-vacuo forces in Eh/Bohr.
|
|
115
|
+
"""
|
|
116
|
+
_check_supported(self, qm_charge, mult, state)
|
|
117
|
+
inputs = {"qm_charge": qm_charge, "mult": mult, "state": state}
|
|
118
|
+
params = _inspect.signature(self.calculate).parameters
|
|
119
|
+
if not any(p.kind is p.VAR_KEYWORD for p in params.values()):
|
|
120
|
+
inputs = {k: v for k, v in inputs.items() if k in params}
|
|
121
|
+
return self.calculate(atomic_numbers, xyz, forces, **inputs, **kwargs)
|
|
122
|
+
|
|
123
|
+
def calculate(self, atomic_numbers, xyz, forces=True):
|
|
124
|
+
"""
|
|
125
|
+
Compute the energy and forces.
|
|
126
|
+
|
|
127
|
+
Parameters
|
|
128
|
+
----------
|
|
129
|
+
|
|
130
|
+
atomic_numbers: numpy.ndarray, (N_BATCH, N_QM_ATOMS,)
|
|
131
|
+
The atomic numbers of the atoms in the QM region.
|
|
132
|
+
|
|
133
|
+
xyz: numpy.ndarray, (N_BATCH, N_QM_ATOMS, 3)
|
|
134
|
+
The coordinates of the atoms in the QM region in Angstrom.
|
|
135
|
+
|
|
136
|
+
forces: bool
|
|
137
|
+
Whether to calculate and return forces.
|
|
138
|
+
|
|
139
|
+
Returns
|
|
140
|
+
-------
|
|
141
|
+
|
|
142
|
+
energy: float
|
|
143
|
+
The in-vacuo energy in Eh.
|
|
144
|
+
|
|
145
|
+
forces: numpy.ndarray
|
|
146
|
+
The in-vacuo forces in Eh/Bohr.
|
|
147
|
+
"""
|
|
148
|
+
raise NotImplementedError
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2023-2026 The EMLE-Engine developers
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""DeePMD in-vacuo backend implementation."""
|
|
5
|
+
|
|
6
|
+
__all__ = ["DeePMD"]
|
|
7
|
+
|
|
8
|
+
try:
|
|
9
|
+
from deepmd.infer import DeepPot as _DeepPot
|
|
10
|
+
except ImportError:
|
|
11
|
+
_DeepPot = None
|
|
12
|
+
|
|
13
|
+
import ase as _ase
|
|
14
|
+
import numpy as _np
|
|
15
|
+
import os as _os
|
|
16
|
+
|
|
17
|
+
from .._units import _EV_TO_HARTREE, _BOHR_TO_ANGSTROM
|
|
18
|
+
|
|
19
|
+
from ._backend import Backend as _Backend
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class DeePMD(_Backend):
|
|
23
|
+
"""
|
|
24
|
+
DeePMD in-vacuo backend implementation.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(self, model, deviation=None, deviation_threshold=None):
|
|
28
|
+
super().__init__()
|
|
29
|
+
|
|
30
|
+
if _DeepPot is None:
|
|
31
|
+
raise ImportError(
|
|
32
|
+
"deepmd-kit does not appear to be installed, but is "
|
|
33
|
+
"required to use the DeePMD backend."
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
# We support a str, or list/tuple of strings.
|
|
37
|
+
if not isinstance(model, (str, list, tuple)):
|
|
38
|
+
raise TypeError("'model' must be of type 'str', or a list of 'str' types")
|
|
39
|
+
else:
|
|
40
|
+
# Make sure all values are strings.
|
|
41
|
+
if isinstance(model, (list, tuple)):
|
|
42
|
+
for m in model:
|
|
43
|
+
if not isinstance(m, str):
|
|
44
|
+
raise TypeError(
|
|
45
|
+
"'model' must be of type 'str', or a list of 'str' types"
|
|
46
|
+
)
|
|
47
|
+
# Convert to a list.
|
|
48
|
+
else:
|
|
49
|
+
model = [model]
|
|
50
|
+
|
|
51
|
+
# Make sure all of the model files exist.
|
|
52
|
+
for m in model:
|
|
53
|
+
if not _os.path.isfile(m):
|
|
54
|
+
raise IOError(f"Unable to locate DeePMD model file: '{m}'")
|
|
55
|
+
|
|
56
|
+
# Validate the deviation file.
|
|
57
|
+
if deviation is not None:
|
|
58
|
+
if not isinstance(deviation, str):
|
|
59
|
+
raise TypeError("'deviation' must be of type 'str'")
|
|
60
|
+
|
|
61
|
+
self._deviation = deviation
|
|
62
|
+
|
|
63
|
+
if deviation_threshold is not None:
|
|
64
|
+
try:
|
|
65
|
+
deviation_threshold = float(deviation_threshold)
|
|
66
|
+
except:
|
|
67
|
+
raise TypeError("'deviation_threshold' must be of type 'float'")
|
|
68
|
+
|
|
69
|
+
self._deviation_threshold = deviation_threshold
|
|
70
|
+
else:
|
|
71
|
+
self._deviation = None
|
|
72
|
+
self._deviation_threshold = None
|
|
73
|
+
|
|
74
|
+
# Store the list of model files, removing any duplicates.
|
|
75
|
+
self._model = list(set(model))
|
|
76
|
+
if len(self._model) == 1 and deviation:
|
|
77
|
+
raise IOError(
|
|
78
|
+
"More that one DeePMD model needed to calculate the deviation!"
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
# Initialise DeePMD backend attributes.
|
|
82
|
+
try:
|
|
83
|
+
self._potential = [_DeepPot(m) for m in self._model]
|
|
84
|
+
self._z_map = []
|
|
85
|
+
for dp in self._potential:
|
|
86
|
+
self._z_map.append(
|
|
87
|
+
{
|
|
88
|
+
element: index
|
|
89
|
+
for index, element in enumerate(dp.get_type_map())
|
|
90
|
+
}
|
|
91
|
+
)
|
|
92
|
+
except Exception as e:
|
|
93
|
+
raise RuntimeError(f"Unable to create the DeePMD potentials: {e}") from e
|
|
94
|
+
|
|
95
|
+
self._max_f_std = None
|
|
96
|
+
|
|
97
|
+
def calculate(self, atomic_numbers, xyz, forces=True, box=None):
|
|
98
|
+
"""
|
|
99
|
+
Compute the energy and forces.
|
|
100
|
+
|
|
101
|
+
Parameters
|
|
102
|
+
----------
|
|
103
|
+
|
|
104
|
+
atomic_numbers: numpy.ndarray, (N_BATCH, N_QM_ATOMS,)
|
|
105
|
+
The atomic numbers of the atoms in the QM region.
|
|
106
|
+
|
|
107
|
+
xyz: numpy.ndarray, (N_BATCH, N_QM_ATOMS, 3)
|
|
108
|
+
The coordinates of the atoms in the QM region in Angstrom.
|
|
109
|
+
|
|
110
|
+
forces: bool
|
|
111
|
+
Whether to calculate and return forces.
|
|
112
|
+
|
|
113
|
+
box: List, Tuple, numpy.ndarray, (3,)
|
|
114
|
+
PBC box. Only orthorhombic boxes are supported.
|
|
115
|
+
|
|
116
|
+
Returns
|
|
117
|
+
-------
|
|
118
|
+
|
|
119
|
+
energy: float
|
|
120
|
+
The in-vacuo energy in Eh.
|
|
121
|
+
|
|
122
|
+
forces: numpy.ndarray
|
|
123
|
+
The in-vacuo forces in Eh/Bohr.
|
|
124
|
+
"""
|
|
125
|
+
|
|
126
|
+
if not isinstance(atomic_numbers, _np.ndarray):
|
|
127
|
+
raise TypeError("'atomic_numbers' must be of type 'numpy.ndarray'")
|
|
128
|
+
if not isinstance(xyz, _np.ndarray):
|
|
129
|
+
raise TypeError("'xyz' must be of type 'numpy.ndarray'")
|
|
130
|
+
|
|
131
|
+
if len(atomic_numbers) != len(xyz):
|
|
132
|
+
raise ValueError(
|
|
133
|
+
f"Length of 'atomic_numbers' ({len(atomic_numbers)}) does not "
|
|
134
|
+
f"match length of 'xyz' ({len(xyz)})"
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
# Convert to batched NumPy arrays.
|
|
138
|
+
if len(atomic_numbers.shape) == 1:
|
|
139
|
+
atomic_numbers = _np.expand_dims(atomic_numbers, axis=0)
|
|
140
|
+
xyz = _np.expand_dims(xyz, axis=0)
|
|
141
|
+
|
|
142
|
+
if box is not None:
|
|
143
|
+
n_batch = len(atomic_numbers)
|
|
144
|
+
# Fon now only support single cell for the whole batch
|
|
145
|
+
cells = _np.repeat(_np.diag(box).flatten()[None, :], n_batch, axis=0)
|
|
146
|
+
else:
|
|
147
|
+
cells = None
|
|
148
|
+
|
|
149
|
+
e_list = []
|
|
150
|
+
f_list = []
|
|
151
|
+
|
|
152
|
+
# Run a calculation for each model and take the average.
|
|
153
|
+
for i, dp in enumerate(self._potential):
|
|
154
|
+
# Assume all frames have the same number of atoms.
|
|
155
|
+
atom_types = [
|
|
156
|
+
self._z_map[i][_ase.Atom(z).symbol] for z in atomic_numbers[0]
|
|
157
|
+
]
|
|
158
|
+
e, f, _ = dp.eval(xyz, cells=cells, atom_types=atom_types)
|
|
159
|
+
e_list.append(e)
|
|
160
|
+
f_list.append(f)
|
|
161
|
+
|
|
162
|
+
# Write the maximum DeePMD force deviation to file.
|
|
163
|
+
if self._deviation:
|
|
164
|
+
from deepmd.infer.model_devi import calc_model_devi_f
|
|
165
|
+
|
|
166
|
+
max_f_std = calc_model_devi_f(_np.array(f_list))[0][0]
|
|
167
|
+
if self._deviation_threshold and max_f_std > self._deviation_threshold:
|
|
168
|
+
msg = "Force deviation threshold reached!"
|
|
169
|
+
self._max_f_std = max_f_std
|
|
170
|
+
raise ValueError(msg)
|
|
171
|
+
with open(self._deviation, "a") as f:
|
|
172
|
+
f.write(f"{max_f_std:12.5f}\n")
|
|
173
|
+
# To be written to qm_xyz_file.
|
|
174
|
+
self._max_f_std = max_f_std
|
|
175
|
+
|
|
176
|
+
# Use the first model for production energy and forces.
|
|
177
|
+
e_sel = e_list[0]
|
|
178
|
+
f_sel = f_list[0]
|
|
179
|
+
|
|
180
|
+
# Convert units.
|
|
181
|
+
e, f = (
|
|
182
|
+
e_sel.flatten() * _EV_TO_HARTREE,
|
|
183
|
+
f_sel * _EV_TO_HARTREE * _BOHR_TO_ANGSTROM,
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
return e, f if forces else e
|
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2023-2026 The EMLE-Engine developers
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""OMNI-P2x in-vacuo backend implementation."""
|
|
5
|
+
|
|
6
|
+
__all__ = ["OMNIP2x"]
|
|
7
|
+
|
|
8
|
+
import os as _os
|
|
9
|
+
|
|
10
|
+
import numpy as _np
|
|
11
|
+
import torch as _torch
|
|
12
|
+
from ase.data import atomic_numbers as _SYMBOL_TO_Z
|
|
13
|
+
from torchani.aev import AEVComputer as _AEVComputer
|
|
14
|
+
from torchani.aev import ANIAngular as _ANIAngular
|
|
15
|
+
from torchani.aev import ANIRadial as _ANIRadial
|
|
16
|
+
|
|
17
|
+
from .._units import _BOHR_TO_ANGSTROM
|
|
18
|
+
from ._backend import Backend as _Backend
|
|
19
|
+
|
|
20
|
+
# Classes pickled in the checkpoints, loaded as empty classes holding their state.
|
|
21
|
+
_CLASSES = (
|
|
22
|
+
"torch.nn.modules.container.Sequential",
|
|
23
|
+
"torch.nn.modules.linear.Linear",
|
|
24
|
+
"torch.nn.modules.activation.CELU",
|
|
25
|
+
"torch.nn.modules.activation.GELU",
|
|
26
|
+
"torchani.aev.AEVComputer", # pickled but not read: the AEV is rebuilt from args
|
|
27
|
+
"torchani.utils.EnergyShifter",
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _load_checkpoint(path):
|
|
32
|
+
"""
|
|
33
|
+
Read the plain data (tensors, numbers, strings, dicts) from an OMNI-P2x
|
|
34
|
+
checkpoint without executing any code from it.
|
|
35
|
+
|
|
36
|
+
The checkpoints pickle whole torchani<2.3 objects. torch's weights-only
|
|
37
|
+
loader reads them, with each of these classes replaced by an empty one,
|
|
38
|
+
so their pickled state only becomes instance attributes.
|
|
39
|
+
"""
|
|
40
|
+
# Empty classes with the original names: from_checkpoint dispatches on them.
|
|
41
|
+
safe = [(type(name.rsplit(".", 1)[1], (), {}), name) for name in _CLASSES]
|
|
42
|
+
# species_order holds numpy str_ scalars, rebuilt from their raw bytes.
|
|
43
|
+
# NumPy 2 pickles them under numpy._core instead of numpy.core.
|
|
44
|
+
scalar = lambda dtype, data: _np.frombuffer(data, dtype)[0]
|
|
45
|
+
safe += [
|
|
46
|
+
(scalar, "numpy.core.multiarray.scalar"),
|
|
47
|
+
(scalar, "numpy._core.multiarray.scalar"),
|
|
48
|
+
_np.dtype,
|
|
49
|
+
type(_np.dtype("U1")), # numpy.dtypes.StrDType, checked by torch on BUILD
|
|
50
|
+
]
|
|
51
|
+
with _torch.serialization.safe_globals(safe):
|
|
52
|
+
return _torch.load(path, map_location="cpu", weights_only=True)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class _OMNIP2xNetwork(_torch.nn.Module):
|
|
56
|
+
"""
|
|
57
|
+
One OMNI-P2x network: an ANI AEV, extended with a level descriptor and
|
|
58
|
+
the electronic state index, fed to one MLP per element.
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
def __init__(self, atomic_numbers, aev, networks, self_energies, descriptor):
|
|
62
|
+
"""
|
|
63
|
+
atomic_numbers: list of int, the model's elements in species order
|
|
64
|
+
aev: torchani AEVComputer
|
|
65
|
+
networks: list of per-element MLPs, in species order
|
|
66
|
+
self_energies: (N_SPECIES,) float64, Hartree
|
|
67
|
+
descriptor: (N_DESCRIPTOR,) level descriptor
|
|
68
|
+
"""
|
|
69
|
+
super().__init__()
|
|
70
|
+
|
|
71
|
+
# Map atomic numbers to the model's species indices.
|
|
72
|
+
species_map = _torch.full((max(atomic_numbers) + 1,), -1)
|
|
73
|
+
for i, z in enumerate(atomic_numbers):
|
|
74
|
+
species_map[z] = i
|
|
75
|
+
self.register_buffer("_species_map", species_map)
|
|
76
|
+
|
|
77
|
+
self._aev = aev
|
|
78
|
+
self._networks = _torch.nn.ModuleList(networks)
|
|
79
|
+
self.register_buffer("_self_energies", self_energies)
|
|
80
|
+
self.register_buffer("_descriptor", descriptor)
|
|
81
|
+
|
|
82
|
+
def forward(self, atomic_numbers, xyz, state):
|
|
83
|
+
"""
|
|
84
|
+
atomic_numbers: (N_BATCH, N_ATOMS) int64
|
|
85
|
+
xyz: (N_BATCH, N_ATOMS, 3) float32, Angstrom
|
|
86
|
+
state: (N_BATCH,) electronic state indices (0 = ground state)
|
|
87
|
+
|
|
88
|
+
Returns the energy in Hartree, (N_BATCH,) float64.
|
|
89
|
+
"""
|
|
90
|
+
species = self._species_map[atomic_numbers]
|
|
91
|
+
aev = self._aev(species, xyz)
|
|
92
|
+
n_batch, n_atoms = species.shape
|
|
93
|
+
state = _torch.as_tensor(state, dtype=aev.dtype, device=aev.device)
|
|
94
|
+
extra = _torch.cat(
|
|
95
|
+
(
|
|
96
|
+
self._descriptor.to(aev.dtype).expand(n_batch, -1),
|
|
97
|
+
state.reshape(n_batch, 1),
|
|
98
|
+
),
|
|
99
|
+
dim=1,
|
|
100
|
+
)
|
|
101
|
+
features = _torch.cat((aev, extra[:, None].expand(-1, n_atoms, -1)), dim=2)
|
|
102
|
+
|
|
103
|
+
energy = _torch.zeros(n_batch, n_atoms, dtype=aev.dtype, device=aev.device)
|
|
104
|
+
for i, network in enumerate(self._networks):
|
|
105
|
+
mask = species == i
|
|
106
|
+
if mask.any():
|
|
107
|
+
energy[mask] = network(features[mask]).squeeze(-1)
|
|
108
|
+
|
|
109
|
+
return energy.sum(dim=1).to(_torch.float64) + self._self_energies[species].sum(
|
|
110
|
+
dim=1
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
@classmethod
|
|
114
|
+
def from_checkpoint(cls, path):
|
|
115
|
+
"""
|
|
116
|
+
Build the network from an OMNI-P2x checkpoint saved by MLatom.
|
|
117
|
+
"""
|
|
118
|
+
checkpoint = _load_checkpoint(path)
|
|
119
|
+
args = checkpoint["args"]
|
|
120
|
+
species = [str(s) for s in args["species_order"]]
|
|
121
|
+
|
|
122
|
+
radial = _ANIRadial(
|
|
123
|
+
float(args["EtaR"].reshape(-1)[0]),
|
|
124
|
+
args["ShfR"].reshape(-1).tolist(),
|
|
125
|
+
float(args["Rcr"]),
|
|
126
|
+
)
|
|
127
|
+
angular = _ANIAngular(
|
|
128
|
+
float(args["EtaA"].reshape(-1)[0]),
|
|
129
|
+
float(args["Zeta"].reshape(-1)[0]),
|
|
130
|
+
args["ShfA"].reshape(-1).tolist(),
|
|
131
|
+
args["ShfZ"].reshape(-1).tolist(),
|
|
132
|
+
float(args["Rca"]),
|
|
133
|
+
)
|
|
134
|
+
aev = _AEVComputer(radial, angular, num_species=len(species))
|
|
135
|
+
|
|
136
|
+
# Per-element MLPs, rebuilt layer by layer from the pickled Sequential
|
|
137
|
+
# (the CV models differ in activation: CELU or GELU).
|
|
138
|
+
if isinstance(checkpoint["network"], list):
|
|
139
|
+
raise ValueError(
|
|
140
|
+
"OMNI-P2x checkpoints with network ensembles are not supported"
|
|
141
|
+
)
|
|
142
|
+
networks = []
|
|
143
|
+
for symbol in species:
|
|
144
|
+
layers = []
|
|
145
|
+
pickled = checkpoint["network"][symbol]._modules
|
|
146
|
+
for layer in pickled.values():
|
|
147
|
+
kind = type(layer).__name__
|
|
148
|
+
if kind == "Linear":
|
|
149
|
+
weight = layer._parameters["weight"]
|
|
150
|
+
layers.append(_torch.nn.Linear(weight.shape[1], weight.shape[0]))
|
|
151
|
+
elif kind == "CELU":
|
|
152
|
+
layers.append(_torch.nn.CELU(layer.alpha))
|
|
153
|
+
elif kind == "GELU":
|
|
154
|
+
layers.append(_torch.nn.GELU(layer.approximate))
|
|
155
|
+
else:
|
|
156
|
+
raise ValueError(f"Unsupported OMNI-P2x layer type: {kind}")
|
|
157
|
+
network = _torch.nn.Sequential(*layers)
|
|
158
|
+
network.load_state_dict(
|
|
159
|
+
{
|
|
160
|
+
key[len(symbol) + 1 :]: value
|
|
161
|
+
for key, value in checkpoint["nn"].items()
|
|
162
|
+
if key.startswith(f"{symbol}.")
|
|
163
|
+
}
|
|
164
|
+
)
|
|
165
|
+
networks.append(network)
|
|
166
|
+
|
|
167
|
+
# Self energies, looked up in the same order as MLatom.
|
|
168
|
+
if "energy_shifter" in checkpoint:
|
|
169
|
+
shifter = checkpoint["energy_shifter"]
|
|
170
|
+
elif "energy_shifter_train" in args:
|
|
171
|
+
shifter = args["energy_shifter_train"]
|
|
172
|
+
else:
|
|
173
|
+
shifter = None
|
|
174
|
+
if shifter is not None:
|
|
175
|
+
if getattr(shifter, "fit_intercept", False):
|
|
176
|
+
raise ValueError(
|
|
177
|
+
"OMNI-P2x checkpoints with an intercept are not supported"
|
|
178
|
+
)
|
|
179
|
+
self_energies = shifter._buffers["self_energies"]
|
|
180
|
+
elif "self_energies_train" in args:
|
|
181
|
+
self_energies = args["self_energies_train"]
|
|
182
|
+
elif "self_energies" in args:
|
|
183
|
+
self_energies = args["self_energies"]
|
|
184
|
+
else:
|
|
185
|
+
raise ValueError("The OMNI-P2x checkpoint has no self energies")
|
|
186
|
+
|
|
187
|
+
# Level descriptor default used by MLatom: one-hot on the last entry.
|
|
188
|
+
n_extra = checkpoint.get(
|
|
189
|
+
"descriptor_dim", networks[0][0].in_features - aev.out_dim - 1
|
|
190
|
+
)
|
|
191
|
+
if n_extra < 1:
|
|
192
|
+
raise ValueError(
|
|
193
|
+
"The checkpoint has no level descriptor inputs, so it does not "
|
|
194
|
+
"look like an OMNI-P2x model"
|
|
195
|
+
)
|
|
196
|
+
descriptor = _torch.zeros(n_extra)
|
|
197
|
+
descriptor[-1] = 1.0
|
|
198
|
+
|
|
199
|
+
return cls(
|
|
200
|
+
[_SYMBOL_TO_Z[s] for s in species],
|
|
201
|
+
aev,
|
|
202
|
+
networks,
|
|
203
|
+
_torch.as_tensor(self_energies, dtype=_torch.float64),
|
|
204
|
+
descriptor,
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
class OMNIP2x(_Backend):
|
|
209
|
+
"""
|
|
210
|
+
OMNI-P2x in-vacuo backend implementation.
|
|
211
|
+
"""
|
|
212
|
+
|
|
213
|
+
# Official OMNI-P2x weights, pinned to an omni-p2x commit, with their sha256.
|
|
214
|
+
_WEIGHTS_URL = (
|
|
215
|
+
"https://github.com/dralgroup/omni-p2x/raw/"
|
|
216
|
+
"320c963038be74166cb89c6fc9f3986b0381c5ae/model_weights/"
|
|
217
|
+
)
|
|
218
|
+
_WEIGHTS = {
|
|
219
|
+
"OMNIP2x_CV_1.pt": "a65acf68b74c8b56b98c51734d6d2bf9a3b49e3b25a3fb9cf82212c0d4b47abc",
|
|
220
|
+
"OMNIP2x_CV_2.pt": "9ec6820841acae90d50146af9bd35c2f1406a39eff49da1f0d8a7c707d73955f",
|
|
221
|
+
"OMNIP2x_CV_3.pt": "e98b78d78aed21f5e1a0db50cfc5405fe0b80ad90a5a289758336cecef1c939e",
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
def __init__(self, model=None, device=None):
|
|
225
|
+
"""
|
|
226
|
+
Constructor.
|
|
227
|
+
|
|
228
|
+
Parameters
|
|
229
|
+
----------
|
|
230
|
+
|
|
231
|
+
model: str, list of str
|
|
232
|
+
Path(s) to OMNI-P2x model files, e.g. fine-tuned models saved by
|
|
233
|
+
MLatom. The energy is averaged over the models. If None, the
|
|
234
|
+
official OMNI-P2x models are downloaded on first use.
|
|
235
|
+
|
|
236
|
+
device: str
|
|
237
|
+
The device to run the model on, e.g. "cpu" or "cuda". If None,
|
|
238
|
+
CUDA is used when available.
|
|
239
|
+
"""
|
|
240
|
+
# The checkpoints don't record how many states the model was trained
|
|
241
|
+
# on, so any state is supported unless declared otherwise.
|
|
242
|
+
super().__init__(states=None)
|
|
243
|
+
|
|
244
|
+
if model is None:
|
|
245
|
+
directory = _os.path.join(_torch.hub.get_dir(), "omnip2x")
|
|
246
|
+
_os.makedirs(directory, exist_ok=True)
|
|
247
|
+
model = []
|
|
248
|
+
for name, sha256 in self._WEIGHTS.items():
|
|
249
|
+
path = _os.path.join(directory, name)
|
|
250
|
+
if not _os.path.isfile(path):
|
|
251
|
+
_torch.hub.download_url_to_file(
|
|
252
|
+
self._WEIGHTS_URL + name, path, hash_prefix=sha256
|
|
253
|
+
)
|
|
254
|
+
model.append(path)
|
|
255
|
+
elif isinstance(model, str):
|
|
256
|
+
model = [model]
|
|
257
|
+
if not isinstance(model, (list, tuple)) or not all(
|
|
258
|
+
isinstance(m, str) for m in model
|
|
259
|
+
):
|
|
260
|
+
raise TypeError("'model' must be of type 'str', or a list of 'str' types")
|
|
261
|
+
for m in model:
|
|
262
|
+
if not _os.path.isfile(m):
|
|
263
|
+
raise IOError(f"Unable to locate OMNI-P2x model file: '{m}'")
|
|
264
|
+
self._model = list(model)
|
|
265
|
+
|
|
266
|
+
if device is None:
|
|
267
|
+
device = "cuda" if _torch.cuda.is_available() else "cpu"
|
|
268
|
+
self._device = _torch.device(device)
|
|
269
|
+
|
|
270
|
+
try:
|
|
271
|
+
self._networks = [
|
|
272
|
+
_OMNIP2xNetwork.from_checkpoint(m).to(self._device) for m in self._model
|
|
273
|
+
]
|
|
274
|
+
except Exception as e:
|
|
275
|
+
raise RuntimeError(f"Unable to load the OMNI-P2x models: {e}") from e
|
|
276
|
+
|
|
277
|
+
def calculate(self, atomic_numbers, xyz, forces=True, state=0):
|
|
278
|
+
"""
|
|
279
|
+
Compute the energy and forces.
|
|
280
|
+
|
|
281
|
+
Parameters
|
|
282
|
+
----------
|
|
283
|
+
|
|
284
|
+
atomic_numbers: numpy.ndarray, (N_BATCH, N_QM_ATOMS,)
|
|
285
|
+
The atomic numbers of the atoms in the QM region.
|
|
286
|
+
|
|
287
|
+
xyz: numpy.ndarray, (N_BATCH, N_QM_ATOMS, 3)
|
|
288
|
+
The coordinates of the atoms in the QM region in Angstrom.
|
|
289
|
+
|
|
290
|
+
forces: bool
|
|
291
|
+
Whether to calculate and return forces.
|
|
292
|
+
|
|
293
|
+
state: int, numpy.ndarray (N_BATCH,)
|
|
294
|
+
The electronic state index (0 is the ground state).
|
|
295
|
+
|
|
296
|
+
Returns
|
|
297
|
+
-------
|
|
298
|
+
|
|
299
|
+
energy: float
|
|
300
|
+
The in-vacuo energy in Eh.
|
|
301
|
+
|
|
302
|
+
forces: numpy.ndarray
|
|
303
|
+
The in-vacuo forces in Eh/Bohr.
|
|
304
|
+
"""
|
|
305
|
+
|
|
306
|
+
if not isinstance(atomic_numbers, _np.ndarray):
|
|
307
|
+
raise TypeError("'atomic_numbers' must be of type 'numpy.ndarray'")
|
|
308
|
+
if not isinstance(xyz, _np.ndarray):
|
|
309
|
+
raise TypeError("'xyz' must be of type 'numpy.ndarray'")
|
|
310
|
+
|
|
311
|
+
if len(atomic_numbers) != len(xyz):
|
|
312
|
+
raise ValueError(
|
|
313
|
+
f"Length of 'atomic_numbers' ({len(atomic_numbers)}) does not "
|
|
314
|
+
f"match length of 'xyz' ({len(xyz)})"
|
|
315
|
+
)
|
|
316
|
+
|
|
317
|
+
# Convert to batched NumPy arrays.
|
|
318
|
+
if len(atomic_numbers.shape) == 1:
|
|
319
|
+
atomic_numbers = _np.expand_dims(atomic_numbers, axis=0)
|
|
320
|
+
xyz = _np.expand_dims(xyz, axis=0)
|
|
321
|
+
|
|
322
|
+
for network in self._networks:
|
|
323
|
+
species_map = network._species_map.cpu().numpy()
|
|
324
|
+
z = _np.unique(atomic_numbers)
|
|
325
|
+
supported = (z < len(species_map)) & (
|
|
326
|
+
species_map[_np.minimum(z, len(species_map) - 1)] >= 0
|
|
327
|
+
)
|
|
328
|
+
if not supported.all():
|
|
329
|
+
raise ValueError(
|
|
330
|
+
f"Elements not supported by the OMNI-P2x model: {z[~supported]}"
|
|
331
|
+
)
|
|
332
|
+
|
|
333
|
+
atomic_numbers = _torch.tensor(atomic_numbers, device=self._device)
|
|
334
|
+
xyz = _torch.tensor(
|
|
335
|
+
xyz, dtype=_torch.float32, device=self._device, requires_grad=forces
|
|
336
|
+
)
|
|
337
|
+
|
|
338
|
+
state = _np.full(len(atomic_numbers), state)
|
|
339
|
+
energy = sum(
|
|
340
|
+
network(atomic_numbers, xyz, state) for network in self._networks
|
|
341
|
+
) / len(self._networks)
|
|
342
|
+
|
|
343
|
+
if not forces:
|
|
344
|
+
return energy.detach().cpu().numpy()
|
|
345
|
+
|
|
346
|
+
(gradient,) = _torch.autograd.grad(energy.sum(), xyz)
|
|
347
|
+
forces = -gradient.detach().cpu().numpy() * _BOHR_TO_ANGSTROM
|
|
348
|
+
|
|
349
|
+
return energy.detach().cpu().numpy(), forces
|