Пример #1
0
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")\
    .ylabel("reproductive rate")\
    .adjust(left = 0.11, bottom = 0.15, right = 0.98, top = 0.98)
plt.plot(sir_model.Rt, "-", color="white", linewidth=3, zorder=10)
sim_rt, = plt.plot(sir_model.Rt,
                   "-",
                   color="dodgerblue",
                   linewidth=2,
                   zorder=11)
anoms = plt.vlines(anomaly_dates, 0, 4, colors="red", linewidth=2, alpha=0.5)
plt.legend([pd.markers["Rt"], sim_rt, anoms],
           ["Estimated $R_t$ (99% CI)", "simulated $R_t$", "anomalies"],
Пример #2
0
# private data
state_cases = pd.read_csv(data / "Bihar_cases_data_Jul23.csv",
                          parse_dates=["date_reported"],
                          dayfirst=True)
state_ts = state_cases["date_reported"].value_counts().sort_index()
district_names, population_counts, _ = etl.district_migration_matrix(
    data / "Migration Matrix - District.csv")
populations = dict(zip(district_names, population_counts))

# first, look at state level predictions
(dates, RR_pred, RR_CI_upper, RR_CI_lower, T_pred, T_CI_upper, T_CI_lower,
 total_cases, new_cases_ts, anomalies,
 anomaly_dates) = analytical_MPVS(state_ts,
                                  CI=CI,
                                  smoothing=convolution(window=smoothing))

plot_RR_est(dates, RR_pred, RR_CI_upper, RR_CI_lower, CI, ymin=0, ymax=4)\
    .title("Bihar: Reproductive Number Estimate Comparisons")\
    .xlabel("Date")\
    .ylabel("Rt", rotation=0, labelpad=20)
plt.ylim(0, 4)

# public data
paths = {
    "v3": [data_path(_) for _ in (1, 2)],
    "v4": [data_path(_) for _ in range(3, 13)]
}

for target in paths['v3'] + paths['v4']:
    download_data(data, target)
    simulate_adaptive_control(adaptive, initial_lockdown, total_time, lockdown, migrations, Rm, {district: R * gamma for (district, R) in Rv.items()}, {district: R * gamma for (district, R) in Rm.items()}, evaluation_period=1*weeks)

    return (release, adaptive)

if __name__ == "__main__":
    root = cwd()
    data = root/"data"
    figs = root/"figs"

    # model details 
    gamma      = 0.2
    prevalence = 1
    total_time = 90 * days 
    release_date = pd.to_datetime("July 28, 2020")
    lockdown_period = (release_date - pd.to_datetime("today")).days
    smoothing = convolution()

    states = ["Maharashtra", "Karnataka", "Andhra Pradesh", "Tamil Nadu", "Madhya Pradesh", "Punjab", "Gujarat", "Kerala"]
    
    # use gravity matrix for states after 2001 census 
    new_state_data_paths = { 
        "Telangana": (data/"telangana.json", data/"telangana_pop.csv")
    }

    # define data versions for api files
    paths = { "v3": ["raw_data1.csv", "raw_data2.csv"],
              "v4": ["raw_data3.csv", "raw_data4.csv",
                     "raw_data5.csv", "raw_data6.csv",
                     "raw_data7.csv", "raw_data8.csv",
                     "raw_data9.csv", "raw_data10.csv", "raw_data11.csv"] } 
Пример #4
0
time_series["dow"] = time_series.index.get_level_values(1).dayofweek
plot_average_change(time_series,
                    "(All India)",
                    filename=figs / "avg_delta_I_DoW_India.png")
for state in tqdm(time_series.index.get_level_values(0).unique()):
    plot_average_change(time_series.loc[state],
                        f"({state})",
                        filename=figs / f"avg_delta_I_DoW_{state}.png")

# are anomalies falling on certain days?
print("checking anomalies...")
smoothing = 5
(*_,
 anomaly_dates) = analytical_MPVS(natl_time_series["Hospitalized"].iloc[:-1],
                                  CI=0.95,
                                  smoothing=convolution(window=smoothing))
anomaly_histogram(anomaly_dates,
                  "(All India)",
                  filename=figs / "anomaly_DoW_hist_India.png")
for state in tqdm(time_series.index.get_level_values(0).unique()):
    (*_, anomaly_dates) = analytical_MPVS(
        time_series.loc[state]["Hospitalized"].iloc[:-1],
        CI=0.95,
        smoothing=convolution(window=smoothing))
    anomaly_histogram(anomaly_dates,
                      f"({state})",
                      filename=figs / f"anomaly_DoW_hist_{state}.png")

print("estimating spectral densities...")
# what does the aggregate spectral density look like?
spectrum(natl_time_series["Hospitalized"], "All India")
Пример #5
0
    df = load_all_data(
        v3_paths = [data/filepath for filepath in paths['v3']], 
        v4_paths = [data/filepath for filepath in paths['v4']]
    )
    data_recency = str(df["date_announced"].max()).split()[0]
    run_date     = str(pd.Timestamp.now()).split()[0]

    ts = get_time_series(df[df.detected_state == "Delhi"])

    (
        dates,
        RR_pred, RR_CI_upper, RR_CI_lower,
        T_pred, T_CI_upper, T_CI_lower,
        total_cases, new_cases_ts,
        anomalies, anomaly_dates
    ) = analytical_MPVS(ts.delta[ts.delta > 0], CI = CI, smoothing = convolution(window = smoothing)) 
    #= analytical_MPVS(ts.Hospitalized[ts.Hospitalized > 0], CI = CI, smoothing = lambda ts: box_filter(ts, smoothing, 10))

    np.random.seed(33)
    delhi = Model([ModelUnit("Delhi", 18_000_000, I0 = T_pred[-1], RR0 = RR_pred[-1], mobility = 0)])
    delhi.run(14, np.zeros((1,1)))

    t_pred = [dates[-1] + pd.Timedelta(days = i) for i in range(len(delhi[0].delta_T))]

    plot_RR_est(dates, RR_pred, RR_CI_upper, RR_CI_lower, CI)
    PlotDevice().title("Delhi: Reproductive Number Estimate").xlabel("Date").ylabel("Rt", rotation=0, labelpad=20)
    plt.show()
    
    delhi[0].lower_CI[0] = T_CI_lower[-1]
    delhi[0].upper_CI[0] = T_CI_upper[-1]
    print(delhi[0].delta_T)