Python API reference¶
The public API of epidemic_dates, generated from the numpy-style docstrings.
Everything listed in the package's __all__ appears here.
For a guided tour see the Python guide.
For the JavaScript equivalent see the JavaScript API reference.
Impute missing earlier event dates in line lists, and measure the bias.
Some line lists fill a missing event date (such as symptom onset) with
the report date minus a delay drawn from the pooled empirical
event-to-report delays of cases with both dates.
The examples here use symptom onset as the earlier event.
epidemic_dates is a stochastic simulation that measures the bias of this
approach and of three alternatives.
It is an independent cross-check of the expected-value maths in
epidemic-dates.js, which drives the interactive page.
It also provides impute_linelist to apply the methods to a real line
list, and nowcast_linelist to nowcast it with uncertainty.
Warning. This code was generated by an LLM. Sam Abbott has only checked the interactive page. This package and its tests have not been reviewed by a person. Treat the results as exploratory.
- Repository: https://github.com/seabbs/EpidemicDates
- Interactive page: https://seabbs.github.io/EpidemicDates/interactive/
Usage
Install from GitHub with pip or uv:
Run the simulation study from the command line.
Results go to output/results.csv:
Run one scenario from Python and look at the bias of each method:
import epidemic_dates as ed
ed.DESC # what each scenario does
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"])
Impute a real line list. Pass one onset day (NaN where missing) and one report day per case, as whole numbers such as days since the first report:
import numpy as np
import epidemic_dates as ed
onset = np.array([0, 2, np.nan, 5, np.nan])
report = np.array([3, 6, 7, 9, 12])
res = ed.impute_linelist(onset, report, cutoff=12)
res["imputed"]["backsampling"] # daily onset counts, pooled empirical delays
res["imputed"]["mean"] # daily onset counts, mean shift
res["imputed"]["em"] # daily onset counts, EM back-projection
res["empirical_delay"] # pooled delay pmf of cases with both dates
res["em_delay"] # delay pmf estimated by EM back-projection
Day i of each output is onset day i.
Methods assume onsets are missing at random given the report day.
See impute_linelist for details and the README for what to check first.
Nowcast with uncertainty.
nowcast_linelist also corrects for right truncation and samples, to
give quantiles in the long format forecast hubs use:
Scenarios
SCEN holds the settings of each scenario and DESC a one-line
description.
The forward method in F picks the delay pmf by report day, as the
onset day is unknown, so it is close to but not exactly an oracle.
Scenarios A, B, B0, C, D and E vary the growth rate.
F has a delay that shortens over time.
G and H make missingness depend on the delay or the report day.
I doubles case numbers from day 70.
Csmall is C with about 300 cases.
W has two waves.
Quick start
From the command line, run two scenarios with 50 replicates each.
Results go to output/results.csv and output/analytic.txt.
From Python:
import epidemic_dates as sim
sim.DESC["W"]
rows = sim.run_scenario("W", reps=100)
rows[0]["relbias_mean"]
sim.write_results(rows, "output")
On a real line list, give integer days (for example days since the first
report), with NaN where the onset is missing:
import numpy as np
onset = np.array([0, 2, np.nan, 5, np.nan])
report = np.array([3, 6, 7, 9, 12])
res = sim.impute_linelist(onset, report, cutoff=12)
res["imputed"]["backsampling"] # daily onset counts, index = onset day
res["imputed"]["em"]
All methods assume onsets are missing at random given the report day.
See impute_linelist for details.
DMAX
module-attribute
¶
Maximum onset-to-report delay in days. Delay pmfs cover 0..DMAX.
F_DEFAULT
module-attribute
¶
Default forward delay pmf, gamma_pmf(8, 8) on 0..DMAX.
Mean 8 days and SD 8 days (an exponential before censoring).
Used by every scenario except F.
The array is read-only.
DELAY_SHRINKAGE
module-attribute
¶
Default strength of the shrinkage of each period's delay towards the
previous period's delay, in expected onsets. See em_fit.
METHODS
module-attribute
¶
Imputation methods compared, in the order used in summary rows.
NOWCAST_METHODS
module-attribute
¶
Imputation methods nowcast_linelist accepts. em is the default.
QUANTILES
module-attribute
¶
Default quantile levels: the median and 50%, 80% and 95% intervals.
DESC
module-attribute
¶
DESC: Final[Mapping[str, str]] = MappingProxyType(
{
"A": "r=0.05 constant",
"B": "r=0.05 then -0.03 at d60",
"B0": "r=0 stable",
"C": "r 0.05->-0.02 over d60-100",
"D": "r 0.06->-0.04 at d80",
"E": "r=0.008 (Isiro-like)",
"F": "r=0.03, mean delay 12->4",
"G": "as C, P(miss) 0.2->0.7 with delay",
"H": "as C, P(miss) 0.2->0.6 by report d60-100",
"I": "as C, ascertainment x2 at d70",
"Csmall": "as C, ~300 cases",
"W": "two waves: growth, control, resurgence, control",
}
)
One-line description of each scenario in SCEN. Read-only.
Unless stated, the delay is F_DEFAULT and each onset is missing with
probability 0.4.
SCEN
module-attribute
¶
SCEN: Final[Mapping[str, Scenario]] = MappingProxyType(
{
"A": Scenario(120, 10000, None),
"B": Scenario(150, 5000, 8),
"B0": Scenario(150, 4000, None),
"C": Scenario(150, 5000, 12),
"D": Scenario(150, 5000, 11),
"E": Scenario(150, 3000, None),
"F": Scenario(150, 5000, None),
"G": Scenario(150, 5000, 12),
"H": Scenario(150, 5000, 12),
"I": Scenario(150, 5000, 10),
"Csmall": Scenario(150, 300, 12),
"W": Scenario(150, 5000, 7),
}
)
Scenario settings, keyed by name. Read-only.
Each value is a Scenario (L, target, cp): the number of onset days,
the expected total number of cases and the change-point week (or
None).
The growth rate path is set in r_path and missingness in miss_prob.
See DESC.
LinelistResult
¶
Bases: TypedDict
Output of impute_linelist.
Daily arrays have length T + 1 and index i is onset day i.
Attributes:
| Name | Type | Description |
|---|---|---|
complete |
numpy.ndarray of float
|
Onset counts of cases with a known onset. |
missing_by_report |
numpy.ndarray of float
|
Counts of missing-onset cases by report day. |
empirical_delay |
numpy.ndarray of float
|
Pooled delay pmf (0..DMAX) of complete cases. |
em_delay |
numpy.ndarray of float
|
Delay pmf (0..DMAX) estimated by EM back-projection: the static
delay, or with |
em_delay_by_period |
numpy.ndarray of float
|
Delay pmf of each period, shape |
delay_period_start |
numpy.ndarray of int
|
First onset day of each period. |
imputed |
dict of str to numpy.ndarray
|
Daily onset counts (complete plus imputed) for |
imputed_before_day0 |
dict of str to float
|
Expected number of missing-onset cases that |
dropped |
int
|
Number of cases dropped before imputation. |
Source code in src/epidemic_dates/linelist.py
EMFit
¶
Bases: NamedTuple
Result of em_fit.
Attributes:
| Name | Type | Description |
|---|---|---|
allocation |
numpy.ndarray of float
|
Expected number of missing-onset cases on each onset day 0..T. |
onsets |
numpy.ndarray of float
|
Estimated expected onsets \(\lambda(s)\) of all cases, including those not yet reported, on each onset day 0..T. |
delay |
numpy.ndarray of float
|
Estimated pooled forward delay pmf \(f(d)\) on 0..DMAX. With one period this is the static delay. With several it is the pooled delay, which the first period is shrunk towards. |
delay_by_period |
numpy.ndarray of float
|
Forward delay pmf \(f_k(d)\) of each period, shape
|
period_start |
numpy.ndarray of int
|
First onset day of each period. |
Source code in src/epidemic_dates/methods.py
NowcastResult
¶
Bases: TypedDict
Output of nowcast_linelist.
Daily arrays have length T + 1 and index i is onset day i. Weekly arrays have one entry per full week ending on the cut-off. Days and weeks without an estimate hold NaN.
Attributes:
| Name | Type | Description |
|---|---|---|
method |
str
|
Imputation method used. |
cutoff |
int
|
Cut-off day T. |
dropped |
int
|
Number of cases dropped before imputation. |
delay |
numpy.ndarray of float
|
Forward delay pmf (0..DMAX) for the point nowcast: the given
static |
delay_by_period |
numpy.ndarray of float
|
Delay pmf of each period, one row per period. Each onset day is its own period when a delay matrix is given. |
period_start |
numpy.ndarray of int
|
First onset day of each period. |
reported |
numpy.ndarray of float
|
Fraction of each onset day's cases reported by the cut-off, \(F_{k(s)}(T - s)\), under the delay of the day's period. |
point |
numpy.ndarray of float
|
Point nowcast by onset day. |
point_weekly |
numpy.ndarray of float
|
Point nowcast by week. |
week_start |
numpy.ndarray of int
|
First onset day of each week. |
samples |
numpy.ndarray of float
|
Sampled nowcasts, shape |
weekly_samples |
numpy.ndarray of float
|
Sampled weekly nowcasts, shape |
quantiles |
tuple of float
|
Quantile levels. |
daily_quantiles |
list of dict
|
Rows with |
weekly_quantiles |
list of dict
|
Rows with |
Source code in src/epidemic_dates/nowcast.py
Scenario
¶
Bases: NamedTuple
Settings of one scenario.
A named tuple, so L, target, cp = SCEN[name] still unpacks it.
Attributes:
| Name | Type | Description |
|---|---|---|
days |
int
|
Number of onset days, |
target |
int
|
Expected total number of cases. |
change_point_week |
int or None
|
Change-point week used for the |
Source code in src/epidemic_dates/scenarios.py
ScenarioSetup
¶
Bases: TypedDict
Scenario inputs returned by scenario_setup.
The single-letter keys match the notation in the module docs and are kept for compatibility.
Attributes:
| Name | Type | Description |
|---|---|---|
L |
int
|
Number of onset days. |
O |
numpy.ndarray of float
|
Expected daily onsets, shape (L,). |
fmat |
numpy.ndarray of float
|
Forward delay pmf by onset day, shape (L, DMAX + 1). |
cp |
int or None
|
Change-point week, or |
Source code in src/epidemic_dates/scenarios.py
main
¶
Run the simulation study from the command line.
Runs run_study, writes results with write_results and prints the
analytic checks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
argv
|
sequence of str
|
Arguments. Defaults to |
None
|
Raises:
| Type | Description |
|---|---|
SystemExit
|
If the arguments are invalid, or for |
Source code in src/epidemic_dates/cli.py
gamma_pmf
¶
Compute a double interval censored daily Gamma delay pmf.
Uses the primarycensored form. The primary event (onset) is uniform within its day and the secondary event (report) is censored to its day, so
where \(F(x; k, \theta)\) is the Gamma CDF with shape
\(k = (\mu / \sigma)^2\) and scale \(\theta = \sigma^2 / \mu\), and
\(G(x) = 0\) for \(x \le 0\).
The pmf is truncated at dmax and renormalised.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mean
|
float
|
Mean of the continuous Gamma delay, in days. Must be positive. |
required |
sd
|
float
|
Standard deviation of the continuous Gamma delay, in days. Must be positive. |
required |
dmax
|
int
|
Maximum delay. Must be non-negative. Defaults to |
DMAX
|
Returns:
| Type | Description |
|---|---|
numpy.ndarray of float
|
Probabilities for delays 0..dmax, of length |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
Source code in src/epidemic_dates/delays.py
impute_linelist
¶
impute_linelist(
onset: ArrayLike,
report: ArrayLike,
cutoff: int | None = None,
n_iter: int = 150,
delay: ArrayLike | None = None,
delay_period: int | None = None,
delay_shrinkage: float = DELAY_SHRINKAGE,
) -> LinelistResult
Impute missing onsets in a real line list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
onset
|
array_like
|
Onset day per case, with NaN (or None) where missing. |
required |
report
|
array_like of int
|
Report day per case. Must have no missing values. Days are integers, for example days since the first report. |
required |
cutoff
|
int
|
Data cut-off day T. Must be non-negative. Defaults to the last report day. Cases reported before day 0 or after T are dropped. |
None
|
n_iter
|
int
|
Number of EM iterations passed to |
150
|
delay
|
array_like of float
|
A known forward delay, used as given (a plug-in). Either one pmf
indexed by delay in days, or a matrix with one pmf per onset day
0..T. If given, |
None
|
delay_period
|
int
|
Length in days of the periods of onset days that get their own
EM delay, counted back from the cut-off. |
None
|
delay_shrinkage
|
float
|
Strength, in expected onsets, of the shrinkage of each period's
delay towards the previous period's delay. Must be positive.
Only used with |
DELAY_SHRINKAGE
|
Returns:
| Type | Description |
|---|---|
LinelistResult
|
Daily arrays have length T + 1 and index i is onset day i.
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the line list is empty, |
Notes
backsamplingspreads each missing case over report day minus each delay, weighted byempirical_delay. It is the expected allocation of the random draw, not a draw.meanshifts each missing case back by the mean ofempirical_delay, rounded with halves up (as JavaScript'sMath.round).emusesem_fit. It estimates a static delay jointly with the onset curve, allowing for right truncation at the cut-off. Withdelay_periodit estimates one delay per period instead, each shrunk towards the previous period's delay. Withdelayit uses that delay as given and estimates only the onset curve.backsamplingandmeanalways use the pooled empirical delay of the data.forwardplaces each missing case by the given delay, \(P(s \mid t) = f_s(t - s)\). With a static delay mass before day 0 is lost, as forbacksampling. With a matrix the weights are renormalised over onset days 0..t.- All methods assume onsets are missing at random given the report day. If missingness depends on the delay, all are biased.
- Complete cases with a negative onset, an onset after report or a
delay over
DMAXare dropped. They are not imputed. - For
backsamplingandmean, imputed onsets before day 0 are not inimputed, so totals can be below the number of cases kept. The amount is inimputed_before_day0. - Outputs are expected counts and need not be whole numbers. Sum to weeks before comparing methods.
Examples:
>>> import numpy as np
>>> onset = np.array([0, 2, np.nan, 5, np.nan])
>>> report = np.array([3, 6, 7, 9, 12])
>>> res = impute_linelist(onset, report, cutoff=12)
>>> res["imputed"]["backsampling"].shape
(13,)
Source code in src/epidemic_dates/linelist.py
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 | |
as_delay
¶
Check a supplied delay, static or one pmf per onset day.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delay
|
array_like of float
|
One delay pmf indexed by delay in days, or a matrix with one pmf per onset day 0..cutoff in its rows. |
required |
cutoff
|
int
|
Data cut-off day T. |
required |
Returns:
| Type | Description |
|---|---|
numpy.ndarray of float
|
The pmf on 0..DMAX, or a |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
Source code in src/epidemic_dates/methods.py
backsampling_allocate
¶
backsampling_allocate(
missing_by_report: NDArray[float64],
delay_pmf: NDArray[float64],
) -> NDArray[np.float64]
Allocate missing-onset cases back from report day by a delay pmf.
This is the expected allocation of the backsampling method: each case
reported on day t is spread over onset days t - d with weight
delay_pmf[d]. It is not a random draw.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
missing_by_report
|
numpy.ndarray of float
|
Counts of missing-onset cases by report day 0..T. |
required |
delay_pmf
|
numpy.ndarray of float
|
Delay pmf on 0..D. |
required |
Returns:
| Type | Description |
|---|---|
numpy.ndarray of float
|
Expected missing-onset cases by onset day 0..T, the same length
as |
Source code in src/epidemic_dates/methods.py
delay_periods
¶
Split onset days 0..cutoff into periods that end on the cut-off.
Periods are delay_period days long and are counted back from the
cut-off, so the latest period is always full length.
The first period holds the days left over and can be shorter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cutoff
|
int
|
Data cut-off day T. Must be non-negative. |
required |
delay_period
|
int or None
|
Period length in days, at least 1. |
required |
Returns:
| Type | Description |
|---|---|
numpy.ndarray of int
|
Period index (0, 1, ...) of each onset day 0..cutoff. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
Source code in src/epidemic_dates/methods.py
em_backproject
¶
em_backproject(
complete: tuple[ArrayLike, ArrayLike],
missing_report: ArrayLike,
cutoff: int,
n_iter: int = 150,
) -> NDArray[np.float64]
Back-project missing-onset cases by EM with an estimated delay.
A shortcut for em_fit(...).allocation. See em_fit for the
method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
complete
|
tuple of array_like
|
|
required |
missing_report
|
array_like of int
|
Report days (0..cutoff) of cases with a missing onset. |
required |
cutoff
|
int
|
Data cut-off day T. Must be non-negative. |
required |
n_iter
|
int
|
Number of EM iterations. Must be at least 1. No convergence check is made. |
150
|
Returns:
| Type | Description |
|---|---|
numpy.ndarray of float
|
Expected number of missing-onset cases on each onset day
0..cutoff, length |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the inputs are invalid. See |
Source code in src/epidemic_dates/methods.py
em_fit
¶
em_fit(
complete: tuple[ArrayLike, ArrayLike],
missing_report: ArrayLike,
cutoff: int,
n_iter: int = 150,
delay: ArrayLike | None = None,
delay_period: int | None = None,
delay_shrinkage: float = DELAY_SHRINKAGE,
) -> EMFit
Back-project missing-onset cases by EM, returning all estimates.
Onset days are split into periods \(k\) of delay_period days, counted
back from the cut-off (see delay_periods).
By default there is one period, so the delay is static.
Expected counts by onset day \(s\) and delay \(d\) are
\(\lambda(s) f_{k(s)}(d)\), observed only when \(s + d \le T\) (right
truncation), where \(T\) is cutoff and \(k(s)\) is the period of onset
day \(s\).
Complete cases give counts \(n_c(s, d)\).
Missing cases give counts \(m(t)\) by report day only.
Starting values are the complete-case delay counts plus 0.5,
normalised, for every \(f_k\), and complete-case onset counts inflated
by the overall missing fraction, plus 0.1, for \(\lambda\).
Each of n_iter iterations then does the following.
E-step: allocate the missing cases reported on day \(t\) as
M-step: with \(n = n_c + n_a\), alternate three times between
where \(F_k\) is the CDF of \(f_k\) and \(D\) = DMAX.
\(f\) is the pooled delay, floored at \(10^{-12}\) and renormalised.
With one period \(f_0 = f\).
With several, each period's delay is shrunk towards the delay of the
period before it, and the first period towards \(f\).
In order \(k = 0, 1, \dots\),
with \(\kappa\) = delay_shrinkage.
\(E_k(d)\) is the expected number of period-\(k\) onsets that could be
seen with delay \(d\) by the cut-off, so the weight on the period's own
data, \(E_k(d) / (E_k(d) + \kappa)\), grows with its effective sample
size.
It is the posterior mode of \(f_k(d)\) under a
\(\operatorname{Gamma}\big(\kappa h_k(d) + 1, \kappa\big)\) prior,
whose mode is \(h_k(d)\), so the periods follow a random walk.
A delay a period cannot yet show (\(E_k(d) = 0\)), and every delay of a
period with no cases, takes the previous period's value.
This matters most for the latest period, which can only show delays
up to its length: its longer delays come from the period before.
\(f_k\) is floored at \(10^{-12}\) and renormalised.
If delay is given it is a plug-in: it is held fixed and only
\(\lambda\) is updated in the M-step.
A one-dimensional delay is a static delay.
A two-dimensional delay has one row per onset day, so the delay of
onset day \(s\) is row \(s\) and can change over time.
The method assumes onsets are missing at random given the report day, and that the delay is constant within each period. No smoothing is applied to \(\lambda\).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
complete
|
tuple of array_like
|
|
required |
missing_report
|
array_like of int
|
Report days (0..cutoff) of cases with a missing onset. |
required |
cutoff
|
int
|
Data cut-off day T. Must be non-negative. |
required |
n_iter
|
int
|
Number of EM iterations. Must be at least 1. No convergence check is made. |
150
|
delay
|
array_like of float
|
Forward delay to hold fixed instead of estimating it. Either one
pmf indexed by delay in days, or a matrix with one such pmf per
onset day 0..cutoff (shape |
None
|
delay_period
|
int
|
Length in days of the periods with their own delay. |
None
|
delay_shrinkage
|
float
|
Shrinkage strength \(\kappa\), in expected onsets, of each
period's delay towards the previous period's delay. Must be
positive. Only
used with |
DELAY_SHRINKAGE
|
Returns:
| Type | Description |
|---|---|
EMFit
|
The expected allocation of missing-onset cases by onset day
(length |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the inputs are out of range, not whole numbers, or of
mismatched length, if |
Source code in src/epidemic_dates/methods.py
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 | |
mean_shift_allocate
¶
Move missing-onset cases back from report day by a fixed shift.
This is the mean method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
missing_by_report
|
numpy.ndarray of float
|
Counts of missing-onset cases by report day 0..T. |
required |
shift
|
int
|
Days to move each case back. Must be non-negative. |
required |
Returns:
| Type | Description |
|---|---|
numpy.ndarray of float
|
Missing-onset cases by onset day 0..T, the same length as
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/epidemic_dates/methods.py
posterior_allocate
¶
posterior_allocate(
missing_by_report: NDArray[float64],
onsets: NDArray[float64],
delay_by_day: NDArray[float64],
) -> NDArray[np.float64]
Allocate missing-onset cases by \(\lambda(s) f_s(t - s)\).
Each case reported on day \(t\) is spread over onset days
\(s = 0, \dots, t\) with weight proportional to
\(\lambda(s) f_s(t - s)\), where \(f_s\) is row \(s\) of delay_by_day.
With \(\lambda\) constant this is the forward draw with a delay that
changes over time.
Weights are renormalised over \(0, \dots, t\), so no case is placed
before day 0.
Cases on a report day with no possible onset are dropped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
missing_by_report
|
numpy.ndarray of float
|
Counts of missing-onset cases by report day 0..T. |
required |
onsets
|
numpy.ndarray of float
|
Onset curve \(\lambda\) on 0..T. |
required |
delay_by_day
|
numpy.ndarray of float
|
Delay pmf of each onset day, shape |
required |
Returns:
| Type | Description |
|---|---|
numpy.ndarray of float
|
Expected missing-onset cases by onset day 0..T. |
Examples:
>>> f = np.array([[0.5, 0.5], [1.0, 0.0]])
>>> posterior_allocate(np.array([0.0, 3.0]), np.ones(2), f).tolist()
[1.0, 2.0]
Source code in src/epidemic_dates/methods.py
round_half_up
¶
Round to the nearest integer, with halves rounded up.
This matches JavaScript's Math.round. Python's built-in round
rounds halves to even.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
float
|
Value to round. Must be finite. |
required |
Returns:
| Type | Description |
|---|---|
int
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
Source code in src/epidemic_dates/methods.py
nowcast_linelist
¶
nowcast_linelist(
onset: ArrayLike,
report: ArrayLike,
cutoff: int | None = None,
method: str = "em",
delay: ArrayLike | None = None,
*,
n_samples: int = 1000,
seed: int = 1,
quantiles: Sequence[float] = QUANTILES,
min_reported: float = 0.05,
bootstrap: bool = True,
n_iter: int = 150,
origin: date | str | None = None,
delay_period: int | None = None,
delay_shrinkage: float = DELAY_SHRINKAGE,
) -> NowcastResult
Nowcast onsets from a line list, with uncertainty.
There are three steps.
1. Impute.
Cases with a known onset keep it.
Missing onsets are imputed by method:
em(default): EM back-projection (em_fit), \(P(s \mid t) \propto \lambda(s) f(t - s)\);backsampling: \(P(s \mid t) = g(t - s)\), with \(g\) the pooled empirical delay of complete cases;mean: \(s = t - \operatorname{round}\big(\sum_d d \, g(d)\big)\);forward: \(P(s \mid t) = f(t - s)\).
Here \(f\) is delay if given, used as is (a plug-in).
It can be one pmf or a matrix with one pmf per onset day, so
\(f_s\) can change over time.
Otherwise it is estimated by em_fit, which allows for right
truncation: one static delay, or with delay_period one delay
\(f_k\) per period of onset days, shrunk towards the previous period's delay.
Write \(f_s\) for the delay of onset day \(s\) in every case.
When \(f_s\) changes over time, forward uses
\(P(s \mid t) \propto f_s(t - s)\) over onset days \(0, \dots, t\).
This gives \(\hat n(s) = n_c(s) + n_i(s)\), the onsets on day \(s\) of
cases reported by the cut-off \(T\).
2. Correct for right truncation. With \(F_s\) the CDF of \(f_s\), the point nowcast is
Days with \(F_s(T - s)\) below min_reported get no estimate (NaN).
3. Sample.
Each of n_samples samples does the following, with a generator
seeded by seed.
- If
bootstrap, resample the complete cases with replacement. Recompute \(g\) from them. Refit EM to the resampled complete cases and the missing cases, warm-started from the point fit formax(10, n_iter // 5)iterations, to get \(f_b\) and \(\lambda_b\). Withdelay_period, \(f_b\) holds one delay per period, refitted in the same way. With a givendelay, \(f_b\) is that delay and only \(\lambda_b\) is refitted. Withoutbootstrap, \(g\), \(f_b = f\) and \(\lambda_b = \lambda\) are fixed. - Draw the onsets of the missing cases.
backsamplingandforwarddraw \(m(t)\) cases reported on day \(t\) as a multinomial over delays with \(g\) or \(f_b\).emdraws a multinomial over onset days with \(P(s \mid t) \propto \lambda_b(s) f_{b,s}(t - s)\). With a delay that changes over time,forwarddraws the same way with \(\lambda_b\) constant.meanshifts every case by the rounded mean of \(g\), with no draw. This gives \(n_b(s)\), which adds the complete cases on day \(s\). - Draw the cases with onset \(s\) not yet reported,
$\(U(s) \sim \operatorname{NegBin}\big(n_b(s), F_{b,s}(T - s)\big),\)$
the number of failures before \(n_b(s)\) successes with success probability \(F_{b,s}(T - s)\), the CDF of the onset day's delay, which has mean \(n_b(s) \big(1 - F_{b,s}\big) / F_{b,s}\). This is the posterior for the total under a prior proportional to \(1 / C(s)\), given \(n_b(s)\) reported with probability \(F_b\). The sample is \(C_b(s) = n_b(s) + U(s)\).
Weekly samples sum the daily samples over full weeks that end on the
cut-off.
A week with any day without an estimate has no estimate.
Quantiles use linear interpolation (numpy.quantile).
What the samples capture.
Sampling of the missing onsets given the delay and onset curve.
The binomial reporting of recent onsets, given the delay.
With bootstrap, sampling uncertainty in the delay from the finite
number of complete cases (and in the onset curve used by em).
What they do not capture.
Error in the model: a delay that changes over time but is estimated
as static, or that changes within a period; onsets missing other
than at random given report day; or reporting that is not
independent between cases.
Uncertainty in the given delay, if one is passed.
Noise in the onset process itself: the target is the onsets that
will eventually be reported, not an expected curve.
Days with no reported onsets get a nowcast of 0 in every sample.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
onset
|
array_like
|
Onset day per case, with NaN (or None) where missing. |
required |
report
|
array_like of int
|
Report day per case. Must have no missing values. |
required |
cutoff
|
int
|
Data cut-off day T. Defaults to the last report day. |
None
|
method
|
('em', 'backsampling', 'mean', 'forward')
|
Imputation method. Defaults to |
"em"
|
delay
|
array_like of float
|
Forward delay, used as given for the truncation correction, for
|
None
|
n_samples
|
int
|
Number of samples. Must be at least 1. |
1000
|
seed
|
int
|
Seed for |
1
|
quantiles
|
sequence of float
|
Quantile levels, each in [0, 1]. Defaults to |
QUANTILES
|
min_reported
|
float
|
Smallest fraction reported, \(F(T - s)\), for a day to get an estimate. Must be in (0, 1]. |
0.05
|
bootstrap
|
bool
|
Resample complete cases to include delay uncertainty. |
True
|
n_iter
|
int
|
Number of EM iterations for the point fit. Must be at least 1. |
150
|
origin
|
date or str
|
Date of day 0, as a date or an ISO string. If given, dates in the quantile tables are ISO strings. Otherwise they are day numbers. |
None
|
delay_period
|
int
|
Length in days of the periods of onset days that get their own
estimated delay, counted back from the cut-off. |
None
|
delay_shrinkage
|
float
|
Strength, in expected onsets, of the shrinkage of each period's delay towards the previous period's delay. Must be positive. |
DELAY_SHRINKAGE
|
Returns:
| Type | Description |
|---|---|
NowcastResult
|
A dict with the point nowcast, daily and weekly samples, and daily and weekly quantile tables in long format (one row per date and quantile). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the line list is invalid (see |
See Also
impute_linelist : the point imputations without truncation correction. write_nowcast_csv : write the quantile table.
Examples:
>>> import numpy as np
>>> onset = np.array([0, 1, np.nan, 3, 4, np.nan, 6, 8, np.nan, 9])
>>> report = np.array([2, 4, 5, 6, 7, 8, 9, 10, 11, 12])
>>> res = nowcast_linelist(onset, report, n_samples=50, seed=1)
>>> res["samples"].shape
(50, 13)
>>> res["daily_quantiles"][0]["target_end_date"], len(res["quantiles"])
(0, 7)
Source code in src/epidemic_dates/nowcast.py
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 | |
write_nowcast_csv
¶
Write the quantile table of a nowcast as CSV.
The table is in long format with one row per date and quantile, the
format forecast hubs use for quantile forecasts.
Columns are target_end_date, quantile and value, with
week_start first for weekly tables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
NowcastResult
|
Output of |
required |
path
|
str or PathLike
|
File to write. |
required |
by
|
('week', 'day')
|
Write the weekly or the daily table. |
"week"
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> import tempfile, pathlib
>>> import numpy as np
>>> onset = np.array([0, 1, np.nan, 3, 4, np.nan, 6, 8, np.nan, 9])
>>> report = np.array([2, 4, 5, 6, 7, 8, 9, 10, 11, 12])
>>> res = nowcast_linelist(onset, report, n_samples=50)
>>> out = pathlib.Path(tempfile.mkdtemp()) / "nowcast.csv"
>>> write_nowcast_csv(res, out)
>>> out.read_text().splitlines()[0]
'week_start,target_end_date,quantile,value'
Source code in src/epidemic_dates/nowcast.py
miss_prob
¶
Compute the probability that each case's onset is missing.
The probability is 0.4 for all cases, except in scenario G (0.2
rising to 0.7 as the delay goes from 0 to 20 days) and H (0.2
rising to 0.6 as the report day goes from 60 to 100).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
A key of |
required |
delay
|
numpy.ndarray of int
|
Onset-to-report delay of each case, in days. |
required |
report
|
numpy.ndarray of int
|
Report day of each case. Same shape as |
required |
Returns:
| Type | Description |
|---|---|
numpy.ndarray of float
|
Probability that each case's onset is missing, same shape as
|
Source code in src/epidemic_dates/scenarios.py
r_path
¶
Compute the daily growth rate path of a scenario.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
A key of |
required |
days
|
int
|
Number of onset days, |
required |
Returns:
| Type | Description |
|---|---|
numpy.ndarray of float
|
Growth rate r(t) per day for days 0..days-1. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/epidemic_dates/scenarios.py
scenario_setup
¶
Build the expected onset curve and delays for a scenario.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
A key of |
required |
Returns:
| Type | Description |
|---|---|
ScenarioSetup
|
Scenario inputs with keys:
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/epidemic_dates/scenarios.py
simulate
¶
simulate(
name: str, setup: ScenarioSetup, rng: Generator
) -> tuple[
NDArray[np.int64], NDArray[np.int64], NDArray[np.bool_]
]
Simulate one line list for a scenario.
Daily onset counts are Poisson with mean setup["O"].
Each case gets a delay from its onset day's forward pmf, a report
day of onset plus delay, and a missing-onset flag from miss_prob.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
A key of |
required |
setup
|
ScenarioSetup
|
Output of |
required |
rng
|
Generator
|
Random number generator. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
onset |
numpy.ndarray of int
|
Onset day of each case. |
report |
numpy.ndarray of int
|
Report day of each case. No cut-off is applied, so reports run
to |
missing |
numpy.ndarray of bool
|
Whether each case's onset is missing. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/epidemic_dates/scenarios.py
analytic
¶
Run analytic checks of pooled complete-case delays.
Compares the forward delay pmf with the backward pmf under constant growth, and checks the result by simulation.
Returns:
| Type | Description |
|---|---|
list of str
|
Lines of text:
|
Source code in src/epidemic_dates/study.py
run_scenario
¶
run_scenario(
name: str,
reps: int = 200,
seed: int = 20261027,
cutoffs: Sequence[int] | None = None,
) -> list[SummaryRow]
Simulate one scenario and summarise each method's bias.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
A key of |
required |
reps
|
int
|
Number of stochastic replicates. Must be at least 1. |
200
|
seed
|
int
|
Seed for |
20261027
|
cutoffs
|
sequence of int
|
Data cut-off days, each non-negative. The retrospective cut-off
is |
None
|
Returns:
| Type | Description |
|---|---|
list of dict
|
One row per cut-off and method. Bias is against the true onsets
of cases reported by the cut-off. Weeks are scored only if the
mean true count is at least 10 (3 for Always present:
If the scenario has a change point within the scored weeks:
Retrospective rows only:
Real-time rows only:
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Notes
In scenario F the delay changes with onset day. The forward
method draws from the pmf of the case's report day, as the onset day
is unknown, so it is close to but not exactly an oracle there.
Source code in src/epidemic_dates/study.py
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 | |
run_study
¶
run_study(
reps: int = 200,
seed: int = 20261027,
scenarios: Sequence[str] | None = None,
verbose: bool = True,
) -> list[SummaryRow]
Run every scenario, or those named, and return all summary rows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reps
|
int
|
Number of replicates per scenario. Must be at least 1. |
200
|
seed
|
int
|
Base seed. Scenario |
20261027
|
scenarios
|
sequence of str
|
Keys of |
None
|
verbose
|
bool
|
Print a line as each scenario finishes. |
True
|
Returns:
| Type | Description |
|---|---|
list of dict
|
Rows from |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a scenario name is unknown or |
Source code in src/epidemic_dates/study.py
summarise
¶
summarise(
name: str,
setup: ScenarioSetup,
cutoff: int,
replicates: Sequence[Replicate],
retro: bool,
) -> list[SummaryRow]
Summarise each method's bias over replicates at one cut-off.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
A key of |
required |
setup
|
ScenarioSetup
|
Output of |
required |
cutoff
|
int
|
Cut-off day. |
required |
replicates
|
sequence of dict
|
Outputs of |
required |
retro
|
bool
|
Whether |
required |
Returns:
| Type | Description |
|---|---|
list of dict
|
One row per method. See |
Source code in src/epidemic_dates/study.py
write_results
¶
Write summary rows and analytic checks to a directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rows
|
sequence of dict
|
Summary rows, for example from |
required |
out
|
str or PathLike
|
Output directory. Created if needed. |
required |
Notes
Writes out/results.csv, with columns in order of first appearance
and floats to 4 decimal places, and out/analytic.txt, the output
of analytic. Existing files are overwritten.