def setup_figure():
    width = 18.3
    height = (1 / 2) * width

    lineweight = width / 3
    mpl.rcParams['lines.linewidth'] = lineweight
    mpl.rcParams['axes.formatter.limits'] = (-3, 6)

    # set up multi-panel figure
    fig = plt.figure(figsize=(width, height))
    gs = gridspec.GridSpec(1, 2)

    plot_positions = [
        {
            "name": "fixed",
            "grid_position": np.s_[0, 0],
            "sharex": None,
            "sharey": None
        },
        {
            "name": "variable",
            "grid_position": np.s_[0, 1],
            "sharex": "fixed",
            "sharey": "fixed"
        },
    ]

    plots = setup_multipanel(fig,
                             plot_positions,
                             gridspec=gs,
                             letter_loc=(0.05, 1.07))

    return (fig, plots)
Example #2
0
def setup_figure():
    width = 18.3
    height = (1/3) * width

    lineweight = width / 3
    mpl.rcParams['lines.linewidth'] = lineweight
    mpl.rcParams['axes.formatter.limits'] = (-3, 6)

    # set up multi-panel figure
    fig = plt.figure(figsize=(width, height))
    gs = mpl.gridspec.GridSpec(1, 3)


    short_col, long_col, exp_long_col = 0, 1, 2
    
    plot_positions = [
        {"name": "typical",
         "grid_position": np.s_[0, short_col],
         "sharex": None,
         "sharey": None},
        
        {"name": "prolonged",
         "grid_position": np.s_[0, long_col],
         "sharex": None,
         "sharey":  "typical"},
                
        {"name": "prolonged-experienced",
         "grid_position": np.s_[0, exp_long_col],
         "sharex": "prolonged",
         "sharey": "typical"}
    ]
    
    plots = setup_multipanel(fig,
                             plot_positions,
                             gridspec=gs)

    return (fig, plots)
