Coverage for cvpack/meta_collective_variable.py: 99%

77 statements  

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

1""" 

2.. class:: MetaCollectiveVariable 

3 :platform: Linux, MacOS, Windows 

4 :synopsis: A function of other collective variables 

5 

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

7 

8""" 

9 

10from __future__ import annotations 

11 

12import typing as t 

13from copy import copy 

14 

15import openmm 

16from openmm import unit as mmunit 

17 

18from .collective_variable import CollectiveVariable 

19from .units import Quantity, ScalarQuantity, VectorQuantity, in_md_units 

20from .utils import ( 

21 compute_effective_mass, 

22 get_platform_and_properties, 

23 get_single_force_state, 

24) 

25 

26 

27class MetaCollectiveVariable(CollectiveVariable, openmm.CustomCVForce): 

28 r""" 

29 A collective variable that is a function of other collective variables: 

30 

31 .. math:: 

32 

33 f({\bf r}) = F\left(c_1({\bf r}), c_2({\bf r}), \ldots, c_n({\bf r})\right) 

34 

35 where :math:`F(c_1,c_2,\ldots,c_n)` is a user-defined function and 

36 :math:`c_i({\bf r})` is the value of the :math:`i`-th collective variable at a 

37 given configuration :math:`{\bf r}`. 

38 

39 The function :math:`F` is defined as a string and can be any expression supported 

40 by the :OpenMM:`CustomCVForce` class. If the expression contains named parameters, 

41 the value of each parameter can be passed in one of two ways: 

42 

43 #. By a semicolon-separated definition in the function string, such as described 

44 in the :OpenMM:`CustomCVForce` documentation. In this case, the parameter value 

45 is fixed. 

46 

47 #. By a scalar passed as a keyword argument to the 

48 :class:`MetaCollectiveVariable` constructor. In this case, the parameter will 

49 become available for on-the-fly modification during a simulation via the 

50 ``setParameter`` method of an :OpenMM:`Context` object. **Warning**: other 

51 collective variables or :OpenMM:`Force` objects in the same system will share 

52 the same values of equal-named parameters. 

53 

54 Parameters 

55 ---------- 

56 function 

57 The function to be evaluated. It must be a valid :OpenMM:`CustomCVForce` 

58 expression. 

59 variables 

60 A sequence of :class:`CollectiveVariable` instances that represent the 

61 collective variables on which the meta-collective variable depends. The name 

62 of each collective variable must be unique and match a symbol used in the 

63 function. 

64 unit 

65 The unit of measurement of the collective variable. It must be compatible 

66 with the MD unit system (mass in `daltons`, distance in `nanometers`, time 

67 in `picoseconds`, temperature in `kelvin`, energy in `kilojoules_per_mol`, 

68 angle in `radians`). If the collective variable does not have a unit, use 

69 `unit.dimensionless`. 

70 periodicBounds 

71 The periodic bounds of the collective variable if it is periodic, or `None` if 

72 it is not periodic. 

73 

74 Keyword Args 

75 ------------ 

76 **parameters 

77 The named parameters of the function, if any. They will become settable context 

78 parameters when this meta-collective variable is added to an :OpenMM:`System`. 

79 The passed objects must be scalar quantities. Their values will be converted to 

80 OpenMM's MD unit system to serve as default values for the context parameters. 

81 

82 Example 

83 ------- 

84 >>> import cvpack 

85 >>> import math 

86 >>> import openmm 

87 >>> from openmm import unit 

88 >>> from openmmtools import testsystems 

89 >>> model = testsystems.AlanineDipeptideVacuum() 

90 >>> phi = cvpack.Torsion(4, 6, 8, 14, name="phi") 

91 >>> driving_force = cvpack.MetaCollectiveVariable( 

92 ... f"0.5*kappa*min(delta,{2*math.pi}-delta)^2" 

93 ... "; delta=abs(phi-phi0)", 

94 ... [phi], 

95 ... unit.kilojoules_per_mole, 

96 ... kappa = 1e3 * unit.kilojoules_per_mole/unit.radian**2, 

97 ... phi0 = 120 * unit.degrees 

98 ... ) 

99 >>> driving_force.addToSystem(model.system) 

100 >>> integrator = openmm.VerletIntegrator(0) 

101 >>> platform = openmm.Platform.getPlatformByName('Reference') 

102 >>> context = openmm.Context(model.system, integrator, platform) 

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

104 >>> driving_force.getParameterDefaultValues() 

105 {'kappa': 1000.0 kJ/(mol rad**2), 'phi0': 2.094... rad} 

106 >>> driving_force.getParameterValues(context) 

107 {'kappa': 1000.0 kJ/(mol rad**2), 'phi0': 2.094... rad} 

108 >>> driving_force.getValue(context) 

109 548.3... kJ/mol 

110 >>> driving_force.getInnerValues(context) 

111 {'phi': -3.14... rad} 

112 >>> driving_force.getInnerEffectiveMasses(context) 

113 {'phi': 0.04795... nm**2 Da/(rad**2)} 

114 >>> driving_force.getParameterDerivatives(context) 

115 {'kappa': 0.548... rad**2, 'phi0': -1047.20... kJ/(mol rad)} 

116 """ 

