Coverage for openxps/extension_writer.py: 100%

119 statements  

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

1""" 

2.. module:: openxps.extension_writer 

3 :platform: Linux, MacOS, Windows 

4 :synopsis: A custom writer for reporting state data from an extension context. 

5 

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

7 

8""" 

9 

10import cvpack 

11import numpy as np 

12import openmm as mm 

13from cvpack.reporting.custom_writer import CustomWriter 

14from openmm import _openmm as mmswig 

15from openmm import unit as mmunit 

16 

17from .integrators import RegulatedNHLIntegrator 

18from .simulation import ExtendedSpaceSimulation 

19 

20 

21class ExtensionWriter(CustomWriter): 

22 """ 

23 A custom writer for reporting state data from an extension context. 

24 

25 This writer can be used with :class:`cvpack.reporting.StateDataReporter` to 

26 report various properties of the extension context in an extended phase-space 

27 simulation. The extension context contains the dynamical variables and their 

28 associated properties. 

29 

30 Parameters 

31 ---------- 

32 kinetic : bool, optional, default=False 

33 If ``True``, the kinetic energy of the dynamical variables will be reported 

34 in units of kJ/mol. If the extension integrator is a 

35 :class:`RegulatedNHLIntegrator`, its regulated kinetic energy is reported 

36 instead, so that equipartition holds for the reported temperature. 

37 temperature : bool, optional, default=False 

38 If ``True``, the temperature of the dynamical variables, with one degree of 

39 freedom per variable, will be reported in units of Kelvin. 

40 dynamical_variables : bool, optional, default=False 

41 If ``True``, the current values of all dynamical variables will be reported. 

42 Each variable will be reported with its name and unit. 

43 forces : bool, optional, default=False 

44 If ``True``, the forces acting on each dynamical variable will be reported 

45 in units of kJ/(mol*unit), where unit is the unit of the corresponding 

46 dynamical variable. 

47 collective_variables : bool, optional, default=False 

48 If ``True``, the current values of collective variables that are part of 

49 collective variable couplings will be reported. 

50 effective_masses : bool, optional, default=False 

51 If ``True``, the effective masses of collective variables from coupling 

52 forces will be reported in units of dalton*(nanometer/unit)^2, where 

53 unit is the unit of the corresponding collective variable. 

54 coupling_functions : bool, optional, default=False 

55 If ``True``, the current values of functions in inner product couplings 

56 will be reported. 

57 

58 Example 

59 ------- 

60 >>> import openxps as xps 

61 >>> from sys import stdout 

62 >>> import openmm 

63 >>> import cvpack 

64 >>> from openmm import unit 

65 >>> from openmmtools import testsystems 

66 >>> model = testsystems.AlanineDipeptideVacuum() 

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

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

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

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

71 >>> harmonic_force = xps.HarmonicCoupling(phi, phi0, kappa) 

72 >>> integrator = openmm.LangevinMiddleIntegrator( 

73 ... 300 * unit.kelvin, 1 / unit.picosecond, 4 * unit.femtosecond 

74 ... ) 

75 >>> integrator.setRandomNumberSeed(1234) 

76 >>> platform = openmm.Platform.getPlatformByName("Reference") 

77 >>> simulation = xps.ExtendedSpaceSimulation( 

78 ... model.topology, 

79 ... xps.ExtendedSpaceSystem(model.system, harmonic_force), 

80 ... xps.LockstepIntegrator(integrator), 

81 ... platform 

82 ... ) 

83 >>> simulation.context.setPositions(model.positions) 

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

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

86 >>> simulation.context.setDynamicalVariableVelocitiesToTemperature( 

87 ... 300 * unit.kelvin, 1234 

88 ... ) 

89 >>> reporter = cvpack.reporting.StateDataReporter( 

90 ... stdout, 

91 ... 10, 

92 ... step=True, 

93 ... kineticEnergy=True, 

94 ... writers=[xps.ExtensionWriter( 

95 ... kinetic=True, 

96 ... temperature=True, 

97 ... dynamical_variables=True 

98 ... )], 

99 ... ) 

100 >>> simulation.reporters.append(reporter) 

101 >>> simulation.step(100) # doctest: +SKIP 

102 #"Step","Kinetic Energy (kJ/mole)","Extension Kinetic Energy (kJ/mole)",\ 

103 "Extension Temperature (K)","phi0 (rad)" 

104 10,60.512...,1.7013...,123.456...,3.1415... 

105 """ 

