Coverage for openxps/couplings/base.py: 98%

154 statements  

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

1""" 

2Base class for couplings. 

3 

4.. module:: openxps.couplings.base 

5 :platform: Linux, MacOS, Windows 

6 :synopsis: Base class for couplings between physical and extended phase-space systems 

7 

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

9 

10""" 

11 

12import typing as t 

13 

14import cvpack 

15import openmm as mm 

16from cvpack.serialization import Serializable 

17from openmm import XmlSerializer 

18from openmm import _openmm as mmswig 

19 

20from ..dynamical_variable import DynamicalVariable 

21 

22 

23class Coupling(Serializable): 

24 """Abstract base class for couplings between physical and extension systems. 

25 

26 A coupling connects the physical system's coordinates to the extension system's 

27 dynamical variables, enabling enhanced sampling simulations. 

28 

29 Subclasses must implement the :meth:`addToPhysicalSystem` and 

30 :meth:`addToExtensionSystem` methods. 

31 

32 Parameters 

33 ---------- 

34 forces 

35 A sequence of :OpenMM:`Force` objects. 

36 dynamical_variables 

37 A sequence of :class:`DynamicalVariable` objects. 

38 """ 

39 

40 def __init__( 

41 self, 

42 forces: t.Iterable[mm.Force], 

43 dynamical_variables: t.Sequence[DynamicalVariable], 

44 ) -> None: 

45 self._forces = list(forces) 

46 self._dynamical_variables = [dv.in_md_units() for dv in dynamical_variables] 

47 unique_names = {dv.name for dv in self._dynamical_variables} 

48 if len(unique_names) != len(self._dynamical_variables): 

49 raise ValueError("The dynamical variables must have unique names.") 

50 self._dv_indices = { 

51 dv.name: index for index, dv in enumerate(self._dynamical_variables) 

52 } 

53 self._flipped_force = None 

54 self._checkGlobalParameters() 

55 

56 def __add__(self, other: "Coupling") -> "CouplingSum": 

57 return CouplingSum([self, other]) 

58 

59 def __copy__(self) -> "Coupling": 

60 new = self.__class__.__new__(self.__class__) 

61 new.__setstate__(self.__getstate__()) 

62 return new 

63 

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

65 return { 

66 "forces": self._forces, 

67 "dynamical_variables": self._dynamical_variables, 

68 "dv_indices": self._dv_indices, 

69 } 

70 

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

72 self._forces = state["forces"] 

73 self._dynamical_variables = state["dynamical_variables"] 

74 self._dv_indices = state["dv_indices"] 

75 self._flipped_force = None 

76 

77 def _checkGlobalParameters(self) -> None: 

78 parameters = {} 

79 for force in self._forces: 

80 force_parameters = {} 

81 for index in range(force.getNumGlobalParameters()): 

82 name = force.getGlobalParameterName(index) 

83 force_parameters[name] = force.getGlobalParameterDefaultValue(index) 

84 for key, value in force_parameters.items(): 

85 if key in parameters and parameters[key] != value: 

86 raise ValueError( 

87 f"Parameter {key} has conflicting default values in " 

88 f"coupling: {parameters[key]} != {value}" 

89 ) 

90 parameters[key] = value 

91 

92 def _createFlippedForce(self, dv_indices: t.Mapping[str, int]) -> mm.Force | None: 

93 return None 

94 

95 @staticmethod 

96 def _addForceToSystem(force: mm.Force, system: mm.System) -> None: 

97 if isinstance(force, cvpack.CollectiveVariable): 

98 # A force left in the default group 0 gets a dedicated unused group, but 

99 # a group chosen by the user (e.g. for multiple time stepping) is kept. 

100 force.addToSystem(system, setUnusedForceGroup=force.getForceGroup() == 0) 

101 else: 

102 system.addForce(force) 

103 

104 def getForces(self) -> list[mm.Force]: 

105 """Get the list of OpenMM Force objects associated with this coupling. 

106 

107 Returns 

108 ------- 

109 list[openmm.Force] 

110 A list of Force objects contained within this coupling. 

111 """ 

