示例#1
0
def demand_curves(ranking_provider,
                  vax_policy,
                  phis=[25, 50, 100, 200],
                  phi_benchmark=25,
                  N_state=N_TN):
    wtp_rankings = {phi: ranking_provider(phi, vax_policy) for phi in phis}

    figure = plt.figure()
    lines = []

    # benchmark
    benchmark = wtp_rankings[phi_benchmark]
    x_pop = list(
        chain(*zip(benchmark.loc[0]["num_vax"].shift(1).fillna(0),
                   benchmark.loc[0]["num_vax"])))
    y_wtp = list(
        chain(*zip(benchmark.loc[0]["wtp_pc_usd"], benchmark.loc[0]
                   ["wtp_pc_usd"])))
    lines.append(
        plt.plot(x_pop, y_wtp, figure=figure, color="black", linewidth=2)[0])
    lines.append(plt.plot(0, 0, color="white")[0])

    # plot dynamic curve
    for (phi, all_wtp) in wtp_rankings.items():
        daily_doses = phi * percent * annually * N_state
        distributed_doses = 0
        x_pop = []
        y_wtp = []
        t_vax = []
        ranking = 0
        for t in range(simulation_range):
            wtp = all_wtp.loc[t].reset_index()
            ranking = wtp[(wtp.index >= ranking)
                          & (wtp.num_vax > distributed_doses)].index.min()
            if np.isnan(ranking):
                break
            x_pop += [distributed_doses, distributed_doses + daily_doses]
            t_vax += [t, t + 1]
            y_wtp += [wtp.iloc[ranking].wtp_pc_usd] * 2
            distributed_doses += daily_doses
        lines.append(
            plt.plot(x_pop,
                     y_wtp,
                     label=f"dynamic, {vax_policy}, $\phi = ${phi}%",
                     figure=figure)[0])
    plt.legend(lines, [f"static, t = 0, $\phi = ${phi_benchmark}%", ""] +
               [f"dynamic, {vax_policy}, $\phi = ${phi}%" for phi in phis],
               title="allocation",
               title_fontsize="24",
               fontsize="20")
    plt.xticks(fontsize="20")
    plt.yticks(fontsize="20")
    plt.PlotDevice().ylabel("WTP (USD)\n").xlabel("\nnumber vaccinated")
    plt.ylim(0, 350)
    plt.xlim(left=0, right=N_TN)
    plt.show()
示例#2
0
def plot_district_age_distribution(percentiles,
                                   ylabel,
                                   fmt,
                                   phi=50,
                                   vax_policy="random",
                                   N_jk=None,
                                   n=5,
                                   district_spacing=1.5,
                                   age_spacing=0.1,
                                   rotation=0):
    fig = plt.figure()
    district_ordering = list(districts_to_run.index)[:n]
    for (i, district) in enumerate(district_ordering):
        ylls = percentiles[district, phi, vax_policy]
        for j in range(7):
            plt.errorbar(x=[district_spacing * i + age_spacing * (j - 3)],
                         y=ylls[1, 6 - j] * USD /
                         (N_jk[f"N_{6-j}"][district] if N_jk else 1),
                         yerr=[[(ylls[1, 6 - j] - ylls[0, 6 - j]) * USD /
                                (N_jk[f"N_{6-j}"][district] if N_jk else 1)],
                               [(ylls[2, 6 - j] - ylls[1, 6 - j]) * USD /
                                (N_jk[f"N_{6-j}"][district] if N_jk else 1)]],
                         fmt=fmt,
                         color=age_group_colors[6 - j],
                         figure=fig,
                         label=None if i > 0 else age_bin_labels[6 - j],
                         ms=12,
                         elinewidth=5)
    plt.xticks([1.5 * _ for _ in range(n)],
               district_ordering,
               rotation=rotation,
               fontsize="20")
    plt.yticks(fontsize="20")
    plt.legend(title="age bin",
               title_fontsize="20",
               fontsize="20",
               ncol=7,
               loc="lower center",
               bbox_to_anchor=(0.5, 1))
    ymin, ymax = plt.ylim()
    plt.vlines(x=[0.75 + 1.5 * _ for _ in range(n - 1)],
               ymin=ymin,
               ymax=ymax,
               color="gray",
               alpha=0.5,
               linewidths=2)
    plt.ylim(ymin, ymax)
    plt.gca().grid(False, axis="x")
    plt.PlotDevice().title(f"\n{vax_policy} demand curves").ylabel(
        f"{ylabel}\n")
