Coverage for openxps/bounds/periodic.py: 91%
23 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"""
2Periodic boundary condition.
4.. module:: openxps.bounds.periodic
5 :platform: Linux, MacOS, Windows
6 :synopsis: Periodic boundary condition
8.. classauthor:: Charlles Abreu <craabreu@gmail.com>
10"""
12import typing as t
14from .base import Bounds
17class PeriodicBounds(Bounds):
18 """
19 A periodic boundary condition. The dynamical variable is allowed to wrap
20 around the upper and lower bounds.
22 Parameters
23 ----------
24 lower
25 The lower bound for the dynamical variable.
26 upper
27 The upper bound for the dynamical variable.
28 unit
29 The unit of measurement of the bounds. If the bounds do not have a unit, use
30 ``dimensionless``.
32 Example
33 -------
34 >>> import openxps as xps
35 >>> import yaml
36 >>> from openmm import unit
37 >>> bounds = xps.PeriodicBounds(-180, 180, unit.degree)
38 >>> print(bounds)
39 PeriodicBounds(lower=-180.0, upper=180.0, unit=deg)
40 >>> assert yaml.safe_load(yaml.safe_dump(bounds)) == bounds
41 """
43 kind: t.ClassVar[str] = "periodic"
45 def __post_init__(self) -> None:
46 super().__post_init__()
47 self.period = self.upper - self.lower
49 def leptonExpression(self, variable: str) -> str:
50 scaled = f"scaled_{variable}"
51 if self.lower == 0:
52 shift = deshift = ""
53 elif self.lower > 0:
54 shift = f"-{self.lower}"
55 deshift = f"+{self.lower}"
56 else:
57 shift = f"+{-self.lower}"
58 deshift = f"-{-self.lower}"
59 return (
60 f"({scaled}-floor({scaled}))*{self.period}{deshift}"
61 f";\n{scaled}=({variable}{shift})/{self.period}"
62 )
64 def wrap(self, value: float, rate: float) -> tuple[float, float]:
65 wrapped = (value - self.lower) % self.period + self.lower
66 # Floating-point modulo can round up to a full period, giving the upper bound
67 if wrapped >= self.upper:
68 wrapped = self.lower
69 return wrapped, rate
72PeriodicBounds.registerTag("!openxps.bounds.PeriodicBounds")