Example #1
0
def plot_endpoints_vs_bax(data_norm, time_pts, bid_ix, bax_concs,
                          plot_filename=None, avg_pts=10):
    # Plot endpoints at 2, 3, and 5 hours
    fig = plt.figure(figsize=(1.5, 1.5), dpi=300)
    ax = fig.gca()
    colors = ['r', 'g', 'b']
    for i, time_ix in enumerate(time_pts):
        # Get endpoint vector
        start_ix = time_ix - avg_pts
        f_avg = np.mean(data_norm[bid_ix, :, VALUE, start_ix:time_ix], axis=1)
        f_sd = np.std(data_norm[bid_ix, :, VALUE, start_ix:time_ix], axis=1,
                      ddof=1)
        ax.errorbar(bax_concs, f_avg, yerr=f_sd, color=colors[i])


    ax.set_ylabel('NBD $F/F_0$')
    ax.set_xlabel('[Bax] (nM)')
    format_axis(ax)
    plt.subplots_adjust(left=0.24, bottom=0.21)
    ax.set_xlim([10, 1500])
    ax.set_xscale('log')

    if plot_filename:
        fig.savefig('%s.pdf' % plot_filename)
        fig.savefig('%s.png' % plot_filename, dpi=300)
Example #2
0
def plot_fmax_data(fmax_data, bid_concs, bax_concs, plot_filename=None):
    fig = plt.figure(figsize=(1.5, 1.5), dpi=300)
    ax = fig.gca()

    for bid_ix, bid_conc in enumerate(bid_concs):
        # Titration fmax data for this Bid concentration
        bid_fmax = fmax_data[bid_ix, :]

        # Plotting
        #c = colors[bid_ix]
        c = brew_colors6[bid_ix]
        bid_str = '2.5' if bid_conc == 2.5 else str(int(bid_conc))
        # Plot the data
        ax.plot(bax_concs, bid_fmax, marker='o', color=c,
                 linestyle='-', markersize=3)

    # Format the plot
    plt.subplots_adjust(left=0.23, bottom=0.19, right=0.92)
    ax.set_xlabel('[Total Bax] (nM)')
    ax.set_ylabel(r'$F_{max}$ (NBD F/F$_0$)')
    #ax.set_ylim([-1e-5, 37e-5])
    ax.set_xlim([10, 2000])
    # ax.set_yticks(np.linspace(0, 35e-5, 8))
    # ax.set_yticklabels([int(f) for f in np.linspace(0, 35, 8)])
    ax.set_xscale('log')
    format_axis(ax)

    if plot_filename:
        fig.savefig('%s.pdf' % plot_filename)
        fig.savefig('%s.png' % plot_filename, dpi=300)
Example #3
0
def plot_bax_titration_timecourses(data_matrix, bid_ix, k_data, fmax_data,
                                   plot_filename=None):
    """Plot F/F0 vs. time for a Bid conc and a range of Bax concs."""
    fig = plt.figure(figsize=(1.5, 1.5), dpi=300)
    plt.subplots_adjust(left=0.24, bottom=0.21)
    ax = fig.gca()
    for bax_ix in range(data_matrix.shape[1]):
        if bax_ix not in [0, 6, 10]:
            continue
        t = data_matrix[bid_ix, bax_ix, TIME, :]
        v = data_matrix[bid_ix, bax_ix, VALUE, :]
        ax.plot(t, v, alpha=0.9, linewidth=1,
                label='%d nM Bax' % bax_concs[bax_ix])
        # Plot exponential fits
        k = k_data[bid_ix, bax_ix]
        fmax = fmax_data[bid_ix, bax_ix]
        fit = tf.OneExpFmax()
        ax.plot(t, fit.fit_func(t, [k, fmax]) + 1, 'k')
    plt.legend(loc='lower right', fontsize=fontsize, frameon=False)
    ax.set_xticks(np.linspace(0, 2.5e4, 6))
    ax.set_xticklabels([int(f) for f in np.linspace(0, 25, 6)])
    ax.set_ylabel('$F/F_0$')
    ax.set_xlabel(r'Time (sec $\times 10^3$)')
    format_axis(ax)

    if plot_filename:
        fig.savefig('%s.pdf' % plot_filename)
        fig.savefig('%s.png' % plot_filename, dpi=300)
Example #4
0
def plot_k_fmax_varying(fmax_arr, k_arr, conc_arr):
    """Plot Fmax and k vs. liposome concentration for fits with Fmax
    allowed to vary.
    """
    set_fig_params_for_publication()
    plt.figure('exp_fits_fmax_var', figsize=(1.9, 1.5), dpi=300)
    # Plot Fmax vs. concentration on the left-hand axis
    plt.plot(conc_arr, fmax_arr, marker='o', markersize=3,
             color='b')
    plt.xlabel('[Liposomes] (nM)')
    ax1 = plt.gca()
    ax1.set_xscale('log')
    ax1.set_xlim([0.05, 30])
    ax1.set_ylabel('$F_{max}$', color='b')
    for tl in ax1.get_yticklabels():
        tl.set_color('b')
    ax1.set_yscale('log')
    # Plot k vs. concentration on the right-hand axis
    ax2 = ax1.twinx()
    ax2.set_xlim([0.05, 30])
    ax2.plot(conc_arr, k_arr, marker='o', markersize=3, color='r')
    ax2.set_ylabel(r'k (sec $\times 10^{-3}$)', color='r')
    ax2.set_yscale('log')
    for tl in ax2.get_yticklabels():
        tl.set_color('r')
    #ax2.set_yticks(np.linspace(6.6e-4, 7.8e-4, 7))
    #ax2.set_yticklabels(['%.1f' % f for f in np.linspace(6.6, 7.8, 7)])
    format_axis(ax1)
    format_axis(ax2, yticks_position='right')
    plt.subplots_adjust(left=0.18, bottom=0.19, right=0.75)
Example #5
0
def calc_pore_size_by_poisson():
    set_fig_params_for_publication()

    (fmax_arr, k1_arr, k2_arr, conc_list) = \
         titration_fits.plot_two_exp_fits(bgsub_norm_wells, layout, plot=False)

    conc_lipos = 2.8

    fmax_means = np.mean(fmax_arr, axis=0)
    fmax_stds = np.std(fmax_arr, axis=0)
    ratios = conc_list / conc_lipos
    isf_pore_sizes = []
    k_max = 20
    for i, ratio in enumerate(ratios):
        if i == 0:
            continue
        # Probability of permeabilization is
        # 1 - poisson.cdf(pore_size, ratio)
        pore_sizes = np.arange(1, k_max)
        probs = [1 - stats.poisson.cdf(pore_size, ratio)
                 for pore_size in pore_sizes]
        isf_pore_size = stats.poisson.isf(fmax_means[i], ratio) + 1
        isf_pore_sizes.append(isf_pore_size)

        #plt.figure()
        #plt.plot(pore_sizes, probs, marker='o')
        #plt.xlabel('Pore size')
        #plt.ylim([-0.05, 1.05])
        #plt.title('Ratio of %f, isf pore size: %f' % (ratio, isf_pore_size))
        #sd_lines = [fmax_means[i] + fmax_stds[i]*num_sds
        #            for num_sds in np.arange(-2, 3)]
        #plt.hlines(sd_lines, 0, k_max, color='r')

    # Plot min pore size vs. Bax, with linear fit
    fig = plt.figure(figsize=(1.5, 1.5), dpi=300)
    ax = fig.gca()
    ax.plot(ratios[1:], isf_pore_sizes, marker='o', markersize=2,
            linestyle='') # Skip the 0 Bax pt
    ax.set_xlabel('[Bax]/[Lipo]')
    ax.set_ylabel('Predicted pore size')
    ax.set_xscale('log')
    ax.set_yscale('log')
    lbound = 0.1
    ubound = 200
    ax.set_xlim(lbound, 1000)
    #ax.set_ylim(1, 200)
    lin_fit = stats.linregress(ratios[1:], isf_pore_sizes)
    slope = lin_fit[0]
    intercept = lin_fit[1]
    ax.plot(ratios[1:], slope*ratios[1:] + intercept, color='r')
    interp_range = np.linspace(lbound, ratios[1])
    ax.plot(interp_range, slope*interp_range + intercept, color='r',
            linestyle='--', dashes=(2, 2))
    ax.plot(interp_range, [slope*ratios[1] + intercept] * len(interp_range),
            color='r', linestyle='--', dashes=(2, 2))
    #ax.set_title('Slope %f, intercept %f' % (slope, intercept),
    #             fontsize=fontsize)
    fig.subplots_adjust(left=0.22, bottom=0.19)
    format_axis(ax)
