Coverage for ufedmm/ufedmm.py: 99%

571 statements  

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

1""" 

2.. module:: ufedmm 

3 :platform: Unix, Windows 

4 :synopsis: Unified Free Energy Dynamics with OpenMM 

5 

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

7""" 

8 

9import functools 

10import warnings 

11from copy import deepcopy 

12 

13import numpy as np 

14import openmm 

15from openmm import app, unit 

16 

17import ufedmm 

18 

19 

20def _standardized(quantity): 

21 """Returns the numerical value of a quantity in a unit of measurement compatible 

22 with the Molecular Dynamics unit system (mass in Da, distance in nm, time in ps, 

23 temperature in K, energy in kJ/mol, angle in rad).""" 

24 if unit.is_quantity(quantity): 

25 return quantity.value_in_unit_system(unit.md_unit_system) 

26 else: 

27 return quantity 

28 

29 

30def _add_fake_particles(force, num_particles): # noqa: PLR0912 

31 if isinstance(force, openmm.CustomCVForce): 

32 for i in range(force.getNumCollectiveVariables()): 

33 _add_fake_particles(force.getCollectiveVariable(i), num_particles) 

34 elif isinstance(force, openmm.NonbondedForce): 

35 for _ in range(num_particles - force.getNumParticles()): 

36 force.addParticle(0.0, 1.0, 0.0) 

37 elif isinstance(force, openmm.CustomNonbondedForce): 

38 for _ in range(num_particles - force.getNumParticles()): 

39 force.addParticle([0.0] * force.getNumPerParticleParameters()) 

40 elif isinstance(force, openmm.CustomGBForce): 

41 if force.getNumParticles() < num_particles: 

42 parameter_list = list( 

43 map(force.getParticleParameters, range(force.getNumParticles())) 

44 ) 

45 force.addPerParticleParameter("isreal") 

46 # Extra particles must neither contribute to pairwise computed values 

47 # (such as the Born radii) nor carry any energy 

48 for index in range(force.getNumComputedValues()): 

49 name, expression, type = force.getComputedValueParameters(index) 

50 if type != force.SingleParticle: 

51 force.setComputedValueParameters( 

52 index, name, f"isreal2*V_GB; V_GB={expression}", type 

53 ) 

54 for index in range(force.getNumEnergyTerms()): 

55 expression, type = force.getEnergyTermParameters(index) 

56 energy = ( 

57 "isreal*E_GB" 

58 if type == force.SingleParticle 

59 else "isreal1*isreal2*E_GB" 

60 ) 

61 force.setEnergyTermParameters( 

62 index, f"{energy}; E_GB={expression}", type 

63 ) 

64 for index, parameters in enumerate(parameter_list): 

65 force.setParticleParameters(index, parameters + (1.0,)) 

66 for _ in range(num_particles - force.getNumParticles()): 

67 force.addParticle(parameter_list[0] + (0.0,)) 

68 elif isinstance(force, openmm.GBSAOBCForce): 

69 raise RuntimeError("GBSAOBCForce not supported") 

70 elif hasattr(force, "getReferencePositions"): 

71 refpos = force.getReferencePositions()._value 

72 if len(refpos) < num_particles: 

73 for _ in range(num_particles - len(refpos)): 

74 refpos.append(openmm.Vec3(0, 0, 0)) 

75 force.setReferencePositions(refpos) 

76 

77 

78class CollectiveVariable: 

79 """A function of the particle coordinates, evaluated by means of an :OpenMM:`Force` 

80 object. 

81 

82 Quoting the manual entry for :OpenMM:`CustomCVForce`: 

83 

84 "Each collective variable is defined by a Force object. The Force's potential 

85 energy is computed, and that becomes the value of the variable. This provides 

86 enormous flexibility in defining collective variables, especially by using 

87 custom forces. Anything that can be computed as a potential function can also 

88 be used as a collective variable." 

89 

90 Parameters 

91 ---------- 

92 id : str 

93 A valid identifier string for this collective variable. 

94 force : openmm.Force 

95 An :OpenMM:`Force` object whose energy function is used to evaluate this 

96 collective variable. 

97 

98 Example 

99 ------- 

100 >>> import openmm 

101 >>> import ufedmm 

102 >>> from openmm import unit 

103 >>> cv = ufedmm.CollectiveVariable('psi', openmm.CustomTorsionForce('theta')) 

104 >>> cv.force.addTorsion(0, 1, 2, 3, []) 

105 0 

106 """ 

107 

108 def __init__(self, id, force): 

109 if not id.isidentifier(): 

110 raise ValueError("Parameter id must be a valid variable identifier") 

111 self.id = id 

112 self.force = force 

113 

114 def _create_context(self, system, positions): 

115 system_copy = deepcopy(system) 

116 for force in system_copy.getForces(): 

117 force.setForceGroup(0) 

118 force_copy = deepcopy(self.force) 

119 force_copy.setForceGroup(1) 

120 _add_fake_particles(force_copy, system.getNumParticles()) 

121 system_copy.addForce(force_copy) 

122 platform = openmm.Platform.getPlatformByName("Reference") 

123 context = openmm.Context(system_copy, openmm.CustomIntegrator(0), platform) 

124 context.setPositions(positions) 

125 return context 

126 

127 def evaluate(self, system, positions, cv_unit=None): 

128 """Computes the value of the collective variable for a given system and a given 

129 set of particle coordinates. 

130 

131 Parameters 

132 ---------- 

133 system : openmm.System 

134 The system for which the collective variable will be evaluated. 

135 positions : list of openmm.Vec3 

136 A list whose size equals the number of particles in the system and which 

137 contains the coordinates of these particles. 

138 

139 Keyword Args 

140 ------------ 

141 cv_unit : unit.Unit, default=None 

142 The unity of measurement of the collective variable. If this is `None`, 

143 then a numerical value is returned based on the OpenMM default units. 

144 

145 Returns 

146 ------- 

147 float or unit.Quantity 

148 

149 Example 

150 ------- 

151 >>> import ufedmm 

152 >>> from openmm import unit 

153 >>> model = ufedmm.AlanineDipeptideModel() 

154 >>> model.phi.evaluate(model.system, model.positions) 

155 3.141592653589793 

156 >>> model.psi.evaluate(model.system, model.positions) 

157 3.141592653589793 

158 """ 

159 context = self._create_context(system, positions) 

160 energy = context.getState(getEnergy=True, groups={1}).getPotentialEnergy() 

161 value = energy.value_in_unit(unit.kilojoules_per_mole) 

162 if cv_unit is not None: 

163 value *= cv_unit / _standardized(1 * cv_unit) 

164 return value 

165 

166 def effective_mass(self, system, positions, cv_unit=None): 

167 """Computes the effective mass of the collective variable for a given system and 

168 a given set of particle coordinates. 

169 

170 The effective mass of a collective variable :math:`q(\\mathbf{r})` is defined as 

171 :cite:`Cuendet_2014`: 

172 

173 .. math:: 

174 m_\\mathrm{eff} = \\left( 

175 \\sum_{j=1}^N \\frac{1}{m_j} \\left\\| 

176 \\frac{dq}{d\\mathbf{r}_j} 

177 \\right\\|^2 

178 \\right)^{-1} 

179 

180 Parameters 

181 ---------- 

182 system : openmm.System 

183 The system for which the collective variable will be evaluated. 

184 positions : list of openmm.Vec3 

185 A list whose size equals the number of particles in the system and which 

186 contains the coordinates of these particles. 

187 

188 Keyword Args 

189 ------------ 

190 cv_unit : unit.Unit, default=None 

191 The unity of measurement of the collective variable. If this is `None`, 

192 then a numerical value is returned based on the OpenMM default units. 

193 

194 Returns 

195 ------- 

196 float or unit.Quantity 

197 

198 Example 

199 ------- 

200 >>> import ufedmm 

201 >>> from openmm import unit 

202 >>> model = ufedmm.AlanineDipeptideModel() 

203 >>> model.phi.effective_mass(model.system, model.positions) 

204 0.04795887... 

205 >>> model.psi.effective_mass(model.system, model.positions) 

206 0.05115582... 

207 """ 

