Coverage for openxps/context.py: 99%

121 statements  

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

1""" 

2.. module:: openxps.context 

3 :platform: Linux, MacOS, Windows 

4 :synopsis: Context for extended phase-space simulations with OpenMM. 

5 

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

7 

8""" 

9 

10import typing as t 

11 

12import openmm as mm 

13from openmm import _openmm as mmswig 

14from openmm import unit as mmunit 

15 

16from .integrator import ExtendedSpaceIntegrator 

17from .system import ExtendedSpaceSystem 

18from .utils import BINARY_SEPARATOR 

19 

20 

21class ExtendedSpaceContext(mm.Context): 

22 """An :OpenMM:`Context` object that includes extra dynamical variables (DVs) and 

23 allows for extended phase-space (XPS) simulations. 

24 

25 Parameters 

26 ---------- 

27 system 

28 The :class:`ExtendedSpaceSystem` to be used in the XPS simulation. 

29 integrator 

30 An :class:`ExtendedSpaceIntegrator` object to be used for advancing the XPS 

31 simulation. Available implementations include :class:`LockstepIntegrator` for 

32 systems where both integrators use the same step size, and 

33 :class:`SplitIntegrator` for systems with different step sizes related by an 

34 even integer ratio. 

35 platform 

36 The :OpenMM:`Platform` to use for calculations. 

37 properties 

38 A dictionary of values for platform-specific properties. 

39 

40 Example 

41 ------- 

42 >>> import openxps as xps 

43 >>> from math import pi 

44 >>> import openmm 

45 >>> import cvpack 

46 >>> from openmm import unit 

47 >>> from openmmtools import testsystems 

48 >>> model = testsystems.AlanineDipeptideVacuum() 

49 >>> mass = 3 * unit.dalton*(unit.nanometer/unit.radian)**2 

50 >>> phi0 = xps.DynamicalVariable("phi0", unit.radian, mass, xps.CircularBounds()) 

51 >>> phi = cvpack.Torsion(6, 8, 14, 16, name="phi") 

52 >>> kappa = 1000 * unit.kilojoule_per_mole / unit.radian**2 

53 >>> harmonic_force = xps.HarmonicCoupling(phi, phi0, kappa) 

54 >>> temp = 300 * unit.kelvin 

55 >>> integrator = openmm.LangevinMiddleIntegrator( 

56 ... temp, 1 / unit.picosecond, 4 * unit.femtosecond 

57 ... ) 

58 >>> integrator.setRandomNumberSeed(1234) 

59 >>> platform = openmm.Platform.getPlatformByName("Reference") 

60 >>> context = xps.ExtendedSpaceContext( 

61 ... xps.ExtendedSpaceSystem(model.system, harmonic_force), 

62 ... xps.LockstepIntegrator(integrator), 

63 ... platform, 

64 ... ) 

65 >>> context.setPositions(model.positions) 

66 >>> context.setVelocitiesToTemperature(temp, 1234) 

67 >>> context.setDynamicalVariableValues([180 * unit.degree]) 

68 >>> context.setDynamicalVariableVelocitiesToTemperature(temp, 1234) 

69 >>> context.getIntegrator().step(100) 

70 >>> print("phi0 =", *context.getDynamicalVariableValues()) 

71 phi0 = ... rad 

72 >>> state = context.getExtensionContext().getState(getEnergy=True) 

73 >>> print("U =", state.getPotentialEnergy(), "K =", state.getKineticEnergy()) 

74 U = ... kJ/mol K = ... kJ/mol 

75 """ 

76 

77 def __init__( 

78 self, 

79 system: ExtendedSpaceSystem, 

80 integrator: ExtendedSpaceIntegrator, 

81 platform: mm.Platform | None = None, 

82 properties: dict | None = None, 

83 ) -> None: 

84 self._validate(system, integrator) 

85 args = [system, integrator.getPhysicalIntegrator()] 

86 if platform is not None: 

87 args.append(platform) 

88 if properties is not None: 

89 args.append(properties) 

90 super().__init__(*args) 