Example #6
0
def plot_emcee_fits(gf, sampler, sample=True, burn=None, nsamples=100,
                    plot_filename=None):
    """Plot fits from the MCMC chain vs. the data."""
    if not DISPLAY and plot_filename is None:
        raise ValueError("DISPLAY is set to False but plot_filename is None, "
                         "so there will be no output.")
    set_fig_params_for_publication()
    # If we're plotting samples, get the indices now and use them for
    # all observables
    if sample:
        (nwalkers, nsteps) = sampler.chain.shape[1:3]
        if burn is None:
            burn = int(nsteps / 2)

        walker_indices = np.random.randint(0, nwalkers, size=nsamples)
        step_indices = np.random.randint(burn, nsteps, size=nsamples)

    for obs_ix in range(gf.data.shape[1]):
        if DISPLAY:
            fig = plt.figure(figsize=(3, 3), dpi=300)
        else:
            fig = Figure(figsize=(3, 3), dpi=300)

        ax = fig.gca()
        ax.set_ylabel('$F/F_0$')
        #ax.set_xlabel(r'Time (sec $\times 10^3$)')
        ax.set_xlabel(r'Time')
        #plt.ylim([0.7, 5.2])
        ax.set_xlim([0, gf.time[-1] + 500])
        #ax.set_xticks(np.linspace(0, 1e4, 6))
        #ax.set_xticklabels([int(f) for f in np.linspace(0, 10, 6)])
        fig.subplots_adjust(bottom=0.21, left=0.20)
        # Plot the different observables
        for cond_ix in range(gf.data.shape[0]):
            data = gf.data[cond_ix, obs_ix, :]
            ax.plot(gf.time, data, 'k', linewidth=1)
        # Colors for different observables
        obs_colors = ['r', 'g', 'b', 'k']
        # If we're plotting samples:
        if sample:
            for i in xrange(nsamples):
                p = sampler.chain[0, walker_indices[i], step_indices[i], :]
                plot_args = {'color': obs_colors[obs_ix], 'alpha': 0.1}
                gf.plot_func(p, obs_ix=obs_ix, ax=ax, plot_args=plot_args)

        # Plot the maximum a posteriori fit
        maxp_flat_ix = np.argmax(sampler.lnprobability[0])
        maxp_ix = np.unravel_index(maxp_flat_ix,
                                   sampler.lnprobability[0].shape)
        maxp = sampler.lnprobability[0][maxp_ix]
        plot_args = {'color': 'm', 'alpha': 1}
        gf.plot_func(sampler.chain[0, maxp_ix[0], maxp_ix[1]], ax=ax,
                     obs_ix=obs_ix, plot_args=plot_args)

        format_axis(ax)
        if plot_filename:
            obs_plot_filename = '%s.obs%d' % (plot_filename, obs_ix)
            save_fig(fig, obs_plot_filename, DISPLAY)
def plot_3confs(plot_filename):
    min_conf_to_plot = 3
    fig = plt.figure(figsize=(1.5, 1.8), dpi=300)
    ax = fig.gca()

    # Create an array to hold all of the values
    evi_matrix = np.zeros((nconf_models, num_rows))
    # Now, iterate over all the keys
    row_index = 0
    xpositions = range(min_conf_to_plot, max_conf + 1)
    arr_start_index = min_conf_to_plot - min_conf
    for (act, res, rep) in product(activators, residues, reps):
        evi_arr = evi_dict[(act, res, rep)]
        evi_matrix[:, row_index] = evi_arr
        # Get jitter values for the xcoordinates
        xjitter = np.random.randn(len(xpositions)) * 0.07
        xvalues = xpositions + xjitter
        # Color code according to part of the protein
        color = color_dict[site_region[res]]
        # Plot
        ax.plot(xvalues, evi_arr[arr_start_index:], linestyle='', marker='.',
                markersize=2, color=color)
        row_index += 1

    ax.set_xlim(min_conf_to_plot - 0.5, max_conf + 0.5)
    ax.set_xticks(xpositions)
    ax.set_xticklabels([str(xpos) for xpos in xpositions])
    #ax.set_xlabel('Conformations in model')
    #ax.set_ylabel('-ln(Marginal likelihood)')

    sub_matrix = evi_matrix[arr_start_index:]
    ax.boxplot(sub_matrix.T, positions=xpositions, widths=0.8, sym='',
               boxprops={'color':'black'},
               meanprops={'color':'black'},
               medianprops={'color':'black'},
               whiskerprops={'color':'black', 'linestyle':'-'})

    format_axis(ax)

    # Create legend with lines to match colors of points
    n_patch = mlines.Line2D([], [], color=color_dict['nterm'],
                            label='N-term')
    bh3_patch = mlines.Line2D([], [], color=color_dict['bh3'],
                              label='BH3')
    a56_patch = mlines.Line2D([], [], color=color_dict['h56'],
                              label='$\\alpha$5-6')
    a9_patch = mlines.Line2D([], [], color=color_dict['h9'],
                              label='$\\alpha 9$')
    leg = plt.legend(handles=[n_patch, bh3_patch, a56_patch, a9_patch],
             loc='upper right', borderaxespad=0.,
             prop={'size': fontsize}, handlelength=2,
             handletextpad=0.2, labelspacing=0.5)
    leg.draw_frame(False)

    plt.subplots_adjust(left=0.16, bottom=0.12)
    plt.savefig('%s.pdf' % plot_filename)
    plt.savefig('%s.png' % plot_filename)
Example #8
0
def plot_k_fmax_fixed(k_arr, conc_arr):
    """Plot fits of k with Fmax fixed to a single value."""
    set_fig_params_for_publication()
    plt.figure('exp_fits_fmax_fixed', figsize=(1.5, 1.5), dpi=300)
    # Plot k vs. concentration on the left-hand axis
    plt.plot(conc_arr, k_arr, marker='o', markersize=3,
             color='r', linestyle='', zorder=3)
    plt.xlabel('[Liposomes] (nM)')
    ax1 = plt.gca()
    ax1.set_ylabel(r'k (sec$^{-1}$)') #, color='r')
    ax1.set_xscale('log')
    ax1.set_xlim([0.05, 30])
    ax1.set_yscale('log')
    ax1.set_ylim([1e-6, 1.2e-3])
    #for tl in ax1.get_yticklabels():
    #    tl.set_color('r')
    format_axis(ax1)
    plt.subplots_adjust(left=0.30, bottom=0.19, right=0.93, top=0.93)

    # Fit to a line
    lin_fit = linregress(conc_arr, k_arr)
    see = lin_fit[4]
    mx = conc_arr.mean()
    sx2 = ((conc_arr - mx)**2).sum()
    sd_slope = see * np.sqrt(1./sx2)

    plt.plot(conc_arr, lin_fit[0] * conc_arr + lin_fit[1], color='b',
             label='Linear fit')
    print("---")
    print("Linear fit of k:")
    print(lin_fit)
    print("Slope: %s +/- %s" % (lin_fit[0], sd_slope))

    #lslope = fitting.Parameter(1.0)
    #lintercept = fitting.Parameter(np.exp(-9.6))
    #def power_law(x):
    #    return lintercept() * x ** lslope()
    #plaw_fit = fitting.fit(power_law, [lslope, lintercept], k_arr[:-1],
    #                       conc_arr[:-1])
    #print("----")
    #print("Power law fit (y = int * x ** slope):")
    #print("intercept: %s" % lintercept())
    #print("slope: %s" % lslope())
    #plt.plot(conc_arr[:-1], power_law(conc_arr[:-1]), color='g')

    log_fit = linregress(np.log(conc_arr), np.log(k_arr))
    plt.plot(conc_arr,
             np.exp(log_fit[1]) * (conc_arr ** log_fit[0]), color='g',
             label='Log-linear fit')
    plt.legend(loc='lower right', fontsize=fontsize, frameon=False)
    print("----")
    print("Log-log linear fit:")
    print(log_fit)