112 return self._forces 

113 

114 def getDynamicalVariables(self) -> t.Sequence[DynamicalVariable]: 

115 """Get the dynamical variables associated with this coupling. 

116 

117 Returns 

118 ------- 

119 list[DynamicalVariable] 

120 The dynamical variables of this coupling, converted to MD units. 

121 """ 

122 return self._dynamical_variables 

123 

124 def getForce(self, index: int) -> mm.Force: 

125 """Retrieve a single OpenMM Force object from this coupling. 

126 

127 Parameters 

128 ---------- 

129 index 

130 The index of the Force object to retrieve. 

131 

132 Returns 

133 ------- 

134 openmm.Force 

135 The Force object at the specified index. 

136 

137 Raises 

138 ------ 

139 IndexError 

140 If the index is out of range. 

141 """ 

142 return self._forces[index] 

143 

144 def getDynamicalVariable(self, index: int) -> DynamicalVariable: 

145 """Retrieve a single dynamical variable from this coupling. 

146 

147 Parameters 

148 ---------- 

149 index 

150 The index of the DynamicalVariable object to retrieve. 

151 

152 Returns 

153 ------- 

154 DynamicalVariable 

155 The DynamicalVariable object at the specified index. 

156 

157 Raises 

158 ------ 

159 IndexError 

160 If the index is out of range. 

161 """ 

162 return self._dynamical_variables[index] 

163 

164 def getProtectedParameters(self) -> set[str]: 

165 """Get parameters of the physical context that should not be manually modified. 

166 

167 Returns 

168 ------- 

169 set[str] 

170 The protected parameters. 

171 """ 

172 if self._flipped_force is None: 

173 raise ValueError("This coupling has not been added to an extension system.") 

174 return { 

175 self._flipped_force.getCollectiveVariableName(index) 

176 for index in range(self._flipped_force.getNumCollectiveVariables()) 

177 } 

178 

179 def addToPhysicalSystem(self, system: mm.System) -> None: 

180 """Add this coupling to an OpenMM system. 

181 

182 Parameters 

183 ---------- 

184 system 

185 The system to which the coupling should be added. 

186 """ 

187 for force in self._forces: 

188 self._addForceToSystem(force, system) 

189 

190 def addToExtensionSystem( 

191 self, system: mm.System, dv_indices: t.Mapping[str, int] | None = None 

192 ) -> None: 

193 """ 

194 Add the flipped version of this coupling to the extension system. 

195 

196 The flipped force replaces dynamical variable parameters with collective 

197 variables that represent the dynamical variables as particles. Physical 

198 collective variables become parameters set to zero. 

199 

200 Parameters 

201 ---------- 

202 system 

203 The extension system to which the flipped coupling should be added. 

204 dv_indices 

205 A mapping from dynamical variable names to extension particle indices. 

206 If ``None``, the dynamical variables of this coupling are assumed to be 

207 the only ones in the system, in their own order. 

208 

209 Examples 

210 -------- 

211 >>> import cvpack 

212 >>> import openxps as xps 

213 >>> from openmm import unit 

214 >>> from math import pi 

215 >>> import openmm as mm 

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

217 >>> phi0 = xps.DynamicalVariable( 

218 ... "phi0", 

219 ... unit.radian, 

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

221 ... xps.CircularBounds() 

222 ... ) 

223 >>> coupling = xps.CollectiveVariableCoupling( 

224 ... f"0.5*kappa*min(delta,{2*pi}-delta)^2; delta=abs(phi-phi0)", 

225 ... [phi], 

226 ... [phi0], 

227 ... kappa=1000 * unit.kilojoules_per_mole / unit.radian**2, 

228 ... ) 

229 >>> extension_system = mm.System() 

230 >>> extension_system.addParticle(phi0.mass / phi0.mass.unit) 

231 0 

232 >>> coupling.addToExtensionSystem(extension_system) 

233 >>> extension_system.getNumForces() 

234 1 

235 """ 

236 if dv_indices is None: 

