Skip to content

Multi-strata infection processes, coupling, and arbitrary strata mappings - #245

Merged
seabbs merged 4 commits into
mainfrom
add-mixing
Aug 5, 2026
Merged

seabbs merged 4 commits into
mainfrom
add-mixing

Conversation

@seabbs-bot

Copy link
Copy Markdown
Collaborator

Closes #45, closes #175.

What this adds

A multi-strata infection process that maps onto a multi-strata observation
process under arbitrary mappings between the two strata sets, and coupling
between the infection strata.

Two seams carry it.

The strata axis is introduced by a latent manipulator, not an
infection-model wrapper. Stratify(shared, across) returns a strata × time
matrix from a shared path and a per-stratum effect. Hand it to
Renewal(; rt = ...) and Rt is a matrix, so the scan window is
strata × lags and the recursion runs per stratum, each with its own seeding
and its own Rt deviation. Replicate(model) draws one independent path per
stratum instead.

Coupling is an operator on the incidence window, applied before Rt.
renewal_pressure(mixing, gen_int, window) is the one dispatch point.
mixing = I, the default, is uncoupled and covers the single-series case
unchanged. Coupling cannot be a renewal modifier, because a modifier
transforms the finished force of infection while mixing sits between the
generation-time convolution and Rt, and K(R ⊙ v) ≠ R ⊙ Kv.

n now means the size of the value the model returns: n::Int is a length-n
path, n::Dims{2} is (n_strata, n_time), which is size(I_t).

Infection strata to observation strata

Every cardinality goes through one weight matrix on Split.

Mapping How
one-to-one no map, or map = I(n)
many-to-one one aggregation row, e.g. [1.0 1.0 1.0]
many-to-many a general weight matrix
finer or coarser than infections a non-square map

The infection-stratum count is read from the observation model and the data at
build time through infection_strata, so three age strata observed as one
hospitalisation stream builds a three-stratum process from a 1 × T matrix.
Nothing about the shape is stored on a struct.

Coupling options

mixing accepts a strata × strata matrix, a strata × lags generation
interval (one interval per stratum), a strata × strata × lags array (a
per-pair interval, built with pairwise_gen_int), or an AbstractMixingModel
whose parameters are drawn per iteration. Gravity is the worked example of
the last; the fixed and inferred paths call the same gravity function, so
they cannot drift.

Nothing about a mixing matrix is checked or normalised. A zero column
K[:, h] means stratum h infects nobody, though its own incidence still
evolves through K[h, h]. A zero row K[g, :] means stratum g receives no
force at all, so its incidence falls to zero and stays there.

Hierarchical generation intervals

An UncertainDelay's parameters are prior slots, so giving one a Hierarchy
partially pools that parameter across strata. A partially pooled generation
interval therefore needs no new component; the interval is drawn at n_strata
and assembled into a strata × lags matrix.

Removed

GroupedInfections, the IDModel(infection, group_effect, observation) and
IDModel(idmodel, group_effect) constructors, _grouped_combiner and the
combiner keyword, and the (n_time, n_groups) shape. No deprecation
handling. GroupedInfections shared the finished I_t and post-multiplied by
a per-stratum scalar, so the strata axis only ever existed outside the
recursion, which blocks per-stratum seeding and coupling. The replacement is
one line:

IDModel(
    DirectInfections(;
        Z = Stratify(RandomWalk(), Hierarchy(; across = IID(Normal(0, 0.5)))),
        initialisation = Normal(log(50), 0.2)),
    Split(PoissonError()))

CombineInfections is unchanged. It runs one scan per stratum, so it cannot be
coupled. One model over an axis is couplable; several independent models are
not.

Also changed

IDProblem and forecast now handle a matrix or a NamedTuple of streams;
neither could drive a multi-strata model before. SusceptibleDepletion is
shape-agnostic and takes a scalar or a per-stratum pop_size. Every path model
takes n::Int, with a guard that tells you to wrap a path model in a
Stratify rather than failing inside a submodel.

modifier_init_state takes the incidence window as a second argument, so a
substate that tracks the incidence can match its shape. Without it a scalar
pop_size on a stratified renewal changes type mid-scan.

Verified

  • The uncoupled path is arithmetically unchanged: a single-series model and the
    same model at shape (1, n) give identical draws.
  • A per-pair generation interval with K = I reproduces the uncoupled model
    exactly, which pins the lag convention.
  • A drawn Gravity with fixed exponents matches the plain gravity matrix.
  • Every renewal_pressure method against a hand-written sum.
  • All four mapping cardinalities end to end, including shape resolution from
    the data alone.
  • NUTS on a coupled stratified model, and both forecast paths.

Docs

A new case study, "Coupled patch models", covering independent patches, a
shared R_t with partial pooling, exogenous and endogenous imports, a fixed
mixing matrix, an inferred gravity model, and a many-to-one observation.

Gate status at time of opening

Gate Result
task test-fast pass
task test-jet pass
task test-quality (Aqua, formatting, doctests) pass
task test-ad pass
task docs-fast still running locally

