Debian Codegraph @

examples/parallel-tempering-2dfes/parallel-tempering-2dfes.py

raw
1 #!/usr/bin/python
2
3 """
4 Estimate 2D free energy surface for alanine dipeptide parallel tempering data using MBAR.
5
6 PROTOCOL
7
8 * Potential energies and (phi, psi) torsions from parallel tempering simulation are read in by temperature
9 * Replica trajectories of potential energies and torsions are reconstructed to reflect their true temporal
10 correlation, and then subsampled to produce statistically independent samples, collecting them again by temperature
11 * The `pymbar` class is initialized to compute the dimensionless free energies at each temperature using MBAR
12 * The torsions are binned into sequentially labeled bins in two dimensions
13 * The relative free energies and uncertainties of these torsion bins at the temperature of interest is estimated
14 * The 2D free energy surface is written out
15
16 REFERENCES
17
18 [1] Shirts MR and Chodera JD. Statistically optimal analysis of samples from multiple equilibrium states.
19 J. Chem. Phys. 129:124105, 2008. http://dx.doi.org/10.1063/1.2978177
20 """
21
22 # ===================================================================================================
23 # IMPORTS
24 # ===================================================================================================
25 from pathlib import Path
26
27 import numpy as np
28 import pymbar # for MBAR analysis
29
30 from pymbar import timeseries # for timeseries analysis
31
32 # ===================================================================================================
33 # CONSTANTS
34 # ===================================================================================================
35
36 kB = 1.3806503 * 6.0221415 / 4184.0 # Boltzmann constant in kcal/mol/K
37
38 # ===================================================================================================
39 # PARAMETERS
40 # ===================================================================================================
41
42 DATA_DIRECTORY = Path("data/") # directory containing the parallel tempering data
43 # file containing temperatures in K
44 temperature_list_filename = DATA_DIRECTORY / "temperatures"
45 free_energies_filename = "f_k.out"
46 # file containing total energies (in kcal/mol) for each temperature and snapshot
47 potential_energies_filename = DATA_DIRECTORY / "energies" / "potential-energies"
48 trajectory_segment_length = 20 # number of snapshots in each contiguous trajectory segment
49 niterations = 500 # number of iterations to use
50 target_temperature = 302 # target temperature for 2D free energy surface (in K)
51 nbins_per_torsion = 10 # number of bins per torsion dimension
52
53 # ===================================================================================================
54 # SUBROUTINES
55 # ===================================================================================================
56
57
58 def read_file(filename):
59 """Read contents of the specified file.
60
61 Parameters:
62 -----------
63 filename : str
64 The name of the file to be read
65
66 Returns
67 -------
68 lines : list of str
69 The contents of the file, split by line
70 """
71 with open(filename, "r") as f:
72 return f.readlines()
73
74
75 # ===================================================================================================
76 # MAIN
77 # ===================================================================================================
78
79 # ===================================================================================================
80 # Read temperatures
81 # ===================================================================================================
82
83 # Read list of temperatures.
84 lines = read_file(temperature_list_filename)
85 # Construct list of temperatures
86 temperatures = lines[0].split()
87 # Create array of temperatures
88 K = len(temperatures)
89 temperature_k = np.zeros([K]) # temperature_k[k] is temperature of temperature index k in K
90 for k in range(K):
91 temperature_k[k] = float(temperatures[k])
92 # Compute inverse temperatures
93 beta_k = (kB * temperature_k) ** (-1)
94
95 # Define other constants
96 T = trajectory_segment_length * niterations # total number of snapshots per temperature
97
98 # ===================================================================================================
99 # Read potential eneriges
100 # ===================================================================================================
101
102 print("Reading potential energies...")
103 # U_kn[k,t] is the potential energy (in kcal/mol) for snapshot t of temperature index k
104 U_kt = np.zeros([K, T])
105 lines = read_file(potential_energies_filename)
106 print(f"{len(lines):d} lines read, processing {T:d} snapshots")
107 for t in range(T):
108 # Get line containing the energies for snapshot t of trajectory segment n
109 line = lines[t]
110 # Extract energy values from text
111 elements = line.split()
112 for k in range(K):
113 U_kt[k, t] = float(elements[k])
114
115 # ===================================================================================================
116 # Read phi, psi trajectories
117 # ===================================================================================================
118
119 print("Reading phi, psi trajectories...")
120 # phi_kt[k,n,t] is phi angle (in degrees) for snapshot t of temperature k
121 phi_kt = np.zeros([K, T])
122 # psi_kt[k,n,t] is psi angle (in degrees) for snapshot t of temperature k
123 psi_kt = np.zeros([K, T])
124 for k in range(K):
125 phi_filename = DATA_DIRECTORY / "backbone-torsions" / f"{k:d}.phi"
126 psi_filename = DATA_DIRECTORY / "backbone-torsions" / f"{k:d}.psi"
127 phi_lines = read_file(phi_filename)
128 psi_lines = read_file(psi_filename)
129 print(f"k = {k:d}, {len(phi_lines):d} phi lines read, {len(psi_lines):d} psi lines read")
130 for t in range(T):
131 # Extract phi and psi
132 phi_kt[k, t] = float(phi_lines[t])
133 psi_kt[k, t] = float(psi_lines[t])
134
135 # ===================================================================================================
136 # Read replica indices
137 # ===================================================================================================
138
139 print("Reading replica indices...")
140 filename = DATA_DIRECTORY / "replica-indices"
141 lines = read_file(filename)
142 # replica_ki[i,k] is the replica index of temperature k for iteration i
143 replica_ik = np.zeros([niterations, K], np.int32)
144 for i in range(niterations):
145 elements = lines[i].split()
146 for k in range(K):
147 replica_ik[i, k] = int(elements[k])
148 print(f"Replica indices for {niterations:d} iterations processed.")
149
150 # ===================================================================================================
151 # Permute data by replica and subsample to generate an uncorrelated subset of data by temperature
152 # ===================================================================================================
153
154 assume_uncorrelated = False
155 if assume_uncorrelated:
156 # DEBUG - use all data, assuming it is uncorrelated
157 print("Using all data, assuming it is uncorrelated...")
158 U_kn = U_kt.copy()
159 phi_kn = phi_kt.copy()
160 psi_kn = psi_kt.copy()
161 N_k = np.zeros([K], np.int32)
162 N_k[:] = T
163 N_max = T
164 else:
165 # Permute data by replica
166 print("Permuting data by replica...")
167 U_kt_replica = U_kt.copy()
168 phi_kt_replica = psi_kt.copy()
169 psi_kt_replica = psi_kt.copy()
170 for iteration in range(niterations):
171 # Determine which snapshot indices are associated with this iteration
172 snapshot_indices = iteration * trajectory_segment_length + np.arange(
173 0, trajectory_segment_length
174 )
175 for k in range(K):
176 # Determine which replica generated the data from temperature k at this iteration
177 replica_index = replica_ik[iteration, k]
178 # Reconstruct portion of replica trajectory.
179 U_kt_replica[replica_index, snapshot_indices] = U_kt[k, snapshot_indices]
180 phi_kt_replica[replica_index, snapshot_indices] = phi_kt[k, snapshot_indices]
181 psi_kt_replica[replica_index, snapshot_indices] = psi_kt[k, snapshot_indices]
182 # Estimate the statistical inefficiency of the simulation by analyzing the timeseries of interest.
183 # We use the max of cos and sin of the phi and psi timeseries because they are periodic angles.
184 # The ## TODO: ???
185 print("Computing statistical inefficiencies...")
186 g_cosphi = timeseries.statistical_inefficiency_multiple(np.cos(phi_kt_replica * np.pi / 180.0))
187 print(f"g_cos(phi) = {g_cosphi:.1f}")
188 g_sinphi = timeseries.statistical_inefficiency_multiple(np.sin(phi_kt_replica * np.pi / 180.0))
189 print(f"g_sin(phi) = {g_sinphi:.1f}")
190 g_cospsi = timeseries.statistical_inefficiency_multiple(np.cos(psi_kt_replica * np.pi / 180.0))
191 print(f"g_cos(psi) = {g_cospsi:.1f}")
192 g_sinpsi = timeseries.statistical_inefficiency_multiple(np.sin(psi_kt_replica * np.pi / 180.0))
193 print(f"g_sin(psi) = {g_sinpsi:.1f}")
194 # Subsample data with maximum of all correlation times.
195 print("Subsampling data...")
196 g = np.max(np.array([g_cosphi, g_sinphi, g_cospsi, g_sinpsi]))
197 indices = timeseries.subsample_correlated_data(U_kt[k, :], g=g)
198 print(f"Using g = {g:.1f} to obtain {len(indices):d} uncorrelated samples per temperature")
199 N_max = int(np.ceil(T / g)) # max number of samples per temperature
200 U_kn = np.zeros([K, N_max])
201 phi_kn = np.zeros([K, N_max])
202 psi_kn = np.zeros([K, N_max])
203 N_k = N_max * np.ones([K], dtype=int)
204 for k in range(K):
205 U_kn[k, :] = U_kt[k, indices]
206 phi_kn[k, :] = phi_kt[k, indices]
207 psi_kn[k, :] = psi_kt[k, indices]
208 print(f"{N_max:d} uncorrelated samples per temperature")
209
210 # ===================================================================================================
211 # Generate a list of indices of all configurations in kn-indexing
212 # ===================================================================================================
213
214 # Create a list of indices of all configurations in kn-indexing.
215 mask_kn = np.zeros([K, N_max], dtype=bool)
216 for k in range(K):
217 mask_kn[k, 0 : N_k[k]] = True
218 # Create a list from this mask.
219 indices = np.where(mask_kn)
220
221 # ===================================================================================================
222 # Compute reduced potential energy of all snapshots at all temperatures
223 # ===================================================================================================
224
225 print("Computing reduced potential energies...")
226 # u_kln[k,l,n] is reduced potential energy of trajectory segment n of temperature k evaluated at temperature l
227 u_kln = np.zeros([K, K, N_max])
228 for k in range(K):
229 for l in range(K):
230 u_kln[k, l, 0 : N_k[k]] = beta_k[l] * U_kn[k, 0 : N_k[k]]
231
232 # ===================================================================================================
233 # Bin torsions into histogram bins for free energy surface calculation
234 # ===================================================================================================
235
236 # Here, we bin the (phi,psi) samples into bins in a 2D histogram.
237 # We assign indices 0...(nbins-1) to the bins, even though the histograms are in two dimensions.
238 # All bins must have at least one sample in them.
239 # This strategy scales to an arbitrary number of dimensions.
240
241 print("Binning torsions...")
242 # Determine torsion bin size (in degrees)
243 torsion_min = -180.0
244 torsion_max = +180.0
245 dx = (torsion_max - torsion_min) / float(nbins_per_torsion)
246 # Assign torsion bins
247 # bin_kn[k,n] is the index of which histogram bin sample n from temperature index k belongs to
248 bin_kn = np.zeros([K, N_max], dtype=int)
249 nbins = 0
250 bin_nonzero = 0
251 bin_counts = []
252 bin_centers = [] # bin_centers[i] is a (phi,psi) tuple that gives the center of bin i
253 count_nonzero = []
254 centers_nonzero = []
255
256 for i in range(nbins_per_torsion):
257 for j in range(nbins_per_torsion):
258 # Determine (phi,psi) of bin center.
259 phi = torsion_min + dx * (i + 0.5)
260 psi = torsion_min + dx * (j + 0.5)
261
262 # Determine which configurations lie in this bin.
263 in_bin = (
264 (phi - dx / 2 <= phi_kn[indices])
265 & (phi_kn[indices] < phi + dx / 2)
266 & (psi - dx / 2 <= psi_kn[indices])
267 & (psi_kn[indices] < psi + dx / 2)
268 )
269 # Count number of configurations in this bin.
270 bin_count = in_bin.sum()
271 # Generate list of indices in bin.
272 # set bin indices of both dimensions
273 if bin_count > 0:
274 count_nonzero.append(bin_count)
275 centers_nonzero.append((phi, psi))
276 bin_nonzero += 1
277
278 print(f"{bin_nonzero:d} bins were populated:")
279 for i in range(bin_nonzero):
280 print(
281 f"bin {i:5d} ({centers_nonzero[i][0]:6.1f}, {centers_nonzero[i][1]:6.1f}) {count_nonzero[i]:12d} conformations"
282 )
283
284 x_n = np.zeros([np.sum(N_k), 2]) # the configurations
285
286 Ntot = 0
287 for k in range(K):
288 for n in range(N_k[k]):
289 x_n[Ntot, 0] = phi_kn[k, n]
290 x_n[Ntot, 1] = psi_kn[k, n]
291 Ntot += 1
292
293 bin_edges = []
294 for i in range(2):
295 bin_edges.append(np.linspace(torsion_min, torsion_max, nbins_per_torsion + 1))
296
297 # Initialize free energy surface with data collected
298 fes = pymbar.FES(u_kln, N_k, mbar_options=dict(solver_protocol="robust"))
299
300 # ===================================================================================================
301 # Compute free energy surface at the desired temperature.
302 # ===================================================================================================
303
304 print("Computing free energy surface...")
305
306 # Compute reduced potential energies at the temperaure of interest
307 target_beta = 1.0 / (kB * target_temperature)
308 u_kn = target_beta * U_kn
309 # Compute FES at this temperature, returning dimensionless free energies and uncertainties.
310 # f_i[i] is the dimensionless free energy of bin i (in kT) at the temperature of interest
311 # df_i[i,j] is an estimate of the covariance in the estimate of (f_i[i] - f_j[j], with reference
312 # the lowest free energy state.
313 # Compute FES in unbiased potential (in units of kT).
314 histogram_parameters = {}
315 histogram_parameters["bin_edges"] = bin_edges
316 fes.generate_fes(u_kn, x_n, fes_type="histogram", histogram_parameters=histogram_parameters)
317 results = fes.get_fes(
318 np.array(centers_nonzero), reference_point="from-lowest", uncertainty_method="analytical"
319 )
320 f_i = results["f_i"]
321 df_i = results["df_i"]
322
323 # Show free energy and uncertainty of each occupied bin relative to lowest free energy
324 print("2D free energy surface")
325 print()
326 print(f"{'bin':>8s} {'phi':>6s} {'psi':>6s} {'N':>8s} {'f':>10s} {'df':>10s}")
327
328 for i in range(bin_nonzero):
329 print(
330 f"{i:>8d} {centers_nonzero[i][0]:>6.1f} {centers_nonzero[i][1]:>6.1f} {count_nonzero[i]:>8d} {f_i[i]:>10.3f} {df_i[i]:>10.3f}"
331 )