208 context = self._create_context(system, positions) 

209 forces = _standardized( 

210 context.getState(getForces=True, groups={1}).getForces(asNumpy=True) 

211 ) 

212 denom = sum( 

213 f.dot(f) / _standardized(system.getParticleMass(i)) 

214 for i, f in enumerate(forces) 

215 ) 

216 effective_mass = 1.0 / float(denom) 

217 if cv_unit is not None: 

218 factor = _standardized(1 * cv_unit) ** 2 

219 effective_mass *= factor * unit.dalton * (unit.nanometers / cv_unit) ** 2 

220 return effective_mass 

221 

222 

223class DynamicalVariable: 

224 """An extended phase-space variable, whose dynamics is coupled to that of one of 

225 more collective variables of a system. 

226 

227 The coupling occurs in the form of a potential energy term involving this dynamical 

228 variable and its associated collective variables. 

229 

230 The default potential is a harmonic driving of the type: 

231 

232 .. math:: 

233 V(s, \\mathbf r) = \\frac{\\kappa}{2} [s - q(\\mathbf r)]^2 

234 

235 where :math:`s` is the new dynamical variable, :math:`q(\\mathbf r)` is its 

236 associated collective variable, and :math:`kappa` is a force constant. 

237 

238 Parameters 

239 ---------- 

240 id : str 

241 A valid identifier string for this dynamical variable. 

242 min_value : float or unit.Quantity 

243 The minimum allowable value for this dynamical variable. 

244 max_value : float or unit.Quantity 

245 The maximum allowable value for this dynamical variable. 

246 mass : float or unit.Quantity 

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

248 be compatible with `unit.dalton*(unit.nanometers/X)**2`, where `X` is the 

249 unit of measurement of the dynamical variable itself. 

250 temperature : float or unit.Quantity 

251 The temperature of the heat bath attached to this variable. 

252 colvars : :class:`~ufedmm.ufedmm.CollectiveVariable` or list thereof 

253 Either a single colective variable or a list. 

254 potential : float or unit.Quantity or str 

255 Either the value of the force constant of a harmonic driving potential or an 

256 algebraic expression giving the energy of the system as a function of this 

257 dynamical variable and its associated collective variable. Such expression 

258 can also contain a set of global parameters, whose values must be passed as 

259 keyword arguments (see below). 

260 

261 Keyword Args 

262 ------------ 

263 periodic : bool, default=True 

264 Whether the collective variable is periodic with period 

265 `L=max_value-min_value`. 

266 sigma : float or unit.Quantity, default=None 

267 The standard deviation. If this is `None`, then no bias will be considered. 

268 grid_size : int, default=None 

269 The grid size. If this is `None` and `sigma` is finite, then a convenient 

270 value will be automatically chosen. 

271 **parameters 

272 Names and values of global parameters present in the algebraic expression 

273 defined as `potential` (see above). 

274 

275 Example 

276 ------- 

277 >>> import openmm 

278 >>> import ufedmm 

279 >>> from openmm import unit 

280 >>> cv = ufedmm.CollectiveVariable('psi', openmm.CustomTorsionForce('theta')) 

281 >>> cv.force.addTorsion(0, 1, 2, 3, []) 

282 0 

283 >>> mass = 50*unit.dalton*(unit.nanometer/unit.radians)**2 

284 >>> K = 1000*unit.kilojoules_per_mole/unit.radians**2 

285 >>> Ts = 1500*unit.kelvin 

286 >>> ufedmm.DynamicalVariable( 

287 ... 's_psi', -180*unit.degrees, 180*unit.degrees, mass, Ts, cv, K 

288 ... ) 

289 <s_psi in [-3.141592653589793, 3.141592653589793], periodic, m=50, T=1500> 

290 """ 

291 

292 def __init__( # noqa: PLR0913, PLR0917 

293 self, 

294 id, 

295 min_value, 

296 max_value, 

297 mass, 

298 temperature, 

299 colvars, 

300 potential, 

301 periodic=True, 

302 sigma=None, 

303 grid_size=None, 

304 **parameters, 

305 ): 

306 self.id = id 

307 self.min_value = _standardized(min_value) 

308 self.max_value = _standardized(max_value) 

309 self._range = self.max_value - self.min_value 

310 self.mass = _standardized(mass) 

311 self.temperature = _standardized(temperature) 

312 

313 self.colvars = colvars if isinstance(colvars, (list, tuple)) else [colvars] 

314 

315 if isinstance(potential, str): 

316 self.potential = potential 

317 self.parameters = { 

318 key: _standardized(value) for key, value in parameters.items() 

319 } 

320 else: 

321 cv_id = self.colvars[0].id 

322 if periodic: 

323 self.potential = f"0.5*K_{cv_id}*min(d{cv_id},{self._range}-d{cv_id})^2" 

324 self.potential += f"; d{cv_id}=abs({cv_id}-{self.id})" 

325 else: 

326 self.potential = f"0.5*K_{cv_id}*({cv_id}-{self.id})^2" 

327 self.parameters = {f"K_{cv_id}": _standardized(potential)} 

328 

329 self.periodic = periodic 

330 

331 if sigma is None or sigma == 0.0: 

332 self.sigma = self.grid_size = None 

333 else: 

334 self.sigma = _standardized(sigma) 

335 self._scaled_variance = (self.sigma / self._range) ** 2 

336 if grid_size is None: 

337 self.grid_size = int(np.ceil(5 * self._range / self.sigma)) + 1 

338 else: 

339 self.grid_size = grid_size 

340 

341 self.force = openmm.CustomExternalForce(self._get_energy_function()) 

342 self.force.addGlobalParameter("Lx", 0.0) 

343 self.force.addParticle(0, []) 

344 

345 def __repr__(self): 

346 properties = f"m={self.mass}, T={self.temperature}" 

347 status = "periodic" if self.periodic else "non-periodic" 

348 return ( 

349 f"<{self.id} in " 

350 f"[{self.min_value}, {self.max_value}], {status}, {properties}>" 

351 ) 

352 

353 def __getstate__(self): 

354 return dict( 

355 id=self.id, 

356 min_value=self.min_value, 

357 max_value=self.max_value, 

358 mass=self.mass, 

359 temperature=self.temperature, 

360 colvars=self.colvars, 

361 potential=self.potential, 

362 periodic=self.periodic, 

363 sigma=self.sigma, 

364 grid_size=self.grid_size, 

365 **self.parameters, 

366 ) 

367 

368 def __setstate__(self, kw): 

369 self.__init__(**kw) 

370 

371 def _particle_mass(self, Lx): 

372 length = Lx if self.periodic else Lx / 2 

373 return self.mass * (self._range / length) ** 2 

374 

375 def _get_energy_function(self, index=""): 

376 """Returns the algebraic expression that transforms the x coordinate of a 

377 particle into this dynamical variables. 

378 

379 Keyword Args 

380 ------------ 

381 index : str or int, default='' 

382 An index for the particle in question, if needed. 

383 

384 Returns 

385 ------- 

386 str 

387 """ 

