Coverage for openxps/integrators/utils.py: 97%
101 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.integrators.utils
3 :platform: Linux, MacOS, Windows
4 :synopsis: A mixin for integrators that provides extra functionality.
6.. classauthor:: Charlles Abreu <craabreu@gmail.com>
8"""
10import textwrap
11import typing as t
13import openmm as mm
14from cvpack.units import Quantity
15from openmm import unit as mmunit
17from openxps.utils import preprocess_args
19BLOCK_START = (6, 7)
20BLOCK_END = 8
22T = t.TypeVar("T")
25class IntegratorMixin:
26 """A mixin for integrators that provides extra functionality."""
28 _forceFirst: bool = False
30 def __repr__(self) -> str:
31 """Return a human-readable version of each integrator step."""
32 readable_lines = []
34 if self.getNumPerDofVariables() > 0:
35 readable_lines.append("Per-dof variables:")
36 per_dof = [
37 self.getPerDofVariableName(index)
38 for index in range(self.getNumPerDofVariables())
39 ]
40 readable_lines.append(" " + ", ".join(per_dof))
42 if self.getNumGlobalVariables() > 0:
43 readable_lines.append("Global variables:")
44 for index in range(self.getNumGlobalVariables()):
45 name = self.getGlobalVariableName(index)
46 value = self.getGlobalVariable(index)
47 readable_lines.append(f" {name} = {value}")
49 readable_lines.append("Computation steps:")
51 step_type_str = [
52 "{target} <- {expr}",
53 "{target} <- {expr}",
54 "{target} <- sum({expr})",
55 "constrain positions",
56 "constrain velocities",
57 "allow forces to update the context state",
58 "if ({expr}):",
59 "while ({expr}):",
60 "end",
61 ]
62 indent_level = 0
63 for step in range(self.getNumComputations()):
64 line = ""
65 step_type, target, expr = self.getComputationStep(step)
66 command = step_type_str[step_type].format(target=target, expr=expr)
67 if step_type == BLOCK_END:
68 indent_level -= 1
69 line += f"{step:4d}: " + " " * indent_level + command
70 if step_type in BLOCK_START:
71 indent_level += 1
72 readable_lines.append(line)
73 return "\n".join(readable_lines)
75 def __getstate__(self) -> dict[str, t.Any]:
76 """Get the state of the integrator for pickling.
78 OpenMM pickles an integrator as its XML serialization only, which loses the
79 Python attributes of these classes, such as the temperature, ``forceFirst``
80 and the random generator of :class:`CSVRIntegrator`.
81 """
82 attributes = {
83 key: value.in_unit_system(mmunit.md_unit_system)
84 if mmunit.is_quantity(value)
85 else value
86 for key, value in vars(self).items()
87 if key != "this"
88 }
89 return {"xml": mm.XmlSerializer.serialize(self), "attributes": attributes}
91 def __setstate__(self, state: dict[str, t.Any] | str) -> None:
92 """Restore the integrator from its pickled state."""
93 if isinstance(state, str):
94 # The XML-only state of pickles written before attributes were kept
95 self.this = mm.XmlSerializer.deserialize(state).this
96 return
97 self.this = mm.XmlSerializer.deserialize(state["xml"]).this
98 self.__dict__.update(
99 {
100 key: Quantity(value) if mmunit.is_quantity(value) else value
101 for key, value in state["attributes"].items()
102 }
103 )
105 def setStepSize(self, size: mmunit.Quantity | float) -> None:
106 """Set the step size and refresh any step-size-dependent global variables."""
107 super().setStepSize(size)
108 if hasattr(self, "_update_global_variables"):
109 self._update_global_variables()
111 def registerWithSystem(self, system: mm.System, isExtension: bool) -> None:
112 """Register the integrator with the system."""
113 pass
115 def _add_dof_mask(self) -> None:
116 """Add the per-DOF variable that gates thermostat updates.
118 It is 1 for every degree of freedom unless :meth:`_set_dof_mask` restricts it.
119 """
120 self.addPerDofVariable("active", 1)
122 @staticmethod
123 def _masked(expression: str) -> str:
124 """Multiply the main part of a Lepton expression by the DOF mask."""
125 head, separator, definitions = expression.partition(";")
126 return f"active*({head}){separator}{definitions}"
128 def _set_dof_mask(self, system: mm.System, isExtension: bool) -> None:
129 """Restrict thermostat updates to the x components of an extension system.
131 Each extension particle represents one dynamical variable along x, while its
132 y and z components are inert and have zero velocity. Thermostatting them
133 would make their thermostat variables drift without bound.
134 """
135 mask = mm.Vec3(1, 0, 0) if isExtension else mm.Vec3(1, 1, 1)
136 self.setPerDofVariableByName("active", [mask] * system.getNumParticles())
138 @staticmethod
139 def _countDegreesOfFreedom(system: mm.System) -> int:
140 """Count the degrees of freedom in a system.
142 Parameters
143 ----------
144 system
145 The :OpenMM:`System` to count the degrees of freedom of.
147 Returns
148 -------
149 int
150 The number of degrees of freedom in the system.
151 """
152 dof = 0
153 for i in range(system.getNumParticles()):
154 if system.getParticleMass(i) > 0 * mmunit.dalton:
155 dof += 3
156 for i in range(system.getNumConstraints()):
157 p1, p2, _ = system.getConstraintParameters(i)
158 if (system.getParticleMass(p1) > 0 * mmunit.dalton) or (
159 system.getParticleMass(p2) > 0 * mmunit.dalton
160 ):
161 dof -= 1
162 if any(
163 isinstance(system.getForce(i), mm.CMMotionRemover)
164 for i in range(system.getNumForces())
165 ):
166 dof -= 3
167 return dof
169 def isForceFirst(self) -> bool:
170 """Check if the integrator follows a force-first scheme.
172 Returns
173 -------
174 bool
175 True if the integrator is force-first, False otherwise.
176 """
177 return self._forceFirst
180def add_property(property: str, unit: mmunit.Unit) -> t.Callable[[type[T]], type[T]]:
181 """A decorator to add a property to the integrator.
183 The property is added to the integrator as a class attribute with the name
184 `_{snake_case_name}`. Three methods are added to the class:
186 * `_init_{snake_case_name}(value)`: Initializes the property.
187 * `set{PascalCaseName}(value)`: Sets the property and updates the global variables
188 if the integrator has a `_update_global_variables` method. A setter defined
189 in the class body takes precedence and is left untouched.
190 * `get{PascalCaseName}()`: Gets the property.
192 Parameters
193 ----------
194 property
195 The name of the property.
196 unit
197 The unit of the property.
198 """
199 if unit.in_unit_system(mmunit.md_unit_system) != unit:
200 raise ValueError(f"The unit of {property} must be in the MD unit system.")
201 PascalCaseName = "".join(s.capitalize() for s in property.split())
202 snake_case_name = "_".join(s.lower() for s in property.split())
204 def set_value(self, value: mmunit.Quantity | float) -> None:
205 args = [value] if mmunit.is_quantity(value) else [value, unit]
206 setattr(self, f"_{snake_case_name}", Quantity(*args))
208 @preprocess_args
209 def set_and_update(self, value: mmunit.Quantity | float) -> None:
210 set_value(self, value)
211 if hasattr(self, "_update_global_variables"):
212 self._update_global_variables()
214 set_and_update.__doc__ = textwrap.dedent(
215 f"""\
216 Set the {property}.
218 Parameters
219 ----------
220 value
221 The {property}.
222 """
223 )
225 def get_value(self) -> mmunit.Quantity:
226 return getattr(self, f"_{snake_case_name}")
228 get_value.__doc__ = textwrap.dedent(
229 f"""\
230 Get the {property}.
232 Returns
233 -------
234 openmm.unit.Quantity
235 The {property}.
236 """
237 )
239 def decorator(cls: type[T]) -> type[T]:
240 setattr(cls, f"_{snake_case_name}", None)
241 setattr(cls, f"_init_{snake_case_name}", set_value)
242 if f"set{PascalCaseName}" not in vars(cls):
243 setattr(cls, f"set{PascalCaseName}", set_and_update)
244 setattr(cls, f"get{PascalCaseName}", get_value)
245 return cls
247 return decorator