Coverage for openxps/integrators/massive_ggmt.py: 100%

103 statements  

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

1""" 

2.. module:: openxps.integrators.massive_ggmt 

3 :platform: Linux, MacOS, Windows 

4 :synopsis: Massive Generalized Gaussian Moment Thermostat (GGMT) integrator. 

5 

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

7 

8""" 

9 

10import numpy as np 

11import openmm as mm 

12from openmm import unit as mmunit 

13 

14from openxps.integrators.utils import IntegratorMixin, add_property 

15from openxps.utils import preprocess_args 

16 

17_COULOMB_STRENGTH = "(2/sqrt(3))*kT^3*invQ2" 

18_V_FLOOR = "max(abs(v), sqrt(1e-30*kT/m))" 

19 

20 

21@add_property("temperature", mmunit.kelvin) 

22@add_property("time constant", mmunit.picosecond) 

23@add_property("friction coefficient", 1 / mmunit.picosecond) 

24class MassiveGGMTIntegrator(IntegratorMixin, mm.CustomIntegrator): 

25 r"""A massive, second- and fourth-moment GGMT integrator :cite:`Liu2000`. 

26 

27 The massive GGMT integrator is effective at maintaining temperature control under 

28 steady-state conditions, such as in d-AFED/TAMD :cite:`Maragliano2006,Abrams2008` 

29 or UFED :cite:`Chen2012` simulations. 

30 

31 .. note:: 

32 If stochasticity is enabled, the friction coefficient is initially set to the 

33 inverse of the time constant, but this value can be customized via 

34 :meth:`setFrictionCoefficient`. Otherwise, the friction coefficient is zero 

35 and cannot be changed. 

36 

37 .. warning:: 

38 This integrator is incompatible with systems subject to constraints. 

39 

40 Parameters 

41 ---------- 

42 temperature 

43 The temperature of the heat bath. 

44 timeConstant 

45 The time constant (a.k.a. coupling/damping/relaxation time) of the thermostat. 

46 stepSize 

47 The integration step size. 

48 

49 Keyword Arguments 

50 ----------------- 

51 stochastic 

52 If True, the integrator will apply a stochastic rescaling to each velocity and 

53 its fourth-moment thermostat variable at the center of the step. 

54 forceFirst 

55 If True, the integrator will apply a force-first scheme. Otherwise, it will 

56 apply a symmetric operator splitting scheme. 

57 halleyIterations 

58 The number of Halley iterations used to solve the hyperbolic Kepler equation 

59 of the Coulomb sub-step (see Notes). The default reaches double precision. 

60 

61 Notes 

62 ----- 

63 Propagated alone, the cubic friction of the GGMT equations has a finite-time 

64 singularity, which makes Trotter-factorized integrators fail at large step sizes. 

65 Here it is propagated together with the fourth-moment thermostat variable, as an 

66 exactly solvable Coulomb problem that requires one hyperbolic Kepler equation per 

67 step. The stochastic version rescales each velocity and its fourth-moment 

68 thermostat variable by a common random factor :cite:`Bussi2007` at the center of 

69 the step, where the friction coefficient sets the rate of the rescaling. 

70 

71 Example 

72 ------- 

73 >>> import openxps as xps 

74 >>> from openmm import unit 

75 >>> from openmmtools import testsystems 

76 

77 Symmetric scheme (default) 

78 

79 >>> integrator = xps.integrators.MassiveGGMTIntegrator( 

80 ... temperature=300 * unit.kelvin, 

81 ... timeConstant=100 * unit.femtoseconds, 

82 ... stepSize=2 * unit.femtoseconds, 

83 ... ) 

84 >>> integrator 

85 Per-dof variables: 

86 v1, v2, active, meanAnomaly, angle, expAngle 

87 Global variables: 

88 kT = 2.494338... 

89 invQ = 40.090... 

90 invQ2 = 2.416... 

91 Computation steps: 

92 0: allow forces to update the context state 

93 1: v <- v + 0.5*dt*f/m 

94 2: x <- x + 0.5*dt*v 

95 3: v1 <- active*(v1 + 0.5*dt*(m*v^2 - kT)*invQ) 

96 4: v <- v*exp(-0.5*dt*(v1 + kT*v2)) 

97 5: meanAnomaly <- (2*step(sinh0) - 1)*log(abs(sinh0) + cosh0) + ... 

98 6: angle <- start - residual*coshA/(2*coshA^3 - residual*sinhA); ... 

99 7: angle <- angle - residual*coshA/(2*coshA^3 - residual*sinhA); ... 

100 8: expAngle <- expA*(1 - delta + delta^2/2 - delta^3/6); ... 

101 9: v <- v*cosh0*2*expAngle/(expAngle^2 + 1); ... 

102 10: v2 <- active*(0.5*(expAngle - 1/expAngle)*... 

103 11: v <- v*exp(-0.5*dt*(v1 + kT*v2)) 

104 12: v1 <- active*(v1 + 0.5*dt*(m*v^2 - kT)*invQ) 

105 13: x <- x + 0.5*dt*v 

106 14: v <- v + 0.5*dt*f/m 

107 

108 Force-first scheme 

109 

110 >>> integrator_ff = xps.integrators.MassiveGGMTIntegrator( 

111 ... temperature=300 * unit.kelvin, 

112 ... timeConstant=40 * unit.femtoseconds, 

113 ... stepSize=2 * unit.femtoseconds, 

114 ... forceFirst=True 

115 ... ) 

116 >>> model = testsystems.AlanineDipeptideVacuum() 

117 >>> try: 

118 ... integrator_ff.registerWithSystem(model.system, False) 

119 ... except ValueError as e: 

120 ... print(e) 

121 Massive GGMT integrators do not support constraints. 

122 """ 

