Skip to content

ConfigurableEpi API

Reference for the exported API of ConfigurableEpi, generated from docstrings and grouped by layer.

ConfigurableEpi.ConfigurableEpi — Module.

ConfigurableEpi

Configurable compartmental forecasting on AlgebraicEpiMech Petri nets. Three layers:

  • model/: everything that defines a model — the TOML-backed options and InferenceConfig, priors, latent processes, the state layout, vector fields, the observation model, seasonality, ascertainment, weekday effects, initialisation — grouped into an EpiModel.
  • inference/: the three engines built by build_inference and driven by fit_forecast!: UKF + Optimise, PF + Liu-West, EnKF + EKP.
  • output/: forecast rolls, quantiles, backtest tables, routine sample output and data linkage.

Configuration

ConfigurableEpi.DEFAULT_JITTER_FLOOR_FRACTION — Constant.

DEFAULT_JITTER_FLOOR_FRACTION

Minimum Liu-West jitter variance per parameter as a fraction of the prior's unconstrained variance, so a collapsed cloud can re-expand rather than freeze.

ConfigurableEpi.HyperMethodConfig — Type.

The concrete hyperparameter options, for @option fields.

ConfigurableEpi.InitialisationConfig — Type.

The concrete initialisation strategies, for @option fields.

ConfigurableEpi.ReportingModeConfig — Type.

The concrete reporting modes, for @option fields.

ConfigurableEpi.StateFilterConfig — Type.

The concrete filter options, for @option fields: Configurations.jl parses an aliased block into a Union.

ConfigurableEpi.CorrectedObservations — Type.

CorrectedObservations()                               # [observation.corrected]
ThinnedObservations()                                 # [observation.thinned]

corrected fits a nowcast-adjusted count against the model's expected count; thinned fits the raw count against the expected count times that day's reporting fraction.

ConfigurableEpi.Durations — Type.

Durations(; latent = 2.0, infectious = 1.5, immunity = 180.0, obs_progression = 6.6)

Mean durations in days. Erlang stage rates are n_stages / mean. Because observation is attached to the infection event, the reporting delay is the observation chain alone: (n_obs_stages - 1) * obs_progression (the terminal stage is the reset accumulator).

ConfigurableEpi.EKP — Type.

EKP(; n_ensemble, iterations, burnin_iterations, reopt_interval = 1, inflation = 0.0,
    window_length = nothing, warm_start = true, threads = false)   # [hyper.ekp]

Outer ensemble Kalman inversion of the static parameters, each candidate scored by a complete inner filter replay. burnin_iterations at the first origin, iterations when warm-starting from the previous ensemble. threads parallelises candidate replays (not together with filter.enkf.threads).

ConfigurableEpi.EnKF — Type.

EnKF(; n_ensemble, inflation = 1.0, threads = false)  # [filter.enkf]

Augmented ensemble Kalman filter. inflation >= 1 multiplies the ensemble spread after each propagation; threads parallelises member propagation.

ConfigurableEpi.HyperMethod — Type.

Supertype of the hyperparameter-inference options, the [hyper.<name>] axis.

ConfigurableEpi.InferenceConfig — Type.

InferenceConfig(; filter, hyper, step_days, supersample = 2, integrator = "Rk4", n_ahead, n_draws = 2000,
                learn_params = String[], priors = Dict())

The settings of one inference run: the [filter.<name>] and [hyper.<name>] axes, the observation step, the integration substeps and SeeToDee integrator (integrator_type), the forecast horizon and draw count, the parameters to learn and [priors] overriding a model's defaults per key. A run script embeds it as one field of its own run config.

ConfigurableEpi.InitialisationStrategy — Type.

Supertype of how the state at t = 0 is seeded (see initial_seed).

ConfigurableEpi.LiuWest — Type.

LiuWest(; discount = 0.95, jitter_floor_fraction = DEFAULT_JITTER_FLOOR_FRACTION,
        forgetting_memory_days = Dict(), replay_on_revision = true)   # [hyper.liu_west]

Learn static hyperparameters online in the particle cloud by the Liu-West shrink-jitter kernel. forgetting_memory_days (parameter => days) adds Kulhavý forgetting toward the prior, merged over the model's own defaults. replay_on_revision marks whether revised, already-assimilated data should trigger a full replay; the package does not read it.

ConfigurableEpi.NoDayOfWeekConfig — Type.

NoDayOfWeekConfig()                                   # [day_of_week.none]
PluginDayOfWeekConfig(; window_days = 182, exclude_recent_days = 14, fit_policy = "per_origin")
LearnedDayOfWeekConfig()                              # [day_of_week.learned]

Weekday observation effect for daily counts: none, multipliers and per-weekday extra dispersion estimated from history (fit_policy is per_origin or first_vintage), or six zero-sum Helmert coordinates learned by Liu-West.

ConfigurableEpi.Optimise — Type.

Optimise(; reopt_interval = 1, maxiters = 50, maxiters_burnin = 300, window_length = nothing,
         warm_start = true)                          # [hyper.optimise]

Maximise the filter's marginal log-posterior over data replays every reopt_interval origins. maxiters_burnin caps every optimiser stage on the first (and any cold-started) optimisation, maxiters on warm-started ones. window_length scores only the most recent observations from a rolling filter checkpoint. warm_start = false restarts from the configured values each time.

ConfigurableEpi.PF — Type.

PF(; n_particles, threads = true)                    # [filter.pf]

Bootstrap particle filter. threads parallelises particle propagation; a seeded run reproduces exactly for a fixed thread count.

ConfigurableEpi.PeakAtStartInitialisation — Type.

PeakAtStartInitialisation()                           # [initialisation.peak_at_start]
PeakFromHistoryInitialisation()                       # [initialisation.peak_from_history]

peak_at_start assumes the fit starts at a prevalence peak, S/N = 1 / (R0 χ(0)). peak_from_history finds an observed peak in the history and carries its susceptible fraction to the start (peak_anchored_susceptible_fraction), falling back to 1 / R0 without one.

ConfigurableEpi.PriorSpec — Type.

PriorSpec(; mean, std, constraint = "positive")

One parameter's prior as written in TOML; constraint is positive, unit_interval or unconstrained. build_prior turns it into an EKP ParameterDistribution.

ConfigurableEpi.ReportingMode — Type.

Supertype of how a partially reported count enters the likelihood (see build_reporting_observation).

ConfigurableEpi.SeasonalityConfig — Type.

SeasonalityConfig(; mode = "indoor_activity", kappa = 0.8, fallback = "us")

Transmission seasonality: mode is indoor_activity (empirical location curve scaled by kappa ∈ [0, 1], the seasonally forced share of transmission), cosine (learned annual harmonic) or none. fallback (us, none, error) covers a location the climatology lacks.

ConfigurableEpi.SlowModeInitialisation — Type.

SlowModeInitialisation(; boundary_low = 0.3, boundary_high = 0.7,
                       historical_multiplier_logsd = log(2) / 1.645)  # [initialisation.slow_mode]

Reconstruct the susceptible fraction from the incidence observed before the fit starts. The susceptible fraction when that history begins is uniform on [boundary_low, boundary_high], and the historical ascertainment is the initial one times a log-normal multiplier with log-sd historical_multiplier_logsd (by default within a factor of 2 with 90% probability).

ConfigurableEpi.StateFilter — Type.

Supertype of the state-filter options, the [filter.<name>] axis.

ConfigurableEpi.UKF — Type.

UKF(; obs_jitter = 1.0)                               # [filter.ukf]

Unscented Kalman filter. obs_jitter scales the accumulator process-noise whisker that keeps the smoother covariance full-rank.

ConfigurableEpi.build_prior — Method.

build_prior(name, spec::PriorSpec) -> ParameterDistribution

Build one scalar EKP prior from its TOML-backed specification.

ConfigurableEpi.build_priors — Method.

build_priors(specs) -> NamedTuple

name => PriorSpec pairs to a name => ParameterDistribution NamedTuple.

ConfigurableEpi.integrator_type — Method.

integrator_type(name) -> Type{<:AbstractIntegrator}

The SeeToDee integrator called name, such as "Rk4" or "Heun".

ConfigurableEpi.load_prior_specs — Method.

load_prior_specs(path) -> Dict{String, PriorSpec}
load_priors(path) -> NamedTuple

Read a flat priors TOML (one [name] table per parameter).

ConfigurableEpi.normalise_config_dict — Method.

normalise_config_dict(dict) -> Dict{String, Any}

dict with string keys at every level, so an option table built in Julia (symbol keys, possibly empty) parses with from_dict.

ConfigurableEpi.option_alias — Method.

option_alias(x) -> String

The TOML alias of an @option value, e.g. option_alias(UKF()) == "ukf".

ConfigurableEpi.prior_R_eff_bound — Method.

prior_R_eff_bound(priors; chi_max = 1.55, probability = 0.95) -> Float64

Conservative bound on R_eff = R0_baseline * Rt * chi * S/N from marginal prior quantiles (S/N <= 1; a missing prior contributes 1). Pass chi_max = seasonal_forcing_upper_bound(...).

ConfigurableEpi.prior_upper — Method.

prior_upper(spec::PriorSpec; probability = 0.99) -> Float64

Upper quantile of a prior on its constrained scale (moment-matched lognormal for positive).

ConfigurableEpi.resolve_prior_specs — Method.