388 if self.periodic: 

389 energy = f"{self.min_value}+{self._range}*(x{index}/Lx-floor(x{index}/Lx))" 

390 else: 

391 energy = f"{self.min_value}+{2 * self._range}*min(pos{index},1-pos{index})" 

392 energy += f";pos{index}=x{index}/Lx-floor(x{index}/Lx)" 

393 return energy 

394 

395 def evaluate(self, x, Lx): 

396 """Computes the value of this dynamical variable for a given x coordinate and a 

397 given length of the simulation box in the x direction. 

398 

399 Parameters 

400 ---------- 

401 x : float or unit.Quantity 

402 The x coordinate. 

403 Lx : float or unit.Quantity 

404 The length of the simulation box in the x direction. 

405 

406 Returns 

407 ------- 

408 float 

409 """ 

410 pos = x / Lx - np.floor(x / Lx) 

411 if self.periodic: 

412 return self.min_value + self._range * pos 

413 else: 

414 return self.min_value + 2 * self._range * min(pos, 1 - pos) 

415 

416 

417def _get_energy_function(variables): 

418 energies = [v.potential.split(";", 1) for v in variables] 

419 energy_terms = [energy[0] for energy in energies] 

420 definitions = [energy[1] for energy in energies if len(energy) == 2] # noqa: PLR2004 

421 expression = ";".join(["+".join(energy_terms)] + list(definitions)) 

422 return expression 

423 

424 

425def _get_parameters(variables): 

426 parameters = {} 

427 for v in variables: 

428 parameters.update(v.parameters) 

429 return parameters 

430 

431 

432def _write_array(file, array): 

433 file.write(array.tobytes()) 

434 

435 

436def _read_array(file, dtype, count): 

437 """Reads `count` items written by :func:`_write_array` from a binary file.""" 

438 size = np.dtype(dtype).itemsize * count 

439 data = file.read(size) 

440 if len(data) != size: 

441 raise ValueError("Unexpected end of checkpoint data") 

442 return np.frombuffer(data, dtype=dtype).copy() 

443 

444 

445class PeriodicTask: 

446 def __init__(self, frequency): 

447 self.frequency = frequency 

448 

449 def initialize(self, simulation): 

450 pass 

451 

452 def update(self, simulation, steps): 

453 pass 

454 

455 def describeNextReport(self, simulation): 

456 steps = self.frequency - simulation.context.getStepCount() % self.frequency 

457 return (steps, True, False, False, False, False) 

458 

459 def report(self, simulation, state): 

460 pass 

461 

462 def saveCheckpoint(self, file): 

463 pass 

464 

465 def loadCheckpoint(self, file, context): 

466 pass 

467 

468 

469class _Metadynamics(PeriodicTask): 

470 """Extended-space Metadynamics. 

471 

472 Parameters 

473 ---------- 

474 variables : list of :class:`DynamicalVariable` 

475 A list of extended-space dynamical variables to which the metadynamics bias 

476 must be applied. In fact, dynamical variables with `sigma = None` will not 

477 be considered. 

478 height : float or unit.Quantity 

479 The height of the Gaussian potential hills to be deposited. If the 

480 `bias_factor` keyword is defined (see below), then this is the unscaled 

481 height. 

482 frequency : int 

483 The frequency of Gaussian hill deposition. 

484 

485 Keyword Args 

486 ------------ 

487 bias_factor : float, default=None 

488 Scales the height of the hills added to the bias potential. If it is `None`, 

489 then the hills will have a constant height over time. For a bias factor to 

490 be applicable, all bias variables must be at the same temperature T. The 

491 extended-space dynamical variables are sampled as if the effective 

492 temperature were T*bias_factor. 

493 buffer_size : int, default=100 

494 The buffer size. 

495 grid_expansion : int, default=20 

496 The number of extra grid points to be used in periodic directions of 

497 multidimensional tabulated functions. This aims at avoiding boundary 

498 discontinuity artifacts. 

499 enforce_gridless : bool, default=False 

500 Enforce gridless metadynamics even for 1D to 3D problems. 

501 """ 

502 

503 def __init__( # noqa: PLR0913, PLR0917 

504 self, 

505 variables, 

506 height, 

507 frequency, 

508 bias_factor=None, 

509 buffer_size=100, 

510 grid_expansion=20, 

511 enforce_gridless=False, 

512 ): 

513 super().__init__(frequency) 

514 self.bias_indices = [i for i, v in enumerate(variables) if v.sigma is not None] 

515 self.bias_variables = [variables[i] for i in self.bias_indices] 

516 self.initial_height = self.height = _standardized(height) 

517 self.bias_factor = bias_factor 

518 if bias_factor is not None: 

519 temperature = self.bias_variables[0].temperature 

520 if any(v.temperature != temperature for v in self.bias_variables): 

521 raise ValueError( 

522 "Well-tempered metadynamics requires same temperature " 

523 "for all variables." 

524 ) 

525 self.delta_kT = _standardized( 

526 (bias_factor - 1) * unit.MOLAR_GAS_CONSTANT_R * temperature 

527 ) 

528 self.buffer_size = buffer_size 

529 self.grid_expansion = grid_expansion 

530 self._use_grid = len(self.bias_variables) < 4 and not enforce_gridless # noqa: PLR2004 

531 self.force = ( 

532 self._interpolation_grid_force() if self._use_grid else self._hills_force() 

533 ) 

534 

535 def _interpolation_grid_force(self): 

536 self._widths = [] 

537 self._bounds = [] 

538 self._extra_points = [] 

539 full_periodic = self._full_periodic = all( 

540 v.periodic for v in self.bias_variables 

541 ) 

542 for v in self.bias_variables: 

543 extra_points = ( 

544 min(self.grid_expansion, v.grid_size - 1) 

545 if v.periodic and not full_periodic 

546 else 0 

547 ) 

548 extra_range = extra_points * v._range / (v.grid_size - 1) 

549 self._widths.append(v.grid_size + 2 * extra_points) 

550 self._bounds += [v.min_value - extra_range, v.max_value + extra_range] 

551 self._extra_points.append(extra_points) 

552 self._bias = np.zeros(np.prod(self._widths)) 

553 num_bias_variables = len(self.bias_variables) 

554 if num_bias_variables == 1: 

555 self._table = openmm.Continuous1DFunction( 

556 self._bias, *self._bounds, full_periodic 

557 ) 

558 elif num_bias_variables == 2: # noqa: PLR2004 

559 self._table = openmm.Continuous2DFunction( 

560 *self._widths, self._bias, *self._bounds, full_periodic 

561 ) 

562 else: 

563 self._table = openmm.Continuous3DFunction( 

564 *self._widths, self._bias, *self._bounds, full_periodic 

565 ) 

566 expression = ( 

567 f"metad_bias_scale*bias({','.join(v.id for v in self.bias_variables)})" 

568 ) 

569 for i, v in enumerate(self.bias_variables): 

570 expression += f";{v.id}={v._get_energy_function(i + 1)}" 

571 force = openmm.CustomCVForce(expression) 

572 for i in range(num_bias_variables): 

573 x = openmm.CustomExternalForce("x") 

574 x.addParticle(0, []) 

575 force.addCollectiveVariable(f"x{i + 1}", x) 

576 force.addTabulatedFunction("bias", self._table) 

577 force.addGlobalParameter("Lx", 0) 

578 force.addGlobalParameter("metad_bias_scale", 1) 

