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.
Files changed (51) hide show
  1. emle/__init__.py +39 -0
  2. emle/_analyzer.py +337 -0
  3. emle/_backends/__init__.py +14 -0
  4. emle/_backends/_ace.py +141 -0
  5. emle/_backends/_aimnet2.py +136 -0
  6. emle/_backends/_backend.py +148 -0
  7. emle/_backends/_deepmd.py +186 -0
  8. emle/_backends/_omnip2x.py +349 -0
  9. emle/_backends/_orca.py +322 -0
  10. emle/_backends/_sander.py +232 -0
  11. emle/_backends/_sqm.py +230 -0
  12. emle/_backends/_xtb.py +126 -0
  13. emle/_compiler.py +279 -0
  14. emle/_csrc/ops.cpp +350 -0
  15. emle/_csrc/ops_cuda.cu +454 -0
  16. emle/_ops.py +173 -0
  17. emle/_orca_parser.py +331 -0
  18. emle/_resources.py +32 -0
  19. emle/_socket.py +211 -0
  20. emle/_tarball_to_extXYZ.py +236 -0
  21. emle/_units.py +16 -0
  22. emle/_utils.py +57 -0
  23. emle/calculator.py +1974 -0
  24. emle/models/__init__.py +13 -0
  25. emle/models/_ani.py +315 -0
  26. emle/models/_deepmd.py +410 -0
  27. emle/models/_emle.py +629 -0
  28. emle/models/_emle_aev_computer.py +616 -0
  29. emle/models/_emle_base.py +1063 -0
  30. emle/models/_mace.py +1368 -0
  31. emle/models/_patches.py +66 -0
  32. emle/models/_utils.py +279 -0
  33. emle/train/__init__.py +8 -0
  34. emle/train/_extxyz.py +63 -0
  35. emle/train/_gpr.py +205 -0
  36. emle/train/_ivm.py +126 -0
  37. emle/train/_loss.py +357 -0
  38. emle/train/_trainer.py +709 -0
  39. emle/train/_utils.py +92 -0
  40. emle_engine-2.0.0.data/scripts/emle-analyze +175 -0
  41. emle_engine-2.0.0.data/scripts/emle-compile +162 -0
  42. emle_engine-2.0.0.data/scripts/emle-server +777 -0
  43. emle_engine-2.0.0.data/scripts/emle-stop +21 -0
  44. emle_engine-2.0.0.data/scripts/emle-train +127 -0
  45. emle_engine-2.0.0.data/scripts/orca +95 -0
  46. emle_engine-2.0.0.data/scripts/tarball-to-extxyz +6 -0
  47. emle_engine-2.0.0.dist-info/METADATA +49 -0
  48. emle_engine-2.0.0.dist-info/RECORD +51 -0
  49. emle_engine-2.0.0.dist-info/WHEEL +5 -0
  50. emle_engine-2.0.0.dist-info/licenses/LICENSE +21 -0
  51. emle_engine-2.0.0.dist-info/top_level.txt +1 -0
