Coverage for openxps/opes.py: 100%

65 statements  

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

1""" 

2.. module:: openxps.opes 

3 :platform: Linux, MacOS, Windows 

4 :synopsis: On-the-fly probability enhanced sampling of dynamical variables. 

5 

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

7 

8""" 

9 

10import typing as t 

11 

12import openmm as mm 

13import openmm_opes 

14from openmm import app as mmapp 

15 

16from .bounds import NoBounds, ReflectiveBounds 

17from .context import ExtendedSpaceContext 

18from .metadynamics import ExtendedSpaceBiasVariable 

19from .system import ExtendedSpaceSystem 

20from .utils import ExtensionSimulation 

21 

22 

23def _biasVariables( 

24 system: ExtendedSpaceSystem, 

25 variables: t.Sequence[ExtendedSpaceBiasVariable], 

26 kwargs: t.Mapping[str, t.Any] | None = None, 

27) -> tuple[list[mmapp.BiasVariable], bool]: 

28 """Bias variables on the extension particles, and whether any is reflective. 

29 

30 Mirrors :class:`ExtendedSpaceMetadynamics`: each dynamical variable, in MD 

31 units, must belong to the system and have bounds, since the bias lives on a 

32 finite grid. ``bounded`` is True if any variable has reflective bounds; with 

33 unbounded variables rejected, the non-periodic variables are exactly the 

34 reflective ones. It must not be given in ``kwargs``, the keyword arguments a 

35 sampler forwards to openmm-opes. 

36 """ 

37 if kwargs and "bounded" in kwargs: 

38 raise TypeError( 

39 "bounded is set from the bounds of the dynamical variables; do not pass it" 

40 ) 

41 system_dvs = system.getDynamicalVariables() 

42 bias_variables = [] 

43 bounded = False 

44 for variable in variables: 

45 dv = variable.dynamical_variable.in_md_units() 

46 if dv not in system_dvs: 

47 raise ValueError(f"Dynamical variable {dv.name} not found in system") 

48 if isinstance(dv.bounds, NoBounds): 

49 raise ValueError( 

50 f"Dynamical variable {dv.name} has no bounds, but OPES needs a " 

51 "finite grid. Use ReflectiveBounds over the range the variable may " 

52 "explore." 

53 ) 

54 bounded = bounded or isinstance(dv.bounds, ReflectiveBounds) 

55 index = system_dvs.index(dv) 

56 bias_variables.append( 

57 mmapp.BiasVariable( 

58 dv.createCollectiveVariable(index), 

59 dv.bounds.lower * dv.bounds.unit, 

60 dv.bounds.upper * dv.bounds.unit, 

61 variable.sigma, 

62 dv.isPeriodic(), 

63 variable.grid_width, 

64 ) 

65 ) 

66 return bias_variables, bounded 

67 

68 

69def _extensionSimulation(simulation): 

70 """A view of ``simulation`` whose context is the extension context. 

71 

72 openmm-opes calls back into the sampler with the object it was given, so an 

73 already converted simulation is returned unchanged. 

74 """ 

75 if isinstance(simulation, ExtensionSimulation): 

76 return simulation 

77 if not isinstance(getattr(simulation, "context", None), ExtendedSpaceContext): 

78 raise TypeError( 

79 "Expected an ExtendedSpaceSimulation, whose context holds the extension " 

80 f"system, not {type(simulation).__name__}" 

81 ) 

82 return ExtensionSimulation(simulation) 

83 

84 

85def _extensionContext(context: mm.Context) -> mm.Context: 

86 """The extension context of an :class:`ExtendedSpaceContext`, else ``context``.""" 

87 if isinstance(context, ExtendedSpaceContext): 

88 return context.getExtensionContext() 

89 return context 

90 

91 

92class ExtendedSpaceOPES(openmm_opes.OPES): 