resolve_prior_specs(cfg::InferenceConfig, default_priors) -> Dict{String, PriorSpec}
resolve_priors(cfg::InferenceConfig, default_priors) -> NamedTuple

A model's default_priors() with the config's [priors] merged over them per key, as specs or as built distributions.

ConfigurableEpi.validate_inference_config — Method.

validate_inference_config(cfg::InferenceConfig) -> cfg

Check what the schema cannot: a positive whole number of step_days, positive counts and the options of both axes.

ConfigurableEpi.validate_initialisation — Method.

validate_initialisation(strategy) -> strategy

Check what the schema cannot: a slow-mode boundary interval inside [0, 1] and a finite, non-negative multiplier log-sd.

Model

ConfigurableEpi.ParameterPriorBundle — Type.

ParameterPriorBundle(priors::NamedTuple; joint = Independent())
ParameterPriorBundle(priors::ParameterDistribution...)

Ordered scalar priors combined into one EKP distribution, coupled by joint (PriorCoupling). constrained_values, unconstrained_values and prior_logpdf map between the optimiser's unconstrained vector and constrained NamedTuples. NamedTuple keys must equal the prior names.

ConfigurableEpi.PriorCoupling — Type.

PriorCoupling
Independent()

How a ParameterPriorBundle combines its scalar priors. Independent() takes their product; a coupling such as RtNBVariancePrior replaces the scalar densities of the parameters it names with a joint one.

ConfigurableEpi.constrained_values — Method.

constrained_values(bundle, unconstrained) -> NamedTuple

Transform an unconstrained optimiser vector to named values on their model scales.

ConfigurableEpi.prior_logpdf — Method.

prior_logpdf(bundle, unconstrained) -> Real

Evaluate the combined prior density in the optimiser's unconstrained coordinates.

ConfigurableEpi.prior_moments — Method.

prior_moments(bundle) -> (mean, covariance)

Mean and covariance of the bundle's prior in the optimiser's unconstrained coordinates.

ConfigurableEpi.prior_name — Method.

prior_name(prior::ParameterDistribution) -> Symbol

Name of a scalar EKP prior. Errors on a combined (multi-name) distribution.

ConfigurableEpi.prior_unconstrained_mean — Method.

prior_unconstrained_mean(prior) -> Float64
prior_unconstrained_variance(prior) -> Float64

Mean and variance of a scalar prior in its unconstrained coordinate, the chart that learned hyperparameters and latent coefficients are stored in.

ConfigurableEpi.sample_prior — Method.

sample_prior(rng, bundle) -> Vector

A draw from the bundle's prior in the optimiser's unconstrained coordinates.

ConfigurableEpi.unconstrained_gaussian — Method.

unconstrained_gaussian(name, mean, sd)
positive_gaussian(name, mean, sd)
unit_interval_gaussian(name, mean, sd)

Scalar EKP constrained_gaussian priors on (-Inf, Inf), (0, Inf) and (0, 1).

ConfigurableEpi.unconstrained_values — Method.

unconstrained_values(bundle, constrained) -> Vector

Transform named model-scale parameter values to the optimiser's unconstrained coordinates.

ConfigurableEpi.RtNBVariancePrior — Type.

RtNBVariancePrior(; transmission_weight, window_days = 30, log_sd_mean = log(0.2),
                  log_sd_std = log(2) / 1.6448536269514722, logit_rt_mean = log(9),
                  logit_rt_std = 1, rt_scale = :Rt_sigma_stat, dispersion = :phi)

A PriorCoupling with independent normal priors on log(sqrt(T)) and logit(f), where T = transmission_weight * rt_scale^2 + 1/dispersion is a local relative variance and f = transmission_weight * rt_scale^2 / T the share of it from transmission. rt_scale and dispersion name the learned Rt scale and negative-binomial dispersion, whose scalar priors it replaces; their constraints must be logs.

transmission_weight is the conditional response variance at the horizon of interest per unit squared Rt scale, and the dispersion adds the relative variance of the negative binomial's gamma multiplier. T is a proxy: it leaves out Poisson variation and ascertainment drift.

ConfigurableEpi.StateLayout — Type.

StateLayout{N, M, L, S}

Layout of the state vector [core compartments (N); observation states (M); latent coefficients (L)] observed through S signals. accumulator_indices are the absolute slots of the reset accumulators, one per signal.

StateLayout(core_names, obs_names, latent_names; signal_names = (:y,), accumulator_indices = nothing)
StateLayout(petri_net, driver_specs; signal_names = nothing, observation_prefixes = (:O,))

Without accumulator_indices the observation states are split evenly over the signals and each signal's last state is its accumulator. The second form reads the observation chains of a net built with AlgebraicEpiMech.attach_observation, one chain namespace per entry of observation_prefixes: a net can carry several chains on one event under distinct prefixes (an incidence chain and a shedding chain, say), listed prefix by prefix. Only drivers with carries_state claim latent slots.

ConfigurableEpi.extract_latent — Method.

extract_latent(state, layout) -> NamedTuple

The latent slots of state as a NamedTuple of unconstrained values.

ConfigurableEpi.AR1ParamSpec — Type.

AR1ParamSpec(name; init, mu, tau, sigma)

Mean-reverting Ornstein–Uhlenbeck latent in the unconstrained chart of init (its initial prior, which also fixes the constraint): u' | u ~ Normal(m + rho (u - m), sigma^2 (1 - rho^2)) with rho = exp(-dt / tau). mu is the constrained stationary mean, tau the correlation time in days and sigma the stationary sd; each may be a Real, a ParameterDistribution (learned under its own name) or a ParamSpec.

ConfigurableEpi.ArrivalProcess — Type.

ArrivalProcess(name; rate, mark, transition!)

A marked point process on the compartments (particle filter only). On each stochastic step it fires with probability 1 - exp(-rate * dt), where rate is a constant or (x_model, latent, hyper, t) -> λ; on firing it draws mark(hyper, rng) -> NamedTuple and applies transition!(x_model, mark, hyper) in place. It carries no state: the compartments record that it fired, so a single-shot arrival is a rate that reads the compartment its own jump seeds.

ConfigurableEpi.FixedParam — Type.

FixedParam(name, value)
HyperParam(prior)
DerivedParam(name, formula)

How a process parameter is resolved from the merged (hyperparams, constrained latents) NamedTuple: a constant, a lookup under the prior's name, or formula(params).

ConfigurableEpi.IntegratedParamSpec — Type.

IntegratedParamSpec(name; init, rate, per_days = 1.0)

Noise-free latent whose unconstrained coordinate advances by rate_value * dt / per_days, where rate_value is the constrained value of the latent or hyperparameter named rate at the start of the step (explicit Euler). With a random-walk rate the pair is an integrated Brownian motion. A negative per_days integrates with the opposite sign.

ConfigurableEpi.RWParamSpec — Type.

RWParamSpec(name; init, sigma_rate)

Driftless random walk in the unconstrained chart; a step of dt days has sd sigma_rate * sqrt(dt).

ConfigurableEpi.StochasticUpdate — Type.

StochasticUpdate{L}

The model's per-step stochastic driver over L coefficient latents, from build_stochastic_update:

  • advance(x, hyper, w, rng, t, dt): the pre-flow state after advancing each coefficient from unit noise w[1:L] and firing each jump driver on rng (rng === nothing skips jumps).
  • extract(x): the coefficients' constrained values as a NamedTuple.
  • extract_params(x, hyper): merge(hyper, extract(x)).
  • to_unconstrained(constrained::NamedTuple): the coefficients as an unconstrained SVector{L}.
  • coefficients: the L state-carrying driver specs in layout order.

ConfigurableEpi.advance_arrival! — Method.

advance_arrival!(process, x_model, latent, hyper, dt, t, rng) -> x_model

Fire one jump driver in place with probability step_arrival_probability(rate, dt).

ConfigurableEpi.assert_gaussian_filter_compatible — Method.

assert_gaussian_filter_compatible(specs)

Throw if any driver is particle-only.

ConfigurableEpi.beta_mark — Method.

beta_mark(; mean_key = :mark_mean, concentration = 1.0, out_key = :mark)

Mark sampler (hyper, rng) -> (; out_key => Beta(μν, (1 - μ)ν)) with mean μ = hyper[mean_key].

ConfigurableEpi.build_stochastic_update — Method.

build_stochastic_update(layout, driver_specs; state_params = Returns((;))) -> StochasticUpdate

Split driver_specs into state-carrying coefficient drivers (which must match layout.latent_names in order) and stateless jump drivers, and build the step driver. Jumps read the pre-step coefficients; the flow then runs on the advanced ones.

state_params(x, hyper, t) -> NamedTuple adds values computed from the pre-step state to the parameters each coefficient's process reads, so a DerivedParam noise scale, mean or correlation time can depend on the compartments.

ConfigurableEpi.carries_state — Method.

carries_state(spec) -> Bool
supports_gaussian_filter(spec) -> Bool

Whether a driver claims latent slots in the StateLayout, and whether a Gaussian (UKF) filter can propagate it. Both hold for the coefficient processes and fail for ArrivalProcess, whose fired/not-fired mixture no single Gaussian represents.

ConfigurableEpi.ou_step — Method.

ou_step(tau, dt) -> (rho, innovation_factor)

Exact one-step OU transition, rho = exp(-dt / tau) and sqrt(1 - rho^2), via expm1 so a very long tau does not cancel to zero.

