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
emle/_backends/_sqm.py ADDED
@@ -0,0 +1,230 @@
1
+ # SPDX-FileCopyrightText: 2023-2026 The EMLE-Engine developers
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """SQM in-vacuo backend implementation."""
5
+
6
+ __all__ = ["SQM"]
7
+
8
+ import numpy as _np
9
+ import os as _os
10
+ import shlex as _shlex
11
+ import subprocess as _subprocess
12
+ import tempfile as _tempfile
13
+
14
+ from .._units import _KCAL_MOL_TO_HARTREE, _BOHR_TO_ANGSTROM
15
+
16
+ from ._backend import Backend as _Backend
17
+
18
+
19
+ class SQM(_Backend):
20
+ """
21
+ SQM in-vacuo backend implementation.
22
+ """
23
+
24
+ def __init__(self, parm7, theory="DFTB3"):
25
+ """
26
+ Constructor.
27
+
28
+ Parameters
29
+ ----------
30
+
31
+ parm7: str
32
+ The path to the AMBER topology file for the QM region.
33
+
34
+ theory: str
35
+ The SQM theory to use.
36
+ """
37
+
38
+ # sqm only supports singlets.
39
+ super().__init__(charges=None)
40
+
41
+ # Make sure a topology file has been set.
42
+ if parm7 is None:
43
+ raise ValueError("'parm7' must be specified when using the SQM backend")
44
+
45
+ try:
46
+ from sander import AmberParm as _AmberParm
47
+
48
+ amber_parm = _AmberParm(parm7)
49
+ except:
50
+ raise IOError(f"Unable to load AMBER topology file: '{parm7}'")
51
+ self._parm7 = parm7
52
+
53
+ if not isinstance(theory, str):
54
+ raise TypeError("'theory' must be of type 'str'.")
55
+
56
+ # Store the atom names for the QM region.
57
+ self._atom_names = [atom.name for atom in amber_parm.atoms]
58
+
59
+ # Strip whitespace.
60
+ self._theory = theory.replace(" ", "")
61
+
62
+ def calculate(self, atomic_numbers, xyz, forces=True, qm_charge=0):
63
+ """
64
+ Compute the energy and forces.
65
+
66
+ Parameters
67
+ ----------
68
+
69
+ atomic_numbers: numpy.ndarray
70
+ The atomic numbers of the atoms in the QM region.
71
+
72
+ xyz: numpy.ndarray
73
+ The coordinates of the atoms in the QM region in Angstrom.
74
+
75
+ forces: bool
76
+ Whether to calculate and return forces.
77
+
78
+ qm_charge: int, numpy.ndarray (N_BATCH,)
79
+ The charge of the QM region.
80
+
81
+ Returns
82
+ -------
83
+
84
+ energy: float
85
+ The in-vacuo energy in Eh.
86
+
87
+ forces: numpy.ndarray
88
+ The in-vacuo gradient in Eh/Bohr.
89
+ """
90
+
91
+ if not isinstance(xyz, _np.ndarray):
92
+ raise TypeError("'xyz' must be of type 'numpy.ndarray'")
93
+ if xyz.dtype != _np.float64:
94
+ raise TypeError("'xyz' must have dtype 'float64'.")
95
+
96
+ if not isinstance(atomic_numbers, _np.ndarray):
97
+ raise TypeError("'atomic_numbers' must be of type 'numpy.ndarray'")
98
+
99
+ if len(atomic_numbers) != len(xyz):
100
+ raise ValueError(
101
+ f"Length of 'atomic_numbers' ({len(atomic_numbers)}) does not "
102
+ f"match length of 'xyz' ({len(xyz)})"
103
+ )
104
+
105
+ # Convert to batched NumPy arrays.
106
+ if len(atomic_numbers.shape) == 1:
107
+ atomic_numbers = _np.expand_dims(atomic_numbers, axis=0)
108
+ xyz = _np.expand_dims(xyz, axis=0)
109
+
110
+ qm_charge = _np.full(len(atomic_numbers), qm_charge)
111
+
112
+ # Lists to store results.
113
+ results_energy = []
114
+ results_forces = []
115
+
116
+ # Loop over batches.
117
+ for i, (atomic_numbers_i, xyz_i) in enumerate(zip(atomic_numbers, xyz)):
118
+ if len(atomic_numbers_i) != len(xyz_i):
119
+ raise ValueError(
120
+ f"Length of 'atomic_numbers' ({len(atomic_numbers_i)}) does not "
121
+ f"match length of 'xyz' ({len(xyz_i)}) for index {i}"
122
+ )
123
+
124
+ # Store the number of QM atoms.
125
+ num_qm = len(atomic_numbers_i)
126
+
127
+ # Create a temporary working directory.
128
+ with _tempfile.TemporaryDirectory() as tmp:
129
+ # Work out the name of the input files.
130
+ inp_name = f"{tmp}/sqm.in"
131
+ out_name = f"{tmp}/sqm.out"
132
+
133
+ # Write the input file.
134
+ with open(inp_name, "w") as f:
135
+ # Write the header.
136
+ f.write("Run semi-empirical minimization\n")
137
+ f.write(" &qmmm\n")
138
+ f.write(f" qm_theory='{self._theory}',\n")
139
+ f.write(f" qmcharge={qm_charge[i]},\n")
140
+ f.write(" maxcyc=0,\n")
141
+ f.write(" verbosity=4,\n")
142
+ f.write(f" /\n")
143
+
144
+ # Write the QM region coordinates.
145
+ for num, name, xyz_qm in zip(
146
+ atomic_numbers_i, self._atom_names, xyz_i
147
+ ):
148
+ x, y, z = xyz_qm
149
+ f.write(f" {num} {name} {x:.4f} {y:.4f} {z:.4f}\n")
150
+
151
+ # Create the SQM command.
152
+ command = f"sqm -i {inp_name} -o {out_name}"
153
+
154
+ # Run the command as a sub-process.
155
+ proc = _subprocess.run(
156
+ _shlex.split(command),
157
+ shell=False,
158
+ stdout=_subprocess.PIPE,
159
+ stderr=_subprocess.PIPE,
160
+ )
161
+
162
+ if proc.returncode != 0:
163
+ raise RuntimeError("SQM job failed!")
164
+
165
+ if not _os.path.isfile(out_name):
166
+ raise IOError(f"Unable to locate SQM output file: {out_name}")
167
+
168
+ with open(out_name, "r") as f:
169
+ is_converged = False
170
+ is_force = False
171
+ num_forces = 0
172
+ forces = []
173
+ for line in f:
174
+ # Skip lines prior to convergence.
175
+ if line.startswith(
176
+ " QMMM SCC-DFTB: SCC-DFTB for step 0 converged"
177
+ ):
178
+ is_converged = True
179
+ continue
180
+
181
+ # Now process the final energy and force records.
182
+ if is_converged:
183
+ if line.startswith(" Total SCF energy"):
184
+ try:
185
+ energy = float(line.split()[4])
186
+ except:
187
+ raise IOError(
188
+ f"Unable to parse SCF energy record: {line}"
189
+ )
190
+ elif line.startswith(
191
+ "QMMM: Forces on QM atoms from SCF calculation"
192
+ ):
193
+ # Flag that force records are coming.
194
+ is_force = True
195
+ elif is_force:
196
+ try:
197
+ force = [float(x) for x in line.split()[3:6]]
198
+ except:
199
+ raise IOError(
200
+ f"Unable to parse SCF gradient record: {line}"
201
+ )
202
+
203
+ # Update the forces.
204
+ forces.append(force)
205
+ num_forces += 1
206
+
207
+ # Exit if we've got all the forces.
208
+ if num_forces == num_qm:
209
+ is_force = False
210
+ break
211
+
212
+ if num_forces != num_qm:
213
+ raise IOError(
214
+ "Didn't find force records for all QM atoms in the SQM output!"
215
+ )
216
+
217
+ # Convert units.
218
+ results_energy.append(energy * _KCAL_MOL_TO_HARTREE)
219
+
220
+ # Convert the gradient to a NumPy array and reshape. Misleading comment
221
+ # in sqm output, the "forces" are actually gradients so need to multiply by -1
222
+ results_forces.append(
223
+ -_np.array(forces) * _KCAL_MOL_TO_HARTREE * _BOHR_TO_ANGSTROM
224
+ )
225
+
226
+ # Convert to NumPy arrays.
227
+ results_energy = _np.array(results_energy)
228
+ results_forces = _np.array(results_forces)
229
+
230
+ return results_energy, results_forces if forces else results_energy
emle/_backends/_xtb.py ADDED
@@ -0,0 +1,126 @@
1
+ # SPDX-FileCopyrightText: 2023-2026 The EMLE-Engine developers
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """XTB in-vacuo backend implementation."""
5
+
6
+ __all__ = ["XTB"]
7
+
8
+ try:
9
+ import xtb as _xtb
10
+ except ImportError:
11
+ _xtb = None
12
+
13
+ import ase as _ase
14
+ import numpy as _np
15
+
16
+ from .._units import _EV_TO_HARTREE, _BOHR_TO_ANGSTROM
17
+
18
+ from ._backend import Backend as _Backend
19
+
20
+
21
+ class XTB(_Backend):
22
+ """
23
+ XTB in-vacuo backend implementation.
24
+ """
25
+
26
+ def __init__(self):
27
+ super().__init__(charges=None, mults=None)
28
+
29
+ if _xtb is None:
30
+ raise ImportError(
31
+ "xtb-python does not appear to be installed, but is "
32
+ "required to use the XTB backend."
33
+ )
34
+
35
+ def calculate(self, atomic_numbers, xyz, forces=True, qm_charge=0, mult=1):
36
+ """
37
+ Compute the energy and forces.
38
+
39
+ Parameters
40
+ ----------
41
+
42
+ atomic_numbers: numpy.ndarray, (N_BATCH, N_QM_ATOMS,)
43
+ The atomic numbers of the atoms in the QM region.
44
+
45
+ xyz: numpy.ndarray, (N_BATCH, N_QM_ATOMS, 3)
46
+ The coordinates of the atoms in the QM region in Angstrom.
47
+
48
+ forces: bool
49
+ Whether to calculate and return forces.
50
+
51
+ qm_charge: int, numpy.ndarray (N_BATCH,)
52
+ The charge of the QM region.
53
+
54
+ mult: int, numpy.ndarray (N_BATCH,)
55
+ The spin multiplicity of the QM region.
56
+
57
+ Returns
58
+ -------
59
+
60
+ energy: float
61
+ The in-vacuo energy in Eh.
62
+
63
+ forces: numpy.ndarray
64
+ The in-vacuo forces in Eh/Bohr.
65
+ """
66
+
67
+ if not isinstance(atomic_numbers, _np.ndarray):
68
+ raise TypeError("'atomic_numbers' must be of type 'numpy.ndarray'")
69
+ if not isinstance(xyz, _np.ndarray):
70
+ raise TypeError("'xyz' must be of type 'numpy.ndarray'")
71
+
72
+ if len(atomic_numbers) != len(xyz):
73
+ raise ValueError(
74
+ f"Length of 'atomic_numbers' ({len(atomic_numbers)}) does not "
75
+ f"match length of 'xyz' ({len(xyz)})"
76
+ )
77
+
78
+ # Convert to batched NumPy arrays.
79
+ if len(atomic_numbers.shape) == 1:
80
+ atomic_numbers = _np.expand_dims(atomic_numbers, axis=0)
81
+ xyz = _np.expand_dims(xyz, axis=0)
82
+
83
+ qm_charge = _np.full(len(atomic_numbers), qm_charge)
84
+ mult = _np.full(len(atomic_numbers), mult)
85
+
86
+ from xtb.ase.calculator import XTB as _XTB
87
+
88
+ # Lists to store results.
89
+ results_energy = []
90
+ results_forces = []
91
+
92
+ # Loop over batches.
93
+ for i, (atomic_numbers_i, xyz_i) in enumerate(zip(atomic_numbers, xyz)):
94
+ if len(atomic_numbers_i) != len(xyz_i):
95
+ raise ValueError(
96
+ f"Length of 'atomic_numbers' ({len(atomic_numbers_i)}) does not "
97
+ f"match length of 'xyz' ({len(xyz_i)}) for index {i}"
98
+ )
99
+
100
+ # Create an ASE atoms object.
101
+ atoms = _ase.Atoms(
102
+ numbers=atomic_numbers_i,
103
+ positions=xyz_i,
104
+ )
105
+
106
+ # The xtb calculator takes the total charge and the number of
107
+ # unpaired electrons from the sums of these per-atom values.
108
+ atoms.set_initial_charges([qm_charge[i]] + [0] * (len(atoms) - 1))
109
+ atoms.set_initial_magnetic_moments([mult[i] - 1] + [0] * (len(atoms) - 1))
110
+
111
+ # Create the calculator.
112
+ atoms.calc = _XTB(method="GFN2-xTB")
113
+
114
+ # Get the energy.
115
+ results_energy.append(atoms.get_potential_energy() * _EV_TO_HARTREE)
116
+
117
+ if forces:
118
+ results_forces.append(
119
+ atoms.get_forces() * _EV_TO_HARTREE * _BOHR_TO_ANGSTROM
120
+ )
121
+
122
+ # Convert to NumPy arrays.
123
+ results_energy = _np.array(results_energy)
124
+ results_forces = _np.array(results_forces)
125
+
126
+ return results_energy, results_forces if forces else results_energy
emle/_compiler.py ADDED
@@ -0,0 +1,279 @@
1
+ # SPDX-FileCopyrightText: 2023-2026 The EMLE-Engine developers
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """
5
+ JIT-compilation of EMLE composite models (backend + embedding) into a
6
+ self-contained TorchScript `.pt` file conforming to the torchani-amber
7
+ custom ML/MM contract (``compute_mlmm`` method).
8
+ """
9
+
10
+ from typing import List, Optional, Tuple, Union
11
+
12
+ import torch as _torch
13
+ from torch import Tensor as _Tensor
14
+
15
+ from .models._utils import _sanitize_alpha_mode
16
+
17
+
18
+ class _CustomMLMMWrapper(_torch.nn.Module):
19
+ """Adapts an EMLE composite (ANI2xEMLE / MACEEMLE) to the torchani-amber
20
+ ``compute_mlmm`` contract.
21
+
22
+ The composite returns ``(E_vac, E_static, E_induced)`` in Hartree; this
23
+ wrapper sums them into a scalar total energy and unpacks the
24
+ ``species_coords`` tuple used by torchani-amber.
25
+
26
+ ``atomic``, ``ensemble_values`` and ``molecule_idxs`` mirror the TorchANI
27
+ ``forward`` signature required by the contract. Only their defaults
28
+ (``False``, ``False``, ``None``) are supported; any other value raises.
29
+ """
30
+
31
+ def __init__(self, composite: _torch.nn.Module):
32
+ super().__init__()
33
+ self._composite = composite
34
+
35
+ @_torch.jit.export
36
+ def compute_mlmm(
37
+ self,
38
+ species_coords: Tuple[_Tensor, _Tensor],
39
+ mm_coords: _Tensor,
40
+ mm_charges: _Tensor,
41
+ cell: Optional[_Tensor],
42
+ pbc: Optional[_Tensor],
43
+ charge: int,
44
+ atomic: bool = False,
45
+ ensemble_values: bool = False,
46
+ molecule_idxs: Optional[_Tensor] = None,
47
+ ) -> _Tensor:
48
+ if atomic:
49
+ raise ValueError("compute_mlmm does not support 'atomic=True'")
50
+ if ensemble_values:
51
+ raise ValueError("compute_mlmm does not support 'ensemble_values=True'")
52
+ if molecule_idxs is not None:
53
+ raise ValueError("compute_mlmm does not support 'molecule_idxs'")
54
+ atomic_numbers, xyz_qm = species_coords
55
+ # torch.jit.load(map_location=...) moves tensors but does not rewrite
56
+ # stored torch.device attributes. Sync EMLE's _device from the actual
57
+ # tensor device so the model is device-agnostic at load time.
58
+ d = xyz_qm.device
59
+ self._composite._emle._device = d
60
+ self._composite._emle._emle_base._device = d
61
+ energies = self._composite(
62
+ atomic_numbers, mm_charges, xyz_qm, mm_coords, cell, charge
63
+ )
64
+ return energies.sum()
65
+
66
+ def forward(
67
+ self,
68
+ species_coords: Tuple[_Tensor, _Tensor],
69
+ mm_coords: _Tensor,
70
+ mm_charges: _Tensor,
71
+ cell: Optional[_Tensor],
72
+ pbc: Optional[_Tensor],
73
+ charge: int,
74
+ atomic: bool = False,
75
+ ensemble_values: bool = False,
76
+ molecule_idxs: Optional[_Tensor] = None,
77
+ ) -> _Tensor:
78
+ return self.compute_mlmm(
79
+ species_coords,
80
+ mm_coords,
81
+ mm_charges,
82
+ cell,
83
+ pbc,
84
+ charge,
85
+ atomic,
86
+ ensemble_values,
87
+ molecule_idxs,
88
+ )
89
+
90
+
91
+ class EMLECompiler:
92
+ """Builds and JIT-compiles an EMLE composite model (in-vacuo backend +
93
+ EMLE embedding head) into a TorchScript ``.pt`` file conforming to the
94
+ torchani-amber custom ML/MM contract.
95
+
96
+ Three in-vacuo backends are scriptable: ``torchani``, ``mace``, and
97
+ ``deepmd`` (DeePMD-kit v3 PyTorch backend, ``.pth`` TorchScript models
98
+ only). Runtime-only backends (ACE, SQM, ORCA, XTB, Sander,
99
+ external, and DeePMD TensorFlow ``.pb`` models) cannot be compiled to a
100
+ self-contained ``.pt`` and are rejected.
101
+ """
102
+
103
+ _supported_backends = ("torchani", "mace", "emle-mace", "deepmd")
104
+
105
+ def __init__(
106
+ self,
107
+ *,
108
+ backend: str = "torchani",
109
+ model: Optional[str] = None,
110
+ method: str = "electrostatic",
111
+ alpha_mode: Optional[str] = None,
112
+ mm_charges: Optional[Union[List[float], Tuple[float, ...]]] = None,
113
+ qm_charge: int = 0,
114
+ ani2x_model_index: Optional[int] = None,
115
+ mace_model: Optional[str] = None,
116
+ deepmd_model: Optional[str] = None,
117
+ use_dipoles: bool = False,
118
+ device: Optional[str] = None,
119
+ ):
120
+ """
121
+ Parameters
122
+ ----------
123
+ backend : str
124
+ In-vacuo ML backend. One of ``"torchani"``, ``"mace"``, or
125
+ ``"deepmd"``.
126
+
127
+ model : str, optional
128
+ Path to a custom EMLE model parameter file. If ``None``, the
129
+ default model for the chosen ``alpha_mode`` is used.
130
+
131
+ method : str
132
+ EMLE embedding method: ``"electrostatic"``, ``"mechanical"``,
133
+ ``"nonpol"``, or ``"mm"``.
134
+
135
+ alpha_mode : str, optional
136
+ Polarizability mode: ``"fixed"`` or ``"flexible"``. Defaults
137
+ to ``"fixed"`` when omitted. Must be ``"fixed"`` (or omitted)
138
+ for the ``"emle-mace"`` backend, which hard-codes that mode.
139
+
140
+ mm_charges : list of float, optional
141
+ Per-atom MM charges for the ML region (only used when
142
+ ``method="mm"``). These are NOT the runtime MM point-charges;
143
+ those are fed through ``compute_mlmm`` every step.
144
+
145
+ qm_charge : int
146
+ ML system net charge.
147
+
148
+ ani2x_model_index : int, optional
149
+ Index into the ANI-2x ensemble (0-7). ``None`` uses the full
150
+ ensemble. Only relevant for ``backend="torchani"``.
151
+
152
+ mace_model : str, optional
153
+ MACE model name (``"mace-off23-small"`` etc.) or path to a
154
+ local MACE model file. Relevant for ``backend="mace"`` and
155
+ ``backend="emle-mace"``. For ``"emle-mace"`` this must be a
156
+ path to an ``EnergyEMLEMACE`` checkpoint (i.e. a MACE model
157
+ that also predicts EMLE properties — valence widths, core
158
+ charges, total charges, atomic dipoles). Vanilla MACE-OFF23
159
+ checkpoints are not valid inputs for ``"emle-mace"``.
160
+
161
+ deepmd_model : str, optional
162
+ Path to a DeePMD-kit v3 PyTorch-backend ``.pth`` (TorchScript)
163
+ model file. Only relevant for ``backend="deepmd"``. TensorFlow
164
+ ``.pb`` models are not scriptable and must be used through the
165
+ runtime DeePMD backend.
166
+
167
+ use_dipoles : bool
168
+ Only relevant for ``backend="emle-mace"``. When ``True``, the
169
+ MACE-predicted atomic dipoles are included in the static
170
+ electrostatic energy. Must be ``False`` for any other backend.
171
+
172
+ device : str, optional
173
+ ``"cpu"`` or ``"cuda"``. Defaults to CPU.
174
+ """
175
+ if backend not in self._supported_backends:
176
+ raise ValueError(
177
+ f"backend={backend!r} is not scriptable. "
178
+ f"Supported backends for compilation: {self._supported_backends}"
179
+ )
180
+
181
+ if use_dipoles and backend != "emle-mace":
182
+ raise ValueError("'use_dipoles' is only valid for backend='emle-mace'.")
183
+
184
+ alpha_mode = _sanitize_alpha_mode(alpha_mode, default=None)
185
+
186
+ if backend == "emle-mace":
187
+ if alpha_mode is not None and alpha_mode != "fixed":
188
+ raise ValueError(
189
+ "backend='emle-mace' requires alpha_mode='fixed' "
190
+ "(MACEEMLEJoint hard-codes the fixed mode)."
191
+ )
192
+ else:
193
+ if alpha_mode is None:
194
+ alpha_mode = "fixed"
195
+
196
+ self._device = _torch.device(device) if device else _torch.device("cpu")
197
+ self._composite = self._build_composite(
198
+ backend=backend,
199
+ model=model,
200
+ method=method,
201
+ alpha_mode=alpha_mode,
202
+ mm_charges=mm_charges,
203
+ qm_charge=qm_charge,
204
+ ani2x_model_index=ani2x_model_index,
205
+ mace_model=mace_model,
206
+ deepmd_model=deepmd_model,
207
+ use_dipoles=use_dipoles,
208
+ )
209
+
210
+ def _build_composite(
211
+ self,
212
+ *,
213
+ backend,
214
+ model,
215
+ method,
216
+ alpha_mode,
217
+ mm_charges,
218
+ qm_charge,
219
+ ani2x_model_index,
220
+ mace_model,
221
+ deepmd_model,
222
+ use_dipoles,
223
+ ):
224
+ if backend == "torchani":
225
+ from .models import ANI2xEMLE
226
+
227
+ return ANI2xEMLE(
228
+ emle_model=model,
229
+ emle_method=method,
230
+ alpha_mode=alpha_mode,
231
+ mm_charges=mm_charges,
232
+ qm_charge=qm_charge,
233
+ model_index=ani2x_model_index,
234
+ device=self._device,
235
+ )
236
+
237
+ if backend == "mace":
238
+ from .models import MACEEMLE
239
+
240
+ return MACEEMLE(
241
+ emle_model=model,
242
+ emle_method=method,
243
+ alpha_mode=alpha_mode,
244
+ mm_charges=mm_charges,
245
+ qm_charge=qm_charge,
246
+ mace_model=mace_model,
247
+ device=self._device,
248
+ )
249
+
250
+ if backend == "emle-mace":
251
+ from .models import MACEEMLEJoint
252
+
253
+ return MACEEMLEJoint(
254
+ emle_model=model,
255
+ emle_method=method,
256
+ mm_charges=mm_charges,
257
+ qm_charge=qm_charge,
258
+ mace_model=mace_model,
259
+ use_dipoles=use_dipoles,
260
+ device=self._device,
261
+ )
262
+
263
+ from .models import DeePMDEMLE
264
+
265
+ return DeePMDEMLE(
266
+ emle_model=model,
267
+ emle_method=method,
268
+ alpha_mode=alpha_mode,
269
+ mm_charges=mm_charges,
270
+ qm_charge=qm_charge,
271
+ deepmd_model=deepmd_model,
272
+ device=self._device,
273
+ )
274
+
275
+ def compile(self, output_path: str) -> None:
276
+ """Script the wrapped model and save it to ``output_path``."""
277
+ wrapper = _CustomMLMMWrapper(self._composite).eval()
278
+ scripted = _torch.jit.script(wrapper)
279
+ scripted.save(output_path)