def main(drift_data_paths=None,
         constant_data_paths=None,
         pt_data_paths=None,
         both_data_paths=None,
         param_file=None,
         output_path=None):

    ## figure styling / setup
    width = 18.3
    mpl.rcParams['font.size'] = width / 1.5
    mpl.rcParams['lines.linewidth'] = width / 2.5
    kernel_lw = width / 4.5
    mpl.rcParams['ytick.major.pad'] = width / 2
    mpl.rcParams['xtick.major.pad'] = width / 2
    mpl.rcParams['legend.fontsize'] = width * 0.9
    mpl.rcParams['legend.title_fontsize'] = width
    mpl.rcParams['legend.handlelength'] = 2

    height = width / 2
    fig = plt.figure(figsize=(width, height))

    nrows = 2
    ncols = 4
    gs = gridspec.GridSpec(nrows, ncols)

    ## multipanel setup
    change_dist_sim_row = 0
    change_dist_ana_row = 1
    drift_col, const_col, both_col, pt_col = 0, 1, 2, 3

    plot_positions = [{
        "name": "change-dist-drift-sim",
        "grid_position": np.s_[change_dist_sim_row, drift_col],
        "sharex": None,
        "sharey": None
    }, {
        "name": "change-dist-constant-sim",
        "grid_position": np.s_[change_dist_sim_row, const_col],
        "sharex": "change-dist-drift-sim",
        "sharey": "change-dist-drift-sim"
    }, {
        "name": "change-dist-both-sim",
        "grid_position": np.s_[change_dist_sim_row, both_col],
        "sharex": "change-dist-drift-sim",
        "sharey": "change-dist-drift-sim"
    }, {
        "name": "change-dist-pt-sim",
        "grid_position": np.s_[change_dist_sim_row, pt_col],
        "sharex": "change-dist-drift-sim",
        "sharey": "change-dist-drift-sim"
    }, {
        "name": "change-dist-drift-ana",
        "grid_position": np.s_[change_dist_ana_row, drift_col],
        "sharex": "change-dist-drift-sim",
        "sharey": None
    }, {
        "name": "change-dist-constant-ana",
        "grid_position": np.s_[change_dist_ana_row, const_col],
        "sharex": "change-dist-drift-ana",
        "sharey": "change-dist-drift-ana"
    }, {
        "name": "change-dist-both-ana",
        "grid_position": np.s_[change_dist_ana_row, both_col],
        "sharex": "change-dist-drift-ana",
        "sharey": "change-dist-drift-ana"
    }, {
        "name": "change-dist-pt-ana",
        "grid_position": np.s_[change_dist_ana_row, pt_col],
        "sharex": "change-dist-drift-ana",
        "sharey": "change-dist-drift-ana"
    }]

    letter_loc = (-0.1, 1.15)
    plots = setup_multipanel(fig,
                             plot_positions,
                             letter_loc=letter_loc,
                             gridspec=gs)

    ## parametrization
    params = pp.get_params(param_file)
    b = int(params.get("DEFAULT_CHAIN_BOTTLENECK"))
    v = int(float(params.get("DEFAULT_VB_RATIO")) * b)
    f_mut = float(params.get("DEFAULT_F_MUT"))
    z_wt = float(params.get("DEFAULT_Z_WT"))
    k = float(params.get("CONSTANT_CHAIN_K"))
    mu = float(params.get("DEFAULT_MU"))
    d_v = float(params.get("DEFAULT_D_V"))
    R0 = float(params.get("DEFAULT_R0_WH"))
    mut_sd = float(params.get("DEFAULT_CHAIN_MUT_SD"))
    mut_mu = float(params.get("DEFAULT_CHAIN_MUT_MEAN"))

    print("parsed parameter file: v = {}, b = {}".format(v, b))
    print("parsed parameter file: f_mut = {}".format(f_mut))
    print("parsed parameter file: z_wt = {}".format(z_wt))

    #####################################
    # simulated kernel shifts
    #####################################

    print("plotting simulated kernel shifts...")
    plot_change_dists(plots,
                      drift_data_paths,
                      constant_data_paths,
                      both_data_paths,
                      pt_data_paths,
                      param_file,
                      kernel_lw=kernel_lw,
                      kernel_color=ps.kernel_color,
                      kernel_alpha=ps.kernel_alpha,
                      kernel_linestyle=ps.kernel_linestyle,
                      dash_capstyle='round')

    #####################################
    # analytical kernel shifts
    #####################################
    print("plotting analytical kernel shifts...")
    ana_phenotypes = np.linspace(-0.35, 0.35, 101)

    ana_gen_phen = -0.8  # least immune history
    ana_recip_phen = -0.8  # from the sim model

    kern_escape = 1
    kern_model = 'linear'

    print("no immunity...")
    plot_kernel_shift_repl(axis=plots['change-dist-drift-ana'],
                           k=0,
                           mu=mu,
                           d_v=d_v,
                           R0=R0,
                           bottleneck=b,
                           t_M=0,
                           t_transmit=2,
                           vb_ratio=v / b,
                           sd_mut=mut_sd,
                           phenotypes=ana_phenotypes,
                           generator_phenotype=-99,
                           z_homotypic=0.95,
                           recipient_phenotype=-99,
                           susceptibility_model=kern_model,
                           escape=kern_escape,
                           dist_color=ps.inocs_color,
                           kernel_color=ps.kernel_color,
                           kernel_alpha=ps.kernel_alpha,
                           kernel_lw=kernel_lw,
                           kernel_linestyle=ps.kernel_linestyle,
                           dist_alpha=ps.dist_alpha,
                           dash_capstyle='round',
                           mark_original_phenotype=True)

    print("constant recall response...")
    plot_kernel_shift_repl(axis=plots['change-dist-constant-ana'],
                           k=k,
                           mu=mu,
                           d_v=d_v,
                           R0=R0,
                           bottleneck=b,
                           t_M=0,
                           t_transmit=2,
                           vb_ratio=v / b,
                           sd_mut=mut_sd,
                           phenotypes=ana_phenotypes,
                           generator_phenotype=ana_gen_phen,
                           z_homotypic=0.95,
                           recipient_phenotype=-99,
                           susceptibility_model=kern_model,
                           escape=kern_escape,
                           dist_color=ps.inocs_color,
                           kernel_color=ps.kernel_color,
                           kernel_alpha=ps.kernel_alpha,
                           kernel_linestyle=ps.kernel_linestyle,
                           kernel_lw=kernel_lw,
                           dist_alpha=ps.dist_alpha,
                           dash_capstyle='round',
                           mark_original_phenotype=True)

    print("constant recall response with mucosal antibodies...")
    plot_kernel_shift_repl(axis=plots['change-dist-both-ana'],
                           k=k,
                           mu=mu,
                           d_v=d_v,
                           R0=R0,
                           bottleneck=b,
                           t_M=0,
                           t_transmit=2,
                           vb_ratio=v / b,
                           sd_mut=mut_sd,
                           phenotypes=ana_phenotypes,
                           generator_phenotype=ana_gen_phen,
                           z_homotypic=0.95,
                           recipient_phenotype=ana_recip_phen,
                           susceptibility_model=kern_model,
                           escape=kern_escape,
                           dist_color=ps.inocs_color,
                           kernel_color=ps.kernel_color,
                           kernel_alpha=ps.kernel_alpha,
                           kernel_linestyle=ps.kernel_linestyle,
                           kernel_lw=kernel_lw,
                           dist_alpha=ps.dist_alpha,
                           dash_capstyle='round',
                           mark_original_phenotype=True)

    print("realistic recall response with mucosal antibodies...")
    plot_kernel_shift_repl(axis=plots['change-dist-pt-ana'],
                           k=k,
                           mu=mu,
                           d_v=d_v,
                           R0=R0,
                           bottleneck=b,
                           t_M=2,
                           t_transmit=2,
                           vb_ratio=v / b,
                           sd_mut=mut_sd,
                           phenotypes=ana_phenotypes,
                           generator_phenotype=ana_gen_phen,
                           z_homotypic=0.95,
                           recipient_phenotype=ana_recip_phen,
                           susceptibility_model=kern_model,
                           escape=kern_escape,
                           dist_color=ps.inocs_color,
                           kernel_color=ps.kernel_color,
                           kernel_alpha=ps.kernel_alpha,
                           kernel_lw=kernel_lw,
                           kernel_linestyle=ps.kernel_linestyle,
                           dist_alpha=ps.dist_alpha,
                           dash_capstyle='round',
                           mark_original_phenotype=True)

    #####################################
    # plot styling
    #####################################

    for plotname, plot in plots.items():
        if 'ana' in plotname:
            plot.set_xlabel('antigenic change')
        if 'drift-sim' in plotname:
            plot.set_ylabel('frequency')
        if 'drift-ana' in plotname:
            plot.set_ylabel('probability density')
        plot.set_ylim(bottom=0)
        plot.label_outer()

    fig.tight_layout()

    # save
    fig.savefig(output_path)

    return 0