ConfigurableEpi.pool_redistribute! — Method.

pool_redistribute!(x_model, sources, targets, weights) -> x_model

Pool the mass in sources, empty them, then add weights[k] * pool to targets[k] (weights should sum to 1). Sources and targets may overlap; the pool is read before anything is written.

ConfigurableEpi.pro_rata_move! — Method.

pro_rata_move!(x_model, sources, targets, amount) -> x_model

Move up to amount individuals out of sources[k] into targets[k], split pro rata by each source's occupancy and capped at what is available. sources and targets must be disjoint.

ConfigurableEpi.seed_transition — Method.

seed_transition(model_names, from, into; size_key) -> transition!

Move mark[size_key] individuals from compartment from into into, capped at what from holds.

ConfigurableEpi.step_arrival_probability — Method.

step_arrival_probability(rate, dt) -> Float64

1 - exp(-rate * dt) for a constant hazard rate >= 0 over a step dt > 0.

ConfigurableEpi.update_single — Function.

update_single(spec, old_unc, w, params, dt[, constraint])

Advance one latent's unconstrained coordinate over dt days given unit noise w. params merges the hyperparameters with every latent's constrained value at the start of the step; constraint is spec.init's pre-resolved ScalarConstraint.

ConfigurableEpi.STATE_FLOOR — Constant.

The floor every ODE state is held at before and after a step of build_full_dynamics.

ConfigurableEpi.build_R1 — Method.

build_R1(layout) -> Diagonal

Identity process-noise covariance sized n_latent + n_accumulators; every noise magnitude is applied inside build_full_dynamics.

ConfigurableEpi.build_full_dynamics — Method.

build_full_dynamics(petri_vf!, stochastic, layout; dt = 1.0, supersample = 2, integrator = Rk4,
                    obs_jitter = 1.0) -> dynamics(x, u, p, t, w[, rng])

One filter step of the augmented state: apply the stochastic driver (coefficient noise from w[1:L], jumps on rng), zero the reset accumulators, integrate the flow over dt with integrator(f, dt; supersample), a SeeToDee explicit integrator, then add the accumulator whisker obs_jitter * w[L+1:end]. w has size(build_R1(layout), 1) entries.

ConfigurableEpi.build_petri_vf — Method.

build_petri_vf(pn, rates; defaults = (;), rate_class) -> petri_vf!(du, u, (hyperparams, latent), t)

In-place mass-action vector field of pn whose rates are merge(defaults, rates(latent, hyperparams, t)): defaults holds the fixed rates and the rate function returns only the dynamic ones. Rates are keyed by the rate keys of rate_class, by default the flattened transition names; further keywords go to AlgebraicEpiMech.kinetic_structure.

ConfigurableEpi.build_unified_vf — Method.

build_unified_vf(petri_vf!, layout) -> (x, u, p, t) -> dx

Out-of-place form of the Petri vector field for a SeeToDee integrator, naming the ODE slots of x.

ConfigurableEpi.make_lvector_constructor — Method.

make_lvector_constructor(names) -> x -> LArray{names}(collect(x))

ConfigurableEpi.LinearScale — Type.

LinearScale(latent::Symbol, inner; link = identity)

Mean modifier link(latent[name]) * inner(latent, hyper, t): linear in the linked, constrained value of the named latent. inner is a Real or a (latent, hyper, t) function that must not read latent[name].

ConfigurableEpi.LogNormalNoise — Type.

LogNormalNoise(sigma)

Multiplicative noise y = μ exp(σ v).

ConfigurableEpi.NegBinomialNoise — Type.

NegBinomialNoise(; phi, sigma_mult = 0.0)

