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.

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
@@ -0,0 +1,322 @@
1
+ # SPDX-FileCopyrightText: 2023-2026 The EMLE-Engine developers
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """ORCA in-vacuo backend implementation."""
5
+
6
+ __all__ = ["ORCA"]
7
+
8
+ import ase as _ase
9
+ import numpy as _np
10
+ import os as _os
11
+ import shlex as _shlex
12
+ import shutil as _shutil
13
+ import subprocess as _subprocess
14
+ import tempfile as _tempfile
15
+
16
+ from ._backend import Backend as _Backend
17
+
18
+
19
+ class ORCA(_Backend):
20
+ """
21
+ ORCA in-vacuo backend implementation.
22
+ """
23
+
24
+ def __init__(self, exe, template=None):
25
+ """
26
+ Constructor.
27
+
28
+ Parameters
29
+ ----------
30
+
31
+ exe: str
32
+ The path to the ORCA executable.
33
+
34
+ template: str
35
+ The path to the ORCA template file.
36
+ """
37
+
38
+ super().__init__(charges=None, mults=None)
39
+
40
+ if not isinstance(exe, str):
41
+ raise TypeError("'exe' must be of type 'str'")
42
+
43
+ if not _os.path.isfile(exe):
44
+ raise IOError(f"Unable to locate ORCA executable: '{exe}'")
45
+
46
+ if template is not None:
47
+ if not isinstance(template, str):
48
+ raise TypeError("'template' must be of type 'str'")
49
+
50
+ if not _os.path.isfile(template):
51
+ raise IOError(f"Unable to locate ORCA template file: '{template}'")
52
+
53
+ # Read the ORCA template file to check for the presence of the
54
+ # '*xyzfile' directive, which is replaced at runtime. Its charge
55
+ # and spin multiplicity are the only ones supported.
56
+ lines = []
57
+ with open(template, "r") as f:
58
+ for line in f:
59
+ if "*xyzfile" in line:
60
+ is_xyzfile = True
61
+ else:
62
+ lines.append(line)
63
+
64
+ if not is_xyzfile:
65
+ raise ValueError(
66
+ "ORCA template file must contain '*xyzfile' directive!"
67
+ )
68
+
69
+ # Try to extract the charge and spin multiplicity from the line.
70
+ try:
71
+ _, charge, mult, _ = line.split()
72
+ except:
73
+ raise ValueError(
74
+ "Unable to parse charge and spin multiplicity from ORCA template file!"
75
+ )
76
+
77
+ self._template_lines = lines
78
+ self.charges = (int(charge),)
79
+ self.mults = (int(mult),)
80
+
81
+ self._exe = exe
82
+ self._template = template
83
+
84
+ def calculate(self, atomic_numbers, xyz, forces=True, qm_charge=0, mult=1):
85
+ """
86
+ Compute the energy and forces.
87
+
88
+ Parameters
89
+ ----------
90
+
91
+ atomic_numbers: numpy.ndarray, (N_BATCH, N_QM_ATOMS,)
92
+ The atomic numbers of the atoms in the QM region.
93
+
94
+ xyz: numpy.ndarray, (N_BATCH, N_QM_ATOMS, 3)
95
+ The coordinates of the atoms in the QM region in Angstrom.
96
+
97
+ forces: bool
98
+ Whether to calculate and return forces.
99
+
100
+ qm_charge: int, numpy.ndarray (N_BATCH,)
101
+ The charge of the QM region.
102
+
103
+ mult: int, numpy.ndarray (N_BATCH,)
104
+ The spin multiplicity of the QM region.
105
+
106
+ Returns
107
+ -------
108
+
109
+ energy: float
110
+ The in-vacuo energy in Eh.
111
+
112
+ forces: numpy.ndarray
113
+ The in-vacuo forces in Eh/Bohr.
114
+ """
115
+
116
+ if not isinstance(atomic_numbers, _np.ndarray):
117
+ raise TypeError("'atomic_numbers' must be of type 'numpy.ndarray'")
118
+ if atomic_numbers.dtype != _np.int64:
119
+ raise TypeError("'atomic_numbers' must have dtype 'int32'.")
120
+
121
+ if not isinstance(xyz, _np.ndarray):
122
+ raise TypeError("'xyz' must be of type 'numpy.ndarray'")
123
+ if xyz.dtype != _np.float64:
124
+ raise TypeError("'xyz' must have dtype 'float64'.")
125
+
126
+ if len(atomic_numbers) != len(xyz):
127
+ raise ValueError(
128
+ f"Length of 'atomic_numbers' ({len(atomic_numbers)}) does not "
129
+ f"match length of 'xyz' ({len(xyz)})"
130
+ )
131
+
132
+ # Convert to batched NumPy arrays.
133
+ if len(atomic_numbers.shape) == 1:
134
+ atomic_numbers = _np.expand_dims(atomic_numbers, axis=0)
135
+ xyz = _np.expand_dims(xyz, axis=0)
136
+
137
+ qm_charge = _np.full(len(atomic_numbers), qm_charge)
138
+ mult = _np.full(len(atomic_numbers), mult)
139
+
140
+ # Lists to store results.
141
+ results_energy = []
142
+ results_forces = []
143
+
144
+ # Loop over batches.
145
+ for i, (atomic_numbers_i, xyz_i) in enumerate(zip(atomic_numbers, xyz)):
146
+ if len(atomic_numbers_i) != len(xyz_i):
147
+ raise ValueError(
148
+ f"Length of 'atomic_numbers' ({len(atomic_numbers_i)}) does not "
149
+ f"match length of 'xyz' ({len(xyz_i)}) for index {i}"
150
+ )
151
+
152
+ # Create a temporary working directory.
153
+ with _tempfile.TemporaryDirectory() as tmp:
154
+ # Workout the name of the input and xyz files.
155
+ inp_name = f"{tmp}/input.inp"
156
+ xyz_name = f"{tmp}/input.xyz"
157
+
158
+ # Write the input file.
159
+ with open(inp_name, "w") as f:
160
+ for line in self._template_lines:
161
+ f.write(line)
162
+ f.write(f"*xyzfile {qm_charge[i]} {mult[i]} {xyz_name}\n")
163
+
164
+ # Work out the elements.
165
+ elements = [_ase.Atom(id).symbol for id in atomic_numbers_i]
166
+
167
+ # Write the xyz file.
168
+ with open(xyz_name, "w") as f:
169
+ f.write(f"{len(elements):5d}\n\n")
170
+ for elem, pos in zip(elements, xyz_i):
171
+ f.write(
172
+ f"{elem:<3s} {pos[0]:20.16f} {pos[1]:20.16f} {pos[2]:20.16f}\n"
173
+ )
174
+
175
+ # Run the ORCA calculation.
176
+ e, f = self.calculate_sander(xyz_name, inp_name, forces=forces)
177
+
178
+ # Store the results.
179
+ results_energy.append(e)
180
+ results_forces.append(f)
181
+
182
+ # Convert the results to NumPy arrays.
183
+ results_energy = _np.array(results_energy)
184
+ results_forces = _np.array(results_forces)
185
+
186
+ return results_energy, results_forces if forces else results_energy
187
+
188
+ def calculate_sander(self, xyz_file, orca_input, forces=True):
189
+ """
190
+ Internal function to compute in vacuo energies and forces using
191
+ ORCA via input written by sander.
192
+
193
+ Parameters
194
+ ----------
195
+
196
+ xyz_file: str
197
+ The path to the xyz coordinate file for the QM region.
198
+
199
+ orca_input: str
200
+ The path to the ORCA input file.
201
+
202
+ forces: bool
203
+ Whether to compute and return the forces.
204
+
205
+ Returns
206
+ -------
207
+
208
+ energy: float
209
+ The in vacuo QM energy in Eh.
210
+
211
+ forces: numpy.array
212
+ The in vacuo QM forces in Eh/Bohr.
213
+ """
214
+
215
+ if not isinstance(xyz_file, str):
216
+ raise TypeError("'xyz_file' must be of type 'str'")
217
+ if not _os.path.isfile(xyz_file):
218
+ raise IOError(f"Unable to locate the ORCA QM xyz file: {xyz_file}")
219
+
220
+ if not isinstance(orca_input, str):
221
+ raise TypeError("'orca_input' must be of type 'str'")
222
+ if not _os.path.isfile(orca_input):
223
+ raise IOError(f"Unable to locate the ORCA input file: {orca_input}")
224
+
225
+ # Create a temporary working directory.
226
+ with _tempfile.TemporaryDirectory() as tmp:
227
+ # Work out the name of the input files.
228
+ inp_name = f"{tmp}/{_os.path.basename(orca_input)}"
229
+ xyz_name = f"{tmp}/{_os.path.basename(xyz_file)}"
230
+
231
+ # Copy the files to the working directory.
232
+ _shutil.copyfile(orca_input, inp_name)
233
+ _shutil.copyfile(xyz_file, xyz_name)
234
+
235
+ # Edit the input file to remove the point charges.
236
+ lines = []
237
+ with open(inp_name, "r") as f:
238
+ for line in f:
239
+ if not line.startswith("%pointcharges"):
240
+ lines.append(line)
241
+ with open(inp_name, "w") as f:
242
+ for line in lines:
243
+ f.write(line)
244
+
245
+ # Create the ORCA command.
246
+ command = f"{self._exe} {inp_name}"
247
+
248
+ # Run the command as a sub-process.
249
+ proc = _subprocess.run(
250
+ _shlex.split(command),
251
+ cwd=tmp,
252
+ shell=False,
253
+ stdout=_subprocess.PIPE,
254
+ stderr=_subprocess.PIPE,
255
+ )
256
+
257
+ if proc.returncode != 0:
258
+ raise RuntimeError("ORCA job failed!")
259
+
260
+ # Parse the output file for the energies and gradients.
261
+ engrad = (
262
+ f"{tmp}/{_os.path.splitext(_os.path.basename(orca_input))[0]}.engrad"
263
+ )
264
+
265
+ if not _os.path.isfile(engrad):
266
+ raise IOError(f"Unable to locate ORCA engrad file: {engrad}")
267
+
268
+ with open(engrad, "r") as f:
269
+ is_nrg = False
270
+ is_grad = False
271
+ gradient = []
272
+ for line in f:
273
+ if line.startswith("# The current total"):
274
+ is_nrg = True
275
+ count = 0
276
+ elif line.startswith("# The current gradient"):
277
+ is_grad = True
278
+ count = 0
279
+ else:
280
+ # This is an energy record. These start two lines after
281
+ # the header, following a comment. So we need to count
282
+ # one line forward.
283
+ if is_nrg and count == 1 and not line.startswith("#"):
284
+ try:
285
+ energy = float(line.strip())
286
+ except:
287
+ IOError("Unable to parse ORCA energy record!")
288
+ # This is a gradient record. These start two lines after
289
+ # the header, following a comment. So we need to count
290
+ # one line forward.
291
+ elif is_grad and count == 1 and not line.startswith("#"):
292
+ try:
293
+ gradient.append(float(line.strip()))
294
+ except:
295
+ IOError("Unable to parse ORCA gradient record!")
296
+ else:
297
+ if is_nrg:
298
+ # We've hit the end of the records, abort.
299
+ if count == 1:
300
+ is_nrg = False
301
+ # Increment the line count since the header.
302
+ else:
303
+ count += 1
304
+ if is_grad:
305
+ # We've hit the end of the records, abort.
306
+ if count == 1:
307
+ is_grad = False
308
+ # Increment the line count since the header.
309
+ else:
310
+ count += 1
311
+
312
+ if not forces:
313
+ return energy
314
+
315
+ # Convert the gradient to a NumPy array and reshape. (Read as a single
316
+ # column, convert to x, y, z components for each atom.)
317
+ try:
318
+ gradient = _np.array(gradient).reshape(int(len(gradient) / 3), 3)
319
+ except:
320
+ raise IOError("Number of ORCA gradient records isn't a multiple of 3!")
321
+
322
+ return energy, -gradient
@@ -0,0 +1,232 @@
1
+ # SPDX-FileCopyrightText: 2023-2026 The EMLE-Engine developers
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """Sander in-vacuo backend implementation."""
5
+
6
+ __all__ = ["Sander"]
7
+
8
+ try:
9
+ import sander as _sander
10
+ except ImportError:
11
+ _sander = None
12
+
13
+ import os as _os
14
+
15
+ import ase as _ase
16
+ import numpy as _np
17
+ from ase.calculators.calculator import Calculator as _Calculator
18
+ from ase.calculators.calculator import all_changes as _all_changes
19
+
20
+ from .._units import _BOHR_TO_ANGSTROM, _KCAL_MOL_TO_HARTREE
21
+ from ._backend import Backend as _Backend
22
+
23
+ # The (topology path, modification time, gas phase, number of atoms) that the
24
+ # sander singleton is set up for. Setup parses the topology, so it is only
25
+ # repeated when this changes.
26
+ _setup_key = None
27
+
28
+
29
+ class SanderCalculator(_Calculator):
30
+ """An ASE calculator for the AMBER Sander molecular dynamics engine."""
31
+
32
+ implemented_properties = [
33
+ "energy",
34
+ "forces",
35
+ ]
36
+
37
+ def __init__(self, atoms, parm7, is_gas=True):
38
+ """
39
+ Constructor.
40
+
41
+ Parameters
42
+ ----------
43
+
44
+ atoms : ase.Atoms
45
+ ASE atoms object containing atomic coordinates matching the topology.
46
+
47
+ parm7 : str
48
+ Path to AMBER topology file.
49
+
50
+ is_gas : bool
51
+ Whether to perform a gas phase calculation.
52
+ """
53
+ if not isinstance(atoms, _ase.Atoms):
54
+ raise TypeError("'atoms' must be of type 'ase.Atoms'")
55
+
56
+ if not isinstance(parm7, str):
57
+ raise TypeError("'parm7' must be of type 'str'")
58
+
59
+ if not isinstance(is_gas, bool):
60
+ raise TypeError("'is_gas' must be of type 'bool'")
61
+
62
+ super().__init__()
63
+
64
+ global _setup_key
65
+ key = (
66
+ _os.path.abspath(parm7),
67
+ _os.path.getmtime(parm7),
68
+ is_gas,
69
+ len(atoms),
70
+ )
71
+ if _sander.is_setup() and key == _setup_key:
72
+ # Already set up for this system: positions (and the box) are
73
+ # updated in calculate.
74
+ return
75
+
76
+ if _sander.is_setup():
77
+ _sander.cleanup()
78
+
79
+ positions = atoms.get_positions()
80
+ box = self._get_box(atoms)
81
+
82
+ if is_gas:
83
+ _sander.setup(parm7, positions, box, _sander.gas_input())
84
+ else:
85
+ _sander.setup(parm7, positions, box, _sander.pme_input())
86
+ _setup_key = key
87
+
88
+ def calculate(
89
+ self, atoms, properties=["energy", "forces"], system_changes=_all_changes
90
+ ):
91
+ # Get the current positions and box.
92
+ super().calculate(atoms, properties, system_changes)
93
+ positions = atoms.get_positions()
94
+ box = self._get_box(atoms)
95
+
96
+ # Update the box.
97
+ if box is not None:
98
+ _sander.set_box(*box)
99
+
100
+ # Update the positions.
101
+ _sander.set_positions(positions)
102
+
103
+ # Compute the energy and forces.
104
+ energy, forces = _sander.energy_forces()
105
+ self.results = {
106
+ "energy": energy.tot * _KCAL_MOL_TO_HARTREE,
107
+ "forces": _np.array(forces).reshape((-1, 3))
108
+ * _KCAL_MOL_TO_HARTREE
109
+ * _BOHR_TO_ANGSTROM,
110
+ }
111
+
112
+ @staticmethod
113
+ def _get_box(atoms):
114
+ if not atoms.get_pbc().all():
115
+ return None
116
+ else:
117
+ return atoms.get_cell().cellpar()
118
+
119
+
120
+ class Sander(_Backend):
121
+ """
122
+ Class for in-vacuo calculations using the AMBER Sander molecular
123
+ dynamics engine.
124
+ """
125
+
126
+ def __init__(self, parm7, is_gas=True):
127
+ """
128
+ Constructor.
129
+ """
130
+
131
+ super().__init__()
132
+
133
+ if _sander is None:
134
+ raise ImportError(
135
+ "sander (part of AmberTools) does not appear to be "
136
+ "installed, but is required to use the Sander backend."
137
+ )
138
+
139
+ if not isinstance(parm7, str):
140
+ raise TypeError("'parm7' must be of type 'str'")
141
+
142
+ if not _os.path.isfile(parm7):
143
+ raise FileNotFoundError(f"Could not find AMBER topology file: '{parm7}'")
144
+
145
+ if not isinstance(is_gas, bool):
146
+ raise TypeError("'is_gas' must be of type 'bool'")
147
+
148
+ self._parm7 = parm7
149
+ self._is_gas = is_gas
150
+
151
+ def calculate(self, atomic_numbers, xyz, forces=True):
152
+ """
153
+ Compute the energy and forces.
154
+
155
+ Parameters
156
+ ----------
157
+
158
+ atomic_numbers: numpy.ndarray, (N_BATCH, N_QM_ATOMS,)
159
+ The atomic numbers of the atoms in the QM region.
160
+
161
+ xyz: numpy.ndarray, (N_BATCH, N_QM_ATOMS, 3)
162
+ The coordinates of the atoms in the QM region in Angstrom.
163
+
164
+ forces: bool
165
+ Whether to calculate and return forces.
166
+
167
+ Returns
168
+ -------
169
+
170
+ energy: float
171
+ The in-vacuo energy in Eh.
172
+
173
+ forces: numpy.ndarray
174
+ The in-vacuo forces in Eh/Bohr.
175
+ """
176
+
177
+ if not isinstance(atomic_numbers, _np.ndarray):
178
+ raise TypeError("'atomic_numbers' must be of type 'numpy.ndarray'")
179
+
180
+ if not isinstance(xyz, _np.ndarray):
181
+ raise TypeError("'xyz' must be of type 'numpy.ndarray'")
182
+
183
+ if len(atomic_numbers) != len(xyz):
184
+ raise ValueError(
185
+ f"Length of 'atomic_numbers' ({len(atomic_numbers)}) does not "
186
+ f"match length of 'xyz' ({len(xyz)})"
187
+ )
188
+
189
+ # Convert to batched NumPy arrays.
190
+ if len(atomic_numbers.shape) == 1:
191
+ atomic_numbers = _np.expand_dims(atomic_numbers, axis=0)
192
+ xyz = _np.expand_dims(xyz, axis=0)
193
+
194
+ if not isinstance(forces, bool):
195
+ raise TypeError("'forces' must be of type 'bool'")
196
+
197
+ # Lists to store results.
198
+ results_energy = []
199
+ results_forces = []
200
+
201
+ # Loop over batches.
202
+ for i, (atomic_numbers_i, xyz_i) in enumerate(zip(atomic_numbers, xyz)):
203
+ if len(atomic_numbers_i) != len(xyz_i):
204
+ raise ValueError(
205
+ f"Length of 'atomic_numbers' ({len(atomic_numbers_i)}) does not "
206
+ f"match length of 'xyz' ({len(xyz_i)}) for index {i}"
207
+ )
208
+
209
+ # Create an ASE atoms object.
210
+ atoms = _ase.Atoms(
211
+ numbers=atomic_numbers_i,
212
+ positions=xyz_i,
213
+ )
214
+
215
+ # Instantiate a SanderCalculator.
216
+ sander_calculator = SanderCalculator(atoms, self._parm7, self._is_gas)
217
+
218
+ # Run the calculation.
219
+ sander_calculator.calculate(atoms)
220
+
221
+ # Get the energy.
222
+ results_energy.append(sander_calculator.results["energy"])
223
+
224
+ # Get the force.
225
+ if forces:
226
+ results_forces.append(sander_calculator.results["forces"])
227
+
228
+ # Convert the results to NumPy arrays.
229
+ results_energy = _np.array(results_energy)
230
+ results_forces = _np.array(results_forces)
231
+
232
+ return results_energy, results_forces if forces else results_energy