Debian Codegraph @

examples/umbrella-sampling-fes/umbrella-sampling-advanced-fes.py

raw
1 """
2 Example illustrating the application of MBAR to compute a 1D free energy profile from an umbrella sampling simulation.
3
4 The data represents an umbrella sampling simulation for the chi torsion of a valine sidechain in lysozyme L99A with benzene bound in the cavity.
5
6 Reference:
7
8 [1] M. R. Shirts and Andrew L. Ferguson,
9 "Statistically optimal continuous potentials of mean force from
10 umbrella sampling and multistate reweighting" https://arxiv.org/abs/2001.01170
11
12 [2] D. L. Mobley, A. P. Graves, J. D. Chodera, A. C. McReynolds, B. K. Shoichet and K. A. Dill,
13 "Predicting absolute ligand binding free energies to a simple model site,"
14 Journal of Molecular Biology 371(4):1118-1134 (2007).
15 http://dx.doi.org/10.1016/j.jmb.2007.06.002
16 """
17
18 import copy
19 from timeit import default_timer as timer
20 import matplotlib
21
22 matplotlib.use("Agg")
23 import matplotlib.pyplot as plt
24 import numpy as np # numerical array library
25
26 import pymbar # multistate Bennett acceptance ratio
27 from pymbar import timeseries # timeseries analysis
28
29 kB = 1.381e-23 * 6.022e23 / 1000.0 # Boltzmann constant in kJ/mol/K
30 nplot = 1200
31 # set minimizer options to display.
32 optimize_options = {"disp": True, "tol": 10 ** (-8)}
33 # histogram is self explanatory. 'kde' is a kernel density approximation. Currently it uses a
34 # Gaussian kernel, but this can be adjusted in the kde_parameters section below.
35
36 methods = ["histogram", "kde", "unbiased-ml", "unbiased-map"]
37 mc_methods = ["unbiased-map"] # which methods to run MCMC sampling on (much slower).
38 # The code supports arbitrary powers of of B-splines (that are supported by scipy
39 # Just replace '3' with the desired degree below. 1-5 suggested.
40 spline_degree = 3
41 nspline = 11 # number of spline knots used for the fit.
42 n_bootstraps = 3 # should increase to ~50 for good statistics
43 mc_iterations = 1000 # could take a while?
44 smoothness_scalefac = 0.01
45 fig_suffix = "test1" # figure suffix for identifiability of the output!
46
47 colors = {}
48 descriptions = {}
49 colors["histogram"] = "k-"
50 colors["kde"] = "k:"
51 colors["biased-ml"] = "g-"
52 colors["biased-map"] = "g--"
53 colors["unbiased-ml"] = "b-"
54 colors["unbiased-map"] = "b--"
55 descriptions["histogram"] = "Histogram"
56 descriptions["kde"] = "Kernel density (Gaussian)"
57 descriptions["unbiased-ml"] = "Unbiased state maximum likelihood"
58 descriptions["unbiased-map"] = "Unbiased state maximum a posteriori"
59 descriptions["simple"] = "vFEP"
60 descriptions["biased-ml"] = "biased states maximum likelihood"
61 descriptions["biased-map"] = "biased states maximum a posteriori"
62
63 optimization_algorithm = "Newton-CG" # other good options are 'L-BFGS-B' and 'Custom-NR'
64 # optimization_algorithm = 'Custom-NR' #other good options are 'L-BFGS-B' and 'Custom-NR'
65 # below - information to load the data.
66 temperature = 300 # assume a single temperature -- can be overridden with data from center.dat
67 # Parameters
68 K = 26 # number of umbrellas
69 N_max = 501 # maximum number of snapshots/simulation
70 T_k = np.ones(K, float) * temperature # inital temperatures are all equal
71 beta = 1.0 / (kB * temperature) # inverse temperature of simulations (in 1/(kJ/mol))
72 chi_min = -180.0 # min for free energy profile
73 chi_max = +180.0 # max for free energy profile
74 # number of bins for 1D free energy profile. Note, does not have to correspond to the number of umbrellas at all.
75 nbins = 30
76
77 # Allocate storage for simulation data
78 N_k = np.zeros([K], np.int32) # N_k[k] is the number of snapshots from umbrella simulation k
79 # K_k[k] is the spring constant (in kJ/mol/deg**2) for umbrella simulation k
80 K_k = np.zeros([K], np.float64)
81 # chi0_k[k] is the spring center location (in deg) for umbrella simulation k
82 chi0_k = np.zeros([K], np.float64)
83 # chi_kn[k,n] is the torsion angle (in deg) for snapshot n from umbrella simulation k
84 chi_kn = np.zeros([K, N_max], np.float64)
85 # u_kn[k,n] is the reduced potential energy without umbrella restraints of snapshot n of umbrella simulation k
86 u_kn = np.zeros([K, N_max], np.float64)
87 g_k = np.zeros([K], np.float32)
88
89 # Read in umbrella spring constants and centers.
90 with open("data/centers.dat") as infile:
91 lines = infile.readlines()
92 for k in range(K):
93 # Parse line k.
94 line = lines[k]
95 tokens = line.split()
96 chi0_k[k] = float(tokens[0]) # spring center locatiomn (in deg)
97 # spring constant (read in kJ/mol/rad**2, converted to kJ/mol/deg**2)
98 K_k[k] = float(tokens[1]) * (np.pi / 180) ** 2
99 if len(tokens) > 2:
100 T_k[k] = float(tokens[2]) # temperature the kth simulation was run at.
101
102 beta_k = 1.0 / (kB * T_k) # beta factor for the different temperatures
103 different_temperatures = True
104 if min(T_k) == max(T_k):
105 # if all the temperatures are the same, then we don't have to read in energies.
106 different_temperatures = False
107
108 # Read the simulation data
109 for k in range(K):
110 # Read torsion angle data.
111 filename = f"data/prod{k:d}_dihed.xvg"
112 print(f"Reading {filename}...")
113 with open(filename) as infile:
114 lines = infile.readlines()
115
116 # Parse data.
117 n = 0
118 for line in lines:
119 if line[0] != "#" and line[0] != "@":
120 tokens = line.split()
121 chi = float(tokens[1]) # torsion angle
122 # wrap chi_kn to be within [-180,+180)
123 while chi < -180.0:
124 chi += 360.0
125 while chi >= +180.0:
126 chi -= 360.0
127 chi_kn[k, n] = chi
128
129 n += 1
130 N_k[k] = n
131
132 if different_temperatures: # if different temperatures are specified the metadata file,
133 # then we need the energies to compute the free energy profile
134 # Read energies
135 filename = f"data/prod{k:d}_energies.xvg"
136 print(f"Reading {filename}...")
137 with open(filename) as infile:
138 lines = infile.readlines()
139
140 # Parse data.
141 n = 0
142 for line in lines:
143 if line[0] != "#" and line[0] != "@":
144 tokens = line.split()
145 # reduced potential energy without umbrella restraint
146 u_kn[k, n] = beta_k[k] * (float(tokens[2]) - float(tokens[1]))
147 n += 1
148
149 # Compute correlation times for potential energy and chi
150 # timeseries. If the temperatures differ, use energies to determine samples; otherwise, use the cosine of chi
151
152 if different_temperatures:
153 g_k[k] = timeseries.statistical_inefficiency(u_kn[k, :], u_kn[k, 0 : N_k[k]])
154 print(f"Correlation time for set {k:5d} is {g_k[k]:10.3f}")
155 indices = timeseries.subsample_correlated_data(u_kn[k, 0 : N_k[k]])
156 else:
157 chi_radians = chi_kn[k, 0 : N_k[k]] / (180.0 / np.pi)
158 g_cos = timeseries.statistical_inefficiency(np.cos(chi_radians))
159 g_sin = timeseries.statistical_inefficiency(np.sin(chi_radians))
160 print(f"g_cos = {g_cos:.1f} | g_sin = {g_sin:.1f}")
161 # g_k[k] = max(g_cos, g_sin) #TODO: switch?
162 g_k[k] = 1
163 print(f"Correlation time for set {k:5d} is {g_k[k]:10.3f}")
164 indices = timeseries.subsample_correlated_data(chi_radians, g=g_k[k])
165 # Subsample data.
166 N_k[k] = len(indices)
167 u_kn[k, 0 : N_k[k]] = u_kn[k, indices]
168 chi_kn[k, 0 : N_k[k]] = chi_kn[k, indices]
169
170 N_max = np.max(N_k) # shorten the array size
171 # u_kln[k,l,n] is the reduced potential energy of snapshot n from umbrella simulation k evaluated at umbrella l
172 u_kln = np.zeros([K, K, N_max], np.float64)
173
174 # Set zero of u_kn -- this is arbitrary.
175 u_kn -= u_kn.min()
176
177 # Construct torsion bins
178 # compute bin centers
179
180 bin_center_i = np.zeros([nbins], np.float64)
181 bin_edges = np.linspace(chi_min, chi_max, nbins + 1)
182 for i in range(nbins):
183 bin_center_i[i] = 0.5 * (bin_edges[i] + bin_edges[i + 1])
184
185 N = np.sum(N_k)
186 chi_n = pymbar.utils.kn_to_n(chi_kn, N_k=N_k)
187
188 # Evaluate reduced energies in all umbrellas
189 print("Evaluating reduced potential energies...")
190 for k in range(K):
191 for n in range(N_k[k]):
192 # Compute minimum-image torsion deviation from umbrella center l
193 dchi = chi_kn[k, n] - chi0_k
194 for l in range(K):
195 if abs(dchi[l]) > 180.0:
196 dchi[l] = 360.0 - abs(dchi[l])
197
198 # Compute energy of snapshot n from simulation k in umbrella potential l
199 u_kln[k, :, n] = u_kn[k, n] + beta_k[k] * (K_k / 2.0) * dchi**2
200
201 # initialize free energy profile with the data collected.
202 basefes = pymbar.FES(u_kln, N_k, verbose=True)
203
204
205 def bias_potential(x, k):
206 """Define the bias potentials needed for umbrella sampling"""
207 dchi = x - chi0_k[k]
208 # vectorize the conditional
209 i = np.fabs(dchi) > 180.0
210 dchi = i * (360.0 - np.fabs(dchi)) + (1 - i) * dchi
211 return beta_k[k] * (K_k[k] / 2.0) * dchi**2
212
213
214 def deltag(c, scalef=1, n=nspline):
215 """bias on the smoothness, including periodicity. Normalization is indepednent of parameters, so we ignore.
216 consider periodicity later!!
217 """
218 cdiff = np.diff(c)
219 logp = -scalef / n * (np.sum(cdiff**2))
220 return logp
221
222
223 def ddeltag(c, scalef=1, n=nspline):
224 r"""derivative of the log prior above
225
226 The logprior is \sum_{i}^{C-1} - scalef*(c_{i+1} - c_{i})^2
227 this is unnormalized. However, the normalization is independent of the values of the parameters, it only
228 depends on the hyperparameter a, so we can omit it in the normalization.
229
230 However, we fix c[1] to be zero. So we are actually minimizing -scalef (c1)^2 + \sum_{i=1}^{C-1} - scalef*(c_{i+1} - c_{i})^2
231 So the derivative is -2*scalef*[c[1]-c[2],c[1]+2*c[2]-c[3],c[2]+2*c[3]-c[4], . . ., c[C-1]-c[C]]
232
233 Finally, for the minimization, we are the first coefficient to zero, and it's not allowed to move.
234 so we shift everything over by
235 """
236 cdiff = np.diff(c)
237 lenc = len(c)
238 dlogp = np.zeros(lenc)
239 dlogp[0 : lenc - 1] = cdiff
240 dlogp[1:lenc] -= cdiff
241 # c[0] only occurs in the first two entries. We ignore the 0th (no derivative) and in the second, it's: 2a*(c[0]-2c[1]+c[2]), so
242 # settting it zero is equal to ignoring it.
243 dlogp = (2 * scalef / n) * dlogp
244 return dlogp[1:]
245
246
247 def dddeltag(c, scalef=1, n=nspline):
248 r"""
249 Hessian of the log prior above
250
251 The logprior is \sum_{i}^{C-1} - scalef*(c_{i+1} - c_{i})^2
252 this is unnormalized. However, the normalization is independent of the values of the parameters, it only
253 depends on the hyperparameter a, so we can omit it in the normalization
254 The derivative is -2*scalef*[c[1]-c[2],c[1]+2*c[2]-c[3],c[2]+2*c[3]-c[4], . . ., c[C-1]-c[C]]
255 so the hessian willl be a constant matrix. Will have -2 down diagonal, 1 on off diagonal, except for
256 first and last rows
257 """
258 cdiff = np.diff(c)
259 lenc = len(c)
260 ddlogp = np.zeros([lenc, lenc])
261 np.fill_diagonal(ddlogp, -2.0)
262 np.fill_diagonal(ddlogp[1:], 1.0)
263 np.fill_diagonal(ddlogp[:, 1:], 1.0)
264 ddlogp[0, 0] = -1
265 ddlogp[lenc - 1, lenc - 1] = -1
266 ddlogp = (2 * scalef / n) * ddlogp
267 # the first variable is set to zero in the MAP.
268 return ddlogp[1:, 1:]
269
270
271 times = {} # keep track of time elaped each method takes
272
273 xplot = np.linspace(chi_min, chi_max, nplot) # number of points we are plotting
274 f_i_kde = None # We check later if these have been defined or not
275 # the data we used initially to parameterize points, from the KDE
276 xstart = np.linspace(chi_min, chi_max, nbins * 3)
277
278 feses = {}
279 for methodfull in methods:
280 # create a fresh copy of the initialized fes object. Operate on that within the loop.
281 # do the deepcopy here since there seem to be issues if it's done after data is added
282 # For example, the scikit-learn kde object fails to deepopy.
283
284 feses[methodfull] = copy.deepcopy(basefes)
285 fes = feses[methodfull]
286 start = timer()
287 if "-" in methodfull:
288 method, tominimize = methodfull.split("-")
289 else:
290 method = methodfull
291
292 if method == "histogram":
293 histogram_parameters = {}
294 histogram_parameters["bin_edges"] = bin_edges
295 fes.generate_fes(
296 u_kn,
297 chi_n,
298 fes_type="histogram",
299 histogram_parameters=histogram_parameters,
300 n_bootstraps=n_bootstraps,
301 )
302
303 if method == "kde":
304 kde_parameters = {}
305 # set the sigma for the spline.
306 kde_parameters["bandwidth"] = 0.5 * ((chi_max - chi_min) / nbins)
307 fes.generate_fes(
308 u_kn, chi_n, fes_type="kde", kde_parameters=kde_parameters, n_bootstraps=n_bootstraps
309 )
310
311 # save this for initializing other types
312 results = fes.get_fes(xstart, reference_point="from-lowest", uncertainty_method=None)
313 f_i_kde = results["f_i"] # kde results
314
315 if method in ["unbiased", "biased", "simple"]:
316 spline_parameters = {}
317 if method == "unbiased":
318 spline_parameters["spline_weights"] = "unbiasedstate"
319 elif method == "biased":
320 spline_parameters["spline_weights"] = "biasedstates"
321 elif method == "simple":
322 spline_parameters["spline_weights"] = "simplesum"
323
324 spline_parameters["nspline"] = nspline
325 spline_parameters["spline_initialize"] = "explicit"
326
327 # need to initialize: use KDE results for now (assumes KDE exists)
328 spline_parameters["xinit"] = xstart
329 if f_i_kde is not None:
330 spline_parameters["yinit"] = f_i_kde
331 else:
332 spline_parameters["yinit"] = np.zeros(len(xstart))
333
334 spline_parameters["xrange"] = [chi_min, chi_max]
335 # introduce klocal to force K to use local definition of K, otherwise would use global value of k.
336 spline_parameters["fkbias"] = [
337 (lambda x, klocal=k: bias_potential(x, klocal)) for k in range(K)
338 ]
339
340 spline_parameters["kdegree"] = spline_degree
341 spline_parameters["optimization_algorithm"] = optimization_algorithm
342 spline_parameters["optimize_options"] = optimize_options
343
344 if tominimize == "map":
345 spline_parameters["objective"] = "map"
346 spline_parameters["map_data"] = {}
347 spline_parameters["map_data"]["logprior"] = lambda x: deltag(
348 x, scalef=smoothness_scalefac
349 )
350 spline_parameters["map_data"]["dlogprior"] = lambda x: ddeltag(
351 x, scalef=smoothness_scalefac
352 )
353 spline_parameters["map_data"]["ddlogprior"] = lambda x: dddeltag(
354 x, scalef=smoothness_scalefac
355 )
356 else:
357 spline_parameters["objective"] = "ml"
358 spline_parameters["map_data"] = None
359
360 fes.generate_fes(
361 u_kn,
362 chi_n,
363 fes_type="spline",
364 spline_parameters=spline_parameters,
365 n_bootstraps=n_bootstraps,
366 )
367
368 end = timer()
369 times[methodfull] = end - start
370
371 yout = {}
372 yerr = {}
373 print(f"free energy profile (in units of kT) for {methodfull}")
374 print(f"{'bin':>8s} {'f':>8s} {'df':>8s}")
375 if method == "histogram":
376 uncertainty_method = "analytical"
377 else:
378 uncertainty_method = "bootstrap"
379 results = fes.get_fes(
380 bin_center_i, reference_point="from-lowest", uncertainty_method=uncertainty_method
381 )
382 for i in range(nbins):
383 if "df_i" in results and results["df_i"] is not None:
384 print(f"{bin_center_i[i]:8.1f} {results['f_i'][i]:8.1f} {results['df_i'][i]:8.1f}")
385 else:
386 print(f"{bin_center_i[i]:8.1f} {results['f_i'][i]:8.1f}")
387
388 results = fes.get_fes(
389 xplot, reference_point="from-lowest", uncertainty_method=uncertainty_method
390 )
391 yout[methodfull] = results["f_i"]
392 yerr[methodfull] = results["df_i"]
393 if len(xplot) <= nbins:
394 errorevery = 1
395 else:
396 errorevery = int(np.floor(len(xplot) / nbins))
397
398 if method == "histogram":
399 # handle histogram differently
400 perbin = nplot // nbins
401 # get the errors in the rigtt place
402 indices = np.arange(0, nplot, perbin) + int(perbin // 2)
403 plt.errorbar(
404 xplot[indices],
405 yout[method][indices],
406 yerr=yerr[method][indices],
407 fmt="none",
408 ecolor="k",
409 elinewidth=1.0,
410 capsize=3,
411 )
412 plt.plot(xplot, yout[method], colors[method], label=descriptions[method])
413 else:
414 plt.errorbar(
415 xplot,
416 yout[methodfull],
417 yerr=yerr[methodfull],
418 errorevery=errorevery,
419 label=descriptions[methodfull],
420 fmt=colors[methodfull],
421 elinewidth=0.8,
422 capsize=3,
423 )
424
425 if "-ml" in methodfull:
426 aic = fes.get_information_criteria(type="AIC")
427 bic = fes.get_information_criteria(type="BIC")
428 print(f"AIC for {method} with {nspline:d} splines is: {aic:f}")
429 print(f"BIC for {method} with {nspline:d} splines is: {bic:f}")
430
431 plt.xlim([chi_min, chi_max])
432 plt.ylim([0, 20])
433 plt.xlabel("Torsion angle (degrees)")
434 plt.ylabel(r"free energy profile (units of $k_BT$)")
435 plt.legend(fontsize="x-small")
436 plt.title("Comparison of free energy profiles")
437 plt.savefig(f"compare_fes_{fig_suffix}.pdf")
438 plt.clf()
439
440 # now perform MC sampling in parameter space
441 pltname = [
442 "bayes_posterior_histogram",
443 "bayesian_95percent",
444 "bayesian_1sigma",
445 "parameter_time_series",
446 ]
447 for method in mc_methods:
448 fes = feses[method]
449 mc_parameters = {
450 "niterations": mc_iterations,
451 "fraction_change": 0.05,
452 "sample_every": 10,
453 "logprior": lambda x: deltag(x, scalef=smoothness_scalefac),
454 "print_every": 50,
455 }
456
457 fes.sample_parameter_distribution(chi_n, mc_parameters=mc_parameters, decorrelate=True)
458
459 mc_results = fes.get_mc_data()
460
461 plt.figure(1)
462 plt.hist(mc_results["logposteriors"], label=descriptions[method])
463
464 # plot maximum likelihood as well
465 method_ml = method.replace("map", "ml")
466 fes_ml = feses[method_ml]
467 results_ml = fes_ml.get_fes(xplot, reference_point="from-lowest", uncertainty_method=None)
468
469 plt.figure(2)
470 plt.xlim([chi_min, chi_max])
471 ci_results = fes.get_confidence_intervals(xplot, 2.5, 97.5, reference="zero")
472 ylow = ci_results["plow"]
473 yhigh = ci_results["phigh"]
474 plt.plot(xplot, ci_results["values"], colors[method], label=descriptions[method])
475 plt.plot(xplot, results_ml["f_i"], colors[method_ml], label=descriptions[method_ml])
476 plt.fill_between(xplot, ylow, yhigh, color=colors[method][0], alpha=0.3)
477 plt.title("FES with 95% confidence intervals")
478 plt.xlabel("Torsion angle (degrees)")
479 plt.ylabel(r"free energy profile (units of $k_BT$)")
480
481 plt.figure(3)
482 plt.xlim([chi_min, chi_max])
483 ci_results = fes.get_confidence_intervals(xplot, 16, 84)
484 plt.plot(xplot, ci_results["values"], colors[method], label=descriptions[method])
485 plt.plot(xplot, results_ml["f_i"], colors[method_ml], label=descriptions[method_ml])
486 ylow = ci_results["plow"]
487 yhigh = ci_results["phigh"]
488 plt.fill_between(xplot, ylow, yhigh, color=colors[method][0], alpha=0.3)
489 plt.xlabel("Torsion angle (degrees)")
490 plt.ylabel(r"free energy profile (units of $k_BT$)")
491 plt.title("free energy profile (in units of kT) with 1 sigma percent confidence intervals")
492
493 # plot the timeseries of the parameters to check for equilibration
494 plt.figure(4)
495 samples = mc_results["samples"]
496 lp, lt = np.shape(samples)
497 for p in range(lp):
498 plt.plot(np.arange(lt), samples[p, :], label=f"{p:d}_{method}")
499 plt.title("Spline parameter time series")
500
501 # print text results
502 ci_results = fes.get_confidence_intervals(bin_center_i, 16, 84)
503 df = (ci_results["phigh"] - ci_results["plow"]) / 2
504 print("free energy profile (in units of kT) with 1 sigma errors from posterior sampling")
505 for i in range(nbins):
506 print(f"{bin_center_i[i]:8.1f} {ci_results['values'][i]:8.1f} {df[i]:8.1f}")
507
508 for i in range(len(pltname)):
509 plt.figure(i + 1)
510 plt.legend(fontsize="x-small")
511 plt.savefig(f"{pltname[i]}_{fig_suffix}.pdf")