Coverage for ufedmm/io.py: 99%
171 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-17 14:20 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-17 14:20 +0000
1"""
2.. module:: io
3 :platform: Unix, Windows
4 :synopsis: Unified Free Energy Dynamics Outputs
6.. moduleauthor:: Charlles Abreu <craabreu@gmail.com>
7"""
9import openmm
10import yaml
11from openmm import app, unit
13import ufedmm
14from ufedmm.ufedmm import _Metadynamics, _standardized
17class Tee:
18 """Allows the use of multiple outputs in an OpenMM Reporter.
20 Parameters
21 ----------
22 A list of valid outputs (file names and/or output streams).
24 Example
25 -------
26 >>> import ufedmm
27 >>> import tempfile
28 >>> from sys import stdout
29 >>> file = tempfile.TemporaryFile(mode='w+t')
30 >>> print('test', file=ufedmm.Tee(stdout, file))
31 test
32 >>> file.close()
33 """
35 def __init__(self, *files):
36 self._files = []
37 self._opened = []
38 for output in files:
39 if isinstance(output, str):
40 self._opened.append(open(output, "w"))
41 self._files.append(self._opened[-1])
42 else:
43 self._files.append(output)
45 def __del__(self):
46 for output in self._opened:
47 output.close()
49 def write(self, message):
50 for output in self._files:
51 output.write(message)
53 def flush(self):
54 for output in self._files:
55 output.flush()
58class StateDataReporter(app.StateDataReporter):
59 """An extension of OpenMM's :OpenMMApp:`statedatareporter.StateDataReporter` class,
60 which outputs information about a simulation, such as energy, temperature, etc.
62 All original functionalities are preserved.
64 Besides, if it is added to an :class:`~ufedmm.ufedmm.ExtendedSpaceSimulation`
65 object, e.g. one created through the
66 :func:`~ufedmm.ufedmm.UnifiedFreeEnergyDynamics.simulation` method, then a
67 new set of keywords are available. In this case, the reported temperature is
68 that of the physical system, excluding the extra particles of the extended-space
69 variables, and so is the reported density, unless a total mass is passed. The
70 kinetic energies of the extra particles are still part of the reported kinetic
71 and total energies.
73 Parameters
74 ----------
75 file : str or stream or afed.temperature
76 The file to write to, specified as a file name, file object, or
77 :class:`~ufedmm.io.Tee` object.
78 report_interval : int
79 The interval (in time steps) at which to report state data.
81 Keyword Args
82 ------------
83 variables : bool, default=False
84 Whether to report all dynamical variables related to the extended-space
85 simulation and their associated collective variables.
86 multipleTemperatures : bool, default=False
87 Whether to separately report the temperature estimates for the atoms and for
88 the extended-space dynamical variables.
89 hillHeights : bool, default=False
90 Whether to report the height of the latest deposited metadynamics hill.
91 collectiveVariables : bool, default=False
92 Whether to report the collective variables in all :OpenMM:`CustomCVForce`
93 objects in the system.
94 globalParameterStates : pandas.DataFrame, default=None
95 A DataFrame containing context global parameters (column names) and sets of
96 values thereof. If it is provided, then the potential energy will be
97 reported for every state defined by these values.
99 Example
100 -------
101 >>> import openmm
102 >>> import ufedmm
103 >>> from openmm import unit
104 >>> from sys import stdout
105 >>> model = ufedmm.AlanineDipeptideModel(water='tip3p')
106 >>> mass = 50*unit.dalton*(unit.nanometer/unit.radians)**2
107 >>> Ks = 1000*unit.kilojoules_per_mole/unit.radians**2
108 >>> T = 300*unit.kelvin
109 >>> Ts = 1500*unit.kelvin
110 >>> dt = 2*unit.femtoseconds
111 >>> gamma = 10/unit.picoseconds
112 >>> limit = 180*unit.degrees
113 >>> s_phi = ufedmm.DynamicalVariable(
114 ... 's_phi', -limit, limit, mass, Ts, model.phi, Ks
115 ... )
116 >>> s_psi = ufedmm.DynamicalVariable(
117 ... 's_psi', -limit, limit, mass, Ts, model.psi, Ks
118 ... )
119 >>> ufed = ufedmm.UnifiedFreeEnergyDynamics([s_phi, s_psi], T)
120 >>> integrator = ufedmm.GeodesicLangevinIntegrator(T, gamma, dt)
121 >>> platform = openmm.Platform.getPlatformByName('Reference')
122 >>> simulation = ufed.simulation(
123 ... model.topology, model.system, integrator, platform
124 ... )
125 >>> simulation.context.setPositions(model.positions)
126 >>> simulation.context.setVelocitiesToTemperature(300*unit.kelvin, 1234)
127 >>> reporter = ufedmm.StateDataReporter(stdout, 1, variables=True)
128 >>> reporter.report(simulation, simulation.context.getState())
129 #"s_phi","phi","s_psi","psi"
130 -3.141592653589793,3.141592653589793,-3.141592653589793,3.141592653589793
131 """
133 def __init__(self, file, report_interval, **kwargs):
134 self._variables = kwargs.pop("variables", False)
135 self._multitemps = kwargs.pop("multipleTemperatures", False)
136 self._hill_heights = kwargs.pop("hillHeights", False)
137 self._collective_variables = kwargs.pop("collectiveVariables", False)
138 self._global_parameter_states = kwargs.pop("globalParameterStates", None)
139 super().__init__(file, report_interval, **kwargs)
140 items = [
141 self._volume,
142 self._density,
143 self._speed,
144 self._elapsedTime,
145 self._remainingTime,
146 ]
147 self._backSteps = -sum(items)
148 # In extended space, temperatures exclude the extra particles, whose kinetic
149 # energies are computed from their velocities
150 if self._multitemps or self._temperature:
151 self._needsVelocities = self._needEnergy = True
152 # OpenMM >= 8.3 requests state data through the "include" list
153 for item in ("velocities", "energy"):
154 if item not in self._includes:
155 self._includes.append(item)
157 def _add_item(self, lst, item):
158 if self._backSteps == 0:
159 lst.append(item)
160 else:
161 lst.insert(self._backSteps, item)
163 def _initializeConstants(self, simulation):
164 compute_total_mass = self._density and self._totalMass is None
165 if self._multitemps and not self._temperature:
166 self._temperature = True
167 super()._initializeConstants(simulation)
168 self._temperature = False
169 else:
170 super()._initializeConstants(simulation)
172 self._extended_space = isinstance(simulation, ufedmm.ExtendedSpaceSimulation)
173 if self._extended_space:
174 if compute_total_mass: # the density is that of the physical system
175 system = simulation.context.getSystem()
176 Nt = system.getNumParticles()
177 for i in range(Nt - len(simulation.context.variables), Nt):
178 self._totalMass -= system.getParticleMass(i)
179 self._cv_names = [
180 force.getCollectiveVariableName(i)
181 for force in simulation.context.driving_forces
182 for i in range(force.getNumCollectiveVariables())
183 ]
184 self._var_names = [v.id for v in simulation.context.variables]
185 if self._hill_heights:
186 metadynamics_tasks = filter(
187 lambda x: isinstance(x, _Metadynamics), simulation._periodic_tasks
188 )
189 try:
190 self._metadynamics = next(metadynamics_tasks)
191 except StopIteration:
192 raise Exception(
193 "hillHeights keyword involked for simulation without "
194 "metadynamics bias"
195 ) from None
196 bias_factor = self._metadynamics.bias_factor
197 self._height_scaling = (
198 1 if bias_factor is None else bias_factor / (bias_factor - 1)
199 )
201 if self._multitemps or self._temperature:
202 self._create_ke_context(simulation)
203 Nv = len(simulation.context.variables)
204 self._atoms_dof = self._dof - 3 * Nv
205 if self._temperature:
206 headers = app.StateDataReporter._constructHeaders(self)
207 self._temperature_index = headers.index("Temperature (K)")
209 if self._collective_variables:
210 forces = simulation.context.getSystem().getForces()
211 self._cv_forces = list(
212 filter(lambda f: isinstance(f, openmm.CustomCVForce), forces)
213 )
215 def _create_ke_context(self, simulation):
216 """Creates a context that computes the kinetic energy of each extra particle
217 with the integrator's kinetic energy expression and per-dof variables."""
218 system = simulation.context.getSystem()
219 integrator = simulation.context.getIntegrator()
220 Nt = system.getNumParticles()
221 Nv = len(simulation.context.variables)
222 ke_system = openmm.System()
223 for i in range(Nt - Nv, Nt):
224 ke_system.addParticle(system.getParticleMass(i))
225 ke_integrator = openmm.CustomIntegrator(0)
226 if isinstance(integrator, openmm.CustomIntegrator):
227 if not getattr(integrator, "_up_to_date", True):
228 raise ValueError("Integrator temperatures were not set")
229 for i in range(integrator.getNumPerDofVariables()):
230 ke_integrator.addPerDofVariable(integrator.getPerDofVariableName(i), 0)
231 expression = integrator.getKineticEnergyExpression()
232 else:
233 expression = "0.5*m*v*v"
234 ke_integrator.addComputePerDof("v", expression)
235 self._ke_context = openmm.Context(
236 ke_system, ke_integrator, openmm.Platform.getPlatformByName("Reference")
237 )
238 for i in range(ke_integrator.getNumPerDofVariables()):
239 values = integrator.getPerDofVariable(i)
240 ke_integrator.setPerDofVariable(i, values[Nt - Nv : Nt])
242 def _extra_kinetic_energies(self, state):
243 """Returns the kinetic energy of each extra particle along x, y, and z."""
244 ke_context = self._ke_context
245 Nv = ke_context.getSystem().getNumParticles()
246 velocities = state.getVelocities(extended=True)
247 ke_context.setVelocities(velocities[len(velocities) - Nv :])
248 ke_context.getIntegrator().step(1)
249 return ke_context.getState(getVelocities=True).getVelocities()
251 def _constructHeaders(self):
252 headers = super()._constructHeaders()
253 if self._extended_space:
254 if self._multitemps:
255 self._add_item(headers, "T[atoms] (K)")
256 for var in self._var_names:
257 self._add_item(headers, f"T[{var}] (K)")
258 if self._variables:
259 for cv in self._cv_names:
260 self._add_item(headers, cv)
261 if self._hill_heights:
262 self._add_item(headers, "Height (kJ/mole)")
263 if self._collective_variables:
264 for force in self._cv_forces:
265 for index in range(force.getNumCollectiveVariables()):
266 self._add_item(headers, force.getCollectiveVariableName(index))
267 if self._global_parameter_states is not None:
268 for index in self._global_parameter_states.index:
269 self._add_item(headers, f"Energy[{index}] (kJ/mole)")
270 return headers
272 def _constructReportValues(self, simulation, state): # noqa: PLR0912
273 values = super()._constructReportValues(simulation, state)
274 if self._extended_space:
275 if self._multitemps or self._temperature:
276 ke_values = self._extra_kinetic_energies(state)
277 xvar_ke = sum(ke.x + ke.y + ke.z for ke in ke_values)
278 total_ke = _standardized(state.getKineticEnergy())
279 kB = _standardized(unit.MOLAR_GAS_CONSTANT_R)
280 atoms_temperature = 2 * (total_ke - xvar_ke) / (self._atoms_dof * kB)
281 if self._temperature:
282 values[self._temperature_index] = atoms_temperature
283 if self._multitemps:
284 self._add_item(values, atoms_temperature)
285 for ke in ke_values:
286 self._add_item(values, 2 * ke.x / kB)
287 if self._variables:
288 for force in simulation.context.driving_forces:
289 for cv in force.getCollectiveVariableValues(simulation.context):
290 self._add_item(values, cv)
291 if self._hill_heights:
292 self._add_item(values, self._metadynamics.height * self._height_scaling)
293 if self._collective_variables:
294 for force in self._cv_forces:
295 for cv in force.getCollectiveVariableValues(simulation.context):
296 self._add_item(values, cv)
297 if self._global_parameter_states is not None:
298 originals = list(
299 map(
300 simulation.context.getParameter,
301 self._global_parameter_states.columns,
302 )
303 )
304 for _, row in self._global_parameter_states.iterrows():
305 for name, value in row.items():
306 simulation.context.setParameter(name, value)
307 energy = simulation.context.getState(
308 getEnergy=True
309 ).getPotentialEnergy()
310 self._add_item(values, energy.value_in_unit(unit.kilojoules_per_mole))
311 for name, value in zip(self._global_parameter_states.columns, originals):
312 simulation.context.setParameter(name, value)
313 return values
316def serialize(object, file):
317 """Serializes a ufedmm object."""
318 dump = yaml.dump(object, Dumper=yaml.CDumper)
319 if isinstance(file, str):
320 with open(file, "w") as f:
321 f.write(dump)
322 else:
323 file.write(dump)
326def deserialize(file):
327 """Deserializes a ufedmm object."""
328 if isinstance(file, str):
329 with open(file) as f:
330 object = yaml.load(f.read(), Loader=yaml.CLoader)
331 else:
332 object = yaml.load(file.read(), Loader=yaml.CLoader)
333 return object