Coverage for openxps/dynamical_variable.py: 99%

78 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-10-22 22:23 +0000

1""" 

2.. module:: openxps.dynamical_variable 

3 :platform: Linux, Windows, macOS 

4 :synopsis: Dynamical variables for XPS simulations 

5 

6.. moduleauthor:: Charlles Abreu <craabreu@gmail.com> 

7 

8""" 

9 

10import typing as t 

11from dataclasses import dataclass 

12 

13import cvpack 

14import openmm as mm 

15import typing_extensions as te 

16from cvpack.serialization import Serializable 

17from cvpack.units import Quantity 

18from openmm import unit as mmunit 

19 

20from .bounds import Bounds, PeriodicBounds 

21from .utils import preprocess_args 

22 

23 

24@dataclass(frozen=True) 

25class DynamicalVariable(Serializable): 

26 """ 

27 Dynamical variable for extended phase-space simulations with OpenMM. 

28 

29 Parameters 

30 ---------- 

31 name 

32 The name of the context parameter to be turned into a dynamical variable. 

33 It must be an identifier, as in Python: a letter or an underscore followed 

34 by letters, digits or underscores, where letters may be non-ASCII (``λ``). 

35 unit 

36 The unit of measurement of this dynamical variable. If it does not have a 

37 unit, use ``openmm.unit.dimensionless``. Couplings convert dynamical 

38 variables to MD units (see :meth:`in_md_units`), so an extended phase-space 

39 context reports values in MD units and, as in OpenMM, reads numbers given 

40 without units in MD units too. 

41 mass 

42 The mass assigned to this dynamical variable, whose unit of measurement 

43 must be compatible with ``dalton*(nanometer/unit)**2``, where ``unit`` is the 

44 dynamical variable's own unit (see ``unit`` above). 

45 bounds 

46 The boundary condition to be applied to this dynamical variable. It must 

47 be an instance of :class:`PeriodicBounds`, :class:`ReflectiveBounds`, or 

48 :class:`NoBounds` (for unbounded variables, whose bounds are then typical 

49 values rather than actual limits). Its unit of measurement must be 

50 compatible with the dynamical variable's own unit. 

51 

52 Example 

53 ------- 

54 >>> import openxps as xps 

55 >>> import yaml 

56 >>> from openmm import unit 

57 >>> dv = xps.DynamicalVariable( 

58 ... "psi", 

59 ... unit.radian, 

60 ... 3 * unit.dalton*(unit.nanometer/unit.radian)**2, 

61 ... xps.PeriodicBounds(-180, 180, unit.degree) 

62 ... ) 

63 >>> dv 

64 DynamicalVariable(name='psi', unit=rad, mass=3 nm**2 Da/(rad**2), bounds=...) 

65 >>> dv.bounds 

66 PeriodicBounds(lower=-3.14159..., upper=3.14159..., unit=rad) 

67 >>> assert yaml.safe_load(yaml.safe_dump(dv)) == dv 

68 """ 

69 

70 name: str 

71 unit: mmunit.Unit 

72 mass: mmunit.Quantity 

73 bounds: Bounds 

74 

75 def __post_init__(self) -> None: 

76 if not (isinstance(self.name, str) and self.name.isidentifier()): 

77 raise ValueError( 

78 f"Invalid name {self.name!r}: it must be an identifier, starting " 

79 "with a letter or an underscore and continuing with letters, digits " 

80 "or underscores." 

81 ) 

82 if not mmunit.is_unit(self.unit): 

83 raise TypeError("The unit must be a valid OpenMM unit.") 

84 if not mmunit.is_quantity(self.mass): 

85 raise TypeError("Mass must have units of measurement.") 

86 mass_unit = mmunit.dalton * (mmunit.nanometer / self.unit) ** 2 

87 if not self.mass.unit.is_compatible(mass_unit): 

88 raise TypeError(f"Mass units must be compatible with {mass_unit}.") 

89 object.__setattr__(self, "mass", Quantity(self.mass.in_units_of(mass_unit))) 

90 

91 if isinstance(self.bounds, Bounds): 

92 if not self.bounds.unit.is_compatible(self.unit): 

93 raise ValueError("Provided bounds have incompatible units.") 

94 object.__setattr__(self, "bounds", self.bounds.convert(self.unit)) 

95 else: 

96 raise TypeError("The bounds must be an instance of Bounds.") 

97 

98 def __getstate__(self) -> dict[str, t.Any]: 

99 return { 

100 "name": self.name, 

101 "unit": self.unit, 

102 "mass": self.mass, 

103 "bounds": self.bounds, 

104 } 

105 

106 def __setstate__(self, keywords: dict[str, t.Any]) -> None: 

107 self.__init__(**keywords) 

108 

109 def __hash__(self) -> int: 

110 return hash((self.name, str(self.unit), self.bounds)) 

111 

112 def in_md_units(self) -> "DynamicalVariable": 

113 """ 

114 Return the dynamical variable in the MD unit system. 

115 """ 

116 unit = self.unit.in_unit_system(mmunit.md_unit_system) 

117 mass_unit = mmunit.dalton * (mmunit.nanometer / self.unit) ** 2 

118 return DynamicalVariable( 

119 self.name, 

120 unit, 

121 self.mass.in_units_of(mass_unit), 

122 self.bounds.in_md_units(), 

123 ) 

124 

125 def isPeriodic(self) -> bool: 

