Skip to content

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.

Usage

Install from GitHub with pip or uv:

pip install git+https://github.com/seabbs/EpidemicDates

Run the simulation study from the command line. Results go to output/results.csv:

epidemic-dates --reps 200 --out output
epidemic-dates --reps 50 --scenarios C W

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:

res = ed.nowcast_linelist(onset, report, cutoff=12, n_samples=500)
res["weekly_quantiles"]                     # week_start, quantile, value
ed.write_nowcast_csv(res, "nowcast.csv")    # the same table as CSV
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.

uv run epidemic-dates --reps 50 --scenarios C W

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

DMAX: Final[int] = 60

Maximum onset-to-report delay in days. Delay pmfs cover 0..DMAX.

F_DEFAULT module-attribute

F_DEFAULT: Final[NDArray[float64]] = gamma_pmf(8, 8)

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

DELAY_SHRINKAGE: Final[float] = 10.0

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

METHODS: Final[tuple[str, ...]] = (
    "backsampling",
    "mean",
    "forward",
    "em",
)

Imputation methods compared, in the order used in summary rows.

NOWCAST_METHODS module-attribute

NOWCAST_METHODS: Final[tuple[str, ...]] = (
    "em",
    "backsampling",
    "mean",
    "forward",
)

Imputation methods nowcast_linelist accepts. em is the default.

QUANTILES module-attribute

QUANTILES: Final[tuple[float, ...]] = (
    0.025,
    0.1,
    0.25,
    0.5,
    0.75,
    0.9,
    0.975,
)

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 delay_period the pooled delay.

em_delay_by_period numpy.ndarray of float

Delay pmf of each period, shape (n_periods, DMAX + 1). One row, equal to em_delay, without delay_period.

delay_period_start numpy.ndarray of int

First onset day of each period. [0] without delay_period.

imputed dict of str to numpy.ndarray

Daily onset counts (complete plus imputed) for backsampling, mean and em, and forward if a delay is given.

imputed_before_day0 dict of str to float

Expected number of missing-onset cases that backsampling, mean and forward place before day 0. These are not in imputed.

dropped int

Number of cases dropped before imputation.

Source code in src/epidemic_dates/linelist.py
class LinelistResult(TypedDict):
    """Output of `impute_linelist`.

    Daily arrays have length T + 1 and index i is onset day i.

    Attributes
    ----------
    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 `delay_period` the pooled delay.
    em_delay_by_period : numpy.ndarray of float
        Delay pmf of each period, shape `(n_periods, DMAX + 1)`. One row,
        equal to `em_delay`, without `delay_period`.
    delay_period_start : numpy.ndarray of int
        First onset day of each period. `[0]` without `delay_period`.
    imputed : dict of str to numpy.ndarray
        Daily onset counts (complete plus imputed) for `backsampling`,
        `mean` and `em`, and `forward` if a delay is given.
    imputed_before_day0 : dict of str to float
        Expected number of missing-onset cases that `backsampling`, `mean`
        and `forward` place before day 0. These are not in `imputed`.
    dropped : int
        Number of cases dropped before imputation.
    """

    complete: NDArray[np.float64]
    missing_by_report: NDArray[np.float64]
    empirical_delay: NDArray[np.float64]
    em_delay: NDArray[np.float64]
    em_delay_by_period: NDArray[np.float64]
    delay_period_start: NDArray[np.int64]
    imputed: dict[str, NDArray[np.float64]]
    imputed_before_day0: dict[str, float]
    dropped: int

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 (n_periods, DMAX + 1). One row, equal to delay, without periods.

period_start numpy.ndarray of int

First onset day of each period. [0] without periods.

Source code in src/epidemic_dates/methods.py
class EMFit(NamedTuple):
    r"""Result of `em_fit`.

    Attributes
    ----------
    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
        `(n_periods, DMAX + 1)`. One row, equal to `delay`, without
        periods.
    period_start : numpy.ndarray of int
        First onset day of each period. `[0]` without periods.
    """

    allocation: NDArray[np.float64]
    onsets: NDArray[np.float64]
    delay: NDArray[np.float64]
    delay_by_period: NDArray[np.float64]
    period_start: NDArray[np.int64]

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, the EM estimate, or with periods or a delay matrix the pooled or onset-weighted mean delay.

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 (n_samples, T + 1).

weekly_samples numpy.ndarray of float

Sampled weekly nowcasts, shape (n_samples, n_weeks).

quantiles tuple of float

Quantile levels.

daily_quantiles list of dict

Rows with target_end_date, quantile and value.

weekly_quantiles list of dict

Rows with week_start, target_end_date, quantile and value.

