fescape 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. fescape/__init__.py +13 -0
  2. fescape/_omm.py +302 -0
  3. fescape/_vendor/__init__.py +1 -0
  4. fescape/_vendor/openmmml/PROVENANCE.md +122 -0
  5. fescape/_vendor/openmmml/__init__.py +3 -0
  6. fescape/_vendor/openmmml/mechanicalembedding.py +201 -0
  7. fescape/_vendor/openmmml/utilities.py +587 -0
  8. fescape/_window.py +150 -0
  9. fescape/analysis.py +147 -0
  10. fescape/backends.py +382 -0
  11. fescape/cli.py +278 -0
  12. fescape/committor.py +315 -0
  13. fescape/config.py +408 -0
  14. fescape/cv.py +146 -0
  15. fescape/cvsetup.py +341 -0
  16. fescape/defaults.py +106 -0
  17. fescape/engine_defaults.py +142 -0
  18. fescape/engines/__init__.py +11 -0
  19. fescape/engines/base.py +99 -0
  20. fescape/engines/mock.py +144 -0
  21. fescape/engines/openmm_nnpmm.py +794 -0
  22. fescape/fe_core.py +229 -0
  23. fescape/fes.py +621 -0
  24. fescape/geometry.py +165 -0
  25. fescape/md.py +46 -0
  26. fescape/mlmm.py +471 -0
  27. fescape/openmmml_adapter.py +453 -0
  28. fescape/parallel.py +456 -0
  29. fescape/pipeline.py +366 -0
  30. fescape/recorder.py +128 -0
  31. fescape/render.py +13 -0
  32. fescape/resdata.py +63 -0
  33. fescape/rxnpath.py +98 -0
  34. fescape/smwst.py +244 -0
  35. fescape/stages/__init__.py +1 -0
  36. fescape/stages/equilibrate.py +95 -0
  37. fescape/stages/minimize.py +44 -0
  38. fescape/stages/prepared.py +34 -0
  39. fescape/stages/release.py +52 -0
  40. fescape/stages/swarm.py +152 -0
  41. fescape/stages/ts.py +331 -0
  42. fescape/stages/umbrella.py +219 -0
  43. fescape/string.py +136 -0
  44. fescape/swarm.py +70 -0
  45. fescape/tsextract.py +362 -0
  46. fescape-0.1.0.dist-info/METADATA +396 -0
  47. fescape-0.1.0.dist-info/RECORD +51 -0
  48. fescape-0.1.0.dist-info/WHEEL +5 -0
  49. fescape-0.1.0.dist-info/entry_points.txt +2 -0
  50. fescape-0.1.0.dist-info/licenses/LICENSE +21 -0
  51. fescape-0.1.0.dist-info/top_level.txt +1 -0