91 extension_context = mm.Context( 

92 system.getExtensionSystem(), 

93 integrator.getExtensionIntegrator(), 

94 mm.Platform.getPlatformByName("Reference"), 

95 ) 

96 integrator.configure( 

97 physical_context=self, 

98 extension_context=extension_context, 

99 coupling=system.getCoupling(), 

100 ) 

101 self._system = system 

102 self._dvs = system.getDynamicalVariables() 

103 self._coupling = system.getCoupling() 

104 self._integrator = integrator 

105 self._extension_context = extension_context 

106 

107 def _validate( 

108 self, 

109 system: ExtendedSpaceSystem, 

110 integrator: ExtendedSpaceIntegrator, 

111 ) -> None: 

112 if not isinstance(system, ExtendedSpaceSystem): 

113 raise TypeError("The system must be an instance of ExtendedSpaceSystem.") 

114 if not isinstance(integrator, ExtendedSpaceIntegrator): 

115 raise TypeError( 

116 "The integrator must be an instance of ExtendedSpaceIntegrator." 

117 ) 

118 

119 def getSystem(self) -> ExtendedSpaceSystem: 

120 """ 

121 Get the system included in the extended phase-space context. 

122 

123 Returns 

124 ------- 

125 ExtendedSpaceSystem 

126 The system. 

127 """ 

128 return self._system 

129 

130 def getIntegrator(self) -> ExtendedSpaceIntegrator: 

131 """ 

132 Get the integrator included in the extended phase-space context. 

133 

134 Returns 

135 ------- 

136 ExtendedSpaceIntegrator 

137 The integrator. 

138 """ 

139 return self._integrator 

140 

141 def synchronize(self) -> None: 

142 """ 

143 Push the dynamical variable values to the physical context and the 

144 collective variable values to the extension context. 

145 

146 Call this after changing the physical state through a channel that bypasses 

147 this class, such as an :OpenMM:`LocalEnergyMinimizer`. 

148 """ 

149 self._coupling.updatePhysicalContext(self, self._extension_context) 

150 self._coupling.updateExtensionContext(self, self._extension_context) 

151 

152 def _pushSharedParameters(self) -> None: 

153 """Copy parameters present in both contexts from the physical one.""" 

154 protected = self._coupling.getProtectedParameters() 

155 extension_parameters = self._extension_context.getParameters() 

156 for name, value in self.getParameters().items(): 

157 if name in extension_parameters and name not in protected: 

158 self._extension_context.setParameter(name, value) 

159 

160 def getParameter(self, name: str) -> float: 

161 """ 

162 Get the value of a global parameter of the physical or extension system. 

163 

164 Parameters 

165 ---------- 

166 name 

167 The name of the parameter. A parameter that exists only in the extension 

168 system (e.g. a parameter of a coupling function) is read from the 

169 extension context. 

170 

171 Returns 

172 ------- 

173 float 

174 The value of the parameter. 

175 """ 

176 if name not in self.getParameters() and ( 

177 name in self._extension_context.getParameters() 

178 ): 

179 return self._extension_context.getParameter(name) 

180 return super().getParameter(name) 

181 

182 def setParameter(self, name: str, value: mmunit.Quantity) -> None: 

183 """ 

184 Set the value of a global parameter defined by a Force object in the System. 

185 

186 Notes 

187 ----- 

188 Parameters that represent dynamical variables are protected and cannot be set 

189 through this method; use :meth:`setDynamicalVariableValues` instead. A 

190 parameter that exists in both systems (e.g. a coupling constant) is updated 

191 in both contexts, and one that exists only in the extension system (e.g. a 

192 parameter of a coupling function) is updated in the extension context. Both 

193 contexts are then synchronized. 

194 

195 Parameters 

196 ---------- 

197 name 

198 The name of the parameter to set. 

199 value 

200 The value of the parameter. 

201 """ 

202 if name in self._coupling.getProtectedParameters(): 

203 raise ValueError( 

204 f'Cannot manually set the parameter "{name}". This parameter is ' 

205 "set automatically via setDynamicalVariableValues." 

206 ) 

207 in_extension = name in self._extension_context.getParameters() 

208 if name in self.getParameters() or not in_extension: 