def main(argv):
    if len(argv) < 2:
        print("USAGE: ./{} <outpath>\n\n" "outpath: path to output figure\n\n")
        return 0

    outpath = argv[1]

    width = 12
    height = width
    color_low, color_high = 0.3, 0.7
    lineweight = width / 2.5
    mpl.rcParams['lines.linewidth'] = lineweight
    mpl.rcParams['font.size'] = 1.5 * width
    mpl.rcParams['legend.fontsize'] = "x-small"
    mpl.rcParams['legend.loc'] = "upper left"

    fig = plt.figure(figsize=(width, height))

    plot_positions = [
        {
            "name": "varying-selection",
            "row": 1,
            "col": 1,
            "sharex": None,
            "sharey": None
        },
        {
            "name": "varying-init-freq",
            "row": 1,
            "col": 2,
            "sharex": "varying-selection",
            "sharey": "varying-selection"
        },
        {
            "name": "varying-selection-ongoing",
            "row": 2,
            "col": 1,
            "sharex": "varying-selection",
            "sharey": None
        },
        {
            "name": "varying-init-freq-ongoing",
            "row": 2,
            "col": 2,
            "sharex": "varying-selection-ongoing",
            "sharey": "varying-selection-ongoing"
        },
    ]

    all_plots = pf.add_bounding_subplot(fig, position="111")
    plots = pf.setup_multipanel(fig, plot_positions)

    times = np.linspace(0, 4, 1000)

    deltas = [12, 9, 6, 3]
    delta_colors = np.linspace(color_high, color_low, len(deltas))
    delta_cmap = plt.cm.Greens

    mu = 0.33e-5
    R0 = 5
    d_v = 4
    t_peak = 1.5
    t_M = 2
    t_emerge = 0

    mu_mult_exps = [3, 2, 1, 0]
    mu_colors = np.linspace(color_high, color_low, len(mu_mult_exps))
    mu_cmap = plt.cm.Blues

    for delta, color in zip(deltas, delta_colors):
        freqs = [whp.freq_mut_select(t, mu, delta) for t in times]
        freqs_ongoing = [
            whp.freq_mut_ongoing_piecewise(t, t_emerge, t_M, t_peak, mu, delta,
                                           mu, R0 * d_v) for t in times
        ]

        plots["varying-selection"].plot(times,
                                        freqs,
                                        color=delta_cmap(color),
                                        label="${}$".format(delta))
        plots["varying-selection-ongoing"].plot(times,
                                                freqs_ongoing,
                                                color=delta_cmap(color))
        plots["varying-selection-ongoing"].axvline(t_M,
                                                   color="k",
                                                   linestyle="dashed")

    delta_fix = 6

    for mult_exp, color in zip(mu_mult_exps, mu_colors):
        freqs = [
            whp.freq_mut_select(t, mu * 10**(mult_exp), delta_fix)
            for t in times
        ]
        freqs_ongoing = [
            whp.freq_mut_ongoing_piecewise(t, t_emerge, t_M, t_peak,
                                           mu * 10**(mult_exp), delta_fix, mu,
                                           R0 * d_v) for t in times
        ]

        plots["varying-init-freq"].plot(
            times,
            freqs,
            color=mu_cmap(color),
            label="$\\mu \\times 10^{}$".format(mult_exp))
        plots["varying-init-freq-ongoing"].plot(times,
                                                freqs_ongoing,
                                                color=mu_cmap(color))
        plots["varying-init-freq-ongoing"].axvline(t_M,
                                                   color="k",
                                                   linestyle="dashed")

    plots["varying-selection"].legend(title="$\delta$",
                                      handlelength=width / 10)
    plots["varying-init-freq"].legend(title="$f_0$", handlelength=width / 20)

    freq_ticks = [0, 0.25, 0.5, 0.75, 1]
    for plotname, plot in plots.items():
        plot.label_outer()
        plot.set_xlim([0, 4])
        if not "ongoing" in plotname:
            plot.set_yticks(freq_ticks)
            plot.set_yticklabels(["${}$".format(x) for x in freq_ticks])
        else:
            plot.set_yscale("log")

    all_plots.set_xlabel("time since first new variant (days)")
    plots["varying-selection"].set_ylabel("variant frequency $f_m$")
    plots["varying-selection-ongoing"].set_ylabel("variant frequency $f_m$")

    fig.tight_layout()

    fig.savefig(outpath)

    return 0