Example #9
0
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_emcee_fits(gf, sampler):
    """Plot fits from the MCMC chain vs. the data."""
    set_fig_params_for_publication()
    fig = plt.figure(figsize=(1.5, 1.5), dpi=300)
    plt.ylabel('$F/F_0$')
    plt.xlabel(r'Time (sec $\times 10^3$)')
    plt.ylim([0.7, 5.2])
    plt.xlim([0, bg_time[-1] + 500])
    ax = plt.gca()
    ax.set_xticks(np.linspace(0, 1e4, 6))
    ax.set_xticklabels([int(f) for f in np.linspace(0, 10, 6)])
    plt.subplots_adjust(bottom=0.24, left=0.21)
    for data_ix in range(data_to_fit.shape[0]):
        plt.plot(bg_time, data_to_fit[data_ix, 0, :], 'k', linewidth=1)
    # Plot the final point (should probably plot max likelihood instead)
    gf.plot_func(sampler.flatchain[0,-1,:])
    format_axis(ax)
Example #11
0
def calc_min_pore_size(jobs, data):
    # For each concentration, get final dye release percentage, or final pore
    # num (start with dye release pctage)
    dr_fmax_means = np.zeros(len(jobs))
    dr_fmax_ses = np.zeros(len(jobs))
    bax_concs = np.zeros(len(jobs))
    num_sims = data.sim_data.shape[1]
    lipo_conc = jobs[0].one_cpt_builder().model.parameters['Vesicles_0'].value
    min_pore_sizes = np.zeros(len(jobs))
    ratios = []
    for cond_index, job in enumerate(jobs):
        (dr_mean, dr_sd) = data.get_mean_dye_release(cond_index)
        dr_se = dr_sd / np.sqrt(num_sims)
        dr_fmax_means[cond_index] = dr_mean[-1]
        dr_fmax_ses[cond_index] = dr_se[-1]
        bax_concs[cond_index] = \
                       job.one_cpt_builder().model.parameters['Bax_0'].value
        ratio = bax_concs[cond_index] / float(lipo_conc)
        ratios.append(ratio)
        min_pore_sizes[cond_index] = \
                stats.poisson.isf(dr_mean[-1], ratio)
    ratios = np.array(ratios)
    fig = plt.figure(figsize=(1.5, 1.5), dpi=300)
    ax = fig.gca()
    ax.plot(ratios, min_pore_sizes, marker='o', linestyle='', color='b',
            markersize=2)
    ax.set_xscale('log')
    ax.set_yscale('log')

    ax.set_xlabel('[Bax]/[Lipo]')
    ax.set_ylabel('Predicted pore size')
    ax.set_ylim(0.7, 250)
    ax.set_xlim(0.1, 300)
    lin_fit = stats.linregress(ratios[0:], min_pore_sizes[0:])
    slope = lin_fit[0]
    intercept = lin_fit[1]
    lbound = 0.1
    ubound = 200
    ax.plot(ratios, slope*ratios + intercept, color='r')
    ax.set_title('Slope %f, intercept %f' % (slope, intercept),
                 fontsize=fontsize)
    format_axis(ax)
    import ipdb; ipdb.set_trace()
Example #12
0
def plot_saturation_binding_predictions(flatchain, plot_filename=None):
    # Plot binding curve for different liposome concentrations
    plt.figure('Lipobinding', figsize=(1.5, 1.5), dpi=300)
    num_tot_steps = flatchain.shape[0]
    num_plot_samples = 2500
    n_pts = 100
    (x_lb, x_ub) = (0.01, 50)
    ypred_samples = np.zeros((num_plot_samples, n_pts))
    lipo_pred = np.logspace(np.log10(x_lb), np.log10(x_ub), n_pts)
    bid_pred = 20.
    for s_ix in range(num_plot_samples):
        p_ix = np.random.randint(num_tot_steps)
        p_samp = flatchain[p_ix]
        ypred = np.array([binding_func(p_samp, bid_pred, liposome_conc=l)
                          for l in lipo_pred])
        ypred_samples[s_ix] = ypred
        #plt.plot(lipo_pred, ypred, alpha=0.01, color='r')
    samp_lb = np.zeros(n_pts)
    samp_ub = np.zeros(n_pts)
    # Plot 95% confidence interval
    ax = plt.gca()
    # Label axes
    plt.xlabel('[Lipos] (nM)')
    plt.ylabel(r'\% cBid bound')
    # Format axes
    ax.set_xscale('log')
    plt.xlim([x_lb, x_ub])
    ax.set_xticks([0.01, 0.1, 1, 10,])
    ax.set_xticklabels([0.01, 0.1, 1, 10])
    plt.subplots_adjust(bottom=0.18, left=0.22, right=0.94, top=0.94)
    ypred_lb = np.percentile(ypred_samples, 2.5, axis=0)
    ypred_ub = np.percentile(ypred_samples, 97.5, axis=0)
    ax.fill_between(lipo_pred, ypred_lb, ypred_ub, color='lightgray')
    format_axis(ax)
    # Plot mean of predictions
    plt.plot(lipo_pred, np.mean(ypred_samples, axis=0), color='r')

    # Plot previously published value
    plt.plot(0.9, 0.5, marker='o', markersize=4, color='b')

    if plot_filename:
        plt.savefig('%s.pdf' % plot_filename)
        plt.savefig('%s.png' % plot_filename, dpi=300)
