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/_orca_parser.py ADDED
@@ -0,0 +1,331 @@
1
+ # SPDX-FileCopyrightText: 2023-2026 The EMLE-Engine developers
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """
5
+ Parser for ORCA and HORTON outputs.
6
+ """
7
+
8
+ __all__ = ["ORCAParser"]
9
+
10
+ import ase as _ase
11
+ import h5py as _h5py
12
+ import os as _os
13
+ import numpy as _np
14
+ import tarfile as _tarfile
15
+
16
+ from ._utils import pad_to_max
17
+ from ._units import _HARTREE_TO_KCAL_MOL
18
+
19
+
20
+ class ORCAParser:
21
+ """
22
+ Parses ORCA gas phase calculations and corresponding HORTON outputs.
23
+ Optionally, extract molecular dipolar polarizability (needed for EMLE
24
+ training) and does energy decomposition analysis for embedding energy. The
25
+ latter requires additional calculation in presence of point charges and
26
+ electrostatic potential of the gas phase system at the positions of the
27
+ point charges).
28
+ """
29
+
30
+ _HORTON_KEYS = (
31
+ "cartesian_multipoles",
32
+ "core_charges",
33
+ "valence_charges",
34
+ "valence_widths",
35
+ )
36
+
37
+ def __init__(self, filename, decompose=False, alpha=False):
38
+ """
39
+ Constructor.
40
+
41
+ Parameters
42
+ ----------
43
+
44
+ filename : str
45
+ Tarball with ORCA and HORTON outputs:
46
+ ".h5":
47
+ HORTON output.
48
+ ".vac.orca":
49
+ ORCA output for gas phase calculation. If alpha=True, must
50
+ contain molecular dipolar polarizability tensor as well.
51
+ The following files are required if decompose=True:
52
+ ".pc.orca":
53
+ ORCA output for calculation with point charges (PC).
54
+ ".pc":
55
+ Charges and positions of the point charges (the ones used for
56
+ .pc.orca calculation).
57
+ ".vpot":
58
+ Output of orca_vpot, electrostatic potential of gas phase
59
+ system at the positions of the point charges.
60
+ ".h5":
61
+ HORTON output.
62
+ ".vac.orca":
63
+ ORCA output for gas phase calculation. If alpha=True, must
64
+ contain molecular dipolar polarizability tensor as well.
65
+ All files must have numeric names (same number for the same structure).
66
+
67
+ decompose: bool
68
+ Whether to do energy decomposition analysis
69
+
70
+ alpha: bool
71
+ Whether to extract molecular dipolar polarizability tensor
72
+
73
+ Notes
74
+ -----
75
+
76
+ Once the files are parsed the following attributes are available:
77
+ z:
78
+ (N_MOLS, MAX_N_ATOMS) atomic indices.
79
+ xyz:
80
+ (N_MOLS, MAX_N_ATOMS, 3) positions of atoms
81
+ mbis:
82
+ a dictionary with MBIS properties (s, q_core, q_val, mu)
83
+ alpha:
84
+ (N_MOLS, 3, 3) array of molecular dipolar polarizability
85
+ tensors (alpha=True)
86
+ E:
87
+ total embedding energies (decompose=True)
88
+ E_static:
89
+ static embedding energies (decompose=True)
90
+ E_induced:
91
+ induced embedding energies (decompose=True)
92
+ """
93
+
94
+ if not isinstance(filename, str):
95
+ raise ValueError("filename must be a string")
96
+
97
+ if not _os.path.exists(filename):
98
+ raise FileNotFoundError(f"{filename} does not exist")
99
+
100
+ if not isinstance(decompose, bool):
101
+ raise ValueError("decompose must be a boolean")
102
+
103
+ if not isinstance(alpha, bool):
104
+ raise ValueError("alpha must be a boolean")
105
+
106
+ try:
107
+ with _tarfile.open(filename, "r") as tar:
108
+
109
+ self._tar = tar
110
+ self.names = self._get_names(tar)
111
+
112
+ self.mbis = self._parse_horton()
113
+ self.z, self.xyz = self._get_z_xyz()
114
+
115
+ self.E_vac = self.get_E_vac()
116
+ self.forces = self.get_forces()
117
+
118
+ if decompose:
119
+ self.vac_E, self.pc_E = self._get_E()
120
+ self.E = self.pc_E - self.vac_E
121
+ self.E_static = self._get_E_static()
122
+ self.E_induced = self.E - self.E_static
123
+
124
+ if alpha:
125
+ self.alpha = self._get_alpha()
126
+
127
+ except Exception as e:
128
+ raise ValueError(f"Failed to parse {filename}: {e}")
129
+
130
+ del self._tar
131
+
132
+ @staticmethod
133
+ def _get_names(tar):
134
+ return sorted(
135
+ [int(name.split(".")[0]) for name in tar.getnames() if name.endswith("h5")]
136
+ )
137
+
138
+ def _get_E(self):
139
+ vac_E = [
140
+ self._get_E_from_out(self._get_file(name, "vac.orca"))
141
+ for name in self.names
142
+ ]
143
+ pc_E = [
144
+ self._get_E_from_out(self._get_file(name, "pc.orca")) for name in self.names
145
+ ]
146
+ return _np.array(vac_E), _np.array(pc_E)
147
+
148
+ def _get_E_from_out(self, f):
149
+ E_prefix = b"FINAL SINGLE POINT ENERGY"
150
+ E_line = next(line for line in f if line.startswith(E_prefix))
151
+ return float(E_line.split()[-1]) * _HARTREE_TO_KCAL_MOL
152
+
153
+ def _get_E_static(self):
154
+ vpot_all = self._get_vpot()
155
+ pc_all = self._get_pc()
156
+ result = _np.array([(vpot @ pc) for vpot, pc in zip(vpot_all, pc_all)])
157
+ return result * _HARTREE_TO_KCAL_MOL
158
+
159
+ def _get_vpot(self):
160
+ return [
161
+ self._get_vpot_from_file(self._get_file(name, "vpot"))
162
+ for name in self.names
163
+ ]
164
+
165
+ @staticmethod
166
+ def _get_vpot_from_file(f):
167
+ return _np.loadtxt(f, skiprows=1)[:, 3]
168
+
169
+ def _get_pc(self):
170
+ return [
171
+ self._get_pc_from_file(self._get_file(name, "pc")) for name in self.names
172
+ ]
173
+
174
+ @staticmethod
175
+ def _get_pc_from_file(f):
176
+ return _np.loadtxt(f, skiprows=1)[:, 0]
177
+
178
+ def _get_alpha(self):
179
+ alpha = [
180
+ self._get_alpha_from_out(self._get_file(name, "vac.orca"))
181
+ for name in self.names
182
+ ]
183
+ return _np.array(alpha)
184
+
185
+ @staticmethod
186
+ def _get_alpha_from_out(f):
187
+ while next(f) != b"The raw cartesian tensor (atomic units):\n":
188
+ pass
189
+ return _np.array([list(map(float, next(f).split())) for _ in range(3)])
190
+
191
+ def _get_z_xyz(self):
192
+ mol_data = [
193
+ self._get_z_xyz_from_out(self._get_file(name, "vac.orca"))
194
+ for name in self.names
195
+ ]
196
+ z, xyz = zip(*mol_data)
197
+ return pad_to_max(z, 0), pad_to_max(xyz)
198
+
199
+ @staticmethod
200
+ def _get_z_xyz_from_out(f):
201
+ while next(f) != b"CARTESIAN COORDINATES (ANGSTROEM)\n":
202
+ pass
203
+ next(f)
204
+ z, xyz = [], []
205
+ try:
206
+ while True:
207
+ raw_atom_z, *raw_atom_xyz = next(f).split()
208
+ z.append(raw_atom_z.decode())
209
+ xyz.append([float(x) for x in raw_atom_xyz])
210
+ except ValueError:
211
+ pass
212
+ return _np.array(_ase.symbols.symbols2numbers(z)), _np.array(xyz)
213
+
214
+ def _parse_horton(self):
215
+ data = [
216
+ self._parse_horton_out(self._get_file(name, "h5")) for name in self.names
217
+ ]
218
+ if len(data) == 0:
219
+ raise ValueError
220
+ return {k: pad_to_max([_[k] for _ in data]) for k in data[0].keys()}
221
+
222
+ def _parse_horton_out(self, f):
223
+ h5f = _h5py.File(f)
224
+ data = {key: h5f[key][:] for key in self._HORTON_KEYS}
225
+ q = data["core_charges"] + data["valence_charges"]
226
+ q_total = _np.sum(q)
227
+ if abs(_np.round(q_total) - q_total) >= 0.1:
228
+ raise ValueError(f"MBIS charges sum to non-integer {q_total}")
229
+ q_shift = (_np.round(q_total) - q_total) / len(q)
230
+ return {
231
+ "s": data["valence_widths"],
232
+ "q_core": data["core_charges"],
233
+ "q_val": data["valence_charges"] + q_shift,
234
+ "mu": data["cartesian_multipoles"][:, 1:4],
235
+ }
236
+
237
+ def _get_file(self, name, suffix):
238
+ return self._tar.extractfile(f"{name}.{suffix}")
239
+
240
+ def get_E_vac(self, energy_unit=_ase.units.eV):
241
+ """
242
+ Parse the gas-phase ORCA output for each configuration and return the
243
+ total energy.
244
+
245
+ Parameters
246
+ ----------
247
+
248
+ energy_unit: float
249
+ ASE energy unit for the returned values (e.g. ase.units.eV or
250
+ ase.units.Hartree). Defaults to ase.units.eV; eV is the default
251
+ because this method is used mainly for MACE model training, which
252
+ works in eV.
253
+
254
+ Returns
255
+ -------
256
+
257
+ E_tot: numpy.ndarray (N_CONFIGS,)
258
+ Total gas-phase energy per configuration, in energy_unit (eV by
259
+ default). NaN where the output has no final energy.
260
+ """
261
+ E_tot = [
262
+ self._get_E_vac_from_out(self._get_file(name, "vac.orca"), energy_unit)
263
+ for name in self.names
264
+ ]
265
+ return _np.array(E_tot)
266
+
267
+ def _get_E_vac_from_out(self, f, energy_unit=_ase.units.eV):
268
+ """
269
+ Extract the total energy from an ORCA gas-phase output file.
270
+
271
+ Reads the FINAL SINGLE POINT ENERGY, which includes the D3BJ dispersion
272
+ correction, not the SCF "Total Energy", which does not.
273
+
274
+ Parameters
275
+ ----------
276
+
277
+ energy_unit: float
278
+ ASE energy unit for the returned value. Defaults to ase.units.eV;
279
+ eV is the default because this function is used mainly for MACE
280
+ model training, which works in eV.
281
+ """
282
+ E_prefix = b"FINAL SINGLE POINT ENERGY"
283
+ E_line = [line for line in f if line.startswith(E_prefix)]
284
+ if not E_line:
285
+ return _np.nan
286
+ return float(E_line[0].split()[-1]) * _ase.units.Hartree / energy_unit
287
+
288
+ def get_forces(self):
289
+ """
290
+ Parse the gas-phase ORCA output for each configuration and return the
291
+ atomic forces in Hartree/Bohr.
292
+
293
+ Returns
294
+ -------
295
+
296
+ forces: List[numpy.ndarray or None]
297
+ Per-configuration atomic forces in Hartree/Bohr, each of shape
298
+ (N_ATOMS, 3). None where the output has no gradient.
299
+ """
300
+ forces = [
301
+ self._get_forces_from_out(self._get_file(name, "vac.orca"))
302
+ for name in self.names
303
+ ]
304
+ return forces
305
+
306
+ def _get_forces_from_out(self, f):
307
+ """
308
+ Extract the Cartesian forces from an ORCA gas-phase output file.
309
+ ORCA reports the gradient in Hartree/Bohr; we negate (forces =
310
+ -gradient) and return in the same units.
311
+ """
312
+ for line in f:
313
+ if line == b"CARTESIAN GRADIENT\n":
314
+ break
315
+ else:
316
+ return None
317
+ next(f)
318
+ next(f)
319
+ forces = []
320
+ try:
321
+ while True:
322
+ line_elements = next(f).split()
323
+ if len(line_elements) == 0:
324
+ break
325
+ # Extract gradient (last 3 elements) and negate to get forces.
326
+ force_values = [-float(x) for x in line_elements[-3:]]
327
+ forces.append(force_values)
328
+
329
+ except ValueError:
330
+ pass
331
+ return _np.asarray(forces)
emle/_resources.py ADDED
@@ -0,0 +1,32 @@
1
+ # SPDX-FileCopyrightText: 2023-2026 The EMLE-Engine developers
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """Resource handling utilities for EMLE."""
5
+
6
+ __author__ = "Lester Hedges"
7
+ __email__ = "lester.hedges@gmail.com"
8
+
9
+ _DEFAULT_MODEL = "emle-1.0.mat"
10
+ _DEFAULT_MODEL_URL = f"https://github.com/chemle/emle-models/raw/v1.0/{_DEFAULT_MODEL}"
11
+ _DEFAULT_MODEL_SHA256 = (
12
+ "0dcfdfa58b72d3c53a27105f073bc41661197ff6a2f60dbd2c46d4e8f5c87922"
13
+ )
14
+
15
+
16
+ def _fetch_default_model():
17
+ """
18
+ Return the path to the default EMLE model in the torch hub cache,
19
+ downloading it on first use.
20
+ """
21
+
22
+ import os as _os
23
+ import torch as _torch
24
+
25
+ directory = _os.path.join(_torch.hub.get_dir(), "emle")
26
+ path = _os.path.join(directory, _DEFAULT_MODEL)
27
+ if not _os.path.isfile(path):
28
+ _os.makedirs(directory, exist_ok=True)
29
+ _torch.hub.download_url_to_file(
30
+ _DEFAULT_MODEL_URL, path, hash_prefix=_DEFAULT_MODEL_SHA256
31
+ )
32
+ return path
emle/_socket.py ADDED
@@ -0,0 +1,211 @@
1
+ # SPDX-FileCopyrightText: 2023-2026 The EMLE-Engine developers
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """Simple TCP socket-server implementation."""
5
+
6
+ __author__ = "Lester Hedges"
7
+ __email__ = "lester.hedges@gmail.com"
8
+
9
+ __all__ = ["Socket"]
10
+
11
+ import socket as _socket
12
+
13
+
14
+ class Socket:
15
+ """
16
+ A wrapper around socket.socket with convenience functions to aid
17
+ the sending and receiving of messages.
18
+ """
19
+
20
+ def __init__(self, sock=None):
21
+ """
22
+ Constructor.
23
+
24
+ Parameters
25
+ ----------
26
+
27
+ sock : socket.socket
28
+ An existing socket object.
29
+ """
30
+ if sock is None:
31
+ self._sock = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
32
+ else:
33
+ if not isinstance(sock, _socket.socket):
34
+ raise TypeError("'sock' must be of type 'socket.sock'")
35
+ else:
36
+ self._sock = sock
37
+
38
+ def connect(self, host, port):
39
+ """
40
+ Connect to a specified host and port.
41
+
42
+ Parameters
43
+ ----------
44
+
45
+ host : str
46
+ The hostname.
47
+
48
+ port : int
49
+ The port number.
50
+ """
51
+ if not isinstance(host, str):
52
+ raise TypeError("'host' must be of type 'str'")
53
+
54
+ if type(port) is not int:
55
+ raise TypeError("'port' must be of type 'int'")
56
+
57
+ print(f"Connecting socket at address: ({host}, {port})")
58
+ self._sock.connect((host, port))
59
+
60
+ def bind(self, host, port):
61
+ """
62
+ Bind to a specified host and port.
63
+
64
+ Parameters
65
+ ----------
66
+
67
+ host : str
68
+ The hostname.
69
+
70
+ port : int
71
+ The port number.
72
+ """
73
+ if not isinstance(host, str):
74
+ raise TypeError("'host' must be of type 'str'")
75
+
76
+ if type(port) is not int:
77
+ raise TypeError("'port' must be of type 'int'")
78
+
79
+ print(f"Binding socket to address: ({host}, {port})")
80
+ self._sock.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, 1)
81
+ self._sock.bind((host, port))
82
+
83
+ def listen(self, num_connections=1):
84
+ """
85
+ Listen for the specified number of connections. If num_connections = 0,
86
+ then the system default will be used.
87
+
88
+ Parameters
89
+ ----------
90
+
91
+ num_connections : int
92
+ """
93
+ if type(num_connections) is not int:
94
+ raise ValueError("'num_connections' must be of type 'int'")
95
+ if num_connections < 0:
96
+ raise ValueError("'num_connections' must be >= 0")
97
+
98
+ print(f"Listening for connections from {num_connections} clients...")
99
+ self._sock.listen(num_connections)
100
+
101
+ def accept(self):
102
+ """
103
+ Accept a conection.
104
+
105
+ Returns
106
+ -------
107
+
108
+ connection : socket.socket
109
+ A new socket to be used for sending and receiving data on
110
+ the connection.
111
+
112
+ address : (str, str)
113
+ The address bound to the socket on the other end of the
114
+ connection.
115
+ """
116
+ connection, address = self._sock.accept()
117
+ return Socket(connection), address
118
+
119
+ def close(self):
120
+ """Close the socket."""
121
+ self._sock.close()
122
+
123
+ def send(self, msg, length):
124
+ """
125
+ Send a message over the socket. The message is ":" token delimited
126
+ string where the header contains the length of the subsequent message.
127
+
128
+ For example, for the client:
129
+
130
+ "23:emlerun:/path/to/client"
131
+
132
+ This communicates an EMLE calculation request to the server, also
133
+ passing the path from which the client was run.
134
+
135
+ On succesful completion, the server will return a fixed message of:
136
+
137
+ "7:emlefin"
138
+
139
+ Parameters
140
+ ----------
141
+
142
+ msg : str
143
+ The message to send.
144
+
145
+ length : int
146
+ The length of the message.
147
+ """
148
+ if not isinstance(msg, str):
149
+ raise TypeError("'msg' must be of type 'str'")
150
+
151
+ if not isinstance(length, int):
152
+ raise TypeError("'length' must be of type 'int'")
153
+
154
+ # Encode the message.
155
+ msg_bytes = msg.encode("utf-8")
156
+
157
+ totalsent = 0
158
+ while totalsent < length:
159
+ sent = self._sock.send(msg_bytes[totalsent:])
160
+ if sent == 0:
161
+ raise ConnectionError("The socket connection was broken!")
162
+ totalsent = totalsent + sent
163
+
164
+ def receive(self):
165
+ """
166
+ Receive a message.
167
+
168
+ Returns
169
+ -------
170
+
171
+ msg : str
172
+ The message received.
173
+
174
+ path/error : str (optional)
175
+ The path from which the message was sent on the client, or the
176
+ error message returned from the server.
177
+ """
178
+
179
+ # First work out the message length.
180
+ buf = b""
181
+ while True:
182
+ c = self._sock.recv(1)
183
+ if not c:
184
+ print("The socket connection was broken!")
185
+ return None, None
186
+ if c == b":":
187
+ break
188
+ else:
189
+ buf += c
190
+
191
+ # Store the length of the message.
192
+ msg_len = int(buf)
193
+
194
+ chunks = []
195
+ bytes_recd = 0
196
+
197
+ # Now read the rest of the message.
198
+ while bytes_recd < msg_len:
199
+ chunk = self._sock.recv(min(msg_len - bytes_recd, msg_len))
200
+ if chunk == b"":
201
+ print("The socket connection was broken!")
202
+ return None, None
203
+ chunks.append(chunk)
204
+ bytes_recd = bytes_recd + len(chunk)
205
+
206
+ data = b"".join(chunks).decode("utf-8").split(":")
207
+
208
+ if len(data) < 2:
209
+ return data[0], None
210
+ else:
211
+ return data[:2]