Coverage for cvpack/composite_rmsd.py: 100%
34 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:: CompositeRMSD
3 :platform: Linux, MacOS, Windows
4 :synopsis: Deviation of multiple corotating bodies from their reference structures
6.. classauthor:: Charlles Abreu <craabreu@gmail.com>
8"""
10from __future__ import annotations
12import itertools
13import typing as t
15import numpy as np
16import openmm
17from openmm import unit as mmunit
19from .base_rmsd import BaseRMSD
20from .units import MatrixQuantity, VectorQuantity
23class CompositeRMSD(BaseRMSD, openmm.CustomCVForce):
24 r"""
25 The composite root-mean-square deviation (RMSD) between the current and reference
26 coordinates of :math:`m` groups of atoms:
28 .. math::
30 d_{\rm crms}({\bf r}) = \sqrt{
31 \frac{1}{n} \min_{
32 \bf q \in \mathbb{R}^4 \atop \|{\bf q}\| = 1
33 } \sum_{j=1}^m \sum_{i \in {\bf g}_j} \left\|
34 {\bf A}({\bf q})\left({\bf r}_i - {\bf c}_j\right) -
35 {\bf r}_i^{\rm ref} + {\bf c}_j^{\rm ref}
36 \right\|^2
37 }
39 where each group :math:`{\bf g}_j` is a set of :math:`n_j` atom indices,
40 :math:`n = \sum_{j=1}^m n_j` is the total number of atoms in these groups,
41 :math:`{\bf A}(\bf q)` is the rotation matrix corresponding to a unit quaternion
42 :math:`{\bf q}`, :math:`{\bf r}_i` and :math:`{\bf r}_i^{\rm ref}` are the
43 positions of atom :math:`i` in the current and reference structures, respectively,
44 :math:`{\bf c}_j` is the centroid of group :math:`j`, given by
46 .. math::
48 {\bf c}_j = \frac{1}{n_j} \sum_{i \in {\bf g}_j} {\bf r}_i
50 and :math:`{\bf c}_j^{\rm ref}` is the centroid of the reference structure for
51 group :math:`j`, defined analogously to :math:`{\bf c}_j`.
53 .. note::
55 The computation is done by OpenMM's :OpenMM:`RMSDForce`, using reference
56 positions shifted so that every group's centroid lies at the origin. With these
57 references, the optimal rotation is the same as above, and the composite RMSD
58 follows from
60 .. math::
62 d_{\rm crms}^2 = d_{\rm rms}^2 - \frac{1}{n^2} \sum_{j=1}^{m-1}
63 \sum_{k=j+1}^m n_j n_k \left\|{\bf c}_j - {\bf c}_k\right\|^2
65 where :math:`d_{\rm rms}` is the RMSD computed by :OpenMM:`RMSDForce` and the
66 sum is computed by a :OpenMM:`CustomCentroidBondForce`.
68 .. warning::
70 Periodic boundary conditions are not supported. Each group of atoms must not be
71 split across periodic images.
73 Parameters
74 ----------
75 referencePositions
76 The reference coordinates, which can be either a coordinate matrix or a mapping
77 from atom indices to coordinate vectors. It must contain all atoms in
78 ``groups``, and does not need to contain all atoms in the system. See
79 ``numAtoms`` below.
80 groups
81 A sequence of disjoint atom groups. Each group is a sequence of atom indices.
82 numAtoms
83 The total number of atoms in the system, including those that are not in
84 ``groups``. This argument is necessary only if ``referencePositions`` does not
85 contain all atoms in the system.
86 name
87 The name of the collective variable.
89 Raises
90 ------
91 ValueError
92 If ``groups`` is not a sequence of disjoint, nonempty atom groups.
93 ValueError
94 If referencePositions is a dict and numAtoms is not given, or if numAtoms
95 is not positive.
97 Example
98 -------
99 >>> import cvpack
100 >>> import openmm as mm
101 >>> from openmmtools import testsystems
102 >>> from openmm import unit
103 >>> model = testsystems.HostGuestVacuum()
104 >>> host_atoms, guest_atoms = (
105 ... [a.index for a in r.atoms()]
106 ... for r in model.topology.residues()
107 ... )
108 >>> composite_rmsd = cvpack.CompositeRMSD(
109 ... model.positions,
110 ... [host_atoms, guest_atoms],
111 ... )
112 >>> composite_rmsd.addToSystem(model.system)
113 >>> context = mm.Context(
114 ... model.system,
115 ... mm.VerletIntegrator(1.0 * unit.femtoseconds),
116 ... mm.Platform.getPlatformByName('Reference'),
117 ... )
118 >>> context.setPositions(model.positions)
119 >>> round(composite_rmsd.getValue(context) / unit.nanometers, 6)
120 0.0
121 >>> model.positions[guest_atoms] += 1.0 * unit.nanometers
122 >>> context.setPositions(model.positions)
123 >>> round(composite_rmsd.getValue(context) / unit.nanometers, 6)
124 0.0
125 """
127 def __init__(
128 self,
129 referencePositions: MatrixQuantity | dict[int, VectorQuantity],
130 groups: t.Iterable[t.Iterable[int]],
131 numAtoms: int | None = None,
132 name: str = "composite_rmsd",
133 ) -> None:
134 num_atoms = self._getNumAtoms(referencePositions, numAtoms)
135 groups = [[int(atom) for atom in group] for group in groups]
136 if not all(groups):
137 # OpenMM's RMSDForce would interpret an empty group as all atoms
138 raise ValueError("The groups of atoms must not be empty")
139 atoms = sum(groups, [])
140 if len(set(atoms)) != len(atoms):
141 raise ValueError("The groups of atoms must be disjoint")
142 defined_coords = self._getDefinedCoords(referencePositions, atoms)
143 all_coords = self._getAllCoords(defined_coords, num_atoms)
144 for group in groups:
145 all_coords[group] -= all_coords[group].mean(axis=0)
146 sizes = np.array([len(group) for group in groups])
147 weights = np.outer(sizes, sizes) / sizes.sum() ** 2
148 spread = openmm.CustomCentroidBondForce(2, "w*distance(g1, g2)^2")
149 spread.addPerBondParameter("w")
150 for group in groups:
151 spread.addGroup(group, [1.0] * len(group))
152 for j, k in itertools.combinations(range(len(groups)), 2):
153 spread.addBond([j, k], [weights[j, k]])
154 # Roundoff can make the squared value slightly negative, and the select call
155 # avoids an infinite derivative of sqrt(d2) at d2 = 0
156 super().__init__("select(d2, sqrt(d2), 0); d2 = max(0, rmsd^2 - spread)")
157 self.addCollectiveVariable("rmsd", openmm.RMSDForce(all_coords, atoms))
158 self.addCollectiveVariable("spread", spread)
159 self._registerCV(
160 name,
161 mmunit.nanometers,
162 referencePositions=defined_coords,
163 groups=groups,
164 numAtoms=num_atoms,
165 )
168CompositeRMSD.registerTag("!cvpack.CompositeRMSD")