Source code in src/epidemic_dates/nowcast.py
class NowcastResult(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
    ----------
    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`, the EM estimate, or with periods or a delay
        matrix the pooled or onset-weighted mean delay.
    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 `(n_samples, T + 1)`.
    weekly_samples : numpy.ndarray of float
        Sampled weekly nowcasts, shape `(n_samples, n_weeks)`.
    quantiles : tuple of float
        Quantile levels.
    daily_quantiles : list of dict
        Rows with `target_end_date`, `quantile` and `value`.
    weekly_quantiles : list of dict
        Rows with `week_start`, `target_end_date`, `quantile` and
        `value`.
    """

    method: str
    cutoff: int
    dropped: int
    delay: NDArray[np.float64]
    delay_by_period: NDArray[np.float64]
    period_start: NDArray[np.int64]
    reported: NDArray[np.float64]
    point: NDArray[np.float64]
    point_weekly: NDArray[np.float64]
    week_start: NDArray[np.int64]
    samples: NDArray[np.float64]
    weekly_samples: NDArray[np.float64]
    quantiles: tuple[float, ...]
    daily_quantiles: list[dict[str, object]]
    weekly_quantiles: list[dict[str, object]]

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, L.

target int

Expected total number of cases.

change_point_week int or None

Change-point week used for the *_cp summary columns, or None.

Source code in src/epidemic_dates/scenarios.py
class Scenario(NamedTuple):
    """Settings of one scenario.

    A named tuple, so `L, target, cp = SCEN[name]` still unpacks it.

    Attributes
    ----------
    days : int
        Number of onset days, `L`.
    target : int
        Expected total number of cases.
    change_point_week : int or None
        Change-point week used for the `*_cp` summary columns, or `None`.
    """

    days: int
    target: int
    change_point_week: int | None

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 None.

Source code in src/epidemic_dates/scenarios.py
class ScenarioSetup(TypedDict):
    """Scenario inputs returned by `scenario_setup`.

    The single-letter keys match the notation in the module docs and are
    kept for compatibility.

    Attributes
    ----------
    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 `None`.
    """

    L: int
    O: NDArray[np.float64]  # noqa: E741 - key kept for compatibility
    fmat: NDArray[np.float64]
    cp: int | None

main

main(argv: Sequence[str] | None = None) -> None

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 sys.argv[1:]. Options are --reps (default 200), --seed (default 20261027), --out (default output), --scenarios (default all) and --quiet.

None

Raises:

Type Description
SystemExit

If the arguments are invalid, or for --help.

Source code in src/epidemic_dates/cli.py
def main(argv: Sequence[str] | None = None) -> None:
    """Run the simulation study from the command line.

    Runs `run_study`, writes results with `write_results` and prints the
    analytic checks.

    Parameters
    ----------
    argv : sequence of str, optional
        Arguments. Defaults to `sys.argv[1:]`. Options are `--reps`
        (default 200), `--seed` (default 20261027), `--out` (default
        `output`), `--scenarios` (default all) and `--quiet`.

    Raises
    ------
    SystemExit
        If the arguments are invalid, or for `--help`.
    """
    args = build_parser().parse_args(argv)
    rows = run_study(
        args.reps, args.seed, args.scenarios, verbose=not args.quiet
    )
    write_results(rows, args.out)
    if not args.quiet:
        print("\n".join(analytic()))

gamma_pmf

gamma_pmf(
    mean: float, sd: float, dmax: int = DMAX
) -> NDArray[np.float64]

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

\[P(d) = G(d + 1) - 2 G(d) + G(d - 1),\]
\[G(x) = \int_0^x F(u; k, \theta) \, du = x F(x; k, \theta) - k \theta F(x; k + 1, \theta),\]

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.

DMAX

Returns:

Type Description
numpy.ndarray of float

Probabilities for delays 0..dmax, of length dmax + 1, summing to 1.

Raises:

Type Description
ValueError

If mean or sd is not a positive finite number, or dmax is negative.

Examples:

>>> pmf = gamma_pmf(8, 8)
>>> pmf.shape
(61,)
>>> round(float(pmf.sum()), 12)
1.0
Source code in src/epidemic_dates/delays.py
def gamma_pmf(mean: float, sd: float, dmax: int = DMAX) -> NDArray[np.float64]:
    r"""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

    $$P(d) = G(d + 1) - 2 G(d) + G(d - 1),$$

    $$G(x) = \int_0^x F(u; k, \theta) \, du
    = x F(x; k, \theta) - k \theta F(x; k + 1, \theta),$$

    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
    ----------
    mean : float
        Mean of the continuous Gamma delay, in days. Must be positive.
    sd : float
        Standard deviation of the continuous Gamma delay, in days. Must
        be positive.
    dmax : int, optional
        Maximum delay. Must be non-negative. Defaults to `DMAX`.

    Returns
    -------
    numpy.ndarray of float
        Probabilities for delays 0..dmax, of length `dmax + 1`, summing
        to 1.

    Raises
    ------
    ValueError
        If `mean` or `sd` is not a positive finite number, or `dmax` is
        negative.

    Examples
    --------
    >>> pmf = gamma_pmf(8, 8)
    >>> pmf.shape
    (61,)
    >>> round(float(pmf.sum()), 12)
    1.0
    """
    if not (math.isfinite(mean) and mean > 0):
        raise ValueError(f"mean must be a positive finite number, got {mean}")
    if not (math.isfinite(sd) and sd > 0):
        raise ValueError(f"sd must be a positive finite number, got {sd}")
    if dmax < 0:
        raise ValueError(f"dmax must be non-negative, got {dmax}")
    shape = (mean / sd) ** 2
    scale = sd**2 / mean

    def integrated_cdf(x: NDArray[np.float64]) -> NDArray[np.float64]:
        x = np.maximum(x, 0.0)
        return np.asarray(
            x * stats.gamma.cdf(x, shape, scale=scale)
            - shape * scale * stats.gamma.cdf(x, shape + 1, scale=scale),
            dtype=np.float64,
        )

    days = np.arange(dmax + 1, dtype=np.float64)
    pmf = np.maximum(
        integrated_cdf(days + 1)
        - 2 * integrated_cdf(days)
        + integrated_cdf(days - 1),
        0.0,
    )
    return pmf / pmf.sum()

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 em_fit. Must be at least 1.

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, em holds it fixed instead of estimating a delay, and imputed also holds forward. Cannot be combined with delay_period.

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 (the default) estimates one static delay. See em_fit.

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_period.

DELAY_SHRINKAGE

Returns:

Type Description
LinelistResult

Daily arrays have length T + 1 and index i is onset day i.

  • complete: onset counts of cases with a known onset.
  • missing_by_report: counts of missing-onset cases by report day.
  • empirical_delay: pooled delay pmf (0..DMAX) of complete cases.
  • em_delay: delay pmf (0..DMAX) used by EM: the static estimate, the pooled estimate with delay_period, or the given delay (its onset-weighted mean if it is a matrix).
  • em_delay_by_period: delay pmf of each period, one row per period.
  • delay_period_start: first onset day of each period.
  • imputed: dict of daily onset counts (complete plus imputed) for backsampling, mean and em, and forward with delay.
  • imputed_before_day0: dict with the expected number of missing-onset cases that backsampling, mean and forward place before day 0.
  • dropped: number of cases dropped.

Raises:

Type Description
ValueError

If the line list is empty, onset and report differ in length, a report day is missing or infinite, a day is not a whole number, cutoff is negative, no complete case is left after dropping, delay is not a valid pmf or matrix of pmfs, delay_period or delay_shrinkage is out of range, or both delay and delay_period are given.

Notes
  • backsampling spreads each missing case over report day minus each delay, weighted by empirical_delay. It is the expected allocation of the random draw, not a draw.
  • mean shifts each missing case back by the mean of empirical_delay, rounded with halves up (as JavaScript's Math.round).
  • em uses em_fit. It estimates a static delay jointly with the onset curve, allowing for right truncation at the cut-off. With delay_period it estimates one delay per period instead, each shrunk towards the previous period's delay. With delay it uses that delay as given and estimates only the onset curve. backsampling and mean always use the pooled empirical delay of the data.
  • forward places 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 for backsampling. 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 DMAX are dropped. They are not imputed.
  • For backsampling and mean, imputed onsets before day 0 are not in imputed, so totals can be below the number of cases kept. The amount is in imputed_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
def 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:
    r"""Impute missing onsets in a real line list.

    Parameters
    ----------
    onset : array_like
        Onset day per case, with NaN (or None) where missing.
    report : array_like of int
        Report day per case. Must have no missing values. Days are
        integers, for example days since the first report.
    cutoff : int, optional
        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.
    n_iter : int, optional
        Number of EM iterations passed to `em_fit`. Must be at least 1.
    delay : array_like of float, optional
        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, `em` holds it fixed instead of estimating a
        delay, and `imputed` also holds `forward`. Cannot be combined
        with `delay_period`.
    delay_period : int, optional
        Length in days of the periods of onset days that get their own
        EM delay, counted back from the cut-off. `None` (the default)
        estimates one static delay. See `em_fit`.
    delay_shrinkage : float, optional
        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_period`.

    Returns
    -------
    LinelistResult
        Daily arrays have length T + 1 and index i is onset day i.

        - `complete`: onset counts of cases with a known onset.
        - `missing_by_report`: counts of missing-onset cases by report
          day.
        - `empirical_delay`: pooled delay pmf (0..DMAX) of complete
          cases.
        - `em_delay`: delay pmf (0..DMAX) used by EM: the static
          estimate, the pooled estimate with `delay_period`, or the given
          `delay` (its onset-weighted mean if it is a matrix).
        - `em_delay_by_period`: delay pmf of each period, one row per
          period.
        - `delay_period_start`: first onset day of each period.
        - `imputed`: dict of daily onset counts (complete plus imputed)
          for `backsampling`, `mean` and `em`, and `forward` with
          `delay`.
        - `imputed_before_day0`: dict with the expected number of
          missing-onset cases that `backsampling`, `mean` and `forward`
          place before day 0.
        - `dropped`: number of cases dropped.

    Raises
    ------
    ValueError
        If the line list is empty, `onset` and `report` differ in
        length, a report day is missing or infinite, a day is not a
        whole number, `cutoff` is negative, no complete case is left
        after dropping, `delay` is not a valid pmf or matrix of pmfs,
        `delay_period` or `delay_shrinkage` is out of range, or both
        `delay` and `delay_period` are given.

    Notes
    -----
    - `backsampling` spreads each missing case over report day minus each delay,
      weighted by `empirical_delay`. It is the expected allocation of
      the random draw, not a draw.
    - `mean` shifts each missing case back by the mean of
      `empirical_delay`, rounded with halves up (as JavaScript's
      `Math.round`).
    - `em` uses `em_fit`. It estimates a static delay jointly with the
      onset curve, allowing for right truncation at the cut-off. With
      `delay_period` it estimates one delay per period instead, each
      shrunk towards the previous period's delay. With `delay` it uses
      that delay as given and estimates only the onset curve. `backsampling` and
      `mean` always use the pooled empirical delay of the data.
    - `forward` places 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 for `backsampling`. 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 `DMAX` are dropped. They are not imputed.
    - For `backsampling` and `mean`, imputed onsets before day 0 are not in
      `imputed`, so totals can be below the number of cases kept. The
      amount is in `imputed_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,)
    """
    prep = _prepare(onset, report, cutoff)
    onset_c, delay_c, report_m = prep.onset, prep.delay, prep.missing_report
    cutoff = prep.cutoff
    n_days = cutoff + 1
    fixed = None if delay is None else as_delay(delay, cutoff)
    complete = np.bincount(onset_c, minlength=n_days)[:n_days].astype(
        np.float64
    )
    missing_by_report = np.bincount(report_m, minlength=n_days)[:n_days].astype(
        np.float64
    )
    empirical = np.bincount(delay_c, minlength=DMAX + 1).astype(np.float64)
    empirical /= empirical.sum()

    backsampled = backsampling_allocate(missing_by_report, empirical)
    shift = round_half_up(float(np.dot(np.arange(DMAX + 1), empirical)))
    mean = mean_shift_allocate(missing_by_report, shift)
    fit = em_fit(
        (onset_c, delay_c),
        report_m,
        cutoff,
        n_iter=n_iter,
        delay=fixed,
        delay_period=delay_period,
        delay_shrinkage=delay_shrinkage,
    )
    n_missing = float(missing_by_report.sum())
    imputed = {
        "backsampling": complete + backsampled,
        "mean": complete + mean,
        "em": complete + fit.allocation,
    }
    before_day0 = {
        "backsampling": max(n_missing - float(backsampled.sum()), 0.0),
        "mean": n_missing - float(mean.sum()),
    }
    if fixed is not None:
        if fixed.ndim == 1:
            forward = backsampling_allocate(missing_by_report, fixed)
        else:
            forward = posterior_allocate(
                missing_by_report, np.ones(n_days), fixed
            )
        imputed["forward"] = complete + forward
        before_day0["forward"] = max(n_missing - float(forward.sum()), 0.0)
    return {
        "complete": complete,
        "missing_by_report": missing_by_report,
        "empirical_delay": empirical,
        "em_delay": fit.delay,
        "em_delay_by_period": fit.delay_by_period,
        "delay_period_start": fit.period_start,
        "imputed": imputed,
        "imputed_before_day0": before_day0,
        "dropped": prep.dropped,
    }

as_delay

as_delay(
    delay: ArrayLike, cutoff: int
) -> NDArray[np.float64]

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 (cutoff + 1, DMAX + 1) matrix, with each pmf renormalised.

Raises:

Type Description
ValueError

If delay is not one- or two-dimensional, a matrix does not have cutoff + 1 rows, or a pmf is not valid (see _as_delay_pmf).

Examples:

>>> as_delay([[1, 1], [0, 1]], cutoff=1).shape
(2, 61)
Source code in src/epidemic_dates/methods.py
def as_delay(delay: ArrayLike, cutoff: int) -> NDArray[np.float64]:
    """Check a supplied delay, static or one pmf per onset day.

    Parameters
    ----------
    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.
    cutoff : int
        Data cut-off day T.

    Returns
    -------
    numpy.ndarray of float
        The pmf on 0..DMAX, or a `(cutoff + 1, DMAX + 1)` matrix, with
        each pmf renormalised.

    Raises
    ------
    ValueError
        If `delay` is not one- or two-dimensional, a matrix does not have
        `cutoff + 1` rows, or a pmf is not valid (see `_as_delay_pmf`).

    Examples
    --------
    >>> as_delay([[1, 1], [0, 1]], cutoff=1).shape
    (2, 61)
    """
    arr = np.asarray(delay, dtype=np.float64)
    if arr.ndim == 1:
        return _as_delay_pmf(arr)
    if arr.ndim != 2:
        raise ValueError("delay must be a pmf or a matrix of pmfs")
    if arr.shape[0] != cutoff + 1:
        raise ValueError(
            "a delay matrix needs one row per onset day 0..cutoff "
            f"({cutoff + 1} rows), got {arr.shape[0]}"
        )
    return np.array([_as_delay_pmf(row) for row in arr])

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 missing_by_report. Mass that falls before day 0 is not included, so the sum can be below missing_by_report.sum().

Source code in src/epidemic_dates/methods.py
def backsampling_allocate(
    missing_by_report: NDArray[np.float64], delay_pmf: NDArray[np.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
    ----------
    missing_by_report : numpy.ndarray of float
        Counts of missing-onset cases by report day 0..T.
    delay_pmf : numpy.ndarray of float
        Delay pmf on 0..D.

    Returns
    -------
    numpy.ndarray of float
        Expected missing-onset cases by onset day 0..T, the same length
        as `missing_by_report`. Mass that falls before day 0 is not
        included, so the sum can be below `missing_by_report.sum()`.
    """
    n_days = missing_by_report.size
    allocation = np.zeros(n_days)
    for delay in range(min(delay_pmf.size, n_days)):
        allocation[: n_days - delay] += (
            missing_by_report[delay:] * delay_pmf[delay]
        )
    return allocation

delay_periods

delay_periods(
    cutoff: int, delay_period: int | None
) -> NDArray[np.int64]

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. None gives one period.

required

Returns:

Type Description
numpy.ndarray of int

Period index (0, 1, ...) of each onset day 0..cutoff.

Raises:

Type Description
ValueError

If delay_period is not a whole number of at least 1.

Examples:

>>> delay_periods(9, 4).tolist()
[0, 0, 1, 1, 1, 1, 2, 2, 2, 2]
Source code in src/epidemic_dates/methods.py
def delay_periods(cutoff: int, delay_period: int | None) -> NDArray[np.int64]:
    """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
    ----------
    cutoff : int
        Data cut-off day T. Must be non-negative.
    delay_period : int or None
        Period length in days, at least 1. `None` gives one period.

    Returns
    -------
    numpy.ndarray of int
        Period index (0, 1, ...) of each onset day 0..cutoff.

    Raises
    ------
    ValueError
        If `delay_period` is not a whole number of at least 1.

    Examples
    --------
    >>> delay_periods(9, 4).tolist()
    [0, 0, 1, 1, 1, 1, 2, 2, 2, 2]
    """
    days = np.arange(cutoff + 1)
    if delay_period is None:
        return np.zeros(cutoff + 1, dtype=np.int64)
    if (
        isinstance(delay_period, bool)
        or not float(delay_period).is_integer()
        or delay_period < 1
    ):
        raise ValueError(
            "delay_period must be a whole number of days of at least 1, "
            f"got {delay_period}"
        )
    period = int(delay_period)
    n_periods = -(-(cutoff + 1) // period)
    return (n_periods - 1 - (cutoff - days) // period).astype(np.int64)

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

(onset_days, delays): integer onset days and delays of complete cases. Onset days must lie in 0..cutoff and delays in 0..DMAX, with onset plus delay <= cutoff.

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 cutoff + 1. Sums to len(missing_report).

Raises:

Type Description
ValueError

If the inputs are invalid. See em_fit.

Source code in src/epidemic_dates/methods.py
def 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
    ----------
    complete : tuple of array_like
        `(onset_days, delays)`: integer onset days and delays of complete
        cases. Onset days must lie in 0..cutoff and delays in 0..DMAX,
        with onset plus delay <= cutoff.
    missing_report : array_like of int
        Report days (0..cutoff) of cases with a missing onset.
    cutoff : int
        Data cut-off day T. Must be non-negative.
    n_iter : int, optional
        Number of EM iterations. Must be at least 1. No convergence
        check is made.

    Returns
    -------
    numpy.ndarray of float
        Expected number of missing-onset cases on each onset day
        0..cutoff, length `cutoff + 1`. Sums to `len(missing_report)`.

    Raises
    ------
    ValueError
        If the inputs are invalid. See `em_fit`.
    """
    return em_fit(complete, missing_report, cutoff, n_iter=n_iter).allocation

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

\[n_a(s, t - s) = m(t) \frac{\lambda(s) f_{k(s)}(t - s)} {\sum_{s'} \lambda(s') f_{k(s')}(t - s')}.\]

M-step: with \(n = n_c + n_a\), alternate three times between

\[\lambda(s) = \frac{\sum_d n(s, d)}{F_{k(s)}\big(\min(T - s, D)\big)}, \qquad f(d) \propto \frac{\sum_s n(s, d)}{\sum_{s \le T - d} \lambda(s)},\]

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\),

\[f_k(d) \propto \frac{N_k(d) + \kappa h_k(d)}{E_k(d) + \kappa}, \qquad h_0 = f, \quad h_k = f_{k-1}, \qquad N_k(d) = \sum_{s \in k} n(s, d), \qquad E_k(d) = \sum_{s \in k,\, s \le T - d} \lambda(s),\]

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

(onset_days, delays): integer onset days and delays of complete cases. Onset days must lie in 0..cutoff and delays in 0..DMAX, with onset plus delay <= cutoff.

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 (cutoff + 1, n_delays)). Entries beyond DMAX are dropped, missing entries up to DMAX are taken as 0 and each pmf is renormalised. Values must be finite and non-negative with a positive sum. Cannot be combined with delay_period.

None
delay_period int

Length in days of the periods with their own delay. None (the default) estimates one static delay. A period at least cutoff + 1 days long gives the same result as None.

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_period.

DELAY_SHRINKAGE

Returns:

Type Description
EMFit

The expected allocation of missing-onset cases by onset day (length cutoff + 1, summing to len(missing_report)), the estimated onset curve, the pooled delay pmf, the delay pmf of each period and the first day of each period. With a two-dimensional delay, each onset day is its own period and delay is the onset-weighted mean of its rows. The onset curve and delays are those after the last M-step; the allocation is from the last E-step.

Raises:

Type Description
ValueError

If the inputs are out of range, not whole numbers, or of mismatched length, if n_iter is below 1, if delay is not a valid pmf, if delay_period or delay_shrinkage is out of range, or if both delay and delay_period are given.

Source code in src/epidemic_dates/methods.py
def 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:
    r"""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

    $$n_a(s, t - s) = m(t) \frac{\lambda(s) f_{k(s)}(t - s)}
    {\sum_{s'} \lambda(s') f_{k(s')}(t - s')}.$$

    M-step: with $n = n_c + n_a$, alternate three times between

    $$\lambda(s) = \frac{\sum_d n(s, d)}{F_{k(s)}\big(\min(T - s, D)\big)},
    \qquad
    f(d) \propto \frac{\sum_s n(s, d)}{\sum_{s \le T - d} \lambda(s)},$$

    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$,

    $$f_k(d) \propto \frac{N_k(d) + \kappa h_k(d)}{E_k(d) + \kappa},
    \qquad
    h_0 = f, \quad h_k = f_{k-1},
    \qquad
    N_k(d) = \sum_{s \in k} n(s, d),
    \qquad
    E_k(d) = \sum_{s \in k,\, s \le T - d} \lambda(s),$$

    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
    ----------
    complete : tuple of array_like
        `(onset_days, delays)`: integer onset days and delays of complete
        cases. Onset days must lie in 0..cutoff and delays in 0..DMAX,
        with onset plus delay <= cutoff.
    missing_report : array_like of int
        Report days (0..cutoff) of cases with a missing onset.
    cutoff : int
        Data cut-off day T. Must be non-negative.
    n_iter : int, optional
        Number of EM iterations. Must be at least 1. No convergence
        check is made.
    delay : array_like of float, optional
        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 `(cutoff + 1, n_delays)`). Entries
        beyond `DMAX` are dropped, missing entries up to `DMAX` are
        taken as 0 and each pmf is renormalised. Values must be finite
        and non-negative with a positive sum. Cannot be combined with
        `delay_period`.
    delay_period : int, optional
        Length in days of the periods with their own delay. `None` (the
        default) estimates one static delay. A period at least
        `cutoff + 1` days long gives the same result as `None`.
    delay_shrinkage : float, optional
        Shrinkage strength $\kappa$, in expected onsets, of each
        period's delay towards the previous period's delay. Must be
        positive. Only
        used with `delay_period`.

    Returns
    -------
    EMFit
        The expected allocation of missing-onset cases by onset day
        (length `cutoff + 1`, summing to `len(missing_report)`), the
        estimated onset curve, the pooled delay pmf, the delay pmf of
        each period and the first day of each period. With a
        two-dimensional `delay`, each onset day is its own period and
        `delay` is the onset-weighted mean of its rows. The onset curve
        and delays are those after the last M-step; the allocation is
        from the last E-step.

    Raises
    ------
    ValueError
        If the inputs are out of range, not whole numbers, or of
        mismatched length, if `n_iter` is below 1, if `delay` is not
        a valid pmf, if `delay_period` or `delay_shrinkage` is out of
        range, or if both `delay` and `delay_period` are given.
    """
    if cutoff < 0:
        raise ValueError(f"cutoff must be non-negative, got {cutoff}")
    if n_iter < 1:
        raise ValueError(f"n_iter must be at least 1, got {n_iter}")
    cutoff = int(cutoff)
    period = delay_periods(cutoff, delay_period)
    shrinkage = _check_shrinkage(delay_shrinkage)
    if delay is not None and delay_period is not None:
        raise ValueError("give either delay or delay_period, not both")
    onset_c = _as_int_days(complete[0], "complete onset days")
    delay_c = _as_int_days(complete[1], "complete delays")
    report_m = _as_int_days(missing_report, "missing_report")
    if onset_c.size != delay_c.size:
        raise ValueError(
            "complete onset days and delays must have the same length"
        )
    if np.any((onset_c < 0) | (onset_c > cutoff)):
        raise ValueError("complete onset days must lie in 0..cutoff")
    if np.any((delay_c < 0) | (delay_c > DMAX)):
        raise ValueError(f"complete delays must lie in 0..{DMAX}")
    if np.any(onset_c + delay_c > cutoff):
        raise ValueError("complete cases must be reported by the cutoff")
    if np.any((report_m < 0) | (report_m > cutoff)):
        raise ValueError("missing_report days must lie in 0..cutoff")

    fixed = None if delay is None else as_delay(delay, cutoff)
    if fixed is not None and fixed.ndim == 2:
        period = np.arange(cutoff + 1, dtype=np.int64)
    n_days = cutoff + 1
    n_complete = np.zeros((n_days, DMAX + 1))
    np.add.at(n_complete, (onset_c, delay_c), 1.0)
    missing = np.bincount(report_m, minlength=n_days)[:n_days].astype(
        np.float64
    )
    if fixed is None:
        start = n_complete.sum(0) + 0.5
        start /= start.sum()
    else:
        start = fixed
    n_cases = missing.sum() + n_complete.sum()
    missing_frac = missing.sum() / n_cases if n_cases > 0 else 0.0
    onsets = n_complete.sum(1) / max(1e-9, 1 - missing_frac) + 0.1
    return _em_iterate(
        n_complete,
        missing,
        cutoff,
        onsets,
        start,
        n_iter,
        fixed is not None,
        period,
        shrinkage,
    )

mean_shift_allocate

mean_shift_allocate(
    missing_by_report: NDArray[float64], shift: int
) -> NDArray[np.float64]

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 missing_by_report. Cases moved before day 0 are not included.

Raises:

Type Description
ValueError

If shift is negative.

Source code in src/epidemic_dates/methods.py
def mean_shift_allocate(
    missing_by_report: NDArray[np.float64], shift: int
) -> NDArray[np.float64]:
    """Move missing-onset cases back from report day by a fixed shift.

    This is the `mean` method.

    Parameters
    ----------
    missing_by_report : numpy.ndarray of float
        Counts of missing-onset cases by report day 0..T.
    shift : int
        Days to move each case back. Must be non-negative.

    Returns
    -------
    numpy.ndarray of float
        Missing-onset cases by onset day 0..T, the same length as
        `missing_by_report`. Cases moved before day 0 are not included.

    Raises
    ------
    ValueError
        If `shift` is negative.
    """
    if shift < 0:
        raise ValueError(f"shift must be non-negative, got {shift}")
    n_days = missing_by_report.size
    allocation = np.zeros(n_days)
    if shift < n_days:
        allocation[: n_days - shift] = missing_by_report[shift:]
    return allocation

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 (T + 1, n_delays).

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
def posterior_allocate(
    missing_by_report: NDArray[np.float64],
    onsets: NDArray[np.float64],
    delay_by_day: NDArray[np.float64],
) -> NDArray[np.float64]:
    r"""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
    ----------
    missing_by_report : numpy.ndarray of float
        Counts of missing-onset cases by report day 0..T.
    onsets : numpy.ndarray of float
        Onset curve $\lambda$ on 0..T.
    delay_by_day : numpy.ndarray of float
        Delay pmf of each onset day, shape `(T + 1, n_delays)`.

    Returns
    -------
    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]
    """
    n_days = missing_by_report.size
    out = np.zeros(n_days)
    n_delays = delay_by_day.shape[1]
    for t in np.flatnonzero(missing_by_report):
        d = np.arange(min(n_delays, t + 1))
        w = onsets[t - d] * delay_by_day[t - d, d]
        if w.sum() <= 0:
            continue
        out[t - d] += missing_by_report[t] * w / w.sum()
    return out

round_half_up

round_half_up(x: float) -> int

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

floor(x + 0.5).

Raises:

Type Description
ValueError

If x is not finite.

Examples:

>>> round_half_up(2.5), round(2.5)
(3, 2)
Source code in src/epidemic_dates/methods.py
def round_half_up(x: float) -> int:
    """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
    ----------
    x : float
        Value to round. Must be finite.

    Returns
    -------
    int
        `floor(x + 0.5)`.

    Raises
    ------
    ValueError
        If `x` is not finite.

    Examples
    --------
    >>> round_half_up(2.5), round(2.5)
    (3, 2)
    """
    if not math.isfinite(x):
        raise ValueError(f"cannot round non-finite value {x}")
    return math.floor(x + 0.5)

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

\[\hat C(s) = \frac{\hat n(s)}{F_s\big(\min(T - s, D)\big)}.\]

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 for max(10, n_iter // 5) iterations, to get \(f_b\) and \(\lambda_b\). With delay_period, \(f_b\) holds one delay per period, refitted in the same way. With a given delay, \(f_b\) is that delay and only \(\lambda_b\) is refitted. Without bootstrap, \(g\), \(f_b = f\) and \(\lambda_b = \lambda\) are fixed.
  • Draw the onsets of the missing cases. backsampling and forward draw \(m(t)\) cases reported on day \(t\) as a multinomial over delays with \(g\) or \(f_b\). em draws 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, forward draws the same way with \(\lambda_b\) constant. mean shifts 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.

"em"
delay array_like of float

Forward delay, used as given for the truncation correction, for forward, and held fixed by em. Either one pmf indexed by delay in days, or a matrix with one pmf per onset day 0..T in its rows. If omitted, it is estimated by em_fit. Entries beyond DMAX are dropped and each pmf renormalised. Cannot be combined with delay_period.

None
n_samples int

Number of samples. Must be at least 1.

1000
seed int

Seed for numpy.random.default_rng.

1
quantiles sequence of float

Quantile levels, each in [0, 1]. Defaults to QUANTILES.

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 (the default) estimates one static delay. See em_fit.

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 impute_linelist), method is unknown, delay is not a valid pmf or matrix of pmfs, both delay and delay_period are given, or n_samples, quantiles, min_reported, n_iter, delay_period or delay_shrinkage are out of range.

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
def 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: dt.date | str | None = None,
    delay_period: int | None = None,
    delay_shrinkage: float = DELAY_SHRINKAGE,
) -> NowcastResult:
    r"""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

    $$\hat C(s) = \frac{\hat n(s)}{F_s\big(\min(T - s, D)\big)}.$$

    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 for `max(10, n_iter // 5)`
      iterations, to get $f_b$ and $\lambda_b$.
      With `delay_period`, $f_b$ holds one delay per period, refitted
      in the same way.
      With a given `delay`, $f_b$ is that delay and only $\lambda_b$ is
      refitted.
      Without `bootstrap`, $g$, $f_b = f$ and $\lambda_b = \lambda$ are
      fixed.
    - Draw the onsets of the missing cases.
      `backsampling` and `forward` draw $m(t)$ cases reported on day
      $t$ as a multinomial over delays with $g$ or $f_b$.
      `em` draws 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, `forward` draws the same way
      with $\lambda_b$ constant.
      `mean` shifts 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
    ----------
    onset : array_like
        Onset day per case, with NaN (or None) where missing.
    report : array_like of int
        Report day per case. Must have no missing values.
    cutoff : int, optional
        Data cut-off day T. Defaults to the last report day.
    method : {"em", "backsampling", "mean", "forward"}, optional
        Imputation method. Defaults to `em`.
    delay : array_like of float, optional
        Forward delay, used as given for the truncation correction, for
        `forward`, and held fixed by `em`. Either one pmf indexed by
        delay in days, or a matrix with one pmf per onset day 0..T in
        its rows. If omitted, it is estimated by `em_fit`. Entries
        beyond `DMAX` are dropped and each pmf renormalised. Cannot be
        combined with `delay_period`.
    n_samples : int, optional
        Number of samples. Must be at least 1.
    seed : int, optional
        Seed for `numpy.random.default_rng`.
    quantiles : sequence of float, optional
        Quantile levels, each in [0, 1]. Defaults to `QUANTILES`.
    min_reported : float, optional
        Smallest fraction reported, $F(T - s)$, for a day to get an
        estimate. Must be in (0, 1].
    bootstrap : bool, optional
        Resample complete cases to include delay uncertainty.
    n_iter : int, optional
        Number of EM iterations for the point fit. Must be at least 1.
    origin : datetime.date or str, optional
        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.
    delay_period : int, optional
        Length in days of the periods of onset days that get their own
        estimated delay, counted back from the cut-off. `None` (the
        default) estimates one static delay. See `em_fit`.
    delay_shrinkage : float, optional
        Strength, in expected onsets, of the shrinkage of each period's
        delay towards the previous period's delay. Must be positive.

    Returns
    -------
    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
    ------
    ValueError
        If the line list is invalid (see `impute_linelist`), `method` is
        unknown, `delay` is not a valid pmf or matrix of pmfs, both
        `delay` and `delay_period` are given, or `n_samples`,
        `quantiles`, `min_reported`, `n_iter`, `delay_period` or
        `delay_shrinkage` are out of range.

    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)
    """
    if method not in NOWCAST_METHODS:
        raise ValueError(
            f"method must be one of {', '.join(NOWCAST_METHODS)}, "
            f"got {method!r}"
        )
    if int(n_samples) != n_samples or n_samples < 1:
        raise ValueError(
            f"n_samples must be a whole number of at least 1, got {n_samples}"
        )
    if n_iter < 1:
        raise ValueError(f"n_iter must be at least 1, got {n_iter}")
    if not (math.isfinite(min_reported) and 0 < min_reported <= 1):
        raise ValueError(f"min_reported must be in (0, 1], got {min_reported}")
    levels = tuple(float(q) for q in quantiles)
    if not levels or any(not (0 <= q <= 1) for q in levels):
        raise ValueError("quantiles must be a non-empty sequence in [0, 1]")
    shrinkage = _check_shrinkage(delay_shrinkage)
    if delay is not None and delay_period is not None:
        raise ValueError("give either delay or delay_period, not both")
    if isinstance(origin, str):
        origin = dt.date.fromisoformat(origin)

    prep = _prepare(onset, report, cutoff)
    cutoff = prep.cutoff
    n_days = cutoff + 1
    fixed = None if delay is None else as_delay(delay, cutoff)
    if fixed is not None and fixed.ndim == 2:
        period = np.arange(n_days, dtype=np.int64)
    else:
        period = delay_periods(cutoff, delay_period)
    varying = int(period[-1]) > 0
    n_samples = int(n_samples)
    complete = np.bincount(prep.onset, minlength=n_days)[:n_days].astype(
        np.float64
    )
    missing = np.bincount(prep.missing_report, minlength=n_days)[
        :n_days
    ].astype(np.float64)
    days_left = np.minimum(cutoff - np.arange(n_days), DMAX)

    def empirical(delays: NDArray[np.int64]) -> NDArray[np.float64]:
        counts = np.bincount(delays, minlength=DMAX + 1).astype(np.float64)
        counts /= counts.sum()
        return counts

    need_em = method == "em" or fixed is None
    fit: EMFit | None = None
    if need_em or varying:
        fit = em_fit(
            (prep.onset, prep.delay),
            prep.missing_report,
            cutoff,
            n_iter=n_iter,
            delay=fixed,
            delay_period=delay_period,
            delay_shrinkage=shrinkage,
        )
    if fixed is not None and fixed.ndim == 1:
        f = fixed
        f_periods = fixed[None, :]
        period_start = np.zeros(1, dtype=np.int64)
    else:
        assert fit is not None
        f, f_periods, period_start = (
            fit.delay,
            fit.delay_by_period,
            fit.period_start,
        )
    f_days = f_periods[period]
    g = empirical(prep.delay)
    reported = np.cumsum(f_periods, axis=1)[period, days_left]
    ok = reported >= min_reported

    if method == "em":
        assert fit is not None
        imputed = complete + fit.allocation
    elif method == "backsampling":
        imputed = complete + backsampling_allocate(missing, g)
    elif method == "forward" and varying:
        flat = np.ones(n_days)
        imputed = complete + posterior_allocate(missing, flat, f_days)
    elif method == "forward":
        imputed = complete + backsampling_allocate(missing, f)
    else:
        shift = round_half_up(float(np.dot(np.arange(DMAX + 1), g)))
        imputed = complete + mean_shift_allocate(missing, shift)
    point = np.where(ok, imputed / np.maximum(reported, 1e-12), np.nan)

    rng = np.random.default_rng(seed)
    n_boot_iter = max(10, n_iter // 5)
    samples = np.full((n_samples, n_days), np.nan)
    n_complete = prep.onset.size
    for b in range(n_samples):
        f_b, g_b, f_b_periods = f, g, f_periods
        lam_b = fit.onsets if fit is not None else None
        if bootstrap:
            idx = rng.integers(0, n_complete, n_complete)
            g_b = empirical(prep.delay[idx])
            if need_em:
                assert fit is not None
                refit = _em_iterate(
                    _complete_matrix(prep.onset[idx], prep.delay[idx], n_days),
                    missing,
                    cutoff,
                    fit.onsets,
                    fit.delay_by_period,
                    n_boot_iter,
                    fixed is not None,
                    period,
                    shrinkage,
                )
                lam_b = refit.onsets
                if fixed is None:
                    f_b, f_b_periods = refit.delay, refit.delay_by_period
        if method == "em":
            assert lam_b is not None
            drawn = _draw_em(missing, lam_b, f_b_periods[period], rng)
        elif method == "backsampling":
            drawn = _draw_backwards(missing, g_b, rng)
        elif method == "forward" and varying:
            drawn = _draw_em(missing, np.ones(n_days), f_b_periods[period], rng)
        elif method == "forward":
            drawn = _draw_backwards(missing, f_b, rng)
        else:
            shift = round_half_up(float(np.dot(np.arange(DMAX + 1), g_b)))
            drawn = mean_shift_allocate(missing, shift)
        n_b = complete + drawn
        rep_b = np.clip(
            np.cumsum(f_b_periods, axis=1)[period, days_left], 1e-12, 1.0
        )
        unseen = np.zeros(n_days)
        pos = ok & (n_b > 0) & (rep_b < 1)
        unseen[pos] = rng.negative_binomial(n_b[pos], rep_b[pos])
        samples[b] = np.where(ok, n_b + unseen, np.nan)

    n_weeks = n_days // 7
    week_start = cutoff + 1 - 7 * (n_weeks - np.arange(n_weeks))
    starts = [int(s) for s in week_start]
    weekly_samples = _weekly(samples, n_weeks)
    point_weekly = _weekly(point, n_weeks)

    def label(day: int) -> object:
        if origin is None:
            return int(day)
        return (origin + dt.timedelta(days=int(day))).isoformat()

    day_labels = [label(s) for s in range(n_days)]
    return {
        "method": method,
        "cutoff": cutoff,
        "dropped": prep.dropped,
        "delay": f,
        "delay_by_period": f_periods,
        "period_start": period_start,
        "reported": reported,
        "point": point,
        "point_weekly": point_weekly,
        "week_start": week_start.astype(np.int64),
        "samples": samples,
        "weekly_samples": weekly_samples,
        "quantiles": levels,
        "daily_quantiles": _quantile_rows(samples, levels, day_labels),
        "weekly_quantiles": _quantile_rows(
            weekly_samples,
            levels,
            [label(s + 6) for s in starts],
            [label(s) for s in starts],
        ),
    }

write_nowcast_csv

write_nowcast_csv(
    result: NowcastResult,
    path: str | PathLike[str],
    by: str = "week",
) -> None

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 nowcast_linelist.

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 by is not week or day.

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
def write_nowcast_csv(
    result: NowcastResult,
    path: str | os.PathLike[str],
    by: str = "week",
) -> None:
    """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
    ----------
    result : NowcastResult
        Output of `nowcast_linelist`.
    path : str or os.PathLike
        File to write.
    by : {"week", "day"}, optional
        Write the weekly or the daily table.

    Raises
    ------
    ValueError
        If `by` is not `week` or `day`.

    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'
    """
    if by == "week":
        rows = result["weekly_quantiles"]
        fields = ["week_start", "target_end_date", "quantile", "value"]
    elif by == "day":
        rows = result["daily_quantiles"]
        fields = ["target_end_date", "quantile", "value"]
    else:
        raise ValueError(f"by must be 'week' or 'day', got {by!r}")
    with open(path, "w", newline="") as fh:
        writer = csv.DictWriter(fh, fieldnames=fields, lineterminator="\n")
        writer.writeheader()
        writer.writerows(rows)

miss_prob

miss_prob(
    name: str, delay: NDArray[int64], report: NDArray[int64]
) -> NDArray[np.float64]

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 SCEN.

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 delay.

required

Returns:

Type Description
numpy.ndarray of float

Probability that each case's onset is missing, same shape as delay.

Source code in src/epidemic_dates/scenarios.py
def miss_prob(
    name: str, delay: NDArray[np.int64], report: NDArray[np.int64]
) -> NDArray[np.float64]:
    """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 : str
        A key of `SCEN`.
    delay : numpy.ndarray of int
        Onset-to-report delay of each case, in days.
    report : numpy.ndarray of int
        Report day of each case. Same shape as `delay`.

    Returns
    -------
    numpy.ndarray of float
        Probability that each case's onset is missing, same shape as
        `delay`.
    """
    if name == "G":
        return 0.2 + 0.5 * np.clip(delay / 20, 0, 1)
    if name == "H":
        return np.interp(report, [0, 60, 100, 1e9], [0.2, 0.2, 0.6, 0.6])
    return np.full(delay.shape, 0.4)

r_path

r_path(name: str, days: int) -> NDArray[np.float64]

Compute the daily growth rate path of a scenario.

Parameters:

Name Type Description Default
name str

A key of SCEN.

required
days int

Number of onset days, L.

required

Returns:

Type Description
numpy.ndarray of float

Growth rate r(t) per day for days 0..days-1.

Raises:

Type Description
ValueError

If name is not a known scenario.

Source code in src/epidemic_dates/scenarios.py
def r_path(name: str, days: int) -> NDArray[np.float64]:
    """Compute the daily growth rate path of a scenario.

    Parameters
    ----------
    name : str
        A key of `SCEN`.
    days : int
        Number of onset days, `L`.

    Returns
    -------
    numpy.ndarray of float
        Growth rate r(t) per day for days 0..days-1.

    Raises
    ------
    ValueError
        If `name` is not a known scenario.
    """
    t = np.arange(days, dtype=np.float64)
    if name == "A":
        return np.full(days, 0.05)
    if name == "B":
        return np.where(t < 60, 0.05, -0.03)
    if name == "B0":
        return np.zeros(days)
    if name in ("C", "G", "H", "I", "Csmall"):
        return np.interp(t, [0, 60, 100, days], [0.05, 0.05, -0.02, -0.02])
    if name == "D":
        return np.where(t < 80, 0.06, -0.04)
    if name == "E":
        return np.full(days, 0.008)
    if name == "F":
        return np.full(days, 0.03)
    if name == "W":
        return np.interp(
            t,
            [0, 30, 50, 90, 105, 135, 150],
            [0.06, 0.06, -0.03, -0.03, 0.05, 0.05, -0.04],
        )
    _check_scenario(name)
    raise ValueError(f"no growth rate path for scenario {name!r}")

scenario_setup

scenario_setup(name: str) -> ScenarioSetup

Build the expected onset curve and delays for a scenario.

Parameters:

Name Type Description Default
name str

A key of SCEN.

required

Returns:

Type Description
ScenarioSetup

Scenario inputs with keys:

  • L: number of onset days.
  • O: expected daily onsets, shape (L,), summing to the target total. Built as exp(cumulative sum of r(t)) and rescaled. In scenario I it is doubled from onset day 70 before rescaling.
  • fmat: forward delay pmf by onset day, shape (L, DMAX + 1). In scenario F the mean (and SD) falls linearly from 12 to 4 days; otherwise every row is F_DEFAULT.
  • cp: change-point week or None.

Raises:

Type Description
ValueError

If name is not a known scenario.

Source code in src/epidemic_dates/scenarios.py
def scenario_setup(name: str) -> ScenarioSetup:
    """Build the expected onset curve and delays for a scenario.

    Parameters
    ----------
    name : str
        A key of `SCEN`.

    Returns
    -------
    ScenarioSetup
        Scenario inputs with keys:

        - `L`: number of onset days.
        - `O`: expected daily onsets, shape (L,), summing to the target
          total. Built as exp(cumulative sum of r(t)) and rescaled. In
          scenario `I` it is doubled from onset day 70 before rescaling.
        - `fmat`: forward delay pmf by onset day, shape (L, DMAX + 1).
          In scenario `F` the mean (and SD) falls linearly from 12 to 4
          days; otherwise every row is `F_DEFAULT`.
        - `cp`: change-point week or `None`.

    Raises
    ------
    ValueError
        If `name` is not a known scenario.
    """
    days, target, change_point = _check_scenario(name)
    growth = r_path(name, days)
    shape = np.exp(np.concatenate([[0], np.cumsum(growth[1:])]))
    if name == "I":
        shape = shape * np.where(np.arange(days) >= 70, 2.0, 1.0)
    expected_onsets = shape * target / shape.sum()
    if name == "F":
        means = np.linspace(12, 4, days)
        fmat = np.array([gamma_pmf(m, m) for m in means])
    else:
        fmat = np.tile(F_DEFAULT, (days, 1))
    return {"L": days, "O": expected_onsets, "fmat": fmat, "cp": change_point}

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 SCEN.

required
setup ScenarioSetup

Output of scenario_setup(name).

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 L - 1 + DMAX.

missing numpy.ndarray of bool

Whether each case's onset is missing.

Raises:

Type Description
ValueError

If name is not a known scenario.

Source code in src/epidemic_dates/scenarios.py
def simulate(
    name: str, setup: ScenarioSetup, rng: np.random.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 : str
        A key of `SCEN`.
    setup : ScenarioSetup
        Output of `scenario_setup(name)`.
    rng : numpy.random.Generator
        Random number generator.

    Returns
    -------
    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 `L - 1 + DMAX`.
    missing : numpy.ndarray of bool
        Whether each case's onset is missing.

    Raises
    ------
    ValueError
        If `name` is not a known scenario.
    """
    _check_scenario(name)
    counts = rng.poisson(setup["O"])
    onset = np.repeat(np.arange(setup["L"]), counts)
    if name == "F":
        cdfs = np.cumsum(setup["fmat"], axis=1)
        u = rng.random(onset.size)
        delay = (u[:, None] > cdfs[onset]).sum(axis=1)
        delay = np.minimum(delay, DMAX)
    else:
        delay = rng.choice(DMAX + 1, size=onset.size, p=F_DEFAULT)
    report = onset + delay
    missing = rng.random(onset.size) < miss_prob(name, delay, report)
    return onset, report, missing

analytic

analytic() -> list[str]

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:

  • for r = 0.05, 0.008 and -0.03, the forward and backward mean delays, the retrospective level factor of backsampling imputed cases, E[exp(-rD)] E[exp(rD)], and of mean imputed cases, exp(rm) E[exp(-rD)], with D ~ F_DEFAULT and m its mean rounded with halves up;
  • the pooled complete-case mean delay in one simulation of scenario A at cut-offs 90 and 179 (seed 1);
  • the mean of the analytic pooled right-truncated pmf under r = 0.05 from day 0 with T = 90, and its total variation distance to the backward pmf.
Source code in src/epidemic_dates/study.py
def analytic() -> list[str]:
    """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
    -------
    list of str
        Lines of text:

        - for r = 0.05, 0.008 and -0.03, the forward and backward mean
          delays, the retrospective level factor of `backsampling`
          imputed cases,
          E[exp(-rD)] E[exp(rD)], and of `mean` imputed cases,
          exp(rm) E[exp(-rD)], with D ~ `F_DEFAULT` and m its mean
          rounded with halves up;
        - the pooled complete-case mean delay in one simulation of
          scenario `A` at cut-offs 90 and 179 (seed 1);
        - the mean of the analytic pooled right-truncated pmf under
          r = 0.05 from day 0 with T = 90, and its total variation
          distance to the backward pmf.
    """
    f = F_DEFAULT
    d = np.arange(DMAX + 1)
    lines = []
    for r in (0.05, 0.008, -0.03):
        mgf_neg = (f * np.exp(-r * d)).sum()
        mgf_pos = (f * np.exp(r * d)).sum()
        backward = f * np.exp(-r * d) / mgf_neg
        shift = round_half_up(float(np.dot(d, f)))
        lines.append(
            f"r={r:+.3f}: forward mean {np.dot(d, f):.2f}, backward mean "
            f"{np.dot(d, backward):.2f}; retrospective back-sampling level "
            "factor for "
            f"imputed cases E[e^-rD]E[e^rD]={mgf_neg * mgf_pos:.3f}; "
            f"mean-shift factor e^(r m)E[e^-rD]="
            f"{np.exp(r * shift) * mgf_neg:.3f}"
        )
    # empirical check under scenario A
    rng = np.random.default_rng(1)
    setup = scenario_setup("A")
    on, rep, mi = simulate("A", setup, rng)
    for cutoff in (90, 179):
        k = (rep <= cutoff) & ~mi
        dd = rep[k] - on[k]
        lines.append(
            f"Scenario A sim, T={cutoff}: pooled complete-case mean delay "
            f"{dd.mean():.2f}"
        )
    # pooled truncated pmf for growth since day 0, T = 90
    cutoff, r = 90, 0.05
    w = np.array([(np.exp(r * np.arange(0, cutoff - x + 1))).sum() for x in d])
    p = f * w / (f * w).sum()
    backward = f * np.exp(-r * d) / (f * np.exp(-r * d)).sum()
    lines.append(
        f"Analytic pooled truncated pmf (A, T=90) mean "
        f"{np.dot(d, p):.2f}; TV distance to backward "
        f"{0.5 * np.abs(p - backward).sum():.4f}"
    )
    return lines

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 SCEN (see DESC).

required
reps int

Number of stochastic replicates. Must be at least 1.

200
seed int

Seed for numpy.random.default_rng.

20261027
cutoffs sequence of int

Data cut-off days, each non-negative. The retrospective cut-off is L - 1 + DMAX, when every case has been reported. Defaults to the retrospective cut-off plus real-time cut-offs 90 and 120 (70 and 90 for A). A cut-off is scored as retrospective only if it equals that day.

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 Csmall).