Example #13
0
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)
Example #14
0
def plot_chain(flatchain, lnprob):
    # Check convergence
    plt.figure('Chains')
    plt.plot(lnprob.T)
    plt.xlabel('MCMC Step')
    plt.ylabel('log(Posterior)')
    plt.title('Chain convergence')

    # Get sampling of trajectories parameters
    set_fig_params_for_publication()
    plt.figure('Fits', figsize=(1.5, 1.5), dpi=300)
    num_tot_steps = flatchain.shape[0]
    num_plot_samples = 2500
    n_pts = 100
    (x_lb, x_ub) = (0.1, 1500)
    ypred_samples = np.zeros((num_plot_samples, n_pts))
    bid_pred = np.logspace(np.log10(x_lb), np.log10(x_ub), n_pts)
    for s_ix in range(num_plot_samples):
        p_ix = np.random.randint(num_tot_steps)
        p_samp = flatchain[p_ix]
        ypred = fret_func(p_samp, bid_pred)
        ypred_samples[s_ix] = ypred
        #plt.plot(bid_pred, ypred, alpha=0.01, color='r')
    samp_lb = np.zeros(n_pts)
    samp_ub = np.zeros(n_pts)
    # Plot 95% confidence interval
    ax = plt.gca()
    ypred_lb = np.percentile(ypred_samples, 2.5, axis=0)
    ypred_ub = np.percentile(ypred_samples, 97.5, axis=0)
    ax.fill_between(bid_pred, ypred_lb, ypred_ub, color='lightgray')
    # Plot maximum likelihood
    ml_ix = np.argmax(lnprob)
    ml_pos = flatchain[ml_ix]
    plt.plot(bid_pred, fret_func(ml_pos, bid_pred), color='r',
             linewidth=0.5)
    # Plot no competitor line, with stderr
    plt.hlines(fret_means[-1], x_lb, x_ub, linestyle='solid', color='k',
               linewidth=0.5)
    # Draw dashed line
    dash_line_pts = np.logspace(np.log10(x_lb), np.log10(x_ub), 50)
    for pt_ix in range(0, len(dash_line_pts) - 1, 2):
        plt.hlines([fret_means[-1] + fret_ses[-1], fret_means[-1] - fret_ses[-1]],
                   dash_line_pts[pt_ix], dash_line_pts[pt_ix + 1], color='k',
                   linewidth=0.5, zorder=3)
    # Plot data
    plt.errorbar(bid_concs[:-1], fret_means[:-1], yerr=fret_ses[:-1], color='k',
                 linewidth=1, capsize=capsize, zorder=3, linestyle='', marker='o',
                 markersize=2)
    # Label axes
    plt.xlabel('[cBid] (nM)')
    plt.ylabel(r'FRET (\%)')
    # Format axes
    ax.set_xscale('log')
    plt.xlim([x_lb, x_ub])
    ax.set_xticks([0.1, 1, 10, 100, 1000])
    ax.set_xticklabels([0.1, 1, 10, 100, 1000])
    ax.set_yticks([0.05, 0.15, 0.25, 0.35])
    ax.set_ylim([0.05, 0.37])
    format_axis(ax)
    plt.subplots_adjust(bottom=0.18, left=0.25, right=0.94, top=0.94)

    # Triangle plots
    #(tri_fig, axes) = plt.subplots(4, 4, figsize=(6, 6))
    # Triangle plots
    #(tri_fig, tri_axes) = plt.subplots(5, 5, figsize=(5, 5), dpi=150)
    (tri_fig, tri_axes) = plt.subplots(2, 2, figsize=(2, 2), dpi=300)
    corner.corner(flatchain[:, 0:2], fig=tri_fig,
                  #labels=['V', 'B', 'PC', 'FRET', 'F0'],
                  labels=['V (cBid eff. charge)', 'B'],
                  plot_datapoints=False, no_fill_contours=True)
    for row_ix, row in enumerate(tri_axes):
        for col_ix, ax in enumerate(row):
            #format_axis(ax, label_padding=20)
            ax.xaxis.set_ticks_position('bottom')
            ax.yaxis.set_ticks_position('left')
            ax.xaxis.set_tick_params(labelsize=fontsize, pad=1, length=1.5,
                                     width=0.5)
            ax.yaxis.set_tick_params(labelsize=fontsize, pad=1, length=1.5,
                                     width=0.5)
            ax.xaxis.label.set_size(fontsize)
            ax.yaxis.label.set_size(fontsize)
            ax.xaxis.set_label_coords(0.5, -0.2)
            ax.yaxis.set_label_coords(-0.2, 0.5)
            if col_ix == 0:
                ax.axvline(2, color='r', alpha=0.5)
            if col_ix == 0 and row_ix == 1:
                ax.axhline(11.5, color='r', alpha=0.5)
            if row_ix == 1:
                ax.axvline(11.5, color='r', alpha=0.5)

    tri_fig.subplots_adjust(right=0.96, top=0.96, bottom=0.15, left=0.15,
                            hspace=0.15, wspace=0.15)
        line_color = 'r' if obs == 'NBD' else 'g'
        for i in xrange(num_samples):
            psamp = sampler.chain[0, walker_indices[i], step_indices[i], :]
            # Set values of parameters
            for p_ix, param in enumerate(gf.builder.estimate_params):
                param.value = 10 ** psamp[p_ix]
            ysim = gf.builder.obs_func(t)[obs]
            ax1.plot(t, ysim, color=line_color, alpha=0.1) 

        """
        # Plot max a posterior fit
        maxp_flat_ix = np.argmax(sampler.lnprobability[0])
        maxp_ix = np.unravel_index(maxp_flat_ix,
                                   sampler.lnprobability[0].shape)
        pmax = sampler.chain[0, maxp_ix[0], maxp_ix[1]]
        # Set values of parameters
        for p_ix, param in enumerate(gf.builder.estimate_params):
            param.value = 10 ** pmax[p_ix]
        ysim = gf.builder.obs_func(t)[obs]
        ax1.plot(t, ysim, color='m')
        """

        # Format axis
        format_axis(ax1)

plt.subplots_adjust(left=0.14, bottom=0.14, hspace=0.35, wspace=0.4)
fig.savefig('data2_example_nbd_fret_fits.pdf', dpi=300)
fig.savefig('data2_example_nbd_fret_fits.png', dpi=300)


Example #16
0
    return fmax() * (1 - np.exp(-k2()*t))

res1 = fitting.fit(fit_func1, [k1], y, t)
res2 = fitting.fit(fit_func2, [fmax, k2], y, t)

# Plot the raw curve and an exponential fit
set_fig_params_for_publication()
plt.figure(figsize=(1.5, 1.5), dpi=300)
plt.plot(t, y, color='k', linewidth=1)
plt.plot(t, fit_func1(t), color='b', linewidth=1)
plt.plot(t, fit_func2(t), color='r', linewidth=1)
plt.xlim([0, 11.3e3])
plt.xlabel(r'Time (sec $\times 10^3$)')
plt.ylabel(r'\% Release')
ax = plt.gca()
format_axis(ax)
ax.set_xticks(np.linspace(0, 1e4, 6))
ax.set_xticklabels([int(f) for f in np.linspace(0, 10, 6)])
ax.set_yticks([0, 0.2, 0.4, 0.6, 0.8])
plt.subplots_adjust(bottom=0.19, left=0.21, top=0.94, right=0.94)
leg = plt.legend(['Data', 'Fit, constant rate', 'Fit, decr. rate'],
                 loc='lower right', prop={'size':6}, frameon=False,
                 handlelength=1.5, handletextpad=0)
# Save the figure
plt.savefig('fig_fmax_fit_comparison.pdf')

# Now plot the hazard rate for data and fits
def failure_rate(t, y):
    dt = np.diff(t)
    dy = -np.diff(y)
    fr = dy / (dt * y[1:])
Example #17
0
def plot_2confs(plot_filename):
    min_conf_to_plot = 2
    f,(ax1, ax2) = plt.subplots(2, 1, figsize=(3, 3), dpi=300)

    # Create an array to hold all of the values
    evi_matrix = np.zeros((nconf_models, num_rows))
    # Now, iterate over all the keys
    row_index = 0
    xpositions = range(min_conf_to_plot, max_conf + 1)
    arr_start_index = min_conf_to_plot - min_conf
    for (act, res, rep) in product(activators, residues, reps):
        evi_arr = evi_dict[(act, res, rep)]
        evi_matrix[:, row_index] = evi_arr
        # Get jitter values for the xcoordinates
        xjitter = np.random.randn(len(xpositions)) * 0.05
        xvalues = xpositions + xjitter
        # Color code according to part of the protein
        color = color_dict[site_region[res]]
        # Plot
        for ax in (ax1, ax2):
            ax.plot(xvalues, evi_arr[arr_start_index:], linestyle='', marker='.',
                    markersize=2, color=color)
        row_index += 1

    ax1.set_xlim(min_conf_to_plot - 0.5, max_conf + 0.5)
    ax2.set_xlim(min_conf_to_plot - 0.5, max_conf + 0.5)
    ax2.set_xticks(xpositions)
    ax2.set_xticklabels([str(xpos) for xpos in xpositions])
    ax2.set_xlabel('Conformations in model')

    ax1.set_ylim(1600, 30000)
    ax2.set_ylim(0, 1300)
    ax1.spines['bottom'].set_visible(False)
    ax2.spines['top'].set_visible(False)
    #ax1.xaxis.tick_top()
    #ax1.tick_params(labeltop='off')
    #ax2.xaxis.tick_bottom()

    # Diagonal lines
    d = .015 # how big to make the diagonal lines in axes coordinates
    # arguments to pass plot, just so we don't keep repeating them
    kwargs = dict(transform=ax1.transAxes, color='k', clip_on=False)
    ax1.plot((-d,+d),(-d,+d), **kwargs)      # top-left diagonal
    ax1.plot((1-d,1+d),(-d,+d), **kwargs)    # top-right diagonal

    kwargs.update(transform=ax2.transAxes)  # switch to the bottom axes
    ax2.plot((-d,+d),(1-d,1+d), **kwargs)   # bottom-left diagonal
    ax2.plot((1-d,1+d),(1-d,1+d), **kwargs) # bottom-right diagonal

    sub_matrix = evi_matrix[arr_start_index:]
    ax2.boxplot(sub_matrix.T, positions=xpositions, widths=0.8, sym='',
               boxprops={'color':'black'},
               meanprops={'color':'black'},
               medianprops={'color':'black'},
               whiskerprops={'color':'black', 'linestyle':'-'})

    # Set up the yaxis for the top plot
    #ax1.yaxis.set_tick_params(which='both', direction='out', labelsize=fontsize,
    #                         pad=0, length=2, width=0.5)
    #ax1.yaxis.set_ticks_positions('left')
    #ax1.yaxis.labelpad = 2
    #ax1.yaxis.label.set_size(fontsize)
    #ax1.set_xticks([])
    format_axis(ax1)
    ax1.set_xticks([])
    format_axis(ax2)
    f.subplots_adjust(hspace=0.05)

    # Add shared yaxis label
    f.text(0.035, 0.5, '-ln(Marginal likelihood)', ha='center', va='center',
           rotation='vertical', fontsize=fontsize)

    plt.subplots_adjust(left=0.16, bottom=0.12)
    plt.savefig('%s.pdf' % plot_filename)
    plt.savefig('%s.png' % plot_filename)
