From 8e531b7a60bd954d90f344f911b722ea8834187b Mon Sep 17 00:00:00 2001 From: seabbs-bot Date: Fri, 4 Sep 2026 13:55:01 +0100 Subject: [PATCH 01/12] feat(inference)!: strip the layer to IDProblem and forecast, and pair a model with its data The method layer predates the `as_turing_model` directive. Every part of it wrapped one Turing call, none was used outside its own tests, and two of them raised `MethodError` on the FlexiChains chain `sample` now returns. `types.jl`, `NUTSampler.jl`, `DirectSample.jl`, `apply_method.jl`, `IDObservables.jl`, `get_param_array.jl`, `post-inference.jl` and `condition_model` all go, and with them `ADTypes`, `AbstractMCMC`, `AdvancedHMC`, `MCMCChains` and `DataFramesMeta`. `as_turing_model(::IDModel, y)` now covers a vector and a `NamedTuple` of streams as well as a matrix, so the shape comes from the data rather than from a restated `length(y)`. `_obs_data_shape` moves to `compose.jl` and the `_shape` that duplicated its matrix case goes, leaving one shape path shared with `forecast`. `IDProblem` is rebuilt on top of that as a model paired with its data. `tspan` goes: every call site restated the data's own length, and the `data_requirements` path that read it now reads the full shape off the data instead, so a stratified problem reports on the stratum axis. The pairing earns its place by printing: the component tree from the package's own printer, plus a line summarising the data, where a conditioned `DynamicPPL.Model` renders as its full nested parametric type with every observation dumped inline. Co-Authored-By: Sam Abbott Co-Authored-By: Claude Opus 5 --- Project.toml | 10 - docs/src/design.md | 2 +- docs/src/tutorials/catalyst-ode.md | 4 +- docs/src/tutorials/delays-dayofweek.md | 29 +-- docs/src/tutorials/gaussian-process.md | 4 +- docs/src/tutorials/realtime-nowcast.md | 6 +- docs/src/tutorials/renewal-negbin.md | 4 +- docs/src/tutorials/sir-ode.md | 4 +- src/ComposableTuringIDModels.jl | 26 +-- src/base/prettyprinting.jl | 12 +- src/compose.jl | 73 +++++- src/inference/DirectSample.jl | 31 --- src/inference/IDObservables.jl | 67 ------ src/inference/IDProblem.jl | 195 +++++++++------- src/inference/NUTSampler.jl | 68 ------ src/inference/apply_method.jl | 55 ----- src/inference/forecast.jl | 20 +- src/inference/get_param_array.jl | 19 -- src/inference/post-inference.jl | 29 --- src/inference/types.jl | 11 - src/observation_models/requirements.jl | 8 +- src/utils/turing-methods.jl | 34 --- test/Project.toml | 3 - test/unit/base/interfaces.jl | 6 +- test/unit/compose_strata.jl | 28 +++ test/unit/inference/inference.jl | 225 ++++++++++--------- test/unit/latent_models/gaussian_process.jl | 4 +- test/unit/observation_models/requirements.jl | 31 +-- test/unit/utils/utils_extra.jl | 22 -- 29 files changed, 393 insertions(+), 637 deletions(-) delete mode 100644 src/inference/DirectSample.jl delete mode 100644 src/inference/IDObservables.jl delete mode 100644 src/inference/NUTSampler.jl delete mode 100644 src/inference/apply_method.jl delete mode 100644 src/inference/get_param_array.jl delete mode 100644 src/inference/post-inference.jl delete mode 100644 src/inference/types.jl delete mode 100644 src/utils/turing-methods.jl diff --git a/Project.toml b/Project.toml index 9b7f940d2..09975950f 100644 --- a/Project.toml +++ b/Project.toml @@ -5,12 +5,8 @@ authors = ["Sam Abbott"] license = "Apache-2.0" [deps] -ADTypes = "47edcb42-4c32-4615-8424-f2b9edc5f35b" -AbstractMCMC = "80f14c24-f653-4e6a-9b94-39d6b0f70001" -AdvancedHMC = "0bf59076-c3b1-5ca4-86bd-e02cd72cde3d" CensoredDistributions = "b2eeebe4-5992-4301-9193-7ebc9f62c855" ConstructionBase = "187b0558-2788-49d3-abe0-74a17ed4e7c9" -DataFramesMeta = "1313f7d8-7da2-5740-9ea0-a2ca25f37964" Distributions = "31c24e10-a181-5473-b8eb-7969acd0382f" DocStringExtensions = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae" DynamicPPL = "366bfd00-2699-11ea-058f-f148b4cae6d8" @@ -18,7 +14,6 @@ FlexiChains = "4a37a8b9-6e57-4b92-8664-298d46e639f7" KernelFunctions = "ec8451be-7e33-11e9-00cf-bbf324bd1392" LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" LogExpFunctions = "2ab3a3ac-af41-5b50-aa03-7779005ae688" -MCMCChains = "c7f686f2-ff18-58e9-bc7b-31028e88f75d" OrdinaryDiffEq = "1dea7af3-3e70-54e6-95c3-0bf5283fa5ed" Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" @@ -35,13 +30,9 @@ ComposableTuringIDModelsCatalystExt = ["Catalyst", "ModelingToolkit"] ComposableTuringIDModelsEnzymeExt = "Enzyme" [compat] -ADTypes = "1.22.1" -AbstractMCMC = "5.15.1" -AdvancedHMC = "0.8.5" Catalyst = "16" CensoredDistributions = "0.2.22" ConstructionBase = "1.6.0" -DataFramesMeta = "0.15.6" Distributions = "0.25.128" DocStringExtensions = "0.9.5" DynamicPPL = "0.42.1" @@ -50,7 +41,6 @@ FlexiChains = "0.6.13" KernelFunctions = "0.10.65, 0.11" LinearAlgebra = "1.11, 1.12" LogExpFunctions = "0.3.29, 1.0" -MCMCChains = "7.7.0" ModelingToolkit = "11" OrdinaryDiffEq = "7.1.0" Random = "1.11, 1.12" diff --git a/docs/src/design.md b/docs/src/design.md index bba162f91..21529fd48 100644 --- a/docs/src/design.md +++ b/docs/src/design.md @@ -206,7 +206,7 @@ It asks whether every observation supplied would be scored, so more data than th data_fits(delayed, y, length(y)), data_fits(delayed, vcat(y, y), length(y)) ``` -An [`IDProblem`](@ref)'s `tspan` is the span of the observations for the same reason, and [`forecast`](@ref) extends the observations by the horizon and derives the rest. +An [`IDProblem`](@ref) holds a model and its data together, so [`data_requirements`](@ref) reads the observation count off the data rather than being told it, and [`forecast`](@ref) extends the observations by the horizon and derives the rest. Length-preserving modifiers ([`Ascertainment`](@ref), [`RightTruncate`](@ref), [`ReportTriangle`](@ref), a [`Split`](@ref)'s streams) consume nothing of their own, so the lead-in comes from the delays alone. A [`Split`](@ref)'s streams run in parallel, so their lead-ins do not add up and the series covers the deepest of them. diff --git a/docs/src/tutorials/catalyst-ode.md b/docs/src/tutorials/catalyst-ode.md index 424ad930d..654755fc3 100644 --- a/docs/src/tutorials/catalyst-ode.md +++ b/docs/src/tutorials/catalyst-ode.md @@ -149,7 +149,7 @@ Both rates collapse from broad priors onto tight, correlated posteriors. ## Posterior trajectories A compartmental model has no time-varying ``R_t``, so the infection signal is the infectious proportion ``I(t)`` solved from the ODE. -[`generated_observables`](@ref) recovers ``I_t`` per draw, and the posterior-predictive in-bed counts come from `predict` on the model with the observations set to `missing`. +`returned` re-runs the fitted model over the chain and recovers ``I_t`` per draw, and the posterior-predictive in-bed counts come from `predict` on the model with the observations set to `missing`. Two small helpers reduce the per-draw trajectories to credible bands. ```@setup catalyst @@ -184,7 +184,7 @@ end ``` ```@example catalyst -gens = vec(generated_observables(posterior, y_obs, chain).generated) +gens = vec(returned(posterior, chain)) It = credible_bands(reduce(hcat, (g.I_t for g in gens))) pred = predict(as_turing_model(model, fill(missing, n), n), chain) diff --git a/docs/src/tutorials/delays-dayofweek.md b/docs/src/tutorials/delays-dayofweek.md index 01848d2f4..2f3e63397 100644 --- a/docs/src/tutorials/delays-dayofweek.md +++ b/docs/src/tutorials/delays-dayofweek.md @@ -99,8 +99,7 @@ Two stacked delays therefore need the infection process to start that many days observation_lead_in(observation) ``` -An [`IDProblem`](@ref)'s `tspan` is the span of the *observations*, so `tspan = (1, length(y))` fits every report we have. -The infection process runs over the extra lead-in days to support them, derived from the chain (see [What data a model needs](@ref lead-in)). +The number of observations is the number of reports we have, and the infection process runs over the extra lead-in days to support them, derived from the chain (see [What data a model needs](@ref lead-in)). [`data_requirements`](@ref) says what a chain needs before it is sampled. ## The data @@ -119,23 +118,25 @@ y_obs = italy.confirm[1:n] ## Assemble and fit -[`IDProblem`](@ref) ties the latent, infection, and observation models to a time span. -Its [`as_turing_model`](@ref) method takes data as a named tuple with a `y_t` field. -Passing `missing` values would instead simulate from the prior. +[`IDProblem`](@ref) holds the model and the data it is fitted to as one object. +Printing it shows the whole composition and a summary of the data, which is the reason to hold one rather than the `DynamicPPL.Model` [`as_turing_model`](@ref) returns: the latter prints as its full nested parametric type with the observations dumped inline. ```@example delays -problem = IDProblem( - infection = renewal, - observation_model = observation, - tspan = (1, n)) -nothing # hide +problem = IDProblem(renewal, observation, y_obs) +``` + +The problem carries its own length, so nothing about the series is restated and [`data_requirements`](@ref) reads straight off it. +Passing a blank series in place of the reports, `Vector{Missing}(missing, n)`, would instead simulate from the prior. + +```@example delays +data_requirements(problem) ``` Fitting conditions on the observed reports, differentiating with the recommended [Mooncake](https://chalk-lab.github.io/Mooncake.jl/) backend, described under [Automatic differentiation backend](@ref ad-backends). We draw two chains in parallel with `MCMCThreads()`, which gives a cross-chain ``\hat R``. ```@example delays -posterior = as_turing_model(problem, (y_t = y_obs,)) +posterior = as_turing_model(problem) chain = sample( posterior, NUTS(0.95; adtype = AutoMooncake(; config = nothing)), MCMCThreads(), 250, 2; progress = false) @@ -176,7 +177,7 @@ The autoregressive damping (`diff.damp`) and moving-average (`diff.θ`) coeffici ## Posterior trajectories -``R_t = \exp(Z_t)`` and the infections ``I_t`` are generated quantities recovered per draw with [`generated_observables`](@ref). +``R_t = \exp(Z_t)`` and the infections ``I_t`` are generated quantities recovered per draw with `returned`. The reports ``y_t`` are scored element-wise, so their posterior-predictive distribution comes from `predict` on the model with the observations set to `missing`. Two small helpers reduce the per-draw trajectories to credible bands. @@ -210,10 +211,10 @@ end ``` ```@example delays -gens = vec(generated_observables(posterior, (y_t = y_obs,), chain).generated) +gens = vec(returned(posterior, chain)) Rt = credible_bands(reduce(hcat, (exp.(g.Z_t) for g in gens))) -pred = predict(as_turing_model(problem, (y_t = fill(missing, n),)), chain) +pred = predict(as_turing_model(problem, Vector{Missing}(missing, n)), chain) yt = predictive_bands(pred, n) fig = Figure(; size = (760, 620)) diff --git a/docs/src/tutorials/gaussian-process.md b/docs/src/tutorials/gaussian-process.md index 60309a739..68d42d922 100644 --- a/docs/src/tutorials/gaussian-process.md +++ b/docs/src/tutorials/gaussian-process.md @@ -133,7 +133,7 @@ fig_sim ## Fit both GPs and compare Conditioning on the counts and sampling with NUTS recovers the posterior, differentiated with [Mooncake](https://chalk-lab.github.io/Mooncake.jl/), the recommended backend for this package. -The helper below fits a chosen GP latent to the first `n_fit` days, times the run, recovers the per-draw ``\log R_t`` with [`generated_observables`](@ref) and scores the posterior mean against the truth. +The helper below fits a chosen GP latent to the first `n_fit` days, times the run, recovers the per-draw ``\log R_t`` with `returned` and scores the posterior mean against the truth. ```@example gp using Turing, Mooncake, Statistics @@ -148,7 +148,7 @@ function fit_gp(latent, n_fit) NUTS(0.9; adtype = AutoMooncake(; config = nothing)), MCMCThreads(), 300, n_chains; initial_params = fill(InitFromPrior(), n_chains), progress = false) - gen = vec(generated_observables(posterior, y, chain).generated) + gen = vec(returned(posterior, chain)) Z = reduce(hcat, (g.Z_t for g in gen)) # time × draw Z_mean = vec(mean(Z; dims = 2)) Z_ref = Z_true[1:n_fit] diff --git a/docs/src/tutorials/realtime-nowcast.md b/docs/src/tutorials/realtime-nowcast.md index c2ade0f78..c64f8fbd9 100644 --- a/docs/src/tutorials/realtime-nowcast.md +++ b/docs/src/tutorials/realtime-nowcast.md @@ -162,7 +162,7 @@ nothing # hide ## Recent Rt -``R_t = \exp(Z_t)`` is a generated quantity, recovered per draw by re-running the fitted model over the chain with [`generated_observables`](@ref). +``R_t = \exp(Z_t)`` is a generated quantity, recovered per draw by re-running the fitted model over the chain with `returned`. Averaging it over the most recent window shows the bias and its removal. Right-truncation biases the naive recent ``R_t`` *downward*, so the naive value sits below the two corrections, which lift it back up towards the complete-data reference. The exact numbers carry Monte Carlo noise on this short run, but the direction repeats. @@ -171,7 +171,7 @@ The exact numbers carry Monte Carlo noise on this short run, but the direction r using Statistics function recent_Rt(post, chain; window = 7) - gens = vec(generated_observables(post, nothing, chain).generated) + gens = vec(returned(post, chain)) Rt_mean = mean(exp.(g.Z_t) for g in gens) round(mean(Rt_mean[(end - window + 1):end]), digits = 2) end @@ -213,7 +213,7 @@ end # generated-quantity bands: stack f(draw) over the chain function gen_bands(post, chain, f) - gens = vec(generated_observables(post, nothing, chain).generated) + gens = vec(returned(post, chain)) credible_bands(reduce(hcat, (f(g) for g in gens))) end diff --git a/docs/src/tutorials/renewal-negbin.md b/docs/src/tutorials/renewal-negbin.md index ce00d8569..2943c88a7 100644 --- a/docs/src/tutorials/renewal-negbin.md +++ b/docs/src/tutorials/renewal-negbin.md @@ -167,7 +167,7 @@ The autoregressive damping ``\rho`` (`damp`), the cluster factor and the initial ## Posterior trajectories The reproduction number ``R_t = \exp(Z_t)`` is a *generated quantity* rather than a sampled parameter. -[`generated_observables`](@ref) re-runs the fitted model over the chain to recover the latent ``Z_t`` and infection ``I_t`` trajectories per draw. +`returned` re-runs the fitted model over the chain to recover the latent ``Z_t`` and infection ``I_t`` trajectories per draw. The reported counts ``y_t`` are scored element-wise, so their posterior *predictive* distribution comes from `predict` on the same model with the observations set to `missing`. A couple of small helpers reduce the per-draw trajectories to credible bands and draw a median line with 50% and 95% ribbons. @@ -212,7 +212,7 @@ end Stack the per-draw ``Z_t`` into an ``R_t`` band, draw the posterior-predictive ``y_t`` from the unconditioned model, and plot both against the observed series. ```@example renewal -gens = vec(generated_observables(posterior, y_obs, chain).generated) +gens = vec(returned(posterior, chain)) Rt = credible_bands(reduce(hcat, (exp.(g.Z_t) for g in gens))) pred = predict(as_turing_model(model, fill(missing, n), n), chain) diff --git a/docs/src/tutorials/sir-ode.md b/docs/src/tutorials/sir-ode.md index 2186a00d3..2e0d8a1a3 100644 --- a/docs/src/tutorials/sir-ode.md +++ b/docs/src/tutorials/sir-ode.md @@ -151,7 +151,7 @@ All three parameters collapse from broad priors onto tight, correlated posterior ## Posterior trajectories A compartmental model has no time-varying ``R_t``, so the infection signal is the infectious proportion ``I(t)`` solved from the ODE. -[`generated_observables`](@ref) recovers ``I_t`` per draw, and the posterior-predictive in-bed counts come from `predict` on the model with the observations set to `missing`. +`returned` re-runs the fitted model over the chain and recovers ``I_t`` per draw, and the posterior-predictive in-bed counts come from `predict` on the model with the observations set to `missing`. Two small helpers reduce the per-draw trajectories to credible bands. ```@setup sir @@ -188,7 +188,7 @@ end ``` ```@example sir -gens = vec(generated_observables(posterior, y_obs, chain).generated) +gens = vec(returned(posterior, chain)) It = credible_bands(reduce(hcat, (g.I_t for g in gens))) pred = predict(as_turing_model(model, fill(missing, n), n), chain) diff --git a/src/ComposableTuringIDModels.jl b/src/ComposableTuringIDModels.jl index 532be41d6..877279fde 100644 --- a/src/ComposableTuringIDModels.jl +++ b/src/ComposableTuringIDModels.jl @@ -26,9 +26,8 @@ module ComposableTuringIDModels # write `using ComposableTuringIDModels, Distributions, Turing`. # Only the names the package itself uses or extends are imported below. -using DynamicPPL: DynamicPPL, @model, to_submodel, fix, condition, prefix, - returned -using Turing: Turing, filldist, sample, MCMCSerial, predict +using DynamicPPL: DynamicPPL, @model, to_submodel, prefix +using Turing: Turing, filldist, predict using FlexiChains: FlexiChains using CensoredDistributions: double_interval_censored # Several wrappers transform an argument before storing it, so they point @@ -46,12 +45,7 @@ using Random: AbstractRNG, randexp, default_rng using KernelFunctions: Kernel, SqExponentialKernel, Matern32Kernel, Matern52Kernel, with_lengthscale, kernelmatrix -# Inference-layer dependencies. -using ADTypes: ADTypes, AutoForwardDiff -using AbstractMCMC: AbstractMCMC -using AdvancedHMC: DiagEuclideanMetric -using MCMCChains: Chains -using DataFramesMeta: DataFrame, @rename! +# `ReportTriangle` accepts reports as a long-form table of rows. using Tables: rowtable # Distributions names used (and, for many, extended) by the package, imported @@ -77,7 +71,7 @@ export as_turing_submodel # Double-interval censoring comes from CensoredDistributions.jl and is not # re-exported here. export accumulate_scan, get_state, HalfNormal, SafePoisson, SafeNegativeBinomial, - NegativeBinomialMeanClust, condition_model + NegativeBinomialMeanClust # --- latent models --- export IID, HierarchicalNormal, RandomWalk, AR, MA, Intercept, @@ -131,9 +125,7 @@ export DataRequirements, StreamRequirement export IDModel # --- inference orchestration --- -export IDProblem, NUTSampler, DirectSample, - apply_method, IDObservables, generated_observables, - spread_draws, get_param_array, forecast +export IDProblem, forecast # --- extension points --- # Names a component author implements against but rarely calls. @@ -178,7 +170,6 @@ include("utils/SafeInt.jl") include("utils/SafePoisson.jl") include("utils/SafeNegativeBinomial.jl") include("utils/censored_pmf.jl") -include("utils/turing-methods.jl") # --- latent models --- include("latent_models/models/IID.jl") @@ -248,14 +239,7 @@ include("observation_models/traversal.jl") include("observation_models/requirements.jl") # --- inference orchestration --- -include("inference/types.jl") include("inference/IDProblem.jl") -include("inference/IDObservables.jl") -include("inference/apply_method.jl") -include("inference/NUTSampler.jl") -include("inference/DirectSample.jl") -include("inference/get_param_array.jl") -include("inference/post-inference.jl") include("inference/forecast.jl") end diff --git a/src/base/prettyprinting.jl b/src/base/prettyprinting.jl index d9610f263..d1cf78372 100644 --- a/src/base/prettyprinting.jl +++ b/src/base/prettyprinting.jl @@ -50,8 +50,12 @@ _node_label(model) = string(nameof(typeof(model))) # Recursively print the component children beneath an already-printed node, using # box-drawing connectors and an accumulated `prefix` for indentation. -function _print_component_tree(io::IO, children, prefix::AbstractString) - n = length(children) +# `trailing` holds already-formatted lines for siblings that are not components +# and so have no subtree of their own, such as the data an `IDProblem` carries. +function _print_component_tree( + io::IO, children, prefix::AbstractString; trailing = () + ) + n = length(children) + length(trailing) for (i, (role, child)) in enumerate(children) is_last = i == n print( @@ -61,6 +65,10 @@ function _print_component_tree(io::IO, children, prefix::AbstractString) child_prefix = string(prefix, is_last ? " " : "│ ") _print_component_tree(io, _component_children(child), child_prefix) end + for (i, line) in enumerate(trailing) + is_last = length(children) + i == n + print(io, '\n', prefix, is_last ? "└─ " : "├─ ", line) + end return nothing end diff --git a/src/compose.jl b/src/compose.jl index 7d5a9baa0..1587c13f2 100644 --- a/src/compose.jl +++ b/src/compose.jl @@ -169,14 +169,19 @@ Convenience 2-argument form: read the infection process's shape from the data. The observation model and the data together fix the shape of the infection process, so nothing about it needs to be supplied explicitly or stored on the -model. `as_turing_model(model, Y)` is `as_turing_model(model, Y, shape)` with -`shape` resolved via [`infection_strata`](@ref): the number of infection -strata the observation model consumes given the data's row count, paired with -the data's time length. +model. `as_turing_model(model, y_t)` is `as_turing_model(model, y_t, shape)` +with `shape` read from `y_t`: its time length, paired (when the data is +stratified) with the number of infection strata the observation model consumes, +resolved via [`infection_strata`](@ref). -Three age strata observed as one hospitalisation stream is -`Split(NegativeBinomialError(), [1.0 1.0 1.0])`; a `1 x T` data matrix then -builds a 3-stratum infection process. +The data may be a plain vector of observations, a `strata x time` matrix, or a +`NamedTuple` of per-stream series. Three age strata observed as one +hospitalisation stream is `Split(NegativeBinomialError(), [1.0 1.0 1.0])`; a +`1 x T` data matrix then builds a 3-stratum infection process. + +A scalar `missing` has no length to read, so simulating from the prior at a +chosen length is either `as_turing_model(model, missing, n)` or the two-argument +form over a blank series of that length. # Examples ```@example IDModel_shape @@ -193,14 +198,60 @@ sim = as_turing_model(model, Ymiss)() size(sim.I_t) ``` " -function as_turing_model(model::IDModel, Y::AbstractMatrix) - return as_turing_model(model, Y, _shape(model, Y)) +function as_turing_model(model::IDModel, y_t) + return as_turing_model(model, y_t, _data_shape(model, y_t)) +end + +# The `ModelShape` a model and a data value imply, over the data's own time +# length. +_data_shape(model::IDModel, y_t) = _obs_data_shape( + model.observation_model, y_t, _series_time_length(y_t) +) + +# A data value's length along the time axis. +# A `NamedTuple` of streams shares one time length, read off its first stream. +# A scalar `missing` has no axis to read, and saying so beats a `MethodError` +# from whichever helper reaches it first. +function _series_time_length(::Missing) + throw( + ArgumentError( + "a scalar `missing` carries no length to read a model shape from; \ + pass the number of observations, as `as_turing_model(model, missing, n)`, \ + or simulate over a blank series such as `Vector{Missing}(missing, n)`" + ) + ) +end +_series_time_length(y_t::AbstractVector) = length(y_t) +_series_time_length(y_t::AbstractMatrix) = size(y_t, 2) +_series_time_length(y_t::NamedTuple) = _series_time_length(first(y_t)) + +# The infection process's `ModelShape` implied by an observation model and a +# data value, shared by the two-argument `as_turing_model`, `IDProblem` and +# `forecast` so all three read a data-driven model's shape the same way. +# Data with no stream axis to read leaves the shape to the observation model +# alone: a scalar `missing`, and a blank series holding nothing but `missing`. +_obs_data_shape(obs, y_t, time_steps) = time_steps +_obs_data_shape(obs, y_t::Missing, time_steps) = _obs_data_shape_missing( + obs, time_steps +) +function _obs_data_shape(obs, y_t::AbstractVector{Missing}, time_steps) + return _obs_data_shape_missing(obs, time_steps) +end +function _obs_data_shape(obs, y_t::AbstractMatrix, time_steps) + return (infection_strata(obs, size(y_t, 1)), time_steps) +end +function _obs_data_shape(obs, y_t::NamedTuple, time_steps) + return (infection_strata(obs, length(y_t)), time_steps) end -function _shape(model::IDModel, Y::AbstractMatrix) - return (infection_strata(model.observation_model, size(Y, 1)), size(Y, 2)) +_obs_data_shape_missing(obs, time_steps) = time_steps +function _obs_data_shape_missing(s::Split, time_steps) + s.map === nothing || return (size(s.map, 2), time_steps) + s.names === nothing || return (length(s.names), time_steps) + return time_steps end + @doc raw" The number of infection strata an observation model consumes. diff --git a/src/inference/DirectSample.jl b/src/inference/DirectSample.jl deleted file mode 100644 index 2a19249f7..000000000 --- a/src/inference/DirectSample.jl +++ /dev/null @@ -1,31 +0,0 @@ -# Direct prior-sampling method. - -@doc raw" -Direct sampling from a model's prior (no MCMC). - -`apply_method(model, ::DirectSample)` samples the prior: with an integer -`n_samples` it draws that many times with `Turing.Prior()` (returning a chain), -and with `nothing` it draws once with `rand` (returning a `NamedTuple`). - -## Fields - - - `n_samples`: number of prior draws, or `nothing` for a single `rand` draw. -" -@kwdef struct DirectSample <: AbstractIDSamplingMethod - "Number of prior draws, or `nothing` for a single `rand` draw." - n_samples::Union{Int, Nothing} = nothing -end - -function _apply_method( - model::DynamicPPL.Model, method::DirectSample, - prev_result = nothing; kwargs... - ) - return _apply_direct_sample(model, method, method.n_samples; kwargs...) -end - -function _apply_direct_sample(model, method, n_samples::Int; kwargs...) - return sample( - model, Turing.Prior(), n_samples; kwargs... - ) -end -_apply_direct_sample(model, method, ::Nothing; kwargs...) = rand(model) diff --git a/src/inference/IDObservables.jl b/src/inference/IDObservables.jl deleted file mode 100644 index 30ae1e15c..000000000 --- a/src/inference/IDObservables.jl +++ /dev/null @@ -1,67 +0,0 @@ -# `IDObservables` container and `generated_observables` wrapper. - -@doc raw" -Container for the outputs of an inference run: the model, the data, the posterior -samples, and any generated quantities. - -## Fields - - - `model`: the model that was sampled. - - `data`: the data the model was conditioned on. - - `samples`: the posterior samples (or optimiser result). - - `generated`: generated quantities, or `missing` if not computed. -" -struct IDObservables{M, D, S, G} - "The model that was sampled." - model::M - "The data the model was conditioned on." - data::D - "The posterior samples (or optimiser result)." - samples::S - "Generated quantities, or `missing`." - generated::G -end - -@doc raw" -Wrap a model, data, and inference solution into an [`IDObservables`](@ref). - -When `solution` is an MCMC `Chains`, the model is re-run over the draws with -`DynamicPPL.returned` to recover the model's returned generated quantities (e.g. -`(; generated_y_t, expected_y_t, I_t, Z_t)`) per sample, stored in the -`generated` field. For -any other solution (an optimiser result, a prior draw, …) there are no per-draw -generated quantities, so `generated` is `missing`. - -# Arguments - - - `model`: the model that was sampled (a conditioned `DynamicPPL.Model`). - - `data`: the data the model was conditioned on. - - `solution`: the inference solution (samples or optimiser result). - -# Examples -```@example generated_observables -using ComposableTuringIDModels, Distributions -m = as_turing_model( - IDModel( - DirectInfections(; Z = RandomWalk(), initialisation = Normal()), - PoissonError()), missing, 10) -generated_observables(m, (; y_t = missing), rand(m)) -``` -" -function generated_observables(model, data, solution) - return IDObservables(model, data, solution, _generated_quantities(model, solution)) -end - -# Re-run the conditioned model over the posterior draws to recover its returned -# generated quantities per draw. -# `solution` may be an `MCMCChains.Chains` or a FlexiChains chain, so rather than -# dispatching on a concrete chain type this asks `returned` to consume it and -# treats anything it cannot as having no generated quantities. -_generated_quantities(model, solution) = missing -function _generated_quantities(model::DynamicPPL.Model, solution) - return try - returned(model, solution) - catch - missing - end -end diff --git a/src/inference/IDProblem.jl b/src/inference/IDProblem.jl index 495dd5425..bd0e0a229 100644 --- a/src/inference/IDProblem.jl +++ b/src/inference/IDProblem.jl @@ -1,104 +1,145 @@ -# `IDProblem`: an infection + observation model over a time span. +# `IDProblem`: a composed model paired with the data it is fitted to. @doc raw" -A full epidemiological inference problem: an infection process, an observation -model, and a time span. The latent (parameter) process is owned by the infection -model, so it is not a separate slot here. - -`as_turing_model(problem, data)` assembles the corresponding [`IDModel`](@ref) -over `tspan` and conditions it on `data.y_t`. The infection process's shape is -read from the observation model and `data.y_t` at build time (see -[`infection_strata`](@ref)), not stored on the problem: a plain vector (or -`missing`) gives a single-series infection process, exactly as today, while a -data matrix or a `NamedTuple` of streams gives a stratified infection process -with one row per stratum. +A composed model and the data it is fitted to, held together. + +An [`IDModel`](@ref) says what the process is; the data says how long it runs +and how many streams it has. `IDProblem` is the pair, so the two travel +together and cannot drift apart. From it, +[`as_turing_model(problem)`](@ref as_turing_model) builds the +`DynamicPPL.Model` and [`data_requirements(problem)`](@ref data_requirements) +reports what the model asks of the data, neither of which needs the length +restating. + +The shape of the infection process is read from the observation model and the +data at build time (see [`infection_strata`](@ref)), not stored: a plain vector +gives a single-series infection process, while a `strata x time` matrix or a +`NamedTuple` of streams gives a stratified one. Simulating from the prior is a +problem over a blank series, `Vector{Missing}(missing, n)`, which carries the +length the same way observations do. + +Printing an `IDProblem` shows the component tree and a summary of the data, +which is the reason to hold one rather than a conditioned `DynamicPPL.Model`: +the latter renders as its full nested parametric type with the observations +dumped inline. # Arguments - - `idproblem`: the [`IDProblem`](@ref). - - `data`: a value with a `y_t` field holding the observations (or `missing`). + - `model`: the composed [`IDModel`](@ref), or an infection model and an + observation model to compose into one. + - `data`: the observations the model is fitted to. A vector, a + `strata x time` matrix, or a `NamedTuple` of streams. # Examples ```@example IDProblem using ComposableTuringIDModels, Distributions problem = IDProblem( - infection = DirectInfections(; Z = RandomWalk(), initialisation = Normal()), - observation_model = PoissonError(), - tspan = (1, 20)) -rand(as_turing_model(problem, (; y_t = missing))) + DirectInfections(; Z = RandomWalk(), initialisation = Normal()), + PoissonError(), + Vector{Missing}(missing, 20)) +``` + +```@example IDProblem +rand(as_turing_model(problem)) ``` ## Fields - - `infection`: the infection process model. - - `observation_model`: the observation model. - - `tspan`: the `(first, last)` time span of the observations. An observation - chain with delays consumes the head of the series it is handed, so the - infection process runs over a longer span than this; see - [`observation_lead_in`](@ref). + - `model`: the composed [`IDModel`](@ref). + - `data`: the observations. " -@kwdef struct IDProblem{I <: AbstractInfectionModel, O <: AbstractObservationModel} - "The infection process model." - infection::I - "The observation model." - observation_model::O - "The `(first, last)` time span of the observations." - tspan::Tuple{Int, Int} +struct IDProblem{M <: IDModel, D} + "The composed model." + model::M + "The observations the model is fitted to." + data::D end -# The infection process's `ModelShape` implied by an observation model and a -# data value, shared by `IDProblem` and `forecast` so the two build a -# data-driven model's shape the same way. -# With `y_t === missing` there is no data to read a stream count from, so the -# shape falls back to the observation model alone. -_obs_data_shape(obs, y_t, time_steps) = time_steps -_obs_data_shape(obs, y_t::Missing, time_steps) = _obs_data_shape_missing( - obs, time_steps -) -function _obs_data_shape(obs, y_t::AbstractMatrix, time_steps) - return (infection_strata(obs, size(y_t, 1)), time_steps) -end -function _obs_data_shape(obs, y_t::NamedTuple, time_steps) - return (infection_strata(obs, length(y_t)), time_steps) +function IDProblem( + infection::AbstractInfectionModel, observation_model::AbstractObservationModel, + data + ) + return IDProblem(IDModel(infection, observation_model), data) end -_obs_data_shape_missing(obs, time_steps) = time_steps -function _obs_data_shape_missing(s::Split, time_steps) - s.map === nothing || return (size(s.map, 2), time_steps) - s.names === nothing || return (length(s.names), time_steps) - return time_steps -end +# The problem's lead-in and observation chain are its model's, so a requirements +# report reads the same either way. +observation_lead_in(problem::IDProblem) = observation_lead_in(problem.model) +_observation_chain(problem::IDProblem) = _observation_chain(problem.model) + +# The problem holds both halves, so it reports what the model asks of the data +# with no arguments at all. +# There is deliberately no `data_fits(::IDProblem)`: the observation count comes +# from the same data the report is checked against, so for a single series the +# answer is true by construction and would be false reassurance. Asking whether +# a dataset fits a model is `data_fits(model, y_t, n)`, where the two are +# independent. +_problem_shape(problem::IDProblem) = _data_shape(problem.model, problem.data) + +data_requirements(problem::IDProblem) = data_requirements( + problem.model, problem.data, _problem_shape(problem) +) -# The problem's lead-in is its observation model's, and `tspan` is the span of -# the OBSERVATIONS, so a requirements report needs no separate `n`. -function observation_lead_in(idproblem::IDProblem) - return observation_lead_in(idproblem.observation_model) -end +@doc raw" +Build the `DynamicPPL.Model` for an [`IDProblem`](@ref). -_observation_chain(idproblem::IDProblem) = idproblem.observation_model +The problem already holds the data, so there is no length to restate: +`as_turing_model(problem)` is `as_turing_model(problem.model, problem.data)`. +Pass a second argument to refit the same model to different data, as in a +rolling refit over a growing series. -data_requirements(idproblem::IDProblem, data) = data_requirements( - idproblem, data.y_t, _tspan_length(idproblem) -) +# Arguments -data_requirements(idproblem::IDProblem) = data_requirements( - idproblem, missing, _tspan_length(idproblem) -) + - `problem`: the [`IDProblem`](@ref). + - `data`: (optional) observations to use in place of the problem's own. +" +as_turing_model(problem::IDProblem) = as_turing_model(problem.model, problem.data) +as_turing_model(problem::IDProblem, data) = as_turing_model(problem.model, data) + +# --- printing --------------------------------------------------------------- + +# The model's components hang directly off the problem, with the data as a final +# sibling, so the pairing reads as one tree rather than as a model with a +# footnote. +function Base.show(io::IO, ::MIME"text/plain", problem::IDProblem) + print(io, "IDProblem") + _print_component_tree( + io, _component_children(problem.model), ""; + trailing = (string("data: ", _data_summary(problem.data)),) + ) + return nothing +end -# Disambiguation: a bare `ModelShape` second argument is a length, not a data -# carrier, so it overrides the problem's own `tspan`. -data_requirements(idproblem::IDProblem, n::ModelShape) = data_requirements( - idproblem, missing, n -) +Base.show(io::IO, ::IDProblem) = print(io, "IDProblem") + +# One line describing what the problem holds, in the same vocabulary +# `data_requirements` uses: streams, observations and the shape they come in. +function _data_summary(y::AbstractVector) + n = length(y) + blank = count(ismissing, y) + blank == n && return "none, $n time points (simulating from the prior)" + counted = string(n, " observation", n == 1 ? "" : "s") + blank == 0 && return string(counted, " (", eltype(y), ")") + return string(counted, ", ", blank, " missing") +end -_tspan_length(idproblem::IDProblem) = - idproblem.tspan[end] - idproblem.tspan[1] + 1 +function _data_summary(y::AbstractMatrix) + strata, n = size(y) + return string( + strata, " strat", strata == 1 ? "um" : "a", " x ", n, + " observation", n == 1 ? "" : "s" + ) +end -@model function as_turing_model(idproblem::IDProblem, data) - y_t = data.y_t - time_steps = _tspan_length(idproblem) - model = IDModel(idproblem.infection, idproblem.observation_model) - shape = _obs_data_shape(idproblem.observation_model, y_t, time_steps) - out ~ as_turing_submodel(model, y_t, shape) - return out +function _data_summary(y::NamedTuple) + n_streams = length(y) + names = join(keys(y), ", ") + return string( + n_streams, " stream", n_streams == 1 ? "" : "s", " (", names, "), ", + _series_time_length(y), " observations each" + ) end + +# Anything else names its type rather than printing itself, since the point of +# the summary is to stay one line. +_data_summary(y) = string(typeof(y)) diff --git a/src/inference/NUTSampler.jl b/src/inference/NUTSampler.jl deleted file mode 100644 index 077e4edf9..000000000 --- a/src/inference/NUTSampler.jl +++ /dev/null @@ -1,68 +0,0 @@ -# NUTS sampling method. - -@doc raw" -NUTS sampling method for a `DynamicPPL.Model`. - -## Fields - - - `target_acceptance`: target acceptance rate. - - `adtype`: automatic-differentiation backend. - - `mcmc_parallel`: MCMC parallelisation strategy. - - `nchains`: number of chains. - - `max_depth`: NUTS tree-depth limit. - - `Δ_max`: divergence threshold. - - `init_ϵ`: initial step size (`0.0` lets NUTS find one). - - `ndraws`: total draws. - - `metricT`: HMC metric type. - - `nadapts`: adaptation steps (`-1` uses the Turing default). -" -@kwdef struct NUTSampler{ - A <: ADTypes.AbstractADType, - E <: AbstractMCMC.AbstractMCMCEnsemble, M, - } <: AbstractIDSamplingMethod - "Target acceptance rate." - target_acceptance::Float64 = 0.8 - "Automatic-differentiation backend." - adtype::A = AutoForwardDiff() - "MCMC parallelisation strategy." - mcmc_parallel::E = MCMCSerial() - "Number of chains." - nchains::Int = 1 - "NUTS tree-depth limit." - max_depth::Int = 10 - "Divergence threshold." - Δ_max::Float64 = 1000.0 - "Initial step size (`0.0` lets NUTS find one)." - init_ϵ::Float64 = 0.0 - "Total draws." - ndraws::Int - "HMC metric type." - metricT::M = DiagEuclideanMetric - "Adaptation steps (`-1` uses the Turing default)." - nadapts::Int = -1 -end - -function _apply_method( - model::DynamicPPL.Model, method::NUTSampler, prev_result = nothing; - kwargs... - ) - return _apply_nuts(model, method, prev_result; kwargs...) -end - -function _apply_nuts(model, method, prev_result; kwargs...) - nuts = Turing.NUTS( - method.target_acceptance; adtype = method.adtype, - max_depth = method.max_depth, Δ_max = method.Δ_max, - init_ϵ = method.init_ϵ, metricT = method.metricT - ) - # The AbstractMCMC keyword is `n_adapts`, and the old `nadapts` was silently - # swallowed by `kwargs...`, so `NUTSampler.nadapts` never took effect. - # `nadapts == -1` is the sentinel for the Turing default, so only an explicit - # value is forwarded. - adapt_kwargs = method.nadapts == -1 ? (;) : (; n_adapts = method.nadapts) - return sample( - model, nuts, - method.mcmc_parallel, method.ndraws ÷ method.nchains, method.nchains; - adapt_kwargs..., kwargs... - ) -end diff --git a/src/inference/apply_method.jl b/src/inference/apply_method.jl deleted file mode 100644 index 937dcc4e8..000000000 --- a/src/inference/apply_method.jl +++ /dev/null @@ -1,55 +0,0 @@ -# `apply_method` driver: condition a model and run an inference method. - -@doc raw" -Condition a model by fixing some parameters and conditioning on others, then run -an inference `method`. - -# Arguments - - - `idproblem`: the [`IDProblem`](@ref) (or a `DynamicPPL.Model`). - - `method`: the inference method (a sampler, e.g. [`NUTSampler`](@ref)). - - `data`: the data to condition on (with a `y_t` field). - -# Keyword Arguments - - - `fix_parameters`: a `NamedTuple` of parameters to fix. - - `condition_parameters`: a `NamedTuple` of parameters to condition on. - - `kwargs...`: forwarded to the inference method. - -# Examples -```@example apply_method -using ComposableTuringIDModels, Distributions -problem = IDProblem( - infection = DirectInfections(; Z = RandomWalk(), initialisation = Normal()), - observation_model = PoissonError(), - tspan = (1, 20)) -y = rand(as_turing_model(problem, (; y_t = missing))) -nothing -``` -" -function apply_method( - idproblem::IDProblem, method::AbstractIDMethod, data; - fix_parameters::NamedTuple = NamedTuple(), - condition_parameters::NamedTuple = NamedTuple(), kwargs... - ) - model = as_turing_model(idproblem, data) - cond_model = condition_model(model, fix_parameters, condition_parameters) - return apply_method(cond_model, method, data; kwargs...) -end - -function apply_method( - model::DynamicPPL.Model, method::AbstractIDMethod, data; - kwargs... - ) - solution = _run_method(model, method; kwargs...) - return generated_observables(model, data, solution) -end - -function apply_method(model::DynamicPPL.Model, method::AbstractIDMethod; kwargs...) - return apply_method(model, method, nothing; kwargs...) -end - -# Run a method to its raw solution. -function _run_method(model::DynamicPPL.Model, method::AbstractIDMethod; kwargs...) - return _apply_method(model, method, nothing; kwargs...) -end diff --git a/src/inference/forecast.jl b/src/inference/forecast.jl index ee3d1b99b..4c091aaca 100644 --- a/src/inference/forecast.jl +++ b/src/inference/forecast.jl @@ -16,7 +16,7 @@ uncertainty. single-series case), a `strata x T` matrix (extended by `horizon` further columns), or a `NamedTuple` of per-stream series (each stream extended in turn). The strata count, when there is one, is read from the observation model -and `y` exactly as [`IDProblem`](@ref) reads it at build time. +and `y` exactly as [`as_turing_model`](@ref) reads it at build time. This works because the package's latent processes are non-centred: a [`RandomWalk`](@ref), [`AR`](@ref) or [`MA`](@ref) accumulates an i.i.d. sequence @@ -38,8 +38,8 @@ The result is a chain of the same shape as the input holding the predicted observations, indexable per time point as `y_t[T+1] … y_t[T+h]`. The in-sample points are generated too, so the same chain carries the in-sample posterior predictive; the fitted latent path is unchanged either way, because `y_t` never -feeds back into it. Pass the chain to [`generated_observables`](@ref) or -`returned` to recover the extended latent trajectories per draw. +feeds back into it. Pass the chain to `DynamicPPL.returned` to recover the +extended latent trajectories per draw. The extension is exact for the package's non-centred processes because their future innovations are independent of the fitted history. A latent whose *stored* @@ -90,11 +90,6 @@ function forecast( return predict(rng, fc_model, extended) end -# A `NamedTuple` of streams shares one time length, read off its first stream. -_series_time_length(y::AbstractVector) = length(y) -_series_time_length(y::AbstractMatrix) = size(y, 2) -_series_time_length(y::NamedTuple) = _series_time_length(first(y)) - # A wholly unobserved series shaped like `y`. # The stream names of a `NamedTuple` are what tells a data-driven `Split` which # streams to build, so they are preserved. @@ -106,15 +101,14 @@ _blank_series(y::NamedTuple, n_time) = map(v -> _blank_series(v, n_time), y) @doc raw" Forecast from a fitted [`IDProblem`](@ref); see [`forecast`](@ref) for the model -method. The observation model and infection process are taken from the problem, -and the horizon extends the problem's `tspan`. +method. The problem holds the series it was fitted to, so only the chain and the +horizon are needed. " function forecast( - problem::IDProblem, y, chain, horizon::Integer; + problem::IDProblem, chain, horizon::Integer; rng::AbstractRNG = default_rng() ) - model = IDModel(problem.infection, problem.observation_model) - return forecast(model, y, chain, horizon; rng = rng) + return forecast(problem.model, problem.data, chain, horizon; rng = rng) end # Extend the latent innovation streams in `chain` to the length `fc_model` diff --git a/src/inference/get_param_array.jl b/src/inference/get_param_array.jl deleted file mode 100644 index 288438e95..000000000 --- a/src/inference/get_param_array.jl +++ /dev/null @@ -1,19 +0,0 @@ -# Reshape a `Chains` object into a `(draws x chains)` array of `NamedTuple`s. - -@doc raw" -Reshape an `MCMCChains.Chains` object into a `(draws × chains)` array of -per-sample `NamedTuple`s. - -# Arguments - - - `chn`: the `Chains` object. - -# Examples -```@example get_param_array -using ComposableTuringIDModels -nothing -``` -" -function get_param_array(chn::Chains) - return rowtable(chn) |> x -> reshape(x, size(chn, 1), size(chn, 3)) -end diff --git a/src/inference/post-inference.jl b/src/inference/post-inference.jl deleted file mode 100644 index efa5e64ab..000000000 --- a/src/inference/post-inference.jl +++ /dev/null @@ -1,29 +0,0 @@ -# Post-inference tidy helper: spread a `Chains` object into a tidy `DataFrame`. - -@doc raw" -Convert an `MCMCChains.Chains` object to a tidy `DataFrame` (one row per draw, -with `draw`, `chain`, and `iteration` columns). - -# Arguments - - - `chn`: the `Chains` object to convert. - -# Examples -```@example spread_draws -using ComposableTuringIDModels -nothing -``` -" -function spread_draws(chn::Chains) - df = DataFrame(chn) - # Current MCMCChains emits the bookkeeping columns as `.iteration` and - # `.chain`, and older versions used undotted names, so accept either. - # A sequential `draw` index is added in tidybayes style. - for (dotted, plain) in ((".iteration", "iteration"), (".chain", "chain")) - if dotted in names(df) - @rename!(df, $(plain) = $(dotted)) - end - end - df = hcat(DataFrame(draw = 1:size(df, 1)), df) - return df -end diff --git a/src/inference/types.jl b/src/inference/types.jl deleted file mode 100644 index b4138881e..000000000 --- a/src/inference/types.jl +++ /dev/null @@ -1,11 +0,0 @@ -# Inference-method supertypes. - -@doc raw" -Abstract supertype for inference / generative-modelling methods. -" -abstract type AbstractIDMethod end - -@doc raw" -Abstract supertype for sampling-based methods (e.g. NUTS). -" -abstract type AbstractIDSamplingMethod <: AbstractIDMethod end diff --git a/src/observation_models/requirements.jl b/src/observation_models/requirements.jl index c267b47f8..99a30ee67 100644 --- a/src/observation_models/requirements.jl +++ b/src/observation_models/requirements.jl @@ -355,7 +355,8 @@ that builds its own prompts from them. - `y_t`: (optional) the data, to report what was supplied alongside what is required. - `n`: the number of observations (an `Int`, or the `(n_strata, n_time)` shape - of a stratified model). An [`IDProblem`](@ref) reads it from `tspan`. + of a stratified model). An [`IDProblem`](@ref) already holds its data, so + `data_requirements(problem)` needs neither. # Examples ```@example data_requirements @@ -588,9 +589,8 @@ end # is scored at the end. # The one exception is a shortfall of exactly the chain's lead-in. # -# This walks the chain rather than building a `DataRequirements`. -# An `IDProblem`'s model body reassembles its `IDModel` on every evaluation, so -# the check runs per evaluation and must not allocate. +# This walks the chain rather than building a `DataRequirements`, because it runs +# once per model build and must not allocate. function _check_observation_count(model, y_t, n::ModelShape) chain = _observation_chain(model) lead_in = observation_lead_in(chain) diff --git a/src/utils/turing-methods.jl b/src/utils/turing-methods.jl deleted file mode 100644 index d231fdd92..000000000 --- a/src/utils/turing-methods.jl +++ /dev/null @@ -1,34 +0,0 @@ -# Turing helper: fix-and-condition a `DynamicPPL.Model`. - -@doc raw" -Condition a `DynamicPPL.Model` by fixing some parameters and conditioning on -others. - -```julia -condition_model(model, fix_parameters, condition_parameters) -``` - -equals `condition(fix(model, fix_parameters), condition_parameters)`. Either -named tuple may be empty. - -# Arguments - - - `model`: the `DynamicPPL.Model` to fix and condition. - - `fix_parameters`: a named tuple of parameters to fix to constant values. - - `condition_parameters`: a named tuple of parameters to condition on data. - -# Examples -```@example condition_model -using ComposableTuringIDModels, Distributions -m = as_turing_model(RandomWalk(), 10) -condition_model(m, (init = 0.0,), NamedTuple()) -``` -" -function condition_model( - model::DynamicPPL.Model, fix_parameters::NamedTuple, - condition_parameters::NamedTuple - ) - _model = fix(model, fix_parameters) - _model = condition(_model, condition_parameters) - return _model -end diff --git a/test/Project.toml b/test/Project.toml index 0b18d22b5..7b7231a3a 100644 --- a/test/Project.toml +++ b/test/Project.toml @@ -5,7 +5,6 @@ Aqua = "4c88cf16-eb10-579e-8560-4a9242c79595" BenchmarkTools = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf" Catalyst = "479239e8-5488-4da2-87a7-35f2df7eef83" ComposableTuringIDModels = "cbebd14a-101c-4997-a79f-d008ad7c07b2" -DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0" DifferentiationInterface = "a0c0ee7d-e4b9-4e03-894e-1c5f64a51d63" DifferentiationInterfaceTest = "a82114a7-5aa3-49a8-9643-716bb13727a3" Distributions = "31c24e10-a181-5473-b8eb-7969acd0382f" @@ -18,7 +17,6 @@ KernelFunctions = "ec8451be-7e33-11e9-00cf-bbf324bd1392" LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" LogDensityProblems = "6fdf6af0-433a-55f7-b3ed-c6c6e0b8df7c" LogExpFunctions = "2ab3a3ac-af41-5b50-aa03-7779005ae688" -MCMCChains = "c7f686f2-ff18-58e9-bc7b-31028e88f75d" ModelingToolkit = "961ee093-0014-501f-94e3-6117800e7a78" OrdinaryDiffEq = "1dea7af3-3e70-54e6-95c3-0bf5283fa5ed" Pkg = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" @@ -38,7 +36,6 @@ ADTypes = "1.23.0" Aqua = "0.8.16" BenchmarkTools = "1.8.0" Catalyst = "16.2.3" -DataFrames = "1.8.2" DifferentiationInterface = "0.7.20" Distributions = "0.25.130" Documenter = "1.17.0" diff --git a/test/unit/base/interfaces.jl b/test/unit/base/interfaces.jl index e2294d3c5..af0797e55 100644 --- a/test/unit/base/interfaces.jl +++ b/test/unit/base/interfaces.jl @@ -95,10 +95,8 @@ end # A latent model is not an infection model, so it cannot fill the infection # slot either. @test_throws MethodError IDModel(latent, obs) - # IDProblem enforces the same role slots (keyword struct → TypeError). - @test_throws Union{MethodError, TypeError} IDProblem( - infection = obs, observation_model = obs, tspan = (1, 10) - ) + # IDProblem enforces the same role slots when it composes the pair itself. + @test_throws MethodError IDProblem(obs, obs, fill(5, 10)) # A latent manipulator cannot wrap an observation model (slot is latent; # keyword constructor → TypeError). @test_throws Union{MethodError, TypeError} DiffLatentModel(; diff --git a/test/unit/compose_strata.jl b/test/unit/compose_strata.jl index 4cf9e1dd7..1d3db63d3 100644 --- a/test/unit/compose_strata.jl +++ b/test/unit/compose_strata.jl @@ -107,3 +107,31 @@ end @test e.young ≈ 0.7 .* vec(sim.I_t) @test e.old ≈ 0.3 .* vec(sim.I_t) end + +@testitem "two-argument as_turing_model reads the shape from any data form" begin + using ComposableTuringIDModels, Distributions, DynamicPPL, Random + Random.seed!(806) + infection = DirectInfections(; Z = RandomWalk(), initialisation = Normal()) + + # A vector of observations gives its own length, so nothing is restated. + model = IDModel(infection, PoissonError()) + y = fill(5, 14) + @test keys(VarInfo(as_turing_model(model, y))) == + keys(VarInfo(as_turing_model(model, y, length(y)))) + @test length(as_turing_model(model, Vector{Missing}(missing, 14))().Z_t) == 14 + + # A `NamedTuple` of streams gives the stream count and the shared time + # length. + split = IDModel( + DirectInfections(; + Z = Stratify(RandomWalk(), FixedIntercept(0.0)), + initialisation = IID(Normal(log(20), 0.2)) + ), + Split((a = PoissonError(), b = PoissonError())) + ) + sim = as_turing_model(split, (a = fill(5, 12), b = fill(3, 12)))() + @test size(sim.I_t) == (2, 12) + + # A scalar `missing` carries no length, and says so. + @test_throws ArgumentError as_turing_model(model, missing) +end diff --git a/test/unit/inference/inference.jl b/test/unit/inference/inference.jl index 072901813..b4052b952 100644 --- a/test/unit/inference/inference.jl +++ b/test/unit/inference/inference.jl @@ -1,22 +1,107 @@ -@testitem "IDProblem assembles and simulates a composed model" begin +@testitem "IDProblem pairs a model with its data and needs no length" begin using ComposableTuringIDModels, Distributions, Random + using DynamicPPL: VarInfo Random.seed!(71) - problem = IDProblem( - infection = DirectInfections(; Z = RandomWalk(), initialisation = Normal()), - observation_model = PoissonError(), - tspan = (1, 20) - ) - m = as_turing_model(problem, (; y_t = missing)) - sim = m() + infection = DirectInfections(; Z = RandomWalk(), initialisation = Normal()) + problem = IDProblem(infection, PoissonError(), Vector{Missing}(missing, 20)) + @test problem.model == IDModel(infection, PoissonError()) + sim = as_turing_model(problem)() @test length(sim.generated_y_t) == 20 @test length(sim.Z_t) == 20 + + # The problem's route and the model's route build the same model, so + # holding one is a convenience rather than a fork in the API. + model = IDModel(infection, PoissonError()) + y = sim.generated_y_t + @test keys(VarInfo(as_turing_model(IDProblem(model, y)))) == + keys(VarInfo(as_turing_model(model, y, length(y)))) + + # A second argument refits the same model to different data. + @test length(as_turing_model(problem, fill(5, 12))().generated_y_t) == 12 +end + +@testitem "IDProblem prints its component tree and a data summary" begin + using ComposableTuringIDModels, Distributions + infection = DirectInfections(; Z = RandomWalk(), initialisation = Normal()) + render(x) = sprint(show, MIME"text/plain"(), x) + + plain = render(IDProblem(infection, PoissonError(), fill(5, 30))) + @test startswith(plain, "IDProblem\n") + # The model's components hang off the problem rather than under a node of + # their own, and the data is the last sibling. + @test occursin("├─ infection: DirectInfections", plain) + @test occursin("├─ observation: PoissonError", plain) + @test occursin("└─ data: 30 observations (Int64)", plain) + + # A wholly blank series says it is simulating rather than reporting zero + # observations. + blank = render(IDProblem(infection, PoissonError(), Vector{Missing}(missing, 30))) + @test occursin("└─ data: none, 30 time points (simulating from the prior)", blank) + + gappy = render( + IDProblem( + infection, PoissonError(), + Vector{Union{Missing, Int}}([missing; fill(5, 29)]) + ) + ) + @test occursin("└─ data: 30 observations, 1 missing", gappy) + + streams = render( + IDProblem( + infection, Split((cases = PoissonError(), deaths = PoissonError())), + (cases = fill(5, 30), deaths = fill(1, 30)) + ) + ) + @test occursin( + "└─ data: 2 streams (cases, deaths), 30 observations each", streams + ) + + strata = render( + IDProblem( + DirectInfections(; + Z = Stratify(RandomWalk(), FixedIntercept(0.0)), + initialisation = IID(Normal()) + ), + PoissonError(), fill(5, 2, 30) + ) + ) + @test occursin("└─ data: 2 strata x 30 observations", strata) + + # Compact rendering stays one line, as it does for a component. + @test sprint(show, IDProblem(infection, PoissonError(), fill(5, 30))) == + "IDProblem" +end + +@testitem "IDProblem reports its own data requirements" begin + using ComposableTuringIDModels, Distributions + infection = DirectInfections(; Z = RandomWalk(), initialisation = Normal()) + obs = LatentDelay(PoissonError(), fill(1 / 5, 5)) # lead-in 4 + + problem = IDProblem(infection, obs, fill(10, 30)) + @test data_requirements(problem).n == 30 + @test data_requirements(problem).series_length == 34 + # The report is the model's over the same data, printed the same way. + report(x...) = sprint(show, MIME"text/plain"(), data_requirements(x...)) + @test report(problem) == report(problem.model, fill(10, 30), 30) + + # A stratified problem reports on the stratum axis, because the shape comes + # from the same helper `as_turing_model` builds with. + strata = IDProblem( + DirectInfections(; + Z = Stratify(RandomWalk(), FixedIntercept(0.0)), + initialisation = IID(Normal()) + ), + obs, fill(10, 2, 30) + ) + @test data_requirements(strata).n == 30 end @testitem "_obs_data_shape resolves stratified shapes from data or Split" begin using ComposableTuringIDModels, Distributions using ComposableTuringIDModels: _obs_data_shape, _obs_data_shape_missing - # `IDProblem` and `forecast` share this helper, so every branch it can - # take is exercised directly here rather than only through the callers. + # The two-argument `as_turing_model`, `IDProblem` and `forecast` share this + # helper, so every branch it can take is exercised directly here rather + # than only through the callers. plain = PoissonError() Y = fill(5.0, 2, 10) @test _obs_data_shape(plain, Y, 10) == (2, 10) # AbstractMatrix y_t @@ -30,6 +115,9 @@ end # `y_t === missing` falls back to `_obs_data_shape_missing`; its three # `Split` branches (map / names / neither) are each checked in turn. @test _obs_data_shape(plain, missing, 10) == 10 + # A blank series carries a length but no stream axis, so it reaches the + # same fallback a scalar `missing` does. + @test _obs_data_shape(mapped, Vector{Missing}(missing, 10), 10) == (3, 10) @test _obs_data_shape_missing(mapped, 10) == (3, 10) # map branch @test _obs_data_shape_missing(named, 10) == (2, 10) # names branch # Data-driven strata mode: no map, no names (both set at data time), so @@ -45,80 +133,21 @@ end T = 12 # A Split with a weight map fixes the infection-stratum count at the # map's column count, regardless of the (1-stream) data. - problem_map = IDProblem( - infection = DirectInfections(; - Z = Stratify( - RandomWalk(), Hierarchy(; across = IID(Normal(0, 0.5))) - ), - initialisation = Normal(log(20), 0.2) - ), - observation_model = Split(PoissonError(), [1.0 1.0 1.0]), - tspan = (1, T) + infection = DirectInfections(; + Z = Stratify(RandomWalk(), Hierarchy(; across = IID(Normal(0, 0.5)))), + initialisation = Normal(log(20), 0.2) ) Y = Matrix{Union{Missing, Float64}}(missing, 1, T) - sim_map = as_turing_model(problem_map, (; y_t = Y))() - @test size(sim_map.I_t) == (3, T) + problem_map = IDProblem(infection, Split(PoissonError(), [1.0 1.0 1.0]), Y) + @test size(as_turing_model(problem_map)().I_t) == (3, T) - # A Split with named streams and `y_t = missing` builds one stratum per - # name. + # A Split with named streams over a blank series builds one stratum per + # name, reading the length off the series. problem_named = IDProblem( - infection = DirectInfections(; - Z = Stratify( - RandomWalk(), Hierarchy(; across = IID(Normal(0, 0.5))) - ), - initialisation = Normal(log(20), 0.2) - ), - observation_model = Split((a = PoissonError(), b = PoissonError())), - tspan = (1, T) - ) - sim_named = as_turing_model(problem_named, (; y_t = missing))() - @test size(sim_named.I_t) == (2, T) -end - -@testitem "apply_method runs a NUTSampler over an IDProblem" tags = [:sample] begin - using ComposableTuringIDModels, Distributions, Random - Random.seed!(72) - problem = IDProblem( - infection = DirectInfections(; Z = RandomWalk(), initialisation = Normal()), - observation_model = PoissonError(), - tspan = (1, 20) - ) - ydata = as_turing_model(problem, (; y_t = missing))().generated_y_t - res = apply_method(problem, NUTSampler(; ndraws = 40, nchains = 1), (; y_t = ydata)) - @test res isa IDObservables - @test res.samples !== nothing - # Generated quantities are now recovered from the chain (previously always - # `missing`); `returned` yields the model's `(; generated_y_t, I_t, Z_t)` - # per draw. - @test res.generated !== missing -end - -@testitem "spread_draws produces tidy draw/chain/iteration columns" tags = [:sample] begin - using ComposableTuringIDModels, Distributions, Turing, MCMCChains, Random - Random.seed!(74) - @model f() = (x ~ Normal()) - chn = MCMCChains.Chains(sample(f(), NUTS(), 30; progress = false)) - df = spread_draws(chn) - @test all(c -> c in names(df), ["draw", "chain", "iteration"]) - @test size(df, 1) == 30 -end - -@testitem "generated_observables wraps model, data, and solution" begin - using ComposableTuringIDModels, Distributions, Random - Random.seed!(75) - m = as_turing_model( - IDModel( - DirectInfections(; Z = RandomWalk(), initialisation = Normal()), - PoissonError() - ), missing, 10 + infection, Split((a = PoissonError(), b = PoissonError())), + Vector{Missing}(missing, T) ) - obs = generated_observables(m, (; y_t = missing), rand(m)) - @test obs isa IDObservables - @test obs.model === m - # `returned` recovers the model's generated quantities for any draw it can - # consume (a chain or, as here, a single draw); only solutions it cannot - # consume (e.g. an optimiser result) leave `generated` as `missing`. - @test obs.generated !== missing + @test size(as_turing_model(problem_named)().I_t) == (2, T) end @testitem "forecast rejects a non-positive horizon" begin @@ -190,18 +219,16 @@ end @testitem "forecast works through an IDProblem and an AR latent" tags = [:sample] begin using ComposableTuringIDModels, Distributions, Turing, Random Random.seed!(102) - problem = IDProblem( - infection = DirectInfections(; Z = AR(), initialisation = Normal()), - observation_model = PoissonError(), - tspan = (1, 18) - ) T, h = 18, 5 - y = as_turing_model(problem, (; y_t = missing))().generated_y_t - chain = sample( - as_turing_model(problem, (; y_t = y)), Prior(), 30; - progress = false - ) - fc = forecast(problem, y, chain, h) + infection = DirectInfections(; Z = AR(), initialisation = Normal()) + y = as_turing_model( + IDProblem(infection, PoissonError(), Vector{Missing}(missing, T)) + )().generated_y_t + # The fitted problem holds the series, so the forecast needs only the chain + # and the horizon. + problem = IDProblem(infection, PoissonError(), y) + chain = sample(as_turing_model(problem), Prior(), 30; progress = false) + fc = forecast(problem, chain, h) @test size(fc, 1) == 30 @test length(vec(fc[@varname(y_t[T + h])])) == 30 end @@ -315,24 +342,6 @@ end @test_throws DomainError forecast(model, y, chain, 6) end -@testitem "generated_observables leaves non-chain solutions missing" begin - using ComposableTuringIDModels, Distributions, Random - Random.seed!(76) - m = as_turing_model( - IDModel( - DirectInfections(; Z = RandomWalk(), initialisation = Normal()), - PoissonError() - ), missing, 10 - ) - # A solution `returned` cannot consume (here a bare marker) has no generated - # quantities, so the field stays `missing`. - obs = generated_observables(m, (; y_t = missing), :no_solution) - @test obs.generated === missing - # And the untyped fallback: a non-model `model` also yields `missing`. - @test generated_observables(:not_a_model, (; y_t = missing), :no_solution).generated === - missing -end - @testitem "forecast generates its horizon from the posterior" tags = [:sample] begin using ComposableTuringIDModels, Distributions, Turing, Random Random.seed!(104) diff --git a/test/unit/latent_models/gaussian_process.jl b/test/unit/latent_models/gaussian_process.jl index 1ce854dbb..44fa4f4dd 100644 --- a/test/unit/latent_models/gaussian_process.jl +++ b/test/unit/latent_models/gaussian_process.jl @@ -436,7 +436,7 @@ end posterior, NUTS(0.9), ndraws; initial_params = InitFromPrior(), progress = false ) - gen = vec(generated_observables(posterior, y_obs, chain).generated) + gen = vec(returned(posterior, chain)) @test length(gen) == ndraws @test all(g -> length(g.Z_t) == n && all(isfinite, g.Z_t), gen) # A degenerate fit (σ initialised far out in the prior tail, step size @@ -611,7 +611,7 @@ end posterior, NUTS(0.9), ndraws; initial_params = InitFromPrior(), progress = false ) - gen = vec(generated_observables(posterior, y_obs, chain).generated) + gen = vec(returned(posterior, chain)) @test length(gen) == ndraws @test all(g -> length(g.Z_t) == n && all(isfinite, g.Z_t), gen) Z_mean = vec(mean(reduce(hcat, (g.Z_t for g in gen)); dims = 2)) diff --git a/test/unit/observation_models/requirements.jl b/test/unit/observation_models/requirements.jl index db41d558c..1dae005ec 100644 --- a/test/unit/observation_models/requirements.jl +++ b/test/unit/observation_models/requirements.jl @@ -74,9 +74,7 @@ end # An IDModel and an IDProblem delegate to their observation model. infection = DirectInfections(; Z = RandomWalk(), initialisation = Normal()) @test observation_lead_in(IDModel(infection, stacked)) == 7 - problem = IDProblem( - infection = infection, observation_model = stacked, tspan = (1, 30) - ) + problem = IDProblem(infection, stacked, fill(10, 30)) @test observation_lead_in(problem) == 7 end @@ -317,14 +315,12 @@ end @test data_fits(model, fill(10, 59), 60) @test data_fits(model, missing, 60) - # An `IDProblem` reads the observation count from its `tspan`. - problem = IDProblem( - infection = model.infection_model, observation_model = obs, - tspan = (1, 60) - ) + # An `IDProblem` reads the observation count from the data it holds, so its + # report is the model's over that data. + problem = IDProblem(model.infection_model, obs, fill(10, 60)) @test data_requirements(problem).series_length == 103 - @test data_fits(data_requirements(problem, (; y_t = fill(10, 60)))) - @test !data_fits(data_requirements(problem, (; y_t = fill(10, 61)))) + report(x...) = sprint(show, MIME"text/plain"(), data_requirements(x...)) + @test report(problem) == report(model, fill(10, 60), 60) end @testitem "data_requirements reads each data shape's contract" begin @@ -516,16 +512,11 @@ end fc = forecast(model, y, chain, h) @test size(fc, 1) == 20 - # An `IDProblem`'s `tspan` is the span of the observations. - problem = IDProblem( - infection = model.infection_model, observation_model = obs, - tspan = (1, length(y)) - ) - @test data_fits(data_requirements(problem, (; y_t = y))) - pchain = sample( - as_turing_model(problem, (; y_t = y)), Prior(), 20; progress = false - ) - pfc = forecast(problem, y, pchain, h) + # An `IDProblem` holds the series, so it needs no length of its own. + problem = IDProblem(model.infection_model, obs, y) + @test data_requirements(problem).n == length(y) + pchain = sample(as_turing_model(problem), Prior(), 20; progress = false) + pfc = forecast(problem, pchain, h) @test size(pfc, 1) == 20 end diff --git a/test/unit/utils/utils_extra.jl b/test/unit/utils/utils_extra.jl index de59bf127..4625c24b3 100644 --- a/test/unit/utils/utils_extra.jl +++ b/test/unit/utils/utils_extra.jl @@ -74,28 +74,6 @@ end @test all(>(0), rt) end -@testitem "DirectSample draws from the prior" begin - using ComposableTuringIDModels, Distributions, Turing, Random - Random.seed!(81) - @model g() = (x ~ Normal()) - # apply_method wraps the solution in IDObservables; `.samples` is the - # raw inference result. - chain = apply_method(g(), DirectSample(; n_samples = 10)) - @test chain isa IDObservables - @test chain.samples !== nothing - single = apply_method(g(), DirectSample()) - @test haskey(single.samples, @varname(x)) -end - -@testitem "get_param_array reshapes a Chains into (draws, chains)" begin - using ComposableTuringIDModels, Distributions, Turing, MCMCChains, Random - Random.seed!(82) - @model g() = (x ~ Normal()) - chn = MCMCChains.Chains(sample(g(), Prior(), MCMCSerial(), 3, 2; progress = false)) - A = get_param_array(chn) - @test size(A) == (3, 2) -end - @testitem "_safe_int_floor rejects non-finite input with a clear DomainError" begin using ComposableTuringIDModels: _safe_int_floor # A non-finite value must raise a `DomainError` naming the offending value, From ebceacda9716f6e7076376f924558b7f2f3cf9f6 Mon Sep 17 00:00:00 2001 From: seabbs-bot Date: Fri, 4 Sep 2026 14:01:48 +0100 Subject: [PATCH 02/12] fix(compose): refuse data with no time axis by name, and stop the display claiming streams The two-argument `as_turing_model` is public, so data it cannot read a length from now raises an `ArgumentError` naming the type rather than a `MethodError` from a private helper. An `IDProblem`'s data line called a `NamedTuple`'s entries streams. They are for a `Split`, but a `BinomialError` reads `(y, N)` as one stream's named fields, so the line now names the entries without claiming which and leaves the answer to `data_requirements`. The same confusion in `_obs_data_shape` itself is older than this branch and is filed separately. Co-Authored-By: Sam Abbott Co-Authored-By: Claude Opus 5 --- src/compose.jl | 17 +++++++++++++++-- src/inference/IDProblem.jl | 9 +++++---- test/unit/compose_strata.jl | 3 +++ test/unit/inference/inference.jl | 13 +++++++++++-- 4 files changed, 34 insertions(+), 8 deletions(-) diff --git a/src/compose.jl b/src/compose.jl index 1587c13f2..c4e9e3e28 100644 --- a/src/compose.jl +++ b/src/compose.jl @@ -210,8 +210,21 @@ _data_shape(model::IDModel, y_t) = _obs_data_shape( # A data value's length along the time axis. # A `NamedTuple` of streams shares one time length, read off its first stream. -# A scalar `missing` has no axis to read, and saying so beats a `MethodError` -# from whichever helper reaches it first. +# The two-argument `as_turing_model` is public, so a value with no time axis is +# refused by name rather than by a `MethodError` from whichever private helper +# reaches it first. +# A scalar `missing` gets its own message, because passing it is the one mistake +# with an obvious intent behind it. +function _series_time_length(y_t) + throw( + ArgumentError( + "cannot read a number of observations from data of type " * + "$(typeof(y_t)); pass it explicitly, as " * + "`as_turing_model(model, y_t, n)`" + ) + ) +end + function _series_time_length(::Missing) throw( ArgumentError( diff --git a/src/inference/IDProblem.jl b/src/inference/IDProblem.jl index bd0e0a229..06b4215e7 100644 --- a/src/inference/IDProblem.jl +++ b/src/inference/IDProblem.jl @@ -131,12 +131,13 @@ function _data_summary(y::AbstractMatrix) ) end +# A `NamedTuple` is a stream per entry for a `Split`, and a field per entry for a +# model that reads more than the counts (a `BinomialError` takes `(y, N)`), so +# the summary names the entries without claiming which. `data_requirements` says +# which, and is where to look. function _data_summary(y::NamedTuple) - n_streams = length(y) - names = join(keys(y), ", ") return string( - n_streams, " stream", n_streams == 1 ? "" : "s", " (", names, "), ", - _series_time_length(y), " observations each" + _series_time_length(y), " observations in each of ", join(keys(y), ", ") ) end diff --git a/test/unit/compose_strata.jl b/test/unit/compose_strata.jl index 1d3db63d3..d0ae27e62 100644 --- a/test/unit/compose_strata.jl +++ b/test/unit/compose_strata.jl @@ -134,4 +134,7 @@ end # A scalar `missing` carries no length, and says so. @test_throws ArgumentError as_turing_model(model, missing) + # So does any other value with no time axis, rather than a `MethodError` + # naming a private helper. + @test_throws ArgumentError as_turing_model(model, 20) end diff --git a/test/unit/inference/inference.jl b/test/unit/inference/inference.jl index b4052b952..0146ccfd2 100644 --- a/test/unit/inference/inference.jl +++ b/test/unit/inference/inference.jl @@ -46,15 +46,24 @@ end ) @test occursin("└─ data: 30 observations, 1 missing", gappy) + # A `NamedTuple` names its entries without claiming they are streams: they + # are for a `Split`, but a `BinomialError` reads `(y, N)` as one stream's + # fields. streams = render( IDProblem( infection, Split((cases = PoissonError(), deaths = PoissonError())), (cases = fill(5, 30), deaths = fill(1, 30)) ) ) - @test occursin( - "└─ data: 2 streams (cases, deaths), 30 observations each", streams + @test occursin("└─ data: 30 observations in each of cases, deaths", streams) + + binom = render( + IDProblem( + infection, BinomialError(), + (y = fill(5, 30), N = fill(20, 30)) + ) ) + @test occursin("└─ data: 30 observations in each of y, N", binom) strata = render( IDProblem( From 2bd31feb6c9559ef4c90ffcf81c54df64f2457ec Mon Sep 17 00:00:00 2001 From: seabbs-bot Date: Fri, 4 Sep 2026 14:14:29 +0100 Subject: [PATCH 03/12] fix(IDProblem): check the data at construction, and respecify with Accessors A problem is a model and its data, so fitting the same model to another series is a new problem rather than a second argument. Drops `as_turing_model(problem, data)` in favour of `@set problem.data = y_new`, which is how the rest of a composition is respecified and which leaves `forecast(problem, chain, horizon)` reading the data the problem holds. The pairing is now checked when it is made, by an inner constructor so `@set` is checked too. What it catches is narrow and the comment says so: streams that disagree with each other, never a single series, whose count comes from the data it would be checked against. It cannot reject data `as_turing_model` accepts, `data_fits` being the weaker of the two. Also refuses `data_requirements(problem, n)`, which fell through to the generic method and reported as if no data had been supplied, and reports a wholly blank matrix or set of streams as a simulation the way a blank vector already was. Co-Authored-By: Sam Abbott Co-Authored-By: Claude Opus 5 --- docs/Project.toml | 2 + docs/src/tutorials/delays-dayofweek.md | 8 +++ src/inference/IDProblem.jl | 74 +++++++++++++++++++--- test/unit/inference/inference.jl | 86 +++++++++++++++++++++++++- 4 files changed, 159 insertions(+), 11 deletions(-) diff --git a/docs/Project.toml b/docs/Project.toml index 751421690..54796e9df 100644 --- a/docs/Project.toml +++ b/docs/Project.toml @@ -1,6 +1,7 @@ [deps] ADFixtures = "a039981f-f823-4177-b744-be8de6cdc156" ADTypes = "47edcb42-4c32-4615-8424-f2b9edc5f35b" +Accessors = "7d9f7c33-5ae7-4f3b-8dc6-eff91059b697" AbstractGPs = "99985d1d-32ba-4be9-9821-2ec096f28918" EpiAwarePackageTools = "7aaea248-0d11-4a0d-a7dc-86da30abb951" AlgebraOfGraphics = "cbdf2221-f076-402e-a563-3d30da359d67" @@ -41,6 +42,7 @@ ADFixtures = {path = "../test/ADFixtures"} ComposableTuringIDModels = {path = ".."} [compat] +Accessors = "0.1" Enzyme = "0.13.199" EpiAwarePackageTools = "0.3, 0.4" ADTypes = "1" diff --git a/docs/src/tutorials/delays-dayofweek.md b/docs/src/tutorials/delays-dayofweek.md index 2f3e63397..23c4a4105 100644 --- a/docs/src/tutorials/delays-dayofweek.md +++ b/docs/src/tutorials/delays-dayofweek.md @@ -126,12 +126,20 @@ problem = IDProblem(renewal, observation, y_obs) ``` The problem carries its own length, so nothing about the series is restated and [`data_requirements`](@ref) reads straight off it. +Construction checks the data against the model, so streams that disagree with each other are refused here rather than at build time. Passing a blank series in place of the reports, `Vector{Missing}(missing, n)`, would instead simulate from the prior. ```@example delays data_requirements(problem) ``` +Fitting the same model to a different series is a new problem rather than a different call, so it is built the way every other part of a composition is respecified, with [Accessors](https://juliaobjects.github.io/Accessors.jl/). + +```@example delays +using Accessors +@set problem.data = y_obs[1:28] +``` + Fitting conditions on the observed reports, differentiating with the recommended [Mooncake](https://chalk-lab.github.io/Mooncake.jl/) backend, described under [Automatic differentiation backend](@ref ad-backends). We draw two chains in parallel with `MCMCThreads()`, which gives a cross-chain ``\hat R``. diff --git a/src/inference/IDProblem.jl b/src/inference/IDProblem.jl index 06b4215e7..3392a283e 100644 --- a/src/inference/IDProblem.jl +++ b/src/inference/IDProblem.jl @@ -23,6 +23,11 @@ which is the reason to hold one rather than a conditioned `DynamicPPL.Model`: the latter renders as its full nested parametric type with the observations dumped inline. +Construction checks the data against the model, so a set of streams that +disagree with each other is refused here rather than at build time. Fitting the +same model to a different series is a new problem, built with `Accessors`: +`@set problem.data = y_new`. + # Arguments - `model`: the composed [`IDModel`](@ref), or an infection model and an @@ -53,6 +58,35 @@ struct IDProblem{M <: IDModel, D} model::M "The observations the model is fitted to." data::D + + function IDProblem(model::M, data::D) where {M <: IDModel, D} + _assert_data_fits(model, data) + return new{M, D}(model, data) + end +end + +# Refuse at construction the mismatch `as_turing_model` would refuse at build, +# so the error names the point where the two halves were put together rather +# than a later one. +# This is an inner constructor so that every route in, `@set problem.data` +# included, is checked. +# +# What it can catch is narrow, and worth stating plainly. It fires only when the +# streams disagree with each other, a stream longer than the one the observation +# count is read from. On a single series the count comes from the same data it +# is checked against, so there is nothing to disagree and the guard is silent. +# It never rejects data `as_turing_model` would accept: `data_fits` is the weaker +# of the two conditions, since the build check adds an exact-length rule and the +# legacy-`n` rule on top of it. +function _assert_data_fits(model::IDModel, data) + required = data_requirements(model, data, _data_shape(model, data)) + data_fits(required) && return nothing + return throw( + ArgumentError( + "the data does not fit the model:\n" * + sprint(show, MIME"text/plain"(), required) + ) + ) end function IDProblem( @@ -80,21 +114,40 @@ data_requirements(problem::IDProblem) = data_requirements( problem.model, problem.data, _problem_shape(problem) ) +# A bare length is meaningless once the problem holds its data. The generic +# method would report as if nothing had been supplied, quietly discarding the +# half of the pairing the type exists for, so it is refused by name. +function data_requirements(::IDProblem, ::ModelShape) + return throw( + ArgumentError( + "an `IDProblem` holds its own data, so `data_requirements(problem)` " * + "takes no length; to report over a different length or dataset " * + "use `data_requirements(problem.model, y_t, n)`" + ) + ) +end + @doc raw" Build the `DynamicPPL.Model` for an [`IDProblem`](@ref). The problem already holds the data, so there is no length to restate: `as_turing_model(problem)` is `as_turing_model(problem.model, problem.data)`. -Pass a second argument to refit the same model to different data, as in a -rolling refit over a growing series. + +There is deliberately no method taking data alongside the problem. An +`IDProblem` *is* a model and its data, so fitting the same model to a different +series is a different problem, not a different call on this one. Build it with +`Accessors`, which is how every other part of this package is respecified: + +```julia +using Accessors +refit = @set problem.data = y_new +``` # Arguments - `problem`: the [`IDProblem`](@ref). - - `data`: (optional) observations to use in place of the problem's own. " as_turing_model(problem::IDProblem) = as_turing_model(problem.model, problem.data) -as_turing_model(problem::IDProblem, data) = as_turing_model(problem.model, data) # --- printing --------------------------------------------------------------- @@ -114,10 +167,14 @@ Base.show(io::IO, ::IDProblem) = print(io, "IDProblem") # One line describing what the problem holds, in the same vocabulary # `data_requirements` uses: streams, observations and the shape they come in. +# Data with nothing observed in it reads as a simulation whatever shape it takes, +# because reporting a count of values that are all blank invites the reader to +# think something was supplied. +_blank_summary(n) = "none, $n time points (simulating from the prior)" function _data_summary(y::AbstractVector) n = length(y) blank = count(ismissing, y) - blank == n && return "none, $n time points (simulating from the prior)" + blank == n && return _blank_summary(n) counted = string(n, " observation", n == 1 ? "" : "s") blank == 0 && return string(counted, " (", eltype(y), ")") return string(counted, ", ", blank, " missing") @@ -125,6 +182,7 @@ end function _data_summary(y::AbstractMatrix) strata, n = size(y) + all(ismissing, y) && return _blank_summary(n) return string( strata, " strat", strata == 1 ? "um" : "a", " x ", n, " observation", n == 1 ? "" : "s" @@ -136,9 +194,9 @@ end # the summary names the entries without claiming which. `data_requirements` says # which, and is where to look. function _data_summary(y::NamedTuple) - return string( - _series_time_length(y), " observations in each of ", join(keys(y), ", ") - ) + n = _series_time_length(y) + all(v -> all(ismissing, v), y) && return _blank_summary(n) + return string(n, " observations in each of ", join(keys(y), ", ")) end # Anything else names its type rather than printing itself, since the point of diff --git a/test/unit/inference/inference.jl b/test/unit/inference/inference.jl index 0146ccfd2..8e1acf149 100644 --- a/test/unit/inference/inference.jl +++ b/test/unit/inference/inference.jl @@ -1,5 +1,5 @@ @testitem "IDProblem pairs a model with its data and needs no length" begin - using ComposableTuringIDModels, Distributions, Random + using ComposableTuringIDModels, Distributions, Random, Accessors using DynamicPPL: VarInfo Random.seed!(71) infection = DirectInfections(; Z = RandomWalk(), initialisation = Normal()) @@ -16,8 +16,62 @@ @test keys(VarInfo(as_turing_model(IDProblem(model, y)))) == keys(VarInfo(as_turing_model(model, y, length(y)))) - # A second argument refits the same model to different data. - @test length(as_turing_model(problem, fill(5, 12))().generated_y_t) == 12 + # Refitting to a different series is a new problem, built with `Accessors`, + # rather than a second argument to `as_turing_model`. + refit = @set problem.data = fill(5, 12) + @test isequal(refit.model, problem.model) + @test isequal(refit.data, fill(5, 12)) + @test isequal(problem.data, Vector{Missing}(missing, 20)) + @test length(as_turing_model(refit)().generated_y_t) == 12 +end + +@testitem "IDProblem refuses streams that disagree at construction" begin + using ComposableTuringIDModels, Distributions, Accessors + infection = DirectInfections(; Z = RandomWalk(), initialisation = Normal()) + # Two streams over one infection stratum, so the observation count is read + # off `cases` and `deaths` can genuinely contradict it. + obs = Split( + (cases = PoissonError(), deaths = PoissonError()), + reshape([1.0, 1.0], 2, 1) + ) + ragged = (cases = fill(5, 30), deaths = fill(1, 40)) + @test_throws ArgumentError IDProblem(infection, obs, ragged) + # The guard is an inner constructor, so respecifying into the same mistake + # is refused too. + ok = IDProblem(infection, obs, (cases = fill(5, 30), deaths = fill(1, 30))) + @test_throws ArgumentError @set ok.data = ragged + + # It never refuses what `as_turing_model` accepts. A shorter stream is + # right-aligned rather than wrong, and a single series cannot disagree with + # a count read off itself. + @test IDProblem(infection, obs, (cases = fill(5, 30), deaths = fill(1, 20))) isa + IDProblem + @test IDProblem(infection, PoissonError(), fill(5, 30)) isa IDProblem + # Both simulation routes stay constructible. + @test IDProblem(infection, PoissonError(), Vector{Missing}(missing, 20)) isa + IDProblem + @test IDProblem( + infection, obs, ( + cases = Vector{Missing}(missing, 20), deaths = Vector{Missing}(missing, 20), + ) + ) isa IDProblem + # And a model reading named fields rather than streams is not mistaken for + # two disagreeing streams. + @test IDProblem( + infection, BinomialError(), (y = fill(5, 30), N = fill(20, 30)) + ) isa IDProblem +end + +@testitem "IDProblem refuses a bare length in place of its data" begin + using ComposableTuringIDModels, Distributions + problem = IDProblem( + DirectInfections(; Z = RandomWalk(), initialisation = Normal()), + PoissonError(), fill(5, 30) + ) + # The generic method would report as if no data had been supplied, which + # discards the half of the pairing the type exists for. + @test_throws ArgumentError data_requirements(problem, 30) + @test_throws ArgumentError data_requirements(problem, (2, 30)) end @testitem "IDProblem prints its component tree and a data summary" begin @@ -65,6 +119,19 @@ end ) @test occursin("└─ data: 30 observations in each of y, N", binom) + blank_streams = render( + IDProblem( + infection, Split((cases = PoissonError(), deaths = PoissonError())), + ( + cases = Vector{Missing}(missing, 30), + deaths = Vector{Missing}(missing, 30), + ) + ) + ) + @test occursin( + "└─ data: none, 30 time points (simulating from the prior)", blank_streams + ) + strata = render( IDProblem( DirectInfections(; @@ -76,6 +143,19 @@ end ) @test occursin("└─ data: 2 strata x 30 observations", strata) + blank_strata = render( + IDProblem( + DirectInfections(; + Z = Stratify(RandomWalk(), FixedIntercept(0.0)), + initialisation = IID(Normal()) + ), + PoissonError(), Matrix{Missing}(missing, 2, 30) + ) + ) + @test occursin( + "└─ data: none, 30 time points (simulating from the prior)", blank_strata + ) + # Compact rendering stays one line, as it does for a component. @test sprint(show, IDProblem(infection, PoissonError(), fill(5, 30))) == "IDProblem" From 3660655abc8ad867a07372a160bcd85788b858ae Mon Sep 17 00:00:00 2001 From: seabbs-bot Date: Fri, 4 Sep 2026 14:31:12 +0100 Subject: [PATCH 04/12] docs(IDProblem): say which object holds no data, and how little the guard sees There is no data-free problem, because the pairing is what the type is; an `IDModel` is the object for a model on its own. A problem whose observations have not arrived is one over a blank series, which fixes the shape and says how many are expected, and the data is attached with `@set`. Both were already true; neither was written down. The construction check's scope moves out of a code comment and into the docstring. It cannot see a length disagreement on a single series, nor across streams that imply their own strata, and a user who knows the type checks something would otherwise reasonably assume it checks those. Co-Authored-By: Sam Abbott Co-Authored-By: Claude Opus 5 --- src/inference/IDProblem.jl | 21 +++++++++++++++++---- test/unit/inference/inference.jl | 31 +++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 4 deletions(-) diff --git a/src/inference/IDProblem.jl b/src/inference/IDProblem.jl index 3392a283e..251747ebc 100644 --- a/src/inference/IDProblem.jl +++ b/src/inference/IDProblem.jl @@ -23,10 +23,23 @@ which is the reason to hold one rather than a conditioned `DynamicPPL.Model`: the latter renders as its full nested parametric type with the observations dumped inline. -Construction checks the data against the model, so a set of streams that -disagree with each other is refused here rather than at build time. Fitting the -same model to a different series is a new problem, built with `Accessors`: -`@set problem.data = y_new`. +Construction rejects data the model cannot fit, but the check is narrow and +worth knowing the shape of: it cannot see a length disagreement on a single +series, nor across streams that imply their own strata, because in both the +observation count is read from the same data it would be checked against. Ask +properly with [`data_requirements`](@ref). + +There is no data-free `IDProblem`, because the pairing is what the type is; +[`IDModel`](@ref) is the object for a model on its own. A problem whose +observations have not arrived yet is one over a blank series, which fixes the +shape and says how many observations are expected, and the data is attached the +way anything else in a composition is respecified. + +```julia +using Accessors +problem = IDProblem(model, Vector{Missing}(missing, 20)) # shape fixed, none observed +fitted = @set problem.data = y # observations attached +``` # Arguments diff --git a/test/unit/inference/inference.jl b/test/unit/inference/inference.jl index 8e1acf149..39a80fe20 100644 --- a/test/unit/inference/inference.jl +++ b/test/unit/inference/inference.jl @@ -62,6 +62,37 @@ end ) isa IDProblem end +@testitem "a blank series is a problem awaiting its observations" begin + using ComposableTuringIDModels, Distributions, Accessors, Random + using DynamicPPL: VarInfo + Random.seed!(73) + model = IDModel( + DirectInfections(; Z = RandomWalk(), initialisation = Normal(log(20), 0.2)), + LatentDelay(PoissonError(), fill(1 / 5, 5)) + ) + # There is no data-free problem; a blank series is how a shape is fixed + # before the observations arrive. It carries a length, so it simulates. + waiting = IDProblem(model, Vector{Missing}(missing, 20)) + @test length(as_turing_model(waiting)().generated_y_t) == 20 + @test data_requirements(waiting).n == 20 + + # A scalar `missing` has no length, so it is not a way to express this. + @test_throws ArgumentError IDProblem(model, missing) + + # Attaching the data gives what the constructor gives, field for field. + y = fill(5, 20) + attached = @set waiting.data = y + built = IDProblem(model, y) + @test all( + f -> isequal(getfield(attached, f), getfield(built, f)), + fieldnames(IDProblem) + ) + @test keys(VarInfo(as_turing_model(attached))) == + keys(VarInfo(as_turing_model(built))) + # The blank problem is unchanged, since `@set` builds rather than mutates. + @test isequal(waiting.data, Vector{Missing}(missing, 20)) +end + @testitem "IDProblem refuses a bare length in place of its data" begin using ComposableTuringIDModels, Distributions problem = IDProblem( From 01f3c1abb18c268120c23d8f0a3d2023a6ec3a78 Mon Sep 17 00:00:00 2001 From: seabbs-bot Date: Fri, 4 Sep 2026 16:50:05 +0100 Subject: [PATCH 05/12] docs(IDProblem): fix the blank-series example and cut the prose to its facts `as_turing_model(problem, data)` was removed with the rest of the data-alongside-problem route, but `delays-dayofweek.md` still called it to build the posterior-predictive model. That raises an `ArgumentError` from the `as_turing_model` fallback, so the page could not build. The refit idiom the page already shows does the same job, and the resulting model adds exactly the `y_t` varnames `predict` needs. Trim the comments and docstrings this branch added to the facts a reader cannot get from the code: the inner-constructor scope of the guard, why there is no `data_fits(::IDProblem)`, and why a value with no time axis is refused by name. Split the sentences that joined clauses with a colon or a semicolon. Record the blank-series requirements report in a test, since `n_supplied` counts positions in the series there exactly as it does for a series with gaps in it. Co-Authored-By: Sam Abbott Co-Authored-By: Claude Opus 5 --- docs/src/design.md | 3 +- docs/src/tutorials/catalyst-ode.md | 3 +- docs/src/tutorials/delays-dayofweek.md | 12 ++-- docs/src/tutorials/sir-ode.md | 3 +- src/compose.jl | 23 +++---- src/inference/IDProblem.jl | 89 +++++++++++--------------- src/observation_models/requirements.jl | 4 +- test/unit/inference/inference.jl | 9 ++- 8 files changed, 68 insertions(+), 78 deletions(-) diff --git a/docs/src/design.md b/docs/src/design.md index 21529fd48..538287c9c 100644 --- a/docs/src/design.md +++ b/docs/src/design.md @@ -206,7 +206,8 @@ It asks whether every observation supplied would be scored, so more data than th data_fits(delayed, y, length(y)), data_fits(delayed, vcat(y, y), length(y)) ``` -An [`IDProblem`](@ref) holds a model and its data together, so [`data_requirements`](@ref) reads the observation count off the data rather than being told it, and [`forecast`](@ref) extends the observations by the horizon and derives the rest. +An [`IDProblem`](@ref) holds a model and its data together, so [`data_requirements`](@ref) reads the observation count off the data rather than being told it. +[`forecast`](@ref) extends the observations by the horizon and derives the rest. Length-preserving modifiers ([`Ascertainment`](@ref), [`RightTruncate`](@ref), [`ReportTriangle`](@ref), a [`Split`](@ref)'s streams) consume nothing of their own, so the lead-in comes from the delays alone. A [`Split`](@ref)'s streams run in parallel, so their lead-ins do not add up and the series covers the deepest of them. diff --git a/docs/src/tutorials/catalyst-ode.md b/docs/src/tutorials/catalyst-ode.md index 654755fc3..13ea0846e 100644 --- a/docs/src/tutorials/catalyst-ode.md +++ b/docs/src/tutorials/catalyst-ode.md @@ -149,7 +149,8 @@ Both rates collapse from broad priors onto tight, correlated posteriors. ## Posterior trajectories A compartmental model has no time-varying ``R_t``, so the infection signal is the infectious proportion ``I(t)`` solved from the ODE. -`returned` re-runs the fitted model over the chain and recovers ``I_t`` per draw, and the posterior-predictive in-bed counts come from `predict` on the model with the observations set to `missing`. +`returned` re-runs the fitted model over the chain to recover ``I_t`` per draw. +The posterior-predictive in-bed counts come from `predict` on the model with the observations set to `missing`. Two small helpers reduce the per-draw trajectories to credible bands. ```@setup catalyst diff --git a/docs/src/tutorials/delays-dayofweek.md b/docs/src/tutorials/delays-dayofweek.md index 23c4a4105..bb80df1af 100644 --- a/docs/src/tutorials/delays-dayofweek.md +++ b/docs/src/tutorials/delays-dayofweek.md @@ -99,7 +99,8 @@ Two stacked delays therefore need the infection process to start that many days observation_lead_in(observation) ``` -The number of observations is the number of reports we have, and the infection process runs over the extra lead-in days to support them, derived from the chain (see [What data a model needs](@ref lead-in)). +The number of observations is the number of reports we have. +The infection process runs over the extra lead-in days needed to support them, derived from the chain (see [What data a model needs](@ref lead-in)). [`data_requirements`](@ref) says what a chain needs before it is sampled. ## The data @@ -119,7 +120,8 @@ y_obs = italy.confirm[1:n] ## Assemble and fit [`IDProblem`](@ref) holds the model and the data it is fitted to as one object. -Printing it shows the whole composition and a summary of the data, which is the reason to hold one rather than the `DynamicPPL.Model` [`as_turing_model`](@ref) returns: the latter prints as its full nested parametric type with the observations dumped inline. +Printing it shows the whole composition and a summary of the data. +That is the reason to hold one rather than the `DynamicPPL.Model` [`as_turing_model`](@ref) returns, which prints as its full nested parametric type with the observations dumped inline. ```@example delays problem = IDProblem(renewal, observation, y_obs) @@ -133,7 +135,8 @@ Passing a blank series in place of the reports, `Vector{Missing}(missing, n)`, w data_requirements(problem) ``` -Fitting the same model to a different series is a new problem rather than a different call, so it is built the way every other part of a composition is respecified, with [Accessors](https://juliaobjects.github.io/Accessors.jl/). +Fitting the same model to a different series is a new problem rather than a different call. +It is built the way every other part of a composition is respecified, with [Accessors](https://juliaobjects.github.io/Accessors.jl/). ```@example delays using Accessors @@ -222,7 +225,8 @@ end gens = vec(returned(posterior, chain)) Rt = credible_bands(reduce(hcat, (exp.(g.Z_t) for g in gens))) -pred = predict(as_turing_model(problem, Vector{Missing}(missing, n)), chain) +blank = @set problem.data = Vector{Missing}(missing, n) +pred = predict(as_turing_model(blank), chain) yt = predictive_bands(pred, n) fig = Figure(; size = (760, 620)) diff --git a/docs/src/tutorials/sir-ode.md b/docs/src/tutorials/sir-ode.md index 2e0d8a1a3..ccccaed0a 100644 --- a/docs/src/tutorials/sir-ode.md +++ b/docs/src/tutorials/sir-ode.md @@ -151,7 +151,8 @@ All three parameters collapse from broad priors onto tight, correlated posterior ## Posterior trajectories A compartmental model has no time-varying ``R_t``, so the infection signal is the infectious proportion ``I(t)`` solved from the ODE. -`returned` re-runs the fitted model over the chain and recovers ``I_t`` per draw, and the posterior-predictive in-bed counts come from `predict` on the model with the observations set to `missing`. +`returned` re-runs the fitted model over the chain to recover ``I_t`` per draw. +The posterior-predictive in-bed counts come from `predict` on the model with the observations set to `missing`. Two small helpers reduce the per-draw trajectories to credible bands. ```@setup sir diff --git a/src/compose.jl b/src/compose.jl index c4e9e3e28..fd65ccae1 100644 --- a/src/compose.jl +++ b/src/compose.jl @@ -170,14 +170,14 @@ Convenience 2-argument form: read the infection process's shape from the data. The observation model and the data together fix the shape of the infection process, so nothing about it needs to be supplied explicitly or stored on the model. `as_turing_model(model, y_t)` is `as_turing_model(model, y_t, shape)` -with `shape` read from `y_t`: its time length, paired (when the data is -stratified) with the number of infection strata the observation model consumes, +with `shape` read from `y_t`. That is the data's time length, and for +stratified data the number of infection strata the observation model consumes, resolved via [`infection_strata`](@ref). The data may be a plain vector of observations, a `strata x time` matrix, or a `NamedTuple` of per-stream series. Three age strata observed as one -hospitalisation stream is `Split(NegativeBinomialError(), [1.0 1.0 1.0])`; a -`1 x T` data matrix then builds a 3-stratum infection process. +hospitalisation stream is `Split(NegativeBinomialError(), [1.0 1.0 1.0])`, and +a `1 x T` data matrix then builds a 3-stratum infection process. A scalar `missing` has no length to read, so simulating from the prior at a chosen length is either `as_turing_model(model, missing, n)` or the two-argument @@ -202,19 +202,13 @@ function as_turing_model(model::IDModel, y_t) return as_turing_model(model, y_t, _data_shape(model, y_t)) end -# The `ModelShape` a model and a data value imply, over the data's own time -# length. _data_shape(model::IDModel, y_t) = _obs_data_shape( model.observation_model, y_t, _series_time_length(y_t) ) -# A data value's length along the time axis. -# A `NamedTuple` of streams shares one time length, read off its first stream. # The two-argument `as_turing_model` is public, so a value with no time axis is -# refused by name rather than by a `MethodError` from whichever private helper -# reaches it first. -# A scalar `missing` gets its own message, because passing it is the one mistake -# with an obvious intent behind it. +# refused by name rather than by a `MethodError` from a private helper. +# A `NamedTuple` of streams shares one time length, read off its first stream. function _series_time_length(y_t) throw( ArgumentError( @@ -241,8 +235,8 @@ _series_time_length(y_t::NamedTuple) = _series_time_length(first(y_t)) # The infection process's `ModelShape` implied by an observation model and a # data value, shared by the two-argument `as_turing_model`, `IDProblem` and # `forecast` so all three read a data-driven model's shape the same way. -# Data with no stream axis to read leaves the shape to the observation model -# alone: a scalar `missing`, and a blank series holding nothing but `missing`. +# A scalar `missing` and a blank series have no stream axis to read, so the +# shape falls back to the observation model alone. _obs_data_shape(obs, y_t, time_steps) = time_steps _obs_data_shape(obs, y_t::Missing, time_steps) = _obs_data_shape_missing( obs, time_steps @@ -264,7 +258,6 @@ function _obs_data_shape_missing(s::Split, time_steps) return time_steps end - @doc raw" The number of infection strata an observation model consumes. diff --git a/src/inference/IDProblem.jl b/src/inference/IDProblem.jl index 251747ebc..cbe7ecb8f 100644 --- a/src/inference/IDProblem.jl +++ b/src/inference/IDProblem.jl @@ -1,9 +1,10 @@ -# `IDProblem`: a composed model paired with the data it is fitted to. +# A composed model paired with the data it is fitted to, so the shape of the +# infection process comes from the data rather than being stored on the model. @doc raw" A composed model and the data it is fitted to, held together. -An [`IDModel`](@ref) says what the process is; the data says how long it runs +An [`IDModel`](@ref) says what the process is. The data says how long it runs and how many streams it has. `IDProblem` is the pair, so the two travel together and cannot drift apart. From it, [`as_turing_model(problem)`](@ref as_turing_model) builds the @@ -12,28 +13,27 @@ reports what the model asks of the data, neither of which needs the length restating. The shape of the infection process is read from the observation model and the -data at build time (see [`infection_strata`](@ref)), not stored: a plain vector +data at build time (see [`infection_strata`](@ref)), not stored. A plain vector gives a single-series infection process, while a `strata x time` matrix or a -`NamedTuple` of streams gives a stratified one. Simulating from the prior is a -problem over a blank series, `Vector{Missing}(missing, n)`, which carries the -length the same way observations do. +`NamedTuple` of streams gives a stratified one. -Printing an `IDProblem` shows the component tree and a summary of the data, -which is the reason to hold one rather than a conditioned `DynamicPPL.Model`: -the latter renders as its full nested parametric type with the observations -dumped inline. +Printing an `IDProblem` shows the component tree and a summary of the data. +That is the reason to hold one rather than a conditioned `DynamicPPL.Model`, +which renders as its full nested parametric type with the observations dumped +inline. Construction rejects data the model cannot fit, but the check is narrow and -worth knowing the shape of: it cannot see a length disagreement on a single +worth knowing the shape of. It cannot see a length disagreement on a single series, nor across streams that imply their own strata, because in both the observation count is read from the same data it would be checked against. Ask properly with [`data_requirements`](@ref). -There is no data-free `IDProblem`, because the pairing is what the type is; +There is no data-free `IDProblem`, because the pairing is what the type is. [`IDModel`](@ref) is the object for a model on its own. A problem whose -observations have not arrived yet is one over a blank series, which fixes the -shape and says how many observations are expected, and the data is attached the -way anything else in a composition is respecified. +observations have not arrived yet is one over a blank series, +`Vector{Missing}(missing, n)`, which fixes the shape and carries the length the +way observations do. The data is attached the way anything else in a +composition is respecified. ```julia using Accessors @@ -78,19 +78,12 @@ struct IDProblem{M <: IDModel, D} end end -# Refuse at construction the mismatch `as_turing_model` would refuse at build, -# so the error names the point where the two halves were put together rather -# than a later one. -# This is an inner constructor so that every route in, `@set problem.data` -# included, is checked. -# -# What it can catch is narrow, and worth stating plainly. It fires only when the -# streams disagree with each other, a stream longer than the one the observation -# count is read from. On a single series the count comes from the same data it -# is checked against, so there is nothing to disagree and the guard is silent. -# It never rejects data `as_turing_model` would accept: `data_fits` is the weaker -# of the two conditions, since the build check adds an exact-length rule and the -# legacy-`n` rule on top of it. +# An inner constructor, so `@set problem.data` is checked on the same terms. +# The guard fires only when the streams disagree with each other, a stream +# longer than the one the observation count is read from. +# It never rejects data `as_turing_model` would accept, because `data_fits` is +# the weaker of the two conditions. +# The build check adds an exact-length rule and the legacy-`n` rule on top. function _assert_data_fits(model::IDModel, data) required = data_requirements(model, data, _data_shape(model, data)) data_fits(required) && return nothing @@ -114,22 +107,18 @@ end observation_lead_in(problem::IDProblem) = observation_lead_in(problem.model) _observation_chain(problem::IDProblem) = _observation_chain(problem.model) -# The problem holds both halves, so it reports what the model asks of the data -# with no arguments at all. -# There is deliberately no `data_fits(::IDProblem)`: the observation count comes -# from the same data the report is checked against, so for a single series the -# answer is true by construction and would be false reassurance. Asking whether -# a dataset fits a model is `data_fits(model, y_t, n)`, where the two are -# independent. +# There is deliberately no `data_fits(::IDProblem)`. +# The count would be read from the same data it was checked against, so for a +# single series it is true by construction and would be false reassurance. +# `data_fits(model, y_t, n)` takes the two independently. _problem_shape(problem::IDProblem) = _data_shape(problem.model, problem.data) data_requirements(problem::IDProblem) = data_requirements( problem.model, problem.data, _problem_shape(problem) ) -# A bare length is meaningless once the problem holds its data. The generic -# method would report as if nothing had been supplied, quietly discarding the -# half of the pairing the type exists for, so it is refused by name. +# The generic method would report as if nothing had been supplied, discarding +# the data the problem exists to hold, so a bare length is refused by name. function data_requirements(::IDProblem, ::ModelShape) return throw( ArgumentError( @@ -143,7 +132,7 @@ end @doc raw" Build the `DynamicPPL.Model` for an [`IDProblem`](@ref). -The problem already holds the data, so there is no length to restate: +The problem already holds the data, so there is no length to restate. `as_turing_model(problem)` is `as_turing_model(problem.model, problem.data)`. There is deliberately no method taking data alongside the problem. An @@ -165,8 +154,7 @@ as_turing_model(problem::IDProblem) = as_turing_model(problem.model, problem.dat # --- printing --------------------------------------------------------------- # The model's components hang directly off the problem, with the data as a final -# sibling, so the pairing reads as one tree rather than as a model with a -# footnote. +# sibling, so the pairing reads as one tree. function Base.show(io::IO, ::MIME"text/plain", problem::IDProblem) print(io, "IDProblem") _print_component_tree( @@ -178,11 +166,9 @@ end Base.show(io::IO, ::IDProblem) = print(io, "IDProblem") -# One line describing what the problem holds, in the same vocabulary -# `data_requirements` uses: streams, observations and the shape they come in. -# Data with nothing observed in it reads as a simulation whatever shape it takes, -# because reporting a count of values that are all blank invites the reader to -# think something was supplied. +# Data with nothing observed in it reads as a simulation whatever shape it +# takes, because a count of values that are all blank reads as if something had +# been supplied. _blank_summary(n) = "none, $n time points (simulating from the prior)" function _data_summary(y::AbstractVector) n = length(y) @@ -202,16 +188,15 @@ function _data_summary(y::AbstractMatrix) ) end -# A `NamedTuple` is a stream per entry for a `Split`, and a field per entry for a -# model that reads more than the counts (a `BinomialError` takes `(y, N)`), so -# the summary names the entries without claiming which. `data_requirements` says -# which, and is where to look. +# A `NamedTuple` is a stream per entry for a `Split`, and a field per entry for +# a model that reads more than the counts (a `BinomialError` takes `(y, N)`), so +# the summary names the entries without claiming which. +# `data_requirements` is what distinguishes them. function _data_summary(y::NamedTuple) n = _series_time_length(y) all(v -> all(ismissing, v), y) && return _blank_summary(n) return string(n, " observations in each of ", join(keys(y), ", ")) end -# Anything else names its type rather than printing itself, since the point of -# the summary is to stay one line. +# Anything else names its type, since the summary has to stay one line. _data_summary(y) = string(typeof(y)) diff --git a/src/observation_models/requirements.jl b/src/observation_models/requirements.jl index 99a30ee67..0e227f118 100644 --- a/src/observation_models/requirements.jl +++ b/src/observation_models/requirements.jl @@ -589,8 +589,8 @@ end # is scored at the end. # The one exception is a shortfall of exactly the chain's lead-in. # -# This walks the chain rather than building a `DataRequirements`, because it runs -# once per model build and must not allocate. +# This walks the chain rather than building a `DataRequirements`, since the +# report would be built only to be discarded. function _check_observation_count(model, y_t, n::ModelShape) chain = _observation_chain(model) lead_in = observation_lead_in(chain) diff --git a/test/unit/inference/inference.jl b/test/unit/inference/inference.jl index 39a80fe20..550e507d2 100644 --- a/test/unit/inference/inference.jl +++ b/test/unit/inference/inference.jl @@ -70,11 +70,16 @@ end DirectInfections(; Z = RandomWalk(), initialisation = Normal(log(20), 0.2)), LatentDelay(PoissonError(), fill(1 / 5, 5)) ) - # There is no data-free problem; a blank series is how a shape is fixed - # before the observations arrive. It carries a length, so it simulates. + # A blank series is how a shape is fixed before the observations arrive. + # It carries a length, so it simulates. waiting = IDProblem(model, Vector{Missing}(missing, 20)) @test length(as_turing_model(waiting)().generated_y_t) == 20 @test data_requirements(waiting).n == 20 + # `n_supplied` counts positions in the series, as it does for a series with + # gaps in it, so a blank series reports its length rather than `nothing`. + # How much was observed is the display's question, not the report's. + @test data_requirements(waiting)[1].n_supplied == 20 + @test data_fits(data_requirements(waiting)) # A scalar `missing` has no length, so it is not a way to express this. @test_throws ArgumentError IDProblem(model, missing) From ebae1202633cd1cbfe3e812dbc520b9cc2a5cefe Mon Sep 17 00:00:00 2001 From: seabbs-bot Date: Fri, 4 Sep 2026 16:54:32 +0100 Subject: [PATCH 06/12] docs(delays): say the problem carries its own length once Co-Authored-By: Sam Abbott Co-Authored-By: Claude Opus 5 --- docs/src/tutorials/delays-dayofweek.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/src/tutorials/delays-dayofweek.md b/docs/src/tutorials/delays-dayofweek.md index bb80df1af..0b2bcd2ee 100644 --- a/docs/src/tutorials/delays-dayofweek.md +++ b/docs/src/tutorials/delays-dayofweek.md @@ -127,7 +127,7 @@ That is the reason to hold one rather than the `DynamicPPL.Model` [`as_turing_mo problem = IDProblem(renewal, observation, y_obs) ``` -The problem carries its own length, so nothing about the series is restated and [`data_requirements`](@ref) reads straight off it. +The problem carries its own length, so [`data_requirements`](@ref) reads straight off it. Construction checks the data against the model, so streams that disagree with each other are refused here rather than at build time. Passing a blank series in place of the reports, `Vector{Missing}(missing, n)`, would instead simulate from the prior. From 63bf08ee6e872adda6c42689403ed792b5f7b6d9 Mon Sep 17 00:00:00 2001 From: seabbs-bot Date: Fri, 4 Sep 2026 17:12:49 +0100 Subject: [PATCH 07/12] docs(requirements): say that n_supplied counts positions, not observations The field was documented twice and the two disagreed. "or `nothing` if none was" reads as `nothing` when the series holds no observations, which is not what it means and not what it does: a wholly blank series reports its length, exactly as a series with gaps in it does. `nothing` means the requirements were asked for with no data argument at all, which is the distinction `_stream_fits` already turns on. Co-Authored-By: Sam Abbott Co-Authored-By: Claude Opus 5 --- src/observation_models/requirements.jl | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/observation_models/requirements.jl b/src/observation_models/requirements.jl index 0e227f118..d7060c4db 100644 --- a/src/observation_models/requirements.jl +++ b/src/observation_models/requirements.jl @@ -207,8 +207,10 @@ What a single observation stream requires of the data supplied for it. - `fields`: the fields the scoring model reads when it needs more than the counts, e.g. `(:y, :N)` for [`BinomialError`](@ref); empty when a plain series is enough. - - `n_supplied`: how much data was actually supplied, or `nothing` when the - requirements were asked for without data. + - `n_supplied`: the length of the supplied series, or `nothing` when the + requirements were asked for without data. It counts positions in the + series, so one that is wholly `missing` reports its length rather than + `nothing`. " struct StreamRequirement "The stream's name, or `:y_t` for a single series." @@ -227,7 +229,7 @@ struct StreamRequirement alignment::Symbol "The fields the scoring model reads, when it needs more than the counts." fields::Tuple{Vararg{Symbol}} - "How much data was supplied, or `nothing` if none was." + "The length of the supplied series, or `nothing` when asked for without data." n_supplied::Union{Int, Nothing} end From ae63645932cc6d2c54a088b5c683c4d111a94bad Mon Sep 17 00:00:00 2001 From: Sam Abbott Date: Fri, 4 Sep 2026 18:56:04 +0100 Subject: [PATCH 08/12] Update docs/src/tutorials/delays-dayofweek.md --- docs/src/tutorials/delays-dayofweek.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/src/tutorials/delays-dayofweek.md b/docs/src/tutorials/delays-dayofweek.md index 0b2bcd2ee..bc7d72023 100644 --- a/docs/src/tutorials/delays-dayofweek.md +++ b/docs/src/tutorials/delays-dayofweek.md @@ -121,7 +121,6 @@ y_obs = italy.confirm[1:n] [`IDProblem`](@ref) holds the model and the data it is fitted to as one object. Printing it shows the whole composition and a summary of the data. -That is the reason to hold one rather than the `DynamicPPL.Model` [`as_turing_model`](@ref) returns, which prints as its full nested parametric type with the observations dumped inline. ```@example delays problem = IDProblem(renewal, observation, y_obs) From 10e3619171fd9fc47b87c66730ceb64f5a239b49 Mon Sep 17 00:00:00 2001 From: Sam Abbott Date: Fri, 4 Sep 2026 18:56:19 +0100 Subject: [PATCH 09/12] Update src/inference/IDProblem.jl --- src/inference/IDProblem.jl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/inference/IDProblem.jl b/src/inference/IDProblem.jl index cbe7ecb8f..ad42e3071 100644 --- a/src/inference/IDProblem.jl +++ b/src/inference/IDProblem.jl @@ -2,7 +2,7 @@ # infection process comes from the data rather than being stored on the model. @doc raw" -A composed model and the data it is fitted to, held together. +A composed model and the data it is fitted to. An [`IDModel`](@ref) says what the process is. The data says how long it runs and how many streams it has. `IDProblem` is the pair, so the two travel From c9d635adb3bf0c94032c58a0016fa60ff94bd059 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Sep 2026 21:25:17 +0000 Subject: [PATCH 10/12] fix(test): declare InteractiveUtils in the test environment The rebuild-coverage test item added in #372 does `using InteractiveUtils: subtypes`, but the stdlib was never added to `test/Project.toml`. Julia 1.12 refuses to load a stdlib that is not in the active environment, so every test matrix job on a branch carrying that item errors in `reconstruction.jl`. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01Lw3PbYZfA1dZhfaaE9tbdp (cherry picked from commit 4d7322a0859c2ea69948cb5ca1d0e6c91e235377) --- test/Project.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/test/Project.toml b/test/Project.toml index 7b7231a3a..bc0fc227a 100644 --- a/test/Project.toml +++ b/test/Project.toml @@ -13,6 +13,7 @@ DynamicPPL = "366bfd00-2699-11ea-058f-f148b4cae6d8" EpiAwarePackageTools = "7aaea248-0d11-4a0d-a7dc-86da30abb951" ExplicitImports = "7d51a73a-1435-4ff3-83d9-f097790105c7" ForwardDiff = "f6369f11-7733-5829-9624-2563aa707210" +InteractiveUtils = "b77e0a4c-d291-57a0-90e8-8db25a27a240" KernelFunctions = "ec8451be-7e33-11e9-00cf-bbf324bd1392" LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" LogDensityProblems = "6fdf6af0-433a-55f7-b3ed-c6c6e0b8df7c" From 2deea07e0932c48dda75288e14af49e7a7dcea00 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Sep 2026 21:31:17 +0000 Subject: [PATCH 11/12] refactor(IDProblem): take an IDModel and its data, and cut the docstrings An IDProblem pairs a composed model with its data, so it takes the IDModel rather than the components an IDModel is built from. The three-argument constructor is gone, and the tutorial and tests build the model first. The IDProblem, as_turing_model(problem) and two-argument as_turing_model docstrings are cut to what the code does not already say. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01Lw3PbYZfA1dZhfaaE9tbdp --- docs/Project.toml | 4 +- docs/src/tutorials/delays-dayofweek.md | 2 +- src/compose.jl | 22 ++-- src/inference/IDProblem.jl | 75 ++++------- test/unit/base/interfaces.jl | 4 +- test/unit/inference/inference.jl | 123 ++++++++----------- test/unit/observation_models/requirements.jl | 2 +- 7 files changed, 95 insertions(+), 137 deletions(-) diff --git a/docs/Project.toml b/docs/Project.toml index 54796e9df..38bd006a5 100644 --- a/docs/Project.toml +++ b/docs/Project.toml @@ -1,8 +1,8 @@ [deps] ADFixtures = "a039981f-f823-4177-b744-be8de6cdc156" ADTypes = "47edcb42-4c32-4615-8424-f2b9edc5f35b" -Accessors = "7d9f7c33-5ae7-4f3b-8dc6-eff91059b697" AbstractGPs = "99985d1d-32ba-4be9-9821-2ec096f28918" +Accessors = "7d9f7c33-5ae7-4f3b-8dc6-eff91059b697" EpiAwarePackageTools = "7aaea248-0d11-4a0d-a7dc-86da30abb951" AlgebraOfGraphics = "cbdf2221-f076-402e-a563-3d30da359d67" CSV = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b" @@ -42,11 +42,11 @@ ADFixtures = {path = "../test/ADFixtures"} ComposableTuringIDModels = {path = ".."} [compat] -Accessors = "0.1" Enzyme = "0.13.199" EpiAwarePackageTools = "0.3, 0.4" ADTypes = "1" AbstractGPs = "0.5" +Accessors = "0.1" AlgebraOfGraphics = "0.12, 0.13" CSV = "0.10" CairoMakie = "0.15" diff --git a/docs/src/tutorials/delays-dayofweek.md b/docs/src/tutorials/delays-dayofweek.md index bc7d72023..7060e9f5a 100644 --- a/docs/src/tutorials/delays-dayofweek.md +++ b/docs/src/tutorials/delays-dayofweek.md @@ -123,7 +123,7 @@ y_obs = italy.confirm[1:n] Printing it shows the whole composition and a summary of the data. ```@example delays -problem = IDProblem(renewal, observation, y_obs) +problem = IDProblem(IDModel(renewal, observation), y_obs) ``` The problem carries its own length, so [`data_requirements`](@ref) reads straight off it. diff --git a/src/compose.jl b/src/compose.jl index fd65ccae1..575afd9d7 100644 --- a/src/compose.jl +++ b/src/compose.jl @@ -167,21 +167,17 @@ end @doc raw" Convenience 2-argument form: read the infection process's shape from the data. -The observation model and the data together fix the shape of the infection -process, so nothing about it needs to be supplied explicitly or stored on the -model. `as_turing_model(model, y_t)` is `as_turing_model(model, y_t, shape)` -with `shape` read from `y_t`. That is the data's time length, and for -stratified data the number of infection strata the observation model consumes, -resolved via [`infection_strata`](@ref). - -The data may be a plain vector of observations, a `strata x time` matrix, or a -`NamedTuple` of per-stream series. Three age strata observed as one -hospitalisation stream is `Split(NegativeBinomialError(), [1.0 1.0 1.0])`, and -a `1 x T` data matrix then builds a 3-stratum infection process. +`as_turing_model(model, y_t)` is `as_turing_model(model, y_t, shape)` with +`shape` read from `y_t`. A plain vector, a `strata x time` matrix, or a +`NamedTuple` of per-stream series gives the time length, and for stratified +data the number of infection strata the observation model consumes (see +[`infection_strata`](@ref)). Three age strata observed as one hospitalisation +stream is `Split(NegativeBinomialError(), [1.0 1.0 1.0])`, and a `1 x T` data +matrix then builds a 3-stratum infection process. A scalar `missing` has no length to read, so simulating from the prior at a -chosen length is either `as_turing_model(model, missing, n)` or the two-argument -form over a blank series of that length. +chosen length is `as_turing_model(model, missing, n)`, or the two-argument form +over a blank series such as `Vector{Missing}(missing, n)`. # Examples ```@example IDModel_shape diff --git a/src/inference/IDProblem.jl b/src/inference/IDProblem.jl index ad42e3071..5e3a367ec 100644 --- a/src/inference/IDProblem.jl +++ b/src/inference/IDProblem.jl @@ -5,56 +5,43 @@ A composed model and the data it is fitted to. An [`IDModel`](@ref) says what the process is. The data says how long it runs -and how many streams it has. `IDProblem` is the pair, so the two travel -together and cannot drift apart. From it, -[`as_turing_model(problem)`](@ref as_turing_model) builds the -`DynamicPPL.Model` and [`data_requirements(problem)`](@ref data_requirements) -reports what the model asks of the data, neither of which needs the length -restating. +and how many streams it has. Holding the two together means +[`as_turing_model(problem)`](@ref as_turing_model) and +[`data_requirements(problem)`](@ref data_requirements) need no length restated. The shape of the infection process is read from the observation model and the -data at build time (see [`infection_strata`](@ref)), not stored. A plain vector -gives a single-series infection process, while a `strata x time` matrix or a -`NamedTuple` of streams gives a stratified one. +data at build time (see [`infection_strata`](@ref)). A plain vector gives a +single series. A `strata x time` matrix or a `NamedTuple` of streams gives a +stratified process. -Printing an `IDProblem` shows the component tree and a summary of the data. -That is the reason to hold one rather than a conditioned `DynamicPPL.Model`, -which renders as its full nested parametric type with the observations dumped -inline. - -Construction rejects data the model cannot fit, but the check is narrow and -worth knowing the shape of. It cannot see a length disagreement on a single -series, nor across streams that imply their own strata, because in both the -observation count is read from the same data it would be checked against. Ask -properly with [`data_requirements`](@ref). - -There is no data-free `IDProblem`, because the pairing is what the type is. -[`IDModel`](@ref) is the object for a model on its own. A problem whose -observations have not arrived yet is one over a blank series, -`Vector{Missing}(missing, n)`, which fixes the shape and carries the length the -way observations do. The data is attached the way anything else in a -composition is respecified. +Construction refuses streams that disagree with each other. It cannot see a +length disagreement on a single series, because the observation count is read +from that same series, so ask [`data_requirements`](@ref) for that. + +A problem whose observations have not arrived yet is one over a blank series, +`Vector{Missing}(missing, n)`. The data is attached, or swapped for a refit, +with `Accessors`: ```julia using Accessors -problem = IDProblem(model, Vector{Missing}(missing, 20)) # shape fixed, none observed -fitted = @set problem.data = y # observations attached +fitted = @set problem.data = y ``` +Printing an `IDProblem` shows the component tree and a summary of the data. + # Arguments - - `model`: the composed [`IDModel`](@ref), or an infection model and an - observation model to compose into one. - - `data`: the observations the model is fitted to. A vector, a - `strata x time` matrix, or a `NamedTuple` of streams. + - `model`: the composed [`IDModel`](@ref). + - `data`: the observations. A vector, a `strata x time` matrix, or a + `NamedTuple` of streams. # Examples ```@example IDProblem using ComposableTuringIDModels, Distributions -problem = IDProblem( +model = IDModel( DirectInfections(; Z = RandomWalk(), initialisation = Normal()), - PoissonError(), - Vector{Missing}(missing, 20)) + PoissonError()) +problem = IDProblem(model, Vector{Missing}(missing, 20)) ``` ```@example IDProblem @@ -95,13 +82,6 @@ function _assert_data_fits(model::IDModel, data) ) end -function IDProblem( - infection::AbstractInfectionModel, observation_model::AbstractObservationModel, - data - ) - return IDProblem(IDModel(infection, observation_model), data) -end - # The problem's lead-in and observation chain are its model's, so a requirements # report reads the same either way. observation_lead_in(problem::IDProblem) = observation_lead_in(problem.model) @@ -132,13 +112,10 @@ end @doc raw" Build the `DynamicPPL.Model` for an [`IDProblem`](@ref). -The problem already holds the data, so there is no length to restate. -`as_turing_model(problem)` is `as_turing_model(problem.model, problem.data)`. - -There is deliberately no method taking data alongside the problem. An -`IDProblem` *is* a model and its data, so fitting the same model to a different -series is a different problem, not a different call on this one. Build it with -`Accessors`, which is how every other part of this package is respecified: +The problem holds the data, so `as_turing_model(problem)` is +`as_turing_model(problem.model, problem.data)`. There is no method taking data +alongside the problem. Fitting the same model to a different series is a +different problem, built with `Accessors`: ```julia using Accessors diff --git a/test/unit/base/interfaces.jl b/test/unit/base/interfaces.jl index af0797e55..6f3ce2482 100644 --- a/test/unit/base/interfaces.jl +++ b/test/unit/base/interfaces.jl @@ -95,8 +95,8 @@ end # A latent model is not an infection model, so it cannot fill the infection # slot either. @test_throws MethodError IDModel(latent, obs) - # IDProblem enforces the same role slots when it composes the pair itself. - @test_throws MethodError IDProblem(obs, obs, fill(5, 10)) + # IDProblem takes an IDModel, so a bare component cannot stand in for one. + @test_throws MethodError IDProblem(obs, fill(5, 10)) # A latent manipulator cannot wrap an observation model (slot is latent; # keyword constructor → TypeError). @test_throws Union{MethodError, TypeError} DiffLatentModel(; diff --git a/test/unit/inference/inference.jl b/test/unit/inference/inference.jl index 550e507d2..75c677dd0 100644 --- a/test/unit/inference/inference.jl +++ b/test/unit/inference/inference.jl @@ -2,16 +2,18 @@ using ComposableTuringIDModels, Distributions, Random, Accessors using DynamicPPL: VarInfo Random.seed!(71) - infection = DirectInfections(; Z = RandomWalk(), initialisation = Normal()) - problem = IDProblem(infection, PoissonError(), Vector{Missing}(missing, 20)) - @test problem.model == IDModel(infection, PoissonError()) + model = IDModel( + DirectInfections(; Z = RandomWalk(), initialisation = Normal()), + PoissonError() + ) + problem = IDProblem(model, Vector{Missing}(missing, 20)) + @test problem.model === model sim = as_turing_model(problem)() @test length(sim.generated_y_t) == 20 @test length(sim.Z_t) == 20 # The problem's route and the model's route build the same model, so # holding one is a convenience rather than a fork in the API. - model = IDModel(infection, PoissonError()) y = sim.generated_y_t @test keys(VarInfo(as_turing_model(IDProblem(model, y)))) == keys(VarInfo(as_turing_model(model, y, length(y)))) @@ -19,7 +21,7 @@ # Refitting to a different series is a new problem, built with `Accessors`, # rather than a second argument to `as_turing_model`. refit = @set problem.data = fill(5, 12) - @test isequal(refit.model, problem.model) + @test refit.model === model @test isequal(refit.data, fill(5, 12)) @test isequal(problem.data, Vector{Missing}(missing, 20)) @test length(as_turing_model(refit)().generated_y_t) == 12 @@ -34,32 +36,31 @@ end (cases = PoissonError(), deaths = PoissonError()), reshape([1.0, 1.0], 2, 1) ) + model = IDModel(infection, obs) ragged = (cases = fill(5, 30), deaths = fill(1, 40)) - @test_throws ArgumentError IDProblem(infection, obs, ragged) + @test_throws ArgumentError IDProblem(model, ragged) # The guard is an inner constructor, so respecifying into the same mistake # is refused too. - ok = IDProblem(infection, obs, (cases = fill(5, 30), deaths = fill(1, 30))) + ok = IDProblem(model, (cases = fill(5, 30), deaths = fill(1, 30))) @test_throws ArgumentError @set ok.data = ragged # It never refuses what `as_turing_model` accepts. A shorter stream is # right-aligned rather than wrong, and a single series cannot disagree with # a count read off itself. - @test IDProblem(infection, obs, (cases = fill(5, 30), deaths = fill(1, 20))) isa + @test IDProblem(model, (cases = fill(5, 30), deaths = fill(1, 20))) isa IDProblem - @test IDProblem(infection, PoissonError(), fill(5, 30)) isa IDProblem + plain = IDModel(infection, PoissonError()) + @test IDProblem(plain, fill(5, 30)) isa IDProblem # Both simulation routes stay constructible. - @test IDProblem(infection, PoissonError(), Vector{Missing}(missing, 20)) isa - IDProblem - @test IDProblem( - infection, obs, ( - cases = Vector{Missing}(missing, 20), deaths = Vector{Missing}(missing, 20), - ) - ) isa IDProblem + @test IDProblem(plain, Vector{Missing}(missing, 20)) isa IDProblem + blank = ( + cases = Vector{Missing}(missing, 20), deaths = Vector{Missing}(missing, 20), + ) + @test IDProblem(model, blank) isa IDProblem # And a model reading named fields rather than streams is not mistaken for # two disagreeing streams. - @test IDProblem( - infection, BinomialError(), (y = fill(5, 30), N = fill(20, 30)) - ) isa IDProblem + binomial = IDModel(infection, BinomialError()) + @test IDProblem(binomial, (y = fill(5, 30), N = fill(20, 30))) isa IDProblem end @testitem "a blank series is a problem awaiting its observations" begin @@ -100,10 +101,11 @@ end @testitem "IDProblem refuses a bare length in place of its data" begin using ComposableTuringIDModels, Distributions - problem = IDProblem( + model = IDModel( DirectInfections(; Z = RandomWalk(), initialisation = Normal()), - PoissonError(), fill(5, 30) + PoissonError() ) + problem = IDProblem(model, fill(5, 30)) # The generic method would report as if no data had been supplied, which # discards the half of the pairing the type exists for. @test_throws ArgumentError data_requirements(problem, 30) @@ -113,9 +115,10 @@ end @testitem "IDProblem prints its component tree and a data summary" begin using ComposableTuringIDModels, Distributions infection = DirectInfections(; Z = RandomWalk(), initialisation = Normal()) + model = IDModel(infection, PoissonError()) render(x) = sprint(show, MIME"text/plain"(), x) - plain = render(IDProblem(infection, PoissonError(), fill(5, 30))) + plain = render(IDProblem(model, fill(5, 30))) @test startswith(plain, "IDProblem\n") # The model's components hang off the problem rather than under a node of # their own, and the data is the last sibling. @@ -125,40 +128,33 @@ end # A wholly blank series says it is simulating rather than reporting zero # observations. - blank = render(IDProblem(infection, PoissonError(), Vector{Missing}(missing, 30))) + blank = render(IDProblem(model, Vector{Missing}(missing, 30))) @test occursin("└─ data: none, 30 time points (simulating from the prior)", blank) gappy = render( - IDProblem( - infection, PoissonError(), - Vector{Union{Missing, Int}}([missing; fill(5, 29)]) - ) + IDProblem(model, Vector{Union{Missing, Int}}([missing; fill(5, 29)])) ) @test occursin("└─ data: 30 observations, 1 missing", gappy) # A `NamedTuple` names its entries without claiming they are streams: they # are for a `Split`, but a `BinomialError` reads `(y, N)` as one stream's # fields. - streams = render( - IDProblem( - infection, Split((cases = PoissonError(), deaths = PoissonError())), - (cases = fill(5, 30), deaths = fill(1, 30)) - ) + split = IDModel( + infection, Split((cases = PoissonError(), deaths = PoissonError())) ) + streams = render(IDProblem(split, (cases = fill(5, 30), deaths = fill(1, 30)))) @test occursin("└─ data: 30 observations in each of cases, deaths", streams) binom = render( IDProblem( - infection, BinomialError(), - (y = fill(5, 30), N = fill(20, 30)) + IDModel(infection, BinomialError()), (y = fill(5, 30), N = fill(20, 30)) ) ) @test occursin("└─ data: 30 observations in each of y, N", binom) blank_streams = render( IDProblem( - infection, Split((cases = PoissonError(), deaths = PoissonError())), - ( + split, ( cases = Vector{Missing}(missing, 30), deaths = Vector{Missing}(missing, 30), ) @@ -168,33 +164,23 @@ end "└─ data: none, 30 time points (simulating from the prior)", blank_streams ) - strata = render( - IDProblem( - DirectInfections(; - Z = Stratify(RandomWalk(), FixedIntercept(0.0)), - initialisation = IID(Normal()) - ), - PoissonError(), fill(5, 2, 30) - ) + stratified = IDModel( + DirectInfections(; + Z = Stratify(RandomWalk(), FixedIntercept(0.0)), + initialisation = IID(Normal()) + ), + PoissonError() ) + strata = render(IDProblem(stratified, fill(5, 2, 30))) @test occursin("└─ data: 2 strata x 30 observations", strata) - blank_strata = render( - IDProblem( - DirectInfections(; - Z = Stratify(RandomWalk(), FixedIntercept(0.0)), - initialisation = IID(Normal()) - ), - PoissonError(), Matrix{Missing}(missing, 2, 30) - ) - ) + blank_strata = render(IDProblem(stratified, Matrix{Missing}(missing, 2, 30))) @test occursin( "└─ data: none, 30 time points (simulating from the prior)", blank_strata ) # Compact rendering stays one line, as it does for a component. - @test sprint(show, IDProblem(infection, PoissonError(), fill(5, 30))) == - "IDProblem" + @test sprint(show, IDProblem(model, fill(5, 30))) == "IDProblem" end @testitem "IDProblem reports its own data requirements" begin @@ -202,7 +188,7 @@ end infection = DirectInfections(; Z = RandomWalk(), initialisation = Normal()) obs = LatentDelay(PoissonError(), fill(1 / 5, 5)) # lead-in 4 - problem = IDProblem(infection, obs, fill(10, 30)) + problem = IDProblem(IDModel(infection, obs), fill(10, 30)) @test data_requirements(problem).n == 30 @test data_requirements(problem).series_length == 34 # The report is the model's over the same data, printed the same way. @@ -211,14 +197,14 @@ end # A stratified problem reports on the stratum axis, because the shape comes # from the same helper `as_turing_model` builds with. - strata = IDProblem( + stratified = IDModel( DirectInfections(; Z = Stratify(RandomWalk(), FixedIntercept(0.0)), initialisation = IID(Normal()) ), - obs, fill(10, 2, 30) + obs ) - @test data_requirements(strata).n == 30 + @test data_requirements(IDProblem(stratified, fill(10, 2, 30))).n == 30 end @testitem "_obs_data_shape resolves stratified shapes from data or Split" begin @@ -263,15 +249,14 @@ end initialisation = Normal(log(20), 0.2) ) Y = Matrix{Union{Missing, Float64}}(missing, 1, T) - problem_map = IDProblem(infection, Split(PoissonError(), [1.0 1.0 1.0]), Y) + mapped = IDModel(infection, Split(PoissonError(), [1.0 1.0 1.0])) + problem_map = IDProblem(mapped, Y) @test size(as_turing_model(problem_map)().I_t) == (3, T) # A Split with named streams over a blank series builds one stratum per # name, reading the length off the series. - problem_named = IDProblem( - infection, Split((a = PoissonError(), b = PoissonError())), - Vector{Missing}(missing, T) - ) + named = IDModel(infection, Split((a = PoissonError(), b = PoissonError()))) + problem_named = IDProblem(named, Vector{Missing}(missing, T)) @test size(as_turing_model(problem_named)().I_t) == (2, T) end @@ -345,13 +330,13 @@ end using ComposableTuringIDModels, Distributions, Turing, Random Random.seed!(102) T, h = 18, 5 - infection = DirectInfections(; Z = AR(), initialisation = Normal()) - y = as_turing_model( - IDProblem(infection, PoissonError(), Vector{Missing}(missing, T)) - )().generated_y_t + model = IDModel( + DirectInfections(; Z = AR(), initialisation = Normal()), PoissonError() + ) + y = as_turing_model(IDProblem(model, Vector{Missing}(missing, T)))().generated_y_t # The fitted problem holds the series, so the forecast needs only the chain # and the horizon. - problem = IDProblem(infection, PoissonError(), y) + problem = IDProblem(model, y) chain = sample(as_turing_model(problem), Prior(), 30; progress = false) fc = forecast(problem, chain, h) @test size(fc, 1) == 30 diff --git a/test/unit/observation_models/requirements.jl b/test/unit/observation_models/requirements.jl index 1dae005ec..e5c9681d7 100644 --- a/test/unit/observation_models/requirements.jl +++ b/test/unit/observation_models/requirements.jl @@ -74,7 +74,7 @@ end # An IDModel and an IDProblem delegate to their observation model. infection = DirectInfections(; Z = RandomWalk(), initialisation = Normal()) @test observation_lead_in(IDModel(infection, stacked)) == 7 - problem = IDProblem(infection, stacked, fill(10, 30)) + problem = IDProblem(IDModel(infection, stacked), fill(10, 30)) @test observation_lead_in(problem) == 7 end From 1fb3ea8eb7aeac7dfbfc1e73aab699d88d2d8672 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Sep 2026 21:49:12 +0000 Subject: [PATCH 12/12] test(requirements): build the IDModel before the IDProblem in two more items Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01Lw3PbYZfA1dZhfaaE9tbdp --- test/unit/observation_models/requirements.jl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/unit/observation_models/requirements.jl b/test/unit/observation_models/requirements.jl index e5c9681d7..bdd871272 100644 --- a/test/unit/observation_models/requirements.jl +++ b/test/unit/observation_models/requirements.jl @@ -317,7 +317,7 @@ end # An `IDProblem` reads the observation count from the data it holds, so its # report is the model's over that data. - problem = IDProblem(model.infection_model, obs, fill(10, 60)) + problem = IDProblem(IDModel(model.infection_model, obs), fill(10, 60)) @test data_requirements(problem).series_length == 103 report(x...) = sprint(show, MIME"text/plain"(), data_requirements(x...)) @test report(problem) == report(model, fill(10, 60), 60) @@ -513,7 +513,7 @@ end @test size(fc, 1) == 20 # An `IDProblem` holds the series, so it needs no length of its own. - problem = IDProblem(model.infection_model, obs, y) + problem = IDProblem(IDModel(model.infection_model, obs), y) @test data_requirements(problem).n == length(y) pchain = sample(as_turing_model(problem), Prior(), 20; progress = false) pfc = forecast(problem, pchain, h)