579 force.addEnergyParameterDerivative("metad_bias_scale") 

580 return force 

581 

582 def _hills_force(self): 

583 num_bias_variables = len(self.bias_variables) 

584 centers = [f"center{i + 1}" for i in range(num_bias_variables)] 

585 exponents = [] 

586 for v, center in zip(self.bias_variables, centers): 

587 if v.periodic: # von Mises 

588 factor = 2 * np.pi / v._range 

589 exponents.append( 

590 f"{1.0 / (factor * v.sigma) ** 2}" 

591 f"*(cos({factor}*({v.id}-{center}))-1)" 

592 ) 

593 else: # Gauss 

594 exponents.append(f"({-0.5 / v.sigma**2})*({v.id}-{center})^2") 

595 expression = f"metad_bias_scale*height*exp({'+'.join(exponents)})" 

596 for i, v in enumerate(self.bias_variables): 

597 expression += f";{v.id}={v._get_energy_function(i + 1)}" 

598 force = openmm.CustomCompoundBondForce(num_bias_variables, expression) 

599 force.addPerBondParameter("height") 

600 for center in centers: 

601 force.addPerBondParameter(center) 

602 force.addGlobalParameter("Lx", 0) 

603 force.addGlobalParameter("metad_bias_scale", 1) 

604 force.addEnergyParameterDerivative("metad_bias_scale") 

605 return force 

606 

607 def _add_buffer(self, simulation): 

608 size = min(self.buffer_size, self._total_hills - self.force.getNumBonds()) 

609 for _ in range(size): 

610 self.force.addBond(self.particles, [0] * (len(self.bias_variables) + 1)) 

611 simulation.context.reinitialize(preserveState=True) 

612 

613 def add_bias(self, simulation, bias): 

614 if self._use_grid: 

615 self._bias += bias.ravel() 

616 if len(self.bias_variables) == 1: 

617 self._table.setFunctionParameters(self._bias, *self._bounds) 

618 else: 

619 self._table.setFunctionParameters( 

620 *self._widths, self._bias, *self._bounds 

621 ) 

622 self.force.updateParametersInContext(simulation.context) 

623 

624 def initialize(self, simulation): 

625 context = simulation.context 

626 np = context.getSystem().getNumParticles() - len(context.variables) 

627 self.particles = [np + index for index in self.bias_indices] 

628 self.Lx = context.getParameter("Lx") 

629 if self._use_grid: 

630 for i, particle in enumerate(self.particles): 

631 self.force.getCollectiveVariable(i).setParticleParameters( 

632 0, particle, [] 

633 ) 

634 else: 

635 self._num_hills = 0 

636 self._total_hills = 0 

637 simulation.system.addForce(self.force) 

638 context.reinitialize(preserveState=True) 

639 

640 def update(self, simulation, steps): 

641 if not self._use_grid: 

642 steps_until_next_report = ( 

643 self.frequency - simulation.currentStep % self.frequency 

644 ) 

645 if steps_until_next_report > steps: 

646 required_hills = 0 

647 else: 

648 required_hills = (steps - steps_until_next_report) // self.frequency + 1 

649 self._total_hills = self._num_hills + required_hills 

650 self._add_buffer(simulation) 

651 

652 def report(self, simulation, state): 

653 centers = state.getDynamicalVariables() 

654 if self.bias_factor is None: 

655 self.height = self.initial_height 

656 else: 

657 hills_state = simulation.context.getState(getParameterDerivatives=True) 

658 energy = hills_state.getEnergyParameterDerivatives()["metad_bias_scale"] 

659 self.height = self.initial_height * np.exp(-energy / self.delta_kT) 

660 if self._use_grid: 

661 hills = [] 

662 for i, v in enumerate(self.bias_variables): 

663 x = (centers[i] - v.min_value) / v._range 

664 dist = np.linspace(0, 1, num=v.grid_size) - x 

665 if v.periodic: # von Mises 

666 exponents = (np.cos(2 * np.pi * dist) - 1) / ( 

667 4 * np.pi * np.pi * v._scaled_variance 

668 ) 

669 exponents[0] = exponents[-1] = 0.5 * (exponents[0] + exponents[-1]) 

670 else: # Gauss 

671 exponents = -0.5 * dist * dist / v._scaled_variance 

672 hills.append(np.exp(exponents)) 

673 ndim = len(self.bias_variables) 

674 bias = self.height * ( 

675 hills[0] 

676 if ndim == 1 

677 else functools.reduce(np.multiply.outer, reversed(hills)) 

678 ) 

679 if not self._full_periodic: 

680 for index, v in enumerate(self.bias_variables): 

681 if v.periodic: 

682 # The first variable runs fastest, so it is the last axis 

683 axis = ndim - 1 - index 

684 n = self._extra_points[index] + 1 

685 begin = tuple( 

686 slice(1, n) if i == axis else slice(None) 

687 for i in range(ndim) 

688 ) 

689 end = tuple( 

690 slice(-n, -1) if i == axis else slice(None) 

691 for i in range(ndim) 

692 ) 

693 bias = np.concatenate((bias[end], bias, bias[begin]), axis=axis) 

694 self.add_bias(simulation, bias) 

695 else: 

696 if self._num_hills == self.force.getNumBonds(): 

697 self._add_buffer(simulation) 

698 self.force.setBondParameters( 

699 self._num_hills, self.particles, [self.height] + centers 

700 ) 

701 self._num_hills += 1 

702 self.force.updateParametersInContext(simulation.context) 

703 

704 def saveCheckpoint(self, file): 

705 if self._use_grid: 

706 _write_array(file, self._bias) 

707 else: 

708 _write_array(file, np.array([self._num_hills], dtype=int)) 

709 parameter_list = [] 

710 for index in range(self._num_hills): 

711 _, parameters = self.force.getBondParameters(index) 

712 parameter_list.append(parameters) 

713 _write_array(file, np.array(parameter_list, dtype=float)) 

714 _write_array(file, np.array([self.height])) 

715 

716 def loadCheckpoint(self, file, context): 

717 if self._use_grid: 

718 self._bias = _read_array(file, float, len(self._bias)) 

719 if len(self.bias_variables) == 1: 

720 self._table.setFunctionParameters(self._bias, *self._bounds) 

721 else: 

722 self._table.setFunctionParameters( 

723 *self._widths, self._bias, *self._bounds 

724 ) 

725 self.force.updateParametersInContext(context) 

726 else: 

727 npars = len(self.bias_variables) + 1 

728 nhills = self._num_hills = int(_read_array(file, int, 1)[0]) 

729 parameter_array = _read_array(file, float, nhills * npars).reshape( 

730 (nhills, npars) 

731 ) 

732 for _ in range(nhills - self.force.getNumBonds()): 

733 self.force.addBond(self.particles, [0] * npars) 

734 self._total_hills = self.force.getNumBonds() 

735 for index, parameters in enumerate(parameter_array): 

736 self.force.setBondParameters(index, self.particles, parameters) 

737 for index in range(nhills, self._total_hills): 

738 self.force.setBondParameters(index, self.particles, [0] * npars) 

739 context.reinitialize(preserveState=True) 

740 self.height = _read_array(file, float, 1)[0] 

741 

742 

743class ExtendedSpaceState(openmm.State): 

744 """An extension of the :OpenMM:`State` class.""" 

745 

746 def __init__(self, variables, state): 

747 self.__class__ = type( 

748 state.__class__.__name__, (self.__class__, state.__class__), {} 

749 ) 

750 self.__dict__ = state.__dict__ 