Example #18
0
def plot_conformations(gf, sampler, sample=True, burn=None, nsamples=100,
                       plot_filename=None):
    """Plot fluorescence conformations from the MCMC chain vs. the data."""
    if not DISPLAY and plot_filename is None:
        raise ValueError("DISPLAY is set to False but plot_filename is None, "
                         "so there will be no output.")
    set_fig_params_for_publication()

    # If we're plotting samples, get the indices now and use them for
    # all observables
    if sample:
        (nwalkers, nsteps) = sampler.chain.shape[1:3]
        if burn is None:
            burn = int(nsteps / 2)

        walker_indices = np.random.randint(0, nwalkers, size=nsamples)
        step_indices = np.random.randint(burn, nsteps, size=nsamples)

    for obs_ix in range(gf.data.shape[1]):
        if DISPLAY:
            fig = plt.figure(figsize=(3, 3), dpi=300)
        else:
            fig = Figure(figsize=(3, 3), dpi=300)
        ax = fig.gca()
        ax.set_ylabel('$F/F_0$')
        #ax.set_xlabel(r'Time (sec $\times 10^3$)')
        ax.set_xlabel(r'Time')
        #plt.ylim([0.7, 5.2])
        ax.set_xlim([0, gf.time[-1] + 500])
        #ax.set_xticks(np.linspace(0, 1e4, 6))
        #ax.set_xticklabels([int(f) for f in np.linspace(0, 10, 6)])
        fig.subplots_adjust(bottom=0.24, left=0.21)
        # Plot the different observables
        for cond_ix in range(gf.data.shape[0]):
            data = gf.data[cond_ix, obs_ix, :]
            ax.plot(gf.time, data, 'k', linewidth=1)
        # Colors for different observables
        obs_colors = ['r', 'g', 'b', 'm', 'k']

        def plot_confs(x, plot_args):
            for cond_ix in range(gf.data.shape[0]):
                gf.set_parameters(x, obs_ix=obs_ix, cond_ix=cond_ix)
                gf.solver.run()
                # Iterate over the number of conformations
                for conf_ix in range(gf.builder.num_confs):
                    conf_y = gf.solver.yobs['Bax_c%d' % conf_ix]
                    conf_scaling = \
                       gf.builder.model.parameters['c%d_scaling' %
                                                     conf_ix].value
                    y = conf_y * conf_scaling
                    if 'color' not in plot_args:
                        ax.plot(gf.solver.tspan, y, label='c%d' % conf_ix,
                                 color=obs_colors[conf_ix], **plot_args)
                    else:
                        ax.plot(gf.solver.tspan, y, label='c%d' % conf_ix,
                                 **plot_args)

        # If we're plotting samples:
        if sample:
            for i in xrange(nsamples):
                p = sampler.chain[0, walker_indices[i], step_indices[i], :]
                plot_args = {'alpha': 0.1}
                plot_confs(p, plot_args=plot_args)

        # Plot the maximum a posteriori fit
        maxp_flat_ix = np.argmax(sampler.lnprobability[0])
        maxp_ix = np.unravel_index(maxp_flat_ix,
                                   sampler.lnprobability[0].shape)
        maxp = sampler.lnprobability[0][maxp_ix]
        plot_args = {'color': 'k', 'alpha': 1, 'linewidth':0.5}
        plot_confs(sampler.chain[0, maxp_ix[0], maxp_ix[1]],
                   plot_args=plot_args)

        format_axis(ax)
        if plot_filename:
            save_fig(fig, plot_filename, DISPLAY)
    ax1.set_title('NBD-%sC-Bax, DAC-Bax' % res, fontsize=fontsize)
    if row_ix == (axarr.shape[0] - 1):
        ax1.set_xlabel(r'Time (sec $\times 10^{-3}$)')
    if col_ix == 0:
        ax1.set_ylabel('NBD F/$F_0$')
        ax2.set_yticks([1, 1.1, 1.2, 1.3, 1.4])
        ax1.set_ylim(0, 60)
        ax2.set_ylim(1, 1.42)
    else:
        ax1.set_ylim(0, 60)
        ax2.set_yticks([1, 2, 3, 4, 5, 6])
        ax2.set_ylim(1, 6.1)
    ax1.set_xticks(np.linspace(0, 4000, 5))
    ax1.set_xticklabels([int(n) for n in np.linspace(0, 4, 5)])
    ax1.set_xlim(-50, 4000)
    # Label axes
    ax1.set_ylabel('\% FRET, \% Release')
    ax2.set_ylabel('NBD $F/F_0$')
    ax1.set_ylim(0, 70)
    # Plot
    ax1.plot(fret_t, fret_v, color='b')
    ax1.plot(rel_t, rel_v, color='r')
    ax2.plot(nbd_t, nbd_v, color='g')
    # Format axes
    format_axis(ax1)
    format_axis(ax2, yticks_position='right')
    plt.subplots_adjust(left=0.14, bottom=0.23, top=0.84, hspace=0.35, wspace=0.7)