237 dv_indices = self._dv_indices 

238 else: 

239 dv_indices = {name: dv_indices[name] for name in self._dv_indices} 

240 self._flipped_force = self._createFlippedForce(dv_indices) 

241 self._addForceToSystem(self._flipped_force, system) 

242 

243 def updatePhysicalContext( 

244 self, 

245 physical_context: mm.Context, 

246 extension_context: mm.Context, 

247 ) -> None: 

248 """Update the physical context with the current extension parameters. 

249 

250 Parameters 

251 ---------- 

252 physical_context 

253 The physical context to update with the extension parameters. 

254 extension_context 

255 The extension context to get the extension parameters from. 

256 

257 """ 

258 collective_variables = mmswig.CustomCVForce_getCollectiveVariableValues( 

259 self._flipped_force, extension_context 

260 ) 

261 for index, value in enumerate(collective_variables): 

262 mmswig.Context_setParameter( 

263 physical_context, 

264 self._flipped_force.getCollectiveVariableName(index), 

265 value, 

266 ) 

267 

268 def updateExtensionContext( 

269 self, 

270 physical_context: mm.Context, 

271 extension_context: mm.Context, 

272 ) -> None: 

273 """Update the extension context with the current physical parameters. 

274 

275 Parameters 

276 ---------- 

277 physical_context 

278 The physical context to get the physical parameters from. 

279 extension_context 

280 The extension context to update with the physical parameters. 

281 

282 """ 

283 raise NotImplementedError("Subclasses must implement this method.") 

284 

285 def getCollectiveVariableValues( 

286 self, physical_context: mm.Context 

287 ) -> dict[str, float]: 

288 """Get the values of the collective variables. 

289 

290 Parameters 

291 ---------- 

292 physical_context 

293 The physical context to get the collective variable values from. 

294 """ 

295 collective_variables = {} 

296 for force in self._forces: 

297 if isinstance(force, mm.CustomCVForce): 

298 cv_values = force.getCollectiveVariableValues(physical_context) 

299 for index, value in enumerate(cv_values): 

300 collective_variables[ 

301 mmswig.CustomCVForce_getCollectiveVariableName(force, index) 

302 ] = value 

303 return collective_variables 

304 

305 

306class CouplingSum(Coupling): 

307 """A sum of couplings. 

308 

309 The dynamical variables of the sum are ordered by first appearance in the 

310 summed couplings, and this is the order in which an 

311 :class:`ExtendedSpaceContext` expects and reports their values and velocities. 

312 

313 Parameters 

314 ---------- 

315 couplings 

316 The couplings to be added. 

317 

318 Examples 

319 -------- 

320 >>> from copy import copy 

321 >>> import cvpack 

322 >>> import openxps as xps 

323 >>> from openmm import unit 

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

325 >>> psi = cvpack.Torsion(4, 6, 8, 14, name="psi") 

326 >>> dv_mass = 3 * unit.dalton * (unit.nanometer / unit.radian)**2 

327 >>> phi_s = xps.DynamicalVariable( 

328 ... "phi_s", unit.radian, dv_mass, xps.CircularBounds() 

329 ... ) 

330 >>> psi_s = xps.DynamicalVariable( 

331 ... "psi_s", unit.radian, dv_mass, xps.CircularBounds() 

332 ... ) 

333 >>> coupling = xps.HarmonicCoupling( 

334 ... phi, phi_s, 1000 * unit.kilojoule_per_mole / unit.radian**2 

335 ... ) + xps.HarmonicCoupling( 

336 ... psi, psi_s, 500 * unit.kilojoule_per_mole / unit.radian**2 

337 ... ) 

338 """ 

339 

340 def __init__(self, couplings: t.Iterable[Coupling]) -> None: 

341 flattened = [] 

342 for coupling in couplings: 

343 if isinstance(coupling, CouplingSum): 

344 flattened.extend(coupling._flattened) 

345 else: 

346 flattened.append(coupling) 

347 dv_dict = {} 

348 for coupling in flattened: 

349 for dv in coupling.getDynamicalVariables(): 