751 self._variables = variables 

752 a, _, _ = self.getPeriodicBoxVectors() 

753 self._Lx = a.x 

754 

755 def _split(self, vector, asNumpy=False): 

756 num = (vector.shape[0] if asNumpy else len(vector)) - len(self._variables) 

757 particles_contribution = vector[:num, :] if asNumpy else vector[:num] 

758 variables_contribution = ( 

759 vector[num:, 0] if asNumpy else [vec.x for vec in vector[num:]] 

760 ) 

761 return particles_contribution, variables_contribution 

762 

763 def getPositions(self, asNumpy=False, extended=False, split=True): 

764 """Gets the positions of all physical particles and optionally also gets the 

765 positions of the extra particles from which the extended-space dynamical 

766 variables are computed. 

767 

768 Keyword Args 

769 ------------ 

770 asNumpy : bool, default=False 

771 Whether to return Numpy arrays instead of lists of openmm.Vec3. 

772 extended : bool, default=False 

773 Whether to include the positions of the extra particles from which the 

774 extended-space dynamical variables are computed. 

775 split : bool, default=True 

776 Whether to return the positions of the physical particles and the 

777 positions of the extra particles separately. 

778 

779 Returns 

780 ------- 

781 list(openmm.Vec3) or numpy.ndarray 

782 If `extended=False` or `split=False`. 

783 list(openmm.Vec3) or numpy.ndarray, list(float) or numpy.ndarray 

784 If `extended=True` and `split=True`. 

785 

786 Raises 

787 ------ 

788 Exception 

789 If positions were not requested in the ``context.getState()`` call. 

790 """ 

791 all_positions = super().getPositions(asNumpy) 

792 if extended and not split: 

793 return all_positions 

794 positions, xvars = self._split(all_positions, asNumpy) 

795 return (positions, xvars) if extended else positions 

796 

797 def getVelocities(self, asNumpy=False, extended=False, split=False): 

798 """Gets the velocities of all physical particles and optionally also gets the 

799 velocities of the extra particles associated to the extended- space dynamical 

800 variables. 

801 

802 Keyword Args 

803 ------------ 

804 asNumpy : bool, default=False 

805 Whether to return Numpy arrays instead of lists of openmm.Vec3. 

806 extended : bool, default=False 

807 Whether to include the velocities of the extra particles. 

808 split : bool, default=False 

809 Whether to return the velocities of the physical particles and the 

810 x velocities of the extra particles separately. Only used if 

811 `extended=True`. 

812 

813 Returns 

814 ------- 

815 list(openmm.Vec3) 

816 If `asNumpy=False`, and either `extended=False` or `split=False`. 

817 numpy.ndarray 

818 If `asNumpy=True`, and either `extended=False` or `split=False`. 

819 list(openmm.Vec3), list(float) 

820 If `asNumpy=False`, `extended=True`, and `split=True`. 

821 numpy.ndarray, numpy.ndarray 

822 If `asNumpy=True`, `extended=True`, and `split=True`. 

823 

824 Raises 

825 ------ 

826 Exception 

827 If velocities were not requested in the ``context.getState()`` call. 

828 """ 

829 all_velocities = super().getVelocities(asNumpy) 

830 if extended and not split: 

831 return all_velocities 

832 velocities, vvars = self._split(all_velocities, asNumpy) 

833 return (velocities, vvars) if extended else velocities 

834 

835 def getDynamicalVariables(self): 

836 """Gets the values of the extended-space dynamical variables. 

837 

838 Returns 

839 ------- 

840 list(float) 

841 

842 Raises 

843 ------ 

844 Exception 

845 If positions were not requested in the ``context.getState()`` call. 

846 

847 Example 

848 ------- 

849 >>> import ufedmm 

850 >>> import numpy as np 

851 >>> model = ufedmm.AlanineDipeptideModel() 

852 >>> integrator = ufedmm.CustomIntegrator(300, 0.001) 

853 >>> args = [-np.pi, np.pi, 50, 1500, model.phi, 1000] 

854 >>> s_phi = ufedmm.DynamicalVariable('s_phi', *args) 

855 >>> s_psi = ufedmm.DynamicalVariable('s_psi', *args) 

856 >>> context = ufedmm.ExtendedSpaceContext( 

857 ... [s_phi, s_psi], model.system, integrator 

858 ... ) 

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

860 >>> state = context.getState(getPositions=True) 

861 >>> [float(x) for x in state.getDynamicalVariables()] 

862 [-3.141592653589793, -3.141592653589793] 

863 """ 

864 _, xvars = self._split(super().getPositions()) 

865 return [v.evaluate(x, self._Lx) for v, x in zip(self._variables, xvars)] 

866 

867 

868class ExtendedSpaceContext(openmm.Context): 

869 """An extension of the :OpenMM:`Context` class. 

870 

871 Parameters 

872 ---------- 

873 variables : list(DynamicalVariable) 

874 The dynamical variables to be added to the system's phase space. 

875 system : openmm.System 

876 The :OpenMM:`System` which will be simulated 

877 integrator : openmm.Integrator 

878 The :OpenMM:`Integrator` which will be used to simulate the 

879 :OpenMM:`System`. 

880 platform : openmm.Platform 

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

882 properties : dict(str: str) 

883 A set of values for platform-specific properties. Keys are the property 

884 names. 

885 

886 Attributes 

887 ---------- 

888 variables : list(DynamicalVariable) 

889 The dynamical variables added to the system's phase space. 

890 driving_forces : list[openmm.CustomCVForce] 

891 A list of :OpenMM:`CustomCVForce` objects responsible for evaluating the 

892 potential energy terms which couples the extra dynamical variables to their 

893 associated collective variables. 

894 

895 Raises 

896 ------ 

897 ValueError 

898 If the system has constraints and the integrator is a UFEDMM integrator 

899 without RATTLE (``num_rattles=0``), which would ignore them. 

900 """ 

901 

902 def __init__(self, variables, system, *args, **kwargs): 

903 integrator = args[0] if args else kwargs.get("integrator") 

904 if ( 

905 getattr(integrator, "_num_rattles", None) == 0 

906 and system.getNumConstraints() 

907 ): 

908 raise ValueError( 

909 f"{integrator.__class__.__name__} without RATTLE cannot handle" 

910 f" constraints, but the system has {system.getNumConstraints()}." 

911 " Create the system without constraints or use an integrator with" 

912 " num_rattles > 0." 

913 ) 

914 

915 def get_driving_force(variables): 

916 driving_force = openmm.CustomCVForce(_get_energy_function(variables)) 

917 for name, value in _get_parameters(variables).items(): 

918 driving_force.addGlobalParameter(name, value) 

919 for var in variables: 

920 driving_force.addCollectiveVariable(var.id, var.force) 

921 for colvar in var.colvars: 

922 driving_force.addCollectiveVariable(colvar.id, colvar.force) 

923 return driving_force 

924 

925 driving_force_variables = [[]] 

926 added_colvars = 0 

927 for var in variables: 

928 colvars_to_add = len(var.colvars) + 1 

929 if added_colvars + colvars_to_add > 32: # noqa: PLR2004 

930 driving_force_variables.append([]) 

931 added_colvars = 0 

932 driving_force_variables[-1].append(deepcopy(var)) 

933 added_colvars += colvars_to_add 

934 driving_forces = [get_driving_force(vars) for vars in driving_force_variables] 

935 box_length_x = system.getDefaultPeriodicBoxVectors()[0].x 

936 num_particles = system.getNumParticles() 

937 collective_variables = [] 