fig.savefig('data3_example_curves.pdf')
fig.savefig('data3_example_curves.png', dpi=300)
Example #20
0
def plot_mm(k_data, bid_concs, bax_concs, plot_filename=None):
    # Create the figure
    fig = plt.figure('mm fit', figsize=(1.5, 1.5), dpi=300)
    ax = fig.gca()

    km_list = []
    kcat_list = []
    v0_list = []

    for bid_ix in range(1, len(bid_concs)):
        bid_conc = bid_concs[bid_ix]
        # Fitting parameters
        kcat = fitting.Parameter(0.06)
        km = fitting.Parameter(250.)
        v0 = fitting.Parameter(5e-5)

        # Fit func for this bid concentration
        def fit_func(bax_concs):
            return ((kcat() * bid_conc) / (km() + bax_concs)) + v0()

        # Titration k data for this Bid concentration
        bid_k = k_data[bid_ix, :]
        # Fit to the MM equation
        fitting.fit(fit_func, [kcat, km, v0], bid_k, np.array(bax_concs))

        # Save the fitted values
        km_list.append(km())
        kcat_list.append(kcat())
        v0_list.append(v0())

        # Plotting
        #c = colors[bid_ix]
        c = brew_colors6[bid_ix-1]
        bid_str = '2.5' if bid_conc == 2.5 else str(int(bid_conc))
        # Plot the MM fit
        ax.plot(bax_concs, fit_func(bax_concs), color=c,
                 label='%s nM' % bid_str)
        # Plot the data
        ax.plot(bax_concs, bid_k, marker='o', color=c,
                linestyle='', markersize=3)

    # Format the plot
    plt.subplots_adjust(left=0.21, bottom=0.19)
    ax.set_xlabel('[Total Bax] (nM)')
    ax.set_ylabel(r'k (sec$^{-1} \times 10^{-5}$)')
    ax.set_ylim([-1e-5, 37e-5])
    ax.set_xlim([10, 2000])
    ax.set_yticks(np.linspace(0, 35e-5, 8))
    ax.set_yticklabels([int(f) for f in np.linspace(0, 35, 8)])
    ax.set_xscale('log')
    format_axis(ax)

    #max_rate_list = []
    #for bid_ix, bid_conc in enumerate(bid_concs):
    #    km = km_list[bid_ix]
    #    kcat = kcat_list[bid_ix]
    #    v0 = v0_list[bid_ix]
    #   #max_rate = ((kcat * bid_conc) / km) + v0
    #    max_rate = (kcat * bid_conc) + v0
    #    max_rate_list.append(max_rate)

    kcat_fig = plt.figure('kcat', figsize=(1.5, 1.5), dpi=300)
    kcat_ax = kcat_fig.gca()
    #kcat_ax.plot(bid_concs[1:], max_rate_list[1:], marker='o')
    max_rate_list = [k_data[i, 0] for i in range(len(bid_concs))]
    kcat_ax.plot(bid_concs, max_rate_list, marker='o', markersize=3,
                 label='Observed $k$')

    #kcat_ax.set_xscale('log')
    kcat_ax.set_xlabel('[cBid] (nM)')
    kcat_ax.set_ylabel('Rate')
    kcat_ax.set_ylabel(r'k (sec$^{-1} \times 10^{-5}$)')
    kcat_ax.set_ylim([-1e-5, 37e-5])
    kcat_ax.set_yticks(np.linspace(0, 35e-5, 8))
    kcat_ax.set_yticklabels([int(f) for f in np.linspace(0, 35, 8)])
    kcat_ax.set_xlim(-2, 82)
    # Define line connecting 0 Bid and 2.5 Bid concs
    bid_slope = (max_rate_list[1] - max_rate_list[0]) / float(bid_concs[1])
    kcat_ax.plot(bid_concs, bid_slope * bid_concs + max_rate_list[0],
                 color='r', label='Fixed $k_{cat}$')
    plt.legend(loc='lower right', frameon=False, fontsize=fontsize)
    kcat_fig.subplots_adjust(left=0.22, bottom=0.2)
    format_axis(kcat_ax)

    if plot_filename:
        fig.savefig('%s.pdf' % plot_filename)
        fig.savefig('%s.png' % plot_filename, dpi=300)
        kcat_fig.savefig('%s_kcat.pdf' % plot_filename)
        kcat_fig.savefig('%s_kcat.png' % plot_filename, dpi=300)
def plot_saturation_binding_predictions(flatchain, plot_filename=None):
    def binding_func(position, bid_tot, lipo_scale=1):
        # Transform all params to linear scale
        log_params = 10 ** position[:2]
        lin_params = position[2:]
        (kd, l_tot) = log_params
        (f0, fmax) = lin_params
        # 1.55 was concentration of lipos used in the experiment
        l_tot = l_tot / 1.55
        l_tot *= lipo_scale
        frac_bid_bound = ((1.0 / (2 * bid_tot)) *
                          (l_tot + bid_tot + kd -
                           np.sqrt((l_tot + bid_tot + kd)**2 -
                                   (4 * l_tot * bid_tot))))
        return frac_bid_bound

    plt.figure('Satbinding', figsize=(1.5, 1.5), dpi=300)
    num_tot_steps = flatchain.shape[0]
    num_plot_samples = 2500
    n_pts = 100
    (x_lb, x_ub) = (0.1, 1500)
    ypred_samples = np.zeros((num_plot_samples, n_pts))
    bid_pred = np.logspace(np.log10(x_lb), np.log10(x_ub), n_pts)
    for s_ix in range(num_plot_samples):
        p_ix = np.random.randint(num_tot_steps)
        p_samp = flatchain[p_ix]
        ypred = binding_func(p_samp, bid_pred, lipo_scale=1.55)
        ypred_samples[s_ix] = ypred
        #plt.plot(bid_pred, ypred, alpha=0.01, color='r')
    samp_lb = np.zeros(n_pts)
    samp_ub = np.zeros(n_pts)
    # Plot 95% confidence interval
    ax = plt.gca()
    # Label axes
    plt.xlabel('[cBid] (nM)')
    plt.ylabel(r'\% [cBid] bound')
    # Format axes
    ax.set_xscale('log')
    plt.xlim([x_lb, x_ub])
    ax.set_xticks([0.1, 1, 10, 100, 1000])
    ax.set_xticklabels([0.1, 1, 10, 100, 1000])
    plt.subplots_adjust(bottom=0.18, left=0.22, right=0.94, top=0.94)
    ypred_lb = np.percentile(ypred_samples, 2.5, axis=0)
    ypred_ub = np.percentile(ypred_samples, 97.5, axis=0)
    ax.fill_between(bid_pred, ypred_lb, ypred_ub, color='lightgray')
    format_axis(ax)
    # Plot mean of predictions
    plt.plot(bid_pred, np.mean(ypred_samples, axis=0), color='r')

    # Plot binding curve for different liposome concentrations
    plt.figure('Lipobinding', figsize=(1.5, 1.5), dpi=300)
    num_tot_steps = flatchain.shape[0]
    num_plot_samples = 2500
    n_pts = 100
    (x_lb, x_ub) = (0.01, 50)
    ypred_samples = np.zeros((num_plot_samples, n_pts))
    lipo_pred = np.logspace(np.log10(x_lb), np.log10(x_ub), n_pts)
    bid_pred = 20.
    for s_ix in range(num_plot_samples):
        p_ix = np.random.randint(num_tot_steps)
        p_samp = flatchain[p_ix]
        ypred = binding_func(p_samp, bid_pred, lipo_scale=lipo_pred)
        ypred_samples[s_ix] = ypred
        #plt.plot(lipo_pred, ypred, alpha=0.01, color='r')
    samp_lb = np.zeros(n_pts)
    samp_ub = np.zeros(n_pts)
    # Plot 95% confidence interval
    ax = plt.gca()
    # Label axes
    plt.xlabel('[Lipos] (nM)')
    plt.ylabel(r'\% cBid bound')
    # Format axes
    ax.set_xscale('log')
    plt.xlim([x_lb, x_ub])
    ax.set_xticks([0.01, 0.1, 1, 10,])
    ax.set_xticklabels([0.01, 0.1, 1, 10])
    plt.subplots_adjust(bottom=0.18, left=0.22, right=0.94, top=0.94)
    ypred_lb = np.percentile(ypred_samples, 2.5, axis=0)
    ypred_ub = np.percentile(ypred_samples, 97.5, axis=0)
    ax.fill_between(lipo_pred, ypred_lb, ypred_ub, color='lightgray')
    format_axis(ax)
    # Plot mean of predictions
    plt.plot(lipo_pred, np.mean(ypred_samples, axis=0), color='r')

    # Plot previously published value
    plt.plot(0.9, 0.5, marker='o', markersize=4, color='b')

    if plot_filename:
        plt.savefig('%s.pdf' % plot_filename)
        plt.savefig('%s.png' % plot_filename, dpi=300)
