| 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 |
generateplots = True |
| 24 |
try: |
| 25 |
import matplotlib |
| 26 |
|
| 27 |
matplotlib.use("Agg") |
| 28 |
import matplotlib.pyplot as plt |
| 29 |
except ImportError: |
| 30 |
print("!!! Can't import matplotlib, will not produce graphs.") |
| 31 |
generateplots = False |
| 32 |
|
| 33 |
import numpy |
| 34 |
from pymbar import testsystems, MBAR, confidenceintervals |
| 35 |
from pymbar.utils import ParameterError, DataError |
| 36 |
|
| 37 |
import logging |
| 38 |
import sys |
| 39 |
|
| 40 |
logging.basicConfig(stream=sys.stdout, level=logging.INFO) |
| 41 |
|
| 42 |
# ============================================================================================= |
| 43 |
# PARAMETERS |
| 44 |
# ============================================================================================= |
| 45 |
|
| 46 |
K_k = numpy.array([25, 16, 9, 4, 1, 1]) # spring constants for each state |
| 47 |
O_k = numpy.array([0, 1, 2, 3, 4, 5]) # offsets for spring constants |
| 48 |
# number of samples from each state (can be zero for some states) |
| 49 |
N_k = numpy.array([2000, 2000, 2000, 2000, 2000, 0]) |
| 50 |
beta = 1.0 # inverse temperature for all simulations |
| 51 |
nreplicates = 200 # number of replicates of experiment for testing uncertainty estimate |
| 52 |
|
| 53 |
|
| 54 |
# the observable, one of 'mean square displacement','position', or 'potential energy' |
| 55 |
observe = "position^2" |
| 56 |
|
| 57 |
# Uncomment the following line to seed the random number generated to produce reproducible output. |
| 58 |
numpy.random.seed(0) |
| 59 |
|
| 60 |
# ============================================================================================= |
| 61 |
# MAIN |
| 62 |
# ============================================================================================= |
| 63 |
|
| 64 |
# Determine number of simulations. |
| 65 |
K = numpy.size(N_k) |
| 66 |
if numpy.shape(K_k) != numpy.shape(N_k): |
| 67 |
raise DataError("K_k and N_k must have same dimensions.") |
| 68 |
|
| 69 |
# Determine maximum number of samples to be drawn for any state. |
| 70 |
N_max = numpy.max(N_k) |
| 71 |
|
| 72 |
# Compute widths of sampled distributions. |
| 73 |
# For a harmonic oscillator with spring constant K, |
| 74 |
# x ~ Normal(x_0, sigma^2), where sigma = 1/sqrt(beta K) |
| 75 |
sigma_k = (beta * K_k) ** -0.5 |
| 76 |
print("Gaussian widths:") |
| 77 |
print(sigma_k) |
| 78 |
|
| 79 |
# Compute the absolute dimensionless free energies of each oscillator analytically. |
| 80 |
# f = - ln(sqrt((2 pi)/(beta K)) ) |
| 81 |
print("Computing dimensionless free energies analytically...") |
| 82 |
f_k_analytical = -numpy.log(numpy.sqrt(2 * numpy.pi) * sigma_k) |
| 83 |
|
| 84 |
# Compute true free energy differences. |
| 85 |
Deltaf_ij_analytical = numpy.zeros([K, K], dtype=numpy.float64) |
| 86 |
for i in range(0, K): |
| 87 |
for j in range(0, K): |
| 88 |
Deltaf_ij_analytical[i, j] = f_k_analytical[j] - f_k_analytical[i] |
| 89 |
|
| 90 |
# Compute ensemble averages analytically |
| 91 |
if observe == "RMS displacement": |
| 92 |
A_k_analytical = sigma_k # mean square displacement |
| 93 |
elif observe == "potential energy": |
| 94 |
A_k_analytical = 1 / (2 * beta) * numpy.ones([K], float) # By eqipartition |
| 95 |
elif observe == "position": |
| 96 |
A_k_analytical = O_k # observable is the position |
| 97 |
elif observe == "position^2": |
| 98 |
A_k_analytical = (1 + beta * K_k * O_k**2) / (beta * K_k) # observable is the position^2 |
| 99 |
else: |
| 100 |
raise ParameterError("Observable %s not known." % observe) |
| 101 |
|
| 102 |
# DEBUG info |
| 103 |
print( |
| 104 |
"This script will perform %d replicates of an experiment where samples are drawn from %d harmonic oscillators." |
| 105 |
% (nreplicates, K) |
| 106 |
) |
| 107 |
print("The harmonic oscillators have equilibrium positions") |
| 108 |
print(O_k) |
| 109 |
print("and spring constants") |
| 110 |
print(K_k) |
| 111 |
print( |
| 112 |
"and the following number of samples will be drawn from each (can be zero if no samples drawn):" |
| 113 |
) |
| 114 |
print(N_k) |
| 115 |
print("") |
| 116 |
|
| 117 |
# Conduct a number of replicates of the same experiment |
| 118 |
replicates_observable = [] # storage for one hash for each replicate |
| 119 |
replicates_standobservable = [] # storage for one hash for each replicate |
| 120 |
replicates_df = [] # storage for one hash for each replicate |
| 121 |
replicates_fdf = [] # storage for one hash for final observable |
| 122 |
|
| 123 |
for replicate_index in range(0, nreplicates): |
| 124 |
print("Performing replicate %d / %d" % (replicate_index + 1, nreplicates)) |
| 125 |
|
| 126 |
# Initialize a hash to store data for this replicate. |
| 127 |
replicate_df = {} |
| 128 |
replicate_fdf = {} |
| 129 |
replicate_bar = {} |
| 130 |
replicate_observable = {} |
| 131 |
replicate_standobservable = {} |
| 132 |
|
| 133 |
# ============================================================================================= |
| 134 |
# Generate independent data samples from K one-dimensional harmonic oscillators centered at q = 0. |
| 135 |
# ============================================================================================= |
| 136 |
|
| 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") |
| 141 |
|
| 142 |
# get the unreduced energies |
| 143 |
U_kln = u_kln / beta |
| 144 |
|
| 145 |
# ============================================================================================= |
| 146 |
# Estimate free energies and expectations. |
| 147 |
# ============================================================================================= |
| 148 |
|
| 149 |
# Initialize the MBAR class, determining the free energies. |
| 150 |
# use fast Newton-Raphson solver |
| 151 |
mbar = MBAR(u_kln, N_k, relative_tolerance=1.0e-10, verbose=False, solver_protocol="robust") |
| 152 |
results = mbar.compute_free_energy_differences() |
| 153 |
Deltaf_ij_estimated = results["Delta_f"] |
| 154 |
dDeltaf_ij_estimated = results["dDelta_f"] |
| 155 |
|
| 156 |
# Compute error from analytical free energy differences. |
| 157 |
Deltaf_ij_error = Deltaf_ij_estimated - Deltaf_ij_analytical |
| 158 |
|
| 159 |
# Estimate the expectation of the mean-squared displacement at each condition. |
| 160 |
if observe == "RMS displacement": |
| 161 |
A_kn = numpy.zeros([K, K, N_max], dtype=numpy.float64) |
| 162 |
for k in range(0, K): |
| 163 |
for l in range(0, K): |
| 164 |
# observable is the squared displacement |
| 165 |
A_kn[k, l, 0 : N_k[k]] = (x_kn[k, 0 : N_k[k]] - O_k[l]) ** 2 |
| 166 |
|
| 167 |
# observable is the potential energy, a 3D array since the potential energy is a function of |
| 168 |
# thermodynamic state |
| 169 |
elif observe == "potential energy": |
| 170 |
A_kn = U_kln |
| 171 |
|
| 172 |
# observable for estimation is the position |
| 173 |
elif observe == "position": |
| 174 |
A_kn = numpy.zeros([K, N_max], dtype=numpy.float64) |
| 175 |
for k in range(0, K): |
| 176 |
A_kn[k, 0 : N_k[k]] = x_kn[k, 0 : N_k[k]] |
| 177 |
|
| 178 |
elif observe == "position^2": |
| 179 |
A_kn = numpy.zeros([K, N_max], dtype=numpy.float64) |
| 180 |
for k in range(0, K): |
| 181 |
A_kn[k, 0 : N_k[k]] = x_kn[k, 0 : N_k[k]] ** 2 |
| 182 |
|
| 183 |
results = mbar.compute_expectations(A_kn) |
| 184 |
A_k_estimated = results["mu"] |
| 185 |
dA_k_estimated = results["sigma"] |
| 186 |
As_k_estimated = numpy.zeros([K], numpy.float64) |
| 187 |
dAs_k_estimated = numpy.zeros([K], numpy.float64) |
| 188 |
|
| 189 |
# 'standard' expectation averages |
| 190 |
ifzero = numpy.array(N_k != 0) |
| 191 |
|
| 192 |
for k in range(K): |
| 193 |
if ifzero[k]: |
| 194 |
if (observe == "position") or (observe == "position^2"): |
| 195 |
As_k_estimated[k] = numpy.average(A_kn[k, 0 : N_k[k]]) |
| 196 |
dAs_k_estimated[k] = numpy.sqrt(numpy.var(A_kn[k, 0 : N_k[k]]) / (N_k[k] - 1)) |
| 197 |
elif (observe == "RMS displacement") or (observe == "potential energy"): |
| 198 |
As_k_estimated[k] = numpy.average(A_kn[k, k, 0 : N_k[k]]) |
| 199 |
dAs_k_estimated[k] = numpy.sqrt(numpy.var(A_kn[k, k, 0 : N_k[k]]) / (N_k[k] - 1)) |
| 200 |
|
| 201 |
print(A_k_estimated) |
| 202 |
print(dA_k_estimated) |
| 203 |
|
| 204 |
# need to additionally transform to get the square root |
| 205 |
if observe == "RMS displacement": |
| 206 |
A_k_estimated = numpy.sqrt(A_k_estimated) |
| 207 |
As_k_estimated = numpy.sqrt(As_k_estimated) |
| 208 |
|
| 209 |
# Compute error from analytical observable estimate. |
| 210 |
dA_k_estimated = dA_k_estimated / (2 * A_k_estimated) |
| 211 |
dAs_k_estimated = dAs_k_estimated / (2 * As_k_estimated) |
| 212 |
|
| 213 |
A_k_error = A_k_estimated - A_k_analytical |
| 214 |
As_k_error = As_k_estimated - A_k_analytical |
| 215 |
|
| 216 |
# ============================================================================================= |
| 217 |
# Store data for this replicate. |
| 218 |
# ============================================================================================= |
| 219 |
replicate_df["estimated"] = Deltaf_ij_estimated.copy() |
| 220 |
replicate_df["destimated"] = numpy.asarray(dDeltaf_ij_estimated.copy()) |
| 221 |
replicate_df["error"] = Deltaf_ij_error.copy() |
| 222 |
replicates_df.append(replicate_df) |
| 223 |
|
| 224 |
replicate_observable["estimated"] = A_k_estimated.copy() |
| 225 |
replicate_observable["destimated"] = numpy.asarray(dA_k_estimated.copy()) |
| 226 |
replicate_observable["error"] = A_k_error.copy() |
| 227 |
replicates_observable.append(replicate_observable) |
| 228 |
|
| 229 |
replicate_standobservable["estimated"] = As_k_estimated[ifzero].copy() |
| 230 |
replicate_standobservable["destimated"] = dAs_k_estimated[ifzero].copy() |
| 231 |
replicate_standobservable["error"] = As_k_error[ifzero].copy() |
| 232 |
replicates_standobservable.append(replicate_standobservable) |
| 233 |
|
| 234 |
|
| 235 |
# compute the probability distribution of all states |
| 236 |
print("Free energies") |
| 237 |
# compute anderson/darling statistics |
| 238 |
|
| 239 |
D = confidenceintervals.anderson_darling(replicates_df, K) |
| 240 |
print("Anderson-Darling Metrics (see README.md)") |
| 241 |
print(D) |
| 242 |
if generateplots: |
| 243 |
confidenceintervals.qq_plot( |
| 244 |
replicates_df, K, title="Q-Q plots of free energy differences", filename="QQdf.pdf" |
| 245 |
) |
| 246 |
( |
| 247 |
alpha_fij, |
| 248 |
Pobs_fij, |
| 249 |
Plow_fij, |
| 250 |
Phigh_fij, |
| 251 |
dPobs_fij, |
| 252 |
Pnorm_fij, |
| 253 |
) = confidenceintervals.generate_confidence_intervals(replicates_df, K) |
| 254 |
|
| 255 |
print("Standard ensemble averaged observables") |
| 256 |
( |
| 257 |
alpha_Ai, |
| 258 |
Pobs_Ai, |
| 259 |
Plow_Ai, |
| 260 |
Phigh_Ai, |
| 261 |
dPobs_Ai, |
| 262 |
Pnorm_Ai, |
| 263 |
) = confidenceintervals.generate_confidence_intervals( |
| 264 |
replicates_standobservable, numpy.sum(ifzero) |
| 265 |
) |
| 266 |
D = confidenceintervals.anderson_darling(replicates_standobservable, numpy.sum(ifzero)) |
| 267 |
print("Anderson-Darling Metrics (see README.md)") |
| 268 |
print(D) |
| 269 |
if generateplots: |
| 270 |
confidenceintervals.qq_plot( |
| 271 |
replicates_standobservable, |
| 272 |
numpy.sum(ifzero), |
| 273 |
title="Q-Q plots of ensemble averaged observables \n with standard error estimates", |
| 274 |
filename="QQstandardobserve.pdf", |
| 275 |
) |
| 276 |
|
| 277 |
print("MBAR ensemble averaged observables") |
| 278 |
( |
| 279 |
alpha_Ai, |
| 280 |
Pobs_Ai, |
| 281 |
Plow_Ai, |
| 282 |
Phigh_Ai, |
| 283 |
dPobs_Ai, |
| 284 |
Pnorm_Ai, |
| 285 |
) = confidenceintervals.generate_confidence_intervals(replicates_observable, K) |
| 286 |
D = confidenceintervals.anderson_darling(replicates_observable, K) |
| 287 |
print("Anderson-Darling Metrics (see README.md)") |
| 288 |
print(D) |
| 289 |
if generateplots: |
| 290 |
confidenceintervals.qq_plot( |
| 291 |
replicates_observable, |
| 292 |
K, |
| 293 |
title="Q-Q plots of ensemble averaged observables using MBAR", |
| 294 |
filename="QQMBARobserve.pdf", |
| 295 |
) |
| 296 |
|
| 297 |
|
| 298 |
if generateplots: |
| 299 |
override = { |
| 300 |
"family": "sans-serif", |
| 301 |
"verticalalignment": "bottom", |
| 302 |
"horizontalalignment": "center", |
| 303 |
"weight": "bold", |
| 304 |
"size": 30, |
| 305 |
} |
| 306 |
|
| 307 |
formatstrings = ["b-", "g-", "c-", "y-", "r-", "m-"] |
| 308 |
|
| 309 |
if generateplots: |
| 310 |
plt.figure(1) |
| 311 |
plt.axis([0.0, 4.0, 0.0, 1.0]) |
| 312 |
plt.plot(alpha_fij, Pnorm_fij, "k-", label="Normal") |
| 313 |
|
| 314 |
for k in range(1, K): |
| 315 |
replicates_fdf = [] |
| 316 |
for replicate_ij in replicates_df: |
| 317 |
replicate = {} |
| 318 |
replicate["estimated"] = replicate_ij["estimated"][0, k] |
| 319 |
replicate["destimated"] = replicate_ij["destimated"][0, k] |
| 320 |
replicate["error"] = replicate_ij["error"][0, k] |
| 321 |
replicates_fdf.append(replicate) |
| 322 |
# compute the distribution of the end states only |
| 323 |
print("") |
| 324 |
print(" ==== State %d alone with MBAR ===== " % (k)) |
| 325 |
( |
| 326 |
alpha_f, |
| 327 |
Pobs_f, |
| 328 |
Plow_f, |
| 329 |
Phigh_f, |
| 330 |
dPobs_f, |
| 331 |
Pnorm_f, |
| 332 |
) = confidenceintervals.generate_confidence_intervals(replicates_fdf, K) |
| 333 |
label = "State %d" % k |
| 334 |
if generateplots: |
| 335 |
plt.plot(alpha_f, Pobs_f, formatstrings[k - 1], label=label) |
| 336 |
|
| 337 |
if generateplots: |
| 338 |
plt.title("Cumulative Probabilty vs.\n Normal Distribution", size=24) |
| 339 |
plt.xlabel("Standard Deviations", size=18) |
| 340 |
plt.ylabel("Cumulative Probability", size=18) |
| 341 |
plt.legend(loc=4) |
| 342 |
plt.savefig("cumulative_probability_comparison_curves.pdf") |
| 343 |
|
| 344 |
if generateplots: |
| 345 |
plt.figure(2) |
| 346 |
plt.axis([0.0, 4.0, 0.0, 1.0]) |
| 347 |
plt.plot(alpha_fij, Pnorm_fij, "k-", label="Normal") |