Always present:

  • scenario, desc, cutoff, retro (1 if retrospective), method, mean_cases (mean cases reported by the cut-off).
  • relbias_mean, relbias_maxabs: mean and maximum absolute relative bias of the replicate-mean weekly count.
  • rel_rmse: root mean square relative error of weekly counts over replicates and weeks (denominator at least 1).
  • gr_bias_meanabs, gr_bias_maxabs: mean and maximum absolute bias in the weekly growth rate (per day). The growth rate is the centred log-linear slope over three weeks of log(count + 0.5).

If the scenario has a change point within the scored weeks:

  • relbias_cp, gr_bias_cp, gr_bias_cp_maxabs: relative bias, growth rate bias and its maximum absolute value within three weeks of the change point.

Retrospective rows only:

  • peak_shift_wk: mean shift of the peak week (estimate minus truth).
  • peak_diff_frac: fraction of replicates with a different peak week.
  • zero_cross_lag_wk: mean lag of the first week (from week 4) with two consecutive negative growth rates (scenarios with a change point only).
  • peak_meancurve_shift: peak shift of the replicate-mean curve.

Real-time rows only:

  • relbias_last2, relbias_last4: relative bias over the last two and four complete weeks.
  • gr_bias_last: growth rate bias in the last week with a centred estimate.