117 

118 def __init__( 

119 self, 

120 function: str, 

121 variables: t.Iterable[CollectiveVariable], 

122 unit: mmunit.Unit, 

123 periodicBounds: VectorQuantity | None = None, 

124 name: str = "meta_collective_variable", 

125 **parameters: ScalarQuantity, 

126 ) -> None: 

127 super().__init__(function) 

128 variables = list(variables) 

129 names = [cv.getName() for cv in variables] 

130 if len(set(names)) != len(names): 

131 raise ValueError(f"The names of the variables must be unique: {names}") 

132 self._cvs = tuple(map(copy, variables)) 

133 self._parameters = {k: in_md_units(v) for k, v in parameters.items()} 

134 for cv in self._cvs: 

135 self.addCollectiveVariable(cv.getName(), cv) 

136 for parameter, value in self._parameters.items(): 

137 self.addGlobalParameter(parameter, value / value.unit) 

138 self.addEnergyParameterDerivative(parameter) 

139 self._registerCV( 

140 name, 

141 unit, 

142 function=function, 

143 variables=variables, 

144 unit=unit, 

145 periodicBounds=periodicBounds, 

146 **self._parameters, 

147 ) 

148 if periodicBounds is not None: 

149 self._registerPeriodicBounds(*periodicBounds) 

150 

151 def getInnerVariables(self) -> tuple[CollectiveVariable]: 

152 """ 

153 Get the collective variables on which the meta-collective variable depends. 

154 

155 Returns 

156 ------- 

157 Tuple[CollectiveVariable] 

158 A tuple with the collective variables. 

159 """ 

160 return self._cvs 

161 

162 def getInnerValues(self, context: openmm.Context) -> dict[str, Quantity]: 

163 """ 

164 Get the values of the collective variables on which the meta-collective variable 

165 depends. The values are returned as a dictionary with the names of the 

166 collective variables as keys. 

167 

168 Parameters 

169 ---------- 

170 context 

171 The context in which the collective variables will be evaluated. 

172 

173 Returns 

174 ------- 

175 Dict[str, Quantity] 

176 A dictionary with the names of the collective variables as keys and their 

177 values as values. 

178 """ 

179 values = self.getCollectiveVariableValues(context) 

180 return { 

181 cv.getName(): Quantity(value, cv.getUnit()) 

182 for cv, value in zip(self._cvs, values) 

183 } 

184 

185 def getInnerEffectiveMasses( 

186 self, context: openmm.Context, names: t.Iterable[str] | None = None 

187 ) -> dict[str, Quantity]: 

188 """ 

189 Get the effective masses of the collective variables on which the 

190 meta-collective variable depends. The effective masses are calculated from the 

191 forces acting on the particles that represent the collective variables. 

192 

193 Parameters 

194 ---------- 

195 context 

196 The context in which the collective variables will be evaluated. 

197 names 

198 The names of the collective variables whose effective masses will be 

199 computed. If ``None``, the effective masses of all collective variables 

200 are computed. 

201 

202 Returns 

203 ------- 

204 Dict[str, Quantity] 

205 A dictionary with the names of the collective variables as keys and their 

206 effective masses as values. 

207 

208 Raises 

209 ------ 

210 ValueError 

211 If any of the names is not the name of an inner collective variable. 

212 """ 

213 all_names = [cv.getName() for cv in self._cvs] 

214 names = all_names if names is None else list(names) 

215 unknown = set(names) - set(all_names) 

216 if unknown: 

217 raise ValueError(f"Unknown collective variables: {sorted(unknown)}") 