938 for dfvars in driving_force_variables: 

939 for var in dfvars: 

940 system.addParticle(var._particle_mass(box_length_x)) 

941 var.force.setParticleParameters(0, num_particles, []) 

942 num_particles += 1 

943 collective_variables += var.colvars 

944 for force in system.getForces(): 

945 _add_fake_particles(force, num_particles) 

946 for cv in collective_variables: 

947 _add_fake_particles(cv.force, num_particles) 

948 for driving_force in driving_forces: 

949 system.addForce(driving_force) 

950 super().__init__(system, *args, **kwargs) 

951 self.setParameter("Lx", box_length_x) 

952 self.variables = variables 

953 self.driving_forces = driving_forces 

954 if len(driving_forces) == 1: 

955 self.driving_force = driving_forces[0] # for backwards compatibility 

956 

957 def getState(self, **kwargs): 

958 """Returns a :class:`ExtendedSpaceState` object. 

959 

960 Keyword Args 

961 ------------ 

962 **kwargs 

963 See ``getState`` in :OpenMM:`Context`. 

964 """ 

965 return ExtendedSpaceState(self.variables, super().getState(**kwargs)) 

966 

967 def setPeriodicBoxVectors(self, a, b, c): 

968 """Set the vectors defining the axes of the periodic box. 

969 

970 .. warning:: 

971 Only orthorhombic boxes are allowed. 

972 

973 Parameters 

974 ---------- 

975 a : openmm.Vec3 

976 The vector defining the first edge of the periodic box. 

977 b : openmm.Vec3 

978 The vector defining the second edge of the periodic box. 

979 c : openmm.Vec3 

980 The vector defining the third edge of the periodic box. 

981 """ 

982 a = openmm.Vec3(*map(_standardized, a)) 

983 b = openmm.Vec3(*map(_standardized, b)) 

984 c = openmm.Vec3(*map(_standardized, c)) 

985 if not (a.y == a.z == b.x == b.z == c.x == c.y == 0.0): 

986 raise ValueError("Only orthorhombic boxes are allowed") 

987 scaling = a.x / self.getParameter("Lx") 

988 self.setParameter("Lx", a.x) 

989 super().setPeriodicBoxVectors(a, b, c) 

990 system = self.getSystem() 

991 ntotal = system.getNumParticles() 

992 nvars = len(self.variables) 

993 for i, v in enumerate(self.variables): 

994 system.setParticleMass(ntotal - nvars + i, v._particle_mass(a.x)) 

995 self.reinitialize(preserveState=True) 

996 if scaling != 1: 

997 # Keep the variables, their velocities, and their kinetic energies, all of 

998 # which depend on the x coordinates of the extra particles relative to Lx 

999 try: 

1000 state = openmm.Context.getState( 

1001 self, getPositions=True, getVelocities=True 

1002 ) 

1003 except openmm.OpenMMException: # positions not set yet 

1004 return 

1005 positions = state.getPositions(asNumpy=True)._value 

1006 velocities = state.getVelocities(asNumpy=True)._value 

1007 positions[ntotal - nvars :, 0] *= scaling 

1008 velocities[ntotal - nvars :, 0] *= scaling 

1009 openmm.Context.setPositions(self, positions) 

1010 openmm.Context.setVelocities(self, velocities) 

1011 

1012 def setPositions(self, positions, extended_positions=None): 

1013 """Sets the positions of all particles and extended-space variables in this 

1014 context. If the latter are not provided, then suitable values are automatically 

1015 determined from the particle positions. 

1016 

1017 Parameters 

1018 ---------- 

1019 positions : list of openmm.Vec3 or numpy.ndarray or unit.Quantity 

1020 The positions of physical particles. 

1021 

1022 Keyword Args 

1023 ------------ 

1024 extended_positions : list of float or unit.Quantity 

1025 The positions of extended-space particles. 

1026 """ 

1027 a, b, _ = self.getState().getPeriodicBoxVectors() 

1028 nvars = len(self.variables) 

1029 particle_positions = [openmm.Vec3(*xyz) for xyz in _standardized(positions)] 

1030 if extended_positions is None: 

1031 extra_positions = [ 

1032 openmm.Vec3(0, b.y * (i + 1) / (nvars + 2), 0) for i in range(nvars) 

1033 ] 

1034 minisystem = openmm.System() 

1035 expression = _get_energy_function(self.variables) 

1036 for i, v in enumerate(self.variables): 

1037 expression += f"; {v.id}={v._get_energy_function(index=i + 1)}" 

1038 force = openmm.CustomCompoundBondForce(nvars, expression) 

1039 force.addBond(range(nvars), []) 

1040 for name, value in _get_parameters(self.variables).items(): 

1041 force.addGlobalParameter(name, value) 

1042 force.addGlobalParameter("Lx", a.x) 

1043 for v in self.variables: 

1044 minisystem.addParticle(v._particle_mass(a.x)) 

1045 for cv in v.colvars: 

1046 value = cv.evaluate( 

1047 self.getSystem(), particle_positions + extra_positions 

1048 ) 

1049 force.addGlobalParameter(cv.id, value) 

1050 minisystem.addForce(force) 

1051 minicontext = openmm.Context( 

1052 minisystem, 

1053 openmm.CustomIntegrator(0), 

1054 openmm.Platform.getPlatformByName("Reference"), 

1055 ) 

1056 minicontext.setPositions(extra_positions) 

1057 openmm.LocalEnergyMinimizer.minimize( 

1058 minicontext, 1 * unit.kilojoules_per_mole / unit.nanometers, 0 

1059 ) 

1060 ministate = minicontext.getState(getPositions=True) 

1061 extra_positions = ministate.getPositions().value_in_unit(unit.nanometers) 

1062 else: 

1063 extra_positions = [ 

1064 openmm.Vec3(x, b.y * (i + 1) / (nvars + 2), 0) 

1065 for i, x in enumerate(extended_positions) 

1066 ] 

1067 super().setPositions(particle_positions + extra_positions) 

1068 

1069 def setVelocitiesToTemperature(self, temperature, randomSeed=None): 

1070 """Sets the velocities of all particles in the system to random values chosen 

1071 from a Maxwell-Boltzmann distribution at a given temperature. 

1072 

1073 The velocities of the physical particles have no center-of-mass component, 

1074 satisfy the system constraints, and are scaled so that the instantaneous 

1075 temperature equals the given one exactly. The number of degrees of freedom 

1076 is counted as in OpenMM's ``StateDataReporter``. Massless particles get zero 

1077 velocity. 

1078 

1079 .. warning :: 

1080 The extra particles of the extended-space variables move along the x axis 

1081 only. Their x velocities are drawn from a Maxwell-Boltzmann distribution 

1082 at each variable's own temperature, and their y and z velocities are set 

1083 to zero. 

1084 

1085 Parameters 

1086 ---------- 

1087 temperature : float or unit.Quantity 

1088 The temperature of the system. 

1089 

1090 Keyword Args 

1091 ------------ 

1092 randomSeed : int, default=None 

1093 A seed for the random number generator. 

1094 """ 

1095 temperature = _standardized(temperature) 

1096 kB = _standardized(unit.MOLAR_GAS_CONSTANT_R) 

1097 system = self.getSystem() 

1098 num_total = system.getNumParticles() 

1099 num_atoms = num_total - len(self.variables) 

1100 masses = np.array( 

1101 [system.getParticleMass(i) / unit.dalton for i in range(num_total)] 

1102 ) 

1103 temperatures = np.array( 

1104 [temperature] * num_atoms + [v.temperature for v in self.variables] 

1105 ) 