def setup_figure():

    # set up multi-panel figure
    fig = plt.figure(figsize=(width, height))

    n_cols = 5
    n_rows = 2
    letter_y = 1.15
    letter_x = -0.05

    gs = gridspec.GridSpec(n_rows, n_cols)

    all_plots = pf.add_bounding_subplot(fig, position=gs[:, :])

    all_timecourses = pf.add_bounding_subplot(fig, position=gs[:, :3])

    plot_positions = [{
        "name": "sterilized-abs",
        "grid_position": np.s_[0, 0],
        "sharex": None,
        "sharey": None
    }, {
        "name": "replication-selected-abs",
        "grid_position": np.s_[0, 1],
        "sharex": "sterilized-abs",
        "sharey": "sterilized-abs"
    }, {
        "name": "inoculation-selected-abs",
        "grid_position": np.s_[0, 2],
        "sharex": "sterilized-abs",
        "sharey": "sterilized-abs"
    }, {
        "name": "proportion-plot",
        "grid_position": np.s_[:, 3:],
        "sharex": None,
        "sharey": None,
        "letter_loc": (letter_x, letter_y + (1 - letter_y) / 2),
        "include_letter": True
    }, {
        "name": "sterilized-freq",
        "grid_position": np.s_[1, 0],
        "sharex": "sterilized-abs",
        "sharey": None,
        "include_letter": False
    }, {
        "name": "replication-selected-freq",
        "grid_position": np.s_[1, 1],
        "sharex": "sterilized-abs",
        "sharey": "sterilized-freq",
        "include_letter": False
    }, {
        "name": "inoculation-selected-freq",
        "grid_position": np.s_[1, 2],
        "sharex": "sterilized-abs",
        "sharey": "sterilized-freq",
        "include_letter": False
    }]

    plots = pf.setup_multipanel(fig,
                                plot_positions,
                                gridspec=gs,
                                letter_loc=(letter_x, letter_y))

    plots['all-plots'] = all_plots
    plots['all-timecourses'] = all_timecourses

    fig.tight_layout()
    return (fig, plots)
def main(param_file=None, output_path=None):

    ## figure styling / setup
    width = 18.3
    mpl.rcParams['font.size'] = width / 1.5
    mpl.rcParams['lines.linewidth'] = width / 2.5
    kernel_lw = width / 4.5
    mpl.rcParams['ytick.major.pad'] = width / 2
    mpl.rcParams['xtick.major.pad'] = width / 2
    mpl.rcParams['legend.fontsize'] = width * 0.9
    mpl.rcParams['legend.title_fontsize'] = width
    mpl.rcParams['legend.handlelength'] = 2

    height = width / 3
    fig = plt.figure(figsize=(width, height))

    nrows = 1
    ncols = 3
    gs = gridspec.GridSpec(nrows, ncols)

    ## multipanel setup
    pop_row = 0
    e_rate_col, reinoc_col, epi_escape_col = 0, 1, 2

    plot_positions = [{
        "name": "emergence-rate",
        "grid_position": np.s_[pop_row, e_rate_col],
        "sharex": None,
        "sharey": None
    }, {
        "name": "reinoculations",
        "grid_position": np.s_[pop_row, reinoc_col],
        "sharex": None,
        "sharey": None
    }, {
        "name": "epi-escape",
        "grid_position": np.s_[pop_row, epi_escape_col],
        "sharex": None,
        "sharey": None
    }]

    letter_loc = (-0.1, 1.15)
    plots = setup_multipanel(fig,
                             plot_positions,
                             letter_loc=letter_loc,
                             gridspec=gs)

    ## parametrization
    params = pp.get_params(param_file)
    b = int(params.get("DEFAULT_BOTTLENECK"))
    v = int(float(params.get("DEFAULT_VB_RATIO")) * b)
    f_mut = float(params.get("DEFAULT_F_MUT"))
    z_wt = float(params.get("DEFAULT_Z_WT"))
    k = float(params.get("CONSTANT_CHAIN_K"))
    mu = float(params.get("DEFAULT_MU"))
    d_v = float(params.get("DEFAULT_D_V"))
    R0 = float(params.get("DEFAULT_R0_WH"))

    v_mult = 5
    epi_sigma = 0.75
    escape = 1

    print("parsed parameter file: v = {}, b = {}".format(v, b))
    print("parsed parameter file: f_mut = {}".format(f_mut))
    print("parsed parameter file: z_wt = {}".format(z_wt))

    pop_R0s = [1.5, 2, 2.5]
    print("Plotting reinoculations vs population immunity...")
    plot_reinoculations(axis=plots["reinoculations"],
                        R0s=pop_R0s,
                        cmap=plt.cm.Greens,
                        leg_cmap=plt.cm.Greys)

    print("Plotting new chains vs population immunity...")
    plot_epidemic_p_inocs(axis=plots["epi-escape"],
                          f_mut=f_mut,
                          bottleneck=b,
                          cross_imm_sigma=epi_sigma,
                          v=v,
                          population_R0s=pop_R0s,
                          escape=escape,
                          leg_cmap=plt.cm.Greys,
                          z_wt=z_wt,
                          legend=True)

    print("Plotting new chains vs population immunity with v = {}..."
          "".format(v * v_mult))

    plot_epidemic_p_inocs(axis=plots["epi-escape"],
                          cross_imm_sigma=epi_sigma,
                          f_mut=f_mut,
                          bottleneck=b,
                          v=v * v_mult,
                          population_R0s=pop_R0s,
                          cmap=plt.cm.Purples,
                          linestyle='dotted',
                          escape=escape,
                          z_wt=z_wt,
                          legend=False)

    print("Plotting emergence vs population immunity...")
    mut_neut_prob_list = [0.75, 0.9, 0.99]

    plot_inoculation_selection_vs_immunity(axis=plots["emergence-rate"],
                                           f_mut=f_mut,
                                           mut_neut_probs=mut_neut_prob_list,
                                           wt_neut_prob=neutralize_prob_from_z(
                                               z_wt, v, "poisson"),
                                           final_bottleneck=b,
                                           mucus_bottleneck=v,
                                           cmap=plt.cm.Reds,
                                           linestyle="solid",
                                           legend=True,
                                           leg_cmap=plt.cm.Greys,
                                           inoculum_model="poisson",
                                           bottleneck_model="binomial")

    plot_inoculation_selection_vs_immunity(axis=plots["emergence-rate"],
                                           f_mut=f_mut,
                                           mut_neut_probs=mut_neut_prob_list,
                                           wt_neut_prob=neutralize_prob_from_z(
                                               z_wt, v * v_mult, "poisson"),
                                           final_bottleneck=b,
                                           mucus_bottleneck=v * v_mult,
                                           cmap=plt.cm.Purples,
                                           linestyle="dotted",
                                           legend=False,
                                           inoculum_model="poisson",
                                           bottleneck_model="binomial")

    #####################################
    # plot styling
    #####################################
    imm_level_text = "population fraction immune\nto wild-type"
    emergence_y_text = "new variant infections\nper inoculation"
    frac_ticks = [0, 0.25, 0.5, 0.75, 1]
    frac_tick_labs = ["$0$", "$0.25$", "$0.5$", "$0.75$", "$1$"]

    plots["reinoculations"].set_xlabel(imm_level_text)
    plots["reinoculations"].set_ylabel("per capita reinoculations")
    plots["epi-escape"].set_xlabel(imm_level_text)
    plots["epi-escape"].set_ylabel("per capita probability\n"
                                   "of new variant infection")
    plots["emergence-rate"].set_xlabel(imm_level_text)
    plots["emergence-rate"].set_ylabel(emergence_y_text)
    plots["epi-escape"].set_ylim([0, 3e-4])

    for plot in plots.values():
        plot.set_xlim(left=0, right=1)
        plot.set_ylim(bottom=0)
        plot.set_xticks(frac_ticks)
        plot.set_xticklabels(frac_tick_labs)

    for plot in plots.values():
        if not type(plot.yaxis._scale) == mpl.scale.LogScale:
            plot.set_ylim(bottom=0)

    plt.tight_layout()

    # save
    fig.savefig(output_path)

    return 0