Example #22
0
def plot_k_data(k_data, k_sd_data, bid_concs, bax_concs, plot_filename=None):
    fig = plt.figure(figsize=(1.5, 1.5), dpi=300)
    ax = fig.gca()

    for bid_ix in reversed(range(len(bid_concs))):
        bid_conc = bid_concs[bid_ix]
        # Titration k data for this Bid concentration
        bid_k = k_data[bid_ix, :]
        bid_k_sd = k_sd_data[bid_ix, :]
        bid_k_ub = 10 ** (np.log10(bid_k) + bid_k_sd) - bid_k
        bid_k_lb = bid_k - 10 ** (np.log10(bid_k) - bid_k_sd)
        #import ipdb; ipdb.set_trace()
        # Plotting
        c = brew_colors6[bid_ix]
        bid_str = '2.5' if bid_conc == 2.5 else str(int(bid_conc))
        # Plot the data
        ax.errorbar(bax_concs, bid_k, yerr=[bid_k_lb, bid_k_ub], marker='o',
                    color=c, linestyle='-', markersize=3)

    # Format the plot
    plt.subplots_adjust(left=0.21, bottom=0.19)
    ax.set_xlabel('[Total Bax] (nM)')
    ax.set_ylabel(r'$k$ (sec$^{-1} \times 10^{-5}$)')
    ax.set_ylim([-1e-5, 37e-5])
    ax.set_xlim([10, 2000])
    ax.set_yticks(np.linspace(0, 35e-5, 8))
    ax.set_yticklabels([int(f) for f in np.linspace(0, 35, 8)])
    ax.set_xscale('log')
    format_axis(ax)

    if plot_filename:
        fig.savefig('%s.pdf' % plot_filename)
        fig.savefig('%s.png' % plot_filename, dpi=300)

    # Now, plot the same data looking at the scaling with Bid
    bid_fig = plt.figure(figsize=(1.5, 1.5), dpi=300)
    ax = bid_fig.gca()

    for bax_ix in reversed(range(len(bax_concs))):
        bax_conc = bax_concs[bax_ix]
        # Titration k data for this Bax concentration
        bax_k = k_data[:, bax_ix]
        bax_k_sd = k_sd_data[:, bax_ix]
        bax_k_ub = 10 ** (np.log10(bax_k) + bax_k_sd) - bax_k
        bax_k_lb = bax_k - 10 ** (np.log10(bax_k) - bax_k_sd)
        #import ipdb; ipdb.set_trace()
        # Plotting
        c = brew_colors11[bax_ix]
        # Plot the data
        ax.errorbar(bid_concs, bax_k, yerr=[bax_k_lb, bax_k_ub], marker='o',
                    color=c, linestyle='-', markersize=3, capsize=3)

    # Format the plot
    plt.subplots_adjust(left=0.21, bottom=0.19)
    ax.set_xlabel('[cBid] (nM)')
    ax.set_ylabel(r'$k$ (sec$^{-1} \times 10^{-5}$)')
    ax.set_ylim([-1e-5, 37e-5])
    ax.set_xlim([-2, 82])
    ax.set_yticks(np.linspace(0, 35e-5, 8))
    ax.set_yticklabels([int(f) for f in np.linspace(0, 35, 8)])
    format_axis(ax)

    if plot_filename:
        bid_fig.savefig('%s_bid.pdf' % plot_filename)
        bid_fig.savefig('%s_bid.png' % plot_filename, dpi=300)
