Coverage for openxps/simulation.py: 96%
54 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-22 22:23 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-22 22:23 +0000
1"""
2.. module:: openxps.simulation
3 :platform: Linux, MacOS, Windows
4 :synopsis: Simulation class for extended phase-space simulations with OpenMM.
6.. classauthor:: Charlles Abreu <craabreu@gmail.com>
8"""
10import os
11import typing as t
13import openmm as mm
14from openmm import app as mmapp
16from .context import ExtendedSpaceContext
17from .integrator import ExtendedSpaceIntegrator
18from .system import ExtendedSpaceSystem
19from .utils import STRING_SEPARATOR
22class ExtendedSpaceSimulation(mmapp.Simulation):
23 """
24 A :OpenMM:`Simulation` object that uses an :class:`ExtendedSpaceContext` to enable
25 extended phase-space (XPS) simulations with dynamical variables.
27 This class extends :OpenMM:`Simulation` to seamlessly integrate extended phase-space
28 capabilities by creating an :class:`ExtendedSpaceContext` instead of a standard
29 :OpenMM:`Context`. All other functionality is inherited from the base class.
31 **Note**: The system and integrator provided as arguments are modified in place.
33 Parameters
34 ----------
35 topology
36 The :OpenMM:`Topology` describing the system to be simulated.
37 system
38 The :class:`ExtendedSpaceSystem` object to simulate.
39 integrator
40 An :class:`ExtendedSpaceIntegrator` object to be used for advancing the XPS
41 simulation. Available implementations include :class:`LockstepIntegrator` for
42 systems where both integrators use the same step size, and
43 :class:`SplitIntegrator` for systems with different step sizes related by an
44 even integer ratio.
45 platform
46 The :OpenMM:`Platform` to use for calculations. If None, the default Platform
47 will be used.
48 platformProperties
49 A dictionary of platform-specific properties. If None, the default properties
50 will be used.
51 state
52 If specified, either an :OpenMM:`State` object or the name or path of a file
53 written by :meth:`saveState`, from which the simulation state is set after
54 initialization.
56 Example
57 -------
58 >>> import openxps as xps
59 >>> from math import pi
60 >>> import cvpack
61 >>> import openmm
62 >>> from openmm import unit
63 >>> from openmmtools import testsystems
64 >>> model = testsystems.AlanineDipeptideVacuum()
65 >>> mass = 3 * unit.dalton*(unit.nanometer/unit.radian)**2
66 >>> phi0 = xps.DynamicalVariable("phi0", unit.radian, mass, xps.CircularBounds())
67 >>> phi = cvpack.Torsion(6, 8, 14, 16, name="phi")
68 >>> kappa = 1000 * unit.kilojoules_per_mole / unit.radian**2
69 >>> harmonic_force = xps.HarmonicCoupling(phi, phi0, kappa)
70 >>> integrator = openmm.LangevinMiddleIntegrator(
71 ... 300 * unit.kelvin, 1 / unit.picosecond, 4 * unit.femtosecond
72 ... )
73 >>> integrator.setRandomNumberSeed(1234)
74 >>> simulation = xps.ExtendedSpaceSimulation(
75 ... model.topology,
76 ... xps.ExtendedSpaceSystem(model.system, harmonic_force),
77 ... xps.LockstepIntegrator(integrator),
78 ... openmm.Platform.getPlatformByName("Reference"),
79 ... )
80 >>> simulation.context.setPositions(model.positions)
81 >>> simulation.context.setVelocitiesToTemperature(300 * unit.kelvin, 1234)
82 >>> simulation.context.setDynamicalVariableValues([180 * unit.degree])
83 >>> simulation.context.setDynamicalVariableVelocitiesToTemperature(
84 ... 300 * unit.kelvin, 1234
85 ... )
86 >>> simulation.step(100)
87 >>> print("phi0 =", *simulation.context.getDynamicalVariableValues())
88 phi0 = ... rad
89 """
91 def __init__( # noqa: PLR0913 pylint: disable=super-init-not-called
92 self,
93 topology: mmapp.Topology,
94 system: ExtendedSpaceSystem,
95 integrator: ExtendedSpaceIntegrator,
96 platform: mm.Platform | None = None,
97 platformProperties: dict | None = None,
98 state: mm.State | str | os.PathLike | None = None,
99 ) -> None:
100 self.topology = topology
101 self.system = system
103 args = [system, integrator]
104 if platform is not None:
105 args.append(platform)
106 if platformProperties is not None:
107 args.append(platformProperties)
109 self.context = self.extended_space_context = ExtendedSpaceContext(*args)
110 self.integrator = self.context.getIntegrator()
112 self.currentStep = 0
113 self.reporters = []
115 if isinstance(state, (str, os.PathLike)):
116 self.loadState(state)
117 elif state is not None:
118 self.context.setState(state)
120 try:
121 self._usesPBC = self.system.usesPeriodicBoundaryConditions()
122 except Exception:
123 self._usesPBC = topology.getUnitCellDimensions() is not None
125 def minimizeEnergy(self, *args, **kwargs) -> None:
126 """
127 Minimize the energy of the physical system and synchronize the extension
128 context. Arguments are those of :OpenMM:`Simulation`.
129 """
130 super().minimizeEnergy(*args, **kwargs)
131 self.context.synchronize()
133 def saveState(self, file: str | os.PathLike | t.IO) -> None:
134 """
135 Save the states of the physical and extension contexts to a file.
137 Parameters
138 ----------
139 file
140 A file name or path, or a file object open in text or binary mode.
141 """
142 physical = self.context.getState(
143 getPositions=True,
144 getVelocities=True,
145 getParameters=True,
146 getIntegratorParameters=True,
147 enforcePeriodicBox=self._usesPBC,
148 )
149 extension = self.context.getExtensionContext().getState(
150 getPositions=True,
151 getVelocities=True,
152 getParameters=True,
153 getIntegratorParameters=True,
154 )
155 content = (
156 mm.XmlSerializer.serialize(physical)
157 + STRING_SEPARATOR
158 + mm.XmlSerializer.serialize(extension)
159 )
160 if isinstance(file, (str, os.PathLike)):
161 with open(file, "w", encoding="utf-8") as stream:
162 stream.write(content)
163 elif hasattr(file, "encoding"): # text mode, including wrapped streams
164 file.write(content)
165 else:
166 file.write(content.encode("utf-8"))
168 def loadState(self, file: str | os.PathLike | t.IO) -> None:
169 """
170 Load the states written by :meth:`saveState` and synchronize the contexts.
172 Parameters
173 ----------
174 file
175 A file name or path, or a file object open in text or binary mode.
176 """
177 if isinstance(file, (str, os.PathLike)):
178 with open(file, encoding="utf-8") as stream:
179 content = stream.read()
180 else:
181 content = file.read()
182 if isinstance(content, bytes):
183 content = content.decode("utf-8")
184 physical, _, extension = content.partition(STRING_SEPARATOR)
185 self.context.setState(mm.XmlSerializer.deserialize(physical))
186 if extension:
187 self.context.getExtensionContext().setState(
188 mm.XmlSerializer.deserialize(extension)
189 )
190 self.context.synchronize()