Пример #1
0
    dT_CI_u = dT + np.sqrt(var_up_school**2 + var_up_nonschool**2)

    return (dT[1:], dT_CI_l[1:], dT_CI_u[1:])


rt1_10x = run_simulation(*models(0, 1.10*school_Rt))
rt1_25x = run_simulation(*models(0, 1.25*school_Rt))
rt1_50x = run_simulation(*models(0, 1.50*school_Rt))

(dates, Rt_pred, Rt_CI_upper, Rt_CI_lower, T_pred, T_CI_upper, T_CI_lower, total_cases, new_cases_ts, anomalies, anomaly_dates)\
    = analytical_MPVS(age_ts.sum(level = 1), CI = CI, smoothing = smoothing, totals = False)

MAK = SIR(name = "MAK", population = 1.339e6, dT0 = T_pred[-1], Rt0 = Rt_pred[-1], upper_CI = T_CI_upper[-1], lower_CI = T_CI_lower[-1], mobility = 0, random_seed = 0, I0 = age_ts.sum(level = 1).sum()).run(30)

plt.daily_cases(dates, T_pred, T_CI_upper, T_CI_lower, new_cases_ts, anomaly_dates, anomalies, CI, 
    prediction_ts = [
        (MAK.dT[:-1], MAK.lower_CI[1:], MAK.upper_CI[1:], plt.PRED_PURPLE, "current social distancing"),
        (*rt1_10x, "orange",         "10% increase in school-age $R_t$"),
        (*rt1_25x, "mediumseagreen", "25% increase in school-age $R_t$"),
        (*rt1_50x, "hotpink",        "50% increase in school-age $R_t$"),
    ])\
    .xlabel("\ndate")\
    .ylabel("cases\n")
    # .title("\nMakassar Daily Cases - school reopening scenarios")\
    # .annotate("\nBayesian training process on empirical data, with anomalies identified")
(_, r) = plt.xlim()
plt.xlim(left = pd.Timestamp("Sep 1, 2020"), right = r)
plt.ylim(bottom = 10, top = 1000)
plt.vlines(dates[-1], ymin = 1, ymax = 1000, color = "black", linestyles = "solid")
plt.semilogy()
plt.show()
Пример #2
0
           ],
           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 = {
    k: np.percentile(v, [0.05, 0.50, 0.95])
    for (k, v) in evaluated_YLLs.items()
}
novax_YLL_percentiles = {
    k: v
    for (k, v) in evaluated_YLL_percentiles.items() if "novaccination" in k
}
random_YLL_percentiles = {
    k: v
    for (k, v) in evaluated_YLL_percentiles.items() if "random" in k
             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)
    Pr_covid_t[:, 0] = lambda_x[:, 0]
    Pr_covid_pre_t[:, 0] = lambda_x[:, 0]
Пример #4
0
        estimates.append((regency, Rt_pred[-1], Rt_CI_lower[-1], Rt_CI_upper[-1], linear_projection(dates, Rt_pred, 7)))
estimates = pd.DataFrame(estimates)
estimates.columns = ["regency", "Rt", "Rt_CI_lower", "Rt_CI_upper", "Rt_proj"]
estimates.set_index("regency", inplace=True)
estimates.to_csv("data/SULSEL_Rt_projections.csv")
print(estimates)

gdf = gpd.read_file("data/gadm36_IDN_shp/gadm36_IDN_2.shp")\
    .query("NAME_1 == 'Sulawesi Selatan'")\
    .merge(estimates, left_on = "NAME_2", right_on = "regency")

choro = plt.choropleth(gdf, mappable = plt.get_cmap(0.4, 1.4, "viridis"))

for ax in choro.figure.axes[:-1]:
    plt.sca(ax)
    plt.xlim(left = 119, right = 122)
    plt.ylim(bottom = -7.56, top = -1.86)

plt.show()

logger.info("adaptive control")
(dates, Rt_pred, Rt_CI_upper, Rt_CI_lower, T_pred, T_CI_upper, T_CI_lower, total_cases, new_cases_ts, anomalies, anomaly_dates)\
    = analytical_MPVS(new_cases, CI = CI, smoothing = smoothing, totals = False)