123 

124 @preprocess_args 

125 def __init__( # noqa: PLR0913 

126 self, 

127 temperature: mmunit.Quantity, 

128 timeConstant: mmunit.Quantity, 

129 stepSize: mmunit.Quantity, 

130 *, 

131 stochastic: bool = False, 

132 forceFirst: bool = False, 

133 halleyIterations: int = 3, 

134 ) -> None: 

135 if halleyIterations < 1: 

136 raise ValueError("The number of Halley iterations must be at least 1.") 

137 super().__init__(stepSize) 

138 self._forceFirst = forceFirst 

139 self._halley_iterations = halleyIterations 

140 self._init_temperature(temperature) 

141 self._init_time_constant(timeConstant) 

142 self._init_friction_coefficient(1 / timeConstant if stochastic else 0.0) 

143 self._stochastic = stochastic 

144 self._add_variables() 

145 self.addUpdateContextState() 

146 self._add_boost(1 if forceFirst else 0.5) 

147 self._add_translation(0.5) 

148 self._add_thermostat() 

149 self._add_translation(0.5) 

150 if not forceFirst: 

151 self._add_boost(0.5) 

152 

153 @preprocess_args 

154 def setFrictionCoefficient(self, value: mmunit.Quantity | float) -> None: 

155 """ 

156 Set the friction coefficient. 

157 

158 Parameters 

159 ---------- 

160 value 

161 The friction coefficient. 

162 

163 Raises 

164 ------ 

165 ValueError 

166 If the integrator is deterministic and the value is not zero. 

167 """ 

168 self._init_friction_coefficient(value) 

169 friction = self.getFrictionCoefficient().value_in_unit(mmunit.picosecond**-1) 

170 if not self._stochastic and friction != 0: 

171 self._init_friction_coefficient(0.0) 

172 raise ValueError( 

173 "The friction coefficient of a deterministic integrator must be zero." 

174 ) 

175 self._update_global_variables() 

176 

177 def _add_variables(self) -> None: 

178 self.addGlobalVariable("kT", 0) 

179 self.addGlobalVariable("invQ", 0) 

180 self.addGlobalVariable("invQ2", 0) 

181 self.addPerDofVariable("v1", 0) 

182 self.addPerDofVariable("v2", 0) 

183 self._add_dof_mask() 

184 for name in ("meanAnomaly", "angle", "expAngle"): 

185 self.addPerDofVariable(name, 0) 

186 if self._stochastic: 

187 self.addGlobalVariable("a", 0) 

188 self.addPerDofVariable("normal", 0) 

189 self.addPerDofVariable("scaleSq", 1) 

190 self._update_global_variables() 

191 

192 def _update_global_variables(self) -> None: 

193 tau = self.getTimeConstant() 

194 kt = mmunit.MOLAR_GAS_CONSTANT_R * self.getTemperature() 

195 self.setGlobalVariableByName("kT", kt) 

196 self.setGlobalVariableByName("invQ", 1 / (kt * tau**2)) 

197 self.setGlobalVariableByName("invQ2", 3 / (8 * kt**3 * tau**2)) 

198 if self._stochastic: 

199 friction = self.getFrictionCoefficient() 

200 dt = self.getStepSize() 

201 self.setGlobalVariableByName("a", np.exp(-friction * dt)) 

202 

203 def _add_translation(self, fraction: float) -> None: 

204 self.addComputePerDof("x", f"x + {fraction}*dt*v") 

205 

206 def _add_boost(self, fraction: float) -> None: 

207 self.addComputePerDof("v", f"v + {fraction}*dt*f/m") 

208 

209 def _add_v1_boost(self, fraction: float) -> None: 

210 self.addComputePerDof( 

211 "v1", self._masked(f"v1 + {fraction}*dt*(m*v^2 - kT)*invQ") 

212 ) 