示例#3
0
def plot_state_age_distribution(percentiles,
                                ylabel,
                                fmt,
                                district_spacing=1.5,
                                n=5,
                                age_spacing=0.1,
                                rotation=0,
                                ymin=0,
                                ymax=1000):
    fig = plt.figure()
    state_ordering = list(
        sorted(percentiles.keys(),
               key=lambda k: percentiles[k][0].max(),
               reverse=True))
    for (i, state) in enumerate(state_ordering[:n]):
        ylls = percentiles[state]
        for j in range(7):
            plt.errorbar(x=[district_spacing * i + age_spacing * (j - 3)],
                         y=ylls[0, 6 - j],
                         yerr=[[(ylls[0, 6 - j] - ylls[1, 6 - j])],
                               [(ylls[2, 6 - j] - ylls[0, 6 - j])]],
                         fmt=fmt,
                         color=agebin_colors[6 - j],
                         figure=fig,
                         label=None if i > 0 else agebin_labels[6 - j],
                         ms=12,
                         elinewidth=5)
    plt.xticks([1.5 * _ for _ in range(n)],
               state_ordering,
               rotation=rotation,
               fontsize="20")
    plt.yticks(fontsize="20")
    # plt.legend(title = "age bin", title_fontsize = "20", fontsize = "20", ncol = 7,
    plt.legend(fontsize="20",
               ncol=7,
               loc="lower center",
               bbox_to_anchor=(0.5, 1))
    plt.vlines(x=[0.75 + 1.5 * _ for _ in range(n - 1)],
               ymin=ymin,
               ymax=ymax,
               color="gray",
               alpha=0.5,
               linewidths=4)
    plt.ylim(ymin, ymax)
    plt.gca().grid(False, axis="x")
    plt.PlotDevice().ylabel(f"{ylabel}\n")
示例#4
0
def plot_component_breakdowns(color,
                              white,
                              colorlabel,
                              whitelabel,
                              semilogy=False,
                              ylabel="WTP (USD)"):
    fig, ax = plt.subplots()
    ax.bar(range(7),
           white * USD,
           bottom=color * USD,
           color="white",
           edgecolor=age_group_colors,
           linewidth=2,
           figure=fig)
    ax.bar(range(7),
           color * USD,
           color=age_group_colors,
           edgecolor=age_group_colors,
           linewidth=2,
           figure=fig)
    ax.bar(range(7), [0],
           label=whitelabel,
           color="white",
           edgecolor="black",
           linewidth=2)
    ax.bar(range(7), [0],
           label=colorlabel,
           color="black",
           edgecolor="black",
           linewidth=2)

    plt.xticks(range(7), age_bin_labels, fontsize="20")
    plt.yticks(fontsize="20")
    plt.legend(ncol=4,
               fontsize="20",
               loc="lower center",
               bbox_to_anchor=(0.5, 1))
    plt.PlotDevice().ylabel(f"{ylabel}\n")
    if semilogy: plt.semilogy()