106 

107 def __init__( # noqa: PLR0913 

108 self, 

109 *, 

110 kinetic: bool = False, 

111 temperature: bool = False, 

112 dynamical_variables: bool = False, 

113 forces: bool = False, 

114 collective_variables: bool = False, 

115 effective_masses: bool = False, 

116 coupling_functions: bool = False, 

117 ) -> None: 

118 self._kinetic = kinetic 

119 self._temperature = temperature 

120 self._dynamical_variables = dynamical_variables 

121 self._forces = forces 

122 self._collective_variables = collective_variables 

123 self._effective_masses = effective_masses 

124 self._coupling_functions = coupling_functions 

125 

126 self._needs_velocities = kinetic or temperature 

127 self._needs_positions = dynamical_variables 

128 self._needs_forces = forces 

129 

130 self._temp_factor = 0.0 

131 self._dv_objects = [] 

132 self._masses = np.empty(0) 

133 self._regulated_integrator = None 

134 self._meta_cvs = [] 

135 self._function_names = [] 

136 self._inner_cvs = [] 

137 self._mass_units = [] 

138 self._initialized = False 

139 

140 def initialize(self, simulation: ExtendedSpaceSimulation) -> None: 

141 context = simulation.extended_space_context 

142 coupling = context.getSystem().getCoupling() 

143 self._dv_objects = coupling.getDynamicalVariables() 

144 self._masses = np.array([dv.mass / dv.mass.unit for dv in self._dv_objects]) 

145 integrator = context.getIntegrator().getExtensionIntegrator() 

146 self._regulated_integrator = ( 

147 integrator if isinstance(integrator, RegulatedNHLIntegrator) else None 

148 ) 

149 kb = mmunit.MOLAR_GAS_CONSTANT_R.value_in_unit( 

150 mmunit.kilojoules_per_mole / mmunit.kelvin 

151 ) 

152 self._temp_factor = 2 / (len(self._dv_objects) * kb) 

153 self._meta_cvs = [ 

154 force 

155 for force in coupling.getForces() 

156 if isinstance(force, cvpack.MetaCollectiveVariable) 

157 ] 

158 self._inner_cvs = [ 

159 cv for meta_cv in self._meta_cvs for cv in meta_cv.getInnerVariables() 

160 ] 

161 self._mass_units = [ 

162 mmunit.dalton * (mmunit.nanometer / cv.getUnit()) ** 2 

163 for cv in self._inner_cvs 

164 ] 

165 dv_names = {dv.name for dv in self._dv_objects} 

166 self._function_names = sorted( 

167 parameter 

168 for parameter in coupling.getProtectedParameters() 

169 if parameter not in dv_names 

170 ) 

171 self._initialized = True 

172 

173 def _checkInitialized(self) -> None: 

174 if not self._initialized: 

175 raise RuntimeError( 

176 "The writer must be initialized with a simulation first." 

177 ) 

178 

179 def getDynamicalVariableHeaders(self) -> list[str]: 

180 """Get the headers for all dynamical variables. 

181 

182 Returns 

183 ------- 

184 list[str] 

185 The headers for all dynamical variables. 

186 """ 

187 self._checkInitialized() 

188 return [f"{dv.name} ({dv.unit.get_symbol()})" for dv in self._dv_objects] 

189 

190 def getForceHeaders(self) -> list[str]: 

191 """Get the header for the force on a dynamical variable. 

192 

193 Returns 

194 ------- 

195 list[str] 

196 The headers for all forces. 

197 """ 

198 self._checkInitialized() 

199 return [ 

200 f"Force on {dv.name} (kJ/(mol*{dv.unit.get_symbol()}))" 

201 for dv in self._dv_objects 

202 ] 

203 