1106 massive = masses > 0 

1107 sigmas = np.zeros(num_total) 

1108 sigmas[massive] = np.sqrt(kB * temperatures[massive] / masses[massive]) 

1109 random = np.random.RandomState(randomSeed) 

1110 velocities = sigmas[:, None] * random.normal(0, 1, (num_total, 3)) 

1111 velocities[num_atoms:, 1:] = 0 

1112 

1113 atoms = np.arange(num_atoms)[massive[:num_atoms]] 

1114 atom_masses = masses[atoms, None] 

1115 velocities[atoms] -= np.sum(atom_masses * velocities[atoms], axis=0) / np.sum( 

1116 atom_masses 

1117 ) 

1118 super().setVelocities(velocities) 

1119 self.applyVelocityConstraints(self.getIntegrator().getConstraintTolerance()) 

1120 state = openmm.Context.getState(self, getVelocities=True) 

1121 velocities = state.getVelocities(asNumpy=True)._value 

1122 

1123 num_constraints = sum( 

1124 1 

1125 for k in range(system.getNumConstraints()) 

1126 if any(massive[i] for i in system.getConstraintParameters(k)[:2]) 

1127 ) 

1128 dof = 3 * atoms.size - num_constraints 

1129 if any(isinstance(f, openmm.CMMotionRemover) for f in system.getForces()): 

1130 dof -= 3 

1131 two_ke = np.sum(atom_masses * velocities[atoms] ** 2) 

1132 velocities[atoms] *= np.sqrt(dof * kB * temperature / two_ke) 

1133 super().setVelocities(velocities) 

1134 

1135 

1136class ExtendedSpaceSimulation(app.Simulation): 

1137 """A simulation involving extended phase-space variables. 

1138 

1139 Parameters 

1140 ---------- 

1141 variables : list of DynamicalVariable 

1142 The dynamical variables to be added to the system's phase space. 

1143 topology : openmm.app.Topology 

1144 A Topology describing the system to be simulated. 

1145 system : openmm.System 

1146 The :OpenMM:`System` object to be simulated. 

1147 integrator : openmm.Integrator 

1148 The OpenMM Integrator to use for simulating the system dynamics. 

1149 

1150 Keyword Args 

1151 ------------ 

1152 platform : openmm.Platform, default=None 

1153 If not None, the :OpenMM:`Platform` to use. 

1154 platformProperties : dict, default=None 

1155 If not None, a set of platform-specific properties to pass to the Context's 

1156 constructor. 

1157 """ 

1158 

1159 def __init__( 

1160 self, 

1161 variables, 

1162 topology, 

1163 system, 

1164 integrator, 

1165 platform=None, 

1166 platformProperties=None, 

1167 ): 

1168 self.variables = variables 

1169 self._periodic_tasks = [] 

1170 

1171 for force in system.getForces(): 

1172 cls = force.__class__.__name__ 

1173 if cls == "CMMotionRemover" or cls.endswith("Barostat"): 

1174 raise Exception( 

1175 "UFED: system cannot contain CMMotionRemover nor any Barostat" 

1176 ) 

1177 

1178 box_vectors = topology.getPeriodicBoxVectors() 

1179 if box_vectors is None: 

1180 raise Exception("UFED: system must be confined in a simulation box") 

1181 

1182 num_particles, num_atoms = system.getNumParticles(), topology.getNumAtoms() 

1183 if num_particles != num_atoms: 

1184 raise ValueError( 

1185 f"UFED: the system has {num_particles} particles, but the topology has" 

1186 f" {num_atoms} atoms. An extended-space simulation adds its extra" 

1187 " particles to the system, so a system cannot be used in more than one" 

1188 " of them. Create a new system for each simulation." 

1189 ) 

1190 

1191 self.topology = topology 

1192 self.system = system 

1193 self.integrator = integrator 

1194 self.reporters = [] 

1195 self._usesPBC = True 

1196 if platform is None: 

1197 self.context = ExtendedSpaceContext(variables, system, integrator) 

1198 elif platformProperties is None: 

1199 self.context = ExtendedSpaceContext(variables, system, integrator, platform) 

1200 else: 

1201 self.context = ExtendedSpaceContext( 

1202 variables, system, integrator, platform, platformProperties 

1203 ) 

1204 

1205 def add_periodic_task(self, task, force_group=0): 

1206 """Adds a task to be executed periodically along this simulation. 

1207 

1208 Parameters 

1209 ---------- 

1210 task : PeriodicTask 

1211 A :class:`~ufedmm.ufedmm.PeriodicTask` object. 

1212 """ 

1213 task.initialize(self) 

1214 self._periodic_tasks.append(task) 

1215 

1216 def step(self, steps): 

1217 """Executed a given number of simulation steps. 

1218 

1219 Parameters 

1220 ---------- 

1221 steps : int 

1222 The number of steps to be executed. 

1223 """ 

1224 if self._periodic_tasks: 

1225 for task in self._periodic_tasks: 

1226 task.update(self, steps) 

1227 self.reporters = self._periodic_tasks + self.reporters 

1228 try: 

1229 self._simulate(endStep=self.currentStep + steps) 

1230 finally: 

1231 # Also when interrupted, or the tasks would run twice from then on 

1232 self.reporters = self.reporters[len(self._periodic_tasks) :] 

1233 else: 

1234 self._simulate(endStep=self.currentStep + steps) 

1235 

1236 def saveCheckpoint(self, file): 

1237 if isinstance(file, str): 

1238 with open(file, "wb") as f: 

1239 self.saveCheckpoint(f) 

1240 else: 

1241 for task in self._periodic_tasks: 

1242 task.saveCheckpoint(file) 

1243 file.write(self.context.createCheckpoint()) 

1244 

1245 def loadCheckpoint(self, file): 

1246 if isinstance(file, str): 

1247 with open(file, "rb") as f: 

1248 self.loadCheckpoint(f) 

1249 else: 

1250 for task in self._periodic_tasks: 

1251 task.loadCheckpoint(file, self.context) 

1252 self.context.loadCheckpoint(file.read()) 

1253 

1254 def saveState(self, file): 

1255 """Saves the current state of the simulation to a file, like 

1256 ``saveState`` in OpenMM's ``Simulation``. 

1257 

1258 .. warning:: 

1259 A saved state does not include the state of periodic tasks, such as the 

1260 metadynamics bias. Use :meth:`saveCheckpoint` to save it too. 

1261 """ 

1262 if self._periodic_tasks: 

1263 warnings.warn( 

1264 "The saved state does not include the periodic tasks of this " 

1265 "simulation (such as a metadynamics bias). Use saveCheckpoint to " 

1266 "save them too.", 

1267 stacklevel=2, 

1268 ) 

1269 super().saveState(file) 

1270 

1271 

1272class UnifiedFreeEnergyDynamics: 