Example #7
0
def main(output_path=None,
         fixed_results_dir=None,
         var_results_dir=None,
         gen_param_file=None,
         empirical_data_file=None,
         bottleneck=1,
         heatmap_bottleneck=1,
         increment=0.05):

    if fixed_results_dir is None:
        fixed_results_dir = "../../out/within_host_results/minimal_visible"
    if var_results_dir is None:
        var_results_dir = "../../out/within_host_results/minimal_visvar"
    if output_path is None:
        output_path = "../../ms/main/figures/figure-wh-dynamics-summary.pdf"
    if gen_param_file is None:
        gen_param_file = "../../dat/RunParameters.mk"

    if empirical_data_file is None:
        empirical_data_file = "../../dat/cleaned/cleaned_wh_data.csv"

    aspect = .9
    width = 18.3
    height = width * aspect

    lineweight = width / 2.5
    mpl.rcParams['lines.linewidth'] = lineweight
    mpl.rcParams['font.size'] = width
    mpl.rcParams['legend.fontsize'] = "small"

    non_trans_alpha = 0.4

    params = pp.get_params(gen_param_file)
    detection_threshold = float(params["DEFAULT_DETECTION_THRESHOLD"])
    detection_limit = float(params["DEFAULT_DETECTION_LIMIT"])
    td_50 = float(params["DEFAULT_TD50"])
    transmission_cutoff = float(params["DEFAULT_TRANS_CUTOFF"])

    transmission_threshold = (-td_50 * np.log(1 - transmission_cutoff) /
                              np.log(2))

    print(transmission_threshold)

    R0_wh = pp.get_param("R0_wh", "minimal_visvar", params)
    C_max = pp.get_param("C_max", "minimal_visvar", params)
    r_w = pp.get_param("r_w", "minimal_visvar", params)
    r_m = pp.get_param("r_m", "minimal_visvar", params)
    mu = pp.get_param("mu", "minimal_visvar", params)
    d_v = pp.get_param("d_v", "minimal_visvar", params)
    t_M = pp.get_param("t_M", "minimal_visvar", params)
    t_N = pp.get_param("t_N", "minimal_visvar", params)

    max_k = 8
    max_t_M = 3.5
    heatmap_t_final = 3

    # set up multi-panel figure
    fig = plt.figure(figsize=(width, height))

    n_cols = 4
    n_rows = 2
    height_ratios = [2, 3.5]
    ly2_inc = 0.07
    ly1 = 1 + 3 * ly2_inc / 2
    ly2 = 1 + ly2_inc
    lx = -0.05
    row_1_loc = (lx, ly1)
    row_2_loc = (lx, ly2)

    gs = gridspec.GridSpec(n_rows, n_cols, height_ratios=height_ratios)
    all_heatmaps = add_bounding_subplot(fig, position=gs[0, 2:])

    all_plots = add_bounding_subplot(fig, position=gs[:, :])
    all_timecourses = add_bounding_subplot(fig, position=gs[1, :])

    plot_positions = [{
        "name": "empirical-detect",
        "grid_position": np.s_[0, 0],
        "sharex": None,
        "sharey": None,
        "letter_loc": row_1_loc
    }, {
        "name": "empirical-hist",
        "grid_position": np.s_[0, 1],
        "sharex": None,
        "sharey": None,
        "letter_loc": row_1_loc
    }, {
        "name": "one-percent-heatmap",
        "grid_position": np.s_[0, 2],
        "sharex": None,
        "sharey": None,
        "letter_loc": row_1_loc
    }, {
        "name": "consensus-heatmap",
        "grid_position": np.s_[0, 3],
        "sharex": "one-percent-heatmap",
        "sharey": "one-percent-heatmap",
        "letter_loc": row_1_loc
    }, {
        "name": "naive",
        "grid_position": np.s_[1, 0],
        "sharex": None,
        "sharey": None,
        "letter_loc": row_2_loc
    }, {
        "name": "fixed",
        "grid_position": np.s_[1, 1],
        "sharex": None,
        "sharey": None,
        "letter_loc": row_2_loc
    }, {
        "name": "var",
        "grid_position": np.s_[1, 2],
        "sharex": None,
        "sharey": None,
        "letter_loc": row_2_loc
    }, {
        "name": "inoc",
        "grid_position": np.s_[1, 3],
        "sharex": None,
        "sharey": None,
        "letter_loc": row_2_loc
    }]

    plots = setup_multipanel(fig, plot_positions, gridspec=gs)
    fig.tight_layout(rect=(0, 0.1, 1, 1), w_pad=-0.5)

    for timecourse in ['naive', 'fixed', 'var', 'inoc']:
        inner = gridspec.GridSpecFromSubplotSpec(
            2, 1, hspace=0.15, subplot_spec=plots[timecourse])
        plots[timecourse + '-abs'] = plt.Subplot(fig, inner[0])
        plots[timecourse + '-freq'] = plt.Subplot(
            fig,
            inner[1],
            sharex=plots.get('naive-freq', None),
            sharey=plots.get('naive-freq', None))
        fig.add_subplot(plots[timecourse + '-abs'])
        fig.add_subplot(plots[timecourse + '-freq'])
        ax = plots[timecourse]
        ax.spines['top'].set_color('none')
        ax.spines['bottom'].set_color('none')
        ax.spines['left'].set_color('none')
        ax.spines['right'].set_color('none')
        ax.grid(b=False)
        ax.patch.set_alpha(0)
        ax.tick_params(labelcolor='w',
                       grid_alpha=0,
                       top=False,
                       bottom=False,
                       left=False,
                       right=False)
        ax.set_zorder(0)

    wt_col = "Vw"
    mut_col = "Vm"
    cell_col = "C"
    col_colors = [ps.wt_color, ps.mut_color, ps.cell_color]
    detection_linestyle = "dashed"
    detection_color = "black"

    empirical_data = pd.read_csv(empirical_data_file)
    plot_wh_ngs(empirical_data,
                axis=plots['empirical-detect'],
                min_freq=0.01,
                legend=True,
                edgecolor="k")

    plot_ngs_hist(empirical_data,
                  axis=plots['empirical-hist'],
                  min_freq=0,
                  legend=True)

    sims_to_plot = {
        "naive": {
            "results-dir": var_results_dir,
            "timecourse": "naive",
            "activation-time": t_N,
            "E_w": False
        },
        "fixed": {
            "results-dir": fixed_results_dir,
            "timecourse": "repl_visible",
            "activation-time": 0,
            "E_w": True
        },
        "var": {
            "results-dir": var_results_dir,
            "timecourse": "repl_visible",
            "activation-time": t_M,
            "E_w": True
        },
        "inoc": {
            "results-dir": var_results_dir,
            "timecourse": "inoc_visible",
            "activation-time": t_M,
            "E_w": True
        }
    }

    for sim_type, metadata in sims_to_plot.items():
        for plot_freq, text in zip([False, True], ["abs", "freq"]):
            plot_axis_name = "{}-{}".format(sim_type, text)
            plot_axis = plots[plot_axis_name]
            plot_wh_timecourse(metadata["timecourse"],
                               bottleneck,
                               metadata["results-dir"],
                               wt_col,
                               mut_col,
                               col_colors=col_colors,
                               cell_col=cell_col,
                               detection_threshold=detection_threshold,
                               detection_color=detection_color,
                               detection_limit=detection_limit,
                               detection_linestyle=detection_linestyle,
                               transmission_threshold=transmission_threshold,
                               axis=plot_axis,
                               t_M=metadata["activation-time"],
                               E_w=metadata["E_w"],
                               gen_param_file=gen_param_file,
                               non_trans_alpha=non_trans_alpha,
                               frequencies=plot_freq,
                               analytical_frequencies=True)
            plot_axis.set_xlim([0, 8])
            plot_axis.set_xticks([0, 2, 4, 6, 8])
            if plot_freq:
                plot_axis.set_ylim([1e-6, 2])

            ## remove inner labels
            if "naive" not in plot_axis_name:
                for label in plot_axis.get_yticklabels():
                    label.set_visible(False)
            if "abs" in plot_axis_name:
                for label in plot_axis.get_xticklabels():
                    label.set_visible(False)

    R0_wh = pp.get_param("R0_wh", "minimal_visvar", params)
    d_v = pp.get_param("d_v", "minimal_visvar", params)

    min_prob = plot_heatmap(axis=plots["consensus-heatmap"],
                            contour_linewidth=(width / 3) * 0.5,
                            contour_fontsize="large",
                            increment=increment,
                            mu=mu,
                            f_target=0.5,
                            t_final=heatmap_t_final,
                            max_t_M=max_t_M,
                            max_k=max_k,
                            R0=R0_wh,
                            c_w=1,
                            c_m=0,
                            d_v=d_v,
                            bottleneck=heatmap_bottleneck,
                            contour_levels=[1e-5, 1e-3, 1e-1],
                            cbar=True)

    plot_heatmap(axis=plots["one-percent-heatmap"],
                 contour_linewidth=(width / 3) * 0.5,
                 contour_fontsize="large",
                 increment=increment,
                 mu=mu,
                 bottleneck=heatmap_bottleneck,
                 f_target=0.01,
                 min_prob=min_prob,
                 t_final=heatmap_t_final,
                 R0=R0_wh,
                 d_v=d_v,
                 c_w=1,
                 c_m=0,
                 max_t_M=max_t_M,
                 max_k=max_k,
                 contour_levels=[1e-3, 1e-2, 1e-1],
                 cbar=False)

    star_size = 20
    star_marker = '*'
    star_facecolor = 'white'
    star_edgecolor = 'black'
    star_edgewidth = 1.5

    plots['empirical-detect'].set_ylabel('number of infections')
    plots['empirical-detect'].set_title('observed HA\npolymorphism')
    plots['empirical-hist'].set_title('variant within-host\nfrequencies')
    plots['empirical-hist'].set_xlabel('variant frequency')
    plots['empirical-hist'].set_ylabel('number of variants')

    for heatmap_name in ['consensus-heatmap', 'one-percent-heatmap']:
        hm = plots[heatmap_name]
        escape = 0.25
        star_x = 2.5
        sterilizing_k = (R0_wh - 1) * d_v
        fitness_diff = sterilizing_k * escape
        star_y = fitness_diff
        hm.plot(star_x,
                star_y,
                marker=star_marker,
                markersize=star_size,
                markerfacecolor=star_facecolor,
                markeredgewidth=star_edgewidth,
                markeredgecolor=star_edgecolor)
        hm.set_xlabel("")
        hm.grid(b=False)
        hm.set_yticks(np.arange(0, 8.5, 2))
        hm.set_xticks(np.arange(0, 3.5, 1))

        hm.set_xlabel("")

        ## need to reintroduce labels because
        ## axis sharing turns them off
        hm.xaxis.set_tick_params(labelbottom=True)

    ## need to reintroduce labels because
    ## axis sharing turns them off
    plots['one-percent-heatmap'].yaxis.set_tick_params(labelleft=True)

    all_heatmaps.set_xlabel("time of recall response $t_M$ (days)")
    all_heatmaps.set_ylabel('selection strength $\delta$')

    all_timecourses.set_xlabel("time (days)", fontsize="xx-large")
    plots["naive-abs"].set_title("no recall\nresponse")
    plots["fixed-abs"].set_title("constant recall\nresponse")
    plots["var-abs"].set_title("recall response at\n48h")
    plots["inoc-abs"].set_title("response at 48h,\nvariant inoculated")
    plots["consensus-heatmap"].set_title("prob. new variant\n" "at consensus")
    plots["one-percent-heatmap"].set_title("prob. new variant\n" "at 1\%")

    plots["naive-abs"].set_ylabel("virions, cells")
    plots["naive-freq"].set_ylabel("variant frequency")

    plots['empirical-hist'].set_xlim([0, 0.5])

    # create legend
    cells = mlines.Line2D([], [],
                          color=ps.cell_color,
                          lw=lineweight,
                          label='target\ncells')
    wt = mlines.Line2D([], [],
                       color=ps.wt_color,
                       lw=lineweight,
                       label='old variant\nvirus')
    mut = mlines.Line2D([], [],
                        color=ps.mut_color,
                        lw=lineweight,
                        label='new variant\nvirus')
    ngs = mlines.Line2D([], [],
                        color='black',
                        lw=lineweight,
                        linestyle="dashed",
                        label='NGS detection\nlimit')
    analytical = mlines.Line2D([], [],
                               color='black',
                               lw=lineweight,
                               linestyle="dotted",
                               label='analytical new\nvariant frequency')
    antibody = mlines.Line2D([], [],
                             color=ps.immune_active_color,
                             lw=2 * lineweight,
                             alpha=0.25,
                             label='recall response\nactive')
    star_leg = mlines.Line2D([], [],
                             color='white',
                             marker=star_marker,
                             markersize=star_size,
                             markerfacecolor=star_facecolor,
                             markeredgewidth=star_edgewidth,
                             markeredgecolor=star_edgecolor,
                             label="influenza-like\nparameters")

    handles = [cells, wt, mut, antibody, ngs, analytical, star_leg]
    labels = [h.get_label() for h in handles]

    all_timecourses.legend(handles=handles,
                           labels=labels,
                           fontsize='x-large',
                           loc="center",
                           bbox_to_anchor=(0.5, -.3),
                           frameon=False,
                           ncol=int(np.ceil(len(handles) / 2)))

    fig.savefig(output_path)
