Ejemplo n.º 1
0
                           pad=0.1,
                           color='black',
                           frameon=False,
                           size_vertical=0.,
                           label_top=True)  # ,fontproperties=fontprops

ax_ins.add_artist(scalebar)

ax_ins.xaxis.labelpad = axis_labelpad
ax_ins.yaxis.labelpad = axis_labelpad
ax_ins.legend(frameon=False,
              columnspacing=0.5,
              handletextpad=0.2,
              loc='upper right',
              bbox_to_anchor=(2.5, 1.2))
mpsetup.despine(ax_ins)

#~ file_in_frames_npz_compr = "{inp}/antigenic_space_time_49999.dat".format(inp=dir_io)

xs = []
ys = []
fs = []
nums = []
times = []

avg_xs = []
avg_ys = []

#centroids_dict={}

for file_in_frames_npz_compr in glob.glob(
Ejemplo n.º 2
0
Q = npz['Q']
x = npz['x']
N = len(x)

import run
lambda_ = run.lambda_
tstart, tend = min(ts_mf)*lambda_, max(ts_mf)*lambda_

tlinend = 5
numplot = [5, 61, -1]

fig = plt.figure()

#### First part of figure (small times) ####
ax1 = fig.add_subplot(121)
mpsetup.despine(ax1)
costs_norm = (costs_mf - fopt)/fopt
m, = ax1.plot(ts_mf * lambda_, costs_norm)
s1, = ax1.plot(ts_stoch * lambda_, (costs_stoch - fopt)/fopt,
               lw=linewidth*0.5)
s2, = ax1.plot(ts_stoch * lambda_, (costs_stoch2 - fopt)/fopt,
               lw=linewidth*0.5)
s3, = ax1.plot(ts_stoch * lambda_, (costs_stoch3 - fopt)/fopt,
               lw=linewidth*0.5)
ax1.set_ylabel(r'relative cost gap')
ax1.xaxis.labelpad = axis_labelpad
ax1.set_xlim(tstart, tlinend)
ax1.locator_params(axis='y', nbins=5)
ax1.set_xticks(range(5))
ax1.legend([m, (s1, s2, s3)], ['mean field', 'stochastic'],
           handler_map={tuple: mpsetup.OffsetHandlerTuple()},
def plot_scatter_colorbar(array_x,
                          array_y,
                          xlabel,
                          ylabel,
                          ax=None,
                          show_cbar=True,
                          fig=None,
                          show_legend=True):  # between two observables
    global m_list
    global f_m_list
    global pplnum_list

    if 'fig2' in xlabel:
        show_cbar = False
        show_legend = False

    #~ markers = np.asarray(["x","+","*"])
    markers = np.asarray(["s", "o", "v"])
    sizes = np.asarray([7, 14])

    array_cycle_ppl = ppl_num
    array_cycle_F0 = F0
    array_cycle_M = mem_points

    array_z_orig = mu
    array_z = mu
    if 'fig2' in xlabel:
        array_z = D_mod_all / (real_rec_width**2.)

    #~ array_z=SIG_SPACE
    #~ array_z=S_TOT
    #~ array_z=D_mod_all
    #~ array_z=avg_I
    #array_z=frac_mutants
    zlabel = r'$\mu$ (1/day)'

    if array_y.size > array_z.size:
        array_z_orig = all_mu
        array_z = all_mu
        #~ array_z=S_TOT
        array_cycle_ppl = all_ppl_num
        array_cycle_F0 = all_F0
        array_cycle_M = all_mem_points

    if ("clust" in xlabel or "lineage"
            in xlabel) and "fails" not in xlabel and "all " not in xlabel:

        #~ array_x=rec_width[~fails_clust.astype(bool)]
        array_z_orig = mu[~fails_clust.astype(bool)]
        array_z = mu[~fails_clust.astype(bool)]
        if 'fig2' in xlabel:
            array_z = D_mod_all[~fails_clust.astype(bool)] / (
                real_rec_width[~fails_clust.astype(bool)]**2.)
        #~ array_z=S_TOT[~fails_clust.astype(bool)]

        array_cycle_ppl = ppl_num[~fails_clust.astype(bool)]
        array_cycle_F0 = F0[~fails_clust.astype(bool)]
        array_cycle_M = mem_points[~fails_clust.astype(bool)]

    if "pers time" in xlabel and "fails" not in xlabel:
        #~ array_x=rec_width[~fails_persl.astype(bool)]
        array_z_orig = mu[~fails_persl.astype(bool)]
        array_z = mu[~fails_persl.astype(bool)]

        array_cycle_ppl = ppl_num[~fails_persl.astype(bool)]
        array_cycle_F0 = F0[~fails_persl.astype(bool)]
        array_cycle_M = mem_points[~fails_persl.astype(bool)]
        if 'fig2' in xlabel:
            array_z = D_mod_all[~fails_persl.astype(bool)] / (
                real_rec_width[~fails_persl.astype(bool)]**2.)

    if "altperscolor" in xlabel:
        # ~ array_z=timelast[~fails_persl.astype(bool)]
        # ~ array_z=timescale_system
        array_z = timescale_system / timelast[~fails_persl.
                                              astype(bool)].astype(float)
        # ~ array_z=chisq_avg_angles_subseg_fit_rw_fct_time
    if "altperscolor2" in xlabel:
        # ~ array_z=timelast[~fails_persl.astype(bool)]
        # ~ array_z=timescale_system
        # ~ array_z=timescale_system/timelast[~fails_persl.astype(bool)].astype(float)
        array_z = chisq_avg_angles_subseg_fit_rw_fct_time

    if "altperscolor3" in xlabel:
        # ~ array_z=timelast[~fails_persl.astype(bool)]
        # ~ array_z=timescale_system
        # ~ array_z=timescale_system/timelast[~fails_persl.astype(bool)].astype(float)
        # ~ array_z=np.abs(pers_l_avg_end2end_fit_varvel_fct_time_fixvel - pers_l_avg_end2end_fit_constvel_fct_time_fixvel)/pers_l_avg_end2end_fit_varvel_fct_time_fixvel
        array_z = np.abs(pers_l_avg_end2end_fit_varvel_fct_time_fixvel -
                         array_y) / array_y

    if 'fig2' in xlabel:
        array_cycle_ppl = array_cycle_ppl[(array_z_orig >= 0.01)]
        array_cycle_F0 = array_cycle_F0[(array_z_orig >= 0.01)]
        array_cycle_M = array_cycle_M[(array_z_orig >= 0.01)]
        array_x = array_x[(array_z_orig >= 0.01)]
        array_y = array_y[(array_z_orig >= 0.01)]
        array_z = array_z[(array_z_orig >= 0.01)]

    mask = np.isfinite(array_x) & np.isfinite(array_y)
    mask = mask & (array_y > 0) & (array_x > 0)

    if "pers time" in xlabel and "angle" in xlabel:
        chisq_mask = chisq_avg_angles_subseg_fit_rw_fct_time
        if 'fig2' in xlabel:
            chisq_mask = chisq_avg_angles_subseg_fit_rw_fct_time[(array_z_orig
                                                                  >= 0.01)]

    if "pers time" in xlabel and "constvel" in xlabel:
        chisq_mask = chisq_avg_end2end_fit_constvel_fct_time_fixvel
    if "pers time" in xlabel and "varvel" in xlabel:
        chisq_mask = chisq_avg_end2end_fit_varvel_fct_time_fixvel

    if "pers time" in xlabel or "turn" in xlabel:
        # ~ mask=mask & (chisq_mask < 1000)  & (chisq_mask > 0.4)
        mask = mask & (array_x > 0)
        # ~ if  "angle" in xlabel:
        # ~ mask=mask  & (array_x<100000)
        # ~ else:
        # ~ mask=mask  & (array_x<10000)
        if 'filterpersl' in xlabel:
            mask = mask & (chisq_mask < 3)

    array_z = array_z[mask]
    X = array_x[mask]
    Y = array_y[mask]

    array_cycle_ppl = array_cycle_ppl[mask]
    array_cycle_F0 = array_cycle_F0[mask]
    array_cycle_M = array_cycle_M[mask]

    array_col_m = np.unique(array_z)

    mincol = np.amin(array_z)
    maxcol = np.amax(array_z)

    if 'fig2' in xlabel:
        mincol = 10.**(-13.)
        maxcol = 2. * 10.**(-6.)

    # ~ if 'fig2' in xlabel:
    # ~ mincol= 0.0005
    # ~ maxcol= 0.01

    print array_x
    print array_y
    print array_y[(array_x > 0)]
    # ~ print D_mod_all
    print array_z
    print array_col_m

    print X
    print Y
    print np.amin(Y)
    print np.amax(Y)
    print np.amin(array_y)
    print np.amax(array_y)
    print np.amin(array_x)
    print np.amax(array_x)

    print array_x.size
    print array_y.size
    print array_z.size

    col_list = []

    cmap = get_cmap(array_z.size)

    for x in range(array_z.size):
        col_list.append(cmap(float(x)))

    fm_ind = np.arange(array_z.size)
    print fm_ind

    #~ col_list = []

    #~ cmap = get_cmap(array_col_m.size)

    #~ for x in range(array_col_m.size):
    #~ col_list.append(cmap(float(x)))

    savefig = False

    if ax is None:

        savefig = True

        fig = plt.figure(figsize=(thisfigsize[0], thisfigsize[0] * 4. /
                                  5))  #figsize=thisfigsize
        grid = gridspec.GridSpec(1,
                                 1,
                                 left=0.17,
                                 right=0.92,
                                 top=0.85,
                                 bottom=0.17,
                                 wspace=0.4,
                                 hspace=0.35)
        labeled_axes = []
        ax = plt.Subplot(fig, grid[0, 0])
        fig.add_subplot(ax)
        labeled_axes.append(ax)
    #color.cycle_cmap(rec_width[0,:].size, cmap='pink', ax=ax)

    ax.set_prop_cycle(cycler('color', col_list))

    sig_ind = np.arange(array_col_m.size)

    cmx = plt.cm.get_cmap('plasma')
    #~ c = plt.cm.gist_rainbow(colors)
    #~ c = plt.cm.jey(colors)

    s_m = matplotlib.cm.ScalarMappable(cmap=cmx,
                                       norm=matplotlib.colors.Normalize(
                                           vmin=np.amin(fm_ind),
                                           vmax=np.amax(fm_ind)))
    s_m.set_array([])

    if "altperscolor" in xlabel:

        mincol = np.amin(array_z)
        maxcol = np.amax(array_z)

    print array_z

    print "color lims"
    print mincol, maxcol

    for i_m, m_mean in enumerate(m_list):
        for i_f, f_mean in enumerate(f_m_list):
            for i_p, ppl in enumerate(pplnum_list):
                print i_p, ppl, markers[i_p]

                # ~ idxs=np.nonzero((array_cycle_F0==f_mean) & (array_cycle_ppl==ppl))[0]
                idxs = np.nonzero((array_cycle_F0 == f_mean)
                                  & (array_cycle_ppl == ppl)
                                  & (array_cycle_M == m_mean))[0]

                array_z_now = array_z[idxs]
                X_now = X[idxs]
                Y_now = Y[idxs]

                #~ if i_f==0:
                #~ face="'none'"
                #~ else:
                #~ face=array_z
                #~ , edgecolor=''

                #~ print i_f,   face

                if show_legend:
                    legend = r'$F0$ {f_ms}, $N_h$ {ppl}'.format(f_ms=f_mean,
                                                                ppl=fmt(ppl))
                else:
                    legend = ''

                sc = ax.scatter(X_now,
                                Y_now,
                                c=array_z_now,
                                vmin=mincol,
                                vmax=maxcol,
                                marker=markers[i_p],
                                s=sizes[i_m],
                                cmap=cmx,
                                norm=matplotlib.colors.LogNorm(),
                                label=legend)

                if i_f == 1:
                    sc.set_facecolor('none')

        show_legend = False

    if show_cbar:

        #~ cbar = fig.colorbar(CS) # draw colorbar
        #cbar.set_label('{obs_name}'.format(obs_name=zlabel), rotation=270, labelpad=+8)

        if 'fig2' in xlabel:
            cbar = plt.colorbar(sc, ticks=[0.001, 0.01, 0.1])
            # ~ cbar = plt.colorbar(sc, ticks=np.unique(array_z))
            # ~ cbar.ax.set_yticklabels(['3*10^'])

        else:
            cbar = plt.colorbar(sc)

        cbar.set_label(zlabel, rotation=270, labelpad=+8)
        # ~ if 'fig2' in xlabel:
        # ~ cbar.ax.set_yticks([0.001, 0.01, 0.1])
    #~ cbar.ax.set_yticklabels(array_col_m)
    #    ax.plot(IS_x, IS_y, linestyle='-', color='r', label='average IS')
    if "pers time teo" in ylabel:
        ax.set_xlabel(r'numerical persistence time')
        ax.set_ylabel('theoretical \n persistence time')

    elif "var clust perp v3" in ylabel:
        ax.set_xlabel(r'$\sqrt{1.66} \sigma_{\parallel}$')
        ax.set_ylabel(r'$\sigma_{\perp}$')

    elif "var clust perp v2" in ylabel:
        ax.set_xlabel(r'$\sqrt{2} \sigma_{\parallel}$')
        ax.set_ylabel(r'$\sigma_{\perp}$')
    elif "vel rescteo" in ylabel:
        ax.set_xlabel(r'numerical $\sigma ^2$')
        ax.set_ylabel(r'numerical $v/s$')
    elif "wave size teo" in ylabel:
        ax.set_xlabel(r'numerical $\sigma$')
        ax.set_ylabel(r'theoretical $\sigma$')
    elif "vel teo" in ylabel:
        ax.set_xlabel(r'numerical $v$')
        ax.set_ylabel(r'theoretical $v$')
    elif "fittest space teo" in ylabel:
        ax.set_xlabel(r'numerical $u_c$')
        ax.set_ylabel(r'theoretical $u_c$')
    elif "sel teo" in ylabel:
        ax.set_xlabel(r'numerical $s$')
        ax.set_ylabel(r'theoretical $s$')
    elif "vtau teo" in ylabel:
        ax.set_xlabel(r'numerical $v\tau$')
        ax.set_ylabel(r'theoretical $v\tau$')
    elif "num virs teo" in ylabel:
        ax.set_xlabel(r'numerical $N$')
        ax.set_ylabel(r'theoretical $N$')
    elif "D X extinction rate" in ylabel:
        ax.set_xlabel(r'numerical $v/N$')
        ax.set_ylabel(r'numerical (extinction rate) $ D$')
    elif "D13 X extinction rate" in ylabel:
        ax.set_xlabel(r'numerical $1/N$')
        ax.set_ylabel(r'numerical (extinction rate) $ D^{1/3}$')
    elif "1oN model" in xlabel:
        ax.set_xlabel(r'numerical $1/N$')
        ax.set_ylabel(r'numerical extinction rate')
    elif "vel resc teo clust" in xlabel:
        ax.set_xlabel(r'theoretical $v/\sqrt{D}$')
        ax.set_ylabel(r'rate of lineage splitting')
    elif "sel teo clust 4" in xlabel:
        ax.set_xlabel(r'theoretical $S$')
        ax.set_ylabel(r'rate of lineage splitting')
    elif "N model clust" in xlabel:
        ax.set_xlabel(r'numerical $N$')
        ax.set_ylabel(r'rate of lineage splitting')
    elif "I model clust 3" in xlabel:
        ax.set_xlabel(r'numerical $I$')
        ax.set_ylabel(r'rate of lineage splitting')

    else:
        ax.set_xlabel(xlabel)
        ax.set_ylabel(ylabel)

    ax.xaxis.labelpad = axis_labelpad
    ax.yaxis.labelpad = axis_labelpad
    #ax.legend( [sc], "fi", frameon=False, columnspacing=0.5, handletextpad=0.2,

    if "single lineage probability" in ylabel:
        ax.set_xscale('log')
        ax.set_xlim(xmin=np.amin(X) / 2., xmax=np.amax(X) * 2.)

    elif "rescaled pop size" not in xlabel:
        ax.set_xscale('log')
        ax.set_yscale('log')
        ax.loglog(X, X, marker='', linestyle='-', linewidth=0.5, color='grey')

        ax.set_ylim(ymin=np.amin(Y) / 2., ymax=np.amax(Y) * 2.)
        ax.set_xlim(xmin=np.amin(X) / 2., xmax=np.amax(X) * 2.)
        #~ ax.set_xlim(xmax=0.1)
        #~ ax.set_ylim(ymax=0.1)

    elif "extinction rate" in ylabel:
        ax.set_yscale('log')

        ax.set_ylim(ymin=np.amin(Y) / 2., ymax=np.amax(Y) * 2.)

    else:
        ax.set_xlim(xmin=0, xmax=20)
        ax.set_ylim(ymin=0, ymax=8)
        ax.set_xticks([2, 6, 10, 14, 18])
        ax.set_yticks([0, 2, 4, 6, 8])

    bbox_to_anchor = (0.95, 1.22)
    if not savefig:
        bbox_to_anchor = (1.5, 1.65)

    leg = ax.legend(frameon=False,
                    ncol=2,
                    columnspacing=0.5,
                    handletextpad=0.2,
                    loc='upper right',
                    bbox_to_anchor=bbox_to_anchor,
                    prop={'size': 7})
    mpsetup.despine(ax)

    #leg = ax.get_legend()
    for handler in leg.legendHandles:
        handler.set_color('black')
    for handler in leg.legendHandles[-len(pplnum_list):]:
        handler.set_facecolor('none')

    #### finish figure ####
    labeldict = dict(labelstyle=r'{\sf \textbf{%s}}',
                     fontsize='medium',
                     xycoords=('axes fraction'),
                     fontweight='bold')
    #    mpsetup.label_axes([labeled_axes[0]], labels='A', xy=(-0.2, 0.95), **labeldict)
    #mpsetup.label_axes([labeled_axes[1]], labels='B', xy=(-0.3, 0.95), **labeldict)

    xstring = xlabel.replace(" ", "_")
    ystring = ylabel.replace(" ", "_")
    title_string = '{xstring}-{ystring}'.format(xstring=xstring,
                                                ystring=ystring)

    print title_string

    out_file = '{out}/{title_string}.pdf'.format(out=dir_o,
                                                 title_string=title_string)
    #    print out_file, dpi=300
    if savefig:

        fig.savefig(out_file)
        fig.clf()
        plt.close('all')
Ejemplo n.º 4
0
rdf = rdfsum / len(filenames)
binmid = npz['binmid']
sigma = immune.parse_value(filename, 'sigma')
## plot
ax = fig.add_subplot(121)
labeled_axes.append(ax)
ax.plot(binmid/sigma, rdf)
ax.axhline(1.0, color=almostblack)
ax.set_xlim(0, 8)
ax.locator_params(axis='y', nbins=3, tight=True)
ax.set_ylim(0, 1.8)
ax.set_xlabel('$R$ / $\sigma$')
ax.xaxis.labelpad = axis_labelpad
ax.yaxis.labelpad = axis_labelpad
ax.set_ylabel('radial distribution\nfunction $g(R)$')
mpsetup.despine(ax)

#### Subfigure B: S(q) ####
ax = fig.add_subplot(122)
labeled_axes.append(ax)
kappas = sorted(list(set(immune.parse_value(f, 'kappa') for f in glob.glob('data/sq*'))))[::-1]
for kappa in kappas:
    files = glob.glob('data/sq*kappa%g*' % kappa)
    sqsum = None
    for f in files:
        npz = np.load(f)
        if sqsum is not None:
            sqsum += npz['sq']
        else:
            sqsum = npz['sq']
    sq = sqsum / len(files)
                                             wspace=0.4,
                                             hspace=0.35)
                    labeled_axes = []

                    ax = plt.Subplot(fig, grid[0, 0])
                    fig.add_subplot(ax)
                    labeled_axes.append(ax)
                    ax.plot(time[1:-1],
                            vel_cloud_avg[1:],
                            linestyle='-',
                            color='g')
                    ax.set_xlabel('time (cy)')
                    ax.set_ylabel('average virus speed')
                    ax.xaxis.labelpad = axis_labelpad
                    ax.yaxis.labelpad = axis_labelpad
                    mpsetup.despine(ax)

                    #### finish figure ####
                    labeldict = dict(labelstyle=r'{\sf \textbf{%s}}',
                                     fontsize='medium',
                                     xycoords=('axes fraction'),
                                     fontweight='bold')
                    #    mpsetup.label_axes([labeled_axes[0]], labels='A', xy=(-0.2, 0.95), **labeldict)
                    #mpsetup.label_axes([labeled_axes[1]], labels='B', xy=(-0.3, 0.95), **labeldict)
                    out_file = '{out}/vir_avg_speed_{real}.pdf'.format(
                        out=dir_out_plots, real=real)
                    #    print out_file
                    fig.savefig(out_file)
                    #    plt.show()
                    #    print out_file
Ejemplo n.º 6
0
    return np.piecewise(x, [x < sigmac, x > sigmac],
                        [lambda x: constcost, lambda x: x / (1 - 1/x**2)**.5])
xmax = sigmac * 2
ymax = 5.5
x = np.linspace(0, xmax, 100)
ax_cost.plot(x, optcost(x), c=color_cycle[0])
ax_cost.set_xticks([sigmac])
ax_cost.set_xticklabels(['$\sqrt{2}$'])
lines = ax_cost.vlines(sigmac, 0, constcost, linestyles='dotted')
ax_cost.set_ylim(0, ymax)
ax_cost.set_xlim(0, xmax)
ax_cost.set_ylabel(r'optimized cost$\; \times \; \sigma$')
ax_cost.set_xlabel('$\sigma \; / \; \sigma_Q$')
ax_cost.xaxis.set_label_coords(0.95, -0.025)
ax_cost.set_yticks([])
mpsetup.despine(ax_cost)
fig.tight_layout(pad=tight_layout_pad)

## plot inset axes
pos = ax_cost.get_position(fig).get_points()
illugrid = gridspec.GridSpec(1, 3,
                             left=pos[0, 0] + 0.03*(pos[1, 0] - pos[0, 0]),
                             bottom=pos[0, 1] + 0.61*(pos[1, 1] - pos[0, 1]),
                             right=pos[1, 0] - 0.17*(pos[1, 0] - pos[0, 0]),
                             top=pos[1, 1] - 0.03*(pos[1, 1] - pos[0, 1]))
illucolors = color_cycle[1:]
x = np.linspace(-4, 4, 100)
ymax = 0.8
for i, sigma in enumerate([0.45, 1.3, 2.1]):
    ax = plt.Subplot(fig, illugrid[0, i], axisbg='none')
    fig.add_subplot(ax)
Ejemplo n.º 7
0
    psd = psdsum / len(files)
    sigma = immune.parse_value(f, 'sigma')
    kappa = immune.parse_value(f, 'kappa')
    Delta = immune.parse_value(f, 'Delta')
    N = (1.0 / (Delta * sigma))**2
    bins = npz['bins']
    axscaled.plot(2*np.pi*bins[1:]*sigma, psd[1:] / kappa**2, '.',
                  label='$\kappa$ = %g' % kappa)
ylims = (1e-6, axscaled.get_ylim()[1] * 2.0)
xlims = (0.1, axscaled.get_xlim()[1])
qsigma = np.logspace(-1, 1, 200)
axscaled.plot(qsigma, np.exp(qsigma**2) / (4 * N),
              label=r'$\frac{\kappa^2}{4 N}\exp\left[(q \sigma)^2\right]$')
axscaled.set_yscale('log')
axscaled.set_xscale('log')
axscaled.set_ylim(*ylims)
axscaled.set_xlim(*xlims)
axscaled.set_ylabel("power spectral density / $\kappa^2$")
h, l = axscaled.get_legend_handles_labels()
legend_kappa = axscaled.legend(h[:3], l[:3], loc='upper left',
                               title='pathogen\nheterogeneity')
legend_function = axscaled.legend(h[3:], l[3:], loc='lower right')
axscaled.add_artist(legend_kappa)
axscaled.set_xlabel("$q \; \sigma$")
axscaled.xaxis.labelpad = axis_labelpad

mpsetup.despine(axscaled)
fig.tight_layout(pad=tight_layout_pad)
fig.savefig('figS3.svg')
plt.show()