204 def getCollectiveVariableHeaders(self) -> list[str]: 

205 """Get the headers for all collective variables. 

206 

207 Returns 

208 ------- 

209 list[str] 

210 The headers for all collective variables. 

211 """ 

212 self._checkInitialized() 

213 return [ 

214 f"{cv.getName()} ({cv.getUnit().get_symbol()})" for cv in self._inner_cvs 

215 ] 

216 

217 def getEffectiveMassHeaders(self) -> list[str]: 

218 """Get the headers for all effective masses. 

219 

220 Returns 

221 ------- 

222 list[str] 

223 The headers for all effective masses. 

224 """ 

225 self._checkInitialized() 

226 return [ 

227 f"emass[{cv.getName()}] ({mass_unit.get_symbol()})" 

228 for cv, mass_unit in zip(self._inner_cvs, self._mass_units) 

229 ] 

230 

231 def getHeaders(self) -> list[str]: 

232 self._checkInitialized() 

233 headers = [] 

234 if self._kinetic: 

235 headers.append("Extension Kinetic Energy (kJ/mole)") 

236 if self._temperature: 

237 headers.append("Extension Temperature (K)") 

238 if self._dynamical_variables: 

239 headers.extend(self.getDynamicalVariableHeaders()) 

240 if self._forces: 

241 headers.extend(self.getForceHeaders()) 

242 if self._collective_variables: 

243 headers.extend(self.getCollectiveVariableHeaders()) 

244 if self._effective_masses: 

245 headers.extend(self.getEffectiveMassHeaders()) 

246 if self._coupling_functions: 

247 headers.extend(self._function_names) 

248 return headers 

249 

250 def _kineticEnergy(self, rates: np.ndarray) -> float: 

251 if self._regulated_integrator is None: 

252 return 0.5 * float(np.dot(self._masses, rates * rates)) 

253 integrator = self._regulated_integrator 

254 kt = integrator.getGlobalVariableByName("kT") 

255 c = np.sqrt(integrator.getRegulationParameter() * kt / self._masses) 

256 return 0.5 * float(np.dot(self._masses, rates * c * np.tanh(rates / c))) 

257 

258 def getValues(self, simulation: ExtendedSpaceSimulation) -> list[float]: # noqa: PLR0912 

259 context = simulation.extended_space_context 

260 extension_context = context.getExtensionContext() 

261 state = extension_context.getState( 

262 getVelocities=self._needs_velocities, 

263 getPositions=self._needs_positions, 

264 getForces=self._needs_forces, 

265 ) 

266 if self._needs_velocities: 

267 velocities = mmswig.State__getVectorAsVec3(state, mm.State.Velocities) 

268 rates = np.array([velocity.x for velocity in velocities]) 

269 kinetic_energy = self._kineticEnergy(rates) 

270 if self._needs_positions: 

271 positions = mmswig.State__getVectorAsVec3(state, mm.State.Positions) 

272 if self._forces: 

273 forces = mmswig.State__getVectorAsVec3(state, mm.State.Forces) 

274 values = [] 

275 if self._kinetic: 

276 values.append(kinetic_energy) 

277 if self._temperature: 

278 values.append(self._temp_factor * kinetic_energy) 

279 if self._dynamical_variables: 

280 for index, dv in enumerate(self._dv_objects): 

281 value, _ = dv.bounds.wrap(positions[index].x, 0) 

282 values.append(value) 

283 if self._forces: 

284 for force in forces: 

285 values.append(force.x) 

286 if self._collective_variables: 

287 for cv in self._inner_cvs: 

288 values.append(extension_context.getParameter(cv.getName())) 

289 if self._effective_masses: 

290 masses = [ 

291 mass 

292 for meta_cv in self._meta_cvs 

293 for mass in meta_cv.getInnerEffectiveMasses(context).values() 

294 ] 

295 for mass, mass_unit in zip(masses, self._mass_units): 

296 values.append(mass.value_in_unit(mass_unit)) 

297 if self._coupling_functions: 

298 for name in self._function_names: 

299 values.append(context.getParameter(name)) 

300 return values