¶
Install epidemic_dates with pip and import it as ed.
The Python package epidemic_dates is an independent stochastic simulation.
It cross-checks the expected-value maths in the JavaScript module that drives the interactive page.
It can also impute a real line list.
- Source:
src/epidemic_dates/ - Every function: API reference
- The maths: Methods
- What it relies on: Assumptions
Warning
This package was generated by an LLM and has not been reviewed by a person. Treat the results as exploratory.
Install¶
Or, from a clone of the repository, prefix commands with uv run.
See Getting started.
Quick start on your own data¶
This reads the example line list, imputes the missing onsets and prints weekly onset counts by method.
import csv
import datetime as dt
import numpy as np
import epidemic_dates as ed
np.set_printoptions(linewidth=100)
day0 = dt.date(2026, 5, 3) # earliest date in the file
def day(x):
return (dt.date.fromisoformat(x) - day0).days if x else np.nan
with open("docs/data/example-linelist.csv") as fh:
rows = list(csv.DictReader(fh))
onset = np.array([day(r["onset_date"]) for r in rows])
report = np.array([day(r["report_date"]) for r in rows])
res = ed.impute_linelist(onset, report, cutoff=int(report.max()))
week = np.arange(int(report.max()) + 1) // 7
for m in ["backsampling", "mean", "em"]:
print(m, np.bincount(week, weights=res["imputed"][m]).round(1))
backsampling [ 6.8 14.9 16.8 27.9 44.7 81.9 122.9 200.2 251.1 353.7 595.8 697.1 455.2 174. ]
mean [ 7. 15. 14. 31. 38. 84. 119. 197. 250. 351. 609. 708. 488. 132.]
em [ 7. 15.4 15.9 26.5 43.5 81.3 121.4 203.2 246.3 346.2 614.2 723.5 440.4 159.2]
The worked example explains each step.
impute_linelist takes:
onset: onset day per case,NaNwhere missing;report: report day per case, never missing;cutoff: the last report day to use, by default the latest;n_iter: the number of EM iterations;delay: an optional known delay, one pmf or a matrix with one pmf per onset day, which EM holds fixed and which addsforward;delay_period: the length in days of periods that each get their own EM delay, by default none;delay_shrinkage: how strongly each period's delay is pulled towards the previous period's, 10 expected cases by default.
It returns a dict.
imputed holds daily onset counts for backsampling, mean and em, and forward if delay is given.
complete holds the cases with a known onset, missing_by_report the missing-onset cases by report day, and empirical_delay the pooled delay pmf.
em_delay is the delay EM used, em_delay_by_period has one row per period and delay_period_start gives the first day of each period.
dropped counts cases that could not be used.
Nowcast with uncertainty¶
nowcast_linelist imputes the missing onsets, corrects for right truncation and samples to give quantiles.
This continues the quick start above.
nc = ed.nowcast_linelist(onset, report, method="em", seed=1, origin=day0)
for r in nc["weekly_quantiles"][-7:]:
print(r["week_start"], r["target_end_date"], r["quantile"], round(r["value"], 1))
ed.write_nowcast_csv(nc, "nowcast.csv")
2026-08-02 2026-08-08 0.025 328.0
2026-08-02 2026-08-08 0.1 351.0
2026-08-02 2026-08-08 0.25 369.0
2026-08-02 2026-08-08 0.5 393.0
2026-08-02 2026-08-08 0.75 415.2
2026-08-02 2026-08-08 0.9 440.0
2026-08-02 2026-08-08 0.975 466.1
The table has one row per week and quantile.
Weeks end on the cut-off.
A day with under 5% of its cases reported gets no estimate, and nor does its week (min_reported); here every week has one.
write_nowcast_csv writes the table to CSV.
method can also be backsampling, mean or forward, and delay holds the delay fixed.
The bands include the draw of missing onsets, the cases not yet reported and, by resampling, uncertainty in the delay.
They do not include a delay that changes over time, unless you set delay_period or pass a delay matrix.
See Step 6 of the worked example and the Methods.
Delays that change over time¶
EM can use the delay in three ways:
- one static delay, estimated (the default);
- one delay per period of onset days, estimated, with
delay_period, each shrunk towards the one before it with strengthdelay_shrinkage; - a known delay, passed as
delay: one pmf, or a matrix with one row per onset day for a delay that changes over time, used as given.
impute_linelist, nowcast_linelist and em_fit all take it.
The nowcast then uses each day's own delay for the truncation correction, the bootstrap and the draws of cases not yet reported.
This uses the second example line list, whose mean delay falls from 12 to 5 days, and the true delay of each onset day, known because the data are simulated. It prints the estimated mean delay of each 14-day period, then the point nowcast of the last four weeks with each of the three delays. This continues the quick start above.
with open("docs/data/example-linelist-changing-delays.csv") as fh:
rows2 = list(csv.DictReader(fh))
onset2 = np.array([day(r["onset_date"]) for r in rows2])
report2 = np.array([day(r["report_date"]) for r in rows2])
cut2 = int(report2.max())
with open("docs/data/example-changing-delays-true-delay.csv") as fh:
true_delay = np.array(
[[float(r[f"p{d}"]) for d in range(61)] for r in csv.DictReader(fh)]
)
res = ed.impute_linelist(onset2, report2, cutoff=cut2, delay_period=14)
print((res["em_delay_by_period"] @ np.arange(61)).round(1))
for name, opts in [
("static", {}),
("periods", {"delay_period": 14}),
("plug-in", {"delay": true_delay}),
]:
nc = ed.nowcast_linelist(
onset2, report2, cutoff=cut2, n_samples=1, bootstrap=False,
min_reported=0.01, **opts
)
print(f"{name:<8}" + " ".join(f"{x:.1f}" for x in nc["point_weekly"][-4:]))
[ 8.5 10.2 12.3 11.9 9.6 8.9 7.1 5.9 5.4]
static 487.5 458.0 421.2 444.1
periods 466.1 428.6 361.0 297.8
plug-in 460.7 420.6 356.5 320.4
The true mean delay falls from 12 days in the first periods to 5 in the last. The eventual true onsets in the last four weeks are 456, 414, 374 and 317. The static delay is too long for recent onsets, so its nowcast is up to 40% too high. Per-period delays bring the error down to 4% on average, and the true delay to 2%.
Delays that change over time in the worked example goes through this in all four languages, and the Methods page has the maths.
Run the simulation study¶
The study simulates each scenario many times and measures the bias of each method.
From the command line, results go to output/results.csv:
The options are --reps, --seed, --out and --scenarios.
From Python, run one scenario:
import epidemic_dates as ed
ed.DESC["W"] # 'two waves: growth, control, ...'
rows = ed.run_scenario("W", reps=100) # one row per cut-off and method
for r in rows:
print(r["cutoff"], r["method"], r["relbias_mean"], r["relbias_maxabs"])
Each row has the scenario, cut-off, method and bias summaries.
relbias_mean and relbias_maxabs are the mean and largest absolute relative bias in weekly counts.
Columns starting gr_ measure bias in the growth rate.
See run_scenario in the API reference for every column.
Run every scenario and write the results:
rows = ed.run_study(reps=200)
ed.write_results(rows, "output")
print("\n".join(ed.analytic())) # checks of the steady-growth result
Scenarios¶
ed.SCEN holds each scenario's settings and ed.DESC a one-line description.
Unless stated, the delay is F_DEFAULT (mean 8 days, SD 8 days) and each onset is missing with probability 0.4.
| Name | Description |
|---|---|
A |
r = 0.05 constant |
B |
r = 0.05, then −0.03 from day 60 |
B0 |
r = 0, stable |
C |
r from 0.05 to −0.02 over days 60 to 100 |
D |
r from 0.06 to −0.04 at day 80 |
E |
r = 0.008 (Isiro-like) |
F |
r = 0.03, mean delay falls from 12 to 4 days |
G |
as C, with P(missing) rising from 0.2 to 0.7 with the delay |
H |
as C, with P(missing) rising from 0.2 to 0.6 by report day 60 to 100 |
I |
as C, with ascertainment doubling at day 70 |
Csmall |
as C, with about 300 cases |
W |
two waves: growth, control, resurgence, control |
To simulate one line list yourself:
import numpy as np
sp = ed.scenario_setup("C")
onset, report, missing = ed.simulate("C", sp, np.random.default_rng(1))
Building blocks¶
gamma_pmf(mean, sd)gives a double interval censored daily Gamma delay pmf on0..DMAX.em_backprojectruns EM back-projection on complete and missing-onset cases.em_fitreturns the delay and onset curve too, can hold a given delay fixed, and takesdelay_period.delay_periods(cutoff, delay_period)gives the period of each onset day.posterior_allocateallocates missing cases by \(\lambda(s) f_s(t - s)\), for a delay that changes over time.METHODSlists the methods compared andDMAXthe maximum delay.
See also¶
- JavaScript guide for the same methods in the browser or Node.
- Methods for the maths.
- Assumptions for what the results rely on.