emle/__init__.py ADDED
@@ -0,0 +1,39 @@
1
+ # SPDX-FileCopyrightText: 2023-2026 The EMLE-Engine developers
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ # Note that this file is empty since EMLECalculator and Socket should
5
+ # be directly imported from their respective sub-modules. This is to
6
+ # avoid severe module import overheads when running the client code,
7
+ # which requires no EMLE functionality.
8
+
9
+ """
10
+ Electrostatic Machine-Learned Embedding.
11
+
12
+ emle is a package for the calculation of electrostatic interactions in
13
+ molecular systems.
14
+ """
15
+
16
+ # List of supported backends.
17
+ _supported_backends = [
18
+ "torchani",
19
+ "mace",
20
+ "emle-mace",
21
+ "ace",
22
+ "deepmd",
23
+ "orca",
24
+ "sqm",
25
+ "sander",
26
+ "xtb",
27
+ "aimnet2",
28
+ "omnip2x",
29
+ ]
30
+
31
+ from importlib.metadata import PackageNotFoundError, version as _version
32
+
33
+ try:
34
+ __version__ = _version("emle-engine")
35
+ except PackageNotFoundError:
36
+ # The package metadata isn't available, e.g. when running from an
37
+ # uninstalled source checkout, so fall back to an unknown version.
38
+ __version__ = "unknown"
39
+ del _version, PackageNotFoundError
emle/_analyzer.py ADDED
@@ -0,0 +1,337 @@
1
+ # SPDX-FileCopyrightText: 2023-2026 The EMLE-Engine developers
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """
5
+ Analyser for EMLE simulation output.
6
+ """
7
+
8
+ __all__ = ["EMLEAnalyzer"]
9
+
10
+
11
+ import ase.io as _ase_io
12
+ import numpy as _np
13
+ import torch as _torch
14
+
15
+ from ._units import _HARTREE_TO_KCAL_MOL, _ANGSTROM_TO_BOHR
16
+ from ._utils import pad_to_max as _pad_to_max
17
+ from .models import MACEEMLEJoint as _MACEEMLEJoint
18
+
19
+
20
+ class EMLEAnalyzer:
21
+ """
22
+ Class for analyzing the output of an EMLE simulation.
23
+ """
24
+
25
+ def __init__(
26
+ self,
27
+ qm_xyz_filename,
28
+ pc_xyz_filename,
29
+ emle_base,
30
+ backend=None,
31
+ parser=None,
32
+ q_total=None,
33
+ use_dipoles=False,
34
+ start=None,
35
+ end=None,
36
+ ):
37
+ """
38
+ Constructor.
39
+
40
+ Parameters
41
+ ----------
42
+
43
+ qm_xyz_filename: str
44
+ The path to the xyz trajectory file for the QM region.
45
+
46
+ pc_xyz_filename: str
47
+ The path to the xyz trajectory file for the point charges.
48
+
49
+ emle_base: :class:`EMLEBase <emle.models.EMLEBase>`
50
+ An EMLEBase model instance.
51
+
52
+ backend: :class:`torch.nn.Module`, :class:`Backend <emle._backends._backend.Backend>`
53
+ The backend for in vacuo calculations.
54
+
55
+ parser: :class:`ORCAParser <emle._orca_parser.ORCAParser>`
56
+ An ORCA parser instance.
57
+
58
+ q_total: int, float
59
+ The total charge of the QM region.
60
+
61
+ start: int
62
+ Structure index to start parsing
63
+
64
+ end: int
65
+ Structure index to end parsing
66
+ """
67
+
68
+ if start is not None and end is not None:
69
+ mask = slice(start, end)
70
+ elif start is None and end is None:
71
+ mask = slice(None)
72
+ else:
73
+ raise ValueError("Both start and end must be provided")
74
+
75
+ if not isinstance(qm_xyz_filename, str):
76
+ raise ValueError("Invalid qm_xyz_filename type. Must be a string.")
77
+
78
+ if not isinstance(pc_xyz_filename, str):
79
+ raise ValueError("Invalid pc_xyz_filename type. Must be a string.")
80
+
81
+ if q_total is not None and not isinstance(q_total, (int, float)):
82
+ raise ValueError("Invalid q_total type. Must be a number.")
83
+
84
+ if q_total is None and parser is None:
85
+ raise ValueError("Either parser or q_total must be provided")
86
+
87
+ from .models._emle_base import EMLEBase
88
+
89
+ if not isinstance(emle_base, EMLEBase):
90
+ raise ValueError("Invalid emle_base type. Must be an EMLEBase object.")
91
+
92
+ dtype = emle_base._dtype
93
+ device = emle_base._device
94
+
95
+ # All the structures are parsed (not only start:end) to ensure the
96
+ # same padding for all the slices (then can be trivially concatenated)
97
+ try:
98
+ atomic_numbers, qm_xyz = self._parse_qm_xyz(qm_xyz_filename)
99
+ except Exception as e:
100
+ raise RuntimeError(f"Unable to parse QM xyz file: {e}")
101
+
102
+ try:
103
+ pc_charges, pc_xyz = self._parse_pc_xyz(pc_xyz_filename)
104
+ except Exception as e:
105
+ raise RuntimeError(f"Unable to parse PC xyz file: {e}")
106
+
107
+ if parser:
108
+ self.q_total = _torch.sum(
109
+ _torch.tensor(
110
+ parser.mbis["q_core"] + parser.mbis["q_val"],
111
+ device=device,
112
+ dtype=dtype,
113
+ ),
114
+ dim=1,
115
+ )
116
+ else:
117
+ self.q_total = (
118
+ _torch.ones(len(qm_xyz), device=device, dtype=dtype) * q_total
119
+ )
120
+
121
+ atomic_numbers = atomic_numbers[mask]
122
+ qm_xyz = qm_xyz[mask]
123
+ pc_charges = pc_charges[mask]
124
+ pc_xyz = pc_xyz[mask]
125
+
126
+ # Store the in vacuo energies if a backend is provided.
127
+ if backend:
128
+ if isinstance(backend, _torch.nn.Module):
129
+ backend = backend.to(device).to(dtype)
130
+ atomic_numbers = _torch.tensor(atomic_numbers, device=device)
131
+ qm_xyz = _torch.tensor(
132
+ qm_xyz, dtype=dtype, device=device, requires_grad=True
133
+ )
134
+ charges_mm = _torch.empty((len(qm_xyz), 0), dtype=dtype, device=device)
135
+ mm_xyz = _torch.empty((len(qm_xyz), 0, 3), dtype=dtype, device=device)
136
+ self.e_backend = (
137
+ backend(
138
+ atomic_numbers, charges_mm, qm_xyz, mm_xyz, qm_charge=q_total
139
+ ).T
140
+ * _HARTREE_TO_KCAL_MOL
141
+ )
142
+ self.grad_backend = _torch.autograd.grad(
143
+ self.e_backend.T[0].sum(), qm_xyz
144
+ )[0]
145
+ else:
146
+ # Non-torch backend (no autograd): gradient = -forces.
147
+ e, f = backend(atomic_numbers, qm_xyz)
148
+ self.e_backend = _torch.from_numpy(e * _HARTREE_TO_KCAL_MOL)[:, None]
149
+ self.grad_backend = _torch.from_numpy(
150
+ -f * _ANGSTROM_TO_BOHR * _HARTREE_TO_KCAL_MOL
151
+ )
152
+
153
+ self.atomic_numbers = _torch.tensor(
154
+ atomic_numbers, dtype=_torch.int, device=device
155
+ )
156
+ self.qm_xyz = _torch.tensor(qm_xyz, dtype=dtype, device=device)
157
+ self.pc_charges = _torch.tensor(pc_charges, dtype=dtype, device=device)
158
+ self.pc_xyz = _torch.tensor(pc_xyz, dtype=dtype, device=device)
159
+
160
+ qm_xyz_bohr = self.qm_xyz * _ANGSTROM_TO_BOHR
161
+ pc_xyz_bohr = self.pc_xyz * _ANGSTROM_TO_BOHR
162
+
163
+ if isinstance(backend, _MACEEMLEJoint):
164
+ self.s = _torch.stack(backend.emle_values["s"])
165
+ self.q_core = _torch.stack(backend.emle_values["q_core"])
166
+ self.q_val = _torch.stack(backend.emle_values["q_val"])
167
+ self.mu = _torch.stack(backend.emle_values["mu"])
168
+
169
+ a_Thole = backend._mace.a_Thole
170
+ species_id = emle_base._species_map[self.atomic_numbers]
171
+ k = backend._mace.elements_alpha_v_ratios[species_id]
172
+ r_data = emle_base._get_r_data(qm_xyz_bohr, atomic_numbers > 0)
173
+ self.A_thole = emle_base._get_A_thole(
174
+ r_data, self.s, self.q_val, k, a_Thole
175
+ )
176
+ else:
177
+ self.s, self.q_core, self.q_val, self.A_thole = emle_base(
178
+ self.atomic_numbers,
179
+ self.qm_xyz,
180
+ self.q_total,
181
+ )
182
+ self.atomic_alpha = 1.0 / _torch.diagonal(self.A_thole, dim1=1, dim2=2)[:, ::3]
183
+ self.alpha = self._get_mol_alpha(self.A_thole, self.atomic_numbers)
184
+
185
+ self.mu_vac = _torch.sum(
186
+ (self.q_core + self.q_val)[:, :, None] * qm_xyz_bohr, dim=1
187
+ )
188
+ if use_dipoles:
189
+ self.mu_vac = self.mu_vac + _torch.sum(self.mu, dim=1)
190
+
191
+ mask = (self.atomic_numbers > 0).unsqueeze(-1)
192
+ mesh_data = emle_base._get_mesh_data(qm_xyz_bohr, pc_xyz_bohr, self.s, mask)
193
+ self.e_static = (
194
+ emle_base.get_static_energy(
195
+ self.q_core, self.q_val, self.pc_charges, mesh_data
196
+ )
197
+ * _HARTREE_TO_KCAL_MOL
198
+ )
199
+ if use_dipoles:
200
+ self.e_static_mu = (
201
+ emle_base.get_static_energy(
202
+ self.q_core, self.q_val, self.pc_charges, mesh_data, self.mu
203
+ )
204
+ * _HARTREE_TO_KCAL_MOL
205
+ )
206
+ self.e_induced = (
207
+ emle_base.get_induced_energy(
208
+ self.A_thole, self.pc_charges, self.s, mesh_data, mask
209
+ )
210
+ * _HARTREE_TO_KCAL_MOL
211
+ )
212
+ mu_ind = EMLEBase._get_mu_ind(
213
+ self.A_thole, mesh_data, self.pc_charges, self.s, mask
214
+ )
215
+ self.mu_induced = _torch.sum(mu_ind, dim=1)
216
+
217
+ if parser:
218
+ self.e_static_mbis = (
219
+ emle_base.get_static_energy(
220
+ _torch.tensor(parser.mbis["q_core"], dtype=dtype, device=device),
221
+ _torch.tensor(parser.mbis["q_val"], dtype=dtype, device=device),
222
+ self.pc_charges,
223
+ mesh_data,
224
+ )
225
+ * _HARTREE_TO_KCAL_MOL
226
+ )
227
+
228
+ for attr in (
229
+ "atomic_numbers",
230
+ "qm_xyz",
231
+ "s",
232
+ "q_core",
233
+ "q_val",
234
+ "q",
235
+ "mu",
236
+ "q_total",
237
+ "atomic_alpha",
238
+ "alpha",
239
+ "mu_vac",
240
+ "mu_induced",
241
+ "e_backend",
242
+ "e_static",
243
+ "e_static_mu",
244
+ "e_induced",
245
+ "e_static_mbis",
246
+ "grad_backend",
247
+ ):
248
+ if attr in self.__dict__:
249
+ setattr(self, attr, getattr(self, attr).detach().cpu().numpy())
250
+
251
+ @staticmethod
252
+ def _parse_qm_xyz(filename):
253
+ """
254
+ Parse the QM xyz file.
255
+
256
+ Parameters
257
+ ----------
258
+
259
+ filename: str
260
+ The path to the QM xyz file.
261
+
262
+ Returns
263
+ -------
264
+
265
+ atomic_numbers: np.ndarray (N_BATCH, N_QM_ATOMS)
266
+ The atomic numbers of the atoms.
267
+
268
+ xyz: np.ndarray (N_BATCH, N_QM_ATOMS, 3)
269
+ The positions of the atoms.
270
+ """
271
+
272
+ atoms = _ase_io.read(filename, index=":")
273
+ atomic_numbers = _pad_to_max([_.get_atomic_numbers() for _ in atoms], 0)
274
+ xyz = _np.array([_.get_positions() for _ in atoms])
275
+ return atomic_numbers, xyz
276
+
277
+ @staticmethod
278
+ def _parse_pc_xyz(filename):
279
+ """
280
+ Parse the PC xyz file.
281
+
282
+ Parameters
283
+ ----------
284
+
285
+ filename: str
286
+ The path to the PC xyz file.
287
+
288
+ Returns
289
+ -------
290
+
291
+ charges: np.ndarray (N_BATCH, MAX_N_PC)
292
+ The charges of the point charges.
293
+
294
+ xyz: np.ndarray (N_BATCH, MAX_N_PC, 3)
295
+ The positions of the point charges.
296
+ """
297
+ frames = []
298
+ with open(filename, "r") as file:
299
+ while True:
300
+ try:
301
+ n = int(file.readline().strip())
302
+ frames.append(_np.loadtxt(file, max_rows=n))
303
+ file.readline()
304
+ except ValueError:
305
+ break
306
+ padded_frames = _pad_to_max(frames)
307
+ return padded_frames[:, :, 0], padded_frames[:, :, 1:]
308
+
309
+ @staticmethod
310
+ def _get_mol_alpha(A_thole, atomic_numbers):
311
+ """
312
+ Calculate the molecular polarizability tensor.
313
+
314
+ Parameters
315
+ ----------
316
+
317
+ A_thole: torch.Tensor (N_BATCH, N_ATOMS * 3, N_ATOMS * 3)
318
+ The Thole tensor.
319
+
320
+ atomic_numbers: torch.Tensor (N_BATCH, N_ATOMS)
321
+ The atomic numbers of the atoms.
322
+
323
+ Returns
324
+ -------
325
+
326
+ alpha: torch.Tensor (N_BATCH, 3, 3)
327
+ The molecular polarizability tensor.
328
+ """
329
+ mask = atomic_numbers > 0
330
+ mask_mat = mask[:, :, None] * mask[:, None, :]
331
+ mask_mat = mask_mat.repeat_interleave(3, dim=1)
332
+ mask_mat = mask_mat.repeat_interleave(3, dim=2)
333
+
334
+ n_mols = A_thole.shape[0]
335
+ n_atoms = A_thole.shape[1] // 3
336
+ Ainv = _torch.linalg.inv(A_thole) * mask_mat
337
+ return _torch.sum(Ainv.reshape(n_mols, n_atoms, 3, n_atoms, 3), dim=(1, 3))
@@ -0,0 +1,14 @@
1
+ # SPDX-FileCopyrightText: 2023-2026 The EMLE-Engine developers
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """
5
+ Backends for in-vacuo calculations.
6
+ """
7
+
8
+ from ._aimnet2 import *
9
+ from ._omnip2x import *
10
+ from ._deepmd import *
11
+ from ._orca import *
12
+ from ._sander import *
13
+ from ._sqm import *
14
+ from ._xtb import *
emle/_backends/_ace.py ADDED
@@ -0,0 +1,141 @@
1
+ # SPDX-FileCopyrightText: 2023-2026 The EMLE-Engine developers
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """ACE in-vacuo backend implementation."""
5
+
6
+ __all__ = ["ACE"]
7
+
8
+ try:
9
+ import pyjulip as _pyjulip
10
+ except ImportError:
11
+ _pyjulip = None
12
+
13
+ import ase as _ase
14
+ import os as _os
15
+ import numpy as _np
16
+
17
+
18
+ from .._units import _EV_TO_HARTREE, _BOHR_TO_ANGSTROM
19
+
20
+ from ._backend import Backend as _Backend
21
+
22
+
23
+ class ACE(_Backend):
24
+ """
25
+ ACE in-vacuo backend implementation.
26
+ """
27
+
28
+ def __init__(self, model):
29
+ """
30
+ Initialize the ACE in-vacuo backend.
31
+
32
+ Parameters
33
+ ----------
34
+
35
+ model: str
36
+ The path to the ACE model.
37
+ """
38
+
39
+ super().__init__()
40
+
41
+ if _pyjulip is None:
42
+ raise ImportError(
43
+ "pyjulip does not appear to be installed, but is required "
44
+ "to use the ACE backend."
45
+ )
46
+
47
+ # Validate the model path.
48
+ if not isinstance(model, str):
49
+ raise TypeError("'model' must be of type 'str'")
50
+ if not _os.path.exists(model):
51
+ raise FileNotFoundError(f"Model file '{model}' not found")
52
+
53
+ # Try to create the ACE calculator.
54
+
55
+ try:
56
+ self._calculator = _pyjulip.ACE(model)
57
+ except Exception as e:
58
+ raise RuntimeError(f"Failed to create ACE calculator: {e}")
59
+
60
+ def calculate(self, atomic_numbers, xyz, forces=True):
61
+ """
62
+ Compute the energy and forces.
63
+
64
+ Parameters
65
+ ----------
66
+
67
+ atomic_numbers: numpy.ndarray, (N_BATCH, N_QM_ATOMS,)
68
+ The atomic numbers of the atoms in the QM region.
69
+
70
+ xyz: numpy.ndarray, (N_BATCH, N_QM_ATOMS, 3)
71
+ The coordinates of the atoms in the QM region in Angstrom.
72
+
73
+ forces: bool
74
+ Whether to calculate and return forces.
75
+
76
+ Returns
77
+ -------
78
+
79
+ energy: float
80
+ The in-vacuo energy in Eh.
81
+
82
+ forces: numpy.ndarray
83
+ The in-vacuo forces in Eh/Bohr.
84
+ """
85
+
86
+ if not isinstance(atomic_numbers, _np.ndarray):
87
+ raise TypeError("'atomic_numbers' must be of type 'numpy.ndarray'")
88
+ if not isinstance(xyz, _np.ndarray):
89
+ raise TypeError("'xyz' must be of type 'numpy.ndarray'")
90
+
91
+ if len(atomic_numbers) != len(xyz):
92
+ raise ValueError(
93
+ f"Length of 'atomic_numbers' ({len(atomic_numbers)}) does not "
94
+ f"match length of 'xyz' ({len(xyz)})"
95
+ )
96
+
97
+ # Convert to batched NumPy arrays.
98
+ if len(atomic_numbers.shape) == 1:
99
+ atomic_numbers = _np.expand_dims(atomic_numbers, axis=0)
100
+ xyz = _np.expand_dims(xyz, axis=0)
101
+
102
+ # Lists to store results.
103
+ results_energy = []
104
+ results_forces = []
105
+
106
+ # Loop over batches.
107
+ for i, (atomic_numbers_i, xyz_i) in enumerate(zip(atomic_numbers, xyz)):
108
+ if len(atomic_numbers_i) != len(xyz_i):
109
+ raise ValueError(
110
+ f"Length of 'atomic_numbers' ({len(atomic_numbers_i)}) does not "
111
+ f"match length of 'xyz' ({len(xyz_i)}) for index {i}"
112
+ )
113
+
114
+ # Create an ASE atoms object.
115
+ atoms = _ase.Atoms(
116
+ numbers=atomic_numbers_i,
117
+ positions=xyz_i,
118
+ )
119
+
120
+ # The calculator requires periodic box information so we translate the atoms
121
+ # so that the lowest (x, y, z) position is zero, then set the cell to the
122
+ # maximum position.
123
+ atoms.positions -= _np.min(atoms.positions, axis=0)
124
+ atoms.cell = _np.max(atoms.positions, axis=0)
125
+
126
+ # Set the calculator.
127
+ atoms.calc = self._calculator
128
+
129
+ # Get the energy.
130
+ results_energy.append(atoms.get_potential_energy() * _EV_TO_HARTREE)
131
+
132
+ if forces:
133
+ results_forces.append(
134
+ atoms.get_forces() * _EV_TO_HARTREE * _BOHR_TO_ANGSTROM
135
+ )
136
+
137
+ # Convert to NumPy arrays.
138
+ results_energy = _np.array(results_energy)
139
+ results_forces = _np.array(results_forces)
140
+
141
+ return results_energy, results_forces if forces else results_energy
@@ -0,0 +1,136 @@
1
+ # SPDX-FileCopyrightText: 2023-2026 The EMLE-Engine developers
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """AIMNet2 in-vacuo backend implementation."""
5
+
6
+ __all__ = ["AIMNet2"]
7
+
8
+ try:
9
+ from aimnet.calculators import AIMNet2Calculator as _AIMNet2Calculator
10
+ except ImportError:
11
+ _AIMNet2Calculator = None
12
+
13
+ import numpy as _np
14
+
15
+ from .._units import _BOHR_TO_ANGSTROM, _EV_TO_HARTREE
16
+ from ._backend import Backend as _Backend
17
+
18
+
19
+ class AIMNet2(_Backend):
20
+ """
21
+ AIMNet2 in-vacuo backend implementation.
22
+ """
23
+
24
+ def __init__(self, model="aimnet2", device=None):
25
+ """
26
+ Constructor.
27
+
28
+ Parameters
29
+ ----------
30
+
31
+ model: str
32
+ The AIMNet2 model to use: a name from the aimnet model registry,
33
+ e.g. "aimnet2" or "aimnet2-b973c", or the path to a model file.
34
+ If None, "aimnet2" is used. Spin multiplicities other than 1
35
+ need an open-shell model, e.g. "aimnet2-nse".
36
+
37
+ device: str
38
+ The device to run the model on, e.g. "cpu" or "cuda". If None,
39
+ CUDA is used when available.
40
+ """
41
+ super().__init__(charges=None, mults=None)
42
+
43
+ if _AIMNet2Calculator is None:
44
+ raise ImportError(
45
+ "aimnet does not appear to be installed, but is "
46
+ "required to use the AIMNet2 backend."
47
+ )
48
+
49
+ if model is None:
50
+ model = "aimnet2"
51
+ if not isinstance(model, str):
52
+ raise TypeError("'model' must be of type 'str'")
53
+ self._model = model
54
+
55
+ if device is not None:
56
+ device = str(device)
57
+
58
+ try:
59
+ self._calculator = _AIMNet2Calculator(model, device=device)
60
+ except Exception as e:
61
+ raise RuntimeError(f"Unable to create the AIMNet2 calculator: {e}") from e
62
+
63
+ # Closed-shell models have no spin multiplicity input.
64
+ if not self._calculator.is_nse:
65
+ self.mults = (1,)
66
+
67
+ def calculate(self, atomic_numbers, xyz, forces=True, qm_charge=0, mult=1):
68
+ """
69
+ Compute the energy and forces.
70
+
71
+ Parameters
72
+ ----------
73
+
74
+ atomic_numbers: numpy.ndarray, (N_BATCH, N_QM_ATOMS,)
75
+ The atomic numbers of the atoms in the QM region.
76
+
77
+ xyz: numpy.ndarray, (N_BATCH, N_QM_ATOMS, 3)
78
+ The coordinates of the atoms in the QM region in Angstrom.
79
+
80
+ forces: bool
81
+ Whether to calculate and return forces.
82
+
83
+ qm_charge: int, numpy.ndarray (N_BATCH,)
84
+ The charge of the QM region.
85
+
86
+ mult: int, numpy.ndarray (N_BATCH,)
87
+ The spin multiplicity of the QM region.
88
+
89
+ Returns
90
+ -------
91
+
92
+ energy: float
93
+ The in-vacuo energy in Eh.
94
+
95
+ forces: numpy.ndarray
96
+ The in-vacuo forces in Eh/Bohr.
97
+ """
98
+
99
+ if not isinstance(atomic_numbers, _np.ndarray):
100
+ raise TypeError("'atomic_numbers' must be of type 'numpy.ndarray'")
101
+ if not isinstance(xyz, _np.ndarray):
102
+ raise TypeError("'xyz' must be of type 'numpy.ndarray'")
103
+
104
+ if len(atomic_numbers) != len(xyz):
105
+ raise ValueError(
106
+ f"Length of 'atomic_numbers' ({len(atomic_numbers)}) does not "
107
+ f"match length of 'xyz' ({len(xyz)})"
108
+ )
109
+
110
+ # Convert to batched NumPy arrays.
111
+ if len(atomic_numbers.shape) == 1:
112
+ atomic_numbers = _np.expand_dims(atomic_numbers, axis=0)
113
+ xyz = _np.expand_dims(xyz, axis=0)
114
+
115
+ # The whole batch is evaluated in one call, so all frames must have
116
+ # the same number of atoms.
117
+ result = self._calculator.eval(
118
+ {
119
+ "coord": xyz,
120
+ "numbers": atomic_numbers,
121
+ "charge": _np.full(len(atomic_numbers), qm_charge, dtype=float),
122
+ "mult": _np.full(len(atomic_numbers), mult, dtype=float),
123
+ },
124
+ forces=forces,
125
+ )
126
+
127
+ energy = result["energy"].detach().cpu().numpy() * _EV_TO_HARTREE
128
+
129
+ if not forces:
130
+ return energy
131
+
132
+ forces = (
133
+ result["forces"].detach().cpu().numpy() * _EV_TO_HARTREE * _BOHR_TO_ANGSTROM
134
+ )
135
+
136
+ return energy, forces