Example #1
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 #2
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 #3
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)
Example #4
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)
def plot_means(deltas, plot_filename=None):
    # Calculate the means
    (activators, residues, reps) = get_keys(deltas)
    residues = [res for res in residues if res != '62']
    set_fig_params_for_publication()
    (fig_width, rel_left, rel_right) = nba.calc_barplot_width(len(residues))
    bar_colors = {'Bid': 'gray', 'Bim': 'black'}

    plt.figure(figsize=(fig_width, 1.5), dpi=300)
    for act_ix, act in enumerate(activators):
        for nbd_ix, res in enumerate(residues):
            vals = [deltas[(act, 'FRET', res, rep)] for rep in reps]
            #means[(act, res)] = np.mean(vals)
            #sds[(act, res)] = np.std(vals, ddof=1)

            plt.bar(range(nbd_ix*3 + act_ix, (nbd_ix*3) + 1 + act_ix),
                    np.mean(vals), width=1, color=bar_colors[act],
                    linewidth=0, ecolor='k', capsize=1.5,
                    yerr=np.std(vals, ddof=1))
    x_lbound = -1
    x_ubound = len(residues) * 3
    plt.hlines(0, x_lbound, x_ubound, color='0.85', zorder=1, linewidth=0.5)
    plt.subplots_adjust(left=rel_left, bottom=0.1, right=rel_right, top=0.94)
    ax = plt.gca()
    ax.set_xlim([x_lbound, x_ubound])
    ax.xaxis.set_ticks_position('none')
    ax.yaxis.set_ticks_position('left')
    ax.xaxis.set_tick_params(which='both', labelsize=fontsize, pad=2,
            length=2, width=0.5)
    ax.yaxis.set_tick_params(which='both', direction='out',
                    labelsize=fontsize, pad=0, length=2, width=0.5)
    ax.xaxis.labelpad = 2
    ax.yaxis.labelpad = 2
    ax.set_xticks(np.arange(1, 1 + len(residues) * 3, 3))
    ax.set_xticklabels(residues)
    ax.set_ylabel('Max FRET - Endpoint FRET', fontsize=fontsize)
    # Create legend with rectangles to match colors of bars
    bid_patch = mpatches.Patch(color=bar_colors['Bid'], label='cBid')
    bim_patch = mpatches.Patch(color=bar_colors['Bim'], label='Bim')
    leg = plt.legend(handles=[bid_patch, bim_patch],
            bbox_to_anchor=(1.02, 0.5), loc='center left', borderaxespad=0.,
            prop={'size': fontsize}, handlelength=1)
    leg.draw_frame(False)

    # Save the figure
    if plot_filename:
        plt.savefig('%s.pdf' % plot_filename)
        plt.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)
from tbidbaxlipo.util import set_fig_params_for_publication, format_axis, \
                             fontsize
from tbidbaxlipo.plots.bax_bax_fret_nbd_release.preprocess_data import \
        df_pre as df
import numpy as np
from matplotlib import pyplot as plt

set_fig_params_for_publication()

curves_to_plot = [('Bid', '54'),
                  ('Bid', '126')]

plt.ion()

fig, axarr = plt.subplots(1, 2, sharex=True, figsize=(3, 1.5), dpi=300)

# Four subplots
for plot_ix, curve_info in enumerate(curves_to_plot):
    row_ix = 1
    col_ix = plot_ix
    act = curve_info[0]
    res = curve_info[1]
    ax1 = axarr[plot_ix]
    ax2 = ax1.twinx()
    # Get data
    nbd_t = df[(act, 'NBD', res, 1, 'TIME')].values
    nbd_v = df[(act, 'NBD', res, 1, 'VALUE')].values
    fret_t = df[(act, 'FRET', res, 1, 'TIME')].values
    fret_v = df[(act, 'FRET', res, 1, 'VALUE')].values
    rel_t = df[(act, 'Release', res, 1, 'TIME')].values
    rel_v = df[(act, 'Release', res, 1, 'VALUE')].values
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)
Example #9
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)
Example #10
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)
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 #12
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)