Coverage for openxps/utils.py: 100%
117 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.utils
3 :platform: Linux, MacOS, Windows
4 :synopsis: Utility functions for OpenXPS.
6.. classauthor:: Charlles Abreu <craabreu@gmail.com>
8"""
10import functools
11import inspect
12import re
13import typing as t
15import cvpack
16from cvpack.serialization import Serializable
17from cvpack.units import Quantity, Unit
18from openmm import unit as mmunit
20#: The separator used to split checkpoint and XML strings into physical and extension
21#: parts.
22STRING_SEPARATOR = "\f\f"
23BINARY_SEPARATOR = b"::SdXN3dO::"
25LEPTON_FUNCTIONS = frozenset(
26 {
27 "sqrt",
28 "exp",
29 "log",
30 "sin",
31 "cos",
32 "sec",
33 "csc",
34 "tan",
35 "cot",
36 "asin",
37 "acos",
38 "atan",
39 "atan2",
40 "sinh",
41 "cosh",
42 "tanh",
43 "erf",
44 "erfc",
45 "square",
46 "cube",
47 "recip",
48 "min",
49 "max",
50 "abs",
51 "floor",
52 "ceil",
53 "step",
54 "delta",
55 "select",
56 }
57)
60def preprocess_args(func: t.Callable) -> t.Callable:
61 """
62 A decorator that converts instances of unserializable classes to their
63 serializable counterparts.
65 Parameters
66 ----------
67 func
68 The function to be decorated.
70 Returns
71 -------
72 The decorated function.
74 Example
75 -------
76 >>> from openxps.utils import preprocess_args
77 >>> from cvpack import units
78 >>> from openmm import unit as mmunit
79 >>> @preprocess_args
80 ... def function(data):
81 ... return data
82 >>> assert isinstance(function(mmunit.angstrom), units.Unit)
83 >>> assert isinstance(function(5 * mmunit.angstrom), units.Quantity)
84 >>> seq = [mmunit.angstrom, mmunit.nanometer]
85 >>> assert isinstance(function(seq), list)
86 >>> assert all(isinstance(item, units.Unit) for item in function(seq))
87 >>> dct = {"length": 3 * mmunit.angstrom, "time": 2 * mmunit.picosecond}
88 >>> assert isinstance(function(dct), dict)
89 >>> assert all(isinstance(item, units.Quantity) for item in function(dct).values())
91 Named tuples keep their type, and other sequences pass through unchanged:
93 >>> import openmm as mm
94 >>> function(mm.Vec3(1, 2, 3))
95 Vec3(x=1, y=2, z=3)
96 >>> function(range(3))
97 range(0, 3)
98 """
99 signature = inspect.signature(func)
101 def convert_container(data: list | tuple | dict) -> t.Any:
102 if isinstance(data, dict):
103 items = {key: convert(value) for key, value in data.items()}
104 if all(items[key] is value for key, value in data.items()):
105 return data
106 return type(data)(items)
107 items = [convert(item) for item in data]
108 if all(new is old for new, old in zip(items, data)):
109 return data
110 if hasattr(data, "_fields"): # named tuple, e.g. openmm.Vec3
111 return type(data)(*items)
112 return type(data)(items)
114 def convert(data: t.Any) -> t.Any:
115 if isinstance(data, mmunit.Quantity):
116 return Quantity(data)
117 if isinstance(data, mmunit.Unit):
118 return Unit(data)
119 if isinstance(data, (list, tuple, dict)):
120 return convert_container(data)
121 return data
123 @functools.wraps(func)
124 def wrapper(*args, **kwargs):
125 bound = signature.bind(*args, **kwargs)
126 for name, data in bound.arguments.items():
127 bound.arguments[name] = convert(data)
128 return func(*bound.args, **bound.kwargs)
130 return wrapper
133# Lepton splits expressions at ASCII whitespace and at these delimiters, and a token
134# that is an identifier (str.isidentifier) is a name
135TOKEN_PATTERN = re.compile(r"[^\s+\-*/^(),;=]+", re.ASCII)
138def _names(expression: str) -> set[str]:
139 return {
140 token for token in TOKEN_PATTERN.findall(expression) if token.isidentifier()
141 }
144class Function(Serializable):
145 """A function of dynamical variables and global parameters.
147 Parameters
148 ----------
149 name
150 The name of the function.
151 expression
152 The expression of the function.
153 **given_parameters
154 The given parameters of the function.
156 Examples
157 --------
158 >>> from copy import copy
159 >>> from openxps.utils import Function
160 >>> f1 = Function("f", "a*x^2", a=1.0)
161 >>> f1
162 Function("f(x)=a*x^2", a=1.0)
163 >>> f2 = Function("g", "exp(-x)*cos(2*pi*y)", pi=3.14159)
164 >>> f2
165 Function("g(x, y)=exp(-x)*cos(2*pi*y)", pi=3.14159)
166 >>> copy(f1)
167 Function("f(x)=a*x^2", a=1.0)
168 """
170 @preprocess_args
171 def __init__(
172 self, name: str, expression: str, **given_parameters: mmunit.Quantity
173 ) -> None:
174 self._name = name
175 self._expression = expression
176 variables, parameters = self._parseDependencies(given_parameters)
177 self._variables = variables
178 self._parameters = {name: given_parameters[name] for name in parameters}
180 def __repr__(self) -> str:
181 variables = ", ".join(sorted(self._variables))
182 parameters = ", ".join(f"{k}={v}" for k, v in sorted(self._parameters.items()))
183 return f'Function("{self._name}({variables})={self._expression}", {parameters})'
185 def __copy__(self) -> "Function":
186 new = Function.__new__(Function)
187 new.__setstate__(self.__getstate__())
188 return new
190 def __getstate__(self) -> dict[str, t.Any]:
191 return {
192 "name": self._name,
193 "expression": self._expression,
194 "variables": self._variables,
195 "parameters": self._parameters,
196 }
198 def __setstate__(self, state: dict[str, t.Any]) -> None:
199 self._name = state["name"]
200 self._expression = state["expression"]
201 self._variables = state["variables"]
202 self._parameters = state["parameters"]
204 def _parseDependencies(
205 self,
206 given_parameters: dict[str, mmunit.Quantity],
207 ) -> tuple[set[str], set[str]]:
208 given_parameters = set(given_parameters.keys())
209 _, *definitions = self._expression.split(";")
210 defined = {definition.partition("=")[0].strip() for definition in definitions}
211 identifiers = _names(self._expression)
212 dependencies = identifiers - LEPTON_FUNCTIONS - defined
213 return dependencies - given_parameters, dependencies & given_parameters
215 def getName(self) -> str:
216 """Return the name of the function."""
217 return self._name
219 def getExpression(self) -> str:
220 """Return the expression string of the function."""
221 return self._expression
223 def getVariables(self) -> set[str]:
224 """Return the set of variable names in the function."""
225 return self._variables
227 def getParameters(self) -> dict[str, mmunit.Quantity]:
228 """Return the dictionary of parameter names and their values."""
229 return self._parameters
231 def createCollectiveVariable(
232 self,
233 variable_indices: t.Mapping[str, int],
234 bounds: t.Mapping[str, t.Any] | None = None,
235 ) -> cvpack.AtomicFunction:
236 """
237 Create a collective variable from the function.
239 Parameters
240 ----------
241 variable_indices
242 A mapping from the name of each variable of the function to the index of
243 the particle whose x coordinate represents it.
244 bounds
245 An optional mapping from variable names to :class:`~openxps.bounds.Bounds`
246 objects. The x coordinate of a variable listed here is wrapped into its
247 bounds before the function is evaluated, so that periodic and reflective
248 variables enter the function with their wrapped values.
250 Returns
251 -------
252 cvpack.AtomicFunction
253 The collective variable object.
255 Examples
256 --------
257 >>> from openxps.utils import Function
258 >>> import openmm as mm
259 >>> from math import exp, cos, pi
260 >>> fn = Function("g", "exp(-x)*cos(2*pi*y)", pi=3.14159)
261 >>> cv = fn.createCollectiveVariable({"x": 0, "y": 1})
262 >>> system = mm.System()
263 >>> for _ in range(2):
264 ... _ = system.addParticle(1.0)
265 >>> cv.addToSystem(system)
266 >>> platform = mm.Platform.getPlatformByName("Reference")
267 >>> context = mm.Context(system, mm.VerletIntegrator(0.0), platform)
268 >>> x, y = 2, 1
269 >>> exp(-x)*cos(2*pi*y)
270 0.13533528...
271 >>> context.setPositions([mm.Vec3(x, 0.0, 0.0), mm.Vec3(y, 0.0, 0.0)])
272 >>> print(context.getState(getEnergy=True).getPotentialEnergy())
273 0.1353352... kJ/mol
275 With reflective bounds, a coordinate beyond the upper bound is mirrored:
277 >>> from openmm import unit
278 >>> from openxps.bounds import ReflectiveBounds
279 >>> fn = Function("h", "u^2")
280 >>> bounds = {"u": ReflectiveBounds(0, 1, unit.dimensionless)}
281 >>> cv = fn.createCollectiveVariable({"u": 0}, bounds)
282 >>> system = mm.System()
283 >>> _ = system.addParticle(1.0)
284 >>> cv.addToSystem(system)
285 >>> context = mm.Context(system, mm.VerletIntegrator(0.0), platform)
286 >>> context.setPositions([mm.Vec3(1.2, 0.0, 0.0)])
287 >>> print(context.getState(getEnergy=True).getPotentialEnergy())
288 0.64... kJ/mol
289 """
290 variables = sorted(self._variables)
291 if unknown := set(variables) - set(variable_indices):
292 raise ValueError(
293 f"Function {self._name} depends on unknown variables: "
294 + ", ".join(sorted(unknown))
295 )
296 bounds = bounds or {}
297 # Variables get private names, because a Lepton definition such as "x1=x2"
298 # would shadow a coordinate that another definition refers to. Wrapped
299 # variables also need a private raw name, from which the bounds expression
300 # derives helper names such as "scaled_<raw>".
301 taken = _names(self._expression)
302 counter = 0
304 def fresh(prefix: str, *derived: str) -> str:
305 nonlocal counter
306 while True:
307 name = f"{prefix}{counter}"
308 counter += 1
309 names = {name} | {f"{d}_{name}" for d in derived}
310 if not names & taken:
311 taken.update(names)
312 return name
314 aliases = {variable: fresh("openxps_var") for variable in variables}
315 expression = TOKEN_PATTERN.sub(
316 lambda match: aliases.get(match.group(0), match.group(0)),
317 self._expression,
318 )
319 definitions = []
320 for index, variable in enumerate(variables):
321 coordinate = f"x{index + 1}"
322 if variable in bounds:
323 raw = fresh("openxps_raw", "scaled", "wrapped")
324 wrapped = bounds[variable].leptonExpression(raw).replace("\n", "")
325 definitions.append(f"{aliases[variable]}={wrapped}")
326 definitions.append(f"{raw}={coordinate}")
327 else:
328 definitions.append(f"{aliases[variable]}={coordinate}")
329 return cvpack.AtomicFunction(
330 function=";".join([expression] + definitions),
331 unit=mmunit.kilojoule_per_mole,
332 groups=[[variable_indices[variable] for variable in variables]],
333 name=self._name,
334 **self._parameters,
335 )
338Function.registerTag("!openxps.utils.Function")
341class ExtensionSimulation:
342 """A view of an extended-space simulation that exposes its extension context.
344 OpenMM's :class:`~openmm.app.Metadynamics` and openmm-opes's samplers read
345 ``simulation.context``, ``simulation.currentStep`` and call ``simulation.step``;
346 this view hands them the extension context, where the bias lives, while stepping
347 the whole extended-space simulation.
348 """
350 def __init__(self, simulation) -> None:
351 self._simulation = simulation
352 self.context = simulation.context.getExtensionContext()
353 self.step = simulation.step
355 @property
356 def currentStep(self) -> int:
357 return self._simulation.currentStep