コード例 #1
0
        label=[
            "random assignment", "contact rate prioritized",
            "mortality prioritized"
        ][i])
(ticks, _) = plt.xticks()
tags = [_.split("_")[1:-2] for _ in metric_percentiles.keys()]
plt.xticks(ticks,
           labels=[""] + [
               v.replace("ve", "$v_e = $") + "\n" +
               p.replace("annualgoal", "$\phi = $") for (v, p) in tags
           ],
           rotation=0)
plt.legend(ncol=3,
           title_fontsize=18,
           fontsize=16,
           framealpha=1,
           handlelength=1,
           bbox_to_anchor=(1.0090, 1),
           loc="lower right")
plt.PlotDevice().ylabel("deaths\n")
plt.xticks(fontsize="16")
plt.yticks(fontsize="16")
plt.grid(False, which="both", axis="x")
ylims = plt.ylim()  #(800, 1150)
plt.vlines([-0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5], ymin=ylims[0], ymax=ylims[1])
plt.xlim(left=-0.5, right=5.5)
plt.ylim(*ylims)
plt.show()

# # plot YLLs
evaluated_YLL_percentiles = {
コード例 #2
0
(model_idx, selected_model) = min(
    ((i, each)
     for (i, each) in enumerate(models) if each.params["tested"] > 0),
    key=lambda _: _[1].aic)
print("  i aic     r2   beta")
for (i, model) in enumerate(models):
    print("*" if i == model_idx else " ", i + 1, model.aic.round(2),
          model.rsquared.round(2), model.params["tested"].round(2))
scale_factor = selected_model.params["tested"]

plt.plot(0.2093 * df[state][:, "delta", "tested"],
         label="national test-scaled")
plt.plot(scale_factor * df[state][:, "delta", "tested"],
         label="state test-scaled")
plt.plot(df[state][:, "delta", "confirmed"], label="confirmed")
plt.legend()
plt.PlotDevice().title(f"\n{state} / case scaling comparison").xlabel(
    "\ndate").ylabel("cases\n")
plt.show()

# I vs D estimators
gamma = 0.2
window = 7 * days
CI = 0.95
smooth = notched_smoothing(window)

(dates_I, Rt_I, Rtu_I, Rtl_I, *_) = analytical_MPVS(df[state][:, "delta",
                                                              "confirmed"],
                                                    CI=CI,
                                                    smoothing=smooth,
                                                    totals=False)
コード例 #3
0
    n = len(dates)
    plt.plot(dates,
             np.array([_.mean().astype(int) for _ in model.dT][:n]),
             label="mean simulated daily cases",
             color="rebeccapurple")
    plt.fill_between(dates, [_.min().astype(int) for _ in model.dT][:n],
                     [_.max().astype(int) for _ in model.dT][:n],
                     label="simulation range",
                     alpha=0.3,
                     color="rebeccapurple")
    plt.vlines(pd.Timestamp(date),
               1,
               1e6,
               linestyles="dashed",
               label="date of seroprevalence study")
    plt.legend(handlelength=1, framealpha=1)
    plt.semilogy()
    plt.xlim(pd.Timestamp("April 1, 2020"), dates[-1])
    plt.ylim(1, 1e6)
    plt.PlotDevice().xlabel("\ndate").ylabel("new daily cases\n").annotate(
        "Daily Cases: Scaled Data & Simulation - Tamil Nadu, no vaccination")
    plt.show()

    # calculate hazards
    dT = np.array([_.mean().astype(int) for _ in model.dT])
    S = np.array([_.mean().astype(int) for _ in model.S])
    dTx = (dT * sero_breakdown[..., None]).astype(int)
    Sx = (S * COVID_age_ratios[..., None]).astype(int)
    lambda_x = dTx / Sx
    Pr_covid_t = np.zeros(lambda_x.shape)
    Pr_covid_pre_t = np.zeros(lambda_x.shape)
コード例 #4
0
                random_seed=0)

total_t = 0
schedule = [(1.01, 75), (1.4, 75), (0.9, 75)]
R0_timeseries = []
for (R0, t) in schedule:
    R0_timeseries += [R0] * t
    sir_model.Rt0 = R0
    sir_model.run(t)
    total_t += t

plt.plot(sir_model.dT)
plt.show()
plt.plot(R0_timeseries, "-", color="black", label="$R_0$")
plt.plot(sir_model.Rt, "-", color="dodgerblue", label="$R_t$")
plt.legend(framealpha=1, handlelength=1, loc="best")
plt.PlotDevice().xlabel("time").ylabel("reproductive rate").adjust(left=0.10,
                                                                   bottom=0.15,
                                                                   right=0.99,
                                                                   top=0.99)
plt.ylim(0.5, 1.5)
plt.show()

# 1: parametric scheme:
dates, Rt, Rt_lb, Rt_ub, *_, anomalies, anomaly_dates = analytical_MPVS(
    pd.DataFrame(sir_model.dT),
    smoothing=convolution("uniform", 2),
    CI=0.99,
    totals=False)
