Coverage for ufedmm/integrators.py: 100%
322 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-17 14:20 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-17 14:20 +0000
1"""
2.. module:: integrators
3 :platform: Unix, Windows
4 :synopsis: Unified Free Energy Dynamics Integrators
6.. moduleauthor:: Charlles Abreu <craabreu@gmail.com>
7"""
9import numpy as np
10import openmm
11from openmm import unit
13from ufedmm.ufedmm import _standardized
16def add_inner_nonbonded_force(system, inner_switch, inner_cutoff, force_group_index):
17 """
18 Adds a new force group to an :OpenMM:`System` containing a :OpenMM:`NonbondedForce`
19 object, with the purpose of performing multiple time-scale integration via the
20 RESPA2 splitting scheme of Morrone, Zhou, and Berne :cite:`Morrone_2010`. Also,
21 assigns the provided `force_group_index` to this new group and `force_group_index+1`
22 to the original :OpenMM:`NonbondedForce`. When used in an instance of any subclass
23 of :class:`AbstractMiddleRespaIntegrator`, the new force group must be set as
24 embodied by the :OpenMM:`NonbondedForce` as opposed to being complimentary to it.
26 .. warning:
27 The new force group is not intended to contribute to the system energy. Its sole
28 purpose is to provide a smooth, short-range force calculator for some
29 intermediary time scale in a RESPA-type integration.
31 Parameters
32 ----------
33 system : openmm.System
34 The system the inner force will be added to, which must contain a
35 :OpenMM:`NonbondedForce`.
36 inner_switch : float or unit.Quantity
37 The inner switching distance, where the interaction of an atom pair begins
38 to switch off to zero.
39 inner_cutoff : float or unit.Quantity
40 The inner cutoff distance, where the interaction of an atom pairs completely
41 switches off.
42 force_group_index : int
43 The force group the new interactions will belong to. The old
44 :OpenMM:`NonbondedForce` will be automatically assigned to
45 `force_group_index+1`.
47 Example
48 -------
49 >>> import ufedmm
50 >>> from openmm import unit
51 >>> dt = 2*unit.femtoseconds
52 >>> temp = 300*unit.kelvin
53 >>> tau = 10*unit.femtoseconds
54 >>> gamma = 10/unit.picoseconds
55 >>> model = ufedmm.AlanineDipeptideModel()
56 >>> ufedmm.add_inner_nonbonded_force(
57 ... model.system, 5*unit.angstroms, 8*unit.angstroms, 1
58 ... )
59 """
60 try:
61 nonbonded_force = next(
62 filter(lambda f: isinstance(f, openmm.NonbondedForce), system.getForces())
63 )
64 except StopIteration:
65 raise Exception(
66 "add_inner_nonbonded_force requires system with NonbondedForce"
67 ) from None
68 if (
69 nonbonded_force.getNumParticleParameterOffsets() > 0
70 or nonbonded_force.getNumExceptionParameterOffsets() > 0
71 ):
72 raise Exception("add_inner_nonbonded_force does not support parameter offsets")
73 periodic = nonbonded_force.usesPeriodicBoundaryConditions()
74 rs = _standardized(inner_switch)
75 rc = _standardized(inner_cutoff)
76 a = rc + rs
77 b = rc * rs
78 c = (30 / (rc - rs) ** 5) * np.array([b**2, -2 * a * b, a**2 + 2 * b, -2 * a, 1])
79 f0s = sum([c[n] * rs ** (n + 1) / (n + 1) for n in range(5)])
81 def coeff(n, m):
82 return c[m - 1] if m == n else c[m - 1] / (m - n)
84 def func(n, m):
85 return "*log(r)" if m == n else (f"*r^{m - n}" if m > n else f"/r^{n - m}")
87 def val(n, m):
88 return f0s if m == 0 else (coeff(n, m) - coeff(0, m) if n != m else coeff(n, m))
90 def sgn(n, m):
91 return "+" if m > 0 and val(n, m) >= 0 else ""
93 def S(n):
94 return "".join(f"{sgn(n, m)}{val(n, m)}{func(n, m)}" for m in range(6))
96 potential = "eps4*((sigma/r)^12-(sigma/r)^6)+Qprod/r"
97 potential += (
98 f"+step(r-{rs})*(eps4*(sigma^12*({S(12)})-sigma^6*({S(6)}))+Qprod*({S(1)}))"
99 )
100 mixing_rules = "; Qprod=Q1*Q2"
101 mixing_rules += "; sigma=halfsig1+halfsig2"
102 mixing_rules += "; eps4=sqrt4eps1*sqrt4eps2"
103 force = openmm.CustomNonbondedForce(potential + mixing_rules)
104 for parameter in ["Q", "halfsig", "sqrt4eps"]:
105 force.addPerParticleParameter(parameter)
106 force.setNonbondedMethod(
107 force.CutoffPeriodic if periodic else force.CutoffNonPeriodic
108 )
109 force.setCutoffDistance(inner_cutoff)
110 force.setUseLongRangeCorrection(False)
111 ONE_4PI_EPS0 = 138.93545764438198
112 for index in range(nonbonded_force.getNumParticles()):
113 charge, sigma, epsilon = map(
114 _standardized, nonbonded_force.getParticleParameters(index)
115 )
116 force.addParticle(
117 [charge * np.sqrt(ONE_4PI_EPS0), sigma / 2, np.sqrt(4 * epsilon)]
118 )
119 non_exclusion_exceptions = []
120 for index in range(nonbonded_force.getNumExceptions()):
121 i, j, q1q2, sigma, epsilon = nonbonded_force.getExceptionParameters(index)
122 q1q2, sigma, epsilon = map(_standardized, [q1q2, sigma, epsilon])
123 force.addExclusion(i, j)
124 if q1q2 != 0.0 or epsilon != 0.0:
125 non_exclusion_exceptions.append(
126 (i, j, q1q2 * ONE_4PI_EPS0, sigma, 4 * epsilon)
127 )
128 force.setForceGroup(force_group_index)
129 system.addForce(force)
130 if non_exclusion_exceptions:
131 exceptions = openmm.CustomBondForce(f"step({rc}-r)*({potential})")
132 for parameter in ["Qprod", "sigma", "eps4"]:
133 exceptions.addPerBondParameter(parameter)
134 for i, j, Qprod, sigma, eps4 in non_exclusion_exceptions:
135 exceptions.addBond(i, j, [Qprod, sigma, eps4])
136 exceptions.setForceGroup(force_group_index)
137 system.addForce(exceptions)
138 nonbonded_force.setForceGroup(force_group_index + 1)
141class CustomIntegrator(openmm.CustomIntegrator):
142 """An extension of :OpenMM:`CustomIntegrator` class with an extra per-dof variable
143 named `temperature`, whose content is the temperature of the heat bath associated to
144 each degree of freedom. A per-dof temperature is necessary if the extended-space
145 variables and the physical system are coupled adiabatically to thermostats at
146 different temperatures. Otherwise, any other OpenMM integrator can be used.
148 Parameters
149 ----------
150 temperature : float or unit.Quantity
151 The temperature.
152 step_size : float or unit.Quantity
153 The step size with which to integrate the equations of motion.
154 """
156 def __init__(self, temperature, step_size):
157 super().__init__(step_size)
158 self.temperature = temperature
159 self.addPerDofVariable("kT", unit.MOLAR_GAS_CONSTANT_R * temperature)
160 self._up_to_date = False
162 def __repr__(self):
163 """A human-readable version of each integrator step (adapted from openmmtools)
165 Returns
166 -------
167 readable_lines : str
168 A list of human-readable versions of each step of the integrator
169 """
170 readable_lines = []
172 self.getNumPerDofVariables() > 0 and readable_lines.append("Per-dof variables:")
173 per_dof = []
174 for index in range(self.getNumPerDofVariables()):
175 per_dof.append(self.getPerDofVariableName(index))
176 readable_lines.append(" " + ", ".join(per_dof))
178 self.getNumGlobalVariables() > 0 and readable_lines.append("Global variables:")
179 for index in range(self.getNumGlobalVariables()):
180 name = self.getGlobalVariableName(index)
181 value = self.getGlobalVariable(index)
182 readable_lines.append(f" {name} = {value}")
184 readable_lines.append("Computation steps:")
186 step_type_str = [
187 "{target} <- {expr}",
188 "{target} <- {expr}",
189 "{target} <- sum({expr})",
190 "constrain positions",
191 "constrain velocities",
192 "allow forces to update the context state",
193 "if ({expr}):",
194 "while ({expr}):",
195 "end",
196 ]
197 indent_level = 0
198 for step in range(self.getNumComputations()):
199 line = ""
200 step_type, target, expr = self.getComputationStep(step)
201 if step_type == 8: # noqa: PLR2004
202 indent_level -= 1
203 command = step_type_str[step_type].format(target=target, expr=expr)
204 line += f"{step:4d}: " + " " * indent_level + command
205 if step_type in [6, 7]:
206 indent_level += 1
207 readable_lines.append(line)
208 return "\n".join(readable_lines)
210 def update_temperatures(self, system_temperature, extended_space_temperatures):
211 nparticles = len(self.getPerDofVariableByName("kT")) - len(
212 extended_space_temperatures
213 )
214 # Extra particles only move along x, so their y and z are not thermostatted
215 kT = [
216 unit.MOLAR_GAS_CONSTANT_R * system_temperature * openmm.Vec3(1, 1, 1)
217 ] * nparticles + [
218 unit.MOLAR_GAS_CONSTANT_R * T * openmm.Vec3(1, 0, 0)
219 for T in extended_space_temperatures
220 ]
221 self.setPerDofVariableByName("kT", kT)
222 self._up_to_date = True
224 def _isotropic_kT(self):
225 """Per-particle kT replicated over x, y and z, for quantities that must not
226 vanish when kT does (such as thermostat masses)."""
227 return [
228 openmm.Vec3(kT.x, kT.x, kT.x) for kT in self.getPerDofVariableByName("kT")
229 ]
231 def step(self, steps):
232 if not self._up_to_date:
233 self.update_temperatures(self.temperature, [])
234 super().step(steps)
237class AbstractMiddleRespaIntegrator(CustomIntegrator):
238 """An abstract class for middle-type, multiple time-scale integrators.
240 .. warning::
241 This class is meant for inheritance only and does not actually include
242 thermostatting. Concrete subclasses are available, such as
243 :class:`MiddleMassiveNHCIntegrator` and :class:`GeodesicLangevinIntegrator`,
244 for instance.
246 Child classes will differ by the thermostat algorithm, which must be implemented
247 by overriding the `_bath` method (see the example below).
248 Temperature is treated as a per-dof parameter so as to allow adiabatic simulations.
250 The following :term:`ODE` system is solved for every degree of freedom in the
251 system, with possibly :math:`n_c` holonomic constraints and with forces possibly
252 split into :math:`m` parts according to their characteristic time scales:
254 .. math::
255 & \\dot{r}_i = v_i \\\\
256 & \\dot{v}_i = \\frac{\\sum_{k=1}^m F_i^{[k]}}{m_i}
257 + \\sum_{k=1}^{n_c} \\lambda_k \\nabla_{r_i} \\sigma_k
258 + \\mathrm{bath}(T_i, v_i) \\\\
259 & \\sigma_k(\\mathbf{r}) = 0
261 An approximate solution is obtained by applying the Trotter-Suzuki splitting
262 formula. In the particular case of two time scales, the default splitting scheme
263 goes as follows:
265 .. math::
266 e^{\\Delta t\\mathcal{L}} =
267 e^{\\frac{\\Delta t}{2}\\mathcal{L}^{[1]}_v}
268 \\left[
269 e^{\\frac{\\Delta t}{2 n_0}\\mathcal{L}^{[0]}_v}
270 \\left(
271 e^{\\frac{\\Delta t}{2 n_0 n_b}\\mathcal{L}_r}
272 e^{\\frac{\\Delta t}{n_0 n_b}\\mathcal{L}_\\mathrm{bath}}
273 e^{\\frac{\\Delta t}{2 n_0 n_b}\\mathcal{L}_r}
274 \\right)^{n_b}
275 e^{\\frac{\\Delta t}{2 n_0}\\mathcal{L}^{[0]}_v}
276 \\right]^{n_0}
277 e^{\\frac{\\Delta t}{2}\\mathcal{L}^{[1]}_v}
279 Each exponential operator is the solution of a particular subsystem of equations.
280 If :math:`\\mathrm{bath}(T_i, v_i) = 0`, the scheme above is time-reversible,
281 measure-preserving, and symplectic. It is referred to as the ``VV-Middle`` scheme
282 :cite:`Zhang_2019`, where VV stands for Velocity Verlet. An alternative approach
283 is also available, which is:
285 .. math::
286 e^{\\Delta t\\mathcal{L}} =
287 \\left[
288 \\left(
289 e^{\\frac{\\Delta t}{2 n_0 n_b}\\mathcal{L}_r}
290 e^{\\frac{\\Delta t}{n_0 n_b}\\mathcal{L}_\\mathrm{bath}}
291 e^{\\frac{\\Delta t}{2 n_0 n_b}\\mathcal{L}_r}
292 \\right)^{n_b}
293 e^{\\frac{\\Delta t}{n_0}\\mathcal{L}^{[0]}_v}
294 \\right]^{n_0}
295 e^{\\Delta t \\mathcal{L}^{[1]}_v}
297 This is referred to as the ``LF-Middle`` scheme :cite:`Zhang_2019`, where LF stands
298 for Leap-Frog. In contrast to the previous scheme, it is not time-reversible.
299 However, in single time-scale simulations, the two approaches result in equivalent
300 coordinate trajectories, while the latter provides a velocity trajectory more
301 consistent with the Maxwell-Boltzmann distribution at the specified temperature
302 :cite:`Zhang_2019`.
304 Parameters
305 ----------
306 temperature : unit.Quantity
307 The temperature of the heat bath.
308 step_size : float or unit.Quantity
309 The outer step size with which to integrate the equations of motion.
311 Keyword Args
312 ------------
313 num_rattles : int, default=0
314 The number of RATTLE computations for geodesic integration
315 :cite:`Leimkuhler_2016`. If ``num_rattles=0``, then no constraints are
316 considered at all.
317 scheme : str, default='VV-Middle'
318 Which splitting scheme will be used. Valid options are 'VV-Middle' and
319 'LF-Middle'.
320 respa_loops : list(int), default=[1]
321 A list of `m` integers, where `respa_loops[k]` determines how many substeps
322 with force group `k` are internally executed for every step with force group
323 `k+1`.
324 bath_loops : int, default=1
325 The number of iterations of the bath operator per each step at time scale
326 `0`. This is useful when the bath operator is not exact, but derived from a
327 splitting solution.
328 embodied_force_groups : list(int), default=[]
329 A list of indices of force groups. The presence of an index `i` is this list
330 means that the contribution of force group `i` is embodied in force group
331 `i+1`. Therefore, such contribution must be properly subtracted during the
332 integration at time scale `i+1`.
333 unroll_loops : bool, default=True
334 Whether the integrator loops should be unrolled for improving efficiency.
335 Using ``unroll_loops=False`` can be useful for printing the integrator
336 steps.
338 Example
339 -------
340 >>> from ufedmm import integrators
341 >>> from openmm import unit
342 >>> class MiddleNoseHooverIntegrator(integrators.AbstractMiddleRespaIntegrator):
343 ... def __init__(self, ndof, tau, temperature, step_size, num_rattles=1):
344 ... super().__init__(
345 ... temperature, step_size, num_rattles, 'VV-Middle', [1], 1
346 ... )
347 ... kB = 8.3144626E-3*unit.kilojoules_per_mole/unit.kelvin
348 ... gkT = ndof*unit.MOLAR_GAS_CONSTANT_R*temperature
349 ... self.addGlobalVariable('gkT', gkT)
350 ... self.addGlobalVariable('Q', gkT*tau**2)
351 ... self.addGlobalVariable('v_eta', 0)
352 ... self.addGlobalVariable('twoK', 0)
353 ... self.addGlobalVariable('scaling', 1)
354 ... def _bath(self, fraction):
355 ... self.addComputeSum('twoK', 'm*v*v')
356 ... self.addComputeGlobal(
357 ... 'v_eta', f'v_eta + {0.5*fraction}*dt*(twoK - gkT)/Q'
358 ... )
359 ... self.addComputeGlobal('scaling', f'exp(-{fraction}*dt*v_eta)')
360 ... self.addComputePerDof('v', f'v*scaling')
361 ... self.addComputeGlobal(
362 ... 'v_eta', f'v_eta + {0.5*fraction}*dt*(scaling^2*twoK - gkT)/Q'
363 ... )
364 >>> integrator = MiddleNoseHooverIntegrator(
365 ... 500, 10*unit.femtoseconds, 300*unit.kelvin,
366 ... 1*unit.femtoseconds, num_rattles=0
367 ... )
368 >>> print(integrator)
369 Per-dof variables:
370 kT
371 Global variables:
372 gkT = 1247.169392722986
373 Q = 0.1247169392722986
374 v_eta = 0.0
375 twoK = 0.0
376 scaling = 1.0
377 Computation steps:
378 0: allow forces to update the context state
379 1: v <- v + 0.5*dt*f/m
380 2: x <- x + 0.5*dt*v
381 3: constrain positions
382 4: twoK <- sum(m*v*v)
383 5: v_eta <- v_eta + 0.5*dt*(twoK - gkT)/Q
384 6: scaling <- exp(-1.0*dt*v_eta)
385 7: v <- v*scaling
386 8: v_eta <- v_eta + 0.5*dt*(scaling^2*twoK - gkT)/Q
387 9: x <- x + 0.5*dt*v
388 10: constrain positions
389 11: v <- v + 0.5*dt*f/m
390 """
392 def __init__( # noqa: PLR0913, PLR0917
393 self,
394 temperature,
395 step_size,
396 num_rattles=0,
397 scheme="VV-Middle",
398 respa_loops=None,
399 bath_loops=1,
400 intertwine=True,
401 embodied_force_groups=None,
402 unroll_loops=True,
403 ):
404 if respa_loops is None:
405 respa_loops = [1]
406 if embodied_force_groups is None:
407 embodied_force_groups = []
408 if scheme not in ["LF-Middle", "VV-Middle"]:
409 raise Exception(f"Invalid value {scheme} for keyword scheme")
410 super().__init__(temperature, step_size)
411 self._num_rattles = num_rattles
412 self._scheme = scheme
413 self._respa_loops = respa_loops
414 self._bath_loops = bath_loops
415 self._intertwine = intertwine
416 self._subtractive_groups = embodied_force_groups
417 num_rattles > 0 and self.addPerDofVariable("x0", 0)
418 num_rattles > 1 and self.addGlobalVariable("irattle", 0)
419 if not unroll_loops:
420 for scale, n in enumerate(respa_loops):
421 n > 1 and self.addGlobalVariable(f"irespa{scale}", 0)
422 bath_loops > 1 and self.addGlobalVariable("ibath", 0)
423 if embodied_force_groups:
424 self.addPerDofVariable("f_emb", 0)
425 integration_groups = set(range(len(respa_loops))) - set(
426 embodied_force_groups
427 )
428 self.setIntegrationForceGroups(integration_groups)
430 self.addUpdateContextState()
431 self._step_initialization()
432 if unroll_loops:
433 self._integrate_respa_unrolled(1, len(respa_loops) - 1)
434 else:
435 self._integrate_respa(1, len(respa_loops) - 1)
437 def _step_initialization(self):
438 pass
440 def _integrate_respa(self, fraction, scale):
441 if scale >= 0:
442 n = self._respa_loops[scale]
443 if n > 1:
444 self.addComputeGlobal(f"irespa{scale}", "0")
445 self.beginWhileBlock(f"irespa{scale} < {n - 1 / 2}")
446 self._boost(fraction / (2 * n if self._scheme == "VV-Middle" else n), scale)
447 self._integrate_respa(fraction / n, scale - 1)
448 self._scheme == "VV-Middle" and self._boost(fraction / (2 * n), scale)
449 if n > 1:
450 self.addComputeGlobal(f"irespa{scale}", f"irespa{scale} + 1")
451 self.endBlock()
452 else:
453 self._intertwine or self._translation(0.5 * fraction)
454 n = self._bath_loops
455 if n > 1:
456 self.addComputeGlobal("ibath", "0")
457 self.beginWhileBlock(f"ibath < {n - 1 / 2}")
458 self._intertwine and self._translation(0.5 * fraction / n)
459 self._bath(fraction / n)
460 self._num_rattles > 0 and self.addConstrainVelocities()
461 self._intertwine and self._translation(0.5 * fraction / n)
462 if n > 1:
463 self.addComputeGlobal("ibath", "ibath + 1")
464 self.endBlock()
465 self._intertwine or self._translation(0.5 * fraction)
467 def _integrate_respa_unrolled(self, fraction, scale):
468 if scale >= 0:
469 n = self._respa_loops[scale]
470 for i in range(n):
471 self._boost(
472 fraction / (2 * n if self._scheme == "VV-Middle" and i == 0 else n),
473 scale,
474 )
475 self._integrate_respa_unrolled(fraction / n, scale - 1)
476 self._scheme == "VV-Middle" and i == n - 1 and self._boost(
477 fraction / (2 * n), scale
478 )
479 else:
480 n = self._bath_loops
481 self._intertwine or self._translation(0.5 * fraction)
482 for i in range(n):
483 self._intertwine and self._translation(
484 fraction / (2 * n if i == 0 else n)
485 )
486 self._bath(fraction / n)
487 self._num_rattles > 0 and self.addConstrainVelocities()
488 i == n - 1 and self._intertwine and self._translation(
489 fraction / (2 * n)
490 )
491 self._intertwine or self._translation(0.5 * fraction)
493 def _translation(self, fraction):
494 if self._num_rattles > 1:
495 self.addComputeGlobal("irattle", "0")
496 self.beginWhileBlock(f"irattle < {self._num_rattles - 1 / 2}")
497 self.addComputePerDof("x", f"x + {fraction / max(1, self._num_rattles)}*dt*v")
498 if self._num_rattles == 0:
499 # Some platforms only update virtual sites in this kind of step
500 self.addConstrainPositions()
501 if self._num_rattles > 0:
502 self.addComputePerDof("x0", "x")
503 self.addConstrainPositions()
504 self.addComputePerDof(
505 "v", f"v + (x - x0)/({fraction / self._num_rattles}*dt)"
506 )
507 self.addConstrainVelocities()
508 if self._num_rattles > 1:
509 self.addComputeGlobal("irattle", "irattle + 1")
510 self.endBlock()
512 def _boost(self, fraction, scale):
513 if len(self._respa_loops) > 1:
514 if scale - 1 in self._subtractive_groups:
515 self.addComputePerDof("f_emb", f"f{scale - 1}")
516 self.addComputePerDof("v", f"v + {fraction}*dt*(f{scale}-f_emb)/m")
517 else:
518 self.addComputePerDof("v", f"v + {fraction}*dt*f{scale}/m")
519 else:
520 self.addComputePerDof("v", f"v + {fraction}*dt*f/m")
521 self._num_rattles > 0 and self.addConstrainVelocities()
523 def _bath(self, fraction):
524 return
527class GeodesicLangevinIntegrator(AbstractMiddleRespaIntegrator):
528 """A geodesic Langevin integrator :cite:`Leimkuhler_2016`, which can be integrated
529 by using either the LF-Middle or the VV-Middle scheme :cite:`Zhang_2019`.
531 .. note:
532 The VV-Middle scheme is also known as the BAOAB :cite:`Leimkuhler_2016` method.
534 Parameters
535 ----------
536 temperature : float or unit.Quantity
537 The temperature.
538 friction_coefficient : float or unit.Quantity
539 The friction coefficient.
540 step_size : float or unit.Quantity
541 The time-step size.
543 Keyword Args
544 ------------
545 num_rattles : int, default=1
546 The number of RATTLE computations for geodesic integration
547 :cite:`Leimkuhler_2016`. If ``num_rattles=0``, then no constraints are
548 considered at all.
549 scheme : str, default='LF-Middle'
550 Which splitting scheme will be used. Valid options are 'VV-Middle' and
551 'LF-Middle'.
552 **kwargs
553 All other keyword arguments in :class:`AbstractMiddleRespaIntegrator`.
555 Example
556 -------
557 >>> import ufedmm
558 >>> dt = 2*unit.femtoseconds
559 >>> temp = 300*unit.kelvin
560 >>> gamma = 10/unit.picoseconds
561 >>> ufedmm.GeodesicLangevinIntegrator(
562 ... temp, gamma, dt, num_rattles=1, scheme='VV-Middle'
563 ... )
564 Per-dof variables:
565 kT, x0
566 Global variables:
567 friction = 10.0
568 Computation steps:
569 0: allow forces to update the context state
570 1: v <- v + 0.5*dt*f/m
571 2: constrain velocities
572 3: x <- x + 0.5*dt*v
573 4: x0 <- x
574 5: constrain positions
575 6: v <- v + (x - x0)/(0.5*dt)
576 7: constrain velocities
577 8: v <- z*v + sqrt((1 - z*z)*kT/m)*gaussian; z = exp(-friction*1.0*dt)
578 9: constrain velocities
579 10: x <- x + 0.5*dt*v
580 11: x0 <- x
581 12: constrain positions
582 13: v <- v + (x - x0)/(0.5*dt)
583 14: constrain velocities
584 15: v <- v + 0.5*dt*f/m
585 16: constrain velocities
586 """
588 def __init__(
589 self,
590 temperature,
591 friction_coefficient,
592 step_size,
593 num_rattles=1,
594 scheme="LF-Middle",
595 **kwargs,
596 ):
597 super().__init__(
598 temperature, step_size, num_rattles=num_rattles, scheme=scheme, **kwargs
599 )
600 self.addGlobalVariable("friction", friction_coefficient)
602 def _bath(self, fraction):
603 expression = (
604 f"z*v + sqrt((1 - z*z)*kT/m)*gaussian; z = exp(-friction*{fraction}*dt)"
605 )
606 self.addComputePerDof("v", expression)
609class MiddleMassiveNHCIntegrator(AbstractMiddleRespaIntegrator):
610 """A massive, middle-type Nose-Hoover Chain Thermostat solver :cite:`Martyna_1992`
611 with optional multiple time-scale integration via RESPA.
613 To enable RESPA, the forces in OpenMM system must be split into distinct force
614 groups and the keyword ``respa_loop`` (see below) must be a list with multiple
615 entries.
617 Parameters
618 ----------
619 temperature : float or unit.Quantity
620 The temperature.
621 time_constant : float or unit.Quantity
622 The characteristic time constant.
623 step_size : float or unit.Quantity
624 The time-step size.
626 Keyword Args
627 ------------
628 nchain : int, default=4
629 The number of thermostats in each Nose-Hoover chain. Short chains can
630 sample stiff, nearly harmonic degrees of freedom poorly.
631 **kwargs
632 All keyword arguments in :class:`AbstractMiddleRespaIntegrator`, except
633 ``num_rattles``.
635 Example
636 -------
637 >>> import ufedmm
638 >>> temp, tau, dt = 300*unit.kelvin, 10*unit.femtoseconds, 2*unit.femtoseconds
639 >>> integrator = ufedmm.MiddleMassiveNHCIntegrator(
640 ... temp, tau, dt, respa_loops=[4, 1], unroll_loops=False
641 ... )
642 >>> print(integrator)
643 Per-dof variables:
644 kT, Q, v1, v2, v3, v4
645 Global variables:
646 irespa0 = 0.0
647 Computation steps:
648 0: allow forces to update the context state
649 1: v <- v + 0.5*dt*f1/m
650 2: irespa0 <- 0
651 3: while (irespa0 < 3.5):
652 4: v <- v + 0.125*dt*f0/m
653 5: x <- x + 0.125*dt*v
654 6: constrain positions
655 7: v4 <- v4 + 0.125*dt*(Q*v3^2 - kT)/Q
656 8: v3 <- (v3*z + 0.125*dt*(Q*v2^2 - kT)/Q)*z; z=exp(-0.0625*dt*v4)
657 9: v2 <- (v2*z + 0.125*dt*(Q*v1^2 - kT)/Q)*z; z=exp(-0.0625*dt*v3)
658 10: v1 <- (v1*z + 0.125*dt*(m*v^2 - kT)/Q)*z; z=exp(-0.0625*dt*v2)
659 11: v <- v*exp(-0.25*dt*v1)
660 12: v1 <- (v1*z + 0.125*dt*(m*v^2 - kT)/Q)*z; z=exp(-0.0625*dt*v2)
661 13: v2 <- (v2*z + 0.125*dt*(Q*v1^2 - kT)/Q)*z; z=exp(-0.0625*dt*v3)
662 14: v3 <- (v3*z + 0.125*dt*(Q*v2^2 - kT)/Q)*z; z=exp(-0.0625*dt*v4)
663 15: v4 <- v4 + 0.125*dt*(Q*v3^2 - kT)/Q
664 16: x <- x + 0.125*dt*v
665 17: constrain positions
666 18: v <- v + 0.125*dt*f0/m
667 19: irespa0 <- irespa0 + 1
668 20: end
669 21: v <- v + 0.5*dt*f1/m
670 """
672 def __init__(
673 self,
674 temperature,
675 time_constant,
676 step_size,
677 nchain=4,
678 **kwargs,
679 ):
680 if "num_rattles" in kwargs.keys() and kwargs["num_rattles"] != 0:
681 raise ValueError(f"{self.__class__.__name__} cannot handle constraints")
682 self._tau = _standardized(time_constant)
683 self._nchain = nchain
684 super().__init__(temperature, step_size, **kwargs)
685 self.addPerDofVariable("Q", 0)
686 for i in range(nchain):
687 self.addPerDofVariable(f"v{i + 1}", 0)
689 def update_temperatures(self, system_temperature, extended_space_temperatures):
690 super().update_temperatures(system_temperature, extended_space_temperatures)
691 Q = [self._tau**2 * kT for kT in self._isotropic_kT()]
692 self.setPerDofVariableByName("Q", Q)
694 def _bath(self, fraction):
695 n = self._nchain
697 def a(i):
698 return f"(Q*v{i - 1}^2 - kT)/Q" if i > 1 else "(m*v^2 - kT)/Q"
700 def z(i):
701 return f"exp(-{fraction / 4}*dt*v{i + 1})"
703 self.addComputePerDof(f"v{n}", f"v{n} + {fraction / 2}*dt*{a(n)}")
704 for i in reversed(range(1, n)):
705 self.addComputePerDof(
706 f"v{i}", f"(v{i}*z + {fraction / 2}*dt*{a(i)})*z; z={z(i)}"
707 )
708 self.addComputePerDof("v", f"v*exp(-{fraction}*dt*v1)")
709 for i in range(1, n):
710 self.addComputePerDof(
711 f"v{i}", f"(v{i}*z + {fraction / 2}*dt*{a(i)})*z; z={z(i)}"
712 )
713 self.addComputePerDof(f"v{n}", f"v{n} + {fraction / 2}*dt*{a(n)}")
716class MiddleMassiveGGMTIntegrator(AbstractMiddleRespaIntegrator):
717 """A massive, middle-type Generalized Gaussian Moment Thermostat :cite:`Liu_2000`
718 solver with optional multiple time-scale integration via RESPA.
720 To enable RESPA, the forces in OpenMM system must be split into distinct force
721 groups and the keyword ``respa_loop`` (see below) must be a list with multiple
722 entries.
724 .. warning::
725 The velocity update of this solver involves the square root of
726 :math:`1 + 2 \\delta t\\, m v^2 v_2/3`, which becomes negative when the
727 thermostat variable :math:`v_2` is negative and the kinetic energy of a degree
728 of freedom is large. Velocities can then become NaN, and this gets more likely
729 as the ratio between the step size and the time constant grows. For example,
730 one in 250 harmonic degrees of freedom failed after a few thousand steps with
731 a 5 fs step size and a 100 fs time constant. The GGMT integrators of
732 `OpenXPS <https://github.com/craabreu/openxps>`_, the successor of UFEDMM, use
733 a splitting without this singularity.
735 Parameters
736 ----------
737 temperature : float or unit.Quantity
738 The temperature.
739 time_constant : float or unit.Quantity
740 The characteristic time constant.
741 step_size : float or unit.Quantity
742 The time-step size.
744 Keyword Args
745 ------------
746 **kwargs
747 All keyword arguments in :class:`AbstractMiddleRespaIntegrator`, except
748 ``num_rattles``.
750 Example
751 -------
752 >>> import ufedmm
753 >>> temp, tau, dt = 300*unit.kelvin, 10*unit.femtoseconds, 2*unit.femtoseconds
754 >>> integrator = ufedmm.MiddleMassiveGGMTIntegrator(temp, tau, dt)
755 >>> print(integrator)
756 Per-dof variables:
757 kT, Q1, Q2, v1, v2
758 Computation steps:
759 0: allow forces to update the context state
760 1: v <- v + 0.5*dt*f/m
761 2: x <- x + 0.5*dt*v
762 3: constrain positions
763 4: v1 <- v1 + 0.5*dt*(m*v^2 - kT)/Q1
764 5: v2 <- v2 + 0.5*dt*((m*v^2)^2/3 - kT^2)/Q2
765 6: v <- v*exp(-1.0*dt*(v1 + kT*v2))/sqrt(1 + 2.0*dt*m*v^2*v2/3)
766 7: v1 <- v1 + 0.5*dt*(m*v^2 - kT)/Q1
767 8: v2 <- v2 + 0.5*dt*((m*v^2)^2/3 - kT^2)/Q2
768 9: x <- x + 0.5*dt*v
769 10: constrain positions
770 11: v <- v + 0.5*dt*f/m
771 """
773 def __init__(self, temperature, time_constant, step_size, **kwargs):
774 if "num_rattles" in kwargs.keys() and kwargs["num_rattles"] != 0:
775 raise ValueError(f"{self.__class__.__name__} cannot handle constraints")
776 self._tau = _standardized(time_constant)
777 super().__init__(temperature, step_size, **kwargs)
778 self.addPerDofVariable("Q1", 0)
779 self.addPerDofVariable("Q2", 0)
780 self.addPerDofVariable("v1", 0)
781 self.addPerDofVariable("v2", 0)
783 def set_extended_space_time_constants(self, time_constants):
784 self._xs_taus = [_standardized(tau) for tau in time_constants]
786 def update_temperatures(self, system_temperature, extended_space_temperatures):
787 super().update_temperatures(system_temperature, extended_space_temperatures)
788 kT_vectors = self._isotropic_kT()
789 kT3_vectors = [openmm.Vec3(kT.x**3, kT.y**3, kT.z**3) for kT in kT_vectors]
790 if hasattr(self, "_xs_taus"):
791 num_particles = len(kT_vectors) - len(extended_space_temperatures)
792 taus = [self._tau] * num_particles + self._xs_taus
793 Q1 = [kT * tau**2 for kT, tau in zip(kT_vectors, taus)]
794 Q2 = [8 / 3 * kT3 * tau**2 for kT3, tau in zip(kT3_vectors, taus)]
795 else:
796 Q1 = [kT * self._tau**2 for kT in kT_vectors]
797 Q2 = [8 / 3 * kT3 * self._tau**2 for kT3 in kT3_vectors]
798 self.setPerDofVariableByName("Q1", Q1)
799 self.setPerDofVariableByName("Q2", Q2)
801 def _bath(self, fraction):
802 self.addComputePerDof("v1", f"v1 + {fraction / 2}*dt*(m*v^2 - kT)/Q1")
803 self.addComputePerDof("v2", f"v2 + {fraction / 2}*dt*((m*v^2)^2/3 - kT^2)/Q2")
804 self.addComputePerDof(
805 "v",
806 f"v*exp(-{fraction}*dt*(v1 + kT*v2))"
807 f"/sqrt(1 + {2 * fraction}*dt*m*v^2*v2/3)",
808 )
809 self.addComputePerDof("v1", f"v1 + {fraction / 2}*dt*(m*v^2 - kT)/Q1")
810 self.addComputePerDof("v2", f"v2 + {fraction / 2}*dt*((m*v^2)^2/3 - kT^2)/Q2")
813class RegulatedNHLIntegrator(AbstractMiddleRespaIntegrator):
814 """A regulated version of the massive Nose-Hoover-Langevin
815 :cite:`Samoletov_2007,Leimkuhler_2009` method. Regulation means that the system
816 Hamiltonian is modified so that velocities remain below a temperature-dependent
817 limit. This is closely related to the SIN(R) method :cite:`Leimkuhler_2013` and
818 allows multiple time-scale integration with very large outer time steps, without
819 resonance.
821 .. info:
822 If `regulation_parameter = 1` (default), this method is equivalent to SIN(R)
823 with a single thermostat per degree of freedom (that is, `L=1`).
825 The following :term:`SDE` system is solved for every degree of freedom in the
826 system:
828 .. math::
829 & dr_i = v_i dt \\\\
830 & dp_i = F_i dt - v_{\\eta_i} m_i v_i dt \\\\
831 & dv_{\\eta_i} = \\frac{1}{Q}\\left(\\frac{n+1}{n} m_i v_i^2 - k_B T\\right) dt
832 - \\gamma v_{\\eta_i} dt + \\sqrt{\\frac{2\\gamma k_B T}{Q}} dW_i,
834 where:
836 .. math::
837 v_i = c_i \\tanh\\left(\\frac{p_i}{m_i c_i}\\right).
839 Here, :math:`n` is the regulation parameter and :math:`c_i` is the maximum speed for
840 degree of freedom `i`, given by :math:`c_i = \\sqrt{\\frac{n k T}{m_i}}`. The
841 inertial parameter :math:`Q` is defined as :math:`Q = n k_B T \\tau^2`, with
842 :math:`\\tau` being a relaxation time :cite:`Tuckerman_1992`. An approximate
843 solution is obtained by applying the Trotter-Suzuki splitting formula:
845 .. math::
846 e^{\\Delta t\\mathcal{L}} =
847 e^{\\frac{\\Delta t}{2}\\mathcal{L}^1_p}
848 \\left[e^{\\frac{\\delta t}{2}\\mathcal{L}^0_p}
849 e^{\\frac{\\delta t}{2}\\mathcal{L}_r}
850 e^{\\delta t \\mathcal{L}_\\mathrm{bath}}
851 e^{\\frac{\\delta t}{2}\\mathcal{L}_r}
852 e^{\\frac{\\delta t}{2}\\mathcal{L}^0_p}\\right]^m
853 e^{\\frac{\\Delta t}{2}\\mathcal{L}^1_p}
855 where :math:`\\delta t = \\frac{\\Delta t}{m}`. Each exponential operator above is
856 the solution of a differential equation.
858 The exact solution for the physical-system part is:
860 .. math::
861 r_i(t) = r_i^0 + c_i \\mathrm{tanh}\\left(\\frac{p_i}{m c_i}\\right) t
863 .. math::
864 p_i(t) = p_i^0 + F_i t
866 The bath propagator is further split as:
868 .. math::
869 e^{\\delta t \\mathcal{L}_\\mathrm{bath}} =
870 e^{\\frac{\\delta t}{2m}\\mathcal{L}_B}
871 e^{\\frac{\\delta t}{2m}\\mathcal{L}_S}
872 e^{\\frac{\\delta t}{m}\\mathcal{L}_O}
873 e^{\\frac{\\delta t}{2m}\\mathcal{L}_S}
874 e^{\\frac{\\delta t}{2m}\\mathcal{L}_B}
876 Part 'B' is a boost, whose solution is:
878 .. math::
879 v_{\\eta_i}(t) = v_{\\eta_i}^0 +
880 \\frac{1}{Q}\\left(\\frac{n+1}{n} m_i v_i^2 - k_B T\\right) t
882 Part 'S' is a scaling, whose solution is:
884 .. math::
885 p_i(t) = m_i c_i \\mathrm{arcsinh}\\left[
886 \\sinh\\left(\\frac{p_i^0}{m_i c_i}\\right) e^{- v_{\\eta_i} t}
887 \\right]
889 Part 'O' is an Ornstein–Uhlenbeck process, whose solution is:
891 .. math::
892 v_{\\eta_i}(t) = v_{\\eta_i}^0 e^{-\\gamma t}
893 + \\sqrt{\\frac{k_B T}{Q}(1-e^{-2\\gamma t})} R_N
895 where :math:`R_N` is a normally distributed random number.
897 Parameters
898 ----------
899 step_size : float or unit.Quantity
900 The outer step size with which to integrate the equations of motion.
901 loops : int
902 The number of internal substeps at each time step.
903 temperature : unit.Quantity
904 The temperature of the heat bath.
905 time_scale : unit.Quantity (time)
906 The relaxation time (:math:`\\tau`) of the Nose-Hoover thermostat.
907 friction_coefficient : unit.Quantity (1/time)
908 The friction coefficient (:math:`\\gamma`) of the Langevin thermostat.
909 regulation_parameter : int or float
910 The regulation parameter n.
912 Keyword Args
913 ------------
914 semi_regulated : bool, default=True
915 Whether to use the semi-regulated NHL version of the method instead of its
916 fully-regulated version.
917 split_ornstein_uhlenbeck : bool, default=True
918 Whether to split the drifted Ornstein-Uhlenbeck operator.
919 **kwargs
920 All keyword arguments in :class:`AbstractMiddleRespaIntegrator`, except
921 ``num_rattles``.
922 """
924 def __init__( # noqa: PLR0913, PLR0917
925 self,
926 temperature,
927 time_constant,
928 friction_coefficient,
929 step_size,
930 regulation_parameter,
931 semi_regulated=True,
932 split_ornstein_uhlenbeck=True,
933 **kwargs,
934 ):
935 if "num_rattles" in kwargs.keys() and kwargs["num_rattles"] != 0:
936 raise ValueError(f"{self.__class__.__name__} cannot handle constraints")
937 self._tau = np.sqrt(regulation_parameter) * time_constant
938 self._n = regulation_parameter
939 self._split = split_ornstein_uhlenbeck
940 self._semi_regulated = semi_regulated
941 super().__init__(temperature, step_size, **kwargs)
942 self.addPerDofVariable("invQ", 0)
943 self.addPerDofVariable("v_eta", 0)
944 self.addPerDofVariable("c", 0)
945 self.addPerDofVariable("kTc", unit.MOLAR_GAS_CONSTANT_R * temperature)
946 self.addGlobalVariable("friction", friction_coefficient)
947 self.addGlobalVariable("omega", 1.0 / self._tau)
948 self.addGlobalVariable("aa", 0)
949 self.addGlobalVariable("bb", 0)
951 def update_temperatures(self, system_temperature, extended_space_temperatures):
952 super().update_temperatures(system_temperature, extended_space_temperatures)
953 kT_vectors = self._isotropic_kT()
954 self.setPerDofVariableByName("kTc", kT_vectors)
955 tauSq = _standardized(self._tau) ** 2
956 Q = [tauSq * kT for kT in kT_vectors]
957 invQ = [openmm.Vec3(*(1 / x if x > 0.0 else 0.0 for x in q)) for q in Q]
958 self.setPerDofVariableByName("invQ", invQ)
960 def _step_initialization(self):
961 self.addComputePerDof("c", f"sqrt({self._n}*kTc/m)")
962 n = np.prod(self._respa_loops) * self._bath_loops
963 self.addComputeGlobal("aa", f"exp(-friction*dt/{n})")
964 self.addComputeGlobal("bb", "omega*sqrt(1-aa^2)")
966 def _translation(self, fraction):
967 n = self._n
968 if self._semi_regulated:
969 expression = f"0.5*m*v*c*tanh(v/c); c=sqrt({n}*kTc/m)"
970 else:
971 expression = f"{0.5 * (n + 1) / n}*m*(c*tanh(v/c))^2; c=sqrt({n}*kTc/m)"
972 self.setKineticEnergyExpression(expression)
973 self.addComputePerDof("x", f"x + c*tanh(v/c)*{fraction}*dt")
974 # Some platforms only update virtual sites in this kind of step
975 self.addConstrainPositions()
977 def _bath(self, fraction):
978 n = self._n
980 if self._semi_regulated:
981 G = "; G=(m*v*c*tanh(v/c) - kT)*invQ"
982 else:
983 G = f"; G=({(n + 1) / n}*m*(c*tanh(v/c))^2 - kT)*invQ"
985 if self._split:
986 boost = f"v_eta + G*{0.5 * fraction}*dt" + G
988 if self._semi_regulated:
989 scaling = f"v*exp(-v_eta*{0.5 * fraction}*dt)"
990 else:
991 scaling = (
992 "c*asinh_z"
993 "; asinh_z=(2*step(z)-1)*log(select(step(za-1E8),2*za,za+sqrt(1+z*z)))"
994 "; za=abs(z)"
995 f"; z=sinh(v/c)*exp(-v_eta*{0.5 * fraction}*dt)"
996 )
998 if self._split:
999 Ornstein_Uhlenbeck = "v_eta*aa + bb*gaussian"
1000 else:
1001 Ornstein_Uhlenbeck = "v_eta*aa + G*(1-aa)/friction + bb*gaussian" + G
1003 self._split and self.addComputePerDof("v_eta", boost)
1004 self.addComputePerDof("v", scaling)
1005 self.addComputePerDof("v_eta", Ornstein_Uhlenbeck)
1006 self.addComputePerDof("v", scaling)
1007 self._split and self.addComputePerDof("v_eta", boost)