209 super().setParameter(name, value) 

210 if in_extension: 

211 self._extension_context.setParameter(name, value) 

212 self.synchronize() 

213 

214 def reinitialize(self, preserveState: bool = False) -> None: 

215 """ 

216 Reinitialize the physical context and restore the dynamical variable 

217 parameters from the extension context, whose state is always preserved. 

218 

219 Parameters shared by both contexts take their values from the physical 

220 context, so they are reset to their defaults when the physical state is not 

221 preserved. 

222 

223 Parameters 

224 ---------- 

225 preserveState 

226 Whether to preserve the state of the physical context. 

227 """ 

228 super().reinitialize(preserveState) 

229 self._extension_context.reinitialize(True) 

230 self._pushSharedParameters() 

231 self._coupling.updatePhysicalContext(self, self._extension_context) 

232 if preserveState: 

233 self._coupling.updateExtensionContext(self, self._extension_context) 

234 

235 def setState(self, state: mm.State) -> None: 

236 """ 

237 Set the state of the physical context and synchronize both contexts. 

238 

239 Parameters restored from the state that also exist in the extension system 

240 (e.g. a coupling constant) are copied to the extension context. 

241 

242 Parameters 

243 ---------- 

244 state 

245 The :OpenMM:`State` to apply to the physical context. 

246 """ 

247 super().setState(state) 

248 self._pushSharedParameters() 

249 self.synchronize() 

250 

251 def setPositions(self, positions: mmunit.Quantity) -> None: 

252 """ 

253 Sets the positions of all particles in the physical system. 

254 

255 Parameters 

256 ---------- 

257 positions 

258 The positions for each particle in the system. 

259 """ 

260 super().setPositions(positions) 

261 self._coupling.updateExtensionContext(self, self._extension_context) 

262 

263 def setDynamicalVariableValues(self, values: t.Iterable[mmunit.Quantity]) -> None: 

264 """ 

265 Set the values of the dynamical variables. 

266 

267 Parameters 

268 ---------- 

269 values 

270 The values of all dynamical variables, in the order of 

271 :meth:`ExtendedSpaceSystem.getDynamicalVariables`. As in OpenMM, a value 

272 given without units is taken in MD units (e.g. radians for angles, even 

273 if the dynamical variable was declared in degrees). 

274 """ 

275 values = list(values) 

276 if len(values) != len(self._dvs): 

277 raise ValueError( 

278 f"Expected values for {len(self._dvs)} dynamical variables, " 

279 f"got {len(values)}." 

280 ) 

281 positions = [] 

282 for dv, quantity in zip(self._dvs, values): 

283 if mmunit.is_quantity(quantity): 

284 value = quantity.value_in_unit(dv.unit) 

285 else: 

286 value = quantity 

287 positions.append(mm.Vec3(value, 0, 0)) 

288 self._extension_context.setPositions(positions) 

289 self._coupling.updatePhysicalContext(self, self._extension_context) 

290 

291 def getDynamicalVariableValues(self) -> tuple[mmunit.Quantity]: 

292 """ 

293 Get the values of the dynamical variables, wrapped into their bounds. 

294 

295 Returns 

296 ------- 

297 t.Tuple[mmunit.Quantity] 

298 The values of the dynamical variables, in the order of 

299 :meth:`ExtendedSpaceSystem.getDynamicalVariables`. They are given in MD 

300 units, whatever unit each dynamical variable was declared in. 

301 """ 

302 state = mmswig.Context_getState(self._extension_context, mm.State.Positions) 

303 positions = mmswig.State__getVectorAsVec3(state, mm.State.Positions) 

304 values = [] 

305 for i, dv in enumerate(self._dvs): 

306 value, _ = dv.bounds.wrap(positions[i].x, 0) 

307 values.append(value * dv.unit) 

308 return tuple(values) 

309 

310 def setDynamicalVariableVelocities( 

311 self, velocities: t.Iterable[mmunit.Quantity] 

312 ) -> None: 

