Coverage for openxps/metadynamics.py: 97%
87 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.metadynamics
3 :platform: Linux, Windows, macOS
4 :synopsis: Bias potentials applied to dynamical variables.
6.. moduleauthor:: Charlles Abreu <craabreu@gmail.com>
8"""
10import typing as t
11from dataclasses import dataclass, field
12from functools import reduce
14import numpy as np
15from cvpack.serialization import Serializable
16from openmm import app as mmapp
17from openmm import unit as mmunit
19from .bounds import NoBounds, PeriodicBounds
20from .dynamical_variable import DynamicalVariable
21from .system import ExtendedSpaceSystem
22from .utils import ExtensionSimulation, preprocess_args
25def _von_mises(displacement: np.ndarray, sigma: float, period: float) -> np.ndarray:
26 """A Gaussian in the chord distance ``(period/pi)*sin(pi*displacement/period)``.
28 It is smooth and periodic, and matches a Gaussian of width ``sigma`` when the
29 displacement is much smaller than the period.
30 """
31 factor = 2 * np.pi / period
32 return np.exp((np.cos(factor * displacement) - 1) / (factor * sigma) ** 2)
35def _axis_kernel(
36 grid: np.ndarray,
37 center: float,
38 sigma: float,
39 bounds: str,
40 lower: float,
41 upper: float,
42) -> np.ndarray:
43 """The bias kernel along one axis, on the given grid points.
45 Periodic variables get a von Mises kernel. Reflective variables get the sum of
46 all mirror images of a Gaussian across both walls, which are images of period
47 ``2*(upper - lower)`` centered at ``center`` and ``2*lower - center``. Two von
48 Mises kernels of that period therefore account for every image, and the kernel
49 has zero slope at both walls.
50 """
51 if bounds == PeriodicBounds.kind:
52 return _von_mises(grid - center, sigma, upper - lower)
53 period = 2 * (upper - lower)
54 return _von_mises(grid - center, sigma, period) + _von_mises(
55 grid + center - 2 * lower, sigma, period
56 )
59@dataclass(frozen=True)
60class ExtendedSpaceBiasVariable(Serializable):
61 """
62 A dynamical variable augmented with a bias kernel.
64 In :class:`ExtendedSpaceMetadynamics`, the kernel shape depends on the bounds of
65 the dynamical variable: a von Mises kernel for :class:`PeriodicBounds` and a
66 Gaussian mirrored across both walls for :class:`ReflectiveBounds`. In
67 :class:`~openxps.ExtendedSpaceOPES` and :class:`~openxps.ExtendedSpaceCombinedOPES`,
68 the kernels are those of openmm-opes, and ``sigma`` is the standard deviation of
69 the unbiased distribution of the variable.
71 Parameters
72 ----------
73 dynamical_variable
74 The dynamical variable to be augmented.
75 sigma
76 The bandwidth of the bias kernel, which approximates the standard deviation
77 of a Gaussian when it is small relative to the bounds.
78 grid_width
79 The width of the grid for the bias kernel. If ``None``, the grid width is
80 automatically determined based on the dynamical variable's bounds and the
81 bandwidth.
83 Example
84 -------
85 >>> import openxps as xps
86 >>> from openmm import unit
87 >>> dv = xps.DynamicalVariable(
88 ... "phi",
89 ... unit.radian,
90 ... 3 * unit.dalton*(unit.nanometer/unit.radian)**2,
91 ... xps.PeriodicBounds(-180, 180, unit.degree)
92 ... )
93 >>> bias_variable = xps.ExtendedSpaceBiasVariable(dv, 18 * unit.degree)
94 >>> bias_variable.dynamical_variable
95 DynamicalVariable(name='phi', unit=rad, mass=3 nm**2 Da/(rad**2), bounds=...)
96 """
98 dynamical_variable: DynamicalVariable
99 sigma: mmunit.Quantity
100 grid_width: int | None = field(default_factory=lambda: None)
102 def __post_init__(self) -> None:
103 if not mmunit.is_quantity(self.sigma):
104 raise TypeError("sigma must be a quantity")
105 if not self.sigma.unit.is_compatible(self.dynamical_variable.unit):
106 raise ValueError(
107 "sigma must be compatible with the dynamical variable's unit"
108 )
109 if self.sigma / self.sigma.unit <= 0:
110 raise ValueError("sigma must be positive")
111 if not (self.grid_width is None or isinstance(self.grid_width, int)):
112 raise TypeError("grid_width must be an integer or None")
113 if self.grid_width is not None and self.grid_width <= 1:
114 raise ValueError("grid_width must be greater than 1")
117ExtendedSpaceBiasVariable.__init__ = preprocess_args(ExtendedSpaceBiasVariable.__init__)
119ExtendedSpaceBiasVariable.registerTag("!openxps.metadynamics.ExtendedSpaceBiasVariable")
122class ExtendedSpaceMetadynamics(mmapp.Metadynamics):
123 """
124 Performs Extended Phase-Space (XPS) Metadynamics simulations, in which a bias
125 potential is applied to dynamical variables (DVs) to enhance sampling of the
126 physical coordinates.
128 Parameters
129 ----------
130 system
131 The :class:`ExtendedSpaceSystem` to be used in the XPS simulation.
132 variables
133 A sequence of :class:`ExtendedSpaceBiasVariable` objects to specify the biased
134 dynamical variables and their corresponding Gaussian kernels.
135 temperature
136 The temperature at which the simulation is being run. This is used in computing
137 the free energy.
138 biasFactor
139 Used in scaling the height of the Gaussians added to the bias. The dynamical
140 variables are sampled as if the effective temperature of the simulation were
141 temperature*biasFactor.
142 height
143 The initial height of the Gaussians to add (in units of energy).
144 frequency
145 The interval in time steps at which Gaussians should be added to the bias
146 potential.
147 saveFrequency
148 The interval in time steps at which to write out the current biases to disk. At
149 the same time it writes biases, it also checks for updated biases written by
150 other processes and loads them in. This must be a multiple of frequency.
151 biasDir
152 The directory to which biases should be written, and from which biases written
153 by other processes should be loaded.
155 .. note::
156 The bias is stored on a grid spanning the bounds of each dynamical variable,
157 so variables with :class:`NoBounds` are rejected. Use
158 :class:`ReflectiveBounds` over the range the variable may explore instead.
159 If the variable never reaches the walls, the reflections never act, and if
160 it does, the coupling turns them into soft walls on the physical system.
162 .. note::
163 Periodic and reflective variables can be mixed. A reflective variable is
164 tabulated as a periodic one of twice its range, holding the bias and its
165 mirror image, which makes the interpolated bias exactly flat at the walls.
166 This doubles the table along each reflective axis.
168 .. note::
169 The bias force is added to the extension system of ``system`` when this
170 object is created, so it must be created before the
171 :class:`~openxps.ExtendedSpaceSimulation` or
172 :class:`~openxps.ExtendedSpaceContext` that uses the system.
174 Example
175 -------
176 >>> import openxps as xps
177 >>> from openmm import unit
178 >>> import cvpack
179 >>> from math import pi
180 >>> import openmm
181 >>> from openmmtools import testsystems
182 >>> model = testsystems.AlanineDipeptideVacuum()
183 >>> phi = cvpack.Torsion(6, 8, 14, 16, name="phi")
184 >>> mass = 3 * unit.dalton*(unit.nanometer/unit.radian)**2
185 >>> phi0 = xps.DynamicalVariable("phi0", unit.radian, mass, xps.CircularBounds())
186 >>> phi = cvpack.Torsion(6, 8, 14, 16, name="phi")
187 >>> kappa = 1000 * unit.kilojoules_per_mole / unit.radian**2
188 >>> harmonic_force = xps.HarmonicCoupling(phi, phi0, kappa)
189 >>> system = xps.ExtendedSpaceSystem(model.system, harmonic_force)
190 >>> bias_variable = xps.ExtendedSpaceBiasVariable(phi0, 18 * unit.degrees)
191 >>> temperature = 300 * unit.kelvin
192 >>> metadynamics = xps.ExtendedSpaceMetadynamics(
193 ... system=system,
194 ... variables=[bias_variable],
195 ... temperature=temperature,
196 ... biasFactor=5,
197 ... height=2 * unit.kilojoule_per_mole,
198 ... frequency=100,
199 ... )
200 >>> simulation = xps.ExtendedSpaceSimulation(
201 ... model.topology,
202 ... system,
203 ... xps.LockstepIntegrator(
204 ... openmm.LangevinMiddleIntegrator(
205 ... temperature, 1 / unit.picosecond, 4 * unit.femtosecond
206 ... )
207 ... ),
208 ... openmm.Platform.getPlatformByName("Reference"),
209 ... )
210 >>> context = simulation.context
211 >>> context.setPositions(model.positions)
212 >>> context.setVelocitiesToTemperature(temperature, 1234)
213 >>> context.setDynamicalVariableValues([180 * unit.degree])
214 >>> context.setDynamicalVariableVelocitiesToTemperature(temperature, 1234)
215 >>> metadynamics.step(simulation, 100)
216 >>> print(metadynamics.getFreeEnergy())
217 [...] kJ/mol
218 """
220 def __init__( # noqa: PLR0913, PLR0917
221 self,
222 system: ExtendedSpaceSystem,
223 variables: t.Sequence[ExtendedSpaceBiasVariable],
224 temperature: mmunit.Quantity,
225 biasFactor: float,
226 height: mmunit.Quantity,
227 frequency: int,
228 saveFrequency: int | None = None,
229 biasDir: str | None = None,
230 ) -> None:
231 system_dvs = system.getDynamicalVariables()
232 bias_variables = []
233 for variable in variables:
234 dv = variable.dynamical_variable.in_md_units()
235 if dv not in system_dvs:
236 raise ValueError(f"Dynamical variable {dv.name} not found in system")
237 if isinstance(dv.bounds, NoBounds):
238 raise ValueError(
239 f"Dynamical variable {dv.name} has no bounds, but metadynamics "
240 "needs a finite grid. Use ReflectiveBounds over the range the "
241 "variable may explore."
242 )
243 index = system_dvs.index(dv)
244 bias_variables.append(
245 mmapp.BiasVariable(
246 dv.createCollectiveVariable(index),
247 dv.bounds.lower * dv.bounds.unit,
248 dv.bounds.upper * dv.bounds.unit,
249 variable.sigma,
250 True,
251 variable.grid_width,
252 )
253 )
254 # Every table axis is periodic, so OpenMM must not reject the mix of periodic
255 # and reflective variables. Their true periodicity is restored afterwards.
256 super().__init__(
257 system.getExtensionSystem(),
258 bias_variables,
259 temperature,
260 biasFactor,
261 height,
262 frequency,
263 saveFrequency,
264 biasDir,
265 )
266 self._bounds_kinds = [
267 variable.dynamical_variable.bounds.kind for variable in variables
268 ]
269 for v, kind in zip(self.variables, self._bounds_kinds):
270 v.periodic = kind == PeriodicBounds.kind
271 self._widths = [
272 v.gridWidth if v.periodic else 2 * v.gridWidth - 1 for v in self.variables
273 ]
274 self._limits = []
275 for v in self.variables:
276 upper = v.maxValue if v.periodic else 2 * v.maxValue - v.minValue
277 self._limits += [v.minValue, upper]
278 self._updateTable()
280 def step(self, simulation, steps):
281 super().step(ExtensionSimulation(simulation), steps)
283 def getCollectiveVariables(self, simulation):
284 return self._force.getCollectiveVariableValues(
285 simulation.context.getExtensionContext()
286 )
288 def _addGaussian(self, position, height, context):
289 """Add a kernel to the bias, overriding the truncated Gaussian of OpenMM."""
290 axis_kernels = []
291 for value, variable, kind in zip(position, self.variables, self._bounds_kinds):
292 lower, upper = variable.minValue, variable.maxValue
293 grid = np.linspace(lower, upper, variable.gridWidth)
294 kernel = _axis_kernel(grid, value, variable.biasWidth, kind, lower, upper)
295 if kind == PeriodicBounds.kind:
296 kernel[-1] = kernel[0]
297 axis_kernels.append(kernel)
298 kernel = reduce(np.multiply.outer, reversed(axis_kernels))
299 height = height.value_in_unit(mmunit.kilojoules_per_mole)
300 self._selfBias += height * kernel
301 self._totalBias += height * kernel
302 self._updateTable()
303 self._force.updateParametersInContext(context)
305 def _updateTable(self):
306 """Copy the total bias into the periodic table.
308 A reflective variable on ``[lower, upper]`` behaves as a periodic one of period
309 ``2*(upper - lower)`` whose bias is mirrored about ``upper``. Its table axis
310 holds the bias followed by its mirror image, so the periodic spline that
311 OpenMM fits is symmetric about both walls and has zero slope there.
312 """
313 bias = self._totalBias
314 # The bias array stores the last variable along its first axis.
315 for axis, v in enumerate(reversed(self.variables)):
316 if not v.periodic:
317 mirror = np.flip(np.take(bias, range(v.gridWidth - 1), axis=axis), axis)
318 bias = np.concatenate((bias, mirror), axis=axis)
319 if len(self.variables) == 1:
320 self._table.setFunctionParameters(bias.flatten(), *self._limits)
321 else:
322 self._table.setFunctionParameters(
323 *self._widths, bias.flatten(), *self._limits
324 )