fescape/__init__.py ADDED
@@ -0,0 +1,13 @@
1
+ """FEScape — molecular dynamics and reaction free-energy sampling.
2
+
3
+ Two MD-ready endpoint structures -> MM minimize / equilibrate / restraint-release -> ML/MM swarm-string
4
+ FES via its built-in SMwST/FES engine. Stage-orchestration design adapted from mdflow. See docs/DESIGN.md.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ __version__ = "0.1.0"
9
+
10
+ from .config import load_config
11
+ from .pipeline import run_pipeline, status, STAGES
12
+
13
+ __all__ = ["load_config", "run_pipeline", "status", "STAGES", "__version__"]
fescape/_omm.py ADDED
@@ -0,0 +1,302 @@
1
+ """Shared OpenMM helpers for the MM endpoint-prep stages (minimize / equilibrate / release).
2
+
3
+ Full periodic solvent box, PME, nothing frozen. Equilibration uses HARMONIC POSITIONAL RESTRAINTS on the
4
+ solute heavy atoms (a CustomExternalForce tether with a tunable global force constant) — a restraint, not
5
+ freezing (mass stays nonzero, atoms still move). The OpenMM platform is selected CUDA->OpenCL->CPU with
6
+ the fallback wrapping Context creation (the old-driver PTX error fires there).
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ from typing import List, Optional
12
+
13
+ import numpy as np
14
+
15
+ NM_PER_ANG = 0.1
16
+ KJ_PER_KCAL = 4.184
17
+ KPOS_KCALA2_TO_KJNM2 = KJ_PER_KCAL / (NM_PER_ANG ** 2) # kcal/mol/Ang^2 -> kJ/mol/nm^2
18
+
19
+
20
+ def _omm():
21
+ import openmm as mm
22
+ import openmm.app as app
23
+ from openmm import unit
24
+ return mm, app, unit
25
+
26
+
27
+ def make_system(prmtop: str, md_cfg: dict):
28
+ """Build the MM System (PME) from an AMBER prmtop. Callers add restraint/barostat forces as needed."""
29
+ mm, app, unit = _omm()
30
+ prm = app.AmberPrmtopFile(prmtop)
31
+ cmap = {"HBonds": app.HBonds, "AllBonds": app.AllBonds, None: None, "None": None}
32
+ ckey = md_cfg.get("constraints", "HBonds")
33
+ if ckey not in cmap:
34
+ raise ValueError(f"unknown md.constraints {ckey!r}; use 'HBonds', 'AllBonds', or 'None'")
35
+ constraints = cmap[ckey]
36
+ # MM prep is PURE MM — no bond is made or broken here and the reactive region is frozen outright, so
37
+ # SHAKE + SETTLE are legitimate and buy a 2 fs timestep. The ML/MM production engine is the opposite
38
+ # case and defaults to no constraints at all (see engine_defaults.ENGINE_KW).
39
+ system = prm.createSystem(nonbondedMethod=app.PME,
40
+ nonbondedCutoff=md_cfg["nonbonded_cutoff_nm"] * unit.nanometer,
41
+ constraints=constraints,
42
+ rigidWater=bool(md_cfg.get("rigid_water", True)))
43
+ return prm, system
44
+
45
+
46
+ def input_box(inp):
47
+ """Periodic box vectors from an AmberInpcrdFile (.boxVectors) or a PDBFile (topology box). None if absent.
48
+
49
+ PME needs a periodic box; an MD-ready input must carry one. AmberInpcrdFile exposes ``.boxVectors`` while
50
+ PDBFile carries the box on its topology (from CRYST1) — normalize both here."""
51
+ box = getattr(inp, "boxVectors", None)
52
+ if box is None and hasattr(inp, "topology"):
53
+ box = inp.topology.getPeriodicBoxVectors()
54
+ return box
55
+
56
+
57
+ def make_input_whole(inp, topology):
58
+ """Repair wrapped bonded molecules before ordinary MM bonded evaluation."""
59
+ from openmm import unit
60
+ from .geometry import whole_molecules
61
+ box = input_box(inp)
62
+ if box is not None:
63
+ pos = np.asarray(inp.positions.value_in_unit(unit.angstrom), float)
64
+ bonds = [(a.index, b.index) for a, b in topology.bonds()]
65
+ xyz = whole_molecules(pos, bonds, np.asarray(box.value_in_unit(unit.angstrom), float))
66
+ inp.positions = xyz * unit.angstrom
67
+ return inp
68
+
69
+
70
+ def solute_heavy_indices(topology) -> List[int]:
71
+ """Non-solvent, non-ion, non-hydrogen atom indices (for equilibration restraints).
72
+
73
+ Uses the canonical WATER/ION tables (case-insensitive) rather than a short hand-rolled set, so an
74
+ OPC/SPC/TIP-named water or a listed ion is NOT tethered as if it were solute — a stale short list left
75
+ bulk solvent restrained and suppressed its relaxation. Virtual sites (element None) are excluded too."""
76
+ from .resdata import WATER, ION
77
+ solvent = {n.upper() for n in WATER} | {n.upper() for n in ION}
78
+ out = []
79
+ for atom in topology.atoms():
80
+ resn = atom.residue.name.strip().upper()
81
+ if resn in solvent:
82
+ continue
83
+ if atom.element is None or atom.element.symbol == "H": # skip hydrogens AND virtual sites
84
+ continue
85
+ out.append(atom.index)
86
+ return out
87
+
88
+
89
+ def add_position_restraint(system, ref_positions_ang: np.ndarray, atom_indices: List[int]):
90
+ """Harmonic tether of `atom_indices` to ref positions. The global parameter 'kpos' is in OpenMM
91
+ units (kJ/mol/nm^2); callers convert from kcal/mol/Ang^2 via KPOS_KCALA2_TO_KJNM2 before setting it."""
92
+ mm, app, unit = _omm()
93
+ # periodicdistance so a restrained atom that crosses a periodic-image boundary in the NPT box is not
94
+ # evaluated as ~one box length away (a huge spurious force); a plain (x-x0)^2 would do exactly that.
95
+ f = mm.CustomExternalForce("0.5*kpos*periodicdistance(x,y,z,x0,y0,z0)^2")
96
+ f.addGlobalParameter("kpos", 0.0)
97
+ for p in ("x0", "y0", "z0"):
98
+ f.addPerParticleParameter(p)
99
+ ref_nm = np.asarray(ref_positions_ang, float) * NM_PER_ANG
100
+ for i in atom_indices:
101
+ f.addParticle(int(i), [float(ref_nm[i, 0]), float(ref_nm[i, 1]), float(ref_nm[i, 2])])
102
+ system.addForce(f)
103
+ return f
104
+
105
+
106
+ def add_ml_restraint(system, ref_positions_ang: np.ndarray, ml_atoms: List[int], k_kcal: float):
107
+ """Constant positional restraint that HOLDS the reactive region (``ml_atoms``) at its input geometry
108
+ through the whole MM prep. The MM force field cannot represent a reactant's non-equilibrium bonding
109
+ (a not-yet-formed bond sits at the MM equilibrium length), so without this the reactive geometry
110
+ collapses toward the MM minimum during minimize/release; restraining it lets only the solvent relax.
111
+ Uses its own always-on ``kml`` global parameter (independent of the equilibration ``kpos`` ramp)."""
112
+ if k_kcal <= 0 or not ml_atoms:
113
+ return None
114
+ mm, app, unit = _omm()
115
+ f = mm.CustomExternalForce("0.5*kml*periodicdistance(x,y,z,x0,y0,z0)^2")
116
+ f.addGlobalParameter("kml", k_kcal * KPOS_KCALA2_TO_KJNM2)
117
+ for p in ("x0", "y0", "z0"):
118
+ f.addPerParticleParameter(p)
119
+ ref_nm = np.asarray(ref_positions_ang, float) * NM_PER_ANG
120
+ for i in ml_atoms:
121
+ f.addParticle(int(i), [float(ref_nm[i, 0]), float(ref_nm[i, 1]), float(ref_nm[i, 2])])
122
+ system.addForce(f)
123
+ return f
124
+
125
+
126
+ def add_distance_restraints(system, ref_positions_ang: np.ndarray, restraints, box_ang=None):
127
+ """Optional harmonic distance restraints during MM prep (hold a forming/breaking bond at a value).
128
+ Each entry: ``{atoms: [i, j], k: <kcal/mol/Ang^2>, r0: <Ang, optional>}``; when ``r0`` is omitted it
129
+ is taken from THIS endpoint's input geometry, so the reactant holds its distance and the product holds
130
+ its own — no per-endpoint editing needed."""
131
+ if not restraints:
132
+ return None
133
+ mm, app, unit = _omm()
134
+ ref = np.asarray(ref_positions_ang, float)
135
+ f = mm.CustomBondForce("0.5*k*(r-r0)^2")
136
+ periodic = system.usesPeriodicBoundaryConditions()
137
+ f.setUsesPeriodicBoundaryConditions(periodic)
138
+ if periodic and box_ang is None:
139
+ box_ang = np.asarray(system.getDefaultPeriodicBoxVectors().value_in_unit(unit.angstrom))
140
+ from .geometry import minimum_image
141
+ f.addPerBondParameter("k")
142
+ f.addPerBondParameter("r0")
143
+ for rr in restraints:
144
+ i, j = int(rr["atoms"][0]), int(rr["atoms"][1])
145
+ r0_ang = float(rr["r0"]) if rr.get("r0") is not None else float(np.linalg.norm(minimum_image(ref[i] - ref[j], box_ang)))
146
+ k_kjnm2 = float(rr.get("k", 20.0)) * KPOS_KCALA2_TO_KJNM2
147
+ f.addBond(i, j, [k_kjnm2, r0_ang * NM_PER_ANG])
148
+ system.addForce(f)
149
+ return f
150
+
151
+
152
+ def apply_prep_holds(system, ref_positions_ang, ml_atoms, md_cfg: dict, box_ang=None):
153
+ """Hold the reactive region during MM prep so only the solvent/environment relaxes. Default = FREEZE
154
+ the ml_region (particle mass 0): the reactant's not-yet-formed bond sits at the MM equilibrium length,
155
+ and the MM bonded force (~hundreds of kcal/mol/Ang^2) overpowers any soft restraint, so freezing is the
156
+ only thing that actually holds the reactive geometry. Set ``md.freeze_ml_region: false`` for a soft
157
+ positional restraint (``md.ml_restraint_k``) instead. Optional ``md.restraints`` distance restraints are
158
+ always applied. MM PREP ONLY — the FES production never freezes anything."""
159
+ ml_atoms = [int(a) for a in (ml_atoms or [])]
160
+ if md_cfg.get("freeze_ml_region", True):
161
+ for i in ml_atoms:
162
+ system.setParticleMass(i, 0.0)
163
+ else:
164
+ add_ml_restraint(system, ref_positions_ang, ml_atoms, float(md_cfg.get("ml_restraint_k", 10.0)))
165
+ add_distance_restraints(system, ref_positions_ang, md_cfg.get("restraints"), box_ang)
166
+
167
+
168
+ def select_platform(system, make_integrator, *, candidates, precision, positions=None, box=None,
169
+ logger=None):
170
+ """Create a Context on the first usable platform, PROBING one force evaluation so a lazy first-execution
171
+ kernel error also falls back.
172
+
173
+ OpenMM compiles/loads its CUDA kernel modules on the FIRST force evaluation, not at Context creation, so
174
+ on a GPU whose driver is older than the installed CUDA toolkit
175
+ ``CUDA_ERROR_UNSUPPORTED_PTX_VERSION`` fires at the first minimize / integrator.step, AFTER a
176
+ creation-only loop has already committed to CUDA — which crashes the run instead of falling back. The
177
+ ``getState(getEnergy=True)`` probe here forces that kernel load + one force eval inside the ``try``, so
178
+ the error triggers the same fallback to the next platform. All of a platform's kernel modules share one
179
+ nvrtc PTX ISA version, so an energy probe is representative of the integrator/constraint kernels too.
180
+
181
+ The probe MUST run on the run's real starting geometry: pass ``positions`` (and ``box`` for a PME
182
+ system). A probe on default all-zero coordinates would collapse an ML region onto the origin and fail
183
+ the MLIP forward pass for a reason unrelated to the OpenMM platform (a false fallback). ``getState`` is a
184
+ pure read (non-perturbing) and synchronizes, so an async CUDA launch error surfaces in the probe.
185
+ ``make_integrator`` returns a FRESH integrator per attempt (an integrator binds to one Context)."""
186
+ mm, app, unit = _omm()
187
+ worker_device = os.environ.get("FESCAPE_OPENMM_DEVICE_INDEX")
188
+ last = None
189
+ for name in candidates:
190
+ ctx = integ = None
191
+ try:
192
+ plat = mm.Platform.getPlatformByName(name)
193
+ integ = make_integrator()
194
+ ctx = mm.Context(system, integ, plat,
195
+ _platform_properties(name, precision, worker_device))
196
+ if positions is not None:
197
+ ctx.setPositions(positions)
198
+ if box is not None:
199
+ ctx.setPeriodicBoxVectors(*box)
200
+ ctx.computeVirtualSites()
201
+ ctx.getState(getEnergy=True) # PROBE: forces kernel-module load + one force eval on real coords
202
+ return ctx, integ, name
203
+ except Exception as exc:
204
+ last = exc
205
+ if logger:
206
+ logger(f"[platform] {name} unusable ({type(exc).__name__}: {exc}); trying next")
207
+ del ctx, integ
208
+ continue
209
+ raise RuntimeError(f"no usable OpenMM platform from {candidates}; last error: {last}")
210
+
211
+
212
+ def _platform_properties(name: str, precision: str, worker_device=None) -> dict:
213
+ """OpenMM Context properties, including worker pinning for CUDA and OpenCL.
214
+
215
+ A window worker exposes one physical GPU through CUDA_VISIBLE_DEVICES. Both CUDA and NVIDIA OpenCL
216
+ then enumerate that selected GPU as logical device 0.
217
+ """
218
+ if name == "CUDA":
219
+ props = {"CudaPrecision": precision}
220
+ if worker_device is not None:
221
+ props["CudaDeviceIndex"] = "0"
222
+ return props
223
+ if name == "OpenCL":
224
+ props = {"OpenCLPrecision": precision}
225
+ if worker_device is not None:
226
+ props["OpenCLDeviceIndex"] = str(worker_device)
227
+ return props
228
+ return {}
229
+
230
+
231
+ def build_context(system, md_cfg: dict, platform: str = "auto", md_precision: str = "double",
232
+ positions=None, box=None, device: str = "auto", logger=None):
233
+ """Create a LangevinMiddle Context on the first usable platform (CUDA->OpenCL->CPU), probing a force
234
+ eval so a first-execution PTX/kernel error also falls back (see ``select_platform``). Pass ``positions``
235
+ (+ ``box`` for PME) so the probe runs on the real geometry.
236
+
237
+ ``md_precision`` is the OpenMM PLATFORM precision ('double' | 'mixed' | 'single'), resolved from
238
+ ``engine.md_precision`` — separate from the MLIP model precision (``engine.precision``). ``device: cpu``
239
+ forces the CPU platform (a no-GPU box, or a forced-CPU test), mirroring the ML/MM engine."""
240
+ mm, app, unit = _omm()
241
+ if md_precision not in ("double", "mixed", "single"):
242
+ raise ValueError(f"unknown md_precision {md_precision!r}; use 'double', 'mixed', or 'single'")
243
+ if str(device).lower() == "cpu":
244
+ candidates = ["CPU"]
245
+ elif platform != "auto":
246
+ candidates = [platform]
247
+ else:
248
+ candidates = ["CUDA", "OpenCL", "CPU"]
249
+
250
+ def make_integrator():
251
+ return mm.LangevinMiddleIntegrator(md_cfg["temperature_K"] * unit.kelvin,
252
+ md_cfg["friction_per_ps"] / unit.picosecond,
253
+ md_cfg.get("timestep_fs", 2.0) * unit.femtoseconds)
254
+
255
+ return select_platform(system, make_integrator, candidates=candidates, precision=md_precision,
256
+ positions=positions, box=box, logger=logger)
257
+
258
+
259
+ def set_positions(context, positions, box=None):
260
+ mm, app, unit = _omm()
261
+ context.setPositions(positions)
262
+ if box is not None:
263
+ context.setPeriodicBoxVectors(*box)
264
+
265
+
266
+ def _box_from_vectors(bv: np.ndarray) -> List[float]:
267
+ """[a, b, c, alpha, beta, gamma] (Angstrom / degrees) from a 3x3 box-vector matrix.
268
+
269
+ Derives the angles from the vectors rather than assuming 90 degrees, so triclinic and
270
+ truncated-octahedron boxes (Amber's default solvation box, angles ~109.47 deg) round-trip correctly."""
271
+ a, b, c = np.asarray(bv[0]), np.asarray(bv[1]), np.asarray(bv[2])
272
+ la, lb, lc = float(np.linalg.norm(a)), float(np.linalg.norm(b)), float(np.linalg.norm(c))
273
+ _ac = lambda x: float(np.degrees(np.arccos(np.clip(x, -1.0, 1.0)))) # clip: fp roundoff can push |cos|>1 -> NaN
274
+ alpha = _ac(np.dot(b, c) / (lb * lc))
275
+ beta = _ac(np.dot(a, c) / (la * lc))
276
+ gamma = _ac(np.dot(a, b) / (la * lb))
277
+ return [la, lb, lc, alpha, beta, gamma]
278
+
279
+
280
+ def save_rst7(context, prmtop: str, out_path: str) -> None:
281
+ """Write current positions + box to an Amber rst7 via parmed (triclinic-safe box)."""
282
+ from openmm import unit
283
+ import parmed
284
+ st = context.getState(getPositions=True)
285
+ pos = st.getPositions(asNumpy=True).value_in_unit(unit.angstrom)
286
+ if not np.isfinite(np.asarray(pos)).all():
287
+ # A NaN'd MD would otherwise be written and pass the existence-only stage sentinel, silently
288
+ # corrupting the resumable pipeline (garbage FES downstream). Fail here with the likely cause.
289
+ raise ValueError(
290
+ f"non-finite coordinates when writing {out_path}: the MD produced NaN/Inf. Most common cause is "
291
+ f"a raw (never-equilibrated) input box, or too-aggressive equilibration. Pre-equilibrate the box "
292
+ f"(minimize -> gentle temperature ramp -> NPT) before handing it to fescape."
293
+ )
294
+ bv = context.getState().getPeriodicBoxVectors(asNumpy=True).value_in_unit(unit.angstrom)
295
+ s = parmed.load_file(prmtop)
296
+ s.coordinates = np.asarray(pos)
297
+ s.box = _box_from_vectors(np.asarray(bv))
298
+ # atomic: write a temp then rename, so an interrupt (SIGINT) can never leave a half-written rst7
299
+ # that the existence-only stage sentinel would accept as complete.
300
+ tmp = f"{out_path}.tmp"
301
+ s.save(tmp, format="rst7", overwrite=True)
302
+ os.replace(tmp, out_path)
@@ -0,0 +1 @@
1
+ """Locally scoped third-party compatibility code."""
@@ -0,0 +1,122 @@
1
+ # OpenMM-ML mechanical embedding backport
2
+
3
+ Upstream: [openmm/openmm-ml](https://github.com/openmm/openmm-ml), commit
4
+ [`5c78d5ab6843ed0dd024e50123771c482aee4700`](https://github.com/openmm/openmm-ml/commit/5c78d5ab6843ed0dd024e50123771c482aee4700).
5
+ The original MIT notices remain in both bundled Python modules.
6
+
7
+ | Original source | SHA-256 |
8
+ | --- | --- |
9
+ | `embeddings/mechanicalembedding.py` | `eecef97cd31e9c15a505459949fa0d8e43973e06aee3e81c900af1b6658c87f4` |
10
+ | `embeddings/utilities.py` | `8768a70baa8602de6d1afe3acb903ee1da6a992819d3f7645c01883517bda7a2` |
11
+ | `models/asepotential.py` | `78db3a59e8c0493422d010e43efdafdbcaaa5d79a144e4687e6a30f958a8950c` |
12
+
13
+ ## Scope and changes
14
+
15
+ The bundled mechanicalembedding.py and utilities.py preserve the upstream
16
+ mechanical-embedding Hamiltonian, including its fixed-distance hydrogen caps,
17
+ bond/angle/torsion selection, periodic exception convention, and mlLongRange
18
+ handling. The adapter does not expose interpolation; that upstream code remains
19
+ in the source to make the backport comparison straightforward.
20
+
21
+ Local changes to the two upstream modules are limited to:
22
+
23
+ 1. Import utilities through this private package, remove the unused embedding
24
+ factory and base class (OpenMM-ML 1.7 lacks that plugin API). MechanicalEmbedding
25
+ is invoked directly, without editing the installed package or its registries.
26
+ 2. Read the element only for ML link parents, allowing elementless MM-only
27
+ virtual sites. This is the utility portion of upstream contribution
28
+ `7db684ca93c1a3fc568c5fe33bfb65eca9bad060`.
29
+ 3. Pad the independent PME-subtraction force with neutral, zero-LJ particles after
30
+ cap insertion, contribution `9ad7f2b8b640689d0227b40dec086c58540d54df`.
31
+
32
+ The FEScape adapter materializes ML indices once, avoiding the exhausted-iterator
33
+ constraint-removal defect represented by contribution
34
+ `60d95de` without altering installed OpenMM-ML code. It removes internal ML
35
+ constraints after the direct backport call, as the upstream public API does.
36
+
37
+ The small per-instance ASE adapter follows upstream ASEPotentialImpl's
38
+ ASE/energy/force unit conventions. It validates only selected atoms, handles the
39
+ full-state PythonForce API on OpenMM 8.5 and setParticles on newer OpenMM, always
40
+ transfers the live periodic cell, and sets ASE PBC independently of OpenMM PBC.
41
+ The optional coordinate transform must consist of locally constant lattice-vector
42
+ translations; no general coordinate transformation or derivative is inferred.
43
+ Charge and spin multiplicity use FEScape's existing ASE info convention.
44
+ Periodic isolated models automatically coimage selected components using cached
45
+ ML--ML and cap--parent connectivity. The periodic long-range path leaves ASE
46
+ coordinates periodic. Molecular boundary parents must be made whole by the caller
47
+ before OpenMM computes native link-site coordinates.
48
+
49
+ ## Fixed and scaled link atoms
50
+
51
+ `link_mode="fixed"` retains the upstream `LocalCoordinatesSite` unchanged.
52
+ `link_mode="scaled"` constructs the same mechanical system, then replaces only
53
+ its appended link sites with `TwoParticleAverageSite(ML, MM, 1-g, g)`, where
54
+ `g = (radius_ML + radius_H)/(radius_ML + radius_MM)`. The radius table is the
55
+ pinned upstream `COVALENT_RADII`; C=75 pm and H=32 pm give C--C g=107/150
56
+ (approximately 0.7133333333333334). Each actual g and its boundary/cap indices
57
+ are recorded in the returned provenance. g is independent of coordinates.
58
+
59
+ Both installed-native and bundled-backport construction use this same local
60
+ post-construction override. Bonded terms, electrostatic exclusions, atom mapping,
61
+ particle masses and cap topology remain those of upstream mechanical embedding.
62
+ OpenMM distributes the link force to its real parents for the selected virtual
63
+ site definition. Fixed-distance overrides are rejected with scaled mode because
64
+ the requested length does not uniquely define the constant scale convention.
65
+
66
+ The post-construction override is a FEScape extension, not a claim that current
67
+ upstream exposes scaled links. No installed module or registry is modified.
68
+ The original vendored modules are unchanged by this option. A future upstream
69
+ API must be reviewed explicitly before replacing this bounded adapter.
70
+
71
+ Native selection tests for the public embedding/returnInfo API, the required
72
+ PythonForce subset API and the pinned upstream's OpenMM >=8.6.1 minimum. Systems
73
+ with MM-only elementless sites or periodic long-range subtraction plus link
74
+ sites take the corrected backport because the pinned native implementation
75
+ contains the defects above. This conservative routing can be relaxed only with
76
+ source review and regressions when upstream adopts the fixes. Native provenance
77
+ records hashes of the installed modules, since development OpenMM-ML still
78
+ reports version 1.7. The reference SHA is a source baseline, not a claim that an
79
+ arbitrary installed native module has that revision.
80
+
81
+ The Reference tests compare independent electrostatic systems and analytic
82
+ fixed-distance and scaled cap force projections, include finite-difference force
83
+ checks, confirm the different responses to stretching a boundary bond, and check
84
+ native/backport and periodic-image parity for both modes when supported.
85
+ These checks do not establish production MLIP accuracy or MD stability.
86
+
87
+ ## Upstream license and ASE source attribution
88
+
89
+ The following notice also applies to the ASE bridge adapted from
90
+ `models/asepotential.py` (author Peter Eastman, copyright 2026 Stanford University
91
+ and the Authors):
92
+
93
+ ```text
94
+ mechanicalembedding.py: Implements mechanical embedding.
95
+
96
+ This is part of the OpenMM molecular simulation toolkit originating from
97
+ Simbios, the NIH National Center for Physics-Based Simulation of
98
+ Biological Structures at Stanford, funded under the NIH Roadmap for
99
+ Medical Research, grant U54 GM072970. See https://simtk.org.
100
+
101
+ Portions copyright (c) 2026 Stanford University and the Authors.
102
+ Authors: Peter Eastman, Evan Pretti
103
+ Contributors:
104
+
105
+ Permission is hereby granted, free of charge, to any person obtaining a
106
+ copy of this software and associated documentation files (the "Software"),
107
+ to deal in the Software without restriction, including without limitation
108
+ the rights to use, copy, modify, merge, publish, distribute, sublicense,
109
+ and/or sell copies of the Software, and to permit persons to whom the
110
+ Software is furnished to do so, subject to the following conditions:
111
+
112
+ The above copyright notice and this permission notice shall be included in
113
+ all copies or substantial portions of the Software.
114
+
115
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
116
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
117
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
118
+ THE AUTHORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
119
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
120
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
121
+ USE OR OTHER DEALINGS IN THE SOFTWARE.
122
+ ```
@@ -0,0 +1,3 @@
1
+ """Bounded OpenMM-ML mechanical-embedding backport; see PROVENANCE.md."""
2
+
3
+ UPSTREAM_SHA = "5c78d5ab6843ed0dd024e50123771c482aee4700"
@@ -0,0 +1,201 @@
1
+ """
2
+ mechanicalembedding.py: Implements mechanical embedding.
3
+
4
+ This is part of the OpenMM molecular simulation toolkit originating from
5
+ Simbios, the NIH National Center for Physics-Based Simulation of
6
+ Biological Structures at Stanford, funded under the NIH Roadmap for
7
+ Medical Research, grant U54 GM072970. See https://simtk.org.
8
+
9
+ Portions copyright (c) 2026 Stanford University and the Authors.
10
+ Authors: Peter Eastman, Evan Pretti
11
+ Contributors:
12
+
13
+ Permission is hereby granted, free of charge, to any person obtaining a
14
+ copy of this software and associated documentation files (the "Software"),
15
+ to deal in the Software without restriction, including without limitation
16
+ the rights to use, copy, modify, merge, publish, distribute, sublicense,
17
+ and/or sell copies of the Software, and to permit persons to whom the
18
+ Software is furnished to do so, subject to the following conditions:
19
+
20
+ The above copyright notice and this permission notice shall be included in
21
+ all copies or substantial portions of the Software.
22
+
23
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
26
+ THE AUTHORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
27
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
28
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
29
+ USE OR OTHER DEALINGS IN THE SOFTWARE.
30
+ """
31
+
32
+ from openmmml.mlpotential import MLPotentialImpl
33
+ from . import utilities
34
+ import openmm
35
+ import openmm.app
36
+ import copy
37
+ import typing
38
+
39
+ class MechanicalEmbedding:
40
+ """Mechanical embedding. This is the default embedding method, and uses the
41
+ conventional force field to compute the interactions between the atoms
42
+ within the ML subset and those outside of it.
43
+
44
+ If long-range electrostatics are in use by the conventional force field but
45
+ not supported by the ML model, the conventional force field charges will be
46
+ used to approximate the interactions between atoms within the ML subset in
47
+ different periodic images. For some models, this cannot be determined based
48
+ on the information provided to OpenMM-ML, and the mlLongRange option must be
49
+ provided explicitly to control whether or not to include these interactions.
50
+
51
+ This implementation assumes that if a model reports using long-range
52
+ interactions, or mlLongRange is True, then the long-range interactions that
53
+ the model computes are purely electrostatic (Ewald/PME), not LJPME.
54
+ """
55
+
56
+ def __init__(self):
57
+ pass
58
+
59
+ def createMixedSystem(self,
60
+ potential: MLPotentialImpl,
61
+ topology: openmm.app.Topology,
62
+ system: openmm.System,
63
+ atoms: list[int],
64
+ forceGroup: int,
65
+ interpolate: bool,
66
+ returnInfo: bool = False,
67
+ **args) -> openmm.System | dict[str, typing.Any]:
68
+
69
+ periodic = system.usesPeriodicBoundaryConditions()
70
+
71
+ # See if the ML potential uses long-range interactions. mlLongRange may
72
+ # end up being None, in which case we were unable to determine this.
73
+
74
+ potentialMLLongRange = potential.getMLLongRange()
75
+ userMLLongRange = args.get("mlLongRange", None)
76
+ if potentialMLLongRange is None:
77
+ mlLongRange = userMLLongRange
78
+ else:
79
+ if userMLLongRange is not None:
80
+ raise ValueError("This ML model does not support the mlLongRange option.")
81
+ mlLongRange = potentialMLLongRange
82
+
83
+ # See if the MM force field uses long-range interactions.
84
+
85
+ mmLongRange = False
86
+ mmLongRangeForce = None
87
+ for force in system.getForces():
88
+ if isinstance(force, openmm.NonbondedForce):
89
+ if force.getNonbondedMethod() in (openmm.NonbondedForce.Ewald, openmm.NonbondedForce.PME, openmm.NonbondedForce.LJPME):
90
+ mmLongRange = True
91
+ if mmLongRangeForce is not None:
92
+ raise ValueError("Multiple long-range NonbondedForce objects encountered.")
93
+ mmLongRangeForce = force
94
+ break
95
+
96
+ excludeLongRange = False
97
+
98
+ if periodic:
99
+
100
+ # For a non-periodic system, we will always use exceptions for the
101
+ # ML subset. Otherwise, we need to know whether or not the ML
102
+ # potential is long-range.
103
+
104
+ if mlLongRange is None:
105
+ raise ValueError("The system is periodic and it is unknown if the ML model uses long-range interactions; provide the mlLongRange option to specify.")
106
+
107
+ # We don't support the case where the MM force field is not
108
+ # long-range but the ML potential is.
109
+
110
+ if mlLongRange:
111
+ if not mmLongRange:
112
+ raise ValueError("The system is periodic and the ML model uses long-range interactions while the MM force field does not.")
113
+
114
+ excludeLongRange = True
115
+
116
+ # Create the new system with ML-ML interactions to be computed by the ML
117
+ # potential removed.
118
+
119
+ linkBonds = utilities.findLinkBonds(topology, atoms)
120
+ newSystem = utilities.removeBonds(system, topology, atoms, True)
121
+
122
+ for force in newSystem.getForces():
123
+ if isinstance(force, openmm.NonbondedForce):
124
+ # All of the LJ interactions in the ML region should be zeroed.
125
+ charges = [force.getParticleParameters(atom)[0] for atom in atoms]
126
+ for iAtom1 in range(len(atoms)):
127
+ for iAtom2 in range(iAtom1):
128
+
129
+ # If the ML region electrostatics should be excluded in
130
+ # long-range, keep this exception's charge product set
131
+ # to the true product of the charges since the energy
132
+ # for this pair will be subtracted later. If not, set
133
+ # it to zero here.
134
+
135
+ if excludeLongRange:
136
+ chargeProd = charges[iAtom1] * charges[iAtom2]
137
+ else:
138
+ chargeProd = 0
139
+ force.addException(atoms[iAtom1], atoms[iAtom2], chargeProd, 1, 0, True)
140
+
141
+ # This may cause exceptions in the MM region to use PBCs, but
142
+ # this should not ordinarily have any significant effects.
143
+
144
+ force.setExceptionsUsePeriodicBoundaryConditions(periodic)
145
+
146
+ elif isinstance(force, openmm.CustomNonbondedForce):
147
+ utilities.addCustomNonbondedExclusions(force, atoms)
148
+
149
+ if excludeLongRange:
150
+ # Prepare a force to calculate the PME energy of the ML-ML region.
151
+
152
+ excludeForce = openmm.NonbondedForce()
153
+ excludeForce.setCutoffDistance(mmLongRangeForce.getCutoffDistance())
154
+ excludeForce.setEwaldErrorTolerance(mmLongRangeForce.getEwaldErrorTolerance())
155
+ excludeForce.setNonbondedMethod(openmm.NonbondedForce.PME)
156
+ excludeForce.setPMEParameters(*mmLongRangeForce.getPMEParameters())
157
+
158
+ atomSet = set(atoms)
159
+ for atom in range(newSystem.getNumParticles()):
160
+ excludeForce.addParticle(mmLongRangeForce.getParticleParameters(atom)[0] if atom in atomSet else 0, 1, 0)
161
+
162
+ newTopology = copy.deepcopy(topology)
163
+ if interpolate:
164
+ # For interpolation setup to work, we need to modify the original
165
+ # system so that its NonbondedForce also has the virtual site.
166
+ system = copy.deepcopy(system)
167
+ systemList = [system, newSystem]
168
+ else:
169
+ systemList = [newSystem]
170
+ capIndices, oldToNew = utilities.addLinkAtomSites(newTopology, systemList, linkBonds, args.get("linkAtomDistances", []))
171
+ atomsWithCaps = atoms + capIndices
172
+
173
+ if excludeLongRange:
174
+ # This force is not yet part of newSystem, so addLinkAtomSites()
175
+ # could not extend it. Link sites carry no MM charge or LJ terms.
176
+ for _ in capIndices:
177
+ excludeForce.addParticle(0, 1, 0)
178
+
179
+ if interpolate:
180
+ interpolator = utilities.InterpolationHelper()
181
+ interpolator.addMLPotentialTerms(potential, newTopology, atomsWithCaps, forceGroup, **args)
182
+ interpolator.addMMBondedTerms(system, topology, atoms)
183
+ interpolator.setupNonbonded(newSystem, system)
184
+ if excludeLongRange:
185
+ interpolator.addMLTerm(excludeForce, "-{}")
186
+ interpolator.setupInterpolation(newSystem)
187
+
188
+ else:
189
+ # Add the ML potential and subtract the ML-ML PME energy if needed.
190
+
191
+ if excludeLongRange:
192
+ cvForce = openmm.CustomCVForce("-excludeForce")
193
+ cvForce.addCollectiveVariable("excludeForce", excludeForce)
194
+ newSystem.addForce(cvForce)
195
+
196
+ potential.addForces(newTopology, newSystem, atomsWithCaps, forceGroup, **args)
197
+
198
+ if returnInfo:
199
+ return dict(system=newSystem, topology=newTopology, oldToNew=oldToNew)
200
+ else:
201
+ return newSystem