Count noise with Var(y) = μ + μ²/φ + (σμ)². The UKF uses the Gaussian approximation with one unit-normal term. A simulated draw is NegativeBinomial(φ, φ/(φ+μ')) about the mean perturbed by a mean-one log-normal, μ' = μ exp(sz − s²/2), with s² = log(1 + σ²φ/(φ+1)) so that the draw has exactly that variance. The mixture has no closed-form density, so the particle filter refuses σ ≠ 0. Each parameter is a Real or a function (latent, hyper, t) -> Real.

ConfigurableEpi.ObservationSpec — Type.

ObservationSpec{R <: RawMean}

One observation: its mean is raw * mean_modifier + baseline, where raw is read from the state as the RawMean kind says, and mean_modifier and baseline are each nothing, a Real or a function (latent, hyper, t) -> Real (an AscertainmentPath, say). Built by SignalObservationSpec, AggregatedSignalSpec, WeightedStateSpec, ShareSignalSpec or LatentObservationSpec.

ConfigurableEpi.PoissonNoise — Type.

PoissonNoise(sigma_mult = nothing)

Poisson count noise y ≈ μ + sqrt(μ) v; with sigma_mult the mean is first perturbed by exp(σ v₁). A simulated draw is that mixture, Poisson(μ exp(σz)); it has no closed-form density, so the particle filter refuses it.

ConfigurableEpi.RawMean — Type.

RawMean

What an observation's mean is read from, before its modifier and baseline. raw_mean(r, x, accumulators) gives it for a resolved kind; resolve_observation resolves a kind against the layout.

ConfigurableEpi.ReportingFractionModifier — Type.

ReportingFractionModifier(inner, fractions)
FullReporting(inner)

Mean modifiers for a partially reported daily count. ReportingFractionModifier multiplies inner by the reporting fraction of each fitted day from t = 0 (missing counts as one); later days, the forecast horizons, are fully reported. FullReporting is inner unchanged. set_reporting_fractions! gives either a new report vintage in place.

ConfigurableEpi.SlotSeries — Type.

SlotSeries(values; step = 1.0)

Mean modifier returning values[k] at the grid slot t = (k - 1) * step, and the last value beyond the series (forecast horizons). A time between slots is an error.

ConfigurableEpi.AggregatedSignalSpec — Method.

AggregatedSignalSpec(signal_indices, noise; mean_modifier = nothing, baseline = nothing, name)
AggregatedSignalSpec(noise; ...)   # the sum of every signal

An observation of the sum of several signals' reset accumulators.

ConfigurableEpi.LatentObservationSpec — Method.

LatentObservationSpec(mean, noise; name)

An observation that reads no compartment: its mean is mean(latent, hyper, t).

ConfigurableEpi.ShareSignalSpec — Method.

ShareSignalSpec(numerator, denominator, noise; mean_modifier = nothing, baseline = nothing, name = :obs_share)

An observation of a share of incidence, Σ_numerator acc / Σ_denominator acc (the H3 fraction of infections, say), usually scaled to counts by a known per-slot total (SlotSeries). The numerator signals must be a subset of the denominator's.

ConfigurableEpi.SignalObservationSpec — Method.

SignalObservationSpec(signal_idx, noise; mean_modifier = nothing, baseline = nothing, name)

An observation of one signal's reset accumulator.

ConfigurableEpi.WeightedStateSpec — Method.

WeightedStateSpec(state_names, weights, noise; mean_modifier = nothing, baseline = nothing, name = :obs_weighted)

An observation of Σ_i weights[i] * max(x[state_names[i]], 0) over named ODE states: the stages of a shedding chain, say, or several signals' accumulators each with its own ascertainment.

ConfigurableEpi.apply_noise — Method.

apply_noise(noise, mean, v, latent, hyper, t)

Gaussian-approximation observation given unit noise v (the UKF measurement).

ConfigurableEpi.build_measurement_logpdf — Method.

build_measurement_logpdf(layout, obs_specs, stochastic; learned = nothing) -> g(x, u, y, p, t)

Particle weighting: the summed exact observation_logpdf of y over the observation specs, skipping a NaN (absent) component. learned (a LearnedHyperparams) lets each particle's own hyperparameters override p.

ConfigurableEpi.build_measurement_model — Method.

build_measurement_model(layout, obs_specs, stochastic) -> (; measure, n_obs, n_noise)
build_measurement_model(layout, noise::ObservationNoiseSpec, stochastic)

The UKF measurement measure(x, u, p, t, v) -> SVector{n_obs} with unit noise v of length n_noise (so R2 = I). The second form observes the single signal of a one-signal layout.

ConfigurableEpi.build_reporting_observation — Method.

build_reporting_observation(mode::ReportingMode, inner, fractions)

The mean modifier for a reporting mode: FullReporting for CorrectedObservations, or a ReportingFractionModifier for ThinnedObservations, which needs the fractions.

ConfigurableEpi.observation_mean — Method.

observation_mean(spec, raw, latent, hyper, t)      # raw * modifier + baseline
observation_scale(spec, latent, hyper, t)          # the modifier at `t`
observation_baseline(spec, latent, hyper, t)       # the baseline at `t`

Reporting code must map accumulators to counts through these, never through a hyperparameter read directly, so a time-varying or latent-driven ascertainment is honoured.

ConfigurableEpi.resolve_observation — Method.

resolve_observation(spec, layout) -> spec

spec checked against layout: signal indices in range, an all-signals sum expanded and state names turned into slots. The measurement builders resolve every spec.

ConfigurableEpi.set_reporting_fractions! — Method.

set_reporting_fractions!(modifier, fractions) -> modifier

Replace a ReportingFractionModifier's fractions in place, so a persistent engine sees a new report vintage; the identity for FullReporting.

ConfigurableEpi.N_SEASON_KNOTS — Constant.

Knots per indoor_activity climatology curve: one per week of the year.

ConfigurableEpi.UnitForcing — Type.

UnitForcing()
CosineForcing(day0)
IndoorActivityForcing(curve, u0)

The three forcings: flat 1.0; the annual harmonic 1 + hyper.seasonal_amp * cos(2π (t + day0 - hyper.seasonal_phase) / 365.25) with day0 the day-of-year of t = 0; and 1 + hyper.seasonal_kappa * (σ(t) - 1) with σ a unit-mean periodic spline through a location's climatology and u0 the year fraction of t = 0.

ConfigurableEpi.assert_seasonal_learnable — Function.

assert_seasonal_learnable(cfg::SeasonalityConfig, learn_params, prior_specs = nothing)

Reject learning a seasonality parameter the active mode never reads (an unidentified dimension), and require a unit_interval prior when seasonal_kappa is learned.

ConfigurableEpi.build_periodic_curve — Method.

build_periodic_curve(knots) -> CubicSpline

Unit-mean periodic cubic spline through knots, knot k at u = (k - 0.5) / N within the year. Periodicity comes from tiling five years and evaluating in the central one (the interpolant's own periodic extrapolation repeats with period (N-1)/N); the annual mean is normalised by the analytic integral.

ConfigurableEpi.build_seasonal_forcing — Method.

build_seasonal_forcing(cfg::SeasonalityConfig, location, start_date::Date; climatology = nothing)
build_seasonal_forcings(cfg, locations, start_date; climatology = nothing) -> Vector

The forcing selected by cfg, anchored so model time t = 0 is start_date. climatology (Dict(location => 52 knots)) is required by indoor_activity. The result type depends on the mode, so specialise the vector field on it through a where {F} function barrier.

ConfigurableEpi.default_seasonal_learned — Method.

default_seasonal_learned(cfg::SeasonalityConfig) -> Vector{Symbol}

Seasonality parameters learned by default: the cosine's amplitude and phase, nothing otherwise (kappa scales an externally estimated curve, so it is opt-in via learn_params).

ConfigurableEpi.load_indoor_activity_climatology — Method.

load_indoor_activity_climatology(path) -> Dict{String, Vector{Float64}}

Read a location,knot,value table of 52-knot, unit-mean curves (lowercase location keys, us included). The package ships no data; the caller owns this file.

ConfigurableEpi.seasonal_forcing_upper_bound — Function.

seasonal_forcing_upper_bound(cfg, fixed_amp, prior_specs, learn_params = ();
                             probability = 0.95, climatology = nothing) -> Float64

Mode-aware upper bound on the seasonal multiplier for the integration stability guard: 1 for none, 1 + |amplitude| for cosine (from the prior when learned), and the largest curve value in climatology scaled by the fixed or learned kappa for indoor_activity. An empty learn_params means the mode's default learned set.

ConfigurableEpi.validate_indoor_activity_climatology — Method.

validate_indoor_activity_climatology(climatology; source = "supplied climatology")

Check that every (lowercase) location carries N_SEASON_KNOTS finite, positive knots with mean 1.

ConfigurableEpi.validate_seasonality — Method.

validate_seasonality(cfg::SeasonalityConfig) -> cfg

Check the mode, the fallback and kappa ∈ [0, 1] (the seasonally forced share of transmission).

ConfigurableEpi.year_fraction — Method.

Position of d within its year in [0, 1), leap-aware.

ConfigurableEpi.ASCERTAINMENT_TREND_LEVEL — Constant.

Latent name of the ascertainment level (observations per infection now); positive, stored as log alpha.

ConfigurableEpi.ASCERTAINMENT_TREND_LEVEL_LOG_SD — Constant.

Initial spread of the level in log units (pinned: the level is not identifiable alongside transmission).

ConfigurableEpi.ASCERTAINMENT_TREND_RATE — Constant.

Latent name of the decline rate per year; the same name (and prior) as the declining path's hyperparameter.

ConfigurableEpi.ASCERTAINMENT_TREND_WANDER — Constant.

Hyperparameter name of the trend's bend scale; see DEFAULT_ASCERTAINMENT_TREND_WANDER.

ConfigurableEpi.DEFAULT_ASCERTAINMENT_TREND_WANDER — Constant.

The 1-sd departure of log-ascertainment from a straight line after one year, in log units: too stiff to mimic a wave, loose enough for the rate to re-diversify over a season.

ConfigurableEpi.DEFAULT_ASCERTAINMENT_TREND_WANDER_MEMORY_DAYS — Constant.

Memory (days) of the Kulhavý forgetting applied to a learned wander: a season and a half.

ConfigurableEpi.AscertainmentPath — Type.

AscertainmentPath(floor_fraction, t_ref_days, rate_bound = Inf)
AscertainmentPath(; floor_fraction, reference_date::Date, start_date::Date, rate_bound = Inf)

Callable (hyper, t) and (latent, hyper, t) giving observations per infection at model time t,

alpha(t) = level * (1 + (1 - floor_fraction) * expm1(-rate * (t - t_ref_days) / 365.25))

with level = hyper.ascertainment and rate = clamp(hyper.ascertainment_decline_rate, ±rate_bound) read on every call, so a learned rate reaches each particle or optimiser candidate. A zero rate returns level bit-for-bit. Use it as an observation spec's mean_modifier and as t -> path(hyper, t) in the initial-state inversion.

ConfigurableEpi.TrendAscertainment — Type.

TrendAscertainment()

The trend model's observation mean_modifier: (latent, hyper, t) -> latent.ascertainment_level.

ConfigurableEpi.TrendAscertainmentSeed — Type.

TrendAscertainmentSeed(level0, decline_rate)

t -> level0 * exp(-decline_rate * t / 365.25) for the initial-state inversion, which evaluates ascertainment at and before t = 0.

ConfigurableEpi.ascertainment_at — Method.

ascertainment_at(level, floor_fraction, rate, days_since_ref)

The path's kernel, level * (1 + (1 - floor_fraction) * expm1(-rate * days_since_ref / 365.25)).

ConfigurableEpi.ascertainment_trend_sigma_rate — Method.

ascertainment_trend_sigma_rate(wander) -> Float64

The rate's random-walk diffusion per sqrt-day that makes the level's one-year departure from a straight line equal wander: wander * sqrt(3 / 365.25).

ConfigurableEpi.ascertainment_trend_specs — Method.

ascertainment_trend_specs(; rate_prior, level0) -> (rate_spec, level_spec)

The trend model's two drivers: the decline rate as a random walk whose diffusion derives from the ascertainment_trend_wander hyperparameter, and the level as the noise-free integral of -rate per year. rate_prior must be named ascertainment_decline_rate.

ConfigurableEpi.assert_ascertainment_learnable — Method.

assert_ascertainment_learnable(fixed, learn_params)

Refuse to learn the decline rate when ascertainment_floor_fraction == 1, where the path never reads it.

ConfigurableEpi.build_ascertainment_path — Method.

build_ascertainment_path(fixed, start_date::Date) -> AscertainmentPath

Anchor a submodel's ascertainment block so model time t = 0 is start_date.

ConfigurableEpi.parse_ascertainment_reference_date — Method.

parse_ascertainment_reference_date(value) -> Date

Parse the ISO YYYY-MM-DD reference date carried as a string in the epi config.

ConfigurableEpi.validate_ascertainment — Method.

validate_ascertainment(fixed)

Check the ascertainment, ascertainment_decline_rate, ascertainment_floor_fraction, ascertainment_rate_bound and ascertainment_reference_date fields of a submodel's fixed config.

ConfigurableEpi.DayOfWeekModifier — Type.

DayOfWeekModifier(inner, dow0, weights)

An observation mean_modifier equal to inner(hyper, t) * w_{d(t)}, callable as (hyper, t) and (latent, hyper, t). weights::NTuple{7} is the plugin effect; weights = nothing reads the learned multipliers from hyper.dow_z1 … dow_z6.

ConfigurableEpi.HyperPhi — Type.

HyperPhi()                            # (latent, hyper, t) -> hyper.phi
DayOfWeekDispersion(dow0, extra_var)  # (latent, hyper, t) -> 1 / (1/hyper.phi + extra_var[d(t)])

The negative-binomial dispersion without and with the plugin's per-weekday widening.

ConfigurableEpi.assert_day_of_week_learnable — Method.

assert_day_of_week_learnable(cfg::DayOfWeekConfig, learn_params)

The weekday coordinates in an explicit learned set must be exactly day_of_week_learned_names(cfg).

ConfigurableEpi.build_day_of_week_observation — Method.

build_day_of_week_observation(cfg, inner, start_date, history; phi, precomputed = nothing)
    -> (; modifier, dispersion, effects, derived_hyperparameters)

The observation pieces for weekday effect cfg: the mean_modifier (inner itself under NoDayOfWeekConfig), the NB dispersion function, the plugin's history estimates to report, and the learned multipliers to summarise. history is (; times, counts) on the model clock; precomputed reuses a first-vintage plugin estimate.

ConfigurableEpi.day_of_week_learned_names — Method.

The θ names this effect adds to the learned set: the six Helmert coordinates under learned.

ConfigurableEpi.day_of_week_multipliers — Method.

day_of_week_multipliers(hyper) -> NTuple{7}

The learned weekday multipliers Monday … Sunday, 7 * softmax(H z) (shifted by the maximum so a large coordinate cannot overflow).

ConfigurableEpi.day_of_week_report_rows — Method.

day_of_week_report_rows(effects) -> Tuple of (parameter, statistic, value)

Summary rows for the plugin's estimates: dow_multiplier_<day> and dow_extra_var_<day>.

ConfigurableEpi.day_of_week_weight — Method.

day_of_week_weight(modifier, hyper, t)

The weekday factor alone at observation time t; true for a modifier without one.

ConfigurableEpi.dow_helmert_prior_sd — Method.

Prior sd of each Helmert coordinate that gives every centred weekday log-effect marginal sd sd.

<a id='ConfigurableEpi.estimate_day_of_week_effects-Tuple{AbstractVector{Dates.Date}, AbstractVector{<:Union{Missing, Real}}}'> <a id='ConfigurableEpi.estimate_day_of_week_effects-Tuple{AbstractVector{Dates.Date}, AbstractVector{<:Union{Missing, Real}}}-1'> ConfigurableEpi.estimate_day_of_week_effects — Method.

estimate_day_of_week_effects(dates, counts; phi, window_days = 182, exclude_recent_days = 14,
                             min_weeks = 4) -> (; weights, extra_var, fallback, n_used)

Multiplicative weekday decomposition of a daily series against a leave-one-out centred weekly baseline: weights w_d = 7 q_d / (6 + q_d) from the ratio of sums q_d = Σy / Σb, normalised to mean 1, and per-weekday extra variance s_d² after removing the Poisson/NB sampling variance of the counts and of the baseline. dates is the complete daily grid; a day with no report is a missing count, and only centres whose whole leave-one-out week is observed are used. Falls back to no effect (with a warning) when any weekday has fewer than min_weeks usable days.

<a id='ConfigurableEpi.prepare_day_of_week_history-Tuple{AbstractVector{Dates.Date}, AbstractVector{<:Union{Missing, Real}}, Dates.Date}'> <a id='ConfigurableEpi.prepare_day_of_week_history-Tuple{AbstractVector{Dates.Date}, AbstractVector{<:Union{Missing, Real}}, Dates.Date}-1'> ConfigurableEpi.prepare_day_of_week_history — Method.

prepare_day_of_week_history(dates, counts, report_date) -> (; dates, counts)

Check one daily as-of series ends on report_date - 1 and is a gap-free daily grid (a day with no report is a missing count), and drop its final slot (the model's history contract).

ConfigurableEpi.remove_day_of_week_effect — Method.

remove_day_of_week_effect(history, modifier, hyper) -> history

Divide each historical count by the weekday weight of its own observation date so the initial-state reconstruction inverts with ascertainment alone.

ConfigurableEpi.validate_day_of_week — Method.

validate_day_of_week(cfg::DayOfWeekConfig) -> cfg

The plugin window must hold at least five weeks; other modes have nothing to check.

ConfigurableEpi.STABILITY_HEADROOM — Constant.

How far below its stability limit a substep is warned about.

ConfigurableEpi.IntegrationBounds — Type.

IntegrationBounds(durations; n_E = 1, n_I = 1, R_eff_max = 1.0, extra_rates = ())

The rates an ODE substep must integrate: the Erlang stages of durations, transmission at up to R_eff_max (size it from the priors' upper tail with prior_R_eff_bound, not the endemic seed), and extra_rates a model adds outside the shared durations, such as a second observation chain's stage rate.

ConfigurableEpi.SeedContext — Type.

SeedContext(; durations, population, bin_days, ascertainment, history = nothing, first_count = nothing,
            R0 = nothing, chi_at = Returns(1.0), n_E = 1, n_I = 1, n_obs = 1)

What initial_seed reads. history = (; times, counts) is on the model clock with each count labelled by the end of its bin_days bin; first_count is the first fitted count. ascertainment is a constant or t -> observations per infection, chi_at(t) the seasonal forcing, and n_obs counts the observation stages including the reset accumulator.

ConfigurableEpi.anchor_is_exact — Method.

Whether R_eff = 1 holds exactly at the peak of E + I: only for a single I stage.

ConfigurableEpi.assert_integration_stable — Method.

assert_integration_stable(bounds::IntegrationBounds, dt, supersample; integrator = Rk4,
                          limit = stability_limit(integrator)) -> lambda_h

Error at the integrator's stability_limit and warn within STABILITY_HEADROOM of it. An integrator without a known limit needs limit.

<a id='ConfigurableEpi.carry_susceptible-Tuple{Real, Real, Real, AbstractVector{<:Real}, AbstractVector{<:Real}, Real}'> <a id='ConfigurableEpi.carry_susceptible-Tuple{Real, Real, Real, AbstractVector{<:Real}, AbstractVector{<:Real}, Real}-1'> ConfigurableEpi.carry_susceptible — Method.

carry_susceptible(s_anchor, t_anchor, t_target, times, daily_incidence, omega) -> Float64

Integrate ds/dt = omega (1 - s) - i(t) from the anchor to the target time (midpoint RK2, steps of at most one day), holding the per-capita incidence flat outside its range.

ConfigurableEpi.chain_stage_seed — Method.

chain_stage_seed(inflow, growth_rate, rate, n_stages) -> Vector{Float64}

Occupancy of an n_stages Erlang chain progressing at rate and fed by inflow · exp(g t) for all t ≤ 0: stage k holds inflow / (rate + g) · (rate / (rate + g))^(k − 1), which at g = 0 is the quasi-steady fill inflow / rate. An empty chain constrains nothing.

ConfigurableEpi.deterministic_spinup — Method.

deterministic_spinup(petri_vf!, layout, x_ode, hyper, latent_at, t_from, t_to;
                     dt = 1.0, supersample = 2, integrator = Rk4, keep_accumulators = false) -> Vector

Integrate the ODE state from t_from to t_to in supersample substeps per dt of a SeeToDee explicit integrator, the latents held on the path latent_at(t) rather than filtered. Reset accumulators are zeroed each dt step, as in a filter step, and at the end unless keep_accumulators, which leaves them holding the last step's flow. States are floored at zero, not STATE_FLOOR, so an empty compartment stays empty.

<a id='ConfigurableEpi.find_observed_peak-Tuple{AbstractVector{<:Real}}'> <a id='ConfigurableEpi.find_observed_peak-Tuple{AbstractVector{<:Real}}-1'> ConfigurableEpi.find_observed_peak — Method.

find_observed_peak(counts; window = 5, min_prominence = 1.1) -> Union{Int, Nothing}

Index of the observed wave peak: an interior, strict maximum of the log-smoothed series at least min_prominence above the higher flank. nothing when the history contains no identified peak.

ConfigurableEpi.initial_infection_state — Method.

initial_infection_state(y0, dur::Durations, ascertainment, accumulation_window_days)
    -> (; daily_incidence, exposed, infectious, obs_stage)

Invert one partially ascertained count into quasi-steady compartment occupancies: daily_incidence = y0 / (ascertainment * accumulation_window_days) and each upstream compartment holds daily_incidence * mean_duration.

ConfigurableEpi.initial_seed — Function.

initial_seed(strategy::InitialisationStrategy, ctx::SeedContext) -> NamedTuple

The state at t = 0 as fractions and stage fills: susceptible_fraction, the stage occupancies exposed, infectious and observation (the in-transit reporting stages), first_observation_accumulator, and the infection stream infection_rate · exp(growth_rate t) they were filled from, which seeds any further chain through chain_stage_seed.

The peak strategies invert first_count into a flat stream and prime the accumulator with that count's infections. SlowModeInitialisation fits the stream to the last three bins of a history that ends before t = 0, primes the accumulator with the extrapolated bin before it, and also returns susceptible_variance and the terms of its susceptible fraction, boundary_survival and kernel. PeakFromHistoryInitialisation also returns its anchor.

ConfigurableEpi.max_transition_rate — Method.

max_transition_rate(bounds::IntegrationBounds) -> Float64

The fastest rate in 1/day: the Erlang stage rates, observation progression, waning, the faster eigenvalue of the linearised (E, I) block at R_eff_max, and the extra rates.

ConfigurableEpi.peak_anchored_susceptible_fraction — Method.

peak_anchored_susceptible_fraction(history, dur, n_obs_stages, ascertainment, pop, dt, chi_at, R0;
                                   n_E = 1, n_I = 1) -> Union{NamedTuple, Nothing}

Find the observed peak in history = (; times, counts) (model clock, bin-end labels), shift it back by half a bin and the reporting delay and forward by the prevalence lag, evaluate S/N = 1 / (R0 * chi_at(t_anchor)) there (R_eff = 1 at the prevalence peak, Rt = 1 by construction), and carry S/N back to t = 0 against the reconstructed incidence. ascertainment is a constant or t -> observations per infection. Returns nothing when no peak is identified or the anchor is inexact (n_I > 1).

ConfigurableEpi.prevalence_peak_lag_days — Function.

prevalence_peak_lag_days(dur::Durations, n_E = 1, n_I = 1) -> Float64

How long after the incidence peak total infected prevalence peaks: the normalised mean E[T²] / (2 E[T]) of the Erlang residence kernel.

ConfigurableEpi.reporting_delay_days — Method.

reporting_delay_days(dur::Durations, n_obs_stages) -> Float64

Mean infection-to-report delay, (n_obs_stages - 1) * obs_progression.

ConfigurableEpi.required_supersample — Method.

required_supersample(bounds::IntegrationBounds, dt; integrator = Rk4, limit = stability_limit(integrator),
                     target = limit / STABILITY_HEADROOM) -> Int

The smallest supersample whose substep keeps |lambda * h| <= target.

ConfigurableEpi.stability_limit — Function.

stability_limit(integrator::Type{<:AbstractIntegrator}) -> Union{Float64, Nothing}

The largest |lambda * h| on the negative real axis at which a SeeToDee integrator is stable: 2 for ForwardEuler and Heun, 2.513 for Rk3 and 2.785 for Rk4; nothing for any other.

ConfigurableEpi.BinnedIncidence — Type.

BinnedIncidence(edges, rates)

Infections per day into each cell, piecewise constant: rates[c, b] holds over [edges[b], edges[b + 1]) and the rate is zero outside the bins.

ConfigurableEpi.InfectionRoutes — Type.

InfectionRoutes(cells, source, targets, cell, weight)

The distinct ways a host enters infection: for route k its source compartment, the compartments it feeds (targets[k], the first infected stage and any observation chain), the index cell[k] into cells of the incidence that drives it, and its relative susceptibility weight[k]. Read off a net by infection_routes.

ConfigurableEpi.ReplayModel — Type.

ReplayModel(vf!, replay_vf!, layout, routes)
ReplayModel(pn, layout, rates; cells, cell, weight = Returns(1.0), is_infection = is_infection_transition,
            defaults = (;), structure_kwargs...)

A model's vector field, the same field with its infection transitions off, its layout and its InfectionRoutes. The second form builds them from the net with build_petri_vf, build_replay_vf and infection_routes.

ConfigurableEpi.build_replay_vf — Method.

build_replay_vf(pn, rates; is_infection = is_infection_transition, defaults = (;), structure_kwargs...)
    -> petri_vf!

build_petri_vf with the rate keys of every infection transition set to zero. A key that also serves another transition, or is fixed, cannot be switched off and is an error.

ConfigurableEpi.infection_routes — Method.

infection_routes(pn, layout; cells, cell, weight = Returns(1.0), is_infection = is_infection_transition)
    -> InfectionRoutes

Each infection transition (by default a transmission… or importation… one) moves one host from a source compartment into its net products, outputs less inputs counted with multiplicity, so an infector on both sides drops out; transitions sharing a source and products are one route. cell(name), one of cells, and weight(name) must agree across a route.

ConfigurableEpi.replay_scale_moments — Method.

replay_scale_moments(replay_at, logsd; relative_step = 1.0e-3) -> (; mean, sensitivity, covariance)

Moments of a replayed state when the history is 1 / m times the central one, m log-normal with median 1 and log-sd logsd (the historical_multiplier_logsd of SlowModeInitialisation). replay_at(scale) is the state at one scale; linear about its mean, the state has a rank-one covariance along sensitivity, its central-difference derivative in the scale.

ConfigurableEpi.replay_state — Method.

replay_state(model::ReplayModel, incidence, x_start, hyper, latent_at, t_from, t_to;
             scale = 1.0, dt = 1.0, supersample = 2, integrator = Rk4, keep_accumulators = false) -> Vector

The ODE state at t_to from x_start at t_from, integrated as deterministic_spinup does but with model.replay_vf!: infections enter cell c at scale × incidence, averaged over each substep, and leave its susceptible classes in proportion to weight × occupancy. An incidence that would draw a compartment below zero in a substep is an error. The state inherits no transmission parameter; the influence of x_start decays at the slowest waning rate.

ConfigurableEpi.closed_loop_start — Method.

closed_loop_start(model::ReplayModel, x_from, hyper, latent_of, closing; window, accumulate_days, fast,
                  conserve = identity, per_infection = nothing, supersample = 2, integrator = Rk4,
                  first_guess = 1.0, refinements = 2, lower = 0.1, upper = 10.0) -> (; state, multiplier, scale, growth)

Run the model itself over the last window days from x_from, with the latents held at latent_of(m), and set two things against closing (closing_incidence):

  • the transmission multiplier m, so the infection rate grows at closing.growth over the last accumulate_days, by refinements secant steps;
  • the fast compartments, scaled together by scale so the infection rate at the start is closing.rate; conserve(state) returns the difference to the slow compartments.

The reset accumulators hold the flow over the last accumulate_days.

ConfigurableEpi.closing_incidence — Method.

closing_incidence(incidence; per_infection = nothing) -> (; rate, growth)

Infections per day over all cells at the history's last edge, and their growth per day: the growth between the last two bins, continued from the last bin's midpoint. With per_infection by cell the rate is in the signal's units, which the signal fixes whatever the split over cells.

<a id='ConfigurableEpi.history_closure-Tuple{BinnedIncidence, AbstractVector{<:Real}, AbstractVector{<:Real}, AbstractVector{<:Real}}'> <a id='ConfigurableEpi.history_closure-Tuple{BinnedIncidence, AbstractVector{<:Real}, AbstractVector{<:Real}, AbstractVector{<:Real}}-1'> ConfigurableEpi.history_closure — Method.

history_closure(incidence, per_infection, ends, counts; delay, interval = 7.0) -> (; reported, implied, ratio)

A reconstructed history pushed back through the observation level: implied[k] is Σ_c per_infection[c] × its infections over the interval ending at ends[k] - delay, and ratio is sum(counts) / sum(implied). A ratio far from 1 says the history's level and the observation level disagree, which a fit would resolve silently by infecting a different number of people.

ConfigurableEpi.log_growth_rate — Method.

log_growth_rate(counts; interval = 1.0) -> Float64

Least-squares slope of log(counts) per unit time over counts interval apart; zero with fewer than two counts or any not positive.

ConfigurableEpi.matched_transmission_multiplier — Method.

matched_transmission_multiplier(rate_at, target; lower = 0.1, upper = 10.0) -> Real

The multiplier m at which rate_at(m), affine in m, equals target, clamped to [lower, upper]; 1 when transmission contributes nothing.

<a id='ConfigurableEpi.signal_incidence-Tuple{AbstractVector{<:Real}, AbstractVector{<:Real}, AbstractVector{<:Real}, AbstractVecOrMat{<:Real}}'> <a id='ConfigurableEpi.signal_incidence-Tuple{AbstractVector{<:Real}, AbstractVector{<:Real}, AbstractVector{<:Real}, AbstractVecOrMat{<:Real}}-1'> ConfigurableEpi.signal_incidence — Method.

signal_incidence(ends, counts, per_infection, split; delay, interval = 7.0, growth_points = 4,
                 until = 0.0) -> BinnedIncidence

The infections a signal implies at the model's observation level: counts[k], reported over the interval ending at ends[k] and observed delay after infection, is Σ_c per_infection[c] split[c, k] per infection over the interval ending at ends[k] - delay, shared over cells as split[:, k] (a vector serves every count). Unobserved infections continue to until at the log_growth_rate of the last growth_points counts; fewer than two hold the last rate.

ConfigurableEpi.splice_incidence — Method.

splice_incidence(history, recent) -> BinnedIncidence

history up to the first edge of recent, then recent; a gap between them has no infections.

ConfigurableEpi.total_infection_rate — Method.

total_infection_rate(model::ReplayModel, x, hyper, latent, t; per_infection = nothing) -> Real

Hosts entering infection per day at ODE state x: what model.vf! takes from the routes' source compartments beyond what model.replay_vf! does. With per_infection by cell the rate is in the signal's units, so a source compartment must feed cells of one level.

ConfigurableEpi.AgeBand — Type.

AgeBand(name, lower_months, upper_months)

One age class, [lower_months, upper_months) in months of age, so the first year of life can be banded finely. The oldest band of a model is open-ended (upper_months = Inf).

ConfigurableEpi.AgeMixing — Type.

AgeMixing(bands, populations, contacts)

A population on age bands (AgeBands partitioning [0, Inf)): populations[g], absolute or as shares, and contacts, a NamedTuple of matrices by setting such as (; school, other), where contacts.school[g, h] is the mean daily number of school contacts one person in band g has with people in band h. The settings are disjoint parts of contact; a single matrix is the one setting all.

ConfigurableEpi.contact_matrix — Method.

contact_matrix(M, a_com) -> Matrix{Float64}

(1 - a_com) I + a_com M: within-location contact at a_com = 0, the radiation matrix at 1.

ConfigurableEpi.contact_spectral_radius — Method.

Spectral radius of the contacts over all settings together.

ConfigurableEpi.load_age_mixing — Method.

load_age_mixing(location, bands; distribution_path, contact_path, population = 1.0) -> AgeMixing

The AgeMixing of location on the model's bands, regrouped from two tables on a common base grid: location,age_band,lower_months,upper_months,share and location,contactor,contactee,contacts_per_day. contact_path is one table, the setting all, or a NamedTuple of tables by setting. The populations are the shares times population.

A model band is any union of base bands or any part of a finite one. Within a finite base band ages are taken as evenly spread and every member is given the band's per-capita contact rates, so a divided band's contacts with a part are in proportion to the part. The regrouping keeps the total contacts between two bands symmetric whenever the base tables are.

Errors when the location is absent, a base band is missing, or the bands do not partition [0, Inf) on the base grid.

ConfigurableEpi.load_radiation_matrix — Method.

load_radiation_matrix(locations; path) -> Matrix{Float64}

Row-normalised contact matrix for locations (in order) from an origin,destination,flow table: M[x, y] is the share of location x's out-of-location contact that is with y, re-normalised over the selected locations. Errors when a location is absent, has a self-flow, or retains no flow to the others.

ConfigurableEpi.load_setting_contacts — Method.

load_setting_contacts(location, bands; matrix_path, population_path, settings = (:school, :other)) -> AgeMixing

The AgeMixing of location read on the tables' own age groups, named by bands: the contact layers settings from location,layer,row_age,col_age,value and the populations from location,age_group,population. Every age pair must be present in every layer.

ConfigurableEpi.validate_age_bands — Method.

validate_age_bands(bands) -> bands

Check that bands partition [0, Inf) in order: the first starts at 0, each starts where the last ended, the last is open-ended, and the names are distinct.

ConfigurableEpi.AnchoredCalendar — Type.

AnchoredCalendar(cal, start_date)

The calendar on model time, t days after start_date, piecewise constant per day and held at its first and last values outside its range.

ConfigurableEpi.SchoolCalendar — Type.

SchoolCalendar(first_date, values)

Daily fraction of school contacts active, from first_date, each in [0, 1].

ConfigurableEpi.assert_calendar_covers — Method.

assert_calendar_covers(cal, from::Date, to::Date)

Error unless the calendar has a value for every day in [from, to].

ConfigurableEpi.load_school_calendar — Method.

load_school_calendar(path) -> SchoolCalendar

Read date,school_open_fraction rows, which must be consecutive days.

ConfigurableEpi.EpiModel — Type.

EpiModel(; vectorfield!, layout, stochastic, observation, hyperparams, priors, initial_state,
         initial_latent_variance = (;), initial_learned_variance = (;),
         initial_accumulator_variance = (;), forgetting_memory_days = (;),
         derived_hyperparameters = nothing, initial_covariance = (hyper, x0, P) -> P,
         initial_particle = (rng, hyper, x0) -> x0, likelihood_warmup_days = 0,
         joint_prior = Independent())

Everything build_inference needs to fit and forecast one model:

  • vectorfield!: the Petri vector field from build_petri_vf.
  • layout, stochastic: the StateLayout and StochasticUpdate.
  • observation: a tuple of observation specs.
  • hyperparams: every hyperparameter the rates, drivers and observation read, including the starting value of each learned one.
  • priors: name => ParameterDistribution for the hyperparameters to learn (a subset of hyperparams, at least one).
  • initial_state: the model-state vector at t = 0, or a function hyperparams -> vector when the seed depends on the parameters (an equilibrium S(0) = N / R0, say).
  • initial_*_variance: by-name overrides of the initial variance of latent coefficient slots, learned slots (PF) and reset accumulators (EnKF), in unconstrained space.
  • forgetting_memory_days: the model's default Liu-West forgetting memories (parameter => days), overridden per key by LiuWest.forgetting_memory_days.
  • derived_hyperparameters: optional hyper -> NamedTuple summarised alongside the learned parameters by the particle filter.
  • initial_covariance(hyper, x0, P): the Gaussian filters' initial state covariance, given the default P built from the variances above.
  • initial_particle(rng, hyper, x): a particle's initial model state, given x, the initial state with the per-slot noise added (to clamp or renormalise it, say).
  • likelihood_warmup_days: the first days of observations that the filter corrects on but that a marginal log-likelihood leaves out, so the transient from an approximate start does not inform the hyperparameters.
  • joint_prior: the PriorCoupling of the priors, such as an RtNBVariancePrior.

ConfigurableEpi.initial_state — Function.

initial_state(model::EpiModel, hyperparams = model.hyperparams) -> Vector

The model-state vector at t = 0 under hyperparams.

ConfigurableEpi.learned_names — Method.

The names of the learned hyperparameters.

ConfigurableEpi.with_joint_prior — Method.

with_joint_prior(model::EpiModel, joint_prior::PriorCoupling) -> EpiModel

model with its priors coupled by joint_prior; Independent() uncouples them.

ConfigurableEpi.with_likelihood_warmup — Method.

with_likelihood_warmup(model::EpiModel, days) -> EpiModel

model with its likelihood_warmup_days set to days.

Inference

ConfigurableEpi.DEFAULT_LATENT_VARIANCE — Constant.

Default initial variance of a latent coefficient slot (unconstrained space): in a log chart, sd 0.45.

ConfigurableEpi.DEFAULT_MODEL_RELATIVE_SD — Constant.

Initial sd of each compartment as a fraction of its own initial value.

ConfigurableEpi.EngineSettings — Type.

EngineSettings(; dt, supersample = 2, integrator = Rk4, n_ahead, n_draws = 2000)

The run-level settings every engine shares: the observation interval in days, the integrator and its substeps per interval (see build_full_dynamics), forecast horizon and forecast draw count.

ConfigurableEpi.ForecastResult — Type.

ForecastResult

What fit_forecast! returns: quantiles, fitted_means, summary, samples and latents.

ConfigurableEpi.InferenceEngine — Type.

InferenceEngine

A (filter, hyper) pairing with all of its mutable state: the filter (cloud or ensemble and its random streams) and the hyperparameter state (learned values, warm-start ensembles, the window checkpoint). Passing it to fit_forecast! again continues inference. A deepcopy of a UKF or EnKF engine is an isolated fork. A particle-filter fork copies the cloud and its own streams, but LowLevelParticleFilters resamples from the task-local RNG, as does an engine built with the default rng, and the copies share it.

ConfigurableEpi.build_inference — Method.

build_inference(filter, hyper, model::EpiModel; dt, supersample = 2, integrator = Rk4, n_ahead,
                n_draws = 2000, rng = Random.default_rng(), kwargs...) -> InferenceEngine
build_inference(cfg::InferenceConfig, model::EpiModel; rng = Random.default_rng())

Build the inference engine for a (filter, hyper) pairing: UKF + Optimise, PF + LiuWest or EnKF + EKP. Drive it with fit_forecast!. The InferenceConfig form takes the pairing, dt = step_days, supersample, integrator, n_ahead and n_draws from the config.

ConfigurableEpi.fit_forecast! — Function.

fit_forecast!(engine, observations, forecast_number; update_range = eachindex(observations),
              emit_forecast = true) -> ForecastResult

Assimilate observations, one entry per slot of the regular dt grid, and forecast n_ahead steps ahead. An entry is a number, a vector with one component per observation, or missing where nothing is observed: the filter predicts through the slot without correcting. A missing component is a signal absent that slot, and every filter corrects on the observed ones only. forecast_number counts fitted origins and drives the re-optimisation cadence. The replay engines (UKF, EnKF) require the complete update_range; the online PF engine keeps its cloud between calls and update_range must start at the slot after the last one it assimilated (the default), so a replay is reset!(engine.filter) followed by the full range.

fitted_means covers update_range (a nowcast at a missing slot). For one observation it is a vector, quantiles is [horizon, quantile] and samples (the predictive draws behind them, each simulated through the model's own process and observation noise) is [horizon, draw]; several observations add an observation axis: [slot, observation], [horizon, observation, quantile] and [horizon, draw, observation]. quantiles and samples are nothing when emit_forecast = false. summary is a (parameter, statistic, value) table of estimates and diagnostics. latents holds the filtered latents over update_range in their unconstrained chart, (; mean, sd) as [slot, latent] matrices (see latent_path_rows).

ConfigurableEpi.marginal_loglik — Method.

marginal_loglik(filter, ys, p; warmup = 0) -> Real

Filter marginal log-likelihood of the observation vectors ys under hyperparameters p after reset!, accumulated at the promoted element type so it differentiates (forward_trajectory(...).ll sizes its buffers as Float64). A missing entry is a grid slot without an observation: the filter predicts through it without correcting. The filter corrects on the first warmup slots without counting their terms.

ConfigurableEpi.positive_cholesky! — Method.

positive_cholesky!(R)

Positive-definite Cholesky via PositiveFactorizations.ldlt!, which unlike its cholesky! wrapper accepts ForwardDiff.Dual matrices. It factors in correlation coordinates, so the repair tolerance does not overwrite small latent variances beside large compartment ones, and scales the lower factor back to state units. Only an exactly zero diagonal takes MIN_MODEL_VARIANCE as its scale.

ConfigurableEpi.build_inference — Method.

build_inference(filter::UKF, hyper::Optimise, model; dt, supersample = 2, integrator = Rk4, n_ahead,
                n_draws = 2000, rng = Random.default_rng(), optimiser = DEFAULT_OPTIMISER_STAGES,
                adtype = AutoForwardDiff())

optimiser is a single optimiser, a tuple of them, or (optimiser, options) pairs. rng seeds the forecast draws; the filter and the optimiser are deterministic.

ConfigurableEpi.PFLiuWestEngine — Type.

PFLiuWestEngine

PF + Liu-West: one persistent particle cloud carrying the learned hyperparameters in its tail, assimilating only the observations it has not yet seen.

ConfigurableEpi.build_pf_dynamics — Method.

build_pf_dynamics(dynamics, layout; rng = Random.default_rng(), learned = nothing, threads = false)
    -> pf_dynamics(x, u, p, t, noise = false)

Adapt the augmented dynamics from build_full_dynamics to the AdvancedParticleFilter convention: noise = true draws the process noise (and fires the jump drivers) from rng, or from a per-thread pool when threads = true, so a seeded run reproduces for a fixed thread count. With learned each particle's tail overrides p and is carried forward unchanged.

ConfigurableEpi.build_pf_measurement — Method.

build_pf_measurement(layout, obs_specs, stochastic; rng = Random.default_rng(), learned = nothing)
    -> pf_measure(x, u, p, t, noise = false)

The particle filter's measurement: the observation means (floored at 1e-6), or with noise = true a draw from the exact observation distribution via sample_observation.

ConfigurableEpi.EnKFEKPEngine — Type.

EnKFEKPEngine

EnKF + EKP: replays the complete series each origin and recalibrates every reopt_interval origins, warm-starting from the previous outer ensemble.

ConfigurableEpi.LearnedHyperparams — Type.

LearnedHyperparams{H}

A block of H hyperparameters carried per particle in the tail after the model state (offset == layout.total_dim). extract(x) reads them constrained as a NamedTuple; to_unconstrained(nt) maps a constrained NamedTuple to the tail's SVector{H}.

ConfigurableEpi.build_hyperparam_updater — Method.

build_hyperparam_updater(learned; discount = 0.95, jitter_floor_fraction = DEFAULT_JITTER_FLOOR_FRACTION,
                         forgetting_memory_days = (;), rng = Random.default_rng(), dt = 1.0, moments) -> update!

update!(particles, weights) refreshes every particle's learned slots in place by the Liu-West kernel θᵢ ← a θᵢ + (1 - a) θ̄ + ε, ε ~ N(0, (1 - a²) V) with a = (3δ - 1) / 2δ and θ̄, V the weighted cloud moments, which preserves the weighted mean and variance. The jitter variance is floored at jitter_floor_fraction of each prior's variance so a collapsed cloud can re-expand. moments is the prior's (mean, covariance) in the learned block's order: by default the scalar priors' own, and prior_moments for a coupled prior. Parameters named in forgetting_memory_days are additionally pulled toward their prior by Kulhavý forgetting with λ = exp(-dt / memory): the marginal N(m, v) becomes the geometric mean of itself and the prior. Call between correct! and predict! on state(pf).xprev with expweights(pf).

ConfigurableEpi.build_learned_hyperparams — Method.

build_learned_hyperparams(priors, layout) -> LearnedHyperparams

priors is a NamedTuple (keys equal to the prior names), a tuple of priors, or one prior.

ConfigurableEpi.DEFAULT_OPTIMISER_STAGES — Constant.

DEFAULT_OPTIMISER_STAGES

Adam first (its step is bounded by the learning rate however badly the filter log-posterior is scaled), then LBFGS to polish; each stage is remaked from the previous solution.

ConfigurableEpi.optimiser_stages — Method.

optimiser_stages(method) -> Tuple of (optimiser, options)

Normalise a single optimiser, a tuple of optimisers, or a tuple of (optimiser, options) pairs.

ConfigurableEpi.optimize_hyperparams — Method.

optimize_hyperparams(neg_logposterior, initial::NamedTuple, bundle::ParameterPriorBundle;
                     stages = DEFAULT_OPTIMISER_STAGES, adtype = AutoForwardDiff(), options = (;))
    -> (; θ, ll, retcode, unconstrained)

Minimise neg_logposterior(u, _) over the bundle's unconstrained coordinates from the constrained initial values. options (such as maxiters) are merged over each stage's own; a stage whose result is non-finite or worse than the incumbent is discarded.

Output

ConfigurableEpi.DEFAULT_QS — Constant.

Default forecast quantile levels.

<a id='ConfigurableEpi.append_latent_audit!-Tuple{Any, Any, AbstractVector, AbstractUnitRange{<:Integer}}'> <a id='ConfigurableEpi.append_latent_audit!-Tuple{Any, Any, AbstractVector, AbstractUnitRange{<:Integer}}-1'> ConfigurableEpi.append_latent_audit! — Method.

append_latent_audit!(summary, latent_names, xt, latent_range; dt) -> summary

In-sample behaviour of each latent's filtered path (unconstrained chart): is_sd, the lag-1 autocorrelation is_acf1, the implied correlation time is_tau_days = -dt / log(acf1) (NaN when acf1 <= 0) and is_drift, the second-half mean minus the first-half mean. Filtered paths absorb data innovations, so read is_acf1 as a lower bound on the process's own.

ConfigurableEpi.append_latent_spread! — Method.

append_latent_spread!(summary, latent_names, log_sd) -> summary

Per-horizon predictive spread of each latent coefficient: fc_log_sd_h<h> (the unconstrained sd, log_sd[h, l]) and fc_factor_h<h> = exp(sd), a multiplicative ±1sd spread for a log-chart latent.

ConfigurableEpi.asof_series — Method.

asof_series(triangle; r_k, date_col = :date, issue_col = :as_of, group_cols = ()) -> DataFrame

No-leakage as-of series at report date r_k: rows with as_of <= r_k, then the latest issue per reference date (within each group_cols series, e.g. (:location,)), sorted date-major.

ConfigurableEpi.backtest_forecast_rows — Method.

backtest_forecast_rows(quantiles, origin, target_dates, truth; qs = DEFAULT_QS, model_id,
                       date_col = :date, value_col = :counts[, locations, loc_col = :location]) -> DataFrame

One row per (horizon, quantile) with columns origin, horizon, target_date, quantile, value, observed, model_id, observed joined from truth at each target date. A [horizon, observation, quantile] array with locations labelling the observations prepends a location column and joins on (location, date).

ConfigurableEpi.forecast_ensemble — Method.

forecast_ensemble(filter, init_states, p; n_ahead, t0, dt = 1.0, u = Float64[], latent_range = 1:0,
                  n_obs = 1, observe_state = Returns(nothing)) -> (samples, latent_samples)

Roll each state forward n_ahead steps with sample_state and draw a predictive observation with sample_measurement (no correct!). samples[h, j, o] is the non-negative predictive draw of observation o; latent_samples[h, j, l] the requested slots (latent_range, any integer vector) in their unconstrained chart, the forecast-spread diagnostic. observe_state(h, j, x) sees draw j's state at every horizon h, from the origin h = 0.

ConfigurableEpi.forecast_quantiles — Method.

forecast_quantiles(samples; qs = DEFAULT_QS)

Per-horizon quantiles over draws: [horizon, quantile] from samples[h, j], or [horizon, observation, quantile] from samples[h, j, o].

ConfigurableEpi.latent_path_rows — Method.

latent_path_rows(stochastic, dates, latents) -> DataFrame

Filtered latents (; mean, sd), each [slot, latent] in the unconstrained chart the filter carries, as one row per date and latent: unconstrained_mean, unconstrained_sd, and q05, median and q95 on the latent's own scale, the chart's Gaussian quantiles mapped through its constraint. dates are the dates of the slots. Empty for latents === nothing.

ConfigurableEpi.forecast_sample_rows — Method.

forecast_sample_rows(samples, target_dates; geo_value, disease, variable, resolution, metadata = (;))
forecast_sample_rows(samples, target_dates; geo_values, diseases, variables, resolution, metadata = (;))

Long draw-level rows from samples[horizon, draw] (or [horizon, draw, signal] with one label per signal): draw-major, with Int32 draw ids. metadata appends scalar or row-length columns after the routine ones (a backtest's origin, say).

ConfigurableEpi.write_forecast_samples — Method.

write_forecast_samples(path, table_or_tables) -> path

Write one sample table, or an iterable of schema-identical tables, to samples.parquet through DuckDB (COPY ... FORMAT parquet), combining the batches inside DuckDB.

ConfigurableEpi.DataLink — Type.

DataLink(schema[, value_column = :value, pivot_column = nothing])

How a DataFrame maps onto a schema: already wide (one column per observation name), or long with a pivot_column whose values are the observation names and a value_column.

ConfigurableEpi.ObservationSchema — Type.

ObservationSchema(names, time_column)

The observation names, in the order the measurement model emits them, and the time column.

ConfigurableEpi.build_observation_schema — Method.

build_observation_schema(obs_specs; time_column = :date)

The schema named by a tuple of observation specs, in their order.

ConfigurableEpi.build_observations — Method.

build_observations(df, link::DataLink; T = Float64) -> (; y, times)
build_observations(df, obs_specs; time_column = :date, value_column = :value, pivot_column = nothing, T = Float64)

Observation vectors y::Vector{SVector{N, T}} in schema order, one per time point, and the times. Missing cells throw.

ConfigurableEpi.pivot_to_wide — Method.

pivot_to_wide(df, link::DataLink) -> DataFrame

Wide frame with the time column followed by one column per schema name, sorted by time. A wide input is validated and sorted; a long one is unstacked on link.pivot_column.

ConfigurableEpi.reindex_to_grid — Method.

reindex_to_grid(df, step_days; date_col = :date, start = nothing, stop = nothing,
                value_cols = (:counts,)) -> DataFrame

One row per grid date start:Day(step_days):stop (the first and last dates of df by default): the regular step_days grid the engines read (fit_forecast! takes one entry per slot). A row of df keeps its value_cols at its slot; a grid date df lacks gets missing in every value column, the predict-only slot the filter advances through without correcting. A reporting gap is therefore stepped through slot by slot instead of being closed up into one step, which is what keeps model time on the calendar. df must be strictly increasing in date_col with every date on the grid; other columns are dropped.

ConfigurableEpi.require_complete_grid — Method.

require_complete_grid(df, link) -> df

Assert exactly one row for every (observation, time) cell of a long frame, reporting every missing and duplicated cell at once (the pivot alone would take the first duplicate silently).