218 self.getCollectiveVariableValues(context) # update the inner context positions 

219 inner_context = self.getInnerContext(context) 

220 forces = inner_context.getSystem().getForces() 

221 system = context.getSystem() 

222 if any(map(system.isVirtualSite, range(system.getNumParticles()))): 

223 # The inner context has no virtual sites, so the forces on them would not 

224 # be distributed to the atoms that define them 

225 inner_context = self._getContextWithVirtualSites(forces, context) 

226 forces = inner_context.getSystem().getForces() 

227 return { 

228 cv.getName(): Quantity( 

229 compute_effective_mass(force, inner_context), cv.getMassUnit() 

230 ) 

231 for cv, force in zip(self._cvs, forces) 

232 if cv.getName() in names 

233 } 

234 

235 def _getContextWithVirtualSites( 

236 self, forces: t.Sequence[openmm.Force], context: openmm.Context 

237 ) -> openmm.Context: 

238 # Built once per outer context, then updated with its current state 

239 cached = getattr(self, "_virtual_site_context", None) 

240 if cached is None or cached[0] is not context: 

241 cached = (context, self._createContextWithVirtualSites(forces, context)) 

242 self._virtual_site_context = cached 

243 new_context = cached[1] 

244 state = context.getState(getPositions=True, getParameters=True) 

245 new_context.setPeriodicBoxVectors(*state.getPeriodicBoxVectors()) 

246 new_context.setPositions(state.getPositions()) 

247 parameters = state.getParameters() 

248 for name in new_context.getParameters(): 

249 if name in parameters: 

250 new_context.setParameter(name, parameters[name]) 

251 return new_context 

252 

253 @staticmethod 

254 def _createContextWithVirtualSites( 

255 forces: t.Sequence[openmm.Force], context: openmm.Context 

256 ) -> openmm.Context: 

257 system = openmm.XmlSerializer.deserialize( 

258 openmm.XmlSerializer.serialize(context.getSystem()) 

259 ) 

260 while system.getNumForces() > 0: 

261 system.removeForce(0) 

262 for group, force in enumerate(forces): 

263 force_copy = openmm.XmlSerializer.deserialize( 

264 openmm.XmlSerializer.serialize(force) 

265 ) 

266 force_copy.setForceGroup(group) 

267 system.addForce(force_copy) 

268 return openmm.Context( 

269 system, openmm.VerletIntegrator(1.0), *get_platform_and_properties(context) 

270 ) 

271 

272 def getParameterDefaultValues(self) -> dict[str, Quantity]: 

273 """ 

274 Get the default values of the named parameters of this meta-collective variable. 

275 

276 Returns 

277 ------- 

278 Dict[str, Quantity] 

279 A dictionary with the names of the named parameters as keys and their 

280 default values as values. 

281 """ 

282 return self._parameters.copy() 

283 

284 def getParameterValues(self, context: openmm.Context) -> dict[str, Quantity]: 

285 """ 

286 Get the values of the named parameters of this meta-collective variable. The 

287 values are returned as a dictionary with the names of the parameters as keys. 

288 

289 Parameters 

290 ---------- 

291 context 

292 The context in which the named parameters will be evaluated. 

293 

294 Returns 

295 ------- 

296 Dict[str, Quantity] 

297 A dictionary with the names of the named parameters as keys and their values 

298 as values. 

299 """ 

300 return { 

301 name: Quantity(context.getParameter(name), parameter.unit) 

302 for name, parameter in self._parameters.items() 

303 } 

304 

305 def getParameterDerivatives( 

306 self, 

307 context: openmm.Context, 

308 allowReinitialization: bool = False, 

309 ) -> dict[str, Quantity]: 

310 """ 

311 Get the derivatives of the named parameters of this meta-collective variable. 

312 

313 Returns 

314 ------- 

315 Dict[str, Quantity] 

316 A dictionary with the names of the named parameters as keys and their 

317 derivatives as values. 

318 """ 

319 state = get_single_force_state( 

320 self, context, allowReinitialization, getParameterDerivatives=True 

321 ) 

322 derivatives = state.getEnergyParameterDerivatives() 

323 return { 

324 name: Quantity(derivatives[name], self._unit / parameter.unit) 

325 for name, parameter in self._parameters.items() 

326 } 

327 

328 

329MetaCollectiveVariable.registerTag("!cvpack.MetaCollectiveVariable")