The docs build takes over 45 minutes here because several case studies run
MCMC, so it had not finished when this was opened. Doctests (every @example
in a docstring) pass as part of the quality gate; what is outstanding is the
full site build of the case-study pages. CI will settle it.

This was opened by a bot. Please ping @seabbs for any questions.

@seabbs-bot
seabbs-bot requested a review from seabbs as a code owner August 5, 2026 13:40
@github-actions

github-actions Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Try this Pull Request!

Option 1: Julia Package Manager

Open Julia and type:

import Pkg
Pkg.activate(temp=true)
Pkg.add(url="https://github.com/EpiAware/ComposableTuringIDModels.jl", rev="add-mixing")
using ComposableTuringIDModels

Option 2: Local Checkout

If you have the repo locally:

git checkout add-mixing
julia --project=. -e "using Pkg; Pkg.instantiate()"

@codecov

codecov Bot commented Aug 5, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.72131% with 8 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/base/shapes.jl 50.00% 3 Missing ⚠️
src/compose.jl 93.33% 1 Missing ⚠️
src/infection_models/utils.jl 90.90% 1 Missing ⚠️
src/steps/ImportedCases.jl 0.00% 1 Missing ⚠️
src/steps/MixingStep.jl 92.30% 1 Missing ⚠️
src/steps/RenewalStep.jl 94.73% 1 Missing ⚠️
Flag Coverage Δ
ad-enzyme-forward 0.00% <0.00%> (ø)
ad-enzyme-reverse 55.44% <35.31%> (-2.37%) ⬇️
ad-forwarddiff 51.06% <35.31%> (-4.13%) ⬇️
ad-mooncake-forward 0.00% <0.00%> (ø)
ad-mooncake-reverse 54.53% <35.31%> (-4.29%) ⬇️
ad-reversediff 51.21% <35.31%> (-7.78%) ⬇️
unit 93.17% <98.33%> (+1.04%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
src/base/interfaces.jl 100.00% <ø> (+11.11%) ⬆️
src/base/priors.jl 92.30% <100.00%> (+0.30%) ⬆️
src/infection_models/CombineInfections.jl 100.00% <ø> (+100.00%) ⬆️
src/infection_models/DirectInfections.jl 100.00% <100.00%> (ø)
src/infection_models/ExpGrowthRate.jl 100.00% <100.00%> (ø)
src/infection_models/Renewal.jl 100.00% <100.00%> (ø)
src/inference/IDProblem.jl 100.00% <100.00%> (ø)
src/inference/forecast.jl 100.00% <100.00%> (ø)
.../latent_models/manipulators/CombineLatentModels.jl 95.23% <100.00%> (+1.12%) ⬆️
...c/latent_models/manipulators/ConcatLatentModels.jl 94.28% <100.00%> (ø)
... and 30 more

... and 3 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@github-actions

github-actions Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Benchmark comparison vs base

Minimum time per call. Buckets are PR time as a % of base, so lower is faster (🟢 faster, ⚪ within 5%, 🔴 slower). Counts of benchmarks per bucket:

Group 🟢 <50% 🟢 50–75% 🟢 75–95% ⚪ 95–105% 🔴 105–125% 🔴 125–150% 🔴 >150%
Evaluation · · · 3 6 · ·
ForwardDiff · · 1 · 1 · ·
ReverseDiff (tape) · · · 1 1 · ·
Mooncake reverse · · · 1 1 · ·
Enzyme reverse · · · · 1 · ·
Evaluation — 9 benchmarks (by time change)
Benchmark base PR time memory
Model evaluation / DirectInfections+Poisson / rand 64.56 μs 71.11 μs 🔴 1.1× ⚪ 1.0×
Model evaluation / DirectInfections+Poisson / forward 65.61 μs 71.87 μs 🔴 1.1× ⚪ 1.0×
Model evaluation / Renewal+NegativeBinomial / rand 67.63 μs 73.34 μs 🔴 1.08× ⚪ 1.0×
Model evaluation / Renewal+NegativeBinomial / forward 70.61 μs 76.3 μs 🔴 1.08× ⚪ 1.0×
Model evaluation / RandomWalk latent / rand 420.0 ns 451.0 ns 🔴 1.07× ⚪ 1.0×
Model evaluation / AR latent / rand 580.0 ns 621.0 ns 🔴 1.07× ⚪ 1.0×
Model evaluation / AR latent / forward 530.0 ns 510.0 ns ⚪ 0.96× ⚪ 1.0×
Sampling / NUTS (DirectInfections+Poisson, 50 draws) 1.01 s 1.04 s ⚪ 1.03× ⚪ 1.0×
Model evaluation / RandomWalk latent / forward 420.0 ns 410.0 ns ⚪ 0.98× ⚪ 1.0×
AD gradients — 7 benchmarks (by time change)
Benchmark base PR time memory
AD gradients / AR latent logjoint / ForwardDiff 6.71 μs 6.09 μs 🟢 0.91× ⚪ 1.0×
AD gradients / DirectInfections+Poisson posterior / Enzyme reverse 69.02 μs 74.72 μs 🔴 1.08× ⚪ 1.0×
AD gradients / DirectInfections+Poisson posterior / Mooncake reverse 77.56 μs 83.13 μs 🔴 1.07× ⚪ 1.0×
AD gradients / DirectInfections+Poisson posterior / ForwardDiff 208.69 μs 220.96 μs 🔴 1.06× ⚪ 1.0×
AD gradients / DirectInfections+Poisson posterior / ReverseDiff (tape) 157.91 μs 167.04 μs 🔴 1.06× ⚪ 1.0×
AD gradients / AR latent logjoint / Mooncake reverse 6.27 μs 6.03 μs ⚪ 0.96× ⚪ 1.0×
AD gradients / AR latent logjoint / ReverseDiff (tape) 49.91 μs 50.15 μs ⚪ 1.0× ⚪ 1.0×

@github-actions

github-actions Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

📖 Documentation preview is ready!

View the docs for this PR at: https://EpiAware.github.io/ComposableTuringIDModels.jl/previews/PR245/

This preview will be updated automatically when you push new commits.

seabbs-bot and others added 2 commits August 5, 2026 17:37
Add a multi-strata infection process that maps onto a multi-strata
observation process under arbitrary mappings, and coupling between the
infection strata.

Two seams carry it. The strata axis is introduced by a latent manipulator,
`Stratify(shared, across)`, returning a `strata × time` matrix, so a renewal
handed one runs a recursion per stratum with its own seed and its own `Rt`
deviation. Coupling is an operator on the incidence window applied before
`Rt`, dispatched through `renewal_pressure`, which cannot be a modifier
because `K(R ⊙ v) ≠ R ⊙ Kv`.

`n` now means the size of the value the model returns: `n::Int` is a
length-`n` path and `n::Dims{2}` is `(n_strata, n_time)`.

Every infection-to-observation cardinality goes through one weight matrix on
`Split`: one-to-one, many-to-one, many-to-many, and finer or coarser than the
infection process. The infection-stratum count is read from the observation
model and the data at build time, so nothing about the shape is stored on a
struct.

`mixing` accepts a matrix, a per-stratum generation interval, a per-pair
array via `pairwise_gen_int`, or an `AbstractMixingModel` drawn per
iteration; `Gravity` is the worked example, sharing one `gravity` function
with the fixed path so the two cannot drift. A `Hierarchy` in an
`UncertainDelay` parameter slot gives a partially pooled generation interval
with no new component.

Remove `GroupedInfections`, the grouped `IDModel` constructors,
`_grouped_combiner` and the `(n_time, n_groups)` shape. It shared the
finished `I_t` and post-multiplied by a per-stratum scalar, so the strata
axis only existed outside the recursion, which blocks per-stratum seeding and
coupling.

`IDProblem` and `forecast` now drive a matrix or a NamedTuple of streams,
neither of which was previously possible. `modifier_init_state` takes the
incidence window so a substate can match its shape.

Co-authored-by: Sam Abbott <contact@samabbott.co.uk>
Adds tests for the paths an audit found uncovered. The two that matter most
are `IDProblem`'s stratified shape resolution and `forecast` with a matrix or
NamedTuple series, neither of which had any coverage, and a real bug had
already hidden in the second.

Also covers the `Dims{2}` methods of the shape-transparent latent
manipulators, `SusceptibleDepletion` and `ImportedCases` composed on a
stratified renewal, `ExpGrowthRate` at a strata shape with a `Replicate` rt,
a mixing matrix combined with per-stratum generation intervals,
`across_shape` as a third-party extension point, and the assertions in
`_seed` and `gravity` that never fired.

`pairwise_gen_int` with `K = I` reproducing the uncoupled model exactly is
now a regression test. That identity pins the per-pair lag convention and
had only been checked by hand.

Co-authored-by: Sam Abbott <contact@samabbott.co.uk>
Comment thread docs/src/tutorials/hierarchy-stacked.md Resolved
seabbs-bot and others added 2 commits August 5, 2026 17:38
A prose review found the same point made in several places and a recurring
habit of stacking clauses behind a colon.

Deduplicated: the couplable-versus-not line now lives only in the coupled
patch-models case study, with pointers from `CombineInfections` and the
split-observations page. The fixed-versus-inferred gravity paths are
described once, in `Gravity`'s docstring. `Split` no longer restates its own
cardinality list twenty lines after giving it.

Split eighteen run-on sentences into separate ones, mostly in the pooling
case study and the `Renewal`, `RenewalSteps`, `Gravity` and `shapes`
docstrings.

Co-authored-by: Sam Abbott <contact@samabbott.co.uk>
The previous push landed while the prior commit's workflows were still
running and GitHub queued no runs for the new head. This empty commit
re-triggers them and can be dropped when squashing.

Co-authored-by: Sam Abbott <contact@samabbott.co.uk>
Comment thread docs/src/tutorials/hierarchy-stacked.md Resolved
Comment thread docs/src/case-studies/patch-models.md Resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants