Coverage for cvpack/path_in_rmsd_space.py: 95%
20 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-21 18:13 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-21 18:13 +0000
1"""
2.. class:: PathInRMSDSpace
3 :platform: Linux, MacOS, Windows
4 :synopsis: A metric of progress or deviation with respect to a path in RMSD space
6.. classauthor:: Charlles Abreu <craabreu@gmail.com>
8"""
10from __future__ import annotations
12import typing as t
14from openmm import unit as mmunit
16from .base_path_cv import BasePathCV
17from .path import Metric, progress
18from .rmsd import RMSD
19from .units.units import VectorQuantity, value_in_md_units
22class PathInRMSDSpace(BasePathCV):
23 r"""
24 A metric of the system's progress (:math:`s`) or deviation (:math:`z`) with
25 respect to a path defined by a sequence of :math:`n` milestones defined as
26 reference structures :cite:`Branduardi_2007`:
28 .. math::
30 s({\bf r}) = \frac{
31 \dfrac{\sum_{i=1}^n i w_i({\bf r})}{\sum_{i=1}^n w_i({\bf r})} - 1
32 }{n-1}
33 \quad \text{or} \quad
34 z({\bf r}) = - 2 \sigma ^2 \ln \sum_{i=1}^n w_i({\bf r})
36 with :math:`w_i({\bf r})` being a Gaussian kernel centered at the :math:`i`-th
37 milestone, i.e.,
39 .. math::
41 w_i({\bf r}) = \exp\left(\
42 -\frac{d^2_{\rm rms}({\bf r},{\bf r}^{\rm ref}_i)}{2 \sigma^2}
43 \right)
45 where :math:`d_{\rm rms}({\bf r},{\bf r}^{\rm ref}_i)` is the root-mean-square
46 deviation between the current system state and the :math:`i`-th reference structure
47 and :math:`\sigma` sets the width of the kernels.
49 .. note::
51 The kernel width :math:`\sigma` is related to the parameter :math:`\lambda` of
52 Ref. :cite:`Branduardi_2007` by :math:`\sigma = \frac{1}{\sqrt{2\lambda}}`.
54 .. note::
56 An OpenMM :OpenMM:`CustomCVForce` holds at most 32 collective variables. For
57 longer paths, the milestones are split into chunks, each evaluated by an inner
58 :OpenMM:`CustomCVForce`. The result is exact, but the progress metric computes
59 every RMSD twice in this case. Paths can have up to 1024 milestones for the
60 deviation metric and up to 512 for the progress metric.
62 Parameters
63 ----------
64 metric
65 The path-related metric to compute. Use ``cvpack.path.progress`` for
66 computing :math:`s({\bf r})` or ``cvpack.path.deviation`` for computing
67 :math:`z({\bf r})`.
68 milestones
69 A sequence of reference structures, each represented as a dictionary mapping
70 atom indices to coordinate vectors.
71 numAtoms
72 The total number of atoms in the system, including those that are not in
73 any of the reference structures.
74 sigma
75 The width of the Gaussian kernels in nanometers
76 name
77 The name of the collective variable. If not provided, it is set to
78 "path_progress_in_rmsd_space" or "path_deviation_in_rmsd_space" depending
79 on the metric.
81 Raises
82 ------
83 ValueError
84 If the number of milestones is less than 2
85 ValueError
86 If the metric is not `cvpack.path.progress` or `cvpack.path.deviation`
88 Examples
89 --------
90 >>> import cvpack
91 >>> import networkx as nx
92 >>> import numpy as np
93 >>> import openmm
94 >>> from openmm import unit
95 >>> from openmmtools import testsystems
96 >>> from scipy.spatial.transform import Rotation
97 >>> model = testsystems.AlanineDipeptideVacuum()
98 >>> atom1, atom2 = 8, 14
99 >>> graph = model.mdtraj_topology.to_bondgraph()
100 >>> nodes = list(graph.nodes)
101 >>> graph.remove_edge(nodes[atom1], nodes[atom2])
102 >>> movable = list(nx.connected_components(graph))[1]
103 >>> x = model.positions / model.positions.unit
104 >>> x0 = x[atom1, :]
105 >>> vector = x[atom2, :] - x0
106 >>> vector /= np.linalg.norm(vector)
107 >>> rotation = Rotation.from_rotvec((np.pi / 6) * vector)
108 >>> atoms = [nodes.index(atom) for atom in movable]
109 >>> frames = [x.copy()]
110 >>> for _ in range(6):
111 ... x[atoms, :] = x0 + rotation.apply(x[atoms, :] - x0)
112 ... frames.append(x.copy())
113 >>> milestones = [
114 ... {i: row for i, row in enumerate(frame)}
115 ... for frame in frames
116 ... ]
117 >>> s, z = [
118 ... cvpack.PathInRMSDSpace(
119 ... metric, milestones, len(x), 0.5 * unit.angstrom
120 ... )
121 ... for metric in (cvpack.path.progress, cvpack.path.deviation)
122 ... ]
123 >>> s.addToSystem(model.system)
124 >>> z.addToSystem(model.system)
125 >>> context = openmm.Context(model.system, openmm.VerletIntegrator(0.001))
126 >>> context.setPositions(model.positions)
127 >>> s.getValue(context)
128 0.172... dimensionless
129 >>> z.getValue(context)
130 -0.004... nm**2
131 """
133 def __init__(
134 self,
135 metric: Metric,
136 milestones: t.Sequence[dict[int, VectorQuantity]],
137 numAtoms: int,
138 sigma: mmunit.Quantity,
139 name: str | None = None,
140 ) -> None:
141 name = self._generateName(metric, name, "rmsd")
142 if mmunit.is_quantity(sigma):
143 sigma = sigma.value_in_unit(mmunit.nanometers)
144 n = len(milestones)
145 if n < 2: # noqa: PLR2004
146 raise ValueError("At least two reference structures are required.")
147 collective_variables = {
148 f"rmsd{i}": RMSD(reference, reference.keys(), numAtoms, name=f"rmsd{i}")
149 for i, reference in enumerate(milestones)
150 }
151 squared_distances = [f"rmsd{i}^2" for i in range(n)]
152 super().__init__(metric, sigma, squared_distances, collective_variables)
153 self._registerCV(
154 name,
155 mmunit.dimensionless if metric == progress else mmunit.nanometers**2,
156 metric=metric,
157 milestones=[
158 {int(k): [float(x) for x in value_in_md_units(v)] for k, v in m.items()}
159 for m in milestones
160 ],
161 numAtoms=numAtoms,
162 sigma=sigma,
163 )
166PathInRMSDSpace.registerTag("!cvpack.PathInRMSDSpace")