Coverage for cvpack/utils.py: 97%
121 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:: Utils
3 :platform: Linux, MacOS, Windows
4 :synopsis: Utility functions and classes for CVPack
6.. classauthor:: Charlles Abreu <craabreu@gmail.com>
8"""
10from __future__ import annotations
12import functools
13import inspect
14import typing as t
16import numpy as np
17import openmm
18from numpy import typing as npt
19from openmm import XmlSerializer
20from openmm import app as mmapp
21from openmm import unit as mmunit
23from .serialization import (
24 Serializable,
25 SerializableAtom,
26 SerializableForce,
27 SerializableResidue,
28)
29from .units import Quantity, Unit, value_in_md_units
32def get_platform_and_properties(
33 context: openmm.Context,
34) -> tuple[openmm.Platform, dict[str, str]]:
35 """Get the platform of a context and the values of its platform properties.
37 Parameters
38 ----------
39 context
40 The context whose platform and properties will be returned.
42 Returns
43 -------
44 tuple[openmm.Platform, dict[str, str]]
45 The platform and a dictionary with the values of its properties, which can
46 be passed to the constructor of another context to reproduce the platform
47 settings (e.g. device index and precision) of the given context.
48 """
49 platform = context.getPlatform()
50 properties = {
51 name: platform.getPropertyValue(context, name)
52 for name in platform.getPropertyNames()
53 }
54 return platform, properties
57def evaluate_in_context(
58 forces: openmm.Force | t.Iterable[openmm.Force], context: openmm.Context
59) -> float | tuple[float, ...]:
60 """Evaluate the potential energies of OpenMM Forces in a given context.
62 Parameters
63 ----------
64 forces
65 The forces to be evaluated.
66 context
67 The context in which the forces will be evaluated.
69 Returns
70 -------
71 float | tuple[float, ...]
72 The potential energy of a single force, or a tuple with the potential
73 energies of multiple forces, in the given context.
74 """
75 is_single = isinstance(forces, openmm.Force)
76 forces = [forces] if is_single else list(forces)
77 if len(forces) > 32: # noqa: PLR2004
78 raise ValueError("At most 32 forces can be evaluated at once")
79 state = context.getState(getPositions=True)
80 system = openmm.System()
81 for _ in range(context.getSystem().getNumParticles()):
82 system.addParticle(1.0)
83 # The cutoffs of periodic forces are checked against the default box vectors
84 system.setDefaultPeriodicBoxVectors(*state.getPeriodicBoxVectors())
85 for i, force in enumerate(forces):
86 force_copy = XmlSerializer.deserialize(XmlSerializer.serialize(force))
87 force_copy.setForceGroup(i)
88 system.addForce(force_copy)
89 new_context = openmm.Context(
90 system, openmm.VerletIntegrator(1.0), *get_platform_and_properties(context)
91 )
92 new_context.setPositions(state.getPositions())
93 parameters = context.getParameters()
94 for name in new_context.getParameters():
95 if name in parameters:
96 new_context.setParameter(name, parameters[name])
97 energies = []
98 for i in range(len(forces)):
99 state = new_context.getState(getEnergy=True, groups=1 << i)
100 energies.append(value_in_md_units(state.getPotentialEnergy()))
101 return energies[0] if is_single else tuple(energies)
104def convert_to_matrix(array: npt.ArrayLike) -> tuple[np.ndarray, int, int]:
105 """Convert a 1D or 2D array-like object to a 2D numpy array.
107 Parameters
108 ----------
109 array : array_like
110 The array to be converted.
112 Returns
113 -------
114 numpy.ndarray
115 The 2D numpy array.
116 int
117 The number of rows in the array.
118 int
119 The number of columns in the array.
120 """
121 array = np.atleast_2d(array)
122 numrows, numcols, *other_dimensions = array.shape
123 if other_dimensions:
124 raise ValueError("Array-like object cannot have more than two dimensions.")
125 return array, numrows, numcols
128def check_contiguous_residues(residues: t.Sequence) -> None:
129 """
130 Raise a ValueError unless the residues are consecutive members of one chain.
132 Parameters
133 ----------
134 residues
135 The residues to check, as OpenMM or serializable residues.
136 """
138 def chain_index(residue):
139 if hasattr(residue, "_chain_index"):
140 return residue._chain_index
141 return residue.chain.index
143 for previous, current in zip(residues[:-1], residues[1:]):
144 if current.index != previous.index + 1 or chain_index(current) != chain_index(
145 previous
146 ):
147 raise ValueError(
148 "The residues must be a contiguous sequence from a single chain, but "
149 f"{previous.name}{previous.id} is not followed by "
150 f"{current.name}{current.id}"
151 )
154def find_unused_force_group(system: openmm.System) -> int:
155 """
156 Return the lowest force group not used by any force in a system.
158 Parameters
159 ----------
160 system
161 The system to search for unused force groups.
163 Raises
164 ------
165 RuntimeError
166 If all force groups are already in use
167 """
168 used_groups = {force.getForceGroup() for force in system.getForces()}
169 for group in range(32):
170 if group not in used_groups:
171 return group
172 raise RuntimeError("All force groups are already in use.")
175def get_single_force_state(
176 force: openmm.Force,
177 context: openmm.Context,
178 allowReinitialization: bool = False,
179 **kwargs: bool,
180) -> openmm.State:
181 """
182 Get an OpenMM State containing the potential energy and/or force values computed
183 from a single force object.
185 Parameters
186 ----------
187 force
188 The force object from which the state should be extracted.
189 context
190 The context from which the state should be extracted.
191 allowReinitialization
192 If True, the force group of the given force will be temporarily changed to a
193 group that is not used by any other force in the system, if necessary.
195 Keyword Args
196 ------------
197 **kwargs
198 Additional keyword arguments to be passed to the `getState` method, except for
199 the `groups` argument.
201 Returns
202 -------
203 openmm.State
204 The state containing the requested values.
206 Raises
207 ------
208 ValueError
209 If this force is not present in the given context.
210 """
211 forces_and_groups = [
212 (f, f.getForceGroup()) for f in context.getSystem().getForces()
213 ]
214 if not any(f.this == force.this for f, _ in forces_and_groups):
215 raise RuntimeError("This force is not present in the given context.")
216 self_group = force.getForceGroup()
217 other_groups = {g for f, g in forces_and_groups if f.this != force.this}
218 if self_group not in other_groups:
219 return context.getState(groups=1 << self_group, **kwargs)
220 if not allowReinitialization:
221 raise ValueError("Context reinitialization required, but not allowed.")
222 new_group = find_unused_force_group(context.getSystem())
223 force.setForceGroup(new_group)
224 try:
225 context.reinitialize(preserveState=True)
226 return context.getState(groups=1 << new_group, **kwargs)
227 finally:
228 force.setForceGroup(self_group)
229 context.reinitialize(preserveState=True)
232def compute_effective_mass(
233 force: openmm.Force, context: openmm.Context, allowReinitialization: bool = False
234) -> float:
235 r"""
236 Compute the effective mass of an :OpenMM:`Force` at a given :OpenMM:`Context`.
238 Parameters
239 ----------
240 force
241 The force object from which the effective mass should be computed
242 context
243 The context at which the force's effective mass should be evaluated
244 allowReinitialization
245 If True, the force group of the given force will be temporarily changed to a
246 group that is not used by any other force in the system, if necessary.
248 Returns
249 -------
250 float
251 The effective mass of the force at the given context
252 """
253 state = get_single_force_state(
254 force, context, allowReinitialization, getForces=True
255 )
256 get_mass = functools.partial(
257 openmm._openmm.System_getParticleMass, context.getSystem()
258 )
259 force_vectors = state.getForces(asNumpy=True)._value
260 squared_forces = np.sum(np.square(force_vectors), axis=1)
261 nonzeros = np.nonzero(squared_forces)[0]
262 mass_values = np.fromiter(map(get_mass, nonzeros), dtype=np.float64)
263 movable = mass_values > 0 # OpenMM treats massless particles as fixed
264 if not np.any(movable):
265 return np.inf
266 return 1.0 / np.sum(squared_forces[nonzeros][movable] / mass_values[movable])
269def preprocess_args(func: t.Callable) -> t.Callable:
270 """
271 A decorator that converts instances of unserializable classes to their
272 serializable counterparts.
274 Parameters
275 ----------
276 func
277 The function to be decorated.
279 Returns
280 -------
281 The decorated function.
283 Example
284 -------
285 >>> from cvpack import units, utils
286 >>> from openmm import unit as mmunit
287 >>> @utils.preprocess_args
288 ... def function(data):
289 ... return data
290 >>> assert isinstance(function(mmunit.angstrom), units.Unit)
291 >>> assert isinstance(function(5 * mmunit.angstrom), units.Quantity)
292 >>> seq = [mmunit.angstrom, mmunit.nanometer]
293 >>> assert isinstance(function(seq), list)
294 >>> assert all(isinstance(item, units.Unit) for item in function(seq))
295 >>> dct = {"length": 3 * mmunit.angstrom, "time": 2 * mmunit.picosecond}
296 >>> assert isinstance(function(dct), dict)
297 >>> assert all(isinstance(item, units.Quantity) for item in function(dct).values())
298 """
299 signature = inspect.signature(func)
301 def convert(data: t.Any) -> t.Any: # noqa: PLR0911
302 if isinstance(data, np.integer):
303 return int(data)
304 if isinstance(data, np.floating):
305 return float(data)
306 if isinstance(data, mmunit.Quantity):
307 return Quantity(data)
308 if isinstance(data, mmunit.Unit):
309 return Unit(data)
310 if isinstance(data, mmapp.Atom):
311 return SerializableAtom(data)
312 if isinstance(data, mmapp.Residue):
313 return SerializableResidue(data)
314 if isinstance(data, openmm.Force) and not isinstance(data, Serializable):
315 return SerializableForce(data)
316 if isinstance(data, np.ndarray):
317 return convert(data.tolist())
318 if isinstance(data, t.Sequence) and not isinstance(data, str):
319 items = [convert(item) for item in data]
320 return tuple(items) if type(data) is tuple else items
321 if isinstance(data, dict):
322 return {key: convert(value) for key, value in data.items()}
323 return data
325 @functools.wraps(func)
326 def wrapper(*args, **kwargs):
327 bound = signature.bind(*args, **kwargs)
328 for name, data in bound.arguments.items():
329 bound.arguments[name] = convert(data)
330 return func(*bound.args, **bound.kwargs)
332 return wrapper