Coverage for ufedmm/analysis.py: 100%
166 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:: analysis
3 :platform: Unix, Windows
4 :synopsis: Unified Free Energy Dynamics with OpenMM
6.. moduleauthor:: Charlles Abreu <craabreu@gmail.com>
8"""
10import itertools
11from collections import namedtuple
13import numpy as np
14import openmm
15from scipy import stats
17from ufedmm.ufedmm import _get_energy_function, _get_parameters, _standardized
20class _RBFContext(openmm.Context):
21 def __init__(self, variables, variances, centers, weights, platform, properties):
22 num_particles = (len(variables) + 2) // 3
23 coordinates = [f"{x}{i + 1}" for i in range(num_particles) for x in "xyz"]
24 exponents = []
25 for v, variance, x in zip(variables, variances, coordinates):
26 if v.periodic: # von Mises
27 factor = 2 * np.pi / v._range
28 exponents.append(
29 f"{1.0 / (variance * factor**2)}*(cos({factor}*({v.id}-{x}))-1)"
30 )
31 else: # Gauss
32 exponents.append(f"(-{0.5 / variance})*({v.id}-{x})^2")
33 expression = f"weight*exp({'+'.join(exponents)})"
35 force = openmm.CustomCompoundBondForce(num_particles, expression)
36 force.addPerBondParameter("weight")
37 for v in variables:
38 force.addGlobalParameter(v.id, 0)
39 force.addEnergyParameterDerivative(v.id)
41 system = openmm.System()
42 positions = []
43 for i, (center, weight) in enumerate(zip(centers, weights)):
44 for position in np.resize(center, (num_particles, 3)):
45 system.addParticle(1.0)
46 positions.append(openmm.Vec3(*position))
47 force.addBond(range(i * num_particles, (i + 1) * num_particles), [weight])
49 system.addForce(force)
50 integrator = openmm.CustomIntegrator(0)
51 super().__init__(system, integrator, platform, properties)
52 self.parameters = [v.id for v in variables]
53 self.setPositions(positions)
56class FreeEnergyAnalyzer:
57 """Calculate free energy landscapes from UFED simulation results.
59 Parameters
60 ----------
61 ufed : :class:`~ufedmm.ufedmm.UnifiedFreeEnergyDynamics`
62 The UFED object.
63 dataframe : pandas.DataFrame
64 A data frame containing sampled sets of collective variables and driver
65 parameters.
66 """
68 def __init__(self, ufed, dataframe):
69 self._ufed = ufed
70 self._dataframe = dataframe
71 self._bias_variables = [v for v in self._ufed.variables if v.sigma is not None]
73 def metadynamics_bias_free_energy(self):
74 """Returns a Python function which, in turn, receives the values of extended-
75 space variables and returns the energy estimated from a Metadynamics bias
76 potential reconstructed from the simulation data.
78 .. warning::
79 Every row of the data frame is taken as a deposited hill, centered at the
80 reported values of the dynamical variables. The data must therefore be
81 reported at the frequency of hill deposition, starting at its first
82 deposition, as a :class:`~ufedmm.io.StateDataReporter` does when its report
83 interval equals the metadynamics frequency. For well-tempered
84 metadynamics, also report ``hillHeights=True``.
86 Returns
87 -------
88 function
89 The free energy function.
90 """
91 Variable = namedtuple("Variable", "sigma factor periodic centers")
92 variables = [
93 Variable(
94 v.sigma, 2 * np.pi / v._range, v.periodic, self._dataframe[v.id].values
95 )
96 for v in self._bias_variables
97 ]
98 try:
99 heights = self._dataframe["Height (kJ/mole)"].values
100 except KeyError:
101 heights = self._ufed.height
103 def free_energy(*position):
104 exponents = 0.0
105 for v, x in zip(variables, position):
106 if v.periodic:
107 exponents += (np.cos(v.factor * (v.centers - x)) - 1.0) / (
108 v.factor * v.sigma
109 ) ** 2
110 else:
111 exponents += -0.5 * ((v.centers - x) / v.sigma) ** 2
112 return -np.sum(heights * np.exp(exponents))
114 return np.vectorize(free_energy)
116 def centers_and_mean_forces(self, bins, min_count=1, adjust_centers=False):
117 """Performs binned statistics with the UFED simulation data.
119 Parameters
120 ----------
121 bins : list(int) or int
122 The number of bins in each direction. If a single integer is passed,
123 then the same number of bins will be considered for all directions.
125 Keyword Args
126 ------------
127 min_count : int, default=1
128 The miminum number of hits for any bin to be considered in the analysis.
129 adjust_centers : bool, default=False
130 Whether to consider the center of a bin as the mean value of the its
131 sampled internal points instead of its geometric center.
133 Returns
134 -------
135 centers : list(numpy.array)
136 A list of Numpy arrays, each one containing the values of an
137 extended-space variable at the centers of all bins that satisfy the
138 minimum-count criterion.
139 mean_forces : list(numpy.array)
140 A list of Numpy arrays, each one containing the mean forces in the
141 direction of an extended-space variable.
142 """
143 variables = self._ufed.variables
144 sample = [self._dataframe[v.id] for v in variables]
145 forces = self._compute_forces()
146 ranges = [(v.min_value, v.max_value) for v in variables]
148 counts = stats.binned_statistic_dd(
149 sample, [], statistic="count", bins=bins, range=ranges
150 )
151 index = np.where(counts.statistic.flatten() >= min_count)
153 n = len(variables)
154 if adjust_centers:
155 means = stats.binned_statistic_dd(
156 sample, sample + forces, bins=bins, range=ranges
157 )
158 centers = [means.statistic[i].flatten()[index] for i in range(n)]
159 mean_forces = [means.statistic[n + i].flatten()[index] for i in range(n)]
160 else:
161 means = stats.binned_statistic_dd(sample, forces, bins=bins, range=ranges)
162 bin_centers = [0.5 * (edges[1:] + edges[:-1]) for edges in counts.bin_edges]
163 center_points = np.stack(
164 [np.array(point) for point in itertools.product(*bin_centers)]
165 )
166 centers = [center_points[:, i][index] for i in range(n)]
167 mean_forces = [statistic.flatten()[index] for statistic in means.statistic]
169 return centers, mean_forces
171 def mean_force_free_energy(
172 self, centers, mean_forces, sigma, platform_name="Reference", properties=None
173 ):
174 """Returns Python functions for evaluating the potential of mean force and their
175 originating mean forces as a function of the collective variables.
177 Parameters
178 ----------
179 centers : list(numpy.array)
180 The bin centers.
181 mean_forces : list(numpy.array)
182 The mean forces.
183 sigmas : float or unit.Quantity or list
184 The standard deviation of kernels.
186 Keyword Args
187 ------------
188 platform_name : string, default='Reference'
189 The name of the OpenMM Platform to be used for potential and mean-force
190 evaluations.
191 properties : dict, default={}
192 A set of values for platform-specific properties. Keys are the property
193 names.
195 Returns
196 -------
197 potential : function
198 A Python function whose arguments are collective variable values and
199 whose result is the potential of mean force at that values.
200 mean_force : function
201 A Python function whose arguments are collective variable values and
202 whose result is the mean force at those values. It takes one argument
203 per variable, and these can be scalars or broadcastable arrays. The
204 result has the broadcast shape of the arguments plus a last axis with
205 one mean-force component per variable, even if there is only one
206 variable.
207 """
208 if properties is None:
209 properties = {}
210 variables = self._ufed.variables
211 n = len(variables)
212 try:
213 variances = [_standardized(value) ** 2 for value in sigma]
214 except TypeError:
215 variances = [_standardized(sigma) ** 2] * n
217 exponent = []
218 derivative = []
219 for v, variance in zip(variables, variances):
220 if v.periodic: # von Mises
221 factor = 2 * np.pi / v._range
222 exponent.append(
223 lambda x, f=factor, var=variance: (
224 (np.cos(f * x) - 1.0) / (f * f * var)
225 )
226 )
227 derivative.append(
228 lambda x, f=factor, var=variance: -np.sin(f * x) / (f * var)
229 )
230 else: # Gauss
231 exponent.append(lambda x, var=variance: -0.5 * x**2 / var)
232 derivative.append(lambda x, var=variance: -x / var)
234 def kernel(x):
235 return np.exp(sum(exponent[i](x[i]) for i in range(n)))
237 def gradient(x, i):
238 return kernel(x) * derivative[i](x[i])
240 grid_points = [np.array(xc) for xc in zip(*centers)]
241 coefficients = []
242 for i in range(n):
243 for x in grid_points:
244 coefficients.append(
245 np.array([gradient(x - xc, i) for xc in grid_points])
246 )
248 M = np.vstack(coefficients)
249 F = -np.hstack(mean_forces)
250 A, _, _, _ = np.linalg.lstsq(M, F, rcond=None)
252 platform = openmm.Platform.getPlatformByName(platform_name)
253 context = _RBFContext(
254 variables, variances, grid_points, A, platform, properties
255 )
256 minimum = 0.0
258 def potential(*x):
259 for parameter, value in zip(context.parameters, x):
260 context.setParameter(parameter, value)
261 state = context.getState(getEnergy=True)
262 return state.getPotentialEnergy()._value - minimum
264 def mean_force(*x):
265 for parameter, value in zip(context.parameters, x):
266 context.setParameter(parameter, value)
267 state = context.getState(getParameterDerivatives=True)
268 derivatives = state.getEnergyParameterDerivatives()
269 return -np.array([derivatives[p] for p in context.parameters])
271 minimum = np.min([potential(*x) for x in grid_points])
272 signature = ",".join(["()"] * n) + "->(n)"
273 return np.vectorize(potential), np.vectorize(mean_force, signature=signature)
275 def _compute_forces(self):
276 variables = self._ufed.variables
277 collective_variables = [colvar.id for v in variables for colvar in v.colvars]
278 extended_variables = [v.id for v in variables]
279 all_variables = collective_variables + extended_variables
281 force = openmm.CustomCVForce(_get_energy_function(variables))
282 for key, value in _get_parameters(variables).items():
283 force.addGlobalParameter(key, value)
284 for variable in all_variables:
285 force.addGlobalParameter(variable, 0)
286 for xv in extended_variables:
287 force.addEnergyParameterDerivative(xv)
289 system = openmm.System()
290 system.addForce(force)
291 system.addParticle(0)
292 platform = openmm.Platform.getPlatformByName("Reference")
293 context = openmm.Context(system, openmm.CustomIntegrator(0), platform)
294 context.setPositions([openmm.Vec3(0, 0, 0)])
296 n = len(self._dataframe.index)
297 forces = [np.empty(n) for xv in extended_variables]
298 for j, (_, row) in enumerate(self._dataframe.iterrows()):
299 for variable in all_variables:
300 context.setParameter(variable, row[variable])
301 state = context.getState(getParameterDerivatives=True)
302 derivatives = state.getEnergyParameterDerivatives()
303 for i, xv in enumerate(extended_variables):
304 forces[i][j] = -derivatives[xv]
305 return forces
308class Analyzer(FreeEnergyAnalyzer):
309 """UFED Analyzer.
311 .. warning::
312 This class is obsolete and will be discontinued. Use :class:`FreeEnergyAnalyzer`
313 instead.
315 Parameters
316 ----------
317 ufed : :class:`~ufedmm.ufedmm.UnifiedFreeEnergyDynamics`
318 The UFED object.
319 dataframe : pandas.DataFrame
320 A data frame containing sampled sets of collective variables and driver
321 parameters.
322 bins : int or list(int)
323 The number of bins in each direction.
325 Keyword Args
326 ------------
327 min_count : int, default=1
328 The miminum number of hits for a given bin to be considered in the analysis.
329 adjust_centers : bool, default=False
330 Whether to consider the center of a bin as the mean value of the its sampled
331 internal points istead of its geometric center.
332 """
334 def __init__(self, ufed, dataframe, bins, min_count=1, adjust_centers=False):
335 super().__init__(ufed, dataframe)
336 try:
337 self._bins = list(bins)
338 except TypeError:
339 self._bins = [bins] * len(ufed.variables)
340 self._min_count = min_count
341 self._adjust_centers = adjust_centers
343 def free_energy_functions(self, sigma=None, factor=8):
344 """Returns Python functions for evaluating the potential of mean force and their
345 originating mean forces as a function of the collective variables.
347 Keyword Args
348 ------------
349 sigma : float or unit.Quantity, default=None
350 The standard deviation of kernels. If this is `None`, then values will
351 be determined from the distances between nodes.
352 factor : float, default=8
353 If ``sigma`` is not explicitly provided, then it will be computed as
354 ``sigma = factor*range/bins`` for each direction.
356 Returns
357 -------
358 potential : function
359 A Python function whose arguments are collective variable values and
360 whose result is the potential of mean force at that values.
361 mean_force : function
362 A Python function whose arguments are collective variable values and
363 whose result is the mean force at that values regarding a given
364 direction. Such direction must be defined through a keyword argument
365 `dir`, whose default value is `0` (meaning the direction of the first
366 collective variable).
367 """
368 self.centers, self.mean_forces = self.centers_and_mean_forces(
369 self._bins,
370 self._min_count,
371 self._adjust_centers,
372 )
373 variables = self._ufed.variables
374 if sigma is None:
375 sigmas = [factor * v._range / bin for v, bin in zip(variables, self._bins)]
376 else:
377 try:
378 sigmas = [_standardized(value) for value in sigma]
379 except TypeError:
380 sigmas = [_standardized(sigma)] * len(variables)
382 return self.mean_force_free_energy(self.centers, self.mean_forces, sigmas)