Coverage for openxps/integrators/csvr.py: 100%
72 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.integrators.csvr
3 :platform: Linux, MacOS, Windows
4 :synopsis: Canonical Sampling through Velocity Rescaling (CSVR) integrator.
6.. classauthor:: Charlles Abreu <craabreu@gmail.com>
8"""
10import numpy as np
11import openmm as mm
12from openmm import unit as mmunit
14from openxps.utils import preprocess_args
16from .utils import IntegratorMixin, add_property
19@add_property("temperature", mmunit.kelvin)
20@add_property("friction coefficient", 1 / mmunit.picosecond)
21class CSVRIntegrator(IntegratorMixin, mm.CustomIntegrator):
22 """The Canonical Sampling through Velocity Rescaling integrator :cite:`Bussi2007`.
24 The Canonical Sampling through Velocity Rescaling (CSVR) thermostat scales all
25 velocities by a single factor stochastically determined in order to preserve the
26 canonical distribution at the specified temperature.
28 .. warning::
29 When used outside OpenXPS, the :meth:`registerWithSystem` method must be called
30 with `isExtension=False` before starting a simulation.
32 .. note::
33 A system with zero kinetic energy is left at rest. Initialize the velocities
34 before starting a simulation.
36 Parameters
37 ----------
38 temperature
39 The temperature.
40 frictionCoeff
41 The friction coefficient.
42 stepSize
43 The integration step size.
44 forceFirst
45 If True, the integrator will apply a force-first scheme rather than a
46 symmetric operator splitting scheme.
48 Example
49 -------
50 >>> import openxps as xps
51 >>> import openmm as mm
52 >>> from openmm import unit
53 >>> from openmmtools import testsystems
55 Symmetric scheme (default)
57 >>> integrator = xps.integrators.CSVRIntegrator(
58 ... temperature=300 * unit.kelvin,
59 ... frictionCoeff=10 / unit.picosecond,
60 ... stepSize=2 * unit.femtoseconds,
61 ... )
62 >>> integrator
63 Per-dof variables:
64 x1
65 Global variables:
66 sumRsq = 0.0
67 mvv = 0.0
68 kT = 2.49433...
69 friction = 10.0
70 scaling_factor = 1.0
71 Computation steps:
72 0: allow forces to update the context state
73 1: v <- v + 0.5*dt*f/m
74 2: constrain velocities
75 3: x <- x + 0.5*dt*v
76 4: x1 <- x
77 5: constrain positions
78 6: v <- v + (x - x1)/(0.5*dt)
79 7: constrain velocities
80 8: mvv <- sum(m*v*v)
81 9: scaling_factor <- select(mvv, sqrt(A + BC*(R1^2 + ...), 1); R1 = ...
82 10: v <- v*scaling_factor
83 11: x <- x + 0.5*dt*v
84 12: x1 <- x
85 13: constrain positions
86 14: v <- v + (x - x1)/(0.5*dt)
87 15: constrain velocities
88 16: v <- v + 0.5*dt*f/m
89 17: constrain velocities
91 Force-first scheme
93 >>> integrator_ff = xps.integrators.CSVRIntegrator(
94 ... temperature=300 * unit.kelvin,
95 ... frictionCoeff=10 / unit.picosecond,
96 ... stepSize=2 * unit.femtoseconds,
97 ... forceFirst=True
98 ... )
99 >>> try:
100 ... integrator_ff.getNumDegreesOfFreedom()
101 ... except ValueError as e:
102 ... print(e)
103 The number of degrees of freedom has not been determined...
104 >>> model = testsystems.AlanineDipeptideVacuum()
105 >>> integrator_ff.registerWithSystem(model.system, False)
106 >>> integrator_ff.getNumDegreesOfFreedom()
107 51
108 >>> integrator_ff.setRandomNumberSeed(1234)
109 >>> platform = mm.Platform.getPlatformByName("Reference")
110 >>> context = mm.Context(model.system, integrator_ff, platform)
111 >>> context.setPositions(model.positions)
112 >>> context.setVelocitiesToTemperature(300 * unit.kelvin, 4321)
113 >>> integrator_ff.step(10)
114 """
116 @preprocess_args
117 def __init__(
118 self,
119 temperature: mmunit.Quantity,
120 frictionCoeff: mmunit.Quantity,
121 stepSize: mmunit.Quantity,
122 forceFirst: bool = False,
123 ) -> None:
124 super().__init__(stepSize)
125 self._init_temperature(temperature)
126 self._init_friction_coefficient(frictionCoeff)
127 self._forceFirst = forceFirst
128 self._num_dof = None
129 self._rng = np.random.default_rng(None)
130 self._add_variables()
131 self.addUpdateContextState()
132 self._add_boost(1 if forceFirst else 0.5)
133 self._add_translation(0.5)
134 self._add_rescaling(1)
135 self._add_translation(0.5)
136 if not forceFirst:
137 self._add_boost(0.5)
139 def _add_variables(self) -> None:
140 self.addPerDofVariable("x1", 0)
141 self.addGlobalVariable("sumRsq", 0)
142 self.addGlobalVariable("mvv", 0)
143 self.addGlobalVariable("kT", 0)
144 self.addGlobalVariable("friction", 0)
145 self.addGlobalVariable("scaling_factor", 1)
146 self._update_global_variables()
148 def _update_global_variables(self) -> None:
149 kt = mmunit.MOLAR_GAS_CONSTANT_R * self.getTemperature()
150 friction = self.getFrictionCoefficient()
151 self.setGlobalVariableByName("kT", kt)
152 self.setGlobalVariableByName("friction", friction)
154 def _add_translation(self, fraction: float) -> None:
155 self.addComputePerDof("x", f"x + {fraction}*dt*v")
156 self.addComputePerDof("x1", "x")
157 self.addConstrainPositions()
158 self.addComputePerDof("v", f"v + (x - x1)/({fraction}*dt)")
159 self.addConstrainVelocities()
161 def _add_boost(self, fraction: float) -> None:
162 self.addComputePerDof("v", f"v + {fraction}*dt*f/m")
163 self.addConstrainVelocities()
165 def _add_rescaling(self, fraction: float) -> None:
166 self.addComputeSum("mvv", "m*v*v")
167 self.addComputeGlobal(
168 "scaling_factor",
169 "select(mvv, sqrt(A + BC*(R1^2 + sumRsq) + 2*sqrt(A*BC)*R1), 1)"
170 "; R1 = gaussian"
171 "; BC = (1 - A)*kT/mvv"
172 f"; A = exp(-{fraction}*dt*friction)",
173 )
174 self.addComputePerDof("v", "v*scaling_factor")
176 def _sums_of_squared_gaussians(self, num_steps: int) -> np.ndarray:
177 num_dof = self.getNumDegreesOfFreedom()
178 sumRsq = 2.0 * self._rng.standard_gamma((num_dof - 1) // 2, num_steps)
179 if num_dof % 2 == 0:
180 sumRsq += self._rng.standard_normal(num_steps) ** 2
181 return sumRsq
183 def getNumDegreesOfFreedom(self) -> int:
184 """Get the number of degrees of freedom in the system.
186 Raises
187 ------
188 ValueError
189 If registerWithSystem has not been called first.
190 """
191 if self._num_dof is None:
192 raise ValueError(
193 "The number of degrees of freedom has not been determined.\n"
194 "Call the `registerWithSystem` method first."
195 )
196 return self._num_dof
198 def registerWithSystem(self, system: mm.System, isExtension: bool) -> None:
199 if isExtension:
200 self._num_dof = system.getNumParticles()
201 else:
202 self._num_dof = IntegratorMixin._countDegreesOfFreedom(system)
204 def setRandomNumberSeed(self, seed: int) -> None:
205 """
206 This method overrides the :class:`openmm.CustomIntegrator` method to also seed
207 the generator used to draw the sum of squared Gaussian variates. As in OpenMM,
208 a seed of 0 selects a random, non-reproducible seed.
210 .. note::
211 The state of this generator is not stored in context checkpoints.
213 Parameters
214 ----------
215 seed
216 The seed to use for the random number generators.
217 """
218 rng = np.random.default_rng(None if seed == 0 else seed % 2**32)
219 super().setRandomNumberSeed(seed)
220 self._rng = rng
222 def step(self, steps: int) -> None:
223 """
224 This method overrides the :class:`openmm.CustomIntegrator` method to include the
225 efficient computation of the sum of squares of normally distributed random
226 numbers.
228 Parameters
229 ----------
230 steps
231 The number of steps to take.
232 """
233 for sumRsq in self._sums_of_squared_gaussians(steps):
234 self.setGlobalVariableByName("sumRsq", sumRsq)
235 super().step(1)