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

111 statements  

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

1""" 

2Inner product coupling. 

3 

4.. module:: openxps.couplings.inner_product_coupling 

5 :platform: Linux, MacOS, Windows 

6 :synopsis: The inner product of two separable vector-valued functions 

7 

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

9 

10""" 

11 

12import math 

13import typing as t 

14 

15import cvpack 

16import openmm as mm 

17from openmm import _openmm as mmswig 

18from openmm import unit as mmunit 

19 

20from openxps.utils import Function, preprocess_args 

21 

22from ..dynamical_variable import DynamicalVariable 

23from .base import Coupling 

24 

25 

26class InnerProductCoupling(Coupling): 

27 r"""Coupling defined by the inner product of two separable vector-valued functions. 

28 

29 Use this class if the coupling energy is the inner product of a vector-valued 

30 function :math:`{\boldsymbol \lambda}` of the extended dynamical variables 

31 :math:`{\bf s}` and a vector-valued function :math:`{\bf u}` of the physical 

32 coordinates :math:`{\bf r}`, i.e., 

33 

34 .. math:: 

35 

36 U = {\boldsymbol \lambda}({\bf s}) \cdot {\bf u}({\bf r}) 

37 = \sum_{i=1}^n \lambda_i({\bf s}) u_i({\bf r}) 

38 

39 where :math:`n` is the dimensionality of the vector-valued functions. 

40 

41 The extension system receives the parameter derivatives 

42 :math:`u_i = \partial U / \partial \lambda_i` evaluated in the physical context, 

43 so the forces on the dynamical variables follow the chain rule exactly. The 

44 extension potential energy equals the coupling energy only if :math:`U` is linear in 

45 each :math:`\lambda_i`, which is also required for multiple time-step schemes 

46 such as :class:`SplitIntegrator`, where the derivatives are held fixed during the 

47 extension substeps. 

48 

49 Functions receive the dynamical variables wrapped into their bounds, so periodic 

50 and reflective variables enter them with the same values reported by 

51 :meth:`ExtendedSpaceContext.getDynamicalVariableValues`. 

52 

53 Inner product couplings combined in a sum are merged into a single coupling, so 

54 forces from different couplings may share global parameters. Shared functions 

55 must have identical definitions. Forces outside the coupling must not depend on 

56 its parameters. 

57 

58 Parameters 

59 ---------- 

60 forces 

61 A sequence of :OpenMM:`Force` objects whose sum depends linearly on a vector of 

62 :math:`n` global context parameters. 

63 dynamical_variables 

64 The dynamical variables of the extended phase-space system. 

65 functions 

66 A dictionary defining global context parameters (keys) as mathematical functions 

67 (values) of the dynamical variables. It is not necessary to include identity 

68 functions (i.e., ``key=value``). 

69 **parameters 

70 Named parameters that appear in the mathematical expressions. 

71 

72 Examples 

73 -------- 

74 >>> from copy import copy 

75 >>> from collections import namedtuple 

76 >>> import cvpack 

77 >>> import openxps as xps 

78 >>> from openmm import unit 

79 >>> from math import pi 

80 >>> import openmm as mm 

81 >>> from openmmtools import testsystems 

82 >>> model = testsystems.AlanineDipeptideVacuum() 

83 

84 A function to remove Coulomb interactions: 

85 

86 >>> Parameters = namedtuple( 

87 ... "Parameters", 

88 ... ["index", "charge", "sigma", "epsilon"], 

89 ... ) 

90 >>> def remove_coulomb_interaction( 

91 ... force: mm.NonbondedForce, p1: Parameters, p2: Parameters 

92 ... ) -> None: 

93 ... force.addException( 

94 ... p1.index, 

95 ... p2.index, 

96 ... 0.0, 

97 ... (p1.sigma + p2.sigma)/2, 

98 ... (p1.epsilon * p2.epsilon).sqrt(), 

99 ... ) 

100 

101 Remove carbonyl oxygen <=> amide hydrogen interactions: 

102 

103 >>> nbforce = next( 

104 ... f for f in model.system.getForces() 

105 ... if isinstance(f, mm.NonbondedForce) 

106 ... ) 

107 >>> O1 = Parameters(5, *nbforce.getParticleParameters(5)) 

108 >>> H1 = Parameters(7, *nbforce.getParticleParameters(7)) 

109 >>> O2 = Parameters(15, *nbforce.getParticleParameters(15)) 

110 >>> H2 = Parameters(17, *nbforce.getParticleParameters(17)) 

111 >>> remove_coulomb_interaction(nbforce, O1, H2) 

112 >>> remove_coulomb_interaction(nbforce, O2, H1) 

113 

114 Add scaled Coulomb interactions: 

115 

116 >>> force = mm.CustomBondForce(f"scaling*chargeProd/r") 

117 >>> _ = force.addGlobalParameter("scaling", 1.0) 

118 >>> _ = force.addEnergyParameterDerivative("scaling") 

119 >>> _ = force.addPerBondParameter("chargeProd") 

120 >>> _ = force.addBond(O1.index, H2.index, [O1.charge*H2.charge]) 

121 >>> _ = force.addBond(O2.index, H1.index, [O2.charge*H1.charge]) 

122 

123 Create a coupling between the dynamical variable and the nonbonded force: 

124 

125 >>> lambda_dv = xps.DynamicalVariable( 

126 ... name="lambda", 

127 ... unit=unit.dimensionless, 

128 ... mass=1.0 * unit.dalton * unit.nanometer**2, 

129 ... bounds=xps.ReflectiveBounds(0.0, 1.0, unit.dimensionless), 

130 ... ) 

131 >>> coupling = xps.InnerProductCoupling( 

132 ... [force], 

133 ... [lambda_dv], 

134 ... functions={"scaling": "(1-cos(alpha*lambda))/2"}, 

135 ... alpha=pi*unit.radian, 

136 ... ) 

137 >>> context = xps.ExtendedSpaceContext( 

138 ... xps.ExtendedSpaceSystem(model.system, coupling), 

139 ... xps.LockstepIntegrator(mm.VerletIntegrator(1.0 * mmunit.femtosecond)), 

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

141 ... ) 

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

143 >>> context.setDynamicalVariableValues([1.0]) 

144 """ 

