Debian Codegraph @

examples/constant-force-optical-trap/force-bias-optical-trap.py

raw
1 """
2 Example illustrating the application of MBAR to compute a 1D free energy profile
3 from a series of force-clamp single-molecule experiments.
4
5 REFERENCE
6
7 Woodside MT, Behnke-Parks WL, Larizadeh K, Travers K, Herschlag D, and Block SM.
8 Nanomechanical measurements of the sequence-dependent folding landscapes of single
9 nucleic acid hairpins. PNAS 103:6190, 2006.
10
11 """
12
13 # =============================================================================================
14 # IMPORTS
15 # =============================================================================================
16 import subprocess
17 import time
18 from pathlib import Path
19
20 import numpy as np
21 import matplotlib
22
23 matplotlib.use("Agg")
24 import matplotlib.pyplot as plt
25
26 import pymbar # multistate Bennett acceptance ratio analysis (provided by pymbar)
27 from pymbar import timeseries, FES # timeseries analysis (provided by pymbar)
28
29 # =============================================================================================
30 # PARAMETERS
31 # =============================================================================================
32
33 prefix = "20R55_4T" # for paper
34 # prefix = '10R50_4T'
35 # prefix = '25R50_4T'
36 # prefix = '30R50_4T'
37 directory = Path("processed-data")
38 temperature = 296.15 # temperature (in K)
39 nbins = 50 # number of bins for 1D FES
40 output_directory = Path("output")
41 plot_directory = Path("plots")
42
43 # =============================================================================================
44 # CONSTANTS
45 # =============================================================================================
46
47 kB = 1.381e-23 # Boltzmann constant (in J/K)
48 pN_nm_to_kT = (1.0e-9) * (1.0e-12) / (kB * temperature) # conversion from nM pN to units of kT
49
50 # =============================================================================================
51 # SUBROUTINES
52 # =============================================================================================
53
54
55 def construct_nonuniform_bins(x_n, nbins):
56 """Construct histogram using bins of unequal size to ensure approximately equal population in each bin.
57
58 Parameters
59 ----------
60 x_n : 1D array of float
61 x_n[n] is data point n
62
63 Returns
64 -------
65 bin_left_boundary_i : 1D array of floats
66 data in bin i will satisfy bin_left_boundary_i[i] <= x < bin_left_boundary_i[i+1]
67 bin_center_i : 1D array of floats
68 bin_center_i[i] is the center of bin i
69 bin_width_i : 1D array of floats
70 bin_width_i[i] is the width of bin i
71 bin_n : 1D array of int32
72 bin_n[n] is the bin index (in range(nbins)) of x_n[n]
73 """
74
75 # Determine number of samples.
76 N = x_n.size
77
78 # Get indices of elements of x_n sorted in order.
79 sorted_indices = x_n.argsort()
80
81 # Allocate storage for results.
82 bin_left_boundary_i = np.zeros([nbins + 1])
83 bin_center_i = np.zeros([nbins])
84 bin_width_i = np.zeros([nbins])
85 bin_n = np.zeros([N])
86
87 # Determine sampled range, adding a little bit to the rightmost range to ensure no samples escape the range.
88 x_min = x_n.min()
89 x_max = x_n.max()
90 x_max += (x_max - x_min) * 1.0e-5
91
92 # Determine bin boundaries and bin assignments.
93 for bin_index in range(nbins):
94 # indices of first and last data points in this span
95 first_index = int(float(N) / float(nbins) * float(bin_index))
96 last_index = int(float(N) / float(nbins) * float(bin_index + 1))
97
98 # store left bin boundary
99 bin_left_boundary_i[bin_index] = x_n[sorted_indices[first_index]]
100
101 # store assignments
102 bin_n[sorted_indices[first_index:last_index]] = bin_index
103
104 # set rightmost boundary
105 bin_left_boundary_i[nbins] = x_max
106
107 # Determine bin centers and widths
108 for bin_index in range(nbins):
109 bin_center_i[bin_index] = (
110 bin_left_boundary_i[bin_index] + bin_left_boundary_i[bin_index + 1]
111 ) / 2.0
112 bin_width_i[bin_index] = (
113 bin_left_boundary_i[bin_index + 1] - bin_left_boundary_i[bin_index]
114 )
115
116 return bin_left_boundary_i, bin_center_i, bin_width_i, bin_n
117
118
119 # =============================================================================================
120 # MAIN
121 # =============================================================================================
122
123
124 def main():
125 # read biasing forces for different trajectories
126 filename = directory / f"{prefix}.forces"
127 with open(filename) as infile:
128 elements = infile.readline().split()
129 K = len(elements) # number of biasing forces
130 # biasing_force_k[k] is the constant external biasing force used to collect trajectory k (in pN)
131 biasing_force_k = np.zeros([K])
132 for k in range(K):
133 biasing_force_k[k] = float(elements[k])
134 print("biasing forces (in pN) = ", biasing_force_k)
135
136 # Determine maximum number of snapshots in all trajectories.
137 filename = directory / f"{prefix}.trajectories"
138 T_max = 0
139 with open(filename) as f:
140 for line in f:
141 T_max += 1
142
143 # Allocate storage for original (correlated) trajectories
144 T_k = np.zeros([K], int) # T_k[k] is the number of snapshots from umbrella simulation k`
145 # x_kt[k,t] is the position of snapshot t from trajectory k (in nm)
146 x_kt = np.zeros([K, T_max])
147
148 # Read the trajectories.
149 filename = directory / f"{prefix}.trajectories"
150 print(f"Reading {filename}...")
151 with open(filename) as infile:
152 for line in infile:
153 elements = line.split()
154 for k in range(K):
155 t = T_k[k]
156 x_kt[k, t] = float(elements[k])
157 T_k[k] += 1
158
159 # Create a list of indices of all configurations in kt-indexing.
160 mask_kt = np.zeros([K, T_max], dtype=bool)
161 for k in range(K):
162 mask_kt[k, 0 : T_k[k]] = True
163 # Create a list from this mask.
164 all_data_indices = np.where(mask_kt)
165
166 # Construct equal-frequency extension bins
167 print("binning data...")
168 bin_kt = np.zeros([K, T_max], int)
169 bin_left_boundary_i, bin_center_i, bin_width_i, bin_assignments = construct_nonuniform_bins(
170 x_kt[all_data_indices], nbins
171 )
172 bin_kt[all_data_indices] = bin_assignments
173
174 # Compute correlation times.
175 N_max = 0
176 g_k = np.zeros([K])
177 for k in range(K):
178 # Compute statistical inefficiency for extension timeseries
179 g = timeseries.statistical_inefficiency(x_kt[k, 0 : T_k[k]], x_kt[k, 0 : T_k[k]])
180 # store statistical inefficiency
181 g_k[k] = g
182 print(
183 f"timeseries {k + 1:d} : g = {g:.1f}, {int(np.floor(T_k[k] / g)):.0f} "
184 f"uncorrelated samples (of {T_k[k]:d} total samples)"
185 )
186 N_max = max(N_max, int(np.ceil(T_k[k] / g)) + 1)
187
188 # Subsample trajectory position data.
189 x_kn = np.zeros([K, N_max])
190 bin_kn = np.zeros([K, N_max])
191 N_k = np.zeros([K], int)
192 for k in range(K):
193 # Compute correlation times for potential energy and chi timeseries.
194 indices = timeseries.subsample_correlated_data(x_kt[k, 0 : T_k[k]])
195 # Store subsampled positions.
196 N_k[k] = len(indices)
197 x_kn[k, 0 : N_k[k]] = x_kt[k, indices]
198 bin_kn[k, 0 : N_k[k]] = bin_kt[k, indices]
199
200 # Set arbitrarynp.zeros for external biasing potential.
201 x0_k = np.zeros([K]) # x position corresponding to zero of potential
202 for k in range(K):
203 x0_k[k] = x_kn[k, 0 : N_k[k]].mean()
204 print("x0_k = ", x0_k)
205
206 # Compute bias energies in units of kT.
207 # u_kln[k,l,n] is the reduced (dimensionless) relative potential energy of
208 # snapshot n from umbrella simulation k evaluated at umbrella l
209 u_kln = np.zeros([K, K, N_max])
210 for k in range(K):
211 for l in range(K):
212 # compute relative energy difference from sampled state to each other state
213 # U_k(x) = F_k x
214 # where F_k is external biasing force
215 # (F_k pN) (x nm) (pN /
216 # u_kln[k,l,0:N_k[k]] = - pN_nm_to_kT * (biasing_force_k[l] - biasing_force_k[k]) * x_kn[k,0:N_k[k]]
217 u_kln[k, l, 0 : N_k[k]] = -pN_nm_to_kT * biasing_force_k[l] * (
218 x_kn[k, 0 : N_k[k]] - x0_k[l]
219 ) + pN_nm_to_kT * biasing_force_k[k] * (x_kn[k, 0 : N_k[k]] - x0_k[k])
220
221 # DEBUG
222 start_time = time.time()
223
224 # Initialize MBAR.
225 print("Running MBAR...")
226 # TODO: change to u_kn inputs
227 mbar = pymbar.MBAR(
228 u_kln, N_k, verbose=True, relative_tolerance=1.0e-10, solver_protocol="robust"
229 )
230
231 # Compute unbiased energies (all biasing forces are zero).
232 # u_n[n] is the reduced potential energy without umbrella restraints of snapshot n
233 u_n = np.zeros([np.sum(N_k)])
234 x_n = np.zeros([np.sum(N_k)])
235
236 Nstart = 0
237 for k in range(K):
238 # u_n[N_k[k]:N_k[k+1]] = - pN_nm_to_kT * (0.0 - biasing_force_k[k]) * x_kn[k,0:N_k[k]]
239 u_n[Nstart : Nstart + N_k[k]] = 0.0 + pN_nm_to_kT * biasing_force_k[k] * (
240 x_kn[k, 0 : N_k[k]] - x0_k[k]
241 )
242 x_n[Nstart : Nstart + N_k[k]] = x_kn[k, 0 : N_k[k]]
243 Nstart += N_k[k]
244
245 # Compute free energy profile in unbiased potential (in units of kT).
246
247 print("Computing free energy profile...")
248 fes = FES(u_kln, N_k, mbar_options=dict(solver_protocol="robust"))
249 histogram_parameters = dict()
250 # 1D array of parameters, one entry because 1D
251 histogram_parameters["bin_edges"] = bin_left_boundary_i
252 fes.generate_fes(u_n, x_n, histogram_parameters=histogram_parameters)
253 results = fes.get_fes(
254 bin_center_i, reference_point="from-lowest", uncertainty_method="analytical"
255 )
256 f_i = results["f_i"]
257 df_i = results["df_i"]
258
259 # compute estimate of FES including Jacobian term
260 fes_i = f_i + np.log(bin_width_i)
261 # Write out unbiased estimate of FES
262 print("Unbiased FES (in units of kT)")
263 print(f"{'bin':>8s} {'f':>8s} {'df':>8s} {'fes':>8s} {'width':>8s}")
264 for i in range(nbins):
265 print(
266 f"{bin_center_i[i]:8.3f}",
267 f"{f_i[i]:8.3f}",
268 f"{df_i[i]:8.3f}",
269 f"{fes_i[i]:8.3f}",
270 f"{bin_width_i[i]:8.3f}",
271 )
272
273 filename = output_directory / "fes-unbiased.out"
274 with open(filename, "w") as outfile:
275 for i in range(nbins):
276 outfile.write(f"{bin_center_i[i]:8.3f} {fes_i[i]:8.3f} {df_i[i]:8.3f}\n")
277
278 fig_filename = plot_directory / f"fes-unbiased.pdf"
279 fig, ax = plt.subplots()
280 ax.errorbar(bin_center_i, fes_i, yerr=df_i, fmt="_ ", elinewidth=0.3)
281 ax.set_title("Unbiased estimate of free energy profile")
282 ax.set_ylabel("Free energy profile of mean force (kT)")
283 ax.set_xlabel("Extension (nm)")
284 fig.savefig(fig_filename)
285
286 # DEBUG
287 stop_time = time.time()
288 elapsed_time = stop_time - start_time
289 print(f"analysis took {elapsed_time:f} seconds")
290
291 # compute observed and expected histograms at each state
292 for l in range(K):
293 # compute FES at state l
294 Nstart = 0
295 for k in range(K):
296 u_n[Nstart : Nstart + N_k[k]] = u_kln[k, l, 0 : N_k[k]]
297 Nstart += N_k[k]
298 fes.generate_fes(u_n, x_n, histogram_parameters=histogram_parameters)
299 results = fes.get_fes(
300 bin_center_i, reference_point="from-lowest", uncertainty_method="analytical"
301 )
302 f_i = results["f_i"]
303 df_i = results["df_i"]
304
305 # compute estimate of FES including Jacobian term
306 fes_i = f_i + np.log(bin_width_i)
307 # center fes
308 fes_i -= fes_i.mean()
309 # compute probability distribution
310 p_i = np.exp(-f_i + f_i.min())
311 p_i /= p_i.sum()
312 # compute observed histograms, filtering to within [x_min,x_max] range
313 N_i_observed = np.zeros([nbins])
314 dN_i_observed = np.zeros([nbins])
315 for t in range(T_k[l]):
316 bin_index = bin_kt[l, t]
317 N_i_observed[bin_index] += 1
318 N = N_i_observed.sum()
319 # estimate uncertainties in observed counts
320 for bin_index in range(nbins):
321 dN_i_observed[bin_index] = np.sqrt(
322 g_k[l] * N_i_observed[bin_index] * (1.0 - N_i_observed[bin_index] / float(N))
323 )
324 # compute expected histograms
325 N_i_expected = float(N) * p_i
326 # only approximate, since correlations df_i df_j are neglected
327 dN_i_expected = np.sqrt(float(N) * p_i * (1.0 - p_i))
328 # plot
329 print(f"state {l:d} ({biasing_force_k[l]:f} pN)")
330 for bin_index in range(nbins):
331 print(
332 f"{bin_center_i[bin_index]:8.3f}",
333 f"{N_i_expected[bin_index]:10f}",
334 f"{N_i_observed[bin_index]:10f} +- {dN_i_observed[bin_index]:10f}",
335 )
336
337 # Write out observed bin counts
338 filename = output_directory / f"counts-observed-{l:d}.out"
339 with open(filename, "w") as outfile:
340 for i in range(nbins):
341 outfile.write(
342 f"{bin_center_i[i]:8.3f} {N_i_observed[i]:16f} {dN_i_observed[i]:16f}\n"
343 )
344
345 # write out expected bin counts
346 filename = output_directory / f"counts-expected-{l:d}.out"
347 with open(filename, "w") as outfile:
348 for i in range(nbins):
349 outfile.write(
350 f"{bin_center_i[i]:8.3f} {N_i_expected[i]:16f} {dN_i_expected[i]:16f}\n"
351 )
352
353 # compute FES from observed counts
354 indices = np.where(N_i_observed > 0)[0]
355 fes_i_observed = np.zeros([nbins])
356 dfes_i_observed = np.zeros([nbins])
357 fes_i_observed[indices] = -np.log(N_i_observed[indices]) + np.log(bin_width_i[indices])
358 fes_i_observed[indices] -= fes_i_observed[indices].mean() # shift observed FES
359 dfes_i_observed[indices] = dN_i_observed[indices] / N_i_observed[indices]
360 # write out observed FES
361 filename = output_directory / f"fes-observed-{l:d}.out"
362 with open(filename, "w") as outfile:
363 for i in indices:
364 outfile.write(
365 f"{bin_center_i[i]:8.3f} {fes_i_observed[i]:8.3f} {dfes_i_observed[i]:8.3f}\n"
366 )
367
368 # Write out unbiased estimate of FES
369 fes_i -= fes_i[indices].mean() # shift to align with observed
370 filename = output_directory / f"fes-expected-{l:d}.out"
371 with open(filename, "w") as outfile:
372 for i in range(nbins):
373 outfile.write(f"{bin_center_i[i]:8.3f} {fes_i[i]:8.3f} {df_i[i]:8.3f}\n")
374
375 # make plots
376 biasing_force = biasing_force_k[l]
377 fig_filename = plot_directory / f"fes-comparison-{l:d}.pdf"
378 fig, ax = plt.subplots()
379 ax.errorbar(
380 bin_center_i, fes_i, yerr=df_i, fmt="x ", elinewidth=0.3, label="MBAR optimal estimate"
381 )
382 ax.errorbar(
383 bin_center_i,
384 fes_i_observed,
385 yerr=dfes_i_observed,
386 fmt="x ",
387 elinewidth=0.3,
388 label="Observed from single experiment",
389 )
390 ax.set_title(f"{prefix.title()} - {biasing_force:.2f} pN")
391 ax.set_ylabel("Free energy of profile (kT)")
392 ax.set_xlabel("Extension (nm)")
393 ax.legend()
394 fig.savefig(fig_filename)
395
396
397 if __name__ == "__main__":
398 main()