350 if dv_dict.setdefault(dv.name, dv) != dv: 

351 raise ValueError( 

352 f'The dynamical variable "{dv.name}" has ' 

353 "conflicting definitions in the couplings." 

354 ) 

355 self._flattened = flattened 

356 self._couplings = self._mergeInnerProductCouplings(flattened) 

357 forces = [force for c in self._couplings for force in c.getForces()] 

358 super().__init__(forces, list(dv_dict.values())) 

359 self._checkCollectiveVariables() 

360 

361 @staticmethod 

362 def _mergeInnerProductCouplings(couplings: list[Coupling]) -> list[Coupling]: 

363 """Replace all inner product couplings with a single merged one. 

364 

365 Inner product couplings handled separately would each declare and update 

366 the same parameter derivatives in the extension context, so that only the 

367 last update would survive. 

368 """ 

369 from .inner_product_coupling import InnerProductCoupling # noqa: PLC0415 

370 

371 inner = [c for c in couplings if isinstance(c, InnerProductCoupling)] 

372 if len(inner) <= 1: 

373 return list(couplings) 

374 merged = InnerProductCoupling.merge(inner) 

375 result = [] 

376 for coupling in couplings: 

377 if coupling is inner[0]: 

378 result.append(merged) 

379 elif not isinstance(coupling, InnerProductCoupling): 

380 result.append(coupling) 

381 return result 

382 

383 def __repr__(self) -> str: 

384 return "+".join(f"({repr(coupling)})" for coupling in self._couplings) 

385 

386 def __copy__(self) -> "CouplingSum": 

387 new = CouplingSum.__new__(CouplingSum) 

388 new.__setstate__(self.__getstate__()) 

389 return new 

390 

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

392 # The couplings before merging, so that a rebuilt sum keeps the order of 

393 # its dynamical variables 

394 return {"couplings": self._flattened} 

395 

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

397 self.__init__(state["couplings"]) 

398 

399 def _checkCollectiveVariables(self) -> None: 

400 cvs = {} 

401 for coupling in self._couplings: 

402 for force in coupling.getForces(): 

403 if isinstance(force, mm.CustomCVForce): 

404 for index in range(force.getNumCollectiveVariables()): 

405 name = force.getCollectiveVariableName(index) 

406 xml_string = XmlSerializer.serialize( 

407 force.getCollectiveVariable(index) 

408 ) 

409 if name in cvs and cvs[name] != xml_string: 

410 raise ValueError( 

411 f'The collective variable "{name}" has conflicting ' 

412 "definitions in the couplings." 

413 ) 

414 cvs[name] = xml_string 

415 

416 def getCouplings(self) -> t.Sequence[Coupling]: 

417 """Get the couplings included in the summed coupling.""" 

418 return self._couplings 

419 

420 def getProtectedParameters(self) -> set[str]: 

421 return set.union( 

422 *[coupling.getProtectedParameters() for coupling in self._couplings] 

423 ) 

424 

425 def addToPhysicalSystem(self, system: mm.System) -> None: 

426 for coupling in self._couplings: 

427 coupling.addToPhysicalSystem(system) 

428 

429 def addToExtensionSystem( 

430 self, system: mm.System, dv_indices: t.Mapping[str, int] | None = None 

431 ) -> None: 

432 if dv_indices is None: 

433 dv_indices = self._dv_indices 

434 for coupling in self._couplings: 

435 coupling.addToExtensionSystem(system, dv_indices) 

436 

437 def updatePhysicalContext( 

438 self, 

439 physical_context: mm.Context, 

440 extension_context: mm.Context, 

441 ): 

442 for coupling in self._couplings: 

443 coupling.updatePhysicalContext(physical_context, extension_context) 

444 

445 def updateExtensionContext( 

446 self, 

447 physical_context: mm.Context, 

448 extension_context: mm.Context, 

449 ): 

450 for coupling in self._couplings: 

451 coupling.updateExtensionContext(physical_context, extension_context) 

452 

453 

454CouplingSum.registerTag("!openxps.CouplingSum")