Coverage for openxps/bounds/base.py: 98%
63 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"""
2Base class for boundary conditions.
4.. module:: openxps.bounds.base
5 :platform: Linux, MacOS, Windows
6 :synopsis: Base class for boundary conditions
8.. classauthor:: Charlles Abreu <craabreu@gmail.com>
10"""
12import math
13import numbers
14import typing as t
15from dataclasses import dataclass
17import cvpack
18from cvpack.serialization import Serializable
19from cvpack.units import Quantity
20from openmm import unit as mmunit
22from ..utils import preprocess_args
25@dataclass(frozen=True, eq=False)
26class Bounds(Serializable):
27 """Boundary condition for a dynamical variable.
29 Parameters
30 ----------
31 lower
32 The lower bound for the dynamical variable.
33 upper
34 The upper bound for the dynamical variable.
35 unit
36 The unit of measurement of the bounds. If the bounds do not have a unit, use
37 ``dimensionless``.
38 """
40 lower: float
41 upper: float
42 unit: cvpack.units.Unit
44 #: The kind of boundary condition; subclasses override it.
45 kind: t.ClassVar[str] = "bounds"
47 def __post_init__(self) -> None:
48 for kind in ("lower", "upper"):
49 value = getattr(self, kind)
50 if isinstance(value, bool) or not isinstance(value, numbers.Real):
51 raise TypeError(f"The {kind} bound must be a real number.")
52 if not math.isfinite(value):
53 raise ValueError(f"The {kind} bound must be finite.")
54 object.__setattr__(self, kind, float(value))
55 if self.lower >= self.upper:
56 raise ValueError("The upper bound must be greater than the lower bound.")
57 if not mmunit.is_unit(self.unit):
58 raise TypeError("The unit must be a valid OpenMM unit.")
59 object.__setattr__(self, "unit", cvpack.units.Unit(self.unit))
60 object.__setattr__(self, "length", self.upper - self.lower)
62 def __getstate__(self) -> dict[str, t.Any]:
63 return {"lower": self.lower, "upper": self.upper, "unit": self.unit}
65 def __setstate__(self, keywords: dict[str, t.Any]) -> None:
66 self.__init__(keywords["lower"], keywords["upper"], keywords["unit"])
68 def __eq__(self, other: t.Any) -> bool:
69 if not isinstance(other, Bounds) or self.kind != other.kind:
70 return False
71 _, self_factor = self._md_unit_and_conversion_factor()
72 other_md_unit, other_factor = other._md_unit_and_conversion_factor()
73 if not self.unit.is_compatible(other_md_unit):
74 return False
75 return math.isclose(
76 self.lower * self_factor, other.lower * other_factor, rel_tol=1e-9
77 ) and math.isclose(
78 self.upper * self_factor, other.upper * other_factor, rel_tol=1e-9
79 )
81 def __hash__(self) -> int:
82 unit, _ = self._md_unit_and_conversion_factor()
83 return hash((self.kind, str(unit)))
85 def _md_unit_and_conversion_factor(self) -> tuple[mmunit.Unit, float]:
86 """
87 Return the MD unit and conversion factor for the bounds.
88 """
89 unit = self.unit.in_unit_system(mmunit.md_unit_system)
90 factor = self.unit.conversion_factor_to(unit)
91 return unit, factor
93 def in_md_units(self) -> "Bounds":
94 """
95 Return the bounds in the MD unit system.
97 Example
98 -------
99 >>> import openxps as xps
100 >>> from openmm import unit
101 >>> bounds = xps.bounds.PeriodicBounds(-1.0, 1.0, unit.kilocalories_per_mole)
102 >>> bounds.in_md_units()
103 PeriodicBounds(lower=-4.184, upper=4.184, unit=nm**2 Da/(ps**2))
104 """
105 unit, factor = self._md_unit_and_conversion_factor()
106 return self.__class__(self.lower * factor, self.upper * factor, unit)
108 def convert(self, unit: mmunit.Unit) -> "Bounds":
109 """
110 Convert the bounds to a different unit of measurement.
112 Parameters
113 ----------
114 unit
115 The new unit of measurement for the bounds.
117 Returns
118 -------
119 Bounds
120 The bounds in the new unit of measurement.
122 Example
123 -------
124 >>> import openxps as xps
125 >>> from openmm import unit
126 >>> bounds = xps.bounds.PeriodicBounds(-180, 180, unit.degree)
127 >>> bounds.convert(unit.radian)
128 PeriodicBounds(lower=-3.14159..., upper=3.14159..., unit=rad)
129 """
130 factor = 1.0 * self.unit / unit
131 if not isinstance(factor, float):
132 raise ValueError("The unit must be compatible with the bounds unit.")
133 return self.__class__(factor * self.lower, factor * self.upper, unit)
135 def asQuantity(self) -> mmunit.Quantity:
136 """
137 Return the bounds as a Quantity object.
139 Returns
140 -------
141 Quantity
142 The bounds as a Quantity object.
144 Example
145 -------
146 >>> import openxps as xps
147 >>> from openmm import unit
148 >>> bounds = xps.bounds.PeriodicBounds(-180, 180, unit.degree)
149 >>> bounds.asQuantity()
150 (-180.0, 180.0) deg
151 """
152 return Quantity((self.lower, self.upper), self.unit)
154 def leptonExpression(self, variable: str) -> str:
155 """
156 Return a lepton expression representing the transformation from an unwrapped
157 variable to a wrapped value under the boundary conditions.
159 Parameters
160 ----------
161 variable
162 The name of the variable in the expression.
163 Returns
164 -------
165 str
166 A string representing the transformation.
168 Example
169 -------
170 >>> import openxps as xps
171 >>> from openmm import unit
172 >>> periodic = xps.bounds.PeriodicBounds(-180, 180, unit.degree)
173 >>> print(periodic.leptonExpression("x"))
174 (scaled_x-floor(scaled_x))*360.0-180.0;
175 scaled_x=(x+180.0)/360.0
176 >>> reflective = xps.bounds.ReflectiveBounds(1, 10, unit.angstrom)
177 >>> print(reflective.leptonExpression("y"))
178 min(wrapped_y,1-wrapped_y)*18.0+1.0;
179 wrapped_y=scaled_y-floor(scaled_y);
180 scaled_y=(y-1.0)/18.0
181 """
182 raise NotImplementedError(
183 "The method leptonExpression must be implemented in subclasses."
184 )
186 def wrap(self, value: float, rate: float) -> tuple[float, float]:
187 """
188 Wrap a value around the bounds and adjust its rate of change.
190 Parameters
191 ----------
192 value
193 The unwrapped value, in the same unit of measurement as the bounds.
194 rate
195 The rate of change of the unwrapped value, in the same unit of measurement
196 as the bounds divided by a time unit.
198 Returns
199 -------
200 float
201 The wrapped value, in the same unit of measurement as the bounds.
202 float
203 The adjusted rate of change of the wrapped value, in the same unit of
204 measurement as the original rate.
205 """
206 raise NotImplementedError("The method wrap must be implemented in subclasses.")
209Bounds.__init__ = preprocess_args(Bounds.__init__)