313 """ 

314 Set the velocities of the dynamical variables. 

315 

316 Parameters 

317 ---------- 

318 velocities 

319 The velocities of all dynamical variables, in the order of 

320 :meth:`ExtendedSpaceSystem.getDynamicalVariables`. As in OpenMM, a 

321 velocity given without units is taken in MD units (e.g. radians per 

322 picosecond for angles). 

323 """ 

324 velocities = list(velocities) 

325 if len(velocities) != len(self._dvs): 

326 raise ValueError( 

327 f"Expected velocities for {len(self._dvs)} dynamical variables, " 

328 f"got {len(velocities)}." 

329 ) 

330 for i, dv in enumerate(self._dvs): 

331 value = velocities[i] 

332 if mmunit.is_quantity(value): 

333 value = value.value_in_unit(dv.unit / mmunit.picosecond) 

334 velocities[i] = mm.Vec3(value, 0, 0) 

335 self._extension_context.setVelocities(velocities) 

336 

337 def setDynamicalVariableVelocitiesToTemperature( 

338 self, temperature: mmunit.Quantity, seed: int | None = None 

339 ) -> None: 

340 """ 

341 Set the velocities of the dynamical variables to a temperature. 

342 

343 Parameters 

344 ---------- 

345 temperature 

346 The temperature to set the velocities to. 

347 """ 

348 args = (temperature,) if seed is None else (temperature, seed) 

349 self._extension_context.setVelocitiesToTemperature(*args) 

350 state = mmswig.Context_getState(self._extension_context, mm.State.Velocities) 

351 velocities = mmswig.State__getVectorAsVec3(state, mm.State.Velocities) 

352 self._extension_context.setVelocities([mm.Vec3(v.x, 0, 0) for v in velocities]) 

353 

354 def getDynamicalVariableVelocities(self) -> tuple[mmunit.Quantity]: 

355 """ 

356 Get the velocities of the dynamical variables. 

357 

358 Returns 

359 ------- 

360 t.Tuple[mmunit.Quantity] 

361 The velocities of the dynamical variables, in the order of 

362 :meth:`ExtendedSpaceSystem.getDynamicalVariables`. They are given in MD 

363 units, whatever unit each dynamical variable was declared in. 

364 """ 

365 state = mmswig.Context_getState( 

366 self._extension_context, mm.State.Positions | mm.State.Velocities 

367 ) 

368 positions = mmswig.State__getVectorAsVec3(state, mm.State.Positions) 

369 velocities = mmswig.State__getVectorAsVec3(state, mm.State.Velocities) 

370 dv_velocities = [] 

371 for i, dv in enumerate(self._dvs): 

372 _, rate = dv.bounds.wrap(positions[i].x, velocities[i].x) 

373 dv_velocities.append(rate * dv.unit / mmunit.picosecond) 

374 return tuple(dv_velocities) 

375 

376 def getExtensionContext(self) -> mm.Context: 

377 """ 

378 Get a reference to the OpenMM context containing the extension system. 

379 

380 Returns 

381 ------- 

382 mm.Context 

383 The context containing the extension system. 

384 """ 

385 return self._extension_context 

386 

387 def createCheckpoint(self) -> bytes: 

388 r"""Create a checkpoint recording the current state of the Context. 

389 

390 This should be treated as an opaque block of binary data. See 

391 :meth:`loadCheckpoint` for more details. 

392 

393 Returns 

394 ------- 

395 bytes 

396 The checkpoint data 

397 

398 """ 

399 return ( 

400 mmswig.Context_createCheckpoint(self) 

401 + BINARY_SEPARATOR 

402 + mmswig.Context_createCheckpoint(self._extension_context) 

403 ) 

404 

405 def loadCheckpoint(self, checkpoint: bytes) -> None: 

406 r"""Load a checkpoint that was written by :meth:`createCheckpoint`. 

407 

408 See :OpenMM:`Context` for more details. 

409 

410 Parameters 

411 ---------- 

412 checkpoint 

413 The checkpoint data to load. 

414 """ 

415 physical_checkpoint, extension_checkpoint = checkpoint.split(BINARY_SEPARATOR) 

416 mmswig.Context_loadCheckpoint(self, physical_checkpoint) 

417 mmswig.Context_loadCheckpoint(self._extension_context, extension_checkpoint)