pd = plt.Rt(dates, Rt, Rt_ub, Rt_lb, ymin = 0.5, ymax = 2.5, CI = 0.99, yaxis_colors = False, format_dates = False, critical_threshold = False)\
    .xlabel("time")\
コード例 #5
0
def plot_mobility(
    series,
    label,
    stringency=None,
    until=None,
    annotation="Google Mobility Data; baseline mobility measured from Jan 3 - Feb 6"
):
    plt.plot(series.date,
             smoothed(
                 series.retail_and_recreation_percent_change_from_baseline),
             label="Retail/Recreation")
    plt.plot(series.date,
             smoothed(
                 series.grocery_and_pharmacy_percent_change_from_baseline),
             label="Grocery/Pharmacy")
    plt.plot(series.date,
             smoothed(series.parks_percent_change_from_baseline),
             label="Parks")
    plt.plot(series.date,
             smoothed(series.transit_stations_percent_change_from_baseline),
             label="Transit Stations")
    plt.plot(series.date,
             smoothed(series.workplaces_percent_change_from_baseline),
             label="Workplaces")
    plt.plot(series.date,
             smoothed(series.residential_percent_change_from_baseline),
             label="Residential")
    if until:
        right = pd.Timestamp(until)
    elif stringency is not None:
        right = stringency.Date.max()
    else:
        right = series.date.iloc[-1]
    lax = plt.gca()
    if stringency is not None:
        plt.sca(lax.twinx())
        stringency_IN = stringency.query("CountryName == 'India'")
        stringency_US = stringency.query(
            "(CountryName == 'United States') & (RegionName.isnull())",
            engine="python")
        plt.plot(stringency_IN.Date,
                 stringency_IN.StringencyIndex,
                 'k--',
                 alpha=0.6,
                 label="IN Measure Stringency")
        plt.plot(stringency_US.Date,
                 stringency_US.StringencyIndex,
                 'k.',
                 alpha=0.6,
                 label="US Measure Stringency")
        plt.PlotDevice().ylabel("lockdown stringency index",
                                rotation=-90,
                                labelpad=50)
        plt.legend()
        plt.sca(lax)
    plt.legend(loc="upper left")
    plt.fill_betweenx((-100, 60),
                      pd.to_datetime("March 24, 2020"),
                      pd.to_datetime("June 1, 2020"),
                      color="black",
                      alpha=0.05,
                      zorder=-1)
    plt.text(s="national lockdown",
             x=pd.to_datetime("April 27, 2020"),
             y=-90,
             fontdict=plt.note_font,
             ha="center",
             va="top")
    plt.PlotDevice()\
        .title(f"\n{label}: Mobility & Lockdown Trends")\
        .annotate(annotation)\
        .xlabel("\ndate")\
        .ylabel("% change in mobility\n")
    plt.ylim(-100, 60)

    plt.xlim(left=series.date.iloc[0], right=right)
コード例 #6
0
         label="Retail/Recreation")
plt.fill_betweenx((-100, 60),
                  pd.to_datetime("March 24, 2020"),
                  pd.to_datetime("June 1, 2020"),
                  color="black",
                  alpha=0.05,
                  zorder=-1)
plt.text(s="national lockdown",
         x=pd.to_datetime("April 27, 2020"),
         y=-20,
         fontdict=plt.note_font,
         ha="center",
         va="top")
plt.ylim(-100, 10)
plt.xlim(series.date.min(), series.date.max())
plt.legend(loc='upper right')
lax = plt.gca()
plt.sca(lax.twinx())
plt.plot(df["TT"][:, "delta", "confirmed"].index,
         smoothed(df["TT"][:, "delta", "confirmed"].values),
         label="Daily Cases",
         color=plt.PRED_PURPLE)
plt.legend(loc='lower right')
plt.PlotDevice().ylabel("new cases", rotation=-90, labelpad=50)
plt.sca(lax)
plt.PlotDevice().title("\nIndia Mobility and Case Count Trends")\
    .annotate("Google Mobility Data + Covid19India.org")\
    .xlabel("\ndate")\
    .ylabel("% change in mobility\n")
plt.show()
コード例 #7
0
all_dT = sum(
    np.pad([np.mean(_) for _ in model.dT[1:]], (0, max_t - len(model.Rt)))
    for model in models.values())

prob_death = dDx / Sx

sns.set_palette(sns.color_palette("hls", 7))
dt = [simulation_start + pd.Timedelta(n, "days") for n in range(max_t - 1)]
PrD = pd.DataFrame(prob_death).T\
    .rename(columns = dict(enumerate(IN_age_structure.keys())))\
    .assign(t = dt)\
    .set_index("t")
PrD.plot()
plt.legend(title="Age category",
           title_fontsize=18,
           fontsize=16,
           framealpha=1,
           handlelength=1)
plt.xlim(right=pd.Timestamp("Feb 01, 2021"))
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()