145 

146 @preprocess_args 

147 def __init__( 

148 self, 

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

150 dynamical_variables: t.Iterable[DynamicalVariable], 

151 functions: dict[str, str] | None = None, 

152 **parameters: mmunit.Quantity, 

153 ) -> None: 

154 forces = list(forces) 

155 for force in forces: 

156 if not all( 

157 hasattr(force, method) 

158 for method in ( 

159 "getNumGlobalParameters", 

160 "getEnergyParameterDerivativeName", 

161 ) 

162 ): 

163 raise TypeError( 

164 f"Force {force.getName()} ({type(force).__name__}) does not " 

165 "support global parameters with energy derivatives, which an " 

166 "InnerProductCoupling requires." 

167 ) 

168 forces = [ 

169 cvpack.OpenMMForceWrapper( 

170 force, 

171 mmunit.kilojoule_per_mole, 

172 name=force.getName(), 

173 ) 

174 if not isinstance(force, cvpack.CollectiveVariable) 

175 else force 

176 for force in forces 

177 ] 

178 self._functions = [ 

179 Function(name, expression, **parameters) 

180 for name, expression in (functions or {}).items() 

181 ] 

182 self._parameters = parameters 

183 self._force_groups = set() 

184 self._request_energy = False 

185 super().__init__(forces, dynamical_variables) 

186 self._dynamic_parameters = self._getDynamicParameters() 

187 

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

189 state = super().__getstate__() 

190 state["functions"] = self._functions 

191 state["parameters"] = self._parameters 

192 state["force_groups"] = self._force_groups 