def plot_chain(flatchain, lnprob):
    # Check convergence
    plt.figure('Chains')
    plt.plot(lnprob.T)
    plt.xlabel('MCMC Step')
    plt.ylabel('log(Posterior)')
    plt.title('Chain convergence')

    # Get sampling of trajectories parameters
    set_fig_params_for_publication()
    plt.figure('Fits', figsize=(1.5, 1.5), dpi=300)
    num_tot_steps = flatchain.shape[0]
    num_plot_samples = 2500
    n_pts = 100
    (x_lb, x_ub) = (0.1, 1500)
    ypred_samples = np.zeros((num_plot_samples, n_pts))
    bid_pred = np.logspace(np.log10(x_lb), np.log10(x_ub), n_pts)
    for s_ix in range(num_plot_samples):
        p_ix = np.random.randint(num_tot_steps)
        p_samp = flatchain[p_ix]
        ypred = model_func(p_samp, bid_pred)
        ypred_samples[s_ix] = ypred
        #plt.plot(bid_pred, ypred, alpha=0.01, color='r')
    samp_lb = np.zeros(n_pts)
    samp_ub = np.zeros(n_pts)
    # Plot 95% confidence interval
    ax = plt.gca()
    ypred_lb = np.percentile(ypred_samples, 2.5, axis=0)
    ypred_ub = np.percentile(ypred_samples, 97.5, axis=0)
    ax.fill_between(bid_pred, ypred_lb, ypred_ub, color='lightgray')
    # Plot maximum likelihood
    ml_ix = np.argmax(lnprob)
    ml_pos = flatchain[ml_ix]
    plt.plot(bid_pred, model_func(ml_pos, bid_pred), color='r',
             linewidth=0.5)
    # Plot no competitor line, with stderr
    plt.hlines(fret_means[-1], x_lb, x_ub, linestyle='solid', color='k',
               linewidth=0.5)
    # Draw dashed line
    dash_line_pts = np.logspace(np.log10(x_lb), np.log10(x_ub), 50)
    for pt_ix in range(0, len(dash_line_pts) - 1, 2):
        plt.hlines([fret_means[-1] + fret_ses[-1], fret_means[-1] - fret_ses[-1]],
                   dash_line_pts[pt_ix], dash_line_pts[pt_ix + 1], color='k',
                   linewidth=0.5, zorder=3)
    # Plot data
    plt.errorbar(bid_concs[:-1], fret_means[:-1], yerr=fret_ses[:-1], color='k',
                 linewidth=1, capsize=capsize, zorder=3, linestyle='', marker='o',
                 markersize=2)
    # Label axes
    plt.xlabel('[cBid] (nM)')
    plt.ylabel(r'FRET (\%)')
    # Format axes
    ax.set_xscale('log')
    plt.xlim([x_lb, x_ub])
    ax.set_xticks([0.1, 1, 10, 100, 1000])
    ax.set_xticklabels([0.1, 1, 10, 100, 1000])
    ax.set_yticks([0.05, 0.15, 0.25, 0.35])
    ax.set_ylim([0.05, 0.37])
    format_axis(ax)
    plt.subplots_adjust(bottom=0.18, left=0.25, right=0.94, top=0.94)

    plt.figure(figsize=(1.1, 1), dpi=300)
    # Linear param values
    lin_lipo_sites = 10 ** flatchain[:, 1]
    lin_sites_per_lipo = lin_lipo_sites / 1.55
    plt.hist(lin_sites_per_lipo, bins=20, normed=True)
    plt.yticks([0, 0.1, 0.2, 0.3])
    plt.xticks([1, 3, 5, 7, 9])
    plt.xlabel('Sites/Lipo')
    plt.ylabel('Density')
    plt.subplots_adjust(bottom=0.25, left=0.28)
    ax = plt.gca()
    format_axis(ax)

    """
Example #24
0
def plot_exp_fits(time, data_to_fit, bax_concs_to_fit):
    fmax_list = []
    k1_list = []

    # Create figure showing the fits to each timecourse
    set_fig_params_for_publication()
    plt.figure('exp_fit_curves', figsize=(1.5, 1.5), dpi=300)

    for i, bax_conc in enumerate(bax_concs_to_fit):
        # Try fitting the high conc trajectory
        y = data_to_fit[i, 0, :]
        y = y / np.mean(y[0:2])
        fmax = fitting.Parameter(25.)
        k1 = fitting.Parameter(np.log(2)/2000.)
        k2 = fitting.Parameter(1e-3)
        b = fitting.Parameter(np.mean(y[0:2]))
        k_bleach = fitting.Parameter(1.17e-5)
        #def exp_func(t):
        #    return (b() + fmax()*(1 - np.exp(-k1() *
        #            (1 - np.exp(-k2()*t))*t))) * np.exp(-k_bleach()*t)
        # One-parameter exp
        def exp_func(t):
            return (b() + fmax()*(1 - np.exp(-k1()*t))) * \
                    np.exp(-k_bleach()*t)

        #fitting.fit(exp_func, [fmax, k1, k2], y, t)
        fitting.fit(exp_func, [fmax, k1], y, time)

        # Add to list
        fmax_list.append(fmax())
        k1_list.append(k1())

        # Plot the data
        plt.plot(time, y, color='k', linewidth=1)
        # Plot fits to the data
        plt.plot(time, exp_func(time), color='r', zorder=3, linewidth=1)

    # Format the finished plot
    # Axis labels
    plt.xlabel(r'Time (sec $\times 10^3$)')
    plt.ylabel('$F/F_0$')
    # Axis bounds and ticks
    ax = plt.gca()
    ax.set_ylim([0.7, 4])
    ax.set_xlim([0, time[-1] + 500])
    ax.set_xticks(np.linspace(0, 1e4, 6))
    ax.set_xticklabels([int(f) for f in np.linspace(0, 10, 6)])
    format_axis(ax)
    plt.subplots_adjust(bottom=0.21, left=0.23)

    # Now, plot the scaling of the parameters with concentration
    plt.figure('exp_fits', figsize=(1.7, 1.5), dpi=300)
    log_concs = np.log10(np.array(bax_concs_to_fit[:-1]))
    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_list[:-1],
                bax_concs_to_fit[:-1])
    plt.plot(bax_concs_to_fit[:-1], fmax_list[:-1], marker='o', markersize=3,
             color='b', linestyle='')
    plt.plot(bax_concs_to_fit[:-1], log_line(bax_concs_to_fit[:-1]), color='b')

    plt.xlabel('[Bax] (nM)')
    ax1 = plt.gca()
    ax1.set_xscale('log')
    ax1.set_xlim([8, 1000])
    ax1.set_ylabel('$F_{max}$', color='b')
    for tl in ax1.get_yticklabels():
        tl.set_color('b')

    ax2 = ax1.twinx()
    ax2.set_xlim([5, 1000])
    ax2.plot(bax_concs_to_fit[:-1], k1_list[:-1], marker='o', markersize=3,
             color='r', linestyle='')
    slope = fitting.Parameter(5e-4)
    intercept = fitting.Parameter(6.6e-3)
    fitting.fit(log_line, [slope, intercept], k1_list[:-1],
                bax_concs_to_fit[:-1])
    ax2.plot(bax_concs_to_fit[:-1], log_line(bax_concs_to_fit[:-1]),
                                    color='r')

    ax2.set_ylabel(r'k (sec $\times\ 10^{-3}$)', color='r')
    for tl in ax2.get_yticklabels():
        tl.set_color('r')
    ax2.set_yticks(np.linspace(6.6e-4, 7.8e-4, 7))
    ax2.set_yticklabels(['%.1f' % f for f in np.linspace(6.6, 7.8, 7)])

    format_axis(ax1)
    format_axis(ax2, yticks_position='right')
    plt.subplots_adjust(left=0.20, bottom=0.19, right=0.80)
Example #25
0
def plot_matrix(plot_type, density_mx, residues, output_file_base):
    if plot_type == 'k1k2':
        lbound = -6
        ubound = -1
        lbound_ix = 15
        xlabel = 'log$_{10}$(k1, k2)'
    elif plot_type == 'c1c2':
        lbound = 2.5
        ubound = 5.5
        lbound_ix = 0
        xlabel = 'log$_{10}$($C_2$, $C_3$)'
    else:
        raise ValueError("Unknown plot type: %s" % plot_type)

    fig = plt.figure(figsize=(2, 3), dpi=300)
    ax = fig.gca()
    ncols = density_mx.shape[0]
    num_reps = 3
    #assert ncols == (len(residues) * num_reps) + len(residues) - 1, \
    #       "Dimensions of density_mx must match numbers of reps/residues"
    ax.imshow(density_mx[:,lbound_ix:,:], interpolation='nearest',
              extent=(lbound, ubound, ncols, 0), aspect='auto')
    # Plot line representing max observed value
    if plot_type == 'c1c2':
        plt.vlines(np.log10(max_nbd_value), ncols, 0, color='gray')
    # Lines separating the different mutants
    lines = np.arange((2*num_reps), ncols, (2*num_reps)+2) + 1
    plt.hlines(lines, lbound, ubound, linewidth=0.5)

    """
    # Plot lines representing starting values
    # FIXME FIXME FIXME
    mut_ix_bounds = [0] + list(lines) + [ncols]
    activator = 'Bid'
    row_ix = 0
    for nbd_ix, nbd_residue in enumerate(residues):
        for rep_num in range(1, num_reps + 1):
            timecourse = \
                    df[(activator, 'NBD', nbd_residue, rep_num, 'VALUE')].values
            f0 = timecourse[0]
            #res_ix_lbound = mut_ix_bounds[nbd_ix]
            #res_ix_ubound = mut_ix_bounds[nbd_ix + 1]
            plt.vlines(np.log10(f0), row_ix, row_ix + 1, color='gray')
            row_ix += 1
        row_ix += 1
    """
    # Ticks for the different mutants
    spacing = 8
    ytick_positions = np.arange(3, ncols, spacing)
    ax.set_yticks(ytick_positions)
    assert len(residues) == len(ytick_positions)
    ax.set_yticklabels(residues)
    # Ticks for the units on the x-axis
    xtick_positions = np.arange(lbound, ubound + 0.1, 1.)
    ax.set_xticks(xtick_positions)
    ax.set_xlabel(xlabel)
    if plot_type == 'c1c2':
        ax.set_ylabel('NBD Position')
    format_axis(ax)
    fig.subplots_adjust(left=0.17, bottom=0.11, top=0.94)
    fig.savefig('%s.pdf' % output_file_base, dpi=1200)
    fig.savefig('%s.png' % output_file_base, dpi=300)
Example #26
0
def plot_exp_fits(time, data, concs, plot_fits=True, fmax_value=None):
    """Fit data to exponential, plot and return fitted values.

    Parameters
    ----------
    time : np.array
        Time vector for each timecourse.
    data : np.array: (conditions, observables, timecourses)
        Array containing the fluorescence timecourses at each
        liposome concentration.
    concs : list
        List of concentrations of liposomes (not lipids) in nanomolar.
    plot_fits : boolean
        If True (default), the fits to the data are plotted, each in its own
        figure. If False, the fits are performed but the results are not
        plotted.

    Returns
    -------
    tuple : (fmax_arr, k_arr, sum_sq_err)
        fmax_arr and k_arr are numpy arrays containing the fitted values for
        the fmax and k parameters, respectively. sum_sq_err is the sum of the
        squares of the values of the residuals at the best fit parameters.
    """
    fmax_arr = np.zeros(len(concs))
    k_arr = np.zeros(len(concs))

    # Create the figure, if applicable
    if plot_fits:
        set_fig_params_for_publication()
        if fmax_value is None:
            figname = 'exp_fits_curves_fmax_var'
        else:
            figname = 'exp_fits_curves_fmax_fixed'
        plt.figure(figname, figsize=(1.5, 1.5), dpi=300)

    # Iterate over all of the liposome concentrations
    for i, conc in enumerate(concs):
        y = data[i, 0, :]

        if fmax_value is None:
            fmax = fitting.Parameter(3.85)
        else:
            fmax = fitting.Parameter(fmax_value)

        k = fitting.Parameter(5e-4)
        def fit_func(t):
            return 1 + fmax() * (1 - np.exp(-k()*t))

        if fmax_value is None:
            fit_result = fitting.fit(fit_func, [k, fmax], y, time)
        else:
            fit_result = fitting.fit(fit_func, [k], y, time)

        fmax_arr[i] = fmax()
        k_arr[i] = k()

        if plot_fits:
            # Plot the data
            plt.plot(time, y, 'k')
            # Plot the fit to the data
            plt.plot(time, fit_func(time), 'r', zorder=3)

    # Format the finished plot
    if plot_fits:
        # Axis labels
        plt.ylabel('$F/F_0$')
        plt.xlabel(r'Time (sec $\times 10^3$)')
        # Axis bounds and ticks
        ax = plt.gca()
        ax.set_ylim([0.7, 5.2])
        ax.set_xlim([0, bg_time[-1] + 500])
        ax.set_xticks(np.linspace(0, 1e4, 6))
        ax.set_xticklabels([int(f) for f in np.linspace(0, 10, 6)])
        format_axis(ax)
        plt.subplots_adjust(bottom=0.24, left=0.21)

    residuals = fit_result[0]
    sum_sq_err = np.sum(residuals ** 2)
    return (fmax_arr, k_arr, sum_sq_err)