93 """On-the-fly probability enhanced sampling (OPES) of dynamical variables. 

94 

95 A bias potential is applied to dynamical variables of an 

96 :class:`~openxps.ExtendedSpaceSystem` to enhance the sampling of the physical 

97 coordinates coupled to them. This is :OpenMMOPES:`OPES <opes>` acting on the 

98 extension system: OPES and OPES-explore (``exploreMode=True``), multiple walkers 

99 and all other options are those of openmm-opes, documented there. 

100 

101 Parameters 

102 ---------- 

103 system 

104 The :class:`~openxps.ExtendedSpaceSystem` to be simulated. The bias force 

105 is added to its extension system when this object is created, so it must 

106 be created before the :class:`~openxps.ExtendedSpaceSimulation` or 

107 :class:`~openxps.ExtendedSpaceContext` that uses the system. 

108 variables 

109 The dynamical variables to bias and their kernel widths, as 

110 :class:`~openxps.ExtendedSpaceBiasVariable` objects. Variables with 

111 :class:`~openxps.bounds.NoBounds` are rejected, since the bias is stored on 

112 a finite grid. Periodic and reflective variables cannot be mixed. 

113 **kwargs 

114 The remaining arguments of :OpenMMOPES:`OPES <opes>` (``temperature``, 

115 ``barrier``, ``frequency``, ``varianceFrequency``, ...), except ``bounded``, 

116 which follows from the variables' bounds. 

117 

118 .. note:: 

119 Kernels are those of openmm-opes: Gaussian by default and minimum-image on 

120 periodic variables, whereas :class:`~openxps.ExtendedSpaceMetadynamics` 

121 uses von Mises kernels. ``sigma`` keeps its openmm-opes meaning: with 

122 ``varianceFrequency=None``, the standard deviation of the unbiased 

123 distribution. 

124 

125 .. note:: 

126 ``extraBias`` entries are evaluated in the extension context, so they must 

127 be forces of the extension system, such as other samplers on it. 

128 

129 .. note:: 

130 To restart, save the sampler with ``getState()`` alongside the simulation's 

131 state, and after ``setState()`` on a new sampler call ``updateContext()`` on 

132 the new context (or take a step): until then, the context holds no bias and 

133 ``getBiasEnergy()`` returns minus the barrier. 

134 

135 Example 

136 ------- 

137 >>> import openxps as xps 

138 >>> from openmm import unit 

139 >>> import cvpack 

140 >>> import openmm 

141 >>> from openmmtools import testsystems 

142 >>> model = testsystems.AlanineDipeptideVacuum() 

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

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

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

146 >>> kappa = 1000 * unit.kilojoules_per_mole / unit.radian**2 

147 >>> system = xps.ExtendedSpaceSystem( 

148 ... model.system, xps.HarmonicCoupling(phi, phi0, kappa) 

149 ... ) 

150 >>> opes = xps.ExtendedSpaceOPES( 

151 ... system, 

152 ... [xps.ExtendedSpaceBiasVariable(phi0, 18 * unit.degrees)], 

153 ... temperature=300 * unit.kelvin, 

154 ... barrier=20 * unit.kilojoules_per_mole, 

155 ... frequency=100, 

156 ... varianceFrequency=None, 

157 ... ) 

158 >>> integrator = openmm.LangevinMiddleIntegrator( 

159 ... 300 * unit.kelvin, 1 / unit.picosecond, 2 * unit.femtosecond 

160 ... ) 

161 >>> integrator.setRandomNumberSeed(1234) 

162 >>> simulation = xps.ExtendedSpaceSimulation( 

163 ... model.topology, 

164 ... system, 

165 ... xps.LockstepIntegrator(integrator), 

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

167 ... ) 

168 >>> context = simulation.context 

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

170 >>> context.setVelocitiesToTemperature(300 * unit.kelvin, 1234) 

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

172 >>> context.setDynamicalVariableVelocitiesToTemperature(300 * unit.kelvin, 1234) 

173 >>> opes.step(simulation, 200) 

174 >>> opes.getNumKernels() # the second kernel merged into the first 

175 1 

176 """ 

177 

178 def __init__( 

179 self, 

180 system: ExtendedSpaceSystem, 

181 variables: t.Sequence[ExtendedSpaceBiasVariable], 

182 **kwargs, 

183 ) -> None: 

184 bias_variables, bounded = _biasVariables(system, variables, kwargs) 

185 super().__init__( 

186 system.getExtensionSystem(), bias_variables, bounded=bounded, **kwargs 

187 ) 

188 

189 def step(self, simulation, steps: int) -> None: 

190 """Advance an :class:`~openxps.ExtendedSpaceSimulation` by ``steps`` steps.""" 

191 super().step(_extensionSimulation(simulation), steps) 

192 

193 @staticmethod 

194 def stepTogether(simulation, samplers, steps: int) -> None: 

195 """Advance a simulation biased by several extended-space samplers at once. 

196 

197 See :OpenMMOPES:`OPES <opes>`. The samplers may be :class:`ExtendedSpaceOPES` or 

198 :class:`ExtendedSpaceCombinedOPES` objects acting on the same extension 

199 system. 

200 """ 

201 openmm_opes.OPES.stepTogether(_extensionSimulation(simulation), samplers, steps) 

202 

203 def getCollectiveVariables(self, simulation): 

204 """Current values of the biased dynamical variables, in MD units.""" 

205 return super().getCollectiveVariables(_extensionSimulation(simulation)) 

206 

207 def getBiasEnergy(self, context: mm.Context): 

208 """The bias energy applied in an :class:`~openxps.ExtendedSpaceContext`.""" 

209 return super().getBiasEnergy(_extensionContext(context)) 

210 

211 def updateContext(self, context: mm.Context) -> None: 

212 """Push the current bias into an :class:`~openxps.ExtendedSpaceContext`.""" 

213 super().updateContext(_extensionContext(context)) 

214 

215 

