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/calculator.py ADDED
@@ -0,0 +1,1974 @@
1
+ # SPDX-FileCopyrightText: 2023-2026 The EMLE-Engine developers
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """
5
+ EMLE calculator implementation.
6
+ """
7
+
8
+ __author__ = "Lester Hedges"
9
+ __email__ = "lester.hedges@gmail.com"
10
+
11
+ __all__ = ["EMLECalculator"]
12
+
13
+ from loguru import logger as _logger
14
+
15
+ import os as _os
16
+ import numpy as _np
17
+ import sys as _sys
18
+ from types import SimpleNamespace as _SimpleNamespace
19
+ import yaml as _yaml
20
+
21
+ import ase as _ase
22
+ import ase.io as _ase_io
23
+
24
+ import torch as _torch
25
+
26
+ from .models import EMLE as _EMLE
27
+ from ._backends._backend import _check_supported
28
+
29
+ from emle._units import (
30
+ _NANOMETER_TO_BOHR,
31
+ _BOHR_TO_ANGSTROM,
32
+ _HARTREE_TO_KJ_MOL,
33
+ _NANOMETER_TO_ANGSTROM,
34
+ )
35
+
36
+
37
+ class EMLECalculator:
38
+ """
39
+ Predicts EMLE energies and gradients allowing QM/MM with ML electrostatic
40
+ embedding. Requires the use of a QM (or ML) engine to compute in vacuo
41
+ energies and gradients, to which those from the EMLE model are added.
42
+ Supported backends are listed in the _supported_backends attribute below.
43
+ """
44
+
45
+ from . import _supported_backends
46
+
47
+ # Class attributes.
48
+
49
+ # List of supported backends.
50
+ _supported_backends = _supported_backends.copy() + ["external"]
51
+
52
+ # List of supported devices.
53
+ _supported_devices = ["cpu", "cuda"]
54
+
55
+ # Default to no interpolation.
56
+ _lambda_interpolate = None
57
+
58
+ # Default to no external callback.
59
+ _is_external_backend = False
60
+
61
+ def __init__(
62
+ self,
63
+ model=None,
64
+ method="electrostatic",
65
+ alpha_mode="fixed",
66
+ use_dipoles=False,
67
+ qm_charge=0,
68
+ mult=1,
69
+ backend="torchani",
70
+ external_backend=None,
71
+ plugin_path=".",
72
+ mm_charges=None,
73
+ box=None,
74
+ deepmd_model=None,
75
+ deepmd_deviation=None,
76
+ deepmd_deviation_threshold=None,
77
+ qm_xyz_file="qm.xyz",
78
+ pc_xyz_file="pc.xyz",
79
+ qm_xyz_frequency=0,
80
+ ani2x_model_index=None,
81
+ mace_model=None,
82
+ qbc_deviation=None,
83
+ qbc_deviation_threshold=None,
84
+ ace_model=None,
85
+ parm7=None,
86
+ qm_indices=None,
87
+ orca_path=None,
88
+ sqm_theory="DFTB3",
89
+ aimnet2_model="aimnet2",
90
+ omnip2x_model=None,
91
+ electronic_state=None,
92
+ model_charges=None,
93
+ model_mults=None,
94
+ model_states=None,
95
+ lambda_interpolate=None,
96
+ interpolate_steps=None,
97
+ restart=False,
98
+ device=None,
99
+ orca_template=None,
100
+ energy_frequency=0,
101
+ energy_file="emle_energy.txt",
102
+ log_level="ERROR",
103
+ log_file=None,
104
+ save_settings=False,
105
+ ):
106
+ """
107
+ Constructor
108
+
109
+ Parameters
110
+ ----------
111
+
112
+ model: str
113
+ Path to the EMLE embedding model parameter file. If None, then a
114
+ default model will be used.
115
+
116
+ method: str
117
+ The desired embedding method. Options are:
118
+ "electrostatic":
119
+ Full ML electrostatic embedding.
120
+ "mechanical":
121
+ ML predicted charges for the core, but zero valence charge.
122
+ "nonpol":
123
+ Non-polarisable ML embedding. Here the induced component of
124
+ the potential is zeroed.
125
+ "mm":
126
+ MM charges are used for the core charge and valence charges
127
+ are set to zero. If this option is specified then the user
128
+ should also specify the MM charges for atoms in the QM
129
+ region.
130
+
131
+ backend: str, Tuple[str]
132
+ The backend to use to compute in vacuo energies and gradients. If None,
133
+ then no backend will be used, allowing you to obtain the electrostatic
134
+ embedding energy and gradients only. If two backends are specified, then
135
+ the second can be used to apply delta-learning corrections to the
136
+ energies and gradients.
137
+
138
+ alpha_mode: str
139
+ How atomic polarizabilities are calculated.
140
+ "fixed":
141
+ one volume scaling factor is used for each species
142
+ "flexible":
143
+ scaling factors are obtained with GPR using the values learned
144
+ for each reference environment
145
+
146
+ use_dipoles: bool
147
+ Whether static atomic dipoles should be used
148
+
149
+ qm_charge: int
150
+ The charge on the QM region. This is required when using an
151
+ EMLECalculator instance with the OpenMM interface. When using
152
+ the sander interface, the QM charge will be taken from the ORCA
153
+ input file.
154
+
155
+ mult: int
156
+ The spin multiplicity of the QM region. When using the sander
157
+ interface, it will be taken from the ORCA input file. With the
158
+ ORCA backend, the charge and multiplicity, from this and
159
+ 'qm_charge' or from the ORCA input file, must match the values in
160
+ 'orca_template'.
161
+
162
+ external_backend: str
163
+ The name of an external backend to use to compute in vacuo energies.
164
+ This should be a callback function formatted as 'module.function'.
165
+ The function should take a single argument, which is an ASE Atoms
166
+ object for the QM region, and return the energy in Hartree along with
167
+ the gradients in Hartree/Bohr as a numpy.ndarray.
168
+
169
+ plugin_path: str
170
+ The direcory containing any scripts used for external backends.
171
+
172
+ mm_charges: List, Tuple, numpy.ndarray, str
173
+ An array of MM charges for atoms in the QM region. This is required
174
+ when the embedding method is "mm". Alternatively, pass the path to
175
+ a file containing the charges. The file should contain a single
176
+ column. Units are electron charge.
177
+
178
+ box: List, Tuple, numpy.ndarray, (3,)
179
+ PBC box. Only orthorhombic boxes are supported.
180
+ (For now only works for DeePMD)
181
+
182
+ deepmd_model: str
183
+ Path to the DeePMD model file to use for in vacuo calculations. This
184
+ must be specified if "deepmd" is the selected backend. This can be
185
+ one or more files, i.e. multiple models can be used to compute
186
+ force deviations. When multiple models are specified, the first model
187
+ will be used for the production energy and forces.
188
+
189
+ deepmd_deviation: str
190
+ Path to a file to write the max deviation between forces predicted
191
+ with the DeePMD models.
192
+
193
+ deepmd_deviation_threshold: float
194
+ The threshold for the maximum deviation between forces predicted with
195
+ the DeePMD models. If the deviation exceeds this value, a ValueError
196
+ will be raised and the calculation will be terminated.
197
+
198
+ qm_xyz_file: str
199
+ Path to an output file for writing the xyz trajectory of the QM
200
+ region.
201
+
202
+ pc_xyz_file: str
203
+ Path to an output file for writing the charges and positions of the
204
+ MM point charges.
205
+
206
+ qm_xyz_frequency: int
207
+ How often to write the xyz trajectory of the QM and MM regions. Zero
208
+ turns off writing.
209
+
210
+ ani2x_model_index: int
211
+ The index of the ANI model to use when using the TorchANI backend.
212
+ If None, then the full 8 model ensemble is used.
213
+
214
+ mace_model: str, list[str]
215
+ Name of the MACE-OFF23 models to use.
216
+ Available models are 'mace-off23-small', 'mace-off23-medium', 'mace-off23-large'.
217
+ To use a locally trained MACE model, provide the path to the model file.
218
+ If a list of strings is provided, deviation between the models will be printed
219
+ on each step to qbc_deviation.
220
+ If None, the MACE-OFF23(S) model will be used by default.
221
+
222
+ qbc_deviation: str
223
+ Path to a file to write the max deviation between forces predicted
224
+ with the models (for Query-by-Committee).
225
+
226
+ qbc_deviation_threshold: float
227
+ The threshold for the maximum deviation between forces.
228
+ If the deviation exceeds this value, a ValueError
229
+ will be raised and the calculation will be terminated.
230
+
231
+ ace_model: str
232
+ Path to the ACE model file to use for in vacuo calculations. This
233
+ must be specified if 'ace' is the selected backend.
234
+
235
+ lambda_interpolate: float, [float, float]
236
+ The value of lambda to use for end-state correction calculations. This
237
+ must be between 0 and 1, which is used to interpolate between a full MM
238
+ and EMLE potential. If two lambda values are specified, the calculator
239
+ will gradually interpolate between them when called multiple times. This
240
+ must be used in conjunction with the 'interpolate_steps' argument.
241
+
242
+ interpolate_steps: int
243
+ The number of steps over which lambda is linearly interpolated.
244
+
245
+ parm7: str
246
+ The path to an AMBER parm7 file for the QM region. This is needed to
247
+ compute in vacuo MM energies for the QM region when interpolating.
248
+
249
+ qm_indices: list, str
250
+ A list of atom indices for the QM region. This must be specified when
251
+ interpolating. Alternatively, a path to a file containing the indices
252
+ can be specified. The file should contain a single column with the
253
+ indices being zero-based.
254
+
255
+ orca_path: str
256
+ The path to the ORCA executable. This is required when using the ORCA
257
+ backend.
258
+
259
+ sqm_theory: str
260
+ The QM theory to use when using the SQM backend. See the AmberTools
261
+ manual for the supported theory levels for your version of AmberTools.
262
+
263
+ aimnet2_model: str
264
+ The AIMNet2 model to use when using the AIMNet2 backend: a name from
265
+ the aimnet model registry, e.g. "aimnet2", or the path to a model file.
266
+
267
+ omnip2x_model: str, [str]
268
+ Path(s) to OMNI-P2x model files to use when using the OMNI-P2x
269
+ backend, e.g. fine-tuned models saved by MLatom. The energy is
270
+ averaged over the models. If None, the official OMNI-P2x models
271
+ are downloaded on first use.
272
+
273
+ electronic_state: int
274
+ The electronic state index (0 is the ground state). If None, the
275
+ ground state is used. For excited states, an EMLE model trained
276
+ for that state should be passed as 'model'.
277
+
278
+ model_charges: list of int
279
+ The QM charges that the in vacuo model supports, replacing those
280
+ of every backend. Models without a charge input, e.g. DeePMD or
281
+ MACE, are assumed to support only 0. A charge that is not
282
+ supported raises an error.
283
+
284
+ model_mults: list of int
285
+ As 'model_charges', for the spin multiplicity (by default 1).
286
+
287
+ model_states: list of int
288
+ As 'model_charges', for the electronic state (by default 0, the
289
+ ground state), e.g. [0, 1] for an OMNI-P2x model fine-tuned for
290
+ two states.
291
+
292
+ restart: bool
293
+ Whether this is a restart simulation with sander. If True, then energies
294
+ are logged immediately.
295
+
296
+ device: str
297
+ The name of the device to be used by PyTorch. Options are "cpu"
298
+ or "cuda".
299
+
300
+ orca_template: str
301
+ The path to a template ORCA input file. This is required when using
302
+ the ORCA backend when using emle-engine with Sire. This should be a
303
+ full template, including the charge and multiplicity of the QM region,
304
+ which are the only ones supported unless declared with
305
+ 'model_charges' and 'model_mults', along with a placeholder name for
306
+ the xyz file that will be replaced with the file generated at runtime,
307
+ e.g.:
308
+
309
+ %pal nprocs 4 end
310
+ !BLYP 6-31G* verytightscf
311
+ %method
312
+ grid 4
313
+ finalgrid 6
314
+ end
315
+ %scf
316
+ maxiter 100
317
+ end
318
+ %MaxCore 1024
319
+ ! ENGRAD
320
+ ! Angs NoUseSym
321
+ *xyzfile 0 1 inpfile.xyz
322
+
323
+ energy_frequency: int
324
+ The frequency of logging energies to file. If 0, then no energies are
325
+ logged.
326
+
327
+ energy_file: str
328
+ The name of the file to which energies are logged.
329
+
330
+ log_level: str
331
+ The logging level to use. Options are "TRACE", "DEBUG", "INFO", "WARNING",
332
+ "ERROR", and "CRITICAL".
333
+
334
+ log_file: str
335
+ The name of the file to which log messages are written.
336
+
337
+ save_settings: bool
338
+ Whether to write a YAML file containing the settings used to initialise
339
+ the calculator.
340
+ """
341
+
342
+ # Validate input.
343
+
344
+ # First handle the logger.
345
+
346
+ if log_level is None:
347
+ log_level = "ERROR"
348
+ else:
349
+ if not isinstance(log_level, str):
350
+ raise TypeError("'log_level' must be of type 'str'")
351
+
352
+ # Delete whitespace and convert to upper case.
353
+ log_level = log_level.upper().replace(" ", "")
354
+
355
+ # Validate the log level.
356
+ if not log_level in _logger._core.levels.keys():
357
+ raise ValueError(
358
+ f"Unsupported logging level '{log_level}'. Options are: {', '.join(_logger._core.levels.keys())}"
359
+ )
360
+ self._log_level = log_level
361
+
362
+ # Validate the log file.
363
+
364
+ if log_file is not None:
365
+ if not isinstance(log_file, str):
366
+ raise TypeError("'log_file' must be of type 'str'")
367
+
368
+ # Try to create the directory.
369
+ dirname = _os.path.dirname(log_file)
370
+ if dirname != "":
371
+ try:
372
+ _os.makedirs(dirname, exist_ok=True)
373
+ except:
374
+ raise IOError(
375
+ f"Unable to create directory for log file: {log_file}"
376
+ )
377
+ self._log_file = _os.path.abspath(log_file)
378
+ else:
379
+ self._log_file = _sys.stderr
380
+
381
+ # Update the logger.
382
+ _logger.remove()
383
+ _logger.add(self._log_file, level=self._log_level)
384
+
385
+ # Validate the PyTorch device.
386
+ if device is not None:
387
+ if not isinstance(device, str):
388
+ msg = "'device' must be of type 'str'"
389
+ _logger.error(msg)
390
+ raise TypeError(msg)
391
+ # Strip whitespace and convert to lower case.
392
+ device = device.lower().replace(" ", "")
393
+ # See if the user has specified a GPU index.
394
+ if device.startswith("cuda"):
395
+ try:
396
+ device, index = device.split(":")
397
+ except:
398
+ index = 0
399
+
400
+ # Make sure the GPU device index is valid.
401
+ try:
402
+ index = int(index)
403
+ except:
404
+ msg = f"Invalid GPU index: {index}"
405
+ _logger.error(msg)
406
+ raise ValueError(msg)
407
+
408
+ if not device in self._supported_devices:
409
+ msg = f"Unsupported device '{device}'. Options are: {', '.join(self._supported_devices)}"
410
+ _logger.error(msg)
411
+ raise ValueError(msg)
412
+ # Create the full CUDA device string.
413
+ if device == "cuda":
414
+ device = f"cuda:{index}"
415
+ # Set the device.
416
+ self._device = _torch.device(device)
417
+ else:
418
+ # Default to CUDA, if available.
419
+ self._device = _torch.device(
420
+ "cuda" if _torch.cuda.is_available() else "cpu"
421
+ )
422
+
423
+ # Validate the MM charges.
424
+ if mm_charges is not None:
425
+ # Convert lists/tuples to NumPy arrays.
426
+ if isinstance(mm_charges, (list, tuple)):
427
+ mm_charges = _np.array(mm_charges)
428
+ if isinstance(mm_charges, _np.ndarray):
429
+ if mm_charges.dtype != _np.float64:
430
+ msg = "'mm_charges' must have dtype 'float64'"
431
+ _logger.error(msg)
432
+ raise TypeError(msg)
433
+ else:
434
+ self._mm_charges = mm_charges
435
+
436
+ elif isinstance(mm_charges, str):
437
+ # Convert to an absolute path.
438
+ mm_charges = _os.path.abspath(mm_charges)
439
+
440
+ if not _os.path.isfile(mm_charges):
441
+ msg = f"Unable to locate 'mm_charges' file: {mm_charges}"
442
+ _logger.error(msg)
443
+ raise IOError(msg)
444
+
445
+ # Read the charges into a list.
446
+ charges = []
447
+ with open(mm_charges, "r") as f:
448
+ for line in f:
449
+ try:
450
+ charges.append(float(line.strip()))
451
+ except:
452
+ msg = f"Unable to read 'mm_charges' from file: {mm_charges}"
453
+ _logger.error(msg)
454
+ raise ValueError(msg)
455
+ self._mm_charges = _np.array(charges)
456
+
457
+ else:
458
+ msg = "'mm_charges' must be of type 'numpy.ndarray' or 'str'"
459
+ _logger.error(msg)
460
+ raise TypeError(msg)
461
+ else:
462
+ self._mm_charges = None
463
+
464
+ self.box = box
465
+
466
+ if qm_charge is not None:
467
+ try:
468
+ qm_charge = int(qm_charge)
469
+ except:
470
+ msg = "'qm_charge' must be of type 'int'"
471
+ _logger.error(msg)
472
+ raise TypeError(msg)
473
+ self._qm_charge = qm_charge
474
+
475
+ if not isinstance(mult, int) or isinstance(mult, bool):
476
+ msg = "'mult' must be of type 'int'"
477
+ _logger.error(msg)
478
+ raise TypeError(msg)
479
+ if mult < 1:
480
+ msg = "'mult' must be greater than or equal to 1"
481
+ _logger.error(msg)
482
+ raise ValueError(msg)
483
+ self._mult = mult
484
+
485
+ # Create the EMLE model instance.
486
+ self._emle = _EMLE(
487
+ model=model,
488
+ method=method,
489
+ alpha_mode=alpha_mode,
490
+ mm_charges=self._mm_charges,
491
+ qm_charge=self._qm_charge,
492
+ device=self._device,
493
+ )
494
+
495
+ # Validate the backend(s).
496
+ if backend is not None:
497
+ if isinstance(backend, (tuple, list)):
498
+ if not len(backend) == 2:
499
+ msg = "If 'backend' is a list or tuple, it must have length 2"
500
+ _logger.error(msg)
501
+ raise ValueError(msg)
502
+ if not all(isinstance(x, str) for x in backend):
503
+ msg = "If 'backend' is a list or tuple, all elements must be of type 'str'"
504
+ _logger.error(msg)
505
+ raise TypeError(msg)
506
+ elif isinstance(backend, str):
507
+ # Strip whitespace and convert to lower case.
508
+ backend = backend.lower().replace(" ", "")
509
+ backend = tuple(backend.split(","))
510
+ if len(backend) > 2:
511
+ msg = "If 'backend' is a string, it must contain at most two comma-separated values"
512
+ _logger.error(msg)
513
+ raise ValueError(msg)
514
+ else:
515
+ msg = "'backend' must be of type 'str', or a tuple of 'str' types"
516
+ _logger.error(msg)
517
+ raise TypeError(msg)
518
+
519
+ formatted_backends = []
520
+ for b in backend:
521
+ # Strip whitespace and convert to lower case.
522
+ b = b.lower().replace(" ", "")
523
+ if not b in self._supported_backends:
524
+ msg = f"Unsupported backend '{b}'. Options are: {', '.join(self._supported_backends)}"
525
+ _logger.error(msg)
526
+ raise ValueError(msg)
527
+ formatted_backends.append(b)
528
+ self._backend = formatted_backends
529
+ else:
530
+ self._backend = None
531
+
532
+ if use_dipoles:
533
+ for backend in formatted_backends:
534
+ if backend != "emle-mace":
535
+ msg = f"Static dipoles can only be used with emle-mace backend"
536
+ _logger.error(msg)
537
+ raise ValueError(msg)
538
+
539
+ self._use_dipoles = use_dipoles
540
+
541
+ # Validate the external backend.
542
+ if external_backend is not None:
543
+ if not isinstance(external_backend, str):
544
+ msg = "'external_backend' must be of type 'str'"
545
+ _logger.error(msg)
546
+ raise TypeError(msg)
547
+
548
+ if plugin_path is None:
549
+ plugin_path = "."
550
+
551
+ if not isinstance(plugin_path, str):
552
+ msg = "'plugin_path' must be of type 'str'"
553
+ _logger.error(msg)
554
+ raise TypeError(msg)
555
+
556
+ # Convert to an absolute path.
557
+ abs_plugin_path = _os.path.abspath(plugin_path)
558
+
559
+ if not _os.path.isdir(abs_plugin_path):
560
+ msg = f"Unable to locate plugin directory: {plugin_path}"
561
+ _logger.error(msg)
562
+ raise IOError(msg)
563
+ self._plugin_path = abs_plugin_path
564
+
565
+ # Strip whitespace.
566
+ external_backend = external_backend.replace(" ", "")
567
+
568
+ # Split the module and function names.
569
+ try:
570
+ function = external_backend.split(".")[-1]
571
+ module = external_backend.replace("." + function, "")
572
+ except:
573
+ msg = f"Unable to parse 'external_backend' callback string: {external_backend}"
574
+ _logger.error(msg)
575
+ raise ValueError(msg)
576
+
577
+ # Try to import the module.
578
+ try:
579
+ from importlib import import_module
580
+
581
+ module = import_module(module)
582
+ except:
583
+ try:
584
+ import sys
585
+
586
+ # Try adding the plugin directory to the path.
587
+ sys.path.append(plugin_path)
588
+ module = import_module(module)
589
+ sys.path.pop()
590
+ except:
591
+ msg = f"Unable to import module '{module}'"
592
+ _logger.error(msg)
593
+ raise ImportError(msg)
594
+
595
+ # Bind the function to the class.
596
+ self._external_backend = getattr(module, function)
597
+
598
+ # Flag that an external backend is being used.
599
+ self._is_external_backend = True
600
+
601
+ # Set the backed to "external".
602
+ self._backend = "external"
603
+
604
+ if parm7 is not None:
605
+ if not isinstance(parm7, str):
606
+ msg = "'parm7' must be of type 'str'"
607
+ _logger.error(msg)
608
+ raise ValueError(msg)
609
+
610
+ # Convert to an absolute path.
611
+ abs_parm7 = _os.path.abspath(parm7)
612
+
613
+ # Make sure the file exists.
614
+ if not _os.path.isfile(abs_parm7):
615
+ msg = f"Unable to locate the 'parm7' file: '{parm7}'"
616
+ raise IOError(msg)
617
+
618
+ self._parm7 = abs_parm7
619
+
620
+ # Validate the QM XYZ file options.
621
+
622
+ if qm_xyz_file is None:
623
+ qm_xyz_file = "qm.xyz"
624
+ else:
625
+ if not isinstance(qm_xyz_file, str):
626
+ msg = "'qm_xyz_file' must be of type 'str'"
627
+ _logger.error(msg)
628
+ raise TypeError(msg)
629
+ self._qm_xyz_file = qm_xyz_file
630
+
631
+ if pc_xyz_file is None:
632
+ pc_xyz_file = "pc.xyz"
633
+ else:
634
+ if not isinstance(pc_xyz_file, str):
635
+ msg = "'pc_xyz_file' must be of type 'str'"
636
+ _logger.error(msg)
637
+ raise TypeError(msg)
638
+ self._pc_xyz_file = pc_xyz_file
639
+
640
+ if qm_xyz_frequency is None:
641
+ qm_xyz_frequency = 0
642
+ else:
643
+ try:
644
+ qm_xyz_frequency = int(qm_xyz_frequency)
645
+ except:
646
+ msg = "'qm_xyz_frequency' must be of type 'int'"
647
+ _logger.error(msg)
648
+ raise TypeError(msg)
649
+ if qm_xyz_frequency < 0:
650
+ msg = "'qm_xyz_frequency' must be greater than or equal to 0"
651
+ _logger.error(msg)
652
+ raise ValueError(msg)
653
+ self._qm_xyz_frequency = qm_xyz_frequency
654
+
655
+ # Validate the supported QM charges, multiplicities and states.
656
+ declared = {}
657
+ for name, value in (
658
+ ("model_charges", model_charges),
659
+ ("model_mults", model_mults),
660
+ ("model_states", model_states),
661
+ ):
662
+ if value is None:
663
+ declared[name] = None
664
+ continue
665
+ if isinstance(value, str) or not hasattr(value, "__iter__"):
666
+ values = None
667
+ else:
668
+ values = list(value)
669
+ if values is None or not all(
670
+ isinstance(x, (int, _np.integer)) and not isinstance(x, bool)
671
+ for x in values
672
+ ):
673
+ msg = f"'{name}' must be a list of int"
674
+ _logger.error(msg)
675
+ raise TypeError(msg)
676
+ declared[name] = tuple(int(x) for x in values)
677
+ model_charges = declared["model_charges"]
678
+ model_mults = declared["model_mults"]
679
+ model_states = declared["model_states"]
680
+
681
+ # Validate and create the backend(s).
682
+ self._backends = []
683
+ if self._backend is not None and not self._is_external_backend:
684
+ for backend in self._backend:
685
+ if backend == "torchani":
686
+ from .models import ANI2xEMLE as _ANI2xEMLE
687
+
688
+ ani2x_emle = _ANI2xEMLE(
689
+ emle_model=model,
690
+ emle_method=method,
691
+ alpha_mode=alpha_mode,
692
+ mm_charges=self._mm_charges,
693
+ qm_charge=self._qm_charge,
694
+ model_index=ani2x_model_index,
695
+ device=self._device,
696
+ )
697
+
698
+ # Convert to TorchScript.
699
+ b = _torch.jit.script(ani2x_emle).eval()
700
+
701
+ # Store the model index.
702
+ self._ani2x_model_index = ani2x_model_index
703
+
704
+ # Initialise the MACEMLE model.
705
+ elif backend in ["mace", "emle-mace"]:
706
+ if backend == "mace":
707
+ from .models import MACEEMLE as _MACEEMLE
708
+
709
+ mace_emle = _MACEEMLE(
710
+ emle_model=model,
711
+ emle_method=method,
712
+ alpha_mode=alpha_mode,
713
+ mm_charges=self._mm_charges,
714
+ qm_charge=self._qm_charge,
715
+ mace_model=mace_model,
716
+ device=self._device,
717
+ )
718
+ else: # emle-mace
719
+ from .models import MACEEMLEJoint as _MACEEMLE
720
+
721
+ mace_emle = _MACEEMLE(
722
+ emle_model=model,
723
+ emle_method=method,
724
+ use_dipoles=self._use_dipoles,
725
+ mm_charges=self._mm_charges,
726
+ qm_charge=self._qm_charge,
727
+ mace_model=mace_model,
728
+ device=self._device,
729
+ )
730
+
731
+ # Convert to TorchScript.
732
+ b = _torch.jit.script(mace_emle).eval()
733
+
734
+ # Store the MACE model.
735
+ self._mace_model = mace_model
736
+
737
+ elif backend == "ace":
738
+ try:
739
+ # Import directly from module since the import is so slow.
740
+ from ._backends._ace import ACE
741
+
742
+ b = ACE(ace_model)
743
+ except:
744
+ msg = "Unable to create ACE backend. Please ensure PyJulip is installed."
745
+ _logger.error(msg)
746
+ raise RuntimeError(msg)
747
+
748
+ elif backend == "orca":
749
+ try:
750
+ from ._backends import ORCA
751
+
752
+ b = ORCA(orca_path, template=orca_template)
753
+ self._orca_path = b._exe
754
+ self._orca_template = b._template
755
+ except Exception as e:
756
+ msg = f"Unable to create ORCA backend: {e}"
757
+ _logger.error(msg)
758
+ raise RuntimeError(msg)
759
+
760
+ elif backend == "deepmd":
761
+ try:
762
+ from ._backends import DeePMD
763
+ from functools import partial
764
+
765
+ b = DeePMD(
766
+ model=deepmd_model,
767
+ deviation=deepmd_deviation,
768
+ deviation_threshold=deepmd_deviation_threshold,
769
+ )
770
+ b.calculate = partial(b.calculate, box=self.box)
771
+
772
+ self._deepmd_model = b._model
773
+ self._deepmd_deviation = b._deviation
774
+ self._deepmd_deviation_threshold = b._deviation_threshold
775
+ except Exception as e:
776
+ msg = f"Unable to create DeePMD backend: {e}"
777
+ _logger.error(msg)
778
+ raise RuntimeError(msg)
779
+
780
+ elif backend == "sqm":
781
+ try:
782
+ from ._backends import SQM
783
+
784
+ b = SQM(parm7, theory=sqm_theory)
785
+ self._sqm_theory = b._theory
786
+ except Exception as e:
787
+ msg = f"Unable to create SQM backend: {e}"
788
+ _logger.error(msg)
789
+ raise RuntimeError(msg)
790
+
791
+ elif backend == "xtb":
792
+ try:
793
+ from ._backends import XTB
794
+
795
+ b = XTB()
796
+ except Exception as e:
797
+ msg = f"Unable to create XTB backend: {e}"
798
+ _logger.error(msg)
799
+ raise RuntimeError(msg)
800
+
801
+ elif backend == "aimnet2":
802
+ try:
803
+ from ._backends import AIMNet2
804
+
805
+ b = AIMNet2(model=aimnet2_model, device=self._device)
806
+ except Exception as e:
807
+ msg = f"Unable to create AIMNet2 backend: {e}"
808
+ _logger.error(msg)
809
+ raise RuntimeError(msg)
810
+
811
+ elif backend == "omnip2x":
812
+ try:
813
+ from ._backends import OMNIP2x
814
+
815
+ b = OMNIP2x(model=omnip2x_model, device=self._device)
816
+ except Exception as e:
817
+ msg = f"Unable to create OMNI-P2x backend: {e}"
818
+ _logger.error(msg)
819
+ raise RuntimeError(msg)
820
+
821
+ elif backend == "sander":
822
+ try:
823
+ from ._backends import Sander
824
+
825
+ b = Sander(parm7)
826
+ except Exception as e:
827
+ msg = f"Unable to create Sander backend: {e}"
828
+ _logger.error(msg)
829
+ raise RuntimeError(msg)
830
+
831
+ # Append the backend to the list.
832
+ self._backends.append(b)
833
+
834
+ # The Torch and external backends have no inputs.
835
+ for b in self._backends:
836
+ if isinstance(b, _torch.nn.Module):
837
+ b.charges, b.mults, b.states = (0,), (1,), (0,)
838
+ self._external_supported = _SimpleNamespace(charges=(0,), mults=(1,), states=(0,))
839
+
840
+ # Apply the supported values that the user declares.
841
+ targets = [self._external_supported] if self._is_external_backend else self._backends
842
+ for b in targets:
843
+ if model_charges is not None:
844
+ b.charges = tuple(model_charges)
845
+ if model_mults is not None:
846
+ b.mults = tuple(model_mults)
847
+ if model_states is not None:
848
+ b.states = tuple(model_states)
849
+
850
+ self._electronic_state = 0
851
+ if electronic_state is not None:
852
+ self.set_electronic_state(electronic_state)
853
+
854
+ if qbc_deviation is not None:
855
+ if not isinstance(qbc_deviation, str):
856
+ raise TypeError("'deviation' must be of type 'str'")
857
+
858
+ self._qbc_deviation = qbc_deviation
859
+
860
+ if qbc_deviation_threshold is not None:
861
+ try:
862
+ qbc_deviation_threshold = float(qbc_deviation_threshold)
863
+ except:
864
+ raise TypeError("'deviation_threshold' must be of type 'float'")
865
+
866
+ self._qbc_deviation_threshold = qbc_deviation_threshold
867
+ else:
868
+ self._qbc_deviation = None
869
+ self._qbc_deviation_threshold = None
870
+
871
+ if restart is not None:
872
+ if not isinstance(restart, bool):
873
+ msg = "'restart' must be of type 'bool'"
874
+ _logger.error(msg)
875
+ raise TypeError(msg)
876
+ else:
877
+ restart = False
878
+ self._restart = restart
879
+
880
+ # Validate the interpolation lambda parameter.
881
+ if lambda_interpolate is not None:
882
+ self._is_interpolate = True
883
+ self.set_lambda_interpolate(lambda_interpolate)
884
+
885
+ # Make sure a topology file has been set.
886
+ if parm7 is None:
887
+ msg = "'parm7' must be specified when interpolating"
888
+ _logger.error(msg)
889
+ raise ValueError(msg)
890
+
891
+ # Make sure MM charges for the QM region have been set.
892
+ if mm_charges is None:
893
+ msg = "'mm_charges' are required when interpolating"
894
+ _logger.error(msg)
895
+ raise ValueError(msg)
896
+
897
+ # Make sure indices for the QM region have been passed.
898
+ if qm_indices is None:
899
+ msg = "'qm_indices' must be specified when interpolating"
900
+ _logger.error(msg)
901
+ raise ValueError(msg)
902
+
903
+ # Validate the indices. Note that we don't check that the are valid, only
904
+ # that they are the correct type.
905
+ if isinstance(qm_indices, list):
906
+ if not all(isinstance(x, int) for x in qm_indices):
907
+ msg = "'qm_indices' must be a list of 'int' types"
908
+ _logger.error(msg)
909
+ raise TypeError(msg)
910
+ self._qm_indices = qm_indices
911
+ elif isinstance(qm_indices, str):
912
+ # Convert to an absolute path.
913
+ qm_indices = _os.path.abspath(qm_indices)
914
+
915
+ if not _os.path.isfile(qm_indices):
916
+ msg = f"Unable to locate 'qm_indices' file: {qm_indices}"
917
+ _logger.error(msg)
918
+ raise IOError(msg)
919
+
920
+ # Read the indices into a list.
921
+ indices = []
922
+ with open(qm_indices, "r") as f:
923
+ for line in f:
924
+ try:
925
+ indices.append(int(line.strip()))
926
+ except:
927
+ msg = f"Unable to read 'qm_indices' from file: {qm_indices}"
928
+ _logger.error(msg)
929
+ raise ValueError(msg)
930
+ self._qm_indices = indices
931
+ else:
932
+ msg = "'qm_indices' must be of type 'list' or 'str'"
933
+ _logger.error(msg)
934
+ raise TypeError(msg)
935
+
936
+ # Make sure the number of interpolation steps has been set if more
937
+ # than one lambda value has been specified.
938
+ if len(self._lambda_interpolate) == 2:
939
+ if interpolate_steps is None:
940
+ msg = "'interpolate_steps' must be specified when interpolating between two lambda values"
941
+ _logger.error(msg)
942
+ raise ValueError(msg)
943
+ else:
944
+ try:
945
+ interpolate_steps = int(interpolate_steps)
946
+ except:
947
+ msg = "'interpolate_steps' must be of type 'int'"
948
+ _logger.error(msg)
949
+ raise TypeError(msg)
950
+ if interpolate_steps < 0:
951
+ msg = "'interpolate_steps' must be greater than or equal to 0"
952
+ _logger.error(msg)
953
+ raise ValueError(msg)
954
+ self._interpolate_steps = interpolate_steps
955
+
956
+ # Create an MM EMLE model for interpolation.
957
+ self._emle_mm = _EMLE(
958
+ model=model,
959
+ alpha_mode=alpha_mode,
960
+ method="mm",
961
+ mm_charges=self._mm_charges,
962
+ device=self._device,
963
+ )
964
+
965
+ else:
966
+ self._is_interpolate = False
967
+
968
+ if energy_frequency is None:
969
+ energy_frequency = 0
970
+
971
+ if not isinstance(energy_frequency, int):
972
+ msg = "'energy_frequency' must be of type 'int'"
973
+ _logger.error(msg)
974
+ raise TypeError(msg)
975
+ else:
976
+ self._energy_frequency = energy_frequency
977
+
978
+ if energy_file is None:
979
+ energy_file = "emle_energy.txt"
980
+ else:
981
+ if not isinstance(energy_file, str):
982
+ msg = "'energy_file' must be of type 'str'"
983
+ _logger.error(msg)
984
+ raise TypeError(msg)
985
+
986
+ # Try to create the directory.
987
+ dirname = _os.path.dirname(energy_file)
988
+ if dirname != "":
989
+ try:
990
+ _os.makedirs(dirname, exist_ok=True)
991
+ except:
992
+ msg = f"Unable to create directory for energy file: {energy_file}"
993
+ _logger.error(msg)
994
+ raise IOError(msg)
995
+
996
+ self._energy_file = _os.path.abspath(energy_file)
997
+
998
+ if save_settings is None:
999
+ save_settings = True
1000
+
1001
+ if not isinstance(save_settings, bool):
1002
+ msg = "'save_settings' must be of type 'bool'"
1003
+ _logger.error(msg)
1004
+ raise TypeError(msg)
1005
+ else:
1006
+ self._save_settings = save_settings
1007
+
1008
+ if orca_template is not None:
1009
+ if not isinstance(orca_template, str):
1010
+ msg = "'orca_template' must be of type 'str'"
1011
+ _logger.error(msg)
1012
+ raise TypeError(msg)
1013
+ # Convert to an absolute path.
1014
+ abs_orca_template = _os.path.abspath(orca_template)
1015
+
1016
+ if not _os.path.isfile(abs_orca_template):
1017
+ msg = f"Unable to locate ORCA template file: '{orca_template}'"
1018
+ _logger.error(msg)
1019
+ raise IOError(msg)
1020
+ self._orca_template = abs_orca_template
1021
+ else:
1022
+ self._orca_template = None
1023
+
1024
+ # Intialise the maximum number of MM atoms that have been seen.
1025
+ self._max_mm_atoms = 0
1026
+
1027
+ # Initialise the number of steps. (Calls to the calculator.)
1028
+ self._step = 0
1029
+
1030
+ # Flag whether to skip logging the first call to the server. This is
1031
+ # used to avoid writing duplicate energy records since sander will call
1032
+ # orca on startup when not performing a restart simulation, i.e. not
1033
+ # just after each integration step.
1034
+ self._is_first_step = not self._restart
1035
+
1036
+ # Get the settings from the internal EMLE model.
1037
+ self._model = self._emle._model
1038
+ self._method = self._emle._method
1039
+ self._alpha_mode = self._emle._alpha_mode
1040
+ # Store the settings as a dictionary.
1041
+ self._settings = {
1042
+ "model": None if model is None else self._model,
1043
+ "method": self._method,
1044
+ "alpha_mode": self._alpha_mode,
1045
+ "qm_charge": self._qm_charge,
1046
+ "mult": self._mult,
1047
+ "backend": self._backend,
1048
+ "external_backend": None if external_backend is None else external_backend,
1049
+ "mm_charges": None if mm_charges is None else self._mm_charges.tolist(),
1050
+ "box": self.box,
1051
+ "deepmd_model": deepmd_model,
1052
+ "deepmd_deviation": deepmd_deviation,
1053
+ "deepmd_deviation_threshold": deepmd_deviation_threshold,
1054
+ "qm_xyz_file": qm_xyz_file,
1055
+ "pc_xyz_file": pc_xyz_file,
1056
+ "qm_xyz_frequency": qm_xyz_frequency,
1057
+ "ani2x_model_index": ani2x_model_index,
1058
+ "mace_model": None if mace_model is None else self._mace_model,
1059
+ "qbc_deviation": qbc_deviation,
1060
+ "qbc_deviation_threshold": qbc_deviation_threshold,
1061
+ "parm7": parm7,
1062
+ "qm_indices": None if qm_indices is None else self._qm_indices,
1063
+ "orca_path": orca_path,
1064
+ "sqm_theory": sqm_theory,
1065
+ "aimnet2_model": aimnet2_model,
1066
+ "omnip2x_model": omnip2x_model,
1067
+ "electronic_state": electronic_state,
1068
+ "model_charges": None if model_charges is None else list(model_charges),
1069
+ "model_mults": None if model_mults is None else list(model_mults),
1070
+ "model_states": None if model_states is None else list(model_states),
1071
+ "lambda_interpolate": lambda_interpolate,
1072
+ "interpolate_steps": interpolate_steps,
1073
+ "restart": restart,
1074
+ "device": device,
1075
+ "orca_template": None if orca_template is None else self._orca_template,
1076
+ "plugin_path": plugin_path,
1077
+ "energy_frequency": energy_frequency,
1078
+ "energy_file": energy_file,
1079
+ "log_level": self._log_level,
1080
+ "log_file": log_file,
1081
+ }
1082
+
1083
+ # Write to a YAML file.
1084
+ if save_settings:
1085
+ with open("emle_settings.yaml", "w") as f:
1086
+ _yaml.dump(self._settings, f)
1087
+
1088
+ def run(self, path=None):
1089
+ """
1090
+ Calculate the energy and gradients.
1091
+
1092
+ Parameters
1093
+ ----------
1094
+
1095
+ path: str
1096
+ Path to the working directory of the sander process.
1097
+ """
1098
+
1099
+ if path is not None:
1100
+ if not isinstance(path, str):
1101
+ msg = "'path' must be of type 'str'"
1102
+ _logger.error(msg)
1103
+ raise TypeError(msg)
1104
+ if not _os.path.isdir(path):
1105
+ msg = f"sander process path does not exist: {path}"
1106
+ _logger.error(msg)
1107
+ raise ValueError(msg)
1108
+ orca_input = f"{path}/orc_job.inp"
1109
+ else:
1110
+ orca_input = "orc_job.inp"
1111
+
1112
+ # Parse the ORCA input file.
1113
+ (
1114
+ dirname,
1115
+ charge,
1116
+ mult,
1117
+ atoms,
1118
+ atomic_numbers,
1119
+ xyz_qm,
1120
+ xyz_mm,
1121
+ charges_mm,
1122
+ xyz_file_qm,
1123
+ ) = self._parse_orca_input(orca_input)
1124
+
1125
+ # Make sure that the number of QM atoms matches the number of MM charges
1126
+ # when using mm embedding.
1127
+ if self._method == "mm":
1128
+ if len(xyz_qm) != len(self._mm_charges):
1129
+ msg = (
1130
+ "MM embedding is specified but the number of atoms in the QM "
1131
+ f"region ({len(xyz_qm)}) doesn't match the number of MM charges "
1132
+ f"({len(self._mm_charges)})"
1133
+ )
1134
+ _logger.error(msg)
1135
+ raise ValueError(msg)
1136
+
1137
+ # Compute the energy and gradients.
1138
+ E_vac, grad_vac, E_tot, grad_qm, grad_mm, lam, E_mm, E_emle, _ = (
1139
+ self._calculate_energy_and_gradients(
1140
+ atomic_numbers,
1141
+ charges_mm,
1142
+ xyz_qm,
1143
+ xyz_mm,
1144
+ atoms=atoms,
1145
+ charge=charge,
1146
+ mult=mult,
1147
+ state=self._electronic_state,
1148
+ )
1149
+ )
1150
+
1151
+ # Create the file names for the ORCA format output.
1152
+ filename = _os.path.splitext(orca_input)[0]
1153
+ engrad = filename + ".engrad"
1154
+ pcgrad = filename + ".pcgrad"
1155
+
1156
+ # Store the number of MM atoms.
1157
+ num_mm_atoms = len(charges_mm)
1158
+
1159
+ with open(engrad, "w") as f:
1160
+ # Write the energy.
1161
+ f.write("# The current total energy in Eh\n")
1162
+ f.write("#\n")
1163
+ f.write(f"{E_tot:22.12f}\n")
1164
+
1165
+ # Write the QM gradients.
1166
+ f.write("# The current gradient in Eh/bohr\n")
1167
+ f.write("#\n")
1168
+ for x, y, z in grad_qm:
1169
+ f.write(f"{x:16.10f}\n{y:16.10f}\n{z:16.10f}\n")
1170
+
1171
+ if grad_mm is not None:
1172
+ with open(pcgrad, "w") as f:
1173
+ # Write the number of MM atoms.
1174
+ f.write(f"{num_mm_atoms}\n")
1175
+ # Write the MM gradients.
1176
+ for x, y, z in grad_mm[:num_mm_atoms]:
1177
+ f.write(f"{x:17.12f}{y:17.12f}{z:17.12f}\n")
1178
+
1179
+ # Log energies to file.
1180
+ if (
1181
+ self._energy_frequency > 0
1182
+ and not self._is_first_step
1183
+ and self._step % self._energy_frequency == 0
1184
+ ):
1185
+ with open(self._energy_file, "a+") as f:
1186
+ # Write the header.
1187
+ if self._step == 0:
1188
+ if self._is_interpolate:
1189
+ f.write(
1190
+ f"#{'Step':>9}{'λ':>22}{'E(λ) (Eh)':>22}{'E(λ=0) (Eh)':>22}{'E(λ=1) (Eh)':>22}\n"
1191
+ )
1192
+ else:
1193
+ f.write(f"#{'Step':>9}{'E_vac (Eh)':>22}{'E_tot (Eh)':>22}\n")
1194
+ # Write the record.
1195
+ if self._is_interpolate:
1196
+ f.write(
1197
+ f"{self._step:>10}{lam:22.12f}{E_tot:22.12f}{E_mm:22.12f}{E_emle:22.12f}\n"
1198
+ )
1199
+ else:
1200
+ f.write(f"{self._step:>10}{E_vac:22.12f}{E_tot:22.12f}\n")
1201
+
1202
+ # Write out the QM region to the xyz trajectory file.
1203
+ if self._qm_xyz_frequency > 0 and self._step % self._qm_xyz_frequency == 0:
1204
+ atoms = _ase.Atoms(positions=xyz_qm, numbers=atomic_numbers)
1205
+ atoms.info["total_charge"] = charge
1206
+ if hasattr(self._backend, "_max_f_std"):
1207
+ atoms.info = {"max_f_std": self._backend._max_f_std}
1208
+ if (
1209
+ self._backends
1210
+ and getattr(self._backends[0], "emle_values", None) is not None
1211
+ ):
1212
+ for key, value in self._backends[0].emle_values.items():
1213
+ assert (
1214
+ len(value) == 1
1215
+ ), "emle_values xyz export assumes a single frame per forward() call"
1216
+ atoms.arrays[key] = value[0].detach().cpu().numpy()
1217
+ _ase_io.write(self._qm_xyz_file, atoms, append=True)
1218
+
1219
+ pc_data = _np.hstack((charges_mm[:, None], xyz_mm))
1220
+ pc_data = pc_data[pc_data[:, 0] != 0]
1221
+ with open(self._pc_xyz_file, "a") as f:
1222
+ f.write(f"{len(pc_data)}\n")
1223
+ _np.savetxt(f, pc_data, fmt="%14.6f")
1224
+ f.write("\n")
1225
+
1226
+ # Increment the step counter.
1227
+ if self._is_first_step:
1228
+ self._is_first_step = False
1229
+ else:
1230
+ self._step += 1
1231
+ _logger.info(f"Step: {self._step}")
1232
+
1233
+ def _calculate_energy_and_gradients(
1234
+ self,
1235
+ atomic_numbers,
1236
+ charges_mm,
1237
+ xyz_qm,
1238
+ xyz_mm,
1239
+ atoms=None,
1240
+ cell=None,
1241
+ charge=0,
1242
+ mult=1,
1243
+ state=0,
1244
+ ):
1245
+ """
1246
+ Calculate the energy and gradients.
1247
+
1248
+ Parameters
1249
+ ----------
1250
+
1251
+ atomic_numbers: numpy.ndarray, (N_QM_ATOMS)
1252
+ Atomic numbers for the QM region.
1253
+
1254
+ charges_mm: numpy.ndarray, (N_MM_ATOMS)
1255
+ The charges on the MM atoms.
1256
+
1257
+ xyz_qm: numpy.ndarray, (N_QM_ATOMS, 3)
1258
+ The QM coordinates.
1259
+
1260
+ xyz_mm: numpy.ndarray, (N_MM_ATOMS, 3)
1261
+ The MM coordinates.
1262
+
1263
+ atoms: ase.Atoms
1264
+ The atoms object for the QM region.
1265
+
1266
+ cell: numpy.ndarray, (3, 3)
1267
+ The simulation cell vectors.
1268
+
1269
+ charge: int
1270
+ The total charge of the QM region.
1271
+
1272
+ mult: int
1273
+ The spin multiplicity of the QM region.
1274
+
1275
+ state: int
1276
+ The electronic state index (0 is the ground state).
1277
+
1278
+ Returns
1279
+ -------
1280
+
1281
+ E_tot: float
1282
+ The total energy.
1283
+
1284
+ grad_qm: numpy.ndarray, (N_QM_ATOMS, 3)
1285
+ The QM gradients.
1286
+
1287
+ grad_mm: numpy.ndarray, (N_MM_ATOMS, 3)
1288
+ The MM gradients.
1289
+ """
1290
+
1291
+ # Update the maximum number of MM atoms if this is the largest seen.
1292
+ num_mm_atoms = len(charges_mm)
1293
+ if num_mm_atoms > self._max_mm_atoms:
1294
+ self._max_mm_atoms = num_mm_atoms
1295
+
1296
+ # Pad the MM coordinates and charges arrays to avoid re-jitting.
1297
+ if self._max_mm_atoms > num_mm_atoms:
1298
+ num_pad = self._max_mm_atoms - num_mm_atoms
1299
+ xyz_mm_pad = num_pad * [[0.0, 0.0, 0.0]]
1300
+ charges_mm_pad = num_pad * [0.0]
1301
+ xyz_mm = _np.append(xyz_mm, xyz_mm_pad, axis=0)
1302
+ charges_mm = _np.append(charges_mm, charges_mm_pad)
1303
+
1304
+ # First try to use the specified backend to compute in vacuo
1305
+ # energies and (optionally) gradients.
1306
+
1307
+ # Base and delta-learning correction models.
1308
+ base_model = None
1309
+ delta_model = None
1310
+
1311
+ # Zero the in vacuo energy and gradients.
1312
+ E_vac = 0.0
1313
+ grad_vac = _np.zeros_like(xyz_qm)
1314
+
1315
+ # Internal backends.
1316
+ if not self._is_external_backend:
1317
+ if self._backend is not None:
1318
+ # Enumerate the backends.
1319
+ for i, backend in enumerate(self._backends):
1320
+ # This is an EMLE Torch model.
1321
+ if isinstance(backend, _torch.nn.Module):
1322
+ try:
1323
+ _check_supported(backend, charge, mult, state)
1324
+ except ValueError as e:
1325
+ msg = f"Failed to calculate in vacuo energies using {self._backend[i]} backend: {e}"
1326
+ _logger.error(msg)
1327
+ raise RuntimeError(msg)
1328
+
1329
+ # Base backend is an EMLE Torch model.
1330
+ if i == 0:
1331
+ base_model = backend
1332
+ # Delta-learning correction is applied using an EMLE Torch model.
1333
+ else:
1334
+ delta_model = backend
1335
+ # This is a non-Torch backend.
1336
+ else:
1337
+ try:
1338
+ # Add the in vacuo energy and gradients to the total.
1339
+ energy, forces = backend(
1340
+ atomic_numbers,
1341
+ xyz_qm,
1342
+ qm_charge=charge,
1343
+ mult=mult,
1344
+ state=state,
1345
+ )
1346
+ E_vac += energy[0]
1347
+ grad_vac += -forces[0]
1348
+ except Exception as e:
1349
+ msg = f"Failed to calculate in vacuo energies using {self._backend[i]} backend: {e}"
1350
+ _logger.error(msg)
1351
+ raise RuntimeError(msg)
1352
+
1353
+ # External backend.
1354
+ else:
1355
+ try:
1356
+ _check_supported(self._external_supported, charge, mult, state)
1357
+ if atoms is None:
1358
+ atoms = _ase.Atoms(positions=xyz_qm, numbers=atomic_numbers)
1359
+ E_vac, grad_vac = self._external_backend(atoms)
1360
+ except Exception as e:
1361
+ msg = (
1362
+ f"Failed to calculate in vacuo energies using external backend: {e}"
1363
+ )
1364
+ _logger.error(msg)
1365
+ raise RuntimeError(msg)
1366
+
1367
+ # Store a copy of the atomic numbers and QM coordinates as NumPy arrays.
1368
+ atomic_numbers_np = atomic_numbers
1369
+ xyz_qm_np = xyz_qm
1370
+
1371
+ # Convert inputs to Torch tensors.
1372
+ atomic_numbers = _torch.tensor(
1373
+ atomic_numbers, dtype=_torch.int64, device=self._device
1374
+ )
1375
+ charges_mm = _torch.tensor(
1376
+ charges_mm, dtype=_torch.float32, device=self._device, requires_grad=True
1377
+ )
1378
+ xyz_qm = _torch.tensor(
1379
+ xyz_qm, dtype=_torch.float32, device=self._device, requires_grad=True
1380
+ )
1381
+ xyz_mm = _torch.tensor(
1382
+ xyz_mm, dtype=_torch.float32, device=self._device, requires_grad=True
1383
+ )
1384
+ if cell is not None:
1385
+ cell = _torch.tensor(cell, dtype=_torch.float32, device=self._device)
1386
+
1387
+ # Are there any MM atoms?
1388
+ allow_unused = len(charges_mm) == 0
1389
+
1390
+ # Apply delta-learning corrections using an EMLE model.
1391
+ if delta_model is not None:
1392
+ model = delta_model.original_name
1393
+ try:
1394
+ # Create null MM inputs.
1395
+ null_charges_mm = _torch.zeros_like(charges_mm)
1396
+ null_xyz_mm = _torch.zeros_like(xyz_mm)
1397
+
1398
+ # Compute the energy.
1399
+ E = delta_model(
1400
+ atomic_numbers, null_charges_mm, xyz_qm, null_xyz_mm, cell, charge
1401
+ )
1402
+
1403
+ # Compute the gradients.
1404
+ dE_dxyz_qm = _torch.autograd.grad(E.sum(), xyz_qm)
1405
+
1406
+ # Compute the delta correction.
1407
+ delta_E = E.sum().detach().cpu().numpy()
1408
+ delta_grad = dE_dxyz_qm[0].cpu().numpy() * _BOHR_TO_ANGSTROM
1409
+
1410
+ # Apply the correction.
1411
+ E_vac += delta_E
1412
+ grad_vac += delta_grad
1413
+
1414
+ except Exception as e:
1415
+ msg = f"Failed to apply delta-learning correction using {model} model: {e}"
1416
+ _logger.error(msg)
1417
+ raise RuntimeError(msg)
1418
+
1419
+ # Compute embedding energy and gradients.
1420
+ if base_model is None:
1421
+ try:
1422
+ if len(xyz_mm) > 0:
1423
+ E = self._emle(
1424
+ atomic_numbers, charges_mm, xyz_qm, xyz_mm, cell, charge
1425
+ )
1426
+ dE_dxyz_qm, dE_dxyz_mm, dE_dcharges_mm = _torch.autograd.grad(
1427
+ E.sum(), (xyz_qm, xyz_mm, charges_mm), allow_unused=allow_unused
1428
+ )
1429
+ dE_dxyz_qm_bohr = dE_dxyz_qm.cpu().numpy() * _BOHR_TO_ANGSTROM
1430
+ dE_dxyz_mm_bohr = (
1431
+ dE_dxyz_mm.cpu().numpy() * _BOHR_TO_ANGSTROM
1432
+ if dE_dxyz_mm is not None
1433
+ else _np.zeros_like(xyz_mm.cpu().numpy())
1434
+ )
1435
+
1436
+ # Compute the total energy and gradients.
1437
+ E_tot = E_vac + E.sum().detach().cpu().numpy()
1438
+ grad_qm = dE_dxyz_qm_bohr + grad_vac
1439
+ grad_mm = dE_dxyz_mm_bohr
1440
+ else:
1441
+ dE_dcharges_mm = None
1442
+ E_tot = E_vac
1443
+ grad_qm = grad_vac
1444
+ grad_mm = None
1445
+
1446
+ except Exception as e:
1447
+ msg = f"Failed to compute EMLE energies and gradients: {e}"
1448
+ _logger.error(msg)
1449
+ raise RuntimeError(msg)
1450
+
1451
+ # Compute in vacuo and embedding energies and gradients in one go using
1452
+ # the EMLE Torch models
1453
+ else:
1454
+ model = base_model.original_name
1455
+ try:
1456
+ with _torch.jit.optimized_execution(False):
1457
+ E = base_model(
1458
+ atomic_numbers, charges_mm, xyz_qm, xyz_mm, cell, charge
1459
+ )
1460
+ dE_dxyz_qm, dE_dxyz_mm, dE_dcharges_mm = _torch.autograd.grad(
1461
+ E.sum(),
1462
+ (xyz_qm, xyz_mm, charges_mm),
1463
+ allow_unused=allow_unused,
1464
+ )
1465
+
1466
+ grad_qm = grad_vac + dE_dxyz_qm.cpu().numpy() * _BOHR_TO_ANGSTROM
1467
+ grad_mm = (
1468
+ dE_dxyz_mm.cpu().numpy() * _BOHR_TO_ANGSTROM
1469
+ if dE_dxyz_mm is not None
1470
+ else _np.zeros_like(xyz_mm.cpu().numpy())
1471
+ )
1472
+ E_vac, E_static, E_induced = E.sum(axis=1).detach().cpu().numpy()
1473
+ E_tot = E_vac + E_static + E_induced
1474
+
1475
+ except Exception as e:
1476
+ msg = f"Failed to compute {model} energies and gradients: {e}"
1477
+ _logger.error(msg)
1478
+ raise RuntimeError(msg)
1479
+
1480
+ if self._qbc_deviation:
1481
+ E_std = _torch.std(base_model._E_vac_qbc).item()
1482
+ max_f_std = _torch.max(_torch.std(base_model._grads_qbc, axis=0)).item()
1483
+ with open(self._qbc_deviation, "a") as f:
1484
+ f.write(f"{E_std:12.5f}{max_f_std:12.5f}\n")
1485
+ if (
1486
+ self._qbc_deviation_threshold
1487
+ and max_f_std > self._qbc_deviation_threshold
1488
+ ):
1489
+ msg = "Force deviation threshold reached!"
1490
+ raise ValueError(msg)
1491
+
1492
+ if self._is_interpolate:
1493
+ # Compute the in vacuo MM energy and gradients for the QM region.
1494
+ if self._backend != None:
1495
+ from ._backends import Sander
1496
+
1497
+ # Create a Sander backend instance.
1498
+ backend = Sander(self._parm7)
1499
+
1500
+ # Compute the in vacuo MM energy and forces for the QM region.
1501
+ energy, forces = backend(atomic_numbers_np, xyz_qm_np)
1502
+ E_mm_qm_vac = energy[0]
1503
+ grad_mm_qm_vac = -forces[0]
1504
+
1505
+ # If no backend is specified, then the MM energy and gradients are zero.
1506
+ else:
1507
+ E_mm_qm_vac, grad_mm_qm_vac = 0.0, _np.zeros_like(xyz_qm_np)
1508
+
1509
+ # Compute the embedding contributions.
1510
+ E = self._emle_mm(atomic_numbers, charges_mm, xyz_qm, xyz_mm, cell, charge)
1511
+ dE_dxyz_qm, dE_dxyz_mm, dE_dcharges_mm_mm = _torch.autograd.grad(
1512
+ E.sum(), (xyz_qm, xyz_mm, charges_mm), allow_unused=allow_unused
1513
+ )
1514
+ dE_dxyz_qm_bohr = dE_dxyz_qm.cpu().numpy() * _BOHR_TO_ANGSTROM
1515
+ dE_dxyz_mm_bohr = (
1516
+ dE_dxyz_mm.cpu().numpy() * _BOHR_TO_ANGSTROM
1517
+ if dE_dxyz_mm is not None
1518
+ else _np.zeros_like(xyz_mm.cpu().numpy())
1519
+ )
1520
+
1521
+ # Store the the MM and EMLE energies. The MM energy is an approximation.
1522
+ E_mm = E_mm_qm_vac + E.sum().detach().cpu().numpy()
1523
+ E_emle = E_tot
1524
+
1525
+ # Work out the current value of lambda.
1526
+ if len(self._lambda_interpolate) == 1:
1527
+ lam = self._lambda_interpolate[0]
1528
+ else:
1529
+ offset = int(not self._restart)
1530
+ lam = self._lambda_interpolate[0] + (
1531
+ (self._step / (self._interpolate_steps - offset))
1532
+ ) * (self._lambda_interpolate[1] - self._lambda_interpolate[0])
1533
+ if lam < 0.0:
1534
+ lam = 0.0
1535
+ elif lam > 1.0:
1536
+ lam = 1.0
1537
+
1538
+ # Calculate the lambda weighted energy and gradients.
1539
+ E_tot = lam * E_tot + (1 - lam) * E_mm
1540
+ grad_qm = lam * grad_qm + (1 - lam) * (grad_mm_qm_vac + dE_dxyz_qm_bohr)
1541
+ grad_mm = lam * grad_mm + (1 - lam) * dE_dxyz_mm_bohr
1542
+
1543
+ # Compute the lambda-weighted dE/dcharges_mm for the chain-rule correction.
1544
+ if dE_dcharges_mm is not None and dE_dcharges_mm_mm is not None:
1545
+ dE_dcharges_mm_interp = (
1546
+ lam * dE_dcharges_mm.cpu().numpy()
1547
+ + (1 - lam) * dE_dcharges_mm_mm.cpu().numpy()
1548
+ )
1549
+ elif dE_dcharges_mm is not None:
1550
+ dE_dcharges_mm_interp = lam * dE_dcharges_mm.cpu().numpy()
1551
+ elif dE_dcharges_mm_mm is not None:
1552
+ dE_dcharges_mm_interp = (1 - lam) * dE_dcharges_mm_mm.cpu().numpy()
1553
+ else:
1554
+ dE_dcharges_mm_interp = None
1555
+
1556
+ return (
1557
+ E_vac,
1558
+ grad_vac,
1559
+ E_tot,
1560
+ grad_qm,
1561
+ grad_mm,
1562
+ lam,
1563
+ E_mm,
1564
+ E_emle,
1565
+ dE_dcharges_mm_interp,
1566
+ )
1567
+
1568
+ dE_dcharges_mm_np = (
1569
+ dE_dcharges_mm.cpu().numpy() if dE_dcharges_mm is not None else None
1570
+ )
1571
+ return (
1572
+ E_vac,
1573
+ grad_vac,
1574
+ E_tot,
1575
+ grad_qm,
1576
+ grad_mm,
1577
+ None,
1578
+ None,
1579
+ None,
1580
+ dE_dcharges_mm_np,
1581
+ )
1582
+
1583
+ def set_lambda_interpolate(self, lambda_interpolate):
1584
+ """
1585
+ Set the value of the lambda interpolation parameter. Note the server must
1586
+ already be in 'interpolation' mode, i.e. the user must have specified an
1587
+ initial value for 'lambda_interpolate' in the constructor.
1588
+
1589
+ Parameters
1590
+ ----------
1591
+
1592
+ lambda_interpolate: float, [float, float]
1593
+ The value of lambda to use for interpolating between pure MM
1594
+ (lambda=0) and ML/MM (lambda=1) potentials.and. If two lambda
1595
+ values are specified, the calculator will gradually interpolate
1596
+ between them when called multiple times.
1597
+ """
1598
+ if not self._is_interpolate:
1599
+ msg = "Server is not in interpolation mode!"
1600
+ _logger.error(msg)
1601
+ raise Exception(msg)
1602
+ elif (
1603
+ self._lambda_interpolate is not None and len(self._lambda_interpolate) == 2
1604
+ ):
1605
+ msg = "Cannot set lambda when interpolating between two lambda values!"
1606
+ _logger.error(msg)
1607
+ raise Exception(msg)
1608
+
1609
+ if isinstance(lambda_interpolate, (list, tuple)):
1610
+ if len(lambda_interpolate) not in [1, 2]:
1611
+ msg = "'lambda_interpolate' must be a single value or a list/tuple of two values"
1612
+ _logger.error(msg)
1613
+ raise ValueError(msg)
1614
+ try:
1615
+ lambda_interpolate = [float(x) for x in lambda_interpolate]
1616
+ except:
1617
+ msg = "'lambda_interpolate' must be a single value or a list/tuple of two values"
1618
+ _logger.error(msg)
1619
+ raise TypeError(msg)
1620
+ if not all(0.0 <= x <= 1.0 for x in lambda_interpolate):
1621
+ msg = "'lambda_interpolate' must be between 0 and 1 for both values"
1622
+ _logger.error(msg)
1623
+ raise ValueError(msg)
1624
+
1625
+ if len(lambda_interpolate) == 2:
1626
+ if _np.isclose(lambda_interpolate[0], lambda_interpolate[1], atol=1e-6):
1627
+ msg = "The two values of 'lambda_interpolate' must be different"
1628
+ _logger.error(msg)
1629
+ raise ValueError(msg)
1630
+ self._lambda_interpolate = lambda_interpolate
1631
+
1632
+ elif isinstance(lambda_interpolate, (int, float)):
1633
+ lambda_interpolate = float(lambda_interpolate)
1634
+ if not 0.0 <= lambda_interpolate <= 1.0:
1635
+ msg = "'lambda_interpolate' must be between 0 and 1"
1636
+ _logger.error(msg)
1637
+ raise ValueError(msg)
1638
+ self._lambda_interpolate = [lambda_interpolate]
1639
+
1640
+ # Reset the first step flag.
1641
+ self._is_first_step = not self._restart
1642
+
1643
+ def set_electronic_state(self, state):
1644
+ """
1645
+ Set the electronic state.
1646
+
1647
+ Parameters
1648
+ ----------
1649
+
1650
+ state: int
1651
+ The electronic state index (0 is the ground state).
1652
+ """
1653
+ if not isinstance(state, int) or isinstance(state, bool):
1654
+ msg = "'state' must be of type 'int'"
1655
+ _logger.error(msg)
1656
+ raise TypeError(msg)
1657
+ if state < 0:
1658
+ msg = "'state' must be greater than or equal to 0"
1659
+ _logger.error(msg)
1660
+ raise ValueError(msg)
1661
+ self._electronic_state = state
1662
+
1663
+ def _sire_callback(
1664
+ self, atomic_numbers, charges_mm, xyz_qm, xyz_mm, cell=None, idx_mm=None
1665
+ ):
1666
+ """
1667
+ A callback function to be used with Sire.
1668
+
1669
+ Parameters
1670
+ ----------
1671
+
1672
+ atomic_numbers: [float]
1673
+ A list of atomic numbers for the QM region.
1674
+
1675
+ charges_mm: [float]
1676
+ The charges on the MM atoms.
1677
+
1678
+ xyz_qm: [[float, float, float]]
1679
+ The coordinates of the QM atoms in Angstrom.
1680
+
1681
+ xyz_mm: [[float, float, float]]
1682
+ The coordinates of the MM atoms in Angstrom.
1683
+
1684
+ cell: [[float, float, float], [float, float, float], [float, float, float]]
1685
+ The simulation box vectors.
1686
+
1687
+ idx_mm: [int]
1688
+ A list of indices of the MM atoms in the QM/MM region.
1689
+ Note that len(idx_mm) <= len(charges_mm) since it only
1690
+ contains the indices of true MM atoms, not link atoms
1691
+ or virtual charges.
1692
+
1693
+ Returns
1694
+ -------
1695
+
1696
+ energy: float
1697
+ The energy in kJ/mol.
1698
+
1699
+ force_qm: [[float, float, float]]
1700
+ The forces on the QM atoms in kJ/mol/nanometer.
1701
+
1702
+ force_mm: [[float, float, float]]
1703
+ The forces on the MM atoms in kJ/mol/nanometer.
1704
+
1705
+ dE_dcharges_mm: [float], optional
1706
+ The derivative of the total energy with respect to the effective MM
1707
+ charges in kJ/mol/e. Only present when MM atoms exist. Used by
1708
+ Sire to apply the chain-rule force correction for the positional
1709
+ dependence of the charge switching function.
1710
+ """
1711
+
1712
+ # For performance, we assume that the input is already validated.
1713
+
1714
+ # Convert to NumPy arrays.
1715
+ atomic_numbers = _np.array(atomic_numbers)
1716
+ charges_mm = _np.array(charges_mm)
1717
+ xyz_qm = _np.array(xyz_qm)
1718
+ xyz_mm = _np.array(xyz_mm)
1719
+ if cell is not None:
1720
+ cell = _np.array(cell)
1721
+
1722
+ # Make sure that the number of QM atoms matches the number of MM charges
1723
+ # when using mm embedding.
1724
+ if self._method == "mm":
1725
+ if len(xyz_qm) != len(self._mm_charges):
1726
+ msg = (
1727
+ "MM embedding is specified but the number of atoms in the "
1728
+ f"QM region ({len(xyz_qm)}) doesn't match the number of MM "
1729
+ f"charges ({len(self._mm_charges)})"
1730
+ )
1731
+ _logger.error(msg)
1732
+ raise ValueError(msg)
1733
+
1734
+ # Compute the energy and gradients.
1735
+ E_vac, grad_vac, E_tot, grad_qm, grad_mm, lam, E_mm, E_emle, dE_dcharges_mm = (
1736
+ self._calculate_energy_and_gradients(
1737
+ atomic_numbers,
1738
+ charges_mm,
1739
+ xyz_qm,
1740
+ xyz_mm,
1741
+ cell=cell,
1742
+ charge=self._qm_charge,
1743
+ mult=self._mult,
1744
+ state=self._electronic_state,
1745
+ )
1746
+ )
1747
+
1748
+ # Store the number of MM atoms.
1749
+ num_mm_atoms = len(charges_mm)
1750
+
1751
+ # Log energies to file.
1752
+ if (
1753
+ self._energy_frequency > 0
1754
+ and not self._is_first_step
1755
+ and self._step % self._energy_frequency == 0
1756
+ ):
1757
+ with open(self._energy_file, "a+") as f:
1758
+ # Write the header.
1759
+ if self._step == 0:
1760
+ if self._is_interpolate:
1761
+ f.write(
1762
+ f"#{'Step':>9}{'λ':>22}{'E(λ) (Eh)':>22}{'E(λ=0) (Eh)':>22}{'E(λ=1) (Eh)':>22}\n"
1763
+ )
1764
+ else:
1765
+ f.write(f"#{'Step':>9}{'E_vac (Eh)':>22}{'E_tot (Eh)':>22}\n")
1766
+ # Write the record.
1767
+ if self._is_interpolate:
1768
+ f.write(
1769
+ f"{self._step:>10}{lam:22.12f}{E_tot:22.12f}{E_mm:22.12f}{E_emle:22.12f}\n"
1770
+ )
1771
+ else:
1772
+ f.write(f"{self._step:>10}{E_vac:22.12f}{E_tot:22.12f}\n")
1773
+
1774
+ # Increment the step counter.
1775
+ if self._is_first_step:
1776
+ self._is_first_step = False
1777
+ else:
1778
+ self._step += 1
1779
+
1780
+ # Write out the QM region to the xyz trajectory file.
1781
+ if self._qm_xyz_frequency > 0 and self._step % self._qm_xyz_frequency == 0:
1782
+ atoms = _ase.Atoms(positions=xyz_qm, numbers=atomic_numbers)
1783
+ if hasattr(self._backend, "_max_f_std"):
1784
+ atoms.info = {"max_f_std": self._backend._max_f_std}
1785
+ _ase_io.write(self._qm_xyz_file, atoms, append=True)
1786
+
1787
+ pc_data = _np.hstack((charges_mm[:, None], xyz_mm))
1788
+ pc_data = pc_data[pc_data[:, 0] != 0]
1789
+ with open(self._pc_xyz_file, "a") as f:
1790
+ f.write(f"{len(pc_data)}\n")
1791
+ _np.savetxt(f, pc_data, fmt="%14.6f")
1792
+ f.write("\n")
1793
+
1794
+ # Return the energy and forces in OpenMM units, plus optional dE/dcharges_mm
1795
+ # for the chain-rule switching correction in Sire's C++ QM force.
1796
+ result = (
1797
+ E_tot.item() * _HARTREE_TO_KJ_MOL,
1798
+ (-grad_qm * _HARTREE_TO_KJ_MOL * _NANOMETER_TO_BOHR).tolist(),
1799
+ (
1800
+ -grad_mm[:num_mm_atoms] * _HARTREE_TO_KJ_MOL * _NANOMETER_TO_BOHR
1801
+ ).tolist(),
1802
+ )
1803
+ if dE_dcharges_mm is not None:
1804
+ # dE_dcharges_mm is in Hartree/e; convert to kJ/mol/e to match the
1805
+ # energy units expected by the chain-rule correction in Sire.
1806
+ result = result + (
1807
+ (dE_dcharges_mm[:num_mm_atoms] * _HARTREE_TO_KJ_MOL).tolist(),
1808
+ )
1809
+ return result
1810
+
1811
+ @staticmethod
1812
+ def _parse_orca_input(orca_input):
1813
+ """
1814
+ Internal method to parse an ORCA input file.
1815
+
1816
+ Parameters
1817
+ ----------
1818
+
1819
+ orca_input: str
1820
+ The path to the ORCA input file.
1821
+
1822
+ Returns
1823
+ -------
1824
+
1825
+ dirname: str
1826
+ The path to the directory containing the ORCA file.
1827
+
1828
+ charge: int
1829
+ The charge on the QM region.
1830
+
1831
+ mult: int
1832
+ The spin multiplicity of the QM region.
1833
+
1834
+ atoms: ase.Atoms
1835
+ The atoms in the QM region.
1836
+
1837
+ atomic_numbers: numpy.array
1838
+ The atomic numbers of the atoms in the QM region.
1839
+
1840
+ xyz_qm: numpy.array
1841
+ The positions of the atoms in the QM region.
1842
+
1843
+ xyz_mm: numpy.array
1844
+ The positions of the atoms in the MM region.
1845
+
1846
+ charges_mm: numpy.array
1847
+ The charges of the atoms in the MM region.
1848
+
1849
+ xyz_file_qm: str
1850
+ The path to the QM xyz file.
1851
+ """
1852
+
1853
+ if not isinstance(orca_input, str):
1854
+ msg = "'orca_input' must be of type 'str'"
1855
+ _logger.error(msg)
1856
+ raise TypeError(msg)
1857
+ if not _os.path.isfile(orca_input):
1858
+ msg = f"Unable to locate the ORCA input file: {orca_input}"
1859
+ _logger.error(msg)
1860
+ raise IOError(msg)
1861
+
1862
+ # Store the directory name for the file. Files within the input file
1863
+ # should be relative to this.
1864
+ dirname = _os.path.dirname(orca_input)
1865
+ if dirname:
1866
+ dirname += "/"
1867
+ else:
1868
+ dirname = "./"
1869
+
1870
+ # Null the required information from the input file.
1871
+ charge = None
1872
+ mult = None
1873
+ xyz_file_qm = None
1874
+ xyz_file_mm = None
1875
+
1876
+ # Parse the file for the required information.
1877
+ with open(orca_input, "r") as f:
1878
+ for line in f:
1879
+ if line.startswith("%pointcharges"):
1880
+ xyz_file_mm = str(line.split()[1]).replace('"', "")
1881
+ elif line.startswith("*xyzfile"):
1882
+ data = line.split()
1883
+ charge = int(data[1])
1884
+ mult = int(data[2])
1885
+ xyz_file_qm = str(data[3]).replace('"', "")
1886
+
1887
+ # Validate that the information was found.
1888
+
1889
+ if charge is None:
1890
+ msg = "Unable to determine QM charge from ORCA input."
1891
+ _logger.error(msg)
1892
+ raise ValueError(msg)
1893
+
1894
+ if mult is None:
1895
+ msg = "Unable to determine QM spin multiplicity from ORCA input."
1896
+ _logger.error(msg)
1897
+ raise ValueError(msg)
1898
+
1899
+ if mult < 1:
1900
+ msg = f"Invalid QM spin multiplicity in ORCA input: {mult}"
1901
+ _logger.error(msg)
1902
+ raise ValueError(msg)
1903
+
1904
+ if xyz_file_qm is None:
1905
+ msg = "Unable to determine QM xyz file from ORCA input."
1906
+ _logger.error(msg)
1907
+ raise ValueError(msg)
1908
+ else:
1909
+ if not _os.path.isfile(xyz_file_qm):
1910
+ xyz_file_qm = dirname + xyz_file_qm
1911
+ if not _os.path.isfile(xyz_file_qm):
1912
+ msg = f"Unable to locate QM xyz file: {xyz_file_qm}"
1913
+ _logger.error(msg)
1914
+ raise ValueError(msg)
1915
+
1916
+ if xyz_file_mm is None:
1917
+ msg = "No MM xyz file in ORCA input, assuming no MM region."
1918
+ _logger.error(msg)
1919
+ else:
1920
+ if not _os.path.isfile(xyz_file_mm):
1921
+ xyz_file_mm = dirname + xyz_file_mm
1922
+ if not _os.path.isfile(xyz_file_mm):
1923
+ msg = f"Unable to locate MM xyz file: {xyz_file_mm}"
1924
+ _logger.error(msg)
1925
+ raise ValueError(msg)
1926
+
1927
+ # Process the QM xyz file.
1928
+ try:
1929
+ atoms = _ase_io.read(xyz_file_qm)
1930
+ except:
1931
+ msg = f"Unable to read QM xyz file: {xyz_file_qm}"
1932
+ _logger.error(msg)
1933
+ raise IOError(msg)
1934
+
1935
+ charges_mm = []
1936
+ xyz_mm = []
1937
+
1938
+ # Process the MM xyz file. (Charges plus coordinates.)
1939
+ if xyz_file_mm is not None:
1940
+ with open(xyz_file_mm, "r") as f:
1941
+ for line in f:
1942
+ data = line.split()
1943
+
1944
+ # MM records have four entries per line.
1945
+ if len(data) == 4:
1946
+ try:
1947
+ charges_mm.append(float(data[0]))
1948
+ except:
1949
+ msg = "Unable to parse MM charge."
1950
+ _logger.error(msg)
1951
+ raise ValueError(msg)
1952
+
1953
+ try:
1954
+ xyz_mm.append([float(x) for x in data[1:]])
1955
+ except:
1956
+ msg = "Unable to parse MM coordinates."
1957
+ _logger.error(msg)
1958
+ raise ValueError(msg)
1959
+
1960
+ # Convert to NumPy arrays.
1961
+ charges_mm = _np.array(charges_mm)
1962
+ xyz_mm = _np.array(xyz_mm)
1963
+
1964
+ return (
1965
+ dirname,
1966
+ charge,
1967
+ mult,
1968
+ atoms,
1969
+ atoms.get_atomic_numbers(),
1970
+ atoms.get_positions(),
1971
+ xyz_mm,
1972
+ charges_mm,
1973
+ xyz_file_qm,
1974
+ )