193 return state 

194 

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

196 self._functions = state["functions"] 

197 self._parameters = state["parameters"] 

198 self._force_groups = state.get("force_groups", set()) 

199 self._request_energy = False 

200 super().__setstate__(state) 

201 self._dynamic_parameters = self._getDynamicParameters() 

202 

203 def _getDynamicParameters(self) -> set[str]: 

204 all_force_parameters = { 

205 force.getGlobalParameterName(index) 

206 for force in self._forces 

207 for index in range(force.getNumGlobalParameters()) 

208 } 

209 function_names = {fn.getName() for fn in self._functions} 

210 if self._functions: 

211 function_variables = set.union( 

212 *(fn.getVariables() for fn in self._functions), 

213 ) 

214 else: 

215 function_variables = set() 

216 

217 if missing := function_names - all_force_parameters: 

218 raise ValueError( 

219 "These functions are not global parameters in the provided forces: " 

220 + ", ".join(sorted(missing)) 

221 ) 

222 

223 all_dvs = {dv.name for dv in self._dynamical_variables} 

224 

225 for fn in self._functions: 

226 if unknown := fn.getVariables() - all_dvs: 

227 raise ValueError( 

228 f"Function {fn.getName()} depends on names that are neither " 

229 "dynamical variables nor given parameters: " 

230 + ", ".join(sorted(unknown)) 

231 ) 

232 

233 if functions_missing_dvs := [ 

234 fn.getName() for fn in self._functions if not (fn.getVariables() & all_dvs) 

235 ]: 

236 raise ValueError( 

237 "These functions do not depend on any dynamical variables: " 

238 + ", ".join(functions_missing_dvs) 

239 ) 

240 

241 dvs_in_force_parameters = all_dvs & all_force_parameters 

242 dvs_in_function_variables = all_dvs & function_variables 

243 

244 if same_names := function_names & all_dvs: 

245 raise ValueError( 

246 "These functions have the same names as dynamical variables: " 

247 + ", ".join(sorted(same_names)) 

248 ) 

249 if dvs_in_neither := all_dvs - ( 

250 dvs_in_function_variables | dvs_in_force_parameters 

251 ): 

252 raise ValueError( 

253 "These dynamical variables are neither function variables nor global " 

254 "context parameters: " + ", ".join(sorted(dvs_in_neither)) 

255 ) 

256 

257 dynamic_parameters = dvs_in_force_parameters | function_names 

258 for force in self._forces: 

259 force_parameters = { 

260 force.getGlobalParameterName(index) 

261 for index in range(force.getNumGlobalParameters()) 

262 } 

263 has_derivatives = { 

264 force.getEnergyParameterDerivativeName(index) 

265 for index in range(force.getNumEnergyParameterDerivatives()) 

266 } 

267 if missing := force_parameters & dynamic_parameters - has_derivatives: 

268 raise ValueError( 

269 "The following parameters require a derivative and are present in " 

270 f"force {force.getName()}, but no derivative was requested: " 

271 + ", ".join(sorted(missing)) 

272 ) 

273 return dynamic_parameters 

274 

275 @classmethod 

276 def merge( 

277 cls, couplings: t.Sequence["InnerProductCoupling"] 

278 ) -> "InnerProductCoupling": 

279 """Merge inner product couplings into a single one. 

280 

281 A sum of inner product couplings whose forces share global parameters must 

282 be handled as a single coupling, so that the parameter derivatives of all 

283 forces are accumulated before reaching the extension system. 

284 

285 Parameters 

286 ---------- 

287 couplings 

288 The inner product couplings to merge. 

289 

290 Returns 

291 ------- 

292 InnerProductCoupling 

293 A coupling with all forces, dynamical variables, functions and 

294 parameters of the merged couplings. 

295 

296 Raises 

297 ------ 

298 ValueError 

299 If two couplings define the same dynamical variable, function or 

300 parameter differently. 

301 """ 