126 """ 

127 Returns whether this dynamical variable is periodic. 

128 

129 Returns 

130 ------- 

131 bool 

132 ``True`` if this dynamical variable is periodic, ``False`` otherwise. 

133 

134 Example 

135 ------- 

136 >>> import openxps as xps 

137 >>> from openmm import unit 

138 >>> dv = xps.DynamicalVariable( 

139 ... "psi", 

140 ... unit.radian, 

141 ... 3 * unit.dalton*(unit.nanometer/unit.radian)**2, 

142 ... xps.PeriodicBounds(-180, 180, unit.degree) 

143 ... ) 

144 >>> dv.isPeriodic() 

145 True 

146 """ 

147 return isinstance(self.bounds, PeriodicBounds) 

148 

149 def createCollectiveVariable( 

150 self, index: int, name: str | None = None 

151 ) -> cvpack.OpenMMForceWrapper: 

152 """ 

153 Returns a :CVPack:`OpenMMForceWrapper` object associating this extra degree of 

154 freedom with the x coordinate of a particle in an OpenMM system. 

155 

156 Parameters 

157 ---------- 

158 index 

159 The index of the particle whose x coordinate will be associated with this 

160 dynamical variable. 

161 name 

162 The name of the context parameter to be used in the OpenMM system. If 

163 ``None``, the name of the dynamical variable will be used. 

164 

165 Returns 

166 ------- 

167 cvpack.OpenMMForceWrapper 

168 The collective variable object representing this dynamical variable. 

169 

170 Example 

171 ------- 

172 >>> import openxps as xps 

173 >>> from openmm import unit 

174 >>> dv = xps.DynamicalVariable( 

175 ... "psi", 

176 ... unit.radian, 

177 ... 3 * unit.dalton*(unit.nanometer/unit.radian)**2, 

178 ... xps.PeriodicBounds(-180, 180, unit.degree) 

179 ... ) 

180 >>> cv = dv.createCollectiveVariable(0) 

181 """ 

182 force = mm.CustomExternalForce(self.bounds.leptonExpression("x")) 

183 bounds = self.bounds.asQuantity() if self.isPeriodic() else None 

184 force.addParticle(index, []) 

185 return cvpack.OpenMMForceWrapper( 

186 force, 

187 self.unit, 

188 bounds, 

189 self.name if name is None else name, 

190 ) 

191 

192 def _distanceToCV(self, other: cvpack.CollectiveVariable) -> str: 

193 name = other.getName() 

194 diff = f"{name}-{self.name}" 

195 if not other.getUnit().is_compatible(self.unit): 

196 raise ValueError("Incompatible units.") 

197 if other.getPeriodicBounds() is None and not self.isPeriodic(): 

198 return f"({diff})" 

199 if self.isPeriodic() and other.getPeriodicBounds() == self.bounds.asQuantity(): 

200 period = self.bounds.in_md_units().period 

201 return f"({diff}-{period}*floor(0.5+({diff})/{period}))" 

202 raise ValueError( 

203 "Incompatible boundary conditions: either both variables are nonperiodic " 

204 "or both have the same periodic bounds (same lower and upper limits)." 

205 ) 

206 

207 def _distanceToDV(self, other: te.Self) -> str: 

208 diff = f"{other.name}-{self.name}" 

209 if not other.unit.is_compatible(self.unit): 

210 raise ValueError("Incompatible units.") 

211 if not (self.isPeriodic() or other.isPeriodic()): 

212 return f"({diff})" 

213 if self.bounds != other.bounds: 

214 raise ValueError( 

215 "Incompatible boundary conditions: either both variables are " 

216 "nonperiodic or both have the same periodic bounds (same lower and " 

217 "upper limits)." 

218 ) 

219 period = self.bounds.in_md_units().period 

220 return f"({diff}-{period}*floor(0.5+({diff})/{period}))" 

221 

222 def distanceTo(self, other: cvpack.CollectiveVariable | te.Self) -> str: 

223 """ 

224 Returns a Lepton expression representing the distance between this extra degree 

225 of freedom and another variable. 

226 

227 Parameters 

228 ---------- 

229 other 

230 The other variable to which the distance will be calculated. 

231 

232 Returns 

233 ------- 

234 str 

235 A string representing the distance between the two variables. 

236 

237 Example 

238 ------- 

239 >>> import openxps as xps 

240 >>> import pytest 

241 >>> from openmm import unit 

242 >>> dv = xps.DynamicalVariable( 

243 ... "psi0", 

244 ... unit.radian, 

245 ... 3 * unit.dalton*(unit.nanometer/unit.radian)**2, 

246 ... xps.PeriodicBounds(-180, 180, unit.degree) 

247 ... ) 

248 >>> psi = cvpack.Torsion(6, 8, 14, 16, name="psi") 

249 >>> dv.distanceTo(psi) 

250 '(psi-psi0-6.28318...*floor(0.5+(psi-psi0)/6.28318...))' 

251 

252 """ 

253 if isinstance(other, cvpack.CollectiveVariable): 

254 return self._distanceToCV(other) 

255 if type(other) is type(self): 

256 return self._distanceToDV(other) 

257 raise TypeError(f"Method distanceTo not implemented for type {type(other)}.") 

258 

259 

260DynamicalVariable.__init__ = preprocess_args(DynamicalVariable.__init__) 

261 

262DynamicalVariable.registerTag("!openxps.DynamicalVariable")