1273 """A Unified Free-Energy Dynamics (UFED) setup. 

1274 

1275 Parameters 

1276 ---------- 

1277 variables : list of DynamicalVariable 

1278 The variables. 

1279 temperature : float or unit.Quantity 

1280 The temperature. 

1281 

1282 Keyword Args 

1283 ------------ 

1284 height : float or unit.Quantity, default=None 

1285 The height. 

1286 frequency : int, default=None 

1287 The frequency. 

1288 bias_factor : float, default=None 

1289 Scales the height of the hills added to the metadynamics bias potential. If 

1290 it is `None`, then the hills will have a constant height over time. For a 

1291 bias factor to be applicable, all bias variables must be at the same 

1292 temperature T. The extended-space dynamical variables are sampled as if the 

1293 effective temperature were T*bias_factor. 

1294 grid_expansion : int, default=20 

1295 The grid expansion. 

1296 enforce_gridless : bool, default=False 

1297 If this is `True`, gridless metadynamics is enforced even for 1D to 3D 

1298 problems. 

1299 buffer_size : int, default=100 

1300 The buffer size. 

1301 

1302 Example 

1303 ------- 

1304 >>> import ufedmm 

1305 >>> from openmm import unit 

1306 >>> model = ufedmm.AlanineDipeptideModel(water='tip3p') 

1307 >>> mass = 50*unit.dalton*(unit.nanometer/unit.radians)**2 

1308 >>> Ks = 1000*unit.kilojoules_per_mole/unit.radians**2 

1309 >>> Ts = 1500*unit.kelvin 

1310 >>> limit = 180*unit.degrees 

1311 >>> s_phi = ufedmm.DynamicalVariable( 

1312 ... 's_phi', -limit, limit, mass, Ts, model.phi, Ks 

1313 ... ) 

1314 >>> s_psi = ufedmm.DynamicalVariable( 

1315 ... 's_psi', -limit, limit, mass, Ts, model.psi, Ks 

1316 ... ) 

1317 >>> ufedmm.UnifiedFreeEnergyDynamics([s_phi, s_psi], 300*unit.kelvin) 

1318 <variables=[s_phi, s_psi], temperature=300, height=None, frequency=None> 

1319 """ 

1320 

1321 def __init__( # noqa: PLR0913, PLR0917 

1322 self, 

1323 variables, 

1324 temperature, 

1325 height=None, 

1326 frequency=None, 

1327 bias_factor=None, 

1328 grid_expansion=20, 

1329 enforce_gridless=False, 

1330 buffer_size=100, 

1331 ): 

1332 self.variables = variables 

1333 self.temperature = _standardized(temperature) 

1334 self.height = _standardized(height) 

1335 self.frequency = frequency 

1336 self.bias_factor = bias_factor 

1337 self.grid_expansion = grid_expansion 

1338 self.enforce_gridless = enforce_gridless 

1339 self.buffer_size = buffer_size 

1340 

1341 dimensions = sum(v.sigma is not None for v in variables) 

1342 self._metadynamics = not ( 

1343 dimensions == 0 or height is None or frequency is None 

1344 ) 

1345 

1346 def __repr__(self): 

1347 properties = ( 

1348 f"temperature={self.temperature}, " 

1349 f"height={self.height}, " 

1350 f"frequency={self.frequency}" 

1351 ) 

1352 return f"<variables=[{', '.join(v.id for v in self.variables)}], {properties}>" 

1353 

1354 def __getstate__(self): 

1355 return { 

1356 "variables": self.variables, 

1357 "temperature": self.temperature, 

1358 "height": self.height, 

1359 "frequency": self.frequency, 

1360 "bias_factor": self.bias_factor, 

1361 "grid_expansion": self.grid_expansion, 

1362 "enforce_gridless": self.enforce_gridless, 

1363 "buffer_size": self.buffer_size, 

1364 } 

1365 

1366 def __setstate__(self, kw): 

1367 self.__init__(**kw) 

1368 

1369 def simulation( 

1370 self, topology, system, integrator, platform=None, platformProperties=None 

1371 ): 

1372 """Returns a ExtendedSpaceSimulation object. 

1373 

1374 .. warning:: 

1375 If the temperature of any driving parameter is different from the 

1376 particle-system temperature, then the passed integrator must be a 

1377 :OpenMM:`CustomIntegrator` object containing a per-dof variable `kT` whose 

1378 content is the Boltzmann constant times the temperature associated to each 

1379 degree of freedom. This is true for all integrators available in 

1380 :mod:`ufedmm.integrators`, which are subclasses of 

1381 :class:`ufedmm.integrators.CustomIntegrator`. 

1382 

1383 Parameters 

1384 ---------- 

1385 topology : openmm.app.Topology 

1386 The topology. 

1387 system : openmm.System 

1388 The system. 

1389 integrator : 

1390 The integrator. 

1391 

1392 Keyword Args 

1393 ------------ 

1394 platform : openmm.Platform, default=None 

1395 The platform. 

1396 platformProperties : dict, default=None 

1397 The platform properties. 

1398 

1399 Example 

1400 ------- 

1401 >>> import ufedmm 

1402 >>> from openmm import unit 

1403 >>> model = ufedmm.AlanineDipeptideModel(water='tip3p') 

1404 >>> mass = 50*unit.dalton*(unit.nanometer/unit.radians)**2 

1405 >>> Ks = 1000*unit.kilojoules_per_mole/unit.radians**2 

1406 >>> Ts = 1500*unit.kelvin 

1407 >>> dt = 2*unit.femtoseconds 

1408 >>> gamma = 10/unit.picoseconds 

1409 >>> limit = 180*unit.degrees 

1410 >>> s_phi = ufedmm.DynamicalVariable( 

1411 ... 's_phi', -limit, limit, mass, Ts, model.phi, Ks 

1412 ... ) 

1413 >>> s_psi = ufedmm.DynamicalVariable( 

1414 ... 's_psi', -limit, limit, mass, Ts, model.psi, Ks 

1415 ... ) 

1416 >>> ufed = ufedmm.UnifiedFreeEnergyDynamics([s_phi, s_psi], 300*unit.kelvin) 

1417 >>> integrator = ufedmm.GeodesicLangevinIntegrator( 

1418 ... 300*unit.kelvin, gamma, dt 

1419 ... ) 

1420 >>> simulation = ufed.simulation(model.topology, model.system, integrator) 

1421 """ 

1422 simulation = ExtendedSpaceSimulation( 

1423 self.variables, 

1424 topology, 

1425 system, 

1426 integrator, 

1427 platform, 

1428 platformProperties, 

1429 ) 

1430 

1431 if self._metadynamics: 

1432 simulation.add_periodic_task( 

1433 _Metadynamics( 

1434 self.variables, 

1435 self.height, 

1436 self.frequency, 

1437 bias_factor=self.bias_factor, 

1438 buffer_size=self.buffer_size, 

1439 grid_expansion=self.grid_expansion, 

1440 enforce_gridless=self.enforce_gridless, 

1441 ), 

1442 ) 

1443 

1444 # UFEDMM integrators need the variable temperatures even if they are all equal 

1445 # to the system temperature, so that the extra particles move along x only 

1446 ufedmm_integrator = isinstance(integrator, ufedmm.integrators.CustomIntegrator) 

1447 if ufedmm_integrator or any( 

1448 v.temperature != self.temperature for v in self.variables 

1449 ): 

1450 ntotal = system.getNumParticles() 

1451 nvars = len(self.variables) 

1452 simulation.context.setPositions( 

1453 [openmm.Vec3(0, 0, 0)] * (ntotal - nvars), [0] * nvars 

1454 ) 

1455 vartemps = [v.temperature for v in self.variables] 

1456 if ufedmm_integrator: 

1457 integrator.update_temperatures(self.temperature, vartemps) 

1458 else: 

1459 temperatures = [self.temperature] * (ntotal - len(vartemps)) + vartemps 

1460 kT = [ 

1461 unit.MOLAR_GAS_CONSTANT_R * T * openmm.Vec3(1, 1, 1) 

1462 for T in temperatures 

1463 ] 

1464 integrator.setPerDofVariableByName("kT", kT) 

1465 

1466 return simulation