213 

214 def _add_coulomb_step(self) -> None: 

215 """Propagate the fourth-moment sub-dynamics over a full step. 

216 

217 A constant kick on ``v2`` over half a step precedes and follows the exact 

218 Coulomb flow, whose final hyperbolic angle solves a Kepler equation by Halley 

219 iterations. In the stochastic version, the rescaling at the center of the flow 

220 only changes the orbit energy by ``scaleSq``, so it enters the same equation. 

221 """ 

222 add = self.addComputePerDof 

223 kick = "0.5*dt*kT^2*invQ2" 

224 orbit = ( 

225 "sinh0 = wCoulomb*sqrt(zCoulomb/(2*strength));" 

226 f" wCoulomb = (2/sqrt(3))*kT*(v2 - {kick});" 

227 " zCoulomb = sqrt(3)*kT/(m*vFloor^2);" 

228 f" vFloor = {_V_FLOOR}; strength = {_COULOMB_STRENGTH}" 

229 ) 

230 if self._stochastic: 

231 # Both normal variates are drawn in adjacent computations to avoid an 

232 # OpenMM 8.6.1 bug in merged per-DOF kernels. 

233 add("normal", "gaussian") 

234 add( 

235 "scaleSq", 

236 "((sqrt(a*normSq) + sqrt((1 - a)*kT)*normal)^2" 

237 " + (1 - a)*kT*gaussian^2)/normSq;" 

238 " normSq = m*vFloor^2 + v2Kicked^2/invQ2;" 

239 f" v2Kicked = v2 - {kick}; vFloor = {_V_FLOOR}", 

240 ) 

241 time_term = ( 

242 "0.5*dt*energy*sqrt(2*energy)*(1 + scaleSq*sqrt(scaleSq))/strength" 

243 ) 

244 scale = "sqrt(scaleSq)*" 

245 else: 

246 time_term = "dt*energy*sqrt(2*energy)/strength" 

247 scale = "" 

248 add( 

249 "meanAnomaly", 

250 f"(2*step(sinh0) - 1)*log(abs(sinh0) + cosh0) + sinh0*cosh0 + {time_term};" 

251 " cosh0 = sqrt(sinh0^2 + 1);" 

252 f" energy = 0.5*wCoulomb^2 + strength/zCoulomb; {orbit}", 

253 ) 

254 guess = ( 

255 "(2*step(meanAnomaly) - 1)" 

256 "*min(0.5*target, 0.5*log(2*target + sqrt(4*target^2 + 1)));" 

257 " target = abs(meanAnomaly)" 

258 ) 

259 

260 def correction(angle: str) -> str: 

261 return ( 

262 "residual*coshA/(2*coshA^3 - residual*sinhA);" 

263 f" residual = {angle} + sinhA*coshA - meanAnomaly;" 

264 " sinhA = 0.5*(expA - 1/expA); coshA = 0.5*(expA + 1/expA);" 

265 f" expA = exp({angle})" 

266 ) 

267 

268 add("angle", f"start - {correction('start')}; start = {guess}") 

269 if self._halley_iterations == 1: 

270 add("expAngle", "exp(angle)") 

271 else: 

272 for _ in range(self._halley_iterations - 2): 

273 add("angle", f"angle - {correction('angle')}") 

274 # The last correction is applied to exp(angle) by a Taylor factor. 

275 add( 

276 "expAngle", 

277 "expA*(1 - delta + delta^2/2 - delta^3/6);" 

278 f" delta = {correction('angle')}", 

279 ) 

280 add( 

281 "v", 

282 f"v*{scale}cosh0*2*expAngle/(expAngle^2 + 1);" 

283 f" cosh0 = sqrt(sinh0^2 + 1); {orbit}", 

284 ) 

285 add( 

286 "v2", 

287 self._masked( 

288 f"0.5*(expAngle - 1/expAngle)*{_V_FLOOR}*sqrt(m*invQ2) - {kick}" 

289 ), 

290 ) 

291 

292 def _add_v_scaling(self, fraction: float) -> None: 

293 self.addComputePerDof("v", f"v*exp(-{fraction}*dt*(v1 + kT*v2))") 

294 

295 def _add_thermostat(self) -> None: 

296 self._add_v1_boost(0.5) 

297 self._add_v_scaling(0.5) 

298 self._add_coulomb_step() 

299 self._add_v_scaling(0.5) 

300 self._add_v1_boost(0.5) 

301 

302 def registerWithSystem(self, system: mm.System, isExtension: bool) -> None: 

303 if system.getNumConstraints() > 0: 

304 raise ValueError("Massive GGMT integrators do not support constraints.") 

305 self._set_dof_mask(system, isExtension)