Raises:

Type Description
ValueError

If name is not a known scenario, reps is below 1 or a cut-off is negative.

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
def 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 : str
        A key of `SCEN` (see `DESC`).
    reps : int, optional
        Number of stochastic replicates. Must be at least 1.
    seed : int, optional
        Seed for `numpy.random.default_rng`.
    cutoffs : sequence of int, optional
        Data cut-off days, each non-negative. The retrospective cut-off
        is `L - 1 + DMAX`, when every case has been reported. Defaults
        to the retrospective cut-off plus real-time cut-offs 90 and 120
        (70 and 90 for `A`). A cut-off is scored as retrospective only
        if it equals that day.

    Returns
    -------
    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 `Csmall`).

        Always present:

        - `scenario`, `desc`, `cutoff`, `retro` (1 if retrospective),
          `method`, `mean_cases` (mean cases reported by the cut-off).
        - `relbias_mean`, `relbias_maxabs`: mean and maximum absolute
          relative bias of the replicate-mean weekly count.
        - `rel_rmse`: root mean square relative error of weekly counts
          over replicates and weeks (denominator at least 1).
        - `gr_bias_meanabs`, `gr_bias_maxabs`: mean and maximum absolute
          bias in the weekly growth rate (per day). The growth rate is
          the centred log-linear slope over three weeks of
          log(count + 0.5).

        If the scenario has a change point within the scored weeks:

        - `relbias_cp`, `gr_bias_cp`, `gr_bias_cp_maxabs`: relative bias,
          growth rate bias and its maximum absolute value within three
          weeks of the change point.

        Retrospective rows only:

        - `peak_shift_wk`: mean shift of the peak week (estimate minus
          truth).
        - `peak_diff_frac`: fraction of replicates with a different peak
          week.
        - `zero_cross_lag_wk`: mean lag of the first week (from week 4)
          with two consecutive negative growth rates (scenarios with a
          change point only).
        - `peak_meancurve_shift`: peak shift of the replicate-mean curve.

        Real-time rows only:

        - `relbias_last2`, `relbias_last4`: relative bias over the last
          two and four complete weeks.
        - `gr_bias_last`: growth rate bias in the last week with a
          centred estimate.

    Raises
    ------
    ValueError
        If `name` is not a known scenario, `reps` is below 1 or a
        cut-off is negative.

    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.
    """
    if name not in SCEN:
        raise ValueError(
            f"unknown scenario {name!r}; choose one of {', '.join(SCEN)}"
        )
    if reps < 1:
        raise ValueError(f"reps must be at least 1, got {reps}")
    setup = scenario_setup(name)
    retro_t = setup["L"] - 1 + DMAX
    if cutoffs is None:
        cutoffs = [retro_t, 90, 120] if name != "A" else [retro_t, 70, 90]
    if any(c < 0 for c in cutoffs):
        raise ValueError(f"cutoffs must be non-negative, got {list(cutoffs)}")
    rng = np.random.default_rng(seed)
    fwd = setup["fmat"] if name == "F" else None
    sims = [run_rep(name, setup, rng, cutoffs, fwd) for _ in range(reps)]
    rows: list[SummaryRow] = []
    for cutoff in cutoffs:
        rows += summarise(name, setup, cutoff, sims, cutoff == retro_t)
    return rows

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 name uses seed + i, where i is the position of name in SCEN, so a scenario gives the same results whichever other scenarios are run with it.

20261027
scenarios sequence of str

Keys of SCEN. Defaults to all scenarios (also when empty).

None
verbose bool

Print a line as each scenario finishes.

True

Returns:

Type Description
list of dict

Rows from run_scenario for each scenario, in the order given.

Raises:

Type Description
ValueError

If a scenario name is unknown or reps is below 1.

Source code in src/epidemic_dates/study.py
def 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
    ----------
    reps : int, optional
        Number of replicates per scenario. Must be at least 1.
    seed : int, optional
        Base seed. Scenario `name` uses `seed + i`, where `i` is the
        position of `name` in `SCEN`, so a scenario gives the same
        results whichever other scenarios are run with it.
    scenarios : sequence of str, optional
        Keys of `SCEN`. Defaults to all scenarios (also when empty).
    verbose : bool, optional
        Print a line as each scenario finishes.

    Returns
    -------
    list of dict
        Rows from `run_scenario` for each scenario, in the order given.

    Raises
    ------
    ValueError
        If a scenario name is unknown or `reps` is below 1.
    """
    names = list(scenarios) if scenarios else list(SCEN)
    unknown = [n for n in names if n not in SCEN]
    if unknown:
        raise ValueError(
            f"unknown scenario(s) {unknown}; choose from {', '.join(SCEN)}"
        )
    order = list(SCEN)
    rows: list[SummaryRow] = []
    for name in names:
        rows += run_scenario(name, reps=reps, seed=seed + order.index(name))
        if verbose:
            print(f"done {name}", flush=True)
    return rows

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 SCEN.

