def fit_std_curve(i_vals, i_sds, dpx_concs): # Plot the intensity ratios as a function of [DPX]: plt.figure() plt.errorbar(dpx_concs, i_vals, yerr=i_sds, linestyle='', marker='o', color='k', linewidth=2) plt.xlabel('[DPX] (M)') plt.ylabel('$I / I_0$') plt.title('Quenching vs. [DPX]') # Fit the curve using scipy least squares kd = fitting.Parameter(0.05) ka = fitting.Parameter(0.490) def eq2(dpx): return 1. / ((1 + kd()*dpx) * (1 + ka()*dpx)) fitting.fit(eq2, [kd, ka], i_vals, dpx_concs) # Plot curve fit dpx_interp = np.linspace(dpx_concs[0], dpx_concs[-1], 100) plt.plot(dpx_interp, eq2(dpx_interp), color='r', linewidth=2) plt.xlabel('[DPX] (mM)') plt.ylabel('$I / I_0$') plt.title('DPX quenching, standard curve') print "kd: %f" % kd() print "ka: %f" % ka() return (ka(), kd())
def fit_stoichiometric_comp_ols(bid_concs, fret_means, fret_ses): """Obtained the equation for analyzing competitive binding assays from Motulsky's article published here: http://www2.uah.es/farmamol/Public/GraphPad/radiolig.htm """ f = fitting.Parameter(0.40) # FRET efficiency ic50 = fitting.Parameter(6.) # kd for binding lipo sites nonspec = fitting.Parameter(0.1) # baseline quenching total = fitting.Parameter(0.80) def fit_func(bid_conc): frac_bound = nonspec() + ((total() - nonspec()) / (1 + 10 ** (np.log10(bid_conc) - np.log10(ic50())))) return f() * frac_bound fitting.fit(fit_func, [f, ic50, nonspec, total], fret_means, bid_concs) plt.figure('Bid FRET, competitive') plt.errorbar(np.log10(bid_concs), fret_means, yerr=fret_ses, linestyle='', color='r') bid_pred = np.logspace(-1, 3, 100) plt.plot(np.log10(bid_pred), fit_func(bid_pred), color='k') plt.xlabel('log10([Total Bid])') plt.ylabel('FRET Efficiency (%)') print "----" print "ic50: %f" % ic50() print "nonspec: %f" % nonspec() print "total: %f" % total() print "f: %f" % f()
def plot_normalized_to_ref_curve(): data = bgsub_norm_averages ref_index = 1 reference = data[data.keys()[ref_index]][VALUE] # Normalize the reference to [0, 1] reference = ((reference - np.min(reference)) / (np.max(reference) - np.min(reference))) plt.figure() for i, conc_str in enumerate(data.keys()): curve = data[conc_str][VALUE] # Define the minval and maxval fit parameters fit_min_val = fitting.Parameter(0.) fit_max_val = fitting.Parameter(max(curve)) # Define the "model" func (just the normalization equation) def normalization_eqn(y): return ((y - fit_min_val()) / (fit_max_val() - fit_min_val())) fitting.fit(normalization_eqn, [fit_max_val], np.array(reference), np.array(curve)) curve = np.array(curve) normalized_curve = normalization_eqn(np.array(curve)) plt.plot(normalized_curve)
def calc_pore_size_by_slope(): (fmax_arr, k1_arr, k2_arr, conc_list) = \ titration_fits.plot_two_exp_fits(bgsub_norm_wells, layout, plot=True) titration_fits.plot_fmax_curve(fmax_arr, conc_list) titration_fits.plot_k1_curve(k1_arr[:,1:], conc_list[1:]) titration_fits.plot_k2_curve(k2_arr[:,1:], conc_list[1:]) conc_lipos = 5.16 fmax_means = np.mean(fmax_arr, axis=0) fmax_stds = np.std(fmax_arr, axis=0) ratios = conc_list / conc_lipos derivs = np.zeros(len(fmax_means)-1) deriv_sds = np.zeros(len(fmax_means)-1) for i in np.arange(1, len(fmax_means)): if i == 1: prev_mean = 0 prev_sd = 0 else: prev_mean = fmax_means[i-1] prev_sd = fmax_stds[i-1] fmax_diff = fmax_means[i] - prev_mean conc_diff = conc_list[i] - conc_list[i-1] derivs[i-1] = fmax_diff / float(conc_diff) deriv_sds[i-1] = np.sqrt(fmax_stds[i] ** 2 + prev_sd ** 2) plt.figure() #plt.errorbar(conc_list[1:], derivs, yerr=deriv_sds, marker='o', ) plt.errorbar(conc_list[1:], derivs, marker='o', ) plt.title('d[Fmax]/d[Bax]') # Fit with exp dist? exp_lambda = fitting.Parameter(1/20.) def exp_dist(x): return exp_lambda() * np.exp(-exp_lambda() * x) (residuals, result) = fitting.fit(exp_dist, [exp_lambda], derivs, conc_list[1:]) plt.plot(conc_list[1:], exp_dist(conc_list[1:]), color='g') print "exp_lambda: %f" % exp_lambda() # Fit with exp decay exp_c0 = fitting.Parameter(0.005) exp_k = fitting.Parameter(1/50.) def exp_decay(x): return exp_c0() * np.exp(-exp_k() * x) (residuals, result) = fitting.fit(exp_decay, [exp_c0, exp_k], derivs, conc_list[1:]) plt.plot(conc_list[1:], exp_decay(conc_list[1:]), color='r') print "exp_c0: %f" % exp_c0() print "exp_k: %f" % exp_k() # We want to estimate Bax per pore, or pores per Bax, if Bax # holes didn't exist. Basically we want to know the fraction release # we would get if the amount of Bax approached 0. In the case of # the exponential decay, this is the value of exp_c0. # We convert exp_c0 from % release to number of pores: # The derivative dfmax/dBax tells us how much more permeabilization we get # per Bax. At low concentrations, we get a certain amount of release # per Bax that is relatively unaffected by the Bax hole phenomenon. print "exp_c0 * conc_lipos: %f" % (exp_c0() * conc_lipos)
def plot_fmax_curve(fmax_arr, conc_list): fmax_means = np.mean(fmax_arr, axis=0) fmax_sds = np.std(fmax_arr, axis=0) # Plot of Fmax plt.figure() plt.errorbar(conc_list, fmax_means, yerr=fmax_sds / np.sqrt(3), label='Data', linestyle='') plt.ylabel(r'$F_{max}$ value (% Release)') plt.xlabel('[Bax] (nM)') plt.title(r'$F_{max}$') # Try fitting the fmax values to a hill function hill_vmax = fitting.Parameter(0.9) kd = fitting.Parameter(100) def hill(s): return ((hill_vmax() * s) / (kd() + s)) fitting.fit(hill, [kd, hill_vmax], fmax_means, conc_list) plt.plot(conc_list, hill(conc_list), 'r', linewidth=2, label='Hill fit') plt.text(35, 0.93, '$K_D$ = %.2f' % kd(), fontsize=16) plt.text(35, 0.99, '$V_{max}$ = %.2f' % hill_vmax(), fontsize=16) # Try fitting the fmax values to an exponential function exp_fmax = fitting.Parameter(1.0) exp_k = fitting.Parameter(0.01) def exp_func(s): return exp_fmax() * (1 - np.exp(-exp_k()*s)) fitting.fit(exp_func, [exp_fmax, exp_k], fmax_means, conc_list) plt.plot(conc_list, exp_func(conc_list), 'g', linewidth=2, label='Exp fit') plt.legend(loc='lower right') plt.show()
def plot_initial_slope_curves(k_arr, conc_list): """Plots the initial slopes as a function of concentration.""" k_means = np.mean(k_arr, axis=0) k_sds = np.std(k_arr, axis=0) plt.figure() plt.errorbar(conc_list, k_means, yerr= k_sds / np.sqrt(3), color='r', linestyle='', linewidth=2) plt.title('Initial permeabilization rate') plt.xlabel('[Bax] (nM)') plt.ylabel('Rate $(\mathrm{sec}^{-1})$') fmax = fitting.Parameter(1e-3) k = fitting.Parameter(np.log(2)/300.) def exp_func(s): return fmax()*(1 - np.exp(-k()*s)) fitting.fit(exp_func, [fmax, k], k_means, conc_list) plt.plot(conc_list, exp_func(conc_list), color='g', label='Exponential') k_linear = fitting.Parameter(4e-7) num_concs = 7 def linear(s): return k_linear()*s fitting.fit(linear, [k_linear], k_means[0:num_concs], conc_list[0:num_concs]) plt.plot(conc_list, linear(conc_list), color='b', label='Linear (first %d concs)' % num_concs) plt.legend(loc='lower right') plt.ylim([0, np.max(k_means) * 1.05]) return k_linear()
def plot_fret_exp_fits(donor_only): # Plot each fret curve, F_DA/F_D figure() fret = collections.OrderedDict() f_d = bgsub_timecourses['cBid 50 nM + 0 nM liposomes'][VALUE] for i, conc_str in enumerate(bgsub_timecourses.keys()): time = bgsub_timecourses[conc_str][TIME] f_d_plus_a = bgsub_timecourses[conc_str][VALUE] f = f_d_plus_a / donor_only fret[conc_str] = [] fret[conc_str].append(time) fret[conc_str].append(f) plot(time, f, marker='o', linestyle='') f0 = fitting.Parameter(1) k = fitting.Parameter(0.001) fmin = fitting.Parameter(0.6) def exp_decay(t): return f0()*np.exp(-k()*t) + fmin() fitting.fit(exp_decay, [f0, k, fmin], f, time) plot(time, exp_decay(time), marker='', color='gray') ylabel('$F_{D+A} / F_A$') xlabel('Time (sec)') title("FRET timecourses") return fret
def plot_liposome_titration_insertion_kinetics(model): """Plot the insertion kinetics of Bax over a liposome titration.""" lipo_concs = np.logspace(-2, 2, 40) t = np.linspace(0, 12000, 100) fmax_list = [] k_list = [] for lipo_conc in lipo_concs: model.parameters['Vesicles_0'].value = lipo_conc # Get the SS mBax value #b_trans.model.parameters['Vesicles_0'].value = lipo_conc #s = Solver(b_trans.model, t) #s.run() #max_mBax = s.yobs['mBax'][-1] # Get the iBax curve s = Solver(model, t) s.run() iBax = s.yobs['iBax'] / model.parameters['Bax_0'].value plt.plot(t, iBax, 'r') # Fit to single exponential fmax = fitting.Parameter(0.9) k = fitting.Parameter(0.01) def single_exp(t): return (fmax() * (1 - np.exp(-k()*t))) fitting.fit(single_exp, [fmax, k], iBax, t) plt.plot(t, single_exp(t), 'b') fmax_list.append(fmax()) k_list.append(k()) plt.title('Inserted Bax with liposome titration') plt.xlabel('Time') plt.ylabel('Fraction of inserted Bax') plt.show() # Make plots of k and fmax as a function of lipo concentration fmax_list = np.array(fmax_list) k_list = np.array(k_list) # k plt.figure() plt.plot(lipo_concs, k_list, 'ro') plt.xlabel('Liposomes (nM)') plt.ylabel('$k$') plt.title("$k$ vs. Liposome conc") plt.ylim([0, 0.0020]) plt.show() # Fmax plt.figure() plt.plot(lipo_concs, fmax_list, 'ro') plt.xlabel('Liposomes (nM)') plt.ylabel('$F_{max}$') plt.title("$F_{max}$ vs. Liposome conc") plt.show()
def plot_normalized(bid_conc=0, bid_conc_for_normalization=0, subtract_background=True, do_fit=False, t0_val=None): plt.figure() k1_arr = [] fmax_arr = [] t0_arr = [] for conc_index in range(NUM_CONCS): time = np.array(data[bid_conc][bax_concs[conc_index]][:].index.values, dtype='float') conc_data = data[bid_conc][bax_concs[conc_index]][:].values f0 = data[bid_conc_for_normalization] \ [bax_concs[conc_index]][1].values[0] if subtract_background: # from 0 Bax timecourse bg = data[bid_conc][0][:].mean(axis=1).values conc_data = np.subtract(conc_data.T, bg).T f0 = f0 - bg[0] conc_data = conc_data / float(f0) # Plots the fits if desired if do_fit: fmax = fitting.Parameter(3.) k1 = fitting.Parameter(0.0005) def one_exp(t): return 1. + fmax() * (1 - np.exp(-k1() * (t + t0()))) # Check if we're supposed to fit the t0 parameter or not if t0_val is None: t0 = fitting.Parameter(556) fitting.fit(one_exp, [fmax, k1, t0], np.mean(conc_data, axis=1), time) else: t0 = fitting.Parameter(t0_val) fitting.fit(one_exp, [fmax, k1], np.mean(conc_data, axis=1), time) k1_arr.append(k1()) fmax_arr.append(fmax()) t0_arr.append(t0()) # Plot plt.plot(time, one_exp(time), color='k') plt.plot(time, np.mean(conc_data, axis=1), label='Bax %s nM' % bax_concs[conc_index]) else: plt.errorbar(time, np.mean(conc_data, axis=1), yerr=np.std(conc_data, axis=1) / np.sqrt(3), label='Bax %s nM' % bax_concs[conc_index]) box = plt.gca().get_position() plt.gca().set_position([box.x0, box.y0, box.width * 0.8, box.height]) plt.legend(loc='upper left', prop=fontP, ncol=1, bbox_to_anchor=(1, 1), fancybox=True, shadow=True) plt.title(r'Normalized ($F/F_0$) by %s nM cBid $F_0$' % \ bid_conc_for_normalization) plt.show() if do_fit: return (k1_arr, fmax_arr, t0_arr) else: return None
def plot_bax_titration_insertion_kinetics(model): """Plot the insertion kinetics of Bax over a Bax titration.""" bax_concs = np.logspace(-1, 3, 40) t = np.linspace(0, 12000, 100) fmax_list = [] k_list = [] for bax_conc in bax_concs: model.parameters['Bax_0'].value = bax_conc # Get the iBax curve s = Solver(model, t) s.run() iBax = s.yobs['iBax'] / model.parameters['Bax_0'].value plt.plot(t, iBax, 'r') # Fit to single exponential fmax = fitting.Parameter(0.9) k = fitting.Parameter(0.01) def single_exp(t): return (fmax() * (1 - np.exp(-k()*t))) fitting.fit(single_exp, [fmax, k], iBax, t) plt.plot(t, single_exp(t), 'b') fmax_list.append(fmax()) k_list.append(k()) plt.title('Inserted Bax with Bax titration') plt.xlabel('Time') plt.ylabel('Fraction of inserted Bax') plt.show() # Make plots of k and fmax as a function of lipo concentration fmax_list = np.array(fmax_list) k_list = np.array(k_list) # k plt.figure() plt.plot(bax_concs, k_list, 'ro') plt.xlabel('Bax (nM)') plt.ylabel('$k$') plt.title("$k$ vs. Bax conc") plt.show() # Fmax plt.figure() plt.plot(bax_concs, fmax_list, 'ro') plt.xlabel('Bax (nM)') plt.ylabel('$F_{max}$') plt.title("$F_{max}$ vs. Bax conc") plt.show()
def plot_fits(means, log_means, conc_list, log_concs): # Ignore any NaNs # Take mean of all dilution series dilution_means = np.mean(means, axis=1) nans = np.isnan(dilution_means) dilution_means = dilution_means[nans==False] dilution_stds = np.std(means[nans==False], axis=1) # Take mean of all dilution series infs = np.isinf(log_concs) log_dilution_means = np.mean(log_means[(infs + nans) == False], axis=1) log_dilution_stds = np.std(log_means[(infs + nans) == False], axis=1) conc_list_no_nan = conc_list[nans == False] conc_list_nonan_noinf = conc_list[(infs + nans) == False] log_concs_nonan_noinf = log_concs[(infs + nans) == False] # Fit with line m = fitting.Parameter(900) b = fitting.Parameter(0) def linear(x): return m()*x + b() fitting.fit(linear, [m, b], dilution_means, conc_list_no_nan) print "m: %f" % m() print "b: %f" % b() r_squared = fitting.r_squared(dilution_means, linear(conc_list_no_nan)) print "R^2: %f" % r_squared figure() errorbar(conc_list_no_nan, dilution_means, yerr=dilution_stds, color='r', linestyle='') plot(conc_list_no_nan, linear(conc_list_no_nan), color='r', label='Linear') xlabel('[Fluorescein] (nM)') ylabel('RFU') title('Fits to Fluorescein titration') legend(loc='lower right') figure() errorbar(log_concs_nonan_noinf, log_dilution_means, yerr=log_dilution_stds, color='r', linestyle='') plot(log_concs_nonan_noinf, np.log10(linear(conc_list_nonan_noinf)), color='r', label='Linear') legend(loc='lower right') xlabel('log10([Fluorescein]) (nM)') ylabel('log10(RFU)') title('Fits to Fluorescein titration, log-log')
def plot_k_fmax_scaling(k_data, fmax_data, bid_ix, bax_concs, plot_filename=None): """Plot Fmax and k vs. Bax concentration for a given Bid concentration.""" assert k_data.shape == fmax_data.shape, \ "k_data and f_max data must have same dimensions" fig = plt.figure('exp_fits_k_fmax_var', figsize=(1.9, 1.5), dpi=300) ax1 = fig.gca() # Plot Fmax vs. concentration on the left-hand axis ax1.plot(bax_concs, fmax_data[bid_ix, :], marker='o', markersize=3, color='b', linestyle='') ax1.set_xlabel('[Bax] (nM)') ax1.set_ylabel('$F_{max}$', color='b') ax1.set_xlim([0, 1100]) for tl in ax1.get_yticklabels(): tl.set_color('b') ax1.set_xscale('log') slope = fitting.Parameter(1.) intercept = fitting.Parameter(1.) def log_line(x): log_concs = np.log10(x) return slope() * log_concs + intercept() fitting.fit(log_line, [slope, intercept], fmax_data[bid_ix, :], bax_concs) ax1.plot(bax_concs, log_line(bax_concs), color='b') # Plot k vs. concentration on the right-hand axis ax2 = ax1.twinx() #ax2.set_xlim([0.05, 30]) ax2.plot(bax_concs, k_data[bid_ix,:], marker='o', markersize=3, color='r') ax2.set_ylabel(r'k (sec$^{-1} \times\ 10^{-5}$)', color='r') for tl in ax2.get_yticklabels(): tl.set_color('r') ax2.set_xlim([0, 1100]) ax2.set_ylim(5e-5, 3e-4) ax2.set_yticks(np.linspace(5e-5, 3e-4, 6)) ax2.set_yticklabels([str(int(f)) for f in np.linspace(5, 30, 6)]) format_axis(ax1) format_axis(ax2, yticks_position='right') plt.subplots_adjust(left=0.18, bottom=0.19, right=0.75) if plot_filename: fig.savefig('%s.pdf' % plot_filename) fig.savefig('%s.png' % plot_filename, dpi=300)
def plot_fit_donor_only(): # Fit the background (donor-only) to a line m = fitting.Parameter(0) b = fitting.Parameter(26000) def linear(x): return m()*x + b() t = timecourse_averages['cBid 50 nM + 0 nM liposomes'][TIME] x = timecourse_averages['cBid 50 nM + 0 nM liposomes'][VALUE] fitting.fit(linear, [m, b], x, t) figure() plot(t, x) plot(t, linear(t)) xlabel('Time (sec)') ylabel('RFU') title('Linear fit of Bid-only control') return linear(t)
def plot_k_titration(fits): bid_concs = [] k_means = [] k_ses = [] for cond_name in bid_fits.keys(): fits = bid_fits[cond_name] bid_conc = float(cond_name.split(' ')[1]) bid_concs.append(bid_conc) num_reps = fits.shape[0] k_means.append(np.mean(fits[:,1])) k_ses.append(np.std(fits[:,1]) / np.sqrt(num_reps)) bid_concs = np.array(bid_concs) k_means = np.array(k_means) plt.figure('k') plt.errorbar(np.log10(bid_concs), k_means, yerr=k_ses, color='k') kd1 = fitting.Parameter(1.) k0 = fitting.Parameter(2e-5) kmax1 = fitting.Parameter(2e-4) slope = fitting.Parameter(1e-8) def hill_func_line(concs): return (k0() + ((kmax1() * concs) / (kd1() + concs)) + (slope() * concs)) res = fitting.fit(hill_func_line, [kd1, k0, kmax1, slope], np.array(k_means), np.array(bid_concs)) plt.figure('k') plt.plot(np.log10(bid_concs), hill_func_line(bid_concs), color='b') #plt.plot(np.log10(bid_concs), slope() * bid_concs, color='r') #plt.plot(np.log10(bid_concs), # k0() + ((kmax1()*bid_concs) / (kd1() + bid_concs)), color='g') kd1 = fitting.Parameter(1.) k0 = fitting.Parameter(7e-5) kmax1 = fitting.Parameter(2e-4) def hill_func_k(concs): return (k0() + ((kmax1() * concs) / (kd1() + concs))) res = fitting.fit(hill_func_k, [kd1, k0, kmax1], np.array(k_means), np.array(bid_concs)) plt.figure('k') plt.plot(np.log10(bid_concs), hill_func_k(bid_concs), color='r')
def normalize_fit(replicates): """ Find normalization parameters that minimize differences between replicates. Chooses one (the first) trajectory as a reference, and then chooses appropriate scaling parameters (min and max vals) to minimize the deviation of the other trajectories from the reference trajectory. Parameters ---------- replicates : list of numpy.array objects Each entry in the list is a numpy.array containing the data for one repeat of the experiment. Returns ------- list of numpy.array objects The replicate data after normalization. """ normalized_replicates = [] # Choose the first replicate (arbitrarily) as the one to fit to, # and normalize it to the range [0, 1] reference = array(replicates[0]) reference = (reference - min(reference)) / (max(reference) - min(reference)) normalized_replicates.append(reference) # For the other replicates, let min val and max val be fit so # as to minimize deviation from the normalized first replicate for replicate in replicates[1:len(replicates)]: # Define the minval and maxval fit parameters fit_min_val = Parameter(min(replicate)) fit_max_val = Parameter(max(replicate)) # Define the "model" func (just the normalization equation) def normalization_eqn(repl): return ((repl - fit_min_val()) / (fit_max_val() - fit_min_val())) fit(normalization_eqn, [fit_min_val, fit_max_val], array(reference), array(replicate)) replicate = array(replicate) normalized_replicate = normalization_eqn(array(replicate)) normalized_replicates.append(normalized_replicate) return normalized_replicates
def approach_1(wells, layout): """In this approach, we take the mean of each condition and then perform a single fit to the mean. We then plot the value of each parameter as a function of the concentration to look for patterns. Note that the data is expected to be in raw format, not pre-averaged. """ (avgs, stderrs) = averages(wells, layout, stderr=True) num_concs = len(layout.keys()) min_rfu_arr = np.zeros((num_concs, 2)) max_rfu_arr = np.zeros((num_concs, 2)) k_arr = np.zeros((num_concs, 2)) conc_list = np.zeros(num_concs) plt.figure() num_rows = 4 num_cols = 3 for i, conc_str in enumerate(layout.keys()): print conc_str conc = float(conc_str.split(' ')[1]) conc_list[i] = conc time = avgs[conc_str][TIME][0:100] curve = avgs[conc_str][VALUE][0:100] plt.subplot(num_rows, num_cols, i+1) plt.errorbar(time, curve, yerr=stderrs[conc_str][VALUE][0:100]) # Define the parameters max_rfu = fitting.Parameter(np.max(curve)) min_rfu = fitting.Parameter(np.min(curve)) k = fitting.Parameter(1e-4) def exp_func(t): return (max_rfu() - min_rfu())*(1 - np.exp(-k()*t)) + min_rfu() result = fitting.fit(exp_func, [max_rfu, min_rfu, k], curve, time) cov_x = result[1] plt.plot(time, exp_func(time), color='r') plt.title(conc_str) plt.xlabel('Time (sec)') plt.ylabel('ANTS (RFU)') max_rfu_arr[i] = [max_rfu(), np.sqrt(cov_x[0, 0])] min_rfu_arr[i] = [min_rfu(), np.sqrt(cov_x[1, 1])] k_arr[i] = [k(), np.sqrt(cov_x[2, 2])] plt.tight_layout(pad=0, w_pad=0, h_pad=0) # Plot values of fitted parameters plt.figure() plt.errorbar(conc_list, k_arr[:,0], yerr=k_arr[:,1], marker='o') plt.figure() plt.errorbar(conc_list, min_rfu_arr[:,0], yerr=min_rfu_arr[:,1], marker='o') plt.figure() plt.errorbar(conc_list, max_rfu_arr[:,0], yerr=max_rfu_arr[:,1], marker='o') plt.figure() plt.plot(conc_list, (max_rfu_arr[:,0] - min_rfu_arr[:,0])/min_rfu_arr[:,0], marker='o') plt.title('Percent increase') import ipdb; ipdb.set_trace()
def calc_exp_fits(data_norm): """Fit each of the timecourses in the data matrix to an exponential func. Parameters ---------- data_norm : np.array Four-dimensional numpy array, with dimensions [bid, bax, datatype (time or value), timepoints] Returns ------- tuple of two np.arrays The first array contains the fitted k values, the second the fitted fmax values. Both are of dimension [bid concs, bax_concs]. """ fmax_data = np.zeros((len(bid_concs), len(bax_concs))) k_data = np.zeros((len(bid_concs), len(bax_concs))) fmax_sd_data = np.zeros((len(bid_concs), len(bax_concs))) k_sd_data = np.zeros((len(bid_concs), len(bax_concs))) for bid_ix in range(data_norm.shape[0]): for bax_ix in range(data_norm.shape[1]): t = data_norm[bid_ix, bax_ix, TIME, :] v = data_norm[bid_ix, bax_ix, VALUE, :] # Get an instance of the fitting function k = fitting.Parameter(1e-4) fmax = fitting.Parameter(3.) def fit_func(t): return 1 + fmax() * (1 - np.exp(-k()*t)) # Subtract 1 so that the curves start from 0 (residuals, result) = fitting.fit(fit_func, [k, fmax], v, t) cov_matrix = result[1] #(k, fmax) = fit.fit_timecourse(t, v) k_data[bid_ix, bax_ix] = k() fmax_data[bid_ix, bax_ix] = fmax() #import ipdb; ipdb.set_trace() # Get variance estimates [k_sd, fmax_sd] = np.sqrt(np.diag(np.var(residuals, ddof=1) * cov_matrix)) k_sd_data[bid_ix, bax_ix] = k_sd fmax_sd_data[bid_ix, bax_ix] = fmax_sd # Some diagnostic plots (commented out) #plt.figure() #plt.plot(t, v, 'k') #plt.plot(t[:numpts], intercept + lin_fit[0] * t[:numpts], 'r') #plt.figure() #plt.plot(t, v / intercept - 1) #plt.plot(t, fit.fit_func(t, [k, fmax])) return (k_data, k_sd_data, fmax_data, fmax_sd_data)
def plot_k1_curve(k1_arr, conc_list): k1_means = np.mean(k1_arr, axis=0) k1_sds = np.std(k1_arr, axis=0) plt.figure() plt.errorbar(conc_list, k1_means, yerr= k1_sds / np.sqrt(3), color='r', linestyle='', linewidth=2) plt.title('$k_1$') plt.xlabel('[Bax] (nM)') plt.ylabel('$k_1\ (\mathrm{sec}^{-1})$') # Fit with exponential-linear curve vi = fitting.Parameter(0.05) vf = fitting.Parameter(0.025) tau = fitting.Parameter(0.02) # Define fitting function def biphasic(t): return (vf()*t) + ( (vi() - vf()) * ((1 - np.exp(-tau()*t))/tau()) ) fitting.fit(biphasic, [vi, vf, tau], k1_means, conc_list) plt.plot(conc_list, biphasic(conc_list), 'r', linewidth=2) # Fit with "double-binding curve" ksat = fitting.Parameter(0.0005) knonsat = fitting.Parameter(20) R0 = fitting.Parameter(20) def double_binding(t): return (R0() * t)/(ksat() + t) + (knonsat()*t) fitting.fit(double_binding, [R0, ksat, knonsat], k1_means, conc_list) plt.plot(conc_list, double_binding(conc_list), 'g', linewidth=2) plt.text(400, 0.00025, r'$\frac{R_0 Bax_0}{K_{sat} + Bax_0} + K_{nonsat} Bax_0$') plt.text(400, 0.00020, r'$R_0$ = %.3g nM' % R0()) plt.text(400, 0.00015, r'$K_{sat}$ = %.3g nM' % ksat()) plt.text(400, 0.00010, r'$K_{nonsat}$ = %.3g nM' % knonsat()) plt.text(35, 0.00054, r'$v_f + (v_i - v_f) \left(\frac{1 - e^{-\tau t}}{\tau}\right)$') plt.text(35, 0.00049, r'$v_i$ = %.3g sec$^{-1}$ nM$^{-1}$' % vi()) plt.text(35, 0.00044, r'$v_f$ = %.3g sec$^{-1}$ nM$^{-1}$' % vf()) plt.text(35, 0.00039, r'$\frac{1}{\tau}$ = %.2f nM' % (1/tau())) plt.title('Biphasic fit of $k_1$') plt.show()
def fit_average_by_leastsq(self, reps): """Fit the average with an exponential model Returns a dict with the parameter values for the fit. """ avg_trajectory = np.mean(reps, axis=0) k_p = fitting.Parameter(np.log(2)/6000.) initial_rfu_p = fitting.Parameter(avg_trajectory[0]) pct_increase_p = fitting.Parameter((avg_trajectory[-1]-avg_trajectory[0])/ avg_trajectory[0]) def exp_func(t): return (pct_increase_p() * initial_rfu_p()) * (1 - np.exp(-k_p() * t)) + \ initial_rfu_p() fitting.fit(exp_func, [k_p, initial_rfu_p, pct_increase_p], avg_trajectory, self.t) return {'k': k_p(), 'initial_rfu': initial_rfu_p(), 'pct_increase': pct_increase_p()}
def fit_data(mcmc_set): data = mcmc_set.chains[0].data fmax_arr = np.zeros(len(data.columns)) k1_arr = np.zeros(len(data.columns)) k2_arr = np.zeros(len(data.columns)) bax_concs = np.array(data.columns, dtype='float') for i, bax_conc in enumerate(bax_concs): conc_data = data[bax_conc] time = conc_data[:, 'TIME'] y = conc_data[:, 'MEAN'] fmax = fitting.Parameter(0.9) k1 = fitting.Parameter(0.01) k2 = fitting.Parameter(0.001) def two_part_exp(t): return (fmax() * (1 - np.exp(-k1() * (1 - np.exp(-k2()*t)) * t))) fitting.fit(two_part_exp, [fmax, k1, k2], y, time) fmax_arr[i] = fmax() k1_arr[i] = k1() k2_arr[i] = k2() two_exp_fits_dict['data'] = (fmax_arr, k1_arr, k2_arr)
def fit_timecourse(self, time, y): """Fit a single timecourse with the desired function. Parameters ---------- time : numpy.array Vector of time values. y : numpy.array Vector of y-axis values (e.g., dye release). Returns ------- list of numbers The best-fit parameter values produced by the fitting procedure. """ params = [fitting.Parameter(self.initial_guesses[i]) for i in range(len(self.initial_guesses))] def fit_func_closure(t): return self.fit_func(t, [p() for p in params]) fitting.fit(fit_func_closure, params, y, time, log_transform=self.log_transform) return [p() for p in params]
def fit_gouy_chapman_ols(bid_concs, fret_means, fret_ses): lipid_conc = 129.8 # uM; 0.1 (mg/mL); ~1.5 nM liposomes v = fitting.Parameter(6.) # charges per peptide chain b = fitting.Parameter(1.) # dimensionless pc = fitting.Parameter(1.) # partition coefficient f = fitting.Parameter(0.35) # FRET efficiency f0 = fitting.Parameter(0.095) # baseline quenching r = np.logspace(-3, 0, 1000) def cf(r): return (r * alpha(r)) / pc() def alpha(r): log_alpha = 2 * v() * np.arcsinh(v() * b() * r) return np.exp(log_alpha) def fit_func(bid_concs): cb = r * lipid_conc cfr = cf(r) ctot = cb + cfr fracs_bound = cb / ctot interp_fracs = np.interp(bid_concs, ctot, fracs_bound) return f() * interp_fracs + f0() fitting.fit(fit_func, [v, b, pc, f, f0], fret_means, bid_concs) plt.figure() plt.errorbar(np.log10(bid_concs), fret_means, yerr=fret_ses, linestyle='', color='r') bid_pred = np.logspace(-1, 3, 100) plt.plot(np.log10(bid_pred), fit_func(bid_pred), color='k') plt.xlabel('log10([Total Bid])') plt.ylabel('FRET Efficiency (%)') print f0() print f() print v() print b() print pc()
def estimate_background_residuals(): """Perform a fit of each background trajectory separately and then use these fits to estimate the variance of the residuals due to measurement error.""" buffer_wells = extract(layout['Buffer'], timecourse_wells) plot_all(buffer_wells) (time_arr, buffer_reps) = get_replicates_for_condition( timecourse_wells, layout, 'Buffer') print "bg_init k_decay k_linear bg_bg" num_timepoints = len(time_arr) num_replicates = buffer_reps.shape[1] residuals = np.zeros((num_timepoints, num_replicates)) param_matrix = np.zeros((num_replicates, 4)) for i in range(num_replicates): plt.figure() plt.plot(time_arr, buffer_reps[:,i]) bg_init = fitting.Parameter(1.) k_decay = fitting.Parameter(1e-2) bg_bg = fitting.Parameter(5.6) k_linear = fitting.Parameter(1e-4) def exp_decay(t): return bg_init()*np.exp(-k_decay() * t) - k_linear()*t + bg_bg() (residuals[:,i], result) = fitting.fit(exp_decay, [bg_init, k_decay, bg_bg, k_linear], buffer_reps[:,i], time_arr) plt.plot(time_arr, exp_decay(time_arr), linewidth=2, color='r') print bg_init(), k_decay(), k_linear(), bg_bg() param_matrix[i,:] = [bg_init(), k_decay(), k_linear(), bg_bg()] plt.figure() plt.hist(residuals.reshape(num_replicates * num_timepoints)) print "Mean" print np.mean(residuals) print "Variance" print np.var(residuals) print "SD" print np.std(residuals) print param_matrix print "Mean" print np.mean(param_matrix, axis=0) print "SD" print np.std(param_matrix, axis=0) return np.var(residuals)
def fit_basic_binding_curve_ols(bid_concs, fret_means, fret_ses): kd = fitting.Parameter(6.) # kd for binding lipo sites f = fitting.Parameter(0.30) # FRET efficiency f0 = fitting.Parameter(0.10) # baseline quenching def fit_func(bid_conc): frac_bound = bid_conc / (bid_conc + kd()) frac_dye = 10. / bid_conc frac_dye_bound = frac_bound * frac_dye return f() * frac_dye_bound + f0() fitting.fit(fit_func, [kd, f], fret_means, bid_concs) plt.figure('Bid FRET') plt.errorbar(np.log10(bid_concs), fret_means, yerr=fret_ses, linestyle='', color='r') bid_pred = np.logspace(-1, 3, 100) plt.plot(np.log10(bid_pred), fit_func(bid_pred), color='k') plt.xlabel('log10([Total Bid])') plt.ylabel('FRET Efficiency (%)') print "Kd: %f" % kd() print "f: %f" % f() print "f0: %f" % f0()
def fit_fda_and_fd_curves(wells, fda, fd, fa, bg): # Get the background averages bg_avg = get_average_bg(wells, bg, plot=False) fa_avg = get_average_fa(wells, fa, plot=False) # Now, plot the curves, with fits for conc_name in fda.keys(): plt.figure() # FDA for well_name in fda[conc_name]: fda_value = np.array(wells[well_name][VALUE]) # Subtract the FA background: fda_value = fda_value - fa_avg # Do the fit f0 = fitting.Parameter(3500.) fmax = fitting.Parameter(2000.) k = fitting.Parameter(1e-3) def fit_func(t): return fmax()*np.exp(-k()*t) + f0() res = fitting.fit(fit_func, [f0, fmax, k], fda_value, time) # Plot data and fit plt.plot(time, fda_value) plt.plot(time, fit_func(time), color='k', linewidth=2) # FD for well_name in fd[conc_name]: fd_value = np.array(wells[well_name][VALUE]) # Subtract the BG background: fd_value = fd_value - bg_avg # Do the fit f0 = fitting.Parameter(3500.) fmax = fitting.Parameter(2000.) k = fitting.Parameter(1e-3) def fit_func(t): return fmax()*np.exp(-k()*t) + f0() res = fitting.fit(fit_func, [f0, fmax, k], fd_value, time) # Plot data and fit plt.plot(time, fd_value) plt.plot(time, fit_func(time), color='k', linewidth=2)
def plot_requenching_result(req_results, plot_filename): # Publication-quality figure of result f_outs = req_results['f_outs'] q_ins = req_results['q_ins'] f_out_errs = req_results['f_out_errs'] q_in_errs = req_results['q_in_errs'] plt.figure(figsize=(1.5, 1.5), dpi=300) plt.errorbar(f_outs, q_ins, xerr=f_out_errs, yerr=q_in_errs, marker='o', markersize=2, color='k', linestyle='', capsize=1) ax = plt.gca() #for i in range(len(f_outs)): # ax.add_patch(patches.Rectangle((f_outs[i], q_ins[i]), # f_out_errs[i], q_in_errs[i], alpha=0.5)) #plt.plot(f_outs[0:12], q_ins[0:12], marker='o', color='r', linestyle='') #plt.plot(f_outs[12:24], q_ins[12:24], marker='o', color='g', linestyle='') #plt.plot(f_outs[24:36], q_ins[24:36], marker='o', color='b', linestyle='') plt.xlabel('$F_{out}$') plt.ylabel('$Q_{in}$') plt.xlim([0, 1]) plt.ylim([0, 0.5]) format_axis(ax) const = fitting.Parameter(0.1) def fit_func(x): return const() fitting.fit(fit_func, [const], q_ins, f_outs) plt.hlines(const(), 0, 1, color='r') #linfit = scipy.stats.linregress(f_outs, q_ins) #f_out_pred = np.linspace(0, 1, 100) #plt.plot(f_out_pred, (f_out_pred * linfit[0]) + linfit[1], color='r', # alpha=0.5) #plt.title('$Q_{in}$ vs. $F_{out}$') plt.subplots_adjust(left=0.23, bottom=0.2) plt.savefig('%s.pdf' % plot_filename) plt.savefig('%s.png' % plot_filename, dpi=300)
def fit_timecourses(layout, timecourses, plot=True): """Fit all timecourses in the experiment.""" # We'll be doing a 3 parameter fit num_params = 3 # This is where we'll store the results of the fitting param_dict = collections.OrderedDict() # Iterate over all of the conditions in the layout for cond_name, rep_list in layout.iteritems(): # How many replicates for this condition? num_reps = len(rep_list) # Set up a plot to show the fits if plot: plt.figure(cond_name, figsize=(6, 2), dpi=150) plots_per_row = 3 # Create an entry in the resulting param dict for this condition. # Results will be stored in a matrix with shape (num_reps, num_params) param_matrix = np.zeros((num_reps, num_params)) # Now iterate over every well in the replicate list for rep_ix, well_name in enumerate(rep_list): # Get the time and fluorescence vectors time = timecourses[well_name][TIME] value = timecourses[well_name][VALUE] # Set up the fitting procedure: first define the parameters fmax = fitting.Parameter(2.1) f0 = fitting.Parameter(2.3) k = fitting.Parameter(1.4e-4) # Define the fitting function def exp_func(t): return (fmax() * f0()) * (1 - np.exp(-k() * t)) + f0() # Do the fit res = fitting.fit(exp_func, [fmax, k, f0], value, time) # Save the values in the order: (fmax, k, f0) param_matrix[rep_ix, 0] = fmax() param_matrix[rep_ix, 1] = k() param_matrix[rep_ix, 2] = f0() # Plot into the appropriate subplot if plot: plt.subplot(1, num_plots_per_row, rep_ix+1) plt.plot(time, value, color='r') plt.plot(time, exp_func(time), color='k', linewidth=2) plt.xlabel('Time (sec)') plt.ylabel('RFU') # Store the resulting parameter matrix in the dict entry for this cond param_dict[cond_name] = param_matrix return param_dict
def estimate_bg_release(): lipo_wells = extract(layout['Bax 0 nM'], timecourse_wells) plot_all(lipo_wells) (time_arr, lipo_reps) = get_replicates_for_condition( timecourse_wells, layout, 'Bax 0 nM') num_timepoints = len(time_arr) num_replicates = lipo_reps.shape[1] residuals = np.zeros((num_timepoints, num_replicates)) param_matrix = np.zeros((num_replicates, 2)) avg_bg = timecourse_averages['Buffer'][VALUE] for i in range(num_replicates): plt.figure() plt.plot(time_arr, lipo_reps[:,i]) bg_sub = lipo_reps[:,i] - avg_bg plt.plot(time_arr, bg_sub) lipo_init = fitting.Parameter(20.) k_app = fitting.Parameter(1e-2) def linear(t): return lipo_init() + k_app()*t (residuals[:,i], result) = fitting.fit(linear, [lipo_init, k_app], bg_sub, time_arr) plt.plot(time_arr, linear(time_arr), linewidth=2, color='r') print lipo_init(), k_app() param_matrix[i,:] = [lipo_init(), k_app()] plt.figure() plt.hist(residuals.reshape(num_replicates * num_timepoints)) print "Mean" print np.mean(residuals) print "Variance" print np.var(residuals) print "SD" print np.std(residuals) print param_matrix print "Mean" print np.mean(param_matrix, axis=0) print "SD" print np.std(param_matrix, axis=0) return
def plot_lipo_background(wells, layout): """Takes the lipo background well timecourses and plots the fluorescence values of the initial points as a function of lipo concentration. Shows that the liposome background fluorescence is strictly linear. """ init_vals = np.zeros(len(layout.keys())) conc_list = np.zeros(len(layout.keys())) for i, cond_name in enumerate(layout): conc = float(cond_name.split(" ")[1]) well_name = layout[cond_name][0] init_val = wells[well_name][VALUE][0] init_vals[i] = init_val conc_list[i] = conc # Fit the liposome background to a line print "Fitting liposome background" m = fitting.Parameter(1.0) b = fitting.Parameter(1.0) def linear(s): return m() * s + b() result = fitting.fit(linear, [m, b], init_vals, conc_list) plt.figure() plt.plot(conc_list, init_vals, marker="o", linestyle="", color="b") plt.plot(conc_list, linear(conc_list), color="r") plt.xlabel("Liposome concentration (mg/ml)") plt.ylabel("RFU") plt.title("Liposome background fluorescence at t=0") ax = plt.gca() ax.set_xscale("log") print "m: %f" % m() print "b: %f" % b() return [m(), b()]
def approach_3(timecourse_wells, layout): """Global fit of all curves by least squares.""" # Get the average trajectories, with standard errors (avgs, stderrs) = averages(timecourse_wells, layout, stderr=True) #(avgs, stderrs) = averages(timecourse_wells, layout, stderr=False) # Build full matrix of all timecourse averages and SDs num_concs = len(layout.keys()) num_timepoints = 100 time_arr = np.zeros((num_timepoints, num_concs)) avg_arr = np.zeros((num_timepoints, num_concs)) std_arr = np.zeros((num_timepoints, num_concs)) conc_list = np.zeros(num_concs) for i, conc_str in enumerate(layout.keys()): conc = float(conc_str.split(' ')[1]) conc_list[i] = conc time_arr[:, i] = avgs[conc_str][TIME][:num_timepoints] avg_arr[:, i] = avgs[conc_str][VALUE][:num_timepoints] std_arr[:, i] = stderrs[conc_str][VALUE][:num_timepoints] # Starting value for highest concentration min_initial = np.min(avg_arr[0,:]) max_initial = avg_arr[0,0] max_conc = conc_list[0] min_final = np.min(avg_arr[-1,:]) max_final = avg_arr[-1,0] min_int = fitting.Parameter(min_initial) min_slope = fitting.Parameter((max_initial - min_initial) / max_conc) max_int = fitting.Parameter(min_final) max_slope = fitting.Parameter((max_final - min_final) / max_conc) k = fitting.Parameter(1.2e-4) avg_arr_lin = avg_arr.T.reshape(num_timepoints * num_concs) def exp_func(t, conc, min_int, min_slope, max_int, max_slope, k): max_val = max_slope * conc + max_int min_val = min_slope * conc + min_int return (max_val - min_val) * (1 - np.exp(-k * t)) + min_val def exp_matrix(t): result = np.zeros((num_timepoints*num_concs)) for i, conc in enumerate(conc_list): result[i*num_timepoints:(i+1)*num_timepoints] = \ exp_func(t, conc, min_int(), min_slope(), max_int(), max_slope(), k()) return result fitting.fit(exp_matrix, [min_int, min_slope, max_int, max_slope, k], avg_arr_lin, time_arr[:,0]) plt.figure() plt.plot(conc_list, avg_arr[0,:], marker='o') plt.plot(conc_list, [min_slope()*conc + min_int() for conc in conc_list], marker='o') plt.figure() num_rows = 4 num_cols = 3 def well_exp(initial_val, t): return 0.05*initial_val*(1 - np.exp(-1.5e-4 * t)) + initial_val for i, conc_str in enumerate(layout.keys()): print conc_str conc = float(conc_str.split(' ')[1]) conc_list[i] = conc time = avgs[conc_str][TIME][0:100] curve = avgs[conc_str][VALUE][0:100] plt.subplot(num_rows, num_cols, i+1) plt.errorbar(time, curve, yerr=stderrs[conc_str][VALUE][0:100], color='b') plt.plot(time, exp_func(time, conc, min_int(), min_slope(), max_int(), max_slope(), k()), color='r') plt.plot(time, well_exp(curve[0], time), color='g') plt.title(conc_str) import ipdb; ipdb.set_trace()
plt.figure() k_list = [] # Perform titration mgtp_concs = np.arange(1, 15) * 1000 # nM (1 - 15 uM) for mgtp_conc in mgtp_concs: # Titration of labeled GTP: model.parameters['mGTP_0'].value = mgtp_conc sol.run() # Fit to an exponential function to extract the pseudo-first-order rates k = fitting.Parameter(1.) def expfunc(t): return 500 * (1 - np.exp(-k() * t)) res = fitting.fit(expfunc, [k], sol.yexpr['HRAS_mGXP_'], t) # Plot data and fits plt.plot(t, sol.yexpr['HRAS_mGXP_'], color='b') plt.plot(t, expfunc(t), color='r') # Keep the fitted rate k_list.append(k()) # Plot the scaling of rates with mGTP concentration plt.figure() plt.plot(mgtp_concs, k_list, marker='o') plt.ylim(bottom=0) # Figure 3: # A constant amount of labeled GDP