216class ExtendedSpaceCombinedOPES(openmm_opes.CombinedOPES): 

217 """OPES and OPES-explore combined (OPES_COM) on dynamical variables. 

218 

219 This is :OpenMMOPES:`CombinedOPES <combined-opes>` acting on the extension 

220 system of an :class:`~openxps.ExtendedSpaceSystem`: both components deposit 

221 kernels on the same dynamical variables, and the total bias is their sum. See 

222 :class:`ExtendedSpaceOPES` for how the variables are handled; the same notes 

223 on kernels and ``extraBias`` apply. 

224 

225 Parameters 

226 ---------- 

227 system 

228 The :class:`~openxps.ExtendedSpaceSystem` to be simulated. The bias force 

229 is added to its extension system when this object is created, so it must 

230 be created before the simulation or context that uses the system. 

231 variables 

232 The dynamical variables to bias and their kernel widths, as 

233 :class:`~openxps.ExtendedSpaceBiasVariable` objects. 

234 **kwargs 

235 The remaining arguments of :OpenMMOPES:`CombinedOPES <combined-opes>` 

236 (``temperature``, ``barrier``, ``exploreBarrier``, ``frequency``, 

237 ``varianceFrequency``, ...), except ``bounded``, which follows from the 

238 variables' bounds. 

239 

240 Example 

241 ------- 

242 >>> import openxps as xps 

243 >>> from openmm import unit 

244 >>> import cvpack 

245 >>> import openmm 

246 >>> from openmmtools import testsystems 

247 >>> model = testsystems.AlanineDipeptideVacuum() 

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

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

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

251 >>> kappa = 1000 * unit.kilojoules_per_mole / unit.radian**2 

252 >>> system = xps.ExtendedSpaceSystem( 

253 ... model.system, xps.HarmonicCoupling(phi, phi0, kappa) 

254 ... ) 

255 >>> opes = xps.ExtendedSpaceCombinedOPES( 

256 ... system, 

257 ... [xps.ExtendedSpaceBiasVariable(phi0, 18 * unit.degrees)], 

258 ... temperature=300 * unit.kelvin, 

259 ... barrier=20 * unit.kilojoules_per_mole, 

260 ... exploreBarrier=10 * unit.kilojoules_per_mole, 

261 ... frequency=100, 

262 ... varianceFrequency=None, 

263 ... ) 

264 >>> integrator = openmm.LangevinMiddleIntegrator( 

265 ... 300 * unit.kelvin, 1 / unit.picosecond, 2 * unit.femtosecond 

266 ... ) 

267 >>> integrator.setRandomNumberSeed(1234) 

268 >>> simulation = xps.ExtendedSpaceSimulation( 

269 ... model.topology, 

270 ... system, 

271 ... xps.LockstepIntegrator(integrator), 

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

273 ... ) 

274 >>> context = simulation.context 

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

276 >>> context.setVelocitiesToTemperature(300 * unit.kelvin, 1234) 

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

278 >>> context.setDynamicalVariableVelocitiesToTemperature(300 * unit.kelvin, 1234) 

279 >>> opes.step(simulation, 200) 

280 >>> opes.getNumKernels() # each component merged its second kernel 

281 (1, 1) 

282 """ 

283 

284 def __init__( 

285 self, 

286 system: ExtendedSpaceSystem, 

287 variables: t.Sequence[ExtendedSpaceBiasVariable], 

288 **kwargs, 

289 ) -> None: 

290 bias_variables, bounded = _biasVariables(system, variables, kwargs) 

291 super().__init__( 

292 system.getExtensionSystem(), bias_variables, bounded=bounded, **kwargs 

293 ) 

294 

295 def step(self, simulation, steps: int) -> None: 

296 """Advance an :class:`~openxps.ExtendedSpaceSimulation` by ``steps`` steps.""" 

297 super().step(_extensionSimulation(simulation), steps) 

298 

299 stepTogether = staticmethod(ExtendedSpaceOPES.stepTogether) 

300 

301 def getCollectiveVariables(self, simulation): 

302 """Current values of the biased dynamical variables, in MD units.""" 

303 return super().getCollectiveVariables(_extensionSimulation(simulation)) 

304 

305 def getBiasEnergy(self, context: mm.Context): 

306 """The total bias energy in an :class:`~openxps.ExtendedSpaceContext`.""" 

307 return super().getBiasEnergy(_extensionContext(context)) 

308 

309 def getComponentBiasEnergies(self, context: mm.Context): 

310 """The OPES and OPES-explore bias energies in an 

311 :class:`~openxps.ExtendedSpaceContext`.""" 

312 return super().getComponentBiasEnergies(_extensionContext(context)) 

313 

314 def updateContext(self, context: mm.Context) -> None: 

315 """Push the current biases into an :class:`~openxps.ExtendedSpaceContext`.""" 

316 super().updateContext(_extensionContext(context))