Debian Codegraph @

examples/heat-capacity/heat-capacity.py

raw
1 """
2 todo -- simplify the total energy read in, the kinetic energy read-in, temperature read-in
3 """
4
5 # =========================================================
6 # IMPORTS
7 # =========================================================
8
9 from optparse import OptionParser
10 from pathlib import Path
11
12 import numpy as np
13
14 import pymbar # for MBAR analysis
15 from pymbar import timeseries # for timeseries analysis
16
17
18 # ===================================================================================================
19 # INPUT PARAMETERS
20 # ===================================================================================================
21 def parse_cli():
22 parser = OptionParser()
23
24 parser.add_option(
25 "-d",
26 "--directory",
27 dest="simulation",
28 default="energydata",
29 help="the directory of the energies we care about",
30 )
31 parser.add_option(
32 "-b",
33 "--n_bootstraps",
34 dest="n_boots",
35 type=int,
36 default=0,
37 help="Number of bootstrap samples taken",
38 )
39 parser.add_option(
40 "-s",
41 "--spacing",
42 dest="num_intermediates",
43 type="int",
44 default=200,
45 help="Number of intermediate simulations used to calculate finite differences (default 200)",
46 )
47 parser.add_option(
48 "-f",
49 "--finitedifftype",
50 dest="dertype",
51 default="temperature",
52 help='the type of finite difference energy, choice is "temperature" or "beta" [default = %default]',
53 )
54 parser.add_option(
55 "-r",
56 "--randomseed",
57 dest="rseed",
58 type=int,
59 default=None,
60 help="random seed for bootstraping [default = %default]",
61 )
62 return parser.parse_args()
63
64
65 options, args = parse_cli()
66 simulation = options.simulation
67 n_boots = options.n_boots
68 num_intermediates = options.num_intermediates
69 dertype = options.dertype
70 rseed = options.rseed
71
72 # ========================================================
73 # CONSTANTS
74 # ========================================================
75
76 kB = 0.008314462 # Boltzmann constant (Gas constant) in kJ/(mol*K)
77 TE_COL_NUM = 11 # The column number of the total energy in ener_box#.output
78
79 num_temps = 16 # Last TEMP # + 1 (start counting at 1)
80 NUM_ITERATIONS = 1000 # The number of energies to be taken and analyzed, starting from the last
81 # Extra data will be ignored
82
83 if dertype == "temperature": # if the temperatures are equally spaced
84 types = "var", "dT", "ddT"
85 elif dertype == "beta": # if the inverse temperatures are equally spaced.
86 types = "var", "dbeta", "ddbeta"
87 else:
88 sys.exit("type of finite difference not recognized must be 'beta' or 'temperature'")
89
90 NTYPES = len(types)
91
92 np.random.seed(rseed) # seed the random numbers
93
94 ###########################################################
95 # For Cv vs T
96 # _____
97 # Cv / \ <-- what we expect the graph to look like
98 # ____________/ \____________
99 # T
100 ############################################################
101
102 # =========================================================
103 # SUBROUTINES
104 # =========================================================
105
106
107 def read_total_energies(pathname, colnum):
108 """Reads in the TEMP#/ener_box#.output file and parses it, returning an array of energies
109
110 Parameters
111 ----------
112 pathname : str
113 the path to the folder of the simulation
114 colnum : int
115 column the energy is found in
116
117 Returns
118 -------
119 array-like
120 """
121 pathname = Path(pathname)
122 print(f"--Reading total energies from {pathname}/...")
123
124 # Initialize Return variables
125 E_kn = np.zeros([num_temps, NUM_ITERATIONS])
126
127 # Read files
128 for k in range(num_temps):
129 # Construct each TEMP#/ener_box#.output name and read in the file
130 filename = pathname / f"TEMP{k}" / f"ener_box{k}.output"
131
132 with open(filename) as infile:
133 lines = infile.readlines()
134 n_lines = len(lines)
135
136 # Initialize arrays for E
137 E_from_file = np.zeros(NUM_ITERATIONS)
138
139 # Parse lines in each file
140 for n in range(NUM_ITERATIONS):
141 # Count down (the 2 is for index purposes(1) and to not use the double-counted last line (1))
142 m = n_lines - 2 - n
143 elements = lines[m].split()
144 E_from_file[n] = float(elements[colnum])
145
146 # Add in the E's for each timestep (n) at this temperature (k)
147 E_kn[k] = E_from_file
148 return E_kn
149
150
151 def read_simulation_temps(pathname, num_temps):
152 """Reads in the various temperatures from each TEMP#/simul.output file by knowing
153 beforehand the total number of temperatures (parameter at top)
154
155 Parameters
156 ----------
157 pathname : str
158 num_temps : int
159
160 """
161 pathname = Path(pathname)
162 print(f"--Reading temperatures from {pathname}/...")
163
164 # Initialize return variable
165 temps_from_file = np.zeros(num_temps)
166
167 for k in range(num_temps):
168 filename = pathname / f"TEMP{k}" / f"simul{k}.output"
169 with open(filename) as f:
170 for line in f:
171 if line[0:11] == "Temperature":
172 vals = line.split(":")
173 break
174 temps_from_file[k] = float(vals[1])
175
176 return temps_from_file
177
178
179 def print_results(string, E, dE, Cv, dCv, types):
180 print(string)
181 print("Temperature dA <E> +/- d<E> ", end=" ")
182 for t in types:
183 print(f" Cv +/- dCv ({t})", end=" ")
184 print()
185 print(
186 "------------------------------------------------------------------------------------------------------"
187 )
188 for k in range(originalK, K):
189 print(
190 f"{temp_k[k]:8.3f} {mbar.f_k[k] / beta_k[k]:8.3f} {E[k]:9.3f} +/- {dE[k]:5.3f}",
191 end=" ",
192 )
193 for i in range(len(types)):
194 if Cv[k, i, 0] < -100000.0:
195 print(" N/A ", end=" ")
196 else:
197 print(f" {Cv[k, i, 0]:7.4f} +/- {dCv[k, i]:6.4f}", end=" ")
198 print()
199
200
201 # ========================================================================
202 # MAIN
203 # ========================================================================
204
205 # ------------------------------------------------------------------------
206 # Read Data From File
207 # ------------------------------------------------------------------------
208
209 print()
210 print("Preparing data:")
211 T_from_file = read_simulation_temps(simulation, num_temps)
212 E_from_file = read_total_energies(simulation, TE_COL_NUM)
213 K = len(T_from_file)
214 N_k = np.zeros(K, dtype=int)
215 g = np.zeros(K)
216
217 for k in range(K): # subsample the energies
218 g[k] = timeseries.statistical_inefficiency(E_from_file[k])
219 # indices of uncorrelated samples
220 indices = np.array(timeseries.subsample_correlated_data(E_from_file[k], g=g[k]))
221 N_k[k] = len(indices) # number of uncorrelated samples
222 E_from_file[k, 0 : N_k[k]] = E_from_file[k, indices]
223
224 # ------------------------------------------------------------------------
225 # Insert Intermediate T's and corresponding blank U's and E's
226 # ------------------------------------------------------------------------
227 temp_k = T_from_file
228 minT = T_from_file[0]
229 maxT = T_from_file[len(T_from_file) - 1]
230 # beta = 1/(k*BT)
231 # T = 1/(kB*beta)
232 if dertype == "temperature":
233 minv = minT
234 maxv = maxT
235 elif dertype == "beta": # actually going in the opposite direction as beta for logistical reasons
236 minv = 1 / (kB * minT)
237 maxv = 1 / (kB * maxT)
238 delta = (maxv - minv) / (num_intermediates - 1)
239 originalK = len(temp_k)
240
241 print("--Adding intermediate temperatures...")
242
243 val_k = []
244 currentv = minv
245 if dertype == "temperature":
246 # Loop, inserting equally spaced T's at which we are interested in the properties
247 while currentv <= maxv:
248 val_k = np.append(val_k, currentv)
249 currentv = currentv + delta
250 temp_k = np.concatenate((temp_k, np.array(val_k)))
251 elif dertype == "beta":
252 # Loop, inserting equally spaced T's at which we are interested in the properties
253 while currentv >= maxv:
254 val_k = np.append(val_k, currentv)
255 currentv = currentv + delta
256 temp_k = np.concatenate((temp_k, (1 / (kB * np.array(val_k)))))
257
258 # Update number of states
259 K = len(temp_k)
260 # Loop, inserting E's into blank matrix (leaving blanks only where new Ts are inserted)
261
262 # Number of samples (n) for each state (k) = number of iterations/energies
263 Nall_k = np.zeros([K], dtype=int)
264 E_kn_files = np.zeros([K, NUM_ITERATIONS])
265
266 for k in range(originalK):
267 E_kn_files[k, 0 : N_k[k]] = E_from_file[k, 0 : N_k[k]]
268 Nall_k[k] = N_k[k]
269
270 # ------------------------------------------------------------------------
271 # Compute inverse temperatures
272 # ------------------------------------------------------------------------
273 beta_k = 1 / (kB * temp_k)
274
275 # ------------------------------------------------------------------------
276 # Compute reduced potential energies
277 # ------------------------------------------------------------------------
278
279 print("--Computing reduced energies...")
280
281 # u_kln is reduced pot. ener. of segment n of temp k evaluated at temp l
282 u_kn = np.zeros([K, np.sum(N_k)])
283 # u_kln is reduced pot. ener. of segment n of temp k evaluated at temp l
284 E_kn_samp = np.zeros([K, NUM_ITERATIONS])
285 # we add +1 to the bootstrap number, as the zeroth bootstrap sample is the original
286 n_boots_work = n_boots + 1
287
288 allCv_expect = np.zeros([K, NTYPES, n_boots_work])
289 dCv_expect = np.zeros([K, NTYPES])
290 allE_expect = np.zeros([K, n_boots_work])
291 allE2_expect = np.zeros([K, n_boots_work])
292 dE_expect = np.zeros([K])
293
294
295 for n in range(n_boots_work):
296 if n > 0:
297 print(f"Bootstrap: {n:d}/{n_boots:d}")
298
299 for k in range(K):
300 # resample the results:
301 if Nall_k[k] > 0:
302 if n == 0: # don't randomize the first one
303 booti = np.array(range(N_k[k]))
304 else:
305 booti = np.random.randint(Nall_k[k], size=Nall_k[k])
306 E_kn_samp[k, 0 : Nall_k[k]] = E_kn_files[k, booti]
307
308 for l in range(K):
309 nsum = 0
310 for k in range(K):
311 u_kn[l, nsum : nsum + Nall_k[k]] = beta_k[l] * E_kn_samp[k, 0 : Nall_k[k]]
312 nsum = nsum + Nall_k[k]
313 # ------------------------------------------------------------------------
314 # Initialize MBAR
315 # ------------------------------------------------------------------------
316
317 # Initialize MBAR with Newton-Raphson
318 if n == 0: # only print this information the first time
319 print()
320 print("Initializing MBAR:")
321 print(f"--K = number of Temperatures with data = {originalK:d}")
322 print(f"--L = number of total Temperatures = {K:d}")
323 print(f"--N = number of Energies per Temperature = {np.max(Nall_k):d}")
324
325 if n == 0:
326 initial_f_k = None # start from zero
327 else:
328 initial_f_k = mbar.f_k # start from the previous final free energies to speed convergence
329
330 mbar = pymbar.MBAR(
331 u_kn,
332 Nall_k,
333 verbose=False,
334 relative_tolerance=1e-12,
335 solver_protocol="robust",
336 initial_f_k=initial_f_k,
337 )
338
339 # ------------------------------------------------------------------------
340 # Compute Expectations for E_kt and E2_kt as E_expect and E2_expect
341 # ------------------------------------------------------------------------
342
343 print("")
344 print("Computing Expectations for E...")
345 E_kn = u_kn.copy()
346 for k in range(K):
347 # get the 'unreduced' potential -- we can't take differences of reduced potentials
348 # because the beta is different; math is much more confusing with derivatives of the reduced potentials.
349 E_kn[k, :] *= beta_k[k] ** (-1)
350 results = mbar.compute_expectations(E_kn, state_dependent=True)
351 E_expect = results["mu"]
352 dE_expect = results["sigma"]
353 allE_expect[:, n] = E_expect[:]
354
355 # expectations for the differences, which we need for numerical derivatives
356 results = mbar.compute_expectations(E_kn, output="differences", state_dependent=True)
357 DeltaE_expect = results["mu"]
358 dDeltaE_expect = results["sigma"]
359 print("Computing Expectations for E^2...")
360
361 results = mbar.compute_expectations(E_kn**2, state_dependent=True)
362 E2_expect = results["mu"]
363 dE2_expect = results["sigma"]
364 allE2_expect[:, n] = E2_expect[:]
365
366 results = mbar.compute_free_energy_differences()
367 df_ij = results["Delta_f"]
368 ddf_ij = results["dDelta_f"]
369
370 # ------------------------------------------------------------------------
371 # Compute Cv for NVT simulations as <E^2> - <E>^2 / (RT^2)
372 # ------------------------------------------------------------------------
373
374 if n == 0:
375 print()
376 print("Computing Heat Capacity as ( <E^2> - <E>^2 ) / ( R*T^2 ) and as d<E>/dT")
377
378 # Problem is that we don't have a good uncertainty estimate for the variance.
379 # Try a silly trick: but it doesn't work super well.
380 # An estimator of the variance of the standard estimator of th evariance is
381 # var(sigma^2) = (sigma^4)*[2/(n-1)+kurt/n]. If we assume the kurtosis is low
382 # (which it will be for sufficiently many samples), then we can say that
383 # d(sigma^2) = sigma^2 sqrt[2/(n-1)].
384 # However, dE_expect**2 is already an estimator of sigma^2/(n-1)
385 # Cv = sigma^2/kT^2, so d(Cv) = d(sigma^2)/kT^2 = sigma^2*[sqrt(2/(n-1)]/kT^2
386 # we just need an estimate of n-1, but we can try to get that by var(dE)/dE_expect**2
387 # it's within 50% or so, but that's not good enough.
388
389 allCv_expect[:, 0, n] = (E2_expect - (E_expect * E_expect)) / (kB * temp_k**2)
390
391 ####################################
392 # C_v by fluctuation formula
393 ####################################
394
395 # Cv = (A - B^2) / (kT^2)
396 # d2(Cv) = [1/(kT^2)]^2 [(dCv/dA)^2*d2A + 2*dCv*(dCv/dA)*(dCv/dB)*dAdB + (dCv/dB)^2*d2B]
397 # = [1/(kT^2)]^2 [d2A - 4*B*dAdB + 4*B^2*d2B]
398 # But this formula is not working for uncertainies!
399
400 if n == 0:
401 # sigma^2 / (sigma^2/n) = effective number of samples
402 N_eff = (E2_expect - (E_expect * E_expect)) / dE_expect**2
403 dCv_expect[:, 0] = allCv_expect[:, 0, n] * np.sqrt(2 / N_eff)
404
405 # only loop over the points that will be plotted, not the ones that
406 for i in range(originalK, K):
407 # Now, calculae heat capacity by T-differences
408 im = i - 1
409 ip = i + 1
410 if i == originalK:
411 im = originalK
412 if i == K - 1:
413 ip = i
414
415 ####################################
416 # C_v by first derivative of energy
417 ####################################
418
419 if dertype == "temperature": # temperature derivative
420 # C_v = d<E>/dT
421 allCv_expect[i, 1, n] = (DeltaE_expect[im, ip]) / (temp_k[ip] - temp_k[im])
422 if n == 0:
423 dCv_expect[i, 1] = (dDeltaE_expect[im, ip]) / (temp_k[ip] - temp_k[im])
424 elif dertype == "beta": # beta derivative
425 # Cv = d<E>/dT = dbeta/dT d<E>/beta = - kB*T(-2) d<E>/dbeta = - kB beta^2 d<E>/dbeta
426 allCv_expect[i, 1, n] = (
427 kB * beta_k[i] ** 2 * (DeltaE_expect[ip, im]) / (beta_k[ip] - beta_k[im])
428 )
429 if n == 0:
430 dCv_expect[i, 1] = (
431 -kB * beta_k[i] ** 2 * (dDeltaE_expect[ip, im]) / (beta_k[ip] - beta_k[im])
432 )
433
434 #########################################
435 # C_v by second derivative of free energy
436 #########################################
437
438 if dertype == "temperature":
439 # C_v = d<E>/dT = d/dT k_B T^2 df/dT = 2*T*df/dT + T^2*d^2f/dT^2
440
441 if (i == originalK) or (i == K - 1):
442 # We can't calculate this, set a number that will be printed as NAN
443 allCv_expect[i, 2, n] = -10000000.0
444 else:
445 allCv_expect[i, 2, n] = (
446 kB
447 * temp_k[i]
448 * (
449 2 * df_ij[ip, im] / (temp_k[ip] - temp_k[im])
450 + temp_k[i]
451 * (df_ij[ip, i] - df_ij[i, im])
452 / ((temp_k[ip] - temp_k[im]) / (ip - im)) ** 2
453 )
454 )
455
456 if n == 0:
457 # Previous work to calculate the uncertainty commented out, should be cleaned up eventually
458 # all_Cv_expect[i,2,n] = kB*temp_k[i]*(2*df_ij[ip,i]+df_ij[i,im]/(temp_k[ip]-temp_k[im]) + temp_k[i]*(df_ij[ip,i]-df_ij[i,im])/(temp_k[ip]-temp_k[i])**2)
459 # all_Cv_expect[i,2,n] = kB*([2*temp_k[i]/(temp_k[ip]-temp_k[im]) + temp_k[i]**2/(temp_k[ip]-temp_k[i])**2]*df_ij[ip,i] + [2*temp_k[i]/(temp_k[ip]-temp_k[im]) - temp_k[i]**2/(temp_k[ip]-temp_k[i])**2]) df_ij[i,im]
460 # all_Cv_expect[i,2,n] = kB*(A df_ij[ip,i] + B df_ij[i,im]
461 A = (
462 2 * temp_k[i] / (temp_k[ip] - temp_k[im])
463 + 4 * temp_k[i] ** 2 / (temp_k[ip] - temp_k[im]) ** 2
464 )
465 B = (
466 2 * temp_k[i] / (temp_k[ip] - temp_k[im])
467 + 4 * temp_k[i] ** 2 / (temp_k[ip] - temp_k[im]) ** 2
468 )
469 # dCv_expect[i,2,n] = kB* [(A ddf_ij[ip,i])**2 + (B sdf_ij[i,im])**2 + 2*A*B*cov(df_ij[ip,i],df_ij[i,im])
470 # This isn't it either: need to figure out that last term.
471 dCv_expect[i, 2] = kB * ((A * ddf_ij[ip, i]) ** 2 + (B * ddf_ij[i, im]) ** 2)
472 # Would need to add function computing covariance of DDG, (A-B)-(C-D)
473
474 elif dertype == "beta":
475 # if beta is evenly spaced, rather than t, we can do 2nd derivative in beta
476 # C_v = d<E>/dT = d/dT (df/dbeta) = dbeta/dT d/dbeta (df/dbeta) = -k_b beta^2 df^2/d^2beta
477 if (i == originalK) or (i == K - 1):
478 # Flag as N/A -- we don't try to compute at the endpoints for now
479 allCv_expect[i, 2, n] = -10000000.0
480 else:
481 allCv_expect[i, 2, n] = (
482 kB
483 * beta_k[i] ** 2
484 * (df_ij[ip, i] - df_ij[i, im])
485 / ((beta_k[ip] - beta_k[im]) / (ip - im)) ** 2
486 )
487 if n == 0:
488 dCv_expect[i, 2] = (
489 kB
490 * (beta_k[i]) ** 2
491 * (ddf_ij[ip, i] - ddf_ij[i, im])
492 / ((beta_k[ip] - beta_k[im]) / (ip - im)) ** 2
493 )
494 # also wrong, need to be fixed.
495
496 if n == 0:
497 print(
498 "WARNING: only the first derivative (dT) analytic error estimates can currently be trusted."
499 )
500 print("They are the only ones reasonably close to bootstrap, within 10-15% at all T.")
501 print()
502 print_results(
503 "Analytic Error Estimates", E_expect, dE_expect, allCv_expect, dCv_expect, types
504 )
505
506 if n_boots > 0:
507 Cv_boot = np.zeros([K, NTYPES])
508 dCv_boot = np.zeros([K, NTYPES])
509 dE_boot = np.zeros([K])
510
511 for k in range(K):
512 for i in range(NTYPES):
513 # for these averages, don't include the first one, because it's the non-bootstrapped one.
514 Cv_boot[k, i] = np.mean(allCv_expect[k, i, 1:n_boots_work])
515 dCv_boot[k, i] = np.std(allCv_expect[k, i, 1:n_boots_work])
516 dE_boot[k] = np.std(allE_expect[k, 1:n_boots_work])
517 print_results(
518 "Bootstrap Error Estimates", allE_expect[:, 0], dE_boot, allCv_expect, dCv_boot, types
519 )