def setup_figure(n_rows=2, n_cols=3):
    aspect = 0.8
    width = 18.3
    height = width * aspect

    lineweight = width / 2.5
    mpl.rcParams['lines.linewidth'] = lineweight
    mpl.rcParams['font.size'] = width * 0.9
    mpl.rcParams['axes.titlesize'] = 'large'
    mpl.rcParams['axes.titleweight'] = 'bold'

    # set up multi-panel figure
    fig = plt.figure(figsize=(width, height))

    gs = gridspec.GridSpec(n_rows, n_cols)

    all_plots = pf.add_bounding_subplot(fig, position=gs[:, :])

    sensitivity_model_names = ['fixed', 'visvar']

    row_plots = [
        pf.add_bounding_subplot(fig, position=gs[row, :])
        for row in range(n_rows)
    ]

    plot_positions = [{
        "name": "fixed-any-inf",
        "grid_position": np.s_[0, 0],
        "sharex": None,
        "sharey": None
    }, {
        "name": "visvar-any-inf",
        "grid_position": np.s_[1, 0],
        "sharex": "fixed-any-inf",
        "sharey": "fixed-any-inf"
    }, {
        "name": "fixed-mut-inf",
        "grid_position": np.s_[0, 1],
        "sharex": "fixed-any-inf",
        "sharey": None
    }, {
        "name": "visvar-mut-inf",
        "grid_position": np.s_[1, 1],
        "sharex": "fixed-any-inf",
        "sharey": "fixed-mut-inf"
    }, {
        "name": "fixed-mut-inf-per",
        "grid_position": np.s_[0, 2],
        "sharex": "fixed-any-inf",
        "sharey": None
    }, {
        "name": "visvar-mut-inf-per",
        "grid_position": np.s_[1, 2],
        "sharex": "fixed-any-inf",
        "sharey": "fixed-mut-inf-per"
    }]

    plots = pf.setup_multipanel(fig, plot_positions, gridspec=gs)

    for row, name in enumerate(sensitivity_model_names):
        plots[name] = row_plots[row]

    plots['all'] = all_plots

    fig.tight_layout()
    return (fig, plots)
