Debian Codegraph @

examples/harmonic-oscillators/harmonic-oscillators.py

raw
1 """
2 Test MBAR by performing statistical tests on a set of of 1D harmonic oscillators, for which
3 the true free energy differences can be computed analytically.
4
5 A number of replications of an experiment in which i.i.d. samples are drawn from a set of
6 K harmonic oscillators are produced. For each replicate, we estimate the dimensionless free
7 energy differences and mean-square displacements (an observable), as well as their uncertainties.
8
9 For a 1D harmonic oscillator, the potential is given by
10 V(x;K) = (K/2) * (x-x_0)**2
11 where K denotes the spring constant.
12
13 The equilibrium distribution is given analytically by
14 p(x;beta,K) = sqrt[(beta K) / (2 pi)] exp[-beta K (x-x_0)**2 / 2]
15 The dimensionless free energy is therefore
16 f(beta,K) = - (1/2) * ln[ (2 pi) / (beta K) ]
17
18 """
19
20 # =============================================================================================
21 # IMPORTS
22 # =============================================================================================
23
24 import sys
25 import numpy as np
26 from pymbar import testsystems, exp, exp_gauss, bar, MBAR, FES
27 from pymbar.utils import ParameterError
28
29 import logging
30 import sys
31
32 logging.basicConfig(stream=sys.stdout, level=logging.INFO)
33
34 # =============================================================================================
35 # HELPER FUNCTIONS
36 # =============================================================================================
37
38
39 def stddev_away(namex, errorx, dx):
40 if dx > 0:
41 print(f"{namex} differs by {errorx / dx:.3f} standard deviations from analytical")
42 else:
43 print(f"{namex} differs by an undefined number of standard deviations")
44
45
46 def get_analytical(beta, K, O, observables):
47 # For a harmonic oscillator with spring constant K,
48 # x ~ Normal(x_0, sigma^2), where sigma = 1/sqrt(beta K)
49
50 # Compute the absolute dimensionless free energies of each oscillator analytically.
51 # f = - ln(sqrt((2 pi)/(beta K)) )
52 print("Computing dimensionless free energies analytically...")
53
54 sigma = (beta * K) ** -0.5
55 f_k_analytical = -np.log(np.sqrt(2 * np.pi) * sigma)
56
57 Delta_f_ij_analytical = f_k_analytical - np.vstack(f_k_analytical)
58
59 A_k_analytical = dict()
60 A_ij_analytical = dict()
61
62 for observe in observables:
63 if observe == "RMS displacement":
64 # mean square displacement
65 A_k_analytical[observe] = sigma
66 if observe == "potential energy":
67 # By equipartition
68 A_k_analytical[observe] = 1 / (2 * beta) * np.ones(len(K), float)
69 if observe == "position":
70 # observable is the position
71 A_k_analytical[observe] = O
72 if observe == "position^2":
73 # observable is the position^2
74 A_k_analytical[observe] = (1 + beta * K * O**2) / (beta * K)
75
76 A_ij_analytical[observe] = A_k_analytical[observe] - np.vstack(A_k_analytical[observe])
77
78 return f_k_analytical, Delta_f_ij_analytical, A_k_analytical, A_ij_analytical
79
80
81 # =============================================================================================
82 # PARAMETERS
83 # =============================================================================================
84
85
86 K_k = np.array([25, 16, 9, 4, 1, 1]) # spring constants for each state
87 O_k = np.array([0, 1, 2, 3, 4, 5]) # offsets for spring constants
88 # number of samples from each state (can be zero for some states)
89 N_k = 10 * np.array([1000, 1000, 1000, 1000, 0, 1000])
90 Nk_ne_zero = N_k != 0
91 beta = 1.0 # inverse temperature for all simulations
92 K_extra = np.array([20, 12, 6, 2, 1])
93 O_extra = np.array([0.5, 1.5, 2.5, 3.5, 4.5])
94 observables = ["position", "position^2", "potential energy", "RMS displacement"]
95
96 seed = None
97 # Uncomment the following line to seed the random number generated to
98 # produce reproducible output.
99 seed = 0
100 np.random.seed(seed)
101
102 # =============================================================================================
103 # MAIN
104 # =============================================================================================
105
106 # Determine number of simulations.
107 K = np.size(N_k)
108 if np.shape(K_k) != np.shape(N_k):
109 msg = f"K_k ({np.shape(K_k):d}) and N_k ({np.shape(N_k):d}) must have same dimensions."
110 raise ParameterError(msg)
111 if np.shape(O_k) != np.shape(N_k):
112 msg = f"O_k ({np.shape(K_k):d}) and N_k ({np.shape(N_k):d}) must have same dimensions."
113 raise ParameterError(msg)
114
115 # Determine maximum number of samples to be drawn for any state.
116 N_max = np.max(N_k)
117
118 f_k_analytical, Delta_f_ij_analytical, A_k_analytical, A_ij_analytical = get_analytical(
119 beta, K_k, O_k, observables
120 )
121
122 print(f"This script will draw samples from {K:d} harmonic oscillators.")
123 print("The harmonic oscillators have equilibrium positions:", O_k)
124 print("and spring constants:", K_k)
125 print(
126 "and the following number of samples will be drawn from each",
127 "(can be zero if no samples drawn):",
128 N_k,
129 )
130
131
132 # =============================================================================================
133 # Generate independent data samples from K one-dimensional harmonic oscillators centered at q = 0.
134 # =============================================================================================
135
136 print("generating samples...")
137 randomsample = testsystems.harmonic_oscillators.HarmonicOscillatorsTestCase(
138 O_k=O_k, K_k=K_k, beta=beta
139 )
140 x_kn, u_kln, N_k = randomsample.sample(N_k, mode="u_kln", seed=seed)
141
142 # get the unreduced energies
143 U_kln = u_kln / beta
144
145 # =============================================================================================
146 # Estimate free energies and expectations.
147 # =============================================================================================
148
149 print("======================================")
150 print(" Initializing MBAR ")
151 print("======================================")
152
153 # Estimate free energies from simulation using MBAR.
154 print("Estimating relative free energies from simulation (this may take a while)...")
155
156 # Initialize the MBAR class, determining the free energies.
157 mbar = MBAR(u_kln, N_k, relative_tolerance=1.0e-10, verbose=True)
158 # Get matrix of dimensionless free energy differences and uncertainty estimate.
159
160 print("=============================================")
161 print(" Testing compute_free_energy_differences ")
162 print("=============================================")
163
164 results = mbar.compute_free_energy_differences()
165 Delta_f_ij_estimated = results["Delta_f"]
166 dDelta_f_ij_estimated = results["dDelta_f"]
167
168 # Compute error from analytical free energy differences.
169 Delta_f_ij_error = Delta_f_ij_estimated - Delta_f_ij_analytical
170
171 print("Error in free energies is:")
172 print(Delta_f_ij_error)
173 print("Uncertainty in free energies is:")
174 print(dDelta_f_ij_estimated)
175
176 print("Standard deviations away is:")
177 # mathematical manipulation to avoid dividing by zero errors; we don't care
178 # about the diagnonals, since they are identically zero.
179 df_ij_mod = dDelta_f_ij_estimated + np.identity(K)
180 stdevs = np.abs(Delta_f_ij_error / df_ij_mod)
181 for k in range(K):
182 stdevs[k, k] = 0
183 print(stdevs)
184
185 print("==============================================")
186 print(" Testing computeBAR ")
187 print("==============================================")
188
189 nonzero_indices = np.arange(K)[Nk_ne_zero]
190 Knon = len(nonzero_indices)
191 for i in range(Knon - 1):
192 k = nonzero_indices[i]
193 k1 = nonzero_indices[i + 1]
194 w_F = u_kln[k, k1, 0 : N_k[k]] - u_kln[k, k, 0 : N_k[k]] # forward work
195 w_R = u_kln[k1, k, 0 : N_k[k1]] - u_kln[k1, k1, 0 : N_k[k1]] # reverse work
196 results = bar(w_F, w_R)
197 df_bar = results["Delta_f"]
198 ddf_bar = results["dDelta_f"]
199 bar_analytical = f_k_analytical[k1] - f_k_analytical[k]
200 bar_error = bar_analytical - df_bar
201 print(
202 f"BAR estimator for reduced free energy from states {k:d} to {k1:d} is {df_bar:f} +/- {ddf_bar:f}"
203 )
204 stddev_away("BAR estimator", bar_error, ddf_bar)
205
206 print("==============================================")
207 print(" Testing EXP ")
208 print("==============================================")
209
210 print("EXP forward free energy")
211 for k in range(K - 1):
212 if N_k[k] != 0:
213 # forward work
214 w_F = u_kln[k, k + 1, 0 : N_k[k]] - u_kln[k, k, 0 : N_k[k]]
215 results = exp(w_F)
216 df_exp = results["Delta_f"]
217 ddf_exp = results["dDelta_f"]
218 exp_analytical = f_k_analytical[k + 1] - f_k_analytical[k]
219 exp_error = exp_analytical - df_exp
220 print(f"df from states {k:d} to {k + 1:d} is {df_exp:f} +/- {ddf_exp:f}")
221 stddev_away("df", exp_error, ddf_exp)
222
223 print("EXP reverse free energy")
224 for k in range(1, K):
225 if N_k[k] != 0:
226 w_R = u_kln[k, k - 1, 0 : N_k[k]] - u_kln[k, k, 0 : N_k[k]] # reverse work
227 results = exp(w_R)
228 df_exp = -results["Delta_f"]
229 ddf_exp = results["dDelta_f"]
230 exp_analytical = f_k_analytical[k] - f_k_analytical[k - 1]
231 exp_error = exp_analytical - df_exp
232 print(f"df from states {k:d} to {k - 1:d} is {df_exp:f} +/- {ddf_exp:f}")
233 stddev_away("df", exp_error, ddf_exp)
234
235 print("==============================================")
236 print(" Testing computeGauss ")
237 print("==============================================")
238
239 print("Gaussian forward estimate")
240 for k in range(K - 1):
241 if N_k[k] != 0:
242 w_F = u_kln[k, k + 1, 0 : N_k[k]] - u_kln[k, k, 0 : N_k[k]] # forward work
243 results = exp_gauss(w_F)
244 df_gauss = results["Delta_f"]
245 ddf_gauss = results["dDelta_f"]
246 gauss_analytical = f_k_analytical[k + 1] - f_k_analytical[k]
247 gauss_error = gauss_analytical - df_gauss
248 print(
249 f"df for reduced free energy from states {k:d} to {k + 1:d} is {df_gauss:f} +/- {ddf_gauss:f}"
250 )
251 stddev_away("df", gauss_error, ddf_gauss)
252
253 print("Gaussian reverse estimate")
254 for k in range(1, K):
255 if N_k[k] != 0:
256 # reverse work
257 w_R = u_kln[k, k - 1, 0 : N_k[k]] - u_kln[k, k, 0 : N_k[k]]
258 results = exp_gauss(w_R)
259 df_gauss = results["Delta_f"]
260 ddf_gauss = results["dDelta_f"]
261 gauss_analytical = f_k_analytical[k] - f_k_analytical[k - 1]
262 gauss_error = gauss_analytical - df_gauss
263 print(
264 f"df for reduced free energy from states {k:d} to {k - 1:d} is {df_gauss:f} +/- {ddf_gauss:f}"
265 )
266 stddev_away("df", gauss_error, ddf_gauss)
267
268 print("======================================")
269 print(" Testing compute_expectations")
270 print("======================================")
271
272 A_kn_all = dict()
273 A_k_estimated_all = dict()
274 A_kl_estimated_all = dict()
275 N = np.sum(N_k)
276
277 for observe in observables:
278 print("============================================")
279 print(f" Testing observable '{observe}'")
280 print("============================================")
281
282 if observe == "RMS displacement":
283 state_dependent = True
284 A_kn = np.zeros([K, N], dtype=np.float64)
285 n = 0
286 for k in range(K):
287 for nk in range(N_k[k]):
288 # observable is the squared displacement
289 A_kn[:, n] = (x_kn[k, nk] - O_k[:]) ** 2
290 n += 1
291
292 # observable is the potential energy, a 3D array since the
293 # potential energy is a function of the thermodynamic state
294 elif observe == "potential energy":
295 state_dependent = True
296 A_kn = np.zeros([K, N], dtype=np.float64)
297 n = 0
298 for k in range(0, K):
299 for nk in range(0, N_k[k]):
300 A_kn[:, n] = U_kln[k, :, nk]
301 n += 1
302
303 # observable for estimation is the position
304 elif observe == "position":
305 state_dependent = False
306 A_kn = np.zeros([K, N_max], dtype=np.float64)
307 for k in range(0, K):
308 A_kn[k, 0 : N_k[k]] = x_kn[k, 0 : N_k[k]]
309
310 # observable for estimation is the position^2
311 elif observe == "position^2":
312 state_dependent = False
313 A_kn = np.zeros([K, N_max], dtype=np.float64)
314 for k in range(0, K):
315 A_kn[k, 0 : N_k[k]] = x_kn[k, 0 : N_k[k]] ** 2
316
317 results = mbar.compute_expectations(A_kn, state_dependent=state_dependent)
318 A_k_estimated = results["mu"]
319 dA_k_estimated = results["sigma"]
320
321 # need to additionally transform to get the square root
322 if observe == "RMS displacement":
323 A_k_estimated = np.sqrt(A_k_estimated)
324 # Compute error from analytical observable estimate.
325 dA_k_estimated = dA_k_estimated / (2 * A_k_estimated)
326
327 As_k_estimated = np.zeros([K], np.float64)
328 dAs_k_estimated = np.zeros([K], np.float64)
329
330 # 'standard' expectation averages - not defined if no samples
331 nonzeros = np.arange(K)[Nk_ne_zero]
332
333 totaln = 0
334 for k in nonzeros:
335 if (observe == "position") or (observe == "position^2"):
336 As_k_estimated[k] = np.average(A_kn[k, 0 : N_k[k]])
337 dAs_k_estimated[k] = np.sqrt(np.var(A_kn[k, 0 : N_k[k]]) / (N_k[k] - 1))
338 elif (observe == "RMS displacement") or (observe == "potential energy"):
339 totalp = totaln + N_k[k]
340 As_k_estimated[k] = np.average(A_kn[k, totaln:totalp])
341 dAs_k_estimated[k] = np.sqrt(np.var(A_kn[k, totaln:totalp]) / (N_k[k] - 1))
342 totaln = totalp
343 if observe == "RMS displacement":
344 As_k_estimated[k] = np.sqrt(As_k_estimated[k])
345 dAs_k_estimated[k] = dAs_k_estimated[k] / (2 * As_k_estimated[k])
346
347 A_k_error = A_k_estimated - A_k_analytical[observe]
348 As_k_error = As_k_estimated - A_k_analytical[observe]
349
350 print("------------------------------")
351 print("Now testing 'averages' mode")
352 print("------------------------------")
353
354 print(f"Analytical estimator of {observe} is")
355 print(A_k_analytical[observe])
356
357 print(f"MBAR estimator of the {observe} is")
358 print(A_k_estimated)
359
360 print("MBAR estimators differ by X standard deviations")
361 stdevs = np.abs(A_k_error / dA_k_estimated)
362 print(stdevs)
363
364 print(f"Standard estimator of {observe} is (states with samples):")
365 print(As_k_estimated[Nk_ne_zero])
366
367 print("Standard estimators differ by X standard deviations (states with samples)")
368 stdevs = np.abs(As_k_error[Nk_ne_zero] / dAs_k_estimated[Nk_ne_zero])
369 print(stdevs)
370
371 results = mbar.compute_expectations(
372 A_kn, state_dependent=state_dependent, output="differences"
373 )
374 A_kl_estimated = results["mu"]
375 dA_kl_estimated = results["sigma"]
376
377 print("------------------------------")
378 print("Now testing 'differences' mode")
379 print("------------------------------")
380
381 if (
382 "RMS displacement" != observe
383 ): # can't test this, because we're actually computing the expectation of
384 # the mean square displacement, and so the differences are <a_i^2> - <a_j^2>,
385 # not sqrt<a_i>^2 - sqrt<a_j>^2
386 A_kl_analytical = A_k_analytical[observe] - np.vstack(A_k_analytical[observe])
387 A_kl_error = A_kl_estimated - A_kl_analytical
388
389 print(f"Analytical estimator of differences of {observe} is")
390 print(A_kl_analytical)
391
392 print(f"MBAR estimator of the differences of {observe} is")
393 print(A_kl_estimated)
394
395 print("MBAR estimators differ by X standard deviations")
396 stdevs = np.abs(A_kl_error / (dA_kl_estimated + np.identity(K)))
397 for k in range(K):
398 stdevs[k, k] = 0
399 print(stdevs)
400
401 # save up the A_k for use in compute_multiple_expectations
402 A_kn_all[observe] = A_kn
403 A_k_estimated_all[observe] = A_k_estimated
404 A_kl_estimated_all[observe] = A_kl_estimated
405
406 print("=============================================")
407 print(" Testing compute_multiple_expectations")
408 print("=============================================")
409
410 # have to exclude the potential and RMS displacemet for now, not functions
411 # of a single state
412 observables_single = ["position", "position^2"]
413
414 A_ikn = np.zeros([len(observables_single), K, N_k.max()], np.float64)
415 for i, observe in enumerate(observables_single):
416 A_ikn[i, :, :] = A_kn_all[observe]
417 for i in range(K):
418 results = mbar.compute_multiple_expectations(A_ikn, u_kln[:, i, :], compute_covariance=True)
419 A_i = results["mu"]
420 dA_ij = results["sigma"]
421 Ca_ij = results["covariances"]
422 print(f"Averages for state {i:d}")
423 print(A_i)
424 print(f"Uncertainties for state {i:d}")
425 print(dA_ij)
426 print(f"Correlation matrix between observables for state {i:d}")
427 print(Ca_ij)
428
429 print("============================================")
430 print(" Testing compute_entropy_and_enthalpy")
431 print("============================================")
432
433 results = mbar.compute_entropy_and_enthalpy(u_kn=u_kln, verbose=True)
434 Delta_f_ij = results["Delta_f"]
435 dDelta_f_ij = results["dDelta_f"]
436 Delta_u_ij = results["Delta_u"]
437 dDelta_u_ij = results["dDelta_u"]
438 Delta_s_ij = results["Delta_s"]
439 dDelta_s_ij = results["dDelta_s"]
440
441 print("Free energies")
442 print(Delta_f_ij)
443 print(dDelta_f_ij)
444 diffs1 = Delta_f_ij - Delta_f_ij_estimated
445 print(
446 f"maximum difference between values computed here and in computeFreeEnergies is {np.max(diffs1):g}"
447 )
448 if np.max(np.abs(diffs1)) > 1.0e-10:
449 print("Difference in values from computeFreeEnergies")
450 print(diffs1)
451 diffs2 = dDelta_f_ij - dDelta_f_ij_estimated
452 print(
453 f"maximum difference between uncertainties computed here and in computeFreeEnergies is {np.max(diffs2):g}"
454 )
455 if np.max(np.abs(diffs2)) > 1.0e-10:
456 print("Difference in expectations from computeFreeEnergies")
457 print(diffs2)
458
459 print("Energies")
460 print(Delta_u_ij)
461 print(dDelta_u_ij)
462 U_k = A_k_estimated_all["potential energy"]
463 expectations = U_k - np.vstack(U_k)
464 diffs1 = Delta_u_ij - expectations
465 print(
466 f"maximum difference between values computed here and in compute_expectations is {np.max(diffs1):g}"
467 )
468 if np.max(np.abs(diffs1)) > 1.0e-10:
469 print("Difference in values from compute_expectations")
470 print(diffs1)
471
472 print("Entropies")
473 print(Delta_s_ij)
474 print(dDelta_s_ij)
475
476 # analytical entropy estimate
477 s_k_analytical = 0.5 / beta - f_k_analytical
478 Delta_s_ij_analytical = s_k_analytical - np.vstack(s_k_analytical)
479
480 Delta_s_ij_error = Delta_s_ij_analytical - Delta_s_ij
481 print("Error in entropies is:")
482 print(Delta_f_ij_error)
483
484 print("Standard deviations away is:")
485 # mathematical manipulation to avoid dividing by zero errors; we don't care
486 # about the diagnonals, since they are identically zero.
487 ds_ij_mod = dDelta_s_ij + np.identity(K)
488 stdevs = np.abs(Delta_s_ij_error / ds_ij_mod)
489 for k in range(K):
490 stdevs[k, k] = 0
491 print(stdevs)
492
493 print("============================================")
494 print(" Testing compute_perturbed_free_energies")
495 print("============================================")
496
497 L = np.size(K_extra)
498 f_k_analytical, Delta_f_ij_analytical, A_k_analytical, A_ij_analytical = get_analytical(
499 beta, K_extra, O_extra, observables
500 )
501
502 if np.size(O_extra) != np.size(K_extra):
503 raise ParameterError(
504 f"O_extra ({np.shape(K_k):d}) and K_extra ({np.shape(N_k):d}) must have the same dimensions."
505 )
506
507 unew_kln = np.zeros([K, L, np.max(N_k)], np.float64)
508 for k in range(K):
509 for l in range(L):
510 unew_kln[k, l, 0 : N_k[k]] = (K_extra[l] / 2.0) * (x_kn[k, 0 : N_k[k]] - O_extra[l]) ** 2
511
512 results = mbar.compute_perturbed_free_energies(unew_kln)
513 Delta_f_ij_estimated = results["Delta_f"]
514 dDelta_f_ij_estimated = results["dDelta_f"]
515
516 Delta_f_ij_error = Delta_f_ij_estimated - Delta_f_ij_analytical
517
518 print("Error in free energies is:")
519 print(Delta_f_ij_error)
520
521 print("Standard deviations away is:")
522 # mathematical manipulation to avoid dividing by zero errors; we don't care
523 # about the diagnonals, since they are identically zero.
524 df_ij_mod = dDelta_f_ij_estimated + np.identity(L)
525 stdevs = np.abs(Delta_f_ij_error / df_ij_mod)
526 for l in range(L):
527 stdevs[l, l] = 0
528 print(stdevs)
529
530 print("============================================")
531 print(" Testing compute_expectation (new states)")
532 print("============================================")
533
534 nth = 3
535 # test the nth "extra" states, O_extra[nth] & K_extra[nth]
536 for observe in observables:
537 print("============================================")
538 print(f" Testing observable '{observe}'")
539 print("============================================")
540
541 if observe == "RMS displacement":
542 state_dependent = True
543 A_kn = np.zeros([K, 1, N_max], dtype=np.float64)
544 for k in range(0, K):
545 # observable is the squared displacement
546 A_kn[k, 0, 0 : N_k[k]] = (x_kn[k, 0 : N_k[k]] - O_extra[nth]) ** 2
547
548 # observable is the potential energy, a 3D array since the potential energy is a function of
549 # thermodynamic state
550 elif observe == "potential energy":
551 state_dependent = True
552 A_kn = unew_kln[:, [nth], :] / beta
553
554 # position and position^2 can use the same observables
555 # observable for estimation is the position
556 elif observe == "position":
557 state_dependent = False
558 A_kn = A_kn_all["position"]
559
560 elif observe == "position^2":
561 state_dependent = False
562 A_kn = A_kn_all["position^2"]
563
564 A_k_estimated, dA_k_estimated
565 results = mbar.compute_expectations(
566 A_kn, unew_kln[:, [nth], :], state_dependent=state_dependent
567 )
568 A_k_estimated = results["mu"]
569 dA_k_estimated = results["sigma"]
570 # need to additionally transform to get the square root
571 if observe == "RMS displacement":
572 A_k_estimated = np.sqrt(A_k_estimated)
573 dA_k_estimated = dA_k_estimated / (2 * A_k_estimated)
574
575 A_k_error = A_k_estimated - A_k_analytical[observe][nth]
576
577 print(f"Analytical estimator of {observe} is")
578 print(A_k_analytical[observe][nth])
579
580 print(f"MBAR estimator of the {observe} is")
581 print(A_k_estimated)
582
583 print("MBAR estimators differ by X standard deviations")
584 stdevs = np.abs(A_k_error / dA_k_estimated)
585 print(stdevs)
586
587 print("============================================")
588 print(" Testing compute_overlap")
589 print("============================================")
590
591 results = mbar.compute_overlap()
592 O = results["scalar"]
593 O_i = results["eigenvalues"]
594 O_ij = results["matrix"]
595
596 print("Overlap matrix output")
597 print(O_ij)
598
599 for k in range(K):
600 print(f"Sum of row {k:d} is {np.sum(O_ij[k, :]):f} (should be 1),", end=" ")
601 if np.abs(np.sum(O_ij[k, :]) - 1) < 1.0e-10:
602 print("looks like it is.")
603 else:
604 print("but it's not.")
605
606 print("Eigenvalues of overlap matrix:")
607 print(O_i)
608
609
610 print("Overlap scalar measure: (1-lambda_2)")
611 print(O)
612
613 print("============================================")
614 print(" Testing compute_effective_sample_number")
615 print("============================================")
616
617 N_eff = mbar.compute_effective_sample_number(verbose=True)
618 print("Effective Sample number")
619 print(N_eff)
620 print("Compare stanadrd estimate of <x> with the MBAR estimate of <x>")
621 print("We should have that with MBAR, err_MBAR = sqrt(N_k/N_eff)*err_standard,")
622 print("so standard (scaled) results should be very close to MBAR results.")
623 print("No standard estimate exists for states that are not sampled.")
624 A_kn = x_kn
625 results = mbar.compute_expectations(A_kn)
626 val_mbar = results["mu"]
627 err_mbar = results["sigma"]
628 err_standard = np.zeros([K], dtype=np.float64)
629 err_scaled = np.zeros([K], dtype=np.float64)
630
631 for k in range(K):
632 if N_k[k] != 0:
633 # use position
634 err_standard[k] = np.std(A_kn[k, 0 : N_k[k]]) / np.sqrt(N_k[k] - 1)
635 err_scaled[k] = np.std(A_kn[k, 0 : N_k[k]]) / np.sqrt(N_eff[k] - 1)
636
637 print(" ", end=" ")
638 for k in range(K):
639 print(f" {k:d} ", end=" ")
640 print("")
641 print("MBAR :", end=" ")
642 print(err_mbar)
643 print("standard :", end=" ")
644 print(err_standard)
645 print("sqrt N_k/N_eff :", end=" ")
646 print(np.sqrt(N_k / N_eff))
647 print("Standard (scaled):", end=" ")
648 print(err_standard * np.sqrt(N_k / N_eff))
649
650 print("============================================")
651 print(" Testing free energy surface functions ")
652 print("============================================")
653
654 # For 2-D, The equilibrium distribution is given analytically by
655 # p(x;beta,K) = sqrt[(beta K) / (2 pi)] exp[-beta K [(x-mu)^2] / 2]
656 #
657 # The dimensionless free energy is therefore
658 # f(beta,K) = - (1/2) * ln[ (2 pi) / (beta K) ]
659 #
660 # In this problem, we are investigating the sum of two Gaussians, once
661 # centered at 0, and others centered at grid points.
662 #
663 # V(x;K) = (K0/2) * [(x-x_0)^2]
664 #
665 # For 1-D, The equilibrium distribution is given analytically by
666 # p(x;beta,K) = 1/N exp[-beta (K0 [x^2] / 2 + KU [(x-mu)^2] / 2)]
667 # Where N is the normalization constant.
668 #
669 # The dimensionless free energy is the integral of this, and can be computed as:
670 # f(beta,K) = - ln [ (2*np.pi/(Ko+Ku))^(d/2) exp[ -Ku*Ko mu' mu / 2(Ko +Ku)]
671 # f(beta,K) - fzero = -Ku*Ko / 2(Ko+Ku) = 1/(1/(Ku/2) + 1/(K0/2))
672
673
674 def generate_fes_data(
675 ndim=1, nbinsperdim=15, nsamples=1000, K0=20.0, Ku=100.0, gridscale=0.2, xrange=((-3, 3),)
676 ):
677 x0 = np.zeros([ndim], np.float64) # center of base potential
678 numbrellas = 1
679 nperdim = np.zeros([ndim], int)
680 for d in range(ndim):
681 nperdim[d] = xrange[d][1] - xrange[d][0] + 1
682 numbrellas *= nperdim[d]
683
684 print(f"There are a total of {numbrellas:d} umbrellas.")
685
686 # Enumerate umbrella centers, and compute the analytical free energy of
687 # that umbrella
688 print("Constructing umbrellas...")
689 ksum = (Ku + K0) / beta
690 kprod = (Ku * K0) / (beta * beta)
691 f_k_analytical = np.zeros(numbrellas, np.float64)
692 # xu_i[i,:] is the center of umbrella i
693 xu_i = np.zeros([numbrellas, ndim], np.float64)
694
695 dp = np.zeros(ndim, int)
696 dp[0] = 1
697 for d in range(1, ndim):
698 dp[d] = nperdim[d] * dp[d - 1]
699
700 umbrella_zero = 0
701 for i in range(numbrellas):
702 center = []
703 for d in range(ndim):
704 val = gridscale * ((int(i // dp[d])) % nperdim[d] + xrange[d][0])
705 center.append(val)
706 center = np.array(center)
707 xu_i[i, :] = center
708 mu2 = np.dot(center, center)
709 f_k_analytical[i] = np.log(
710 (ndim * np.pi / ksum) ** (3.0 / 2.0) * np.exp(-kprod * mu2 / (2.0 * ksum))
711 )
712 # assumes that we have one state that is at the zero.
713 if np.all(center == 0.0):
714 umbrella_zero = i
715 i += 1
716 f_k_analytical -= f_k_analytical[umbrella_zero]
717
718 print(f"Generating {nsamples:d} samples for each of {numbrellas:d} umbrellas...")
719 x_n = np.zeros([numbrellas * nsamples, ndim], np.float64)
720
721 for i in range(numbrellas):
722 for dim in range(ndim):
723 # Compute mu and sigma for this dimension for sampling from V0(x) + Vu(x).
724 # Product of Gaussians: N(x ; a, A) N(x ; b, B) = N(a ; b , A+B) x N(x ; c, C) where
725 # C = 1/(1/A + 1/B)
726 # c = C(a/A+b/B)
727 # A = 1/K0, B = 1/Ku
728 sigma = 1.0 / (K0 + Ku)
729 mu = sigma * (x0[dim] * K0 + xu_i[i, dim] * Ku)
730 # Generate normal deviates for this dimension.
731 x_n[i * nsamples : (i + 1) * nsamples, dim] = np.random.normal(
732 mu, np.sqrt(sigma), [nsamples]
733 )
734
735 u_kn = np.zeros([numbrellas, nsamples * numbrellas], np.float64)
736 # Compute reduced potential due to V0.
737 u_n = beta * (K0 / 2) * np.sum((x_n[:, :] - x0) ** 2, axis=1)
738 for k in range(numbrellas):
739 # reduced potential due to umbrella k
740 uu = beta * (Ku / 2) * np.sum((x_n[:, :] - xu_i[k, :]) ** 2, axis=1)
741 u_kn[k, :] = u_n + uu
742
743 return u_kn, u_n, x_n, f_k_analytical
744
745
746 nbinsperdim = 15
747 gridscale = 0.2
748 nsamples = 1000
749 ndim = 1
750 K0 = 20.0
751 Ku = 100.0
752 print("============================================")
753 print(" Test 1: 1D free energy profile ")
754 print("============================================")
755
756 xrange = [[-3, 3]]
757 ndim = 1
758 u_kn, u_n, x_n, f_k_analytical = generate_fes_data(
759 K0=K0,
760 Ku=Ku,
761 ndim=ndim,
762 nbinsperdim=nbinsperdim,
763 nsamples=nsamples,
764 gridscale=gridscale,
765 xrange=xrange,
766 )
767 numbrellas = (np.shape(u_kn))[0]
768 N_k = nsamples * np.ones([numbrellas], int)
769 print("Solving for free energies of state ...")
770 mbar = MBAR(u_kn, N_k)
771
772 # Histogram bins are indexed using the scheme:
773 # index = 1 + np.floor((x[0] - xmin)/dx) + nbins*np.floor((x[1] - xmin)/dy)
774 # index = 0 is reserved for samples outside of the allowed domain
775 xmin = gridscale * (np.min(xrange[0][0]) - 1 / 2.0)
776 xmax = gridscale * (np.max(xrange[0][1]) + 1 / 2.0)
777 dx = (xmax - xmin) / nbinsperdim
778 nbins = 1 + nbinsperdim**ndim
779 bin_edges = np.linspace(xmin, xmax, nbins) # list of bin edges.
780 bin_centers = np.zeros([nbins, ndim], np.float64)
781
782 ibin = 1
783 fes_analytical = np.zeros([nbins], np.float64)
784 minmu2 = 1000000
785 zeroindex = 0
786 # construct the bins and the fes
787 for i in range(nbinsperdim):
788 xbin = xmin + dx * (i + 0.5)
789 bin_centers[ibin, 0] = xbin
790 mu2 = xbin * xbin
791 if mu2 < minmu2:
792 minmu2 = mu2
793 zeroindex = ibin
794 fes_analytical[ibin] = K0 * mu2 / 2.0
795 ibin += 1
796 fzero = fes_analytical[zeroindex]
797 fes_analytical -= fzero
798 fes_analytical[0] = 0
799
800 bin_n = np.zeros([numbrellas * nsamples], int)
801 # Determine indices of those within bounds.
802 within_bounds = (x_n[:, 0] >= xmin) & (x_n[:, 0] < xmax)
803 # Determine states for these.
804 bin_n[within_bounds] = 1 + np.floor((x_n[within_bounds, 0] - xmin) / dx)
805 # Determine indices of bins that are not empty.
806 bin_counts = np.zeros([nbins], int)
807 for i in range(nbins):
808 bin_counts[i] = (bin_n == i).sum()
809
810 # Compute fre energy profile, first with histograms
811 print("Solving for free energies of state to initialize free energy profile...")
812 mbar_options = dict()
813 mbar_options["verbose"] = False
814 fes = FES(u_kn, N_k, mbar_options=mbar_options)
815 print("Computing free energy profile ...")
816 histogram_parameters = dict()
817 histogram_parameters["bin_edges"] = bin_edges
818 fes.generate_fes(u_n, x_n, histogram_parameters=histogram_parameters)
819 results = fes.get_fes(
820 bin_centers[:, 0],
821 reference_point="from-specified",
822 fes_reference=0.0,
823 uncertainty_method="analytical",
824 )
825 f_ih = results["f_i"]
826 df_ih = results["df_i"]
827
828 # now estimate the PDF with a kde
829 kde_parameters = dict()
830 kde_parameters["bandwidth"] = dx / 3.0
831 fes.generate_fes(u_n, x_n, fes_type="kde", n_bootstraps=20, kde_parameters=kde_parameters)
832 results_kde = fes.get_fes(
833 bin_centers,
834 reference_point="from-specified",
835 fes_reference=0.0,
836 uncertainty_method="bootstrap",
837 )
838 f_ik = results_kde["f_i"]
839 df_ik = results_kde["df_i"]
840
841 # Show free energy and uncertainty of each occupied bin relative to lowest
842 # free energy
843
844 print("1D free energy profile:")
845 print(f"{bin_counts[0]:d} counts out of {numbrellas * nsamples:d} counts not in any bin")
846 print(
847 f"{'bin':>8s} {'x':>6s} {'N':>8s} {'true':>10s}"
848 f"{'f_hist':>10s} {'err_hist':>10s} {'df_hist':>10s} {'sig_hist':>8s}"
849 f"{'f_kde':>10s} {'err_kde':>10s} {'df_kde':>10s} {'sig_kde':>8s}"
850 )
851
852 for i in range(1, nbins):
853 error_h = fes_analytical[i] - f_ih[i]
854 error_k = fes_analytical[i] - f_ik[i]
855 if df_ih[i] > 0:
856 stdevs_h = np.abs(error_h) / df_ih[i]
857 else:
858 stdevs_h = 0
859
860 if df_ik[i] > 0:
861 stdevs_k = np.abs(error_k) / df_ik[i]
862 else:
863 stdevs_k = 0
864
865 print(
866 f"{i:>8d} {bin_centers[i, 0]:>6.2f} {bin_counts[i]:>8d} {fes_analytical[i]:>10.3f}"
867 f"{f_ih[i]:>10.3f} {error_h:>10.3f} {df_ih[i]:>10.3f} {stdevs_h:>8.2f}"
868 f"{f_ik[i]:>10.3f} {error_k:>10.3f} {df_ik[i]:>10.3f} {stdevs_k:>8.2f}"
869 )
870
871 print("============================================")
872 print(" Test 2: 2D free energy surface ")
873 print("============================================")
874
875 xrange = [[-3, 3], [-3, 3]]
876 ndim = 2
877 nsamples = 500
878 u_kn, u_n, x_n, f_k_analytical = generate_fes_data(
879 K0=K0,
880 Ku=Ku,
881 ndim=ndim,
882 nbinsperdim=nbinsperdim,
883 nsamples=nsamples,
884 gridscale=gridscale,
885 xrange=xrange,
886 )
887 numbrellas = np.shape(u_kn)[0]
888 N_k = nsamples * np.ones([numbrellas], int)
889 print("Solving for free energies of state ...")
890 mbar = MBAR(u_kn, N_k)
891
892 # The dimensionless free energy is the integral of this, and can be computed as:
893 # f(beta,K) = - ln [ (2*np.pi/(Ko+Ku))^(d/2) exp[ -Ku*Ko mu' mu / 2(Ko +Ku)]
894 # f(beta,K) - fzero = -Ku*Ko / 2(Ko+Ku) = 1/(1/(Ku/2) + 1/(K0/2))
895 # for computing harmonic samples
896
897 # Can compare the free energies computed with MBAR if desired with
898 # f_k_analytical
899
900 # Histogram bins are indexed using the scheme:
901 # index = 1 + np.floor((x[0] - xmin)/dx) + nbins*np.floor((x[1] - xmin)/dy)
902 # index = 0 is reserved for samples outside of the allowed domain
903
904 xmin = gridscale * (np.min(xrange[0][0]) - 1 / 2.0)
905 xmax = gridscale * (np.max(xrange[0][1]) + 1 / 2.0)
906 ymin = gridscale * (np.min(xrange[1][0]) - 1 / 2.0)
907 ymax = gridscale * (np.max(xrange[1][1]) + 1 / 2.0)
908 dx = (xmax - xmin) / nbinsperdim
909 dy = (ymax - ymin) / nbinsperdim
910 nbins = 1 + nbinsperdim**ndim
911 bin_centers = np.zeros([nbins, ndim], np.float64)
912
913 ibin = 1 # first reserved for something outside.
914 fes_analytical = np.zeros([nbins], np.float64)
915 minmu2 = 1000000
916 zeroindex = 0
917 # construct the bins and the fes
918 for i in range(nbinsperdim):
919 xbin = xmin + dx * (i + 0.5)
920 for j in range(nbinsperdim):
921 # Determine (x,y) of bin center.
922 ybin = ymin + dy * (j + 0.5)
923 bin_centers[ibin, 0] = xbin
924 bin_centers[ibin, 1] = ybin
925 mu2 = xbin * xbin + ybin * ybin
926 if mu2 < minmu2:
927 minmu2 = mu2
928 zeroindex = ibin
929 fes_analytical[ibin] = K0 * mu2 / 2.0
930 ibin += 1
931 fzero = fes_analytical[zeroindex]
932 fes_analytical -= fzero
933
934 bin_n = np.zeros([numbrellas * nsamples], int)
935 # Determine indices of those within bounds.
936 within_bounds = (x_n[:, 0] >= xmin) & (x_n[:, 0] < xmax) & (x_n[:, 1] >= ymin) & (x_n[:, 1] < ymax)
937 # Determine states for these.
938 xgrid = (x_n[within_bounds, 0] - xmin) / dx
939 ygrid = (x_n[within_bounds, 1] - ymin) / dy
940 bin_n[within_bounds] = 1 + xgrid.astype(int) + nbinsperdim * ygrid.astype(int)
941
942 # Determine indices of bins that are not empty.
943 bin_counts = np.zeros([nbins], int)
944 for i in range(nbins):
945 bin_counts[i] = (bin_n == i).sum()
946
947 # Compute free energy surface, first using histograms weighted with MBAR
948 print("Computing free energy surface ...")
949 fes = FES(u_kn, N_k)
950
951 # for 2D bins, we input a list of the bin edges in each dimension.
952 histogram_parameters["bin_edges"] = [
953 np.linspace(xmin, xmax, nbinsperdim + 1),
954 np.linspace(ymin, ymax, nbinsperdim + 1),
955 ] # list of histogram edges.
956 fes.generate_fes(u_n, x_n, fes_type="histogram", histogram_parameters=histogram_parameters)
957 delta = 0.0001 # to break ties in things being too close.
958
959 results = fes.get_fes(
960 bin_centers + delta,
961 reference_point="from-specified",
962 fes_reference=[0, 0],
963 uncertainty_method="analytical",
964 )
965 f_i = results["f_i"]
966 df_i = results["df_i"]
967
968 # now generate the kernel density estimate
969 kde_parameters["bandwidth"] = 0.5 * dx
970 fes.generate_fes(u_n, x_n, fes_type="kde", kde_parameters=kde_parameters)
971 results_kde = fes.get_fes(bin_centers, reference_point="from-specified", fes_reference=[0, 0])
972 f_ik = results_kde["f_i"]
973
974 # Show free energy and uncertainty of each occupied bin relative to lowest
975 # free energy
976 print("2D FES:")
977
978 print(f"{bin_counts[0]:d} counts out of {numbrellas * nsamples:d} counts not in any bin")
979 print("Uncertainties only calculated for histogram methods")
980 print(
981 f"{'bin':>8s} {'x':>6s} {'y':>6s} {'N':>8s} {'f_hist':>10s} {'f_kde':>10s} {'true':>10s} {'err_hist':>10s} {'err_kde':>10s} {'df':>10s} {'sigmas':>8s}"
982 )
983 for i in range(1, nbins):
984 if i == zeroindex:
985 stdevs = 0
986 df_i[0] = 0
987 else:
988 error = fes_analytical[i] - f_i[i]
989 if df_i[i] > 0:
990 stdevs = np.abs(error) / df_i[i]
991 else:
992 stdevs = np.nan
993 print(
994 f"{i:>8d} "
995 f"{bin_centers[i, 0]:>6.2f} "
996 f"{bin_centers[i, 1]:>6.2f} "
997 f"{bin_counts[i]:>8d} "
998 f"{f_i[i]:>10.3f} "
999 f"{f_ik[i]:>10.3f} "
1000 f"{fes_analytical[i]:>10.3f} "
1001 f"{error:>10.3f} "
1002 f"{fes_analytical[i]-f_ik[i]:>10.3f} "
1003 f"{df_i[i]:>10.3f} "
1004 f"{stdevs:>8.2f}"
1005 )