Rt = pd.DataFrame(data = {"Rt": Rt_pred[1:]}, index = dates)
Rt_current = Rt_pred[-1]
Rt_m = np.mean(Rt[(Rt.index >= "April 21, 2020") & (Rt.index <= "May 22, 2020")])[0]
Rt_v = np.mean(Rt[(Rt.index <= "April 14, 2020")])[0]

Rt_m_scaled = Rt_current + 0.75 * (Rt_m - Rt_current)
Rt_v_scaled = Rt_current + 0.75 * (Rt_v - Rt_current)
Пример #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
         smoothed(series.retail_and_recreation_percent_change_from_baseline),
         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
sulsel = pd.read_csv("data/3 OCT 2020 Data collection template update South Sulawesi_CASE.csv", usecols = schema.keys())\
        .rename(columns = schema)\
        .dropna(how = 'all')
parse_datetimes(sulsel.loc[:, "confirmed"])

sulsel = sulsel.confirmed.value_counts().sort_index()

plt.plot(dkij.index, dkij.values, color = "royalblue", label = "private")
plt.plot(dkij_public.diff(), color = "firebrick", label = "public")
plt.legend()
plt.PlotDevice()\
    .title("\nJakarta: public vs private case counts")\
    .xlabel("date")\
    .ylabel("cases")
plt.xlim(right = dkij.index.max())
plt.ylim(top = 800)
plt.show()

plt.plot(sulsel,               color = "royalblue", label = "private", linewidth = 3)
plt.plot(sulsel_public.diff(), color = "firebrick", label = "public")
plt.legend()
plt.PlotDevice()\
    .title("\nSouth Sulawesi: public vs private case counts")\
    .xlabel("date")\
    .ylabel("cases")
plt.xlim(right = sulsel.index.max())
plt.show()

# correlation: dkij
dkij_diff = dkij_public.diff().dropna()
Пример #8
0
    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()
plt.ylim(bottom=1e-7)
plt.show()
Пример #9
0
        .show()
    
    I0 = (ts.loc[state].Hospitalized - ts.loc[state].Recovered - ts.loc[state].Deceased).sum()
    state_model = SIR(name = state, population = pop, dT0 = T_pred[-1], Rt0 = Rt_pred[-1], mobility = 0, I0 = I0, upper_CI = T_CI_upper[-1], lower_CI = T_CI_lower[-1], random_seed = 0).run(10)

    empirical = state_ts_full[(state_ts_full.index >= "Oct 14, 2020") & (state_ts_full.index < "Oct 25, 2020")]

    plt.daily_cases(dates, T_pred, T_CI_upper, T_CI_lower, new_cases_ts, anomaly_dates, anomalies, CI, 
        prediction_ts=[
            (state_model.dT, state_model.lower_CI, state_model.upper_CI, plt.PRED_PURPLE, "predicted cases"),
        ] + [(empirical, empirical, empirical, "black", "empirical post-prediction cases")] if state != "Maharashtra" else [])\
        .ylabel("cases")\
        .xlabel("date")\
        .title(f"\n{state}: Daily Cases")\
        .annotate("\nBayesian training process on empirical data, with anomalies identified")
    _, r = plt.xlim()
    plt.xlim(left = pd.Timestamp("August 01, 2020"), right = r)
    plt.show()
    
    gdf = gpd.read_file(data/f"{code}.json")
    district_names = sorted(gdf.district)
    district_time_series = get_time_series(df[df.detected_state == state], "detected_district").Hospitalized
    migration = np.zeros((len(district_names), len(district_names)))
    estimates = []
    max_len = 1 + max(map(len, district_names))
    with tqdm(district_time_series.index.get_level_values(0).unique()) as districts:
        for district in districts:
            districts.set_description(f"{district :<{max_len}}")
            try: 
                (dates, Rt_pred, Rt_CI_upper, Rt_CI_lower, *_) = analytical_MPVS(district_time_series.loc[district], CI = CI, smoothing = notched_smoothing(window = smoothing), totals = False)
                estimates.append((district, Rt_pred[-1], Rt_CI_lower[-1], Rt_CI_upper[-1], linear_projection(dates, Rt_pred, smoothing, period = 7)))