Coverage for openxps/integrator.py: 99%
164 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.integrator
3 :platform: Linux, MacOS, Windows
4 :synopsis: Integrators for extended phase-space simulations with OpenMM.
6.. classauthor:: Charlles Abreu <craabreu@gmail.com>
8"""
10from abc import ABC, abstractmethod
11from copy import copy, deepcopy
13import numpy as np
14import openmm as mm
15from cvpack.units import Quantity
16from openmm import _openmm as mmswig
17from openmm import unit as mmunit
19from . import integrators
20from .couplings import Coupling
21from .integrators.utils import IntegratorMixin
23#: Tuple of OpenMM integrator classes known to evaluate forces exclusively at the
24#: beginning of each time step (force-first or leapfrog schemes).
25KNOWN_FORCE_FIRST_INTEGRATORS = (
26 mm.VerletIntegrator,
27 mm.LangevinIntegrator,
28 mm.LangevinMiddleIntegrator,
29 mm.NoseHooverIntegrator,
30)
32#: Tuple of OpenMM integrator classes known to be symmetric in the sense of operator
33#: splitting, i.e., they can be represented as a palindromic sequence of operations.
34KNOWN_SYMMETRIC_INTEGRATORS = (
35 integrators.SymmetricVerletIntegrator,
36 integrators.SymmetricLangevinIntegrator,
37)
40def _integrator_state(integrator: mm.Integrator) -> tuple[type, str, dict]:
41 attributes = {
42 key: value.in_unit_system(mmunit.md_unit_system)
43 if mmunit.is_quantity(value)
44 else value
45 for key, value in vars(integrator).items()
46 if key != "this"
47 }
48 return type(integrator), mm.XmlSerializer.serialize(integrator), attributes
51def _restore_integrator(cls: type, xml: str, attributes: dict) -> mm.Integrator:
52 integrator = cls.__new__(cls)
53 integrator.this = mm.XmlSerializer.deserialize(xml).this
54 integrator.__dict__.update(
55 {
56 key: Quantity(value) if mmunit.is_quantity(value) else value
57 for key, value in attributes.items()
58 }
59 )
60 return integrator
63def _decorrelate_random_seed(physical: mm.Integrator, extension: mm.Integrator) -> None:
64 if hasattr(physical, "getRandomNumberSeed"):
65 seed = physical.getRandomNumberSeed()
66 extension.setRandomNumberSeed(0 if seed == 0 else seed % (2**31 - 1) + 1)
69class ExtendedSpaceIntegrator(mm.Integrator, ABC):
70 """Base class for integrators that advance extended phase-space simulations.
72 An extended phase-space integrator manages two separate OpenMM integrators: one for
73 the physical system and one for the extension system containing dynamical variables.
75 The step size of this integrator is the maximum of the step sizes of the physical
76 and extension integrators.
78 All :OpenMM:`Integrator` methods are applied to the physical system integrator,
79 except for ``step``, ``getStepSize``, and ``setStepSize``, which are applied to
80 both the physical and extension system integrators.
82 Parameters
83 ----------
84 physical_integrator
85 The integrator for the physical system.
86 extension_integrator
87 The integrator for the extension system.
89 """
91 def __init__(
92 self,
93 physical_integrator: mm.Integrator,
94 extension_integrator: mm.Integrator,
95 ) -> None:
96 self._physical_integrator = physical_integrator
97 self._extension_integrator = extension_integrator
98 self._assume_valid = getattr(self, "_assume_valid", False)
99 self._initialize()
101 def __copy__(self) -> "ExtendedSpaceIntegrator":
102 """Return an unconfigured copy of the integrator."""
103 clone = self.__class__.__new__(self.__class__)
104 clone._physical_integrator = copy(self._physical_integrator)
105 clone._extension_integrator = copy(self._extension_integrator)
106 clone._assume_valid = self._assume_valid
107 clone._initialize()
108 return clone
110 def __deepcopy__(self, memo: dict) -> "ExtendedSpaceIntegrator":
111 return self.__copy__()
113 def __getstate__(self) -> dict:
114 """Get the state of the integrator as a picklable dictionary."""
115 return {
116 "physical": _integrator_state(self._physical_integrator),
117 "extension": _integrator_state(self._extension_integrator),
118 "assume_valid": self._assume_valid,
119 }
121 def __setstate__(self, state: dict) -> None:
122 """Set the state of the integrator from a dictionary."""
123 self._physical_integrator = _restore_integrator(*state["physical"])
124 self._extension_integrator = _restore_integrator(*state["extension"])
125 self._assume_valid = state["assume_valid"]
126 self._initialize()
128 def _initialize(self) -> None:
129 """Initialize the integrator."""
130 self.this = self._physical_integrator.this
131 self._step_size = max(
132 mmswig.Integrator_getStepSize(self._physical_integrator),
133 mmswig.Integrator_getStepSize(self._extension_integrator),
134 )
135 self._extension_context = None
136 self._physical_context = None
137 self._dynamical_variables = None
138 self._coupling = None
140 def configure(
141 self,
142 physical_context: mm.Context,
143 extension_context: mm.Context,
144 coupling: Coupling,
145 ) -> None:
146 """Configure the integrator.
148 Store pointers to the given contexts, dynamical variables, and coupling
149 potential in the integrator. This allows the integrator to update the contexts
150 during the simulation.
152 Parameters
153 ----------
154 physical_context
155 The OpenMM context containing the physical system.
156 extension_context
157 The OpenMM context containing the extension system.
158 coupling
159 The potential that couples the physical and dynamical variables.
160 """
161 for integrator, context, isExtension in (
162 (self._physical_integrator, physical_context, False),
163 (self._extension_integrator, extension_context, True),
164 ):
165 if isinstance(integrator, IntegratorMixin):
166 integrator.registerWithSystem(context.getSystem(), isExtension)
167 self._physical_context = physical_context
168 self._extension_context = extension_context
169 self._coupling = coupling
170 self._dynamical_variables = coupling.getDynamicalVariables()
172 def getPhysicalIntegrator(self) -> mm.Integrator:
173 """Get the integrator for the physical system.
175 Returns
176 -------
177 mm.Integrator
178 The integrator for the physical system.
179 """
180 return self._physical_integrator
182 def getExtensionIntegrator(self) -> mm.Integrator:
183 """Get the integrator for the extension system.
185 Returns
186 -------
187 mm.Integrator
188 The integrator for the extension system.
189 """
190 return self._extension_integrator
192 def getStepSize(self) -> mmunit.Quantity:
193 """Get the step size for the integrator.
195 This is the maximum of the step sizes of the physical and extension integrators.
197 Returns
198 -------
199 mmunit.Quantity
200 The step size for the integrator.
201 """
202 return self._step_size * mmunit.picosecond
204 def setStepSize(self, size: mmunit.Quantity | float) -> None:
205 """Set the step size for the extended phase-space integrator.
207 This scales the step size of the physical and extension integrators by a factor
208 defined by the ratio of the given step size to the largest current step size.
210 Parameters
211 ----------
212 size
213 The step size for the extended phase-space integrator.
214 """
215 if mmunit.is_quantity(size):
216 size = size.value_in_unit(mmunit.picosecond)
217 factor = size / self._step_size
218 self._physical_integrator.setStepSize(
219 factor * mmswig.Integrator_getStepSize(self._physical_integrator)
220 )
221 self._extension_integrator.setStepSize(
222 factor * mmswig.Integrator_getStepSize(self._extension_integrator)
223 )
224 self._step_size = size
226 @abstractmethod
227 def step(self, steps: int) -> None:
228 """Advance the extended phase-space simulation by a specified number of steps.
230 Parameters
231 ----------
232 steps
233 The number of time steps to advance the simulation.
234 """
235 raise NotImplementedError("This method must be implemented by the subclass.")
238class LockstepIntegrator(ExtendedSpaceIntegrator):
239 """
240 An integrator that advances the physical and extension systems in lockstep.
242 This class integrates both the physical and extension systems simultaneously, then
243 synchronizes the contexts after each step. It assumes that both integrators apply
244 all forces at the beginning of each time step (a force-first scheme). If either
245 integrator does not follow this scheme, the overall integration will be incorrect.
247 The step sizes of the physical and extension integrators must be equal.
249 Parameters
250 ----------
251 physical_integrator
252 The integrator for the physical system.
253 extension_integrator
254 The integrator for the extension system. If None, a copy of the physical
255 integrator is used.
256 assume_force_first
257 If True, skip the validation that checks whether the integrators are known
258 to follow a force-first scheme. Use this at your own risk if you know your
259 integrators are compatible. Default is False.
261 Raises
262 ------
263 ValueError
264 If the physical and extension integrators do not follow a force-first scheme or
265 do not have the same step size.
267 Example
268 -------
269 >>> import openxps as xps
270 >>> import openmm as mm
271 >>> from openmm import unit
273 Using OpenMM's LangevinMiddleIntegrator integrator (force-first)
275 >>> integrator = mm.LangevinMiddleIntegrator(
276 ... 300 * unit.kelvin, 1 / unit.picosecond, 1 * unit.femtosecond
277 ... )
278 >>> xps_integrator = xps.LockstepIntegrator(integrator)
279 >>> print(xps_integrator.getStepSize())
280 0.001 ps
282 Using CSVR integrator with force-first scheme for the extension system
284 >>> csvr = xps.integrators.CSVRIntegrator(
285 ... 300 * unit.kelvin, 10 / unit.picosecond, 1 * unit.femtosecond,
286 ... forceFirst=True
287 ... )
288 >>> xps_integrator_ff = xps.LockstepIntegrator(integrator, csvr)
289 """
291 def __init__(
292 self,
293 physical_integrator: mm.Integrator,
294 extension_integrator: mm.Integrator | None = None,
295 assume_force_first: bool = False,
296 ) -> None:
297 self._assume_valid = assume_force_first
298 if extension_integrator is None:
299 extension_integrator = deepcopy(physical_integrator)
300 _decorrelate_random_seed(physical_integrator, extension_integrator)
301 elif not np.isclose(
302 mmswig.Integrator_getStepSize(physical_integrator),
303 mmswig.Integrator_getStepSize(extension_integrator),
304 ):
305 raise ValueError("The step sizes must be equal.")
306 if not (
307 assume_force_first
308 or (
309 self._is_force_first(physical_integrator)
310 and self._is_force_first(extension_integrator)
311 )
312 ):
313 raise ValueError(
314 "The integrators must follow a force-first scheme.\n"
315 "If you are certain they do, set assume_force_first=True."
316 )
317 super().__init__(physical_integrator, extension_integrator)
319 @staticmethod
320 def _is_force_first(integrator: mm.Integrator) -> bool:
321 """Check if an integrator follows a force-first scheme."""
322 if isinstance(integrator, KNOWN_FORCE_FIRST_INTEGRATORS):
323 return True
324 if isinstance(integrator, IntegratorMixin):
325 return integrator.isForceFirst()
326 return False
328 def step(self, steps: int) -> None:
329 """Advance the extended phase-space simulation by a specified number of steps.
331 Parameters
332 ----------
333 steps
334 The number of time steps to advance the simulation.
335 """
336 for _ in range(steps):
337 self._physical_integrator.step(1)
338 self._extension_integrator.step(1)
339 self._coupling.updatePhysicalContext(
340 self._physical_context,
341 self._extension_context,
342 )
343 self._coupling.updateExtensionContext(
344 self._physical_context,
345 self._extension_context,
346 )
349class SplitIntegrator(ExtendedSpaceIntegrator):
350 r"""
351 An integrator that advances the physical and extension systems using an operator
352 splitting scheme.
354 This integrator assumes that the physical and extension integrators are symmetric
355 in terms of operator splitting, i.e., they can be represented as a palindromic
356 sequence of operations. If either integrator does not follow this scheme, the
357 overall integration scheme will be incorrect.
359 The step sizes of the physical and extension integrators must be related by an even
360 integer ratio, with either the physical or extension integrator having the larger
361 step size.
363 This class integrates the physical and extension systems in a :math:`B^n A B^n`
364 pattern, where :math:`n` is the number of substeps, :math:`A` is the integrator with
365 the larger step size :math:`\Delta t` (considered as the overall step size), and
366 :math:`B` is the integrator with the smaller step size :math:`\Delta t/(2n)`.
368 Parameters
369 ----------
370 physical_integrator
371 The integrator for the physical system.
372 extension_integrator
373 The integrator for the extension system. If None, a copy of the physical
374 integrator is used with half the step size of the physical integrator.
375 assume_symmetric
376 If True, skip the validation that checks whether the integrators are known
377 to be symmetric in terms of operator splitting. Use this at your own risk if
378 you know your integrators are compatible but are not in the known list.
379 Default is False.
381 When the physical integrator takes the substeps, the extension context only needs
382 updating before each extension step, so the update after the second half of a
383 step is done in the last step of a call to :meth:`step` only, for observers.
385 Raises
386 ------
387 ValueError
388 If the physical and extension integrators are not symmetric in terms of
389 operator splitting, or do not have a step size ratio equal to an even integer
390 number.
392 Example
393 -------
394 >>> import openxps as xps
395 >>> import openmm as mm
396 >>> from openmm import unit
398 Using symmetric Verlet integrator with half step size
400 >>> integrator = xps.integrators.SymmetricVerletIntegrator(4 * unit.femtosecond)
401 >>> xps_integrator = xps.SplitIntegrator(integrator)
402 >>> print(xps_integrator.getStepSize())
403 0.004 ps
404 >>> xps_integrator.getNumSubsteps()
405 1
407 Using symmetric Langevin integrator with 4:1 step size ratio
409 >>> physical = xps.integrators.SymmetricLangevinIntegrator(
410 ... 300 * unit.kelvin, 1 / unit.picosecond, 4 * unit.femtosecond
411 ... )
412 >>> extension = xps.integrators.SymmetricLangevinIntegrator(
413 ... 300 * unit.kelvin, 1 / unit.picosecond, 1 * unit.femtosecond
414 ... )
415 >>> xps_integrator = xps.SplitIntegrator(physical, extension)
416 >>> print(xps_integrator.getStepSize())
417 0.004 ps
418 >>> xps_integrator.getNumSubsteps()
419 2
421 Using symmetric Langevin integrator with 1:4 step size ratio
423 >>> physical = xps.integrators.SymmetricLangevinIntegrator(
424 ... 300 * unit.kelvin, 1 / unit.picosecond, 2 * unit.femtosecond
425 ... )
426 >>> extension = xps.integrators.SymmetricLangevinIntegrator(
427 ... 300 * unit.kelvin, 1 / unit.picosecond, 8 * unit.femtosecond
428 ... )
429 >>> xps_integrator = xps.SplitIntegrator(physical, extension)
430 >>> print(xps_integrator.getStepSize())
431 0.008 ps
432 >>> xps_integrator.getNumSubsteps()
433 2
434 """
436 def __init__(
437 self,
438 physical_integrator: mm.Integrator,
439 extension_integrator: mm.Integrator | None = None,
440 assume_symmetric: bool = False,
441 ) -> None:
442 self._assume_valid = assume_symmetric
443 physical_step_size = mmswig.Integrator_getStepSize(physical_integrator)
444 if extension_integrator is None:
445 extension_integrator = deepcopy(physical_integrator)
446 _decorrelate_random_seed(physical_integrator, extension_integrator)
447 extension_step_size = physical_step_size / 2
448 extension_integrator.setStepSize(extension_step_size)
449 else:
450 extension_step_size = mmswig.Integrator_getStepSize(extension_integrator)
451 if not (
452 assume_symmetric
453 or (
454 self._is_symmetric(physical_integrator)
455 and self._is_symmetric(extension_integrator)
456 )
457 ):
458 raise ValueError(
459 "The integrators must be symmetric in terms of operator splitting.\n"
460 "If you are certain they are, set assume_symmetric=True."
461 )
462 step_size = max(physical_step_size, extension_step_size)
463 substep_size = min(physical_step_size, extension_step_size)
464 if not self._is_even_division(step_size, substep_size):
465 raise ValueError("The step sizes must be related by an even integer ratio.")
466 super().__init__(physical_integrator, extension_integrator)
468 @staticmethod
469 def _is_symmetric(integrator: mm.Integrator) -> bool:
470 """Check if an integrator is symmetric in terms of operator splitting."""
471 if isinstance(integrator, KNOWN_SYMMETRIC_INTEGRATORS):
472 return True
473 if isinstance(integrator, IntegratorMixin):
474 return not integrator.isForceFirst()
475 return False
477 @staticmethod
478 def _is_even_division(a: float, b: float) -> bool:
479 if b == 0:
480 raise ValueError("Division by zero is not allowed.")
481 return np.isclose(a / b - round(a / b), 0) and int(round(a / b)) % 2 == 0
483 def _initialize(self) -> None:
484 super()._initialize()
485 physical_step_size = mmswig.Integrator_getStepSize(self._physical_integrator)
486 extension_step_size = mmswig.Integrator_getStepSize(self._extension_integrator)
487 if physical_step_size > extension_step_size:
488 self._middle_integrator = self._physical_integrator
489 self._end_integrator = self._extension_integrator
490 ratio = physical_step_size / (2 * extension_step_size)
491 else:
492 self._middle_integrator = self._extension_integrator
493 self._end_integrator = self._physical_integrator
494 ratio = extension_step_size / (2 * physical_step_size)
495 self._num_substeps = int(np.rint(ratio))
496 self._physical_takes_substeps = (
497 self._end_integrator is self._physical_integrator
498 )
500 def configure(
501 self,
502 physical_context: mm.Context,
503 extension_context: mm.Context,
504 coupling: Coupling,
505 ) -> None:
506 super().configure(physical_context, extension_context, coupling)
507 if self._middle_integrator is self._physical_integrator:
508 self._update_middle_context = self._coupling.updatePhysicalContext
509 self._update_end_context = self._coupling.updateExtensionContext
510 else:
511 self._update_middle_context = self._coupling.updateExtensionContext
512 self._update_end_context = self._coupling.updatePhysicalContext
514 def getNumSubsteps(self) -> int:
515 """Get the number of substeps for the integrator.
517 Returns
518 -------
519 int
520 The number of substeps for the integrator.
521 """
522 return self._num_substeps
524 def step(self, steps: int) -> None:
525 """Advance the extended phase-space simulation by integrating the physical and
526 extension systems in lockstep over a specified number of time steps.
528 Parameters
529 ----------
530 steps : int
531 The number of time steps to advance the simulation.
532 """
533 step_count = self._physical_context.getStepCount()
534 contexts = (self._physical_context, self._extension_context)
535 for i in range(steps):
536 self._end_integrator.step(self._num_substeps)
537 self._update_middle_context(*contexts)
538 self._middle_integrator.step(1)
539 self._update_end_context(*contexts)
540 self._end_integrator.step(self._num_substeps)
541 # When the physical integrator takes the substeps, the extension update
542 # here only serves observers: the next step redoes it before the
543 # extension system moves again. It is done once, at the end of the call.
544 if i == steps - 1 or not self._physical_takes_substeps:
545 self._update_middle_context(*contexts)
546 self._physical_context.setStepCount(step_count + steps)