302 forces, dvs, functions, parameters = [], {}, {}, {} 

303 for coupling in couplings: 

304 forces.extend(coupling.getForces()) 

305 for dv in coupling.getDynamicalVariables(): 

306 if dvs.setdefault(dv.name, dv) != dv: 

307 raise ValueError( 

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

309 "definitions in the couplings." 

310 ) 

311 for fn in coupling._functions: 

312 name, expression = fn.getName(), fn.getExpression() 

313 if functions.setdefault(name, expression) != expression: 

314 raise ValueError( 

315 f'The function "{name}" has conflicting definitions in the ' 

316 f"couplings: {functions[name]} != {expression}" 

317 ) 

318 for name, value in coupling._parameters.items(): 

319 if name in parameters and parameters[name] != value: 

320 raise ValueError( 

321 f'The parameter "{name}" has conflicting values in the ' 

322 f"couplings: {parameters[name]} != {value}" 

323 ) 

324 parameters[name] = value 

325 return cls(forces, list(dvs.values()), functions, **parameters) 

326 

327 @staticmethod 

328 def _derivativeName(parameter: str) -> str: 

329 return "derivative_with_respect_to_" + parameter 

330 

331 def _createFlippedForce(self, dv_indices: t.Mapping[str, int]) -> mm.CustomCVForce: 

332 flipped_force = mm.CustomCVForce( 

333 "+".join(f"{p}*{self._derivativeName(p)}" for p in self._dynamic_parameters) 

334 ) 

335 for parameter in self._dynamic_parameters: 

336 flipped_force.addGlobalParameter(self._derivativeName(parameter), 0.0) 

337 bounds = {dv.name: dv.bounds for dv in self._dynamical_variables} 

338 for fn in self._functions: 

339 flipped_force.addCollectiveVariable( 

340 fn.getName(), fn.createCollectiveVariable(dv_indices, bounds) 

341 ) 

342 for dv in self._dynamical_variables: 

343 if dv.name in self._dynamic_parameters: 

344 flipped_force.addCollectiveVariable( 

345 dv.name, dv.createCollectiveVariable(dv_indices[dv.name]) 

346 ) 

347 return flipped_force 

348 

349 def getForceGroups(self) -> set[int]: 

350 """ 

351 Get the force groups of the coupling forces, which are empty until the 

352 coupling is added to a physical system. 

353 """ 

354 return self._force_groups 

355 

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

357 super().addToPhysicalSystem(system) 

358 self._force_groups = {force.getForceGroup() for force in self._forces} 

359 

360 def updateExtensionContext( 

361 self, 

362 physical_context: mm.Context, 

363 extension_context: mm.Context, 

364 ) -> None: 

365 derivatives = self._getDerivatives(physical_context, self._request_energy) 

366 if not self._request_energy and any(map(math.isnan, derivatives.values())): 

367 # Some forces compute parameter derivatives only along with the energy and 

368 # return NaN otherwise, such as SlicedNonbondedForce from the 

369 # openmm-nonbonded-slicing plugin. Request the energy from now on. 

370 self._request_energy = True 

371 derivatives = self._getDerivatives(physical_context, True) 

372 for name, value in derivatives.items(): 

373 mmswig.Context_setParameter( 

374 extension_context, self._derivativeName(name), value 

375 ) 

376 

377 def _getDerivatives( 

378 self, physical_context: mm.Context, energy: bool 

379 ) -> dict[str, float]: 

380 groups = sum(1 << group for group in self._force_groups) or -1 

381 state = mm.Context.getState( 

382 physical_context, 

383 getEnergy=energy, 

384 getParameterDerivatives=True, 

385 groups=groups, 

386 ) 

387 return { 

388 name: value 

389 for name, value in state.getEnergyParameterDerivatives().items() 

390 if name in self._dynamic_parameters 

391 } 

392 

393 

394InnerProductCoupling.registerTag("!openxps.InnerProductCoupling")