示例#5
0
def outcomes_per_policy(percentiles,
                        metric_label,
                        fmt,
                        phis=[25, 50, 100, 200],
                        reference=(25, "no_vax"),
                        reference_color=no_vax_color,
                        vax_policies=["contact", "random", "mortality"],
                        policy_colors=[
                            contactrate_vax_color, random_vax_color,
                            mortality_vax_color
                        ],
                        policy_labels=[
                            "contact rate priority", "random assignment",
                            "mortality priority"
                        ],
                        spacing=0.2):
    fig = plt.figure()

    md, lo, hi = percentiles[reference]
    *_, bars = plt.errorbar(x=[0],
                            y=[md],
                            yerr=[[md - lo], [hi - md]],
                            figure=fig,
                            fmt=fmt,
                            color=reference_color,
                            label="no vaccination",
                            ms=12,
                            elinewidth=5)
    [_.set_alpha(0.5) for _ in bars]
    plt.hlines(md,
               xmin=-1,
               xmax=5,
               linestyles="dotted",
               colors=reference_color)

    for (i, phi) in enumerate(phis, start=1):
        for (j, (vax_policy, color, label)) in enumerate(
                zip(vax_policies, policy_colors, policy_labels)):
            md, lo, hi = death_percentiles[phi, vax_policy]
            *_, bars = plt.errorbar(x=[i + spacing * (j - 1)],
                                    y=[md],
                                    yerr=[[md - lo], [hi - md]],
                                    figure=fig,
                                    fmt=fmt,
                                    color=color,
                                    label=label if i == 0 else None,
                                    ms=12,
                                    elinewidth=5)
            [_.set_alpha(0.5) for _ in bars]

    plt.legend(ncol=4,
               fontsize="20",
               loc="lower center",
               bbox_to_anchor=(0.5, 1))
    plt.xticks(range(len(phis) + 1),
               [f"$\phi = {phi}$%" for phi in ([0] + phis)],
               fontsize="20")
    plt.yticks(fontsize="20")
    plt.PlotDevice().ylabel(f"{metric_label}\n")
    plt.gca().grid(False, axis="x")
    ymin, ymax = plt.ylim()
    plt.vlines(x=[0.5 + _ for _ in range(len(phis))],
               ymin=ymin,
               ymax=ymax,
               color="gray",
               alpha=0.5,
               linewidths=2)
    plt.ylim(ymin, ymax)
    plt.xlim(-0.5, len(phis) + 1.5)
示例#6
0
                         dT_conf_scaled_TT[idx] / N_TT,
                         color=IN_color,
                         label="India (raw)",
                         figure=fig,
                         alpha=0.5,
                         marker="o",
                         s=10,
                         zorder=10)
plot_TT, = plt.plot(idx,
                    dT_conf_scaled_smooth_TT[idx] / N_TT,
                    color=IN_color,
                    label="India (smoothed)",
                    figure=fig,
                    zorder=10,
                    linewidth=2)
plt.xticks(fontsize="20", rotation=0)
plt.yticks(fontsize="20")
plt.legend([scatter_TN, plot_TN, scatter_TT, plot_TT], [
    "Tamil Nadu (raw)", "Tamil Nadu (smoothed)", "India (raw)",
    "India (smoothed)"
],
           fontsize="20",
           ncol=4,
           framealpha=1,
           handlelength=0.75,
           loc="lower center",
           bbox_to_anchor=(0.5, 1))
plt.gca().xaxis.set_major_formatter(plt.bY_FMT)
plt.gca().xaxis.set_minor_formatter(plt.bY_FMT)
plt.xlim(left=pd.Timestamp("March 1, 2020"),
         right=pd.Timestamp("April 15, 2021"))
示例#7
0
        *_, bars = plt.errorbar(
            x=[i],
            y=[md],
            yerr=[[md - lo], [hi - md]],
            figure=fig,
            fmt="o",
            color=clr,
            label=None if i > 0 else [
                "contact rate prioritized", "random assignment",
                "mortality prioritized"
            ][dx],
            ms=12,
            elinewidth=5)
        [_.set_alpha(0.5) for _ in bars]
plt.xticks(
    range(len(metrics)),
    [f"{phi}%" for phi in (100 * (10**np.linspace(-1, 1, 11))).round(0)],
    fontsize="20")
plt.yticks(fontsize="20")
plt.PlotDevice().ylabel("deaths\n").xlabel(
    "\npercentage of population vaccinated annually")
# plt.ylim(200, 450)
plt.legend(fontsize="20")
plt.show()

# evaluated_YLL_percentiles = {k: np.percentile(v, [5, 50, 95]) for (k, v) in evaluated_YLLs.items() if "ve70" in k or "novaccination" in k}
# contact_percentiles   = {k: v for (k, v) in evaluated_YLL_percentiles.items() if "contact"   in k}
# random_percentiles    = {k: v for (k, v) in evaluated_YLL_percentiles.items() if "random"    in k}
# mortality_percentiles = {k: v for (k, v) in evaluated_YLL_percentiles.items() if "mortality" in k}
# novax_percentiles     = {k: v for (k, v) in evaluated_YLL_percentiles.items() if "novacc"    in k}