Example #9
0
def setup_figure():
    magnif = 3
    width = magnif * 18.3
    nrows = 3
    ncols = 4
    height = width
    font_mag = 1

    lineweight = width / 3
    mpl.rcParams['lines.linewidth'] = lineweight
    mpl.rcParams['axes.formatter.limits'] = (-3, 6)
    mpl.rcParams['font.size'] *= magnif * font_mag
    mpl.rcParams['ytick.major.pad'] = width / 4
    mpl.rcParams['xtick.major.pad'] = width / 2

    # set up multi-panel figure
    fig = plt.figure(figsize=(width, height))
    gs = gridspec.GridSpec(nrows, ncols)

    schematic_row, inoc_dist_row, selectors_row = 0, 1, 2

    prefilter_col, postfilter_col, mut_inf_col = 0, 1, 2

    virion_survival_col, cutdown_col, sus_mod_col, opt_sel_col = 0, 1, 2, 3

    plot_positions = [{
        "name": "bottleneck-schematic",
        "grid_position": np.s_[schematic_row, :],
        "letter_loc": (-0.0125, 1.1),
        "sharex": None,
        "sharey": None
    }, {
        "name":
        "virion-survival",
        "grid_position":
        np.s_[selectors_row, virion_survival_col],
        "sharex":
        None,
        "sharey":
        None
    }, {
        "name": "cutdown",
        "grid_position": np.s_[selectors_row, cutdown_col],
        "sharex": None,
        "sharey": None
    }, {
        "name": "susceptibility-models",
        "grid_position": np.s_[selectors_row, sus_mod_col],
        "sharex": None,
        "sharey": None
    }, {
        "name": "optimal-selectors",
        "grid_position": np.s_[selectors_row, opt_sel_col],
        "sharex": "susceptibility-models",
        "sharey": None
    }]

    plots = setup_multipanel(fig,
                             plot_positions,
                             gridspec=gs,
                             verbose=True,
                             letters=['a', 'e', 'f', 'g', 'h', 'i'])

    distrow = gs[inoc_dist_row, :]
    inner_gs = gridspec.GridSpecFromSubplotSpec(1, 3, subplot_spec=distrow)
    plots['all_dists'] = add_bounding_subplot(fig, position=distrow)

    letters = ['B', 'C', 'D']
    for idist, dist in enumerate(
        ['pre-filter', 'post-filter', 'mutant-creator']):
        plotname = dist + '-dist'
        plots[plotname] = fig.add_subplot(
            inner_gs[idist],
            sharex=plots.get('pre-filter-dist', None),
            sharey=plots.get('pre-filter-dist', None))
        letter_x, letter_y = ps.letter_loc
        plots[plotname].text(letter_x,
                             letter_y,
                             letters[idist],
                             transform=plots[plotname].transAxes,
                             fontsize=ps.letter_size,
                             fontweight='bold',
                             va='top')

    return (fig, plots)