required
setup ScenarioSetup

Output of scenario_setup(name).

required
cutoff int

Cut-off day.

required
replicates sequence of dict

Outputs of run_rep, each including cutoff.

required
retro bool

Whether cutoff is the retrospective cut-off. If so, weeks 0..L//7-1 are scored. Otherwise the complete weeks up to the cut-off are scored.

required

Returns:

Type Description
list of dict

One row per method. See run_scenario for the columns.

Source code in src/epidemic_dates/study.py
def 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 : str
        A key of `SCEN`.
    setup : ScenarioSetup
        Output of `scenario_setup(name)`.
    cutoff : int
        Cut-off day.
    replicates : sequence of dict
        Outputs of `run_rep`, each including `cutoff`.
    retro : bool
        Whether `cutoff` is the retrospective cut-off. If so, weeks
        0..L//7-1 are scored. Otherwise the complete weeks up to the
        cut-off are scored.

    Returns
    -------
    list of dict
        One row per method. See `run_scenario` for the columns.
    """
    with warnings.catch_warnings():
        # Weeks at the edges have all-NaN growth rates by design.
        warnings.filterwarnings(
            "ignore", "Mean of empty slice|All-NaN slice", RuntimeWarning
        )
        return _summarise(name, setup, cutoff, replicates, retro)

write_results

write_results(
    rows: Sequence[SummaryRow], out: str | PathLike[str]
) -> None

Write summary rows and analytic checks to a directory.

Parameters:

Name Type Description Default
rows sequence of dict

Summary rows, for example from run_study.

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.

Source code in src/epidemic_dates/study.py
def write_results(
    rows: Sequence[SummaryRow], out: str | os.PathLike[str]
) -> None:
    """Write summary rows and analytic checks to a directory.

    Parameters
    ----------
    rows : sequence of dict
        Summary rows, for example from `run_study`.
    out : str or os.PathLike
        Output directory. Created if needed.

    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.
    """
    keys: list[str] = []
    for r in rows:
        for k in r:
            if k not in keys:
                keys.append(k)
    out_dir = Path(out)
    out_dir.mkdir(parents=True, exist_ok=True)
    with (out_dir / "results.csv").open(
        "w", newline="", encoding="utf-8"
    ) as fh:
        writer = csv.DictWriter(fh, fieldnames=keys)
        writer.writeheader()
        for r in rows:
            writer.writerow(
                {
                    k: (f"{v:.4f}" if isinstance(v, float) else v)
                    for k, v in r.items()
                }
            )
    (out_dir / "analytic.txt").write_text(
        "\n".join(analytic()) + "\n", encoding="utf-8"
    )