# fig = plt.figure()
示例#8
0
        N_natl = districts_to_run.N_tot.sum()
        figure = plt.figure()
        x_pop = list(
            chain(*zip(
                all_tev_50.loc[0]["num_vax"].shift(1).fillna(0) * 100 /
                N_natl, all_tev_50.loc[0]["num_vax"] * 100 / N_natl)))
        y_tev = list(
            chain(*zip(all_tev_50.loc[0]["pc_tev_usd"], all_tev_50.loc[0]
                       ["pc_tev_usd"])))
        static, = plt.plot(x_pop,
                           y_tev,
                           figure=figure,
                           color="grey",
                           linewidth=2)
        lines = [static]
        plt.xticks(fontsize="20")
        plt.yticks(fontsize="20")
        plt.PlotDevice().ylabel("TEV (USD)\n").xlabel(
            "\npercentage of country vaccinated")
        # plt.ylim(0, 1600)
        # plt.xlim(left = 0, right = 100)

        lines.append(plt.plot(0, 0, color="white")[0])

        # plot dynamic curve
        phis = [25, 50, 100, 200]
        for (phi, all_tev) in zip(
                phis, [all_tev_25, all_tev_50, all_tev_100, all_tev_200]):
            daily_doses = phi * percent * annually * N_natl
            distributed_doses = 0
            x_pop = []
示例#9
0
            x=[i + 0.2 * (dx - 1)],
            y=[md],
            yerr=[[md - lo], [hi - md]],
            figure=fig,
            fmt="o",
            color=clr,
            label=None if i > 0 else [
                "contact rate prioritized", "random assignment",
                "mortality prioritized"
            ][dx],
            ms=12,
            elinewidth=5)
        [_.set_alpha(0.5) for _ in bars]

plt.xticks(list(range(-1, len(metrics))),
           [f"$\phi = {phi}$%" for phi in [0, 25, 50, 75, 100, 200, 400]],
           fontsize="20")
plt.yticks(fontsize="20")
plt.PlotDevice().ylabel("\ndeaths")
plt.legend(fontsize="20", ncol=4, loc="lower center", bbox_to_anchor=(0.5, 1))
plt.show()

evaluated_YLL_percentiles = {
    k: np.percentile(v, [5, 50, 95])
    for (k, v) in evaluated_YLLs.items() if "ve70" in k or "novaccination" in k
}
contact_percentiles = {
    k: v
    for (k, v) in evaluated_YLL_percentiles.items() if "contact" in k
}
random_percentiles = {
示例#10
0
PrD.plot()
plt.legend(title="Age category",
           title_fontsize=18,
           fontsize=16,
           framealpha=1,
           handlelength=1)
plt.xlim(right=pd.Timestamp("Jan 01, 2022"))
plt.PlotDevice()\
    .xlabel("\nDate")\
    .ylabel("Probability\n")
plt.subplots_adjust(left=0.12, bottom=0.12, right=0.94, top=0.96)
plt.gca().xaxis.set_minor_locator(mpl.ticker.NullLocator())
plt.gca().xaxis.set_minor_formatter(mpl.ticker.NullFormatter())
plt.gca().xaxis.set_major_locator(mdates.AutoDateLocator())
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))
plt.xticks(fontsize="16")
plt.yticks(fontsize="16")
plt.gca().xaxis.grid(True, which="major")
plt.semilogy()
plt.ylim(bottom=1e-7)
plt.show()

PrD = pd.DataFrame(prob_death).set_index(
    pd.date_range(start=simulation_start, freq="D", periods=len(prob_death)))
plt.plot(PrD, color=TN_color, linewidth=2, label="probability of death")
plt.xlim(left=pd.Timestamp("Jan 01, 2021"), right=pd.Timestamp("Jan 01, 2022"))
plt.PlotDevice().ylabel("log-probability\n")
# plt.subplots_adjust(left = 0.12, bottom = 0.12, right = 0.94, top = 0.96)
plt.gca().xaxis.set_minor_locator(mpl.ticker.NullLocator())
plt.gca().xaxis.set_minor_formatter(mpl.ticker.NullFormatter())
plt.gca().xaxis.set_major_locator(mdates.AutoDateLocator())