diff --git a/Project.toml b/Project.toml index 9b7f940d..09975950 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 60c9ab83..d55f326e 100644 --- a/docs/src/design.md +++ b/docs/src/design.md @@ -238,7 +238,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)'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. +[`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 c5abb384..e17e078f 100644 --- a/docs/src/tutorials/catalyst-ode.md +++ b/docs/src/tutorials/catalyst-ode.md @@ -146,7 +146,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. -[`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 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 @@ -181,7 +182,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 03cd35c4..4a576215 100644 --- a/docs/src/tutorials/delays-dayofweek.md +++ b/docs/src/tutorials/delays-dayofweek.md @@ -92,8 +92,8 @@ 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. +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 @@ -112,23 +112,34 @@ 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. ```@example delays -problem = IDProblem( - infection = renewal, - observation_model = observation, - tspan = (1, n)) -nothing # hide +problem = IDProblem(IDModel(renewal, observation), y_obs) +``` + +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. + +```@example delays +data_requirements(problem) +``` + +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 +@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``. ```@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) @@ -167,7 +178,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. @@ -196,10 +207,11 @@ 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) +blank = @set problem.data = Vector{Missing}(missing, n) +pred = predict(as_turing_model(blank), chain) yt = predictive_bands(pred, n) lead_in = observation_lead_in(observation) diff --git a/docs/src/tutorials/gaussian-process.md b/docs/src/tutorials/gaussian-process.md index 8bb897fb..60b9a914 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 2442a77b..c5f8940a 100644 --- a/docs/src/tutorials/realtime-nowcast.md +++ b/docs/src/tutorials/realtime-nowcast.md @@ -167,7 +167,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. @@ -176,7 +176,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 @@ -215,7 +215,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 d94c9dd3..458699e3 100644 --- a/docs/src/tutorials/renewal-negbin.md +++ b/docs/src/tutorials/renewal-negbin.md @@ -174,7 +174,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. @@ -219,7 +219,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 5890109a..6a162c05 100644 --- a/docs/src/tutorials/sir-ode.md +++ b/docs/src/tutorials/sir-ode.md @@ -148,7 +148,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. -[`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 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 @@ -185,7 +186,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 2405f7c5..95eb98e6 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 # `Accessors` and `rewrap` rebuild a component through @@ -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 d9610f26..d1cf7837 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 7d5a9baa..575afd9d 100644 --- a/src/compose.jl +++ b/src/compose.jl @@ -167,16 +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)` 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. - -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. +`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 `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 @@ -193,12 +194,64 @@ 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 + +_data_shape(model::IDModel, y_t) = _obs_data_shape( + model.observation_model, y_t, _series_time_length(y_t) +) + +# 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 a private helper. +# A `NamedTuple` of streams shares one time length, read off its first stream. +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( + "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. +# 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 +) +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" diff --git a/src/inference/DirectSample.jl b/src/inference/DirectSample.jl deleted file mode 100644 index 2a19249f..00000000 --- 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 30ae1e15..00000000 --- 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 495dd542..5e3a367e 100644 --- a/src/inference/IDProblem.jl +++ b/src/inference/IDProblem.jl @@ -1,104 +1,179 @@ -# `IDProblem`: an infection + observation model over a time span. +# 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 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. + +An [`IDModel`](@ref) says what the process is. The data says how long it runs +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)). A plain vector gives a +single series. A `strata x time` matrix or a `NamedTuple` of streams gives a +stratified process. + +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 +fitted = @set problem.data = y +``` + +Printing an `IDProblem` shows the component tree and a summary of the data. # Arguments - - `idproblem`: the [`IDProblem`](@ref). - - `data`: a value with a `y_t` field holding the observations (or `missing`). + - `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( - infection = DirectInfections(; Z = RandomWalk(), initialisation = Normal()), - observation_model = PoissonError(), - tspan = (1, 20)) -rand(as_turing_model(problem, (; y_t = missing))) +model = IDModel( + DirectInfections(; Z = RandomWalk(), initialisation = Normal()), + PoissonError()) +problem = IDProblem(model, 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 + + function IDProblem(model::M, data::D) where {M <: IDModel, D} + _assert_data_fits(model, data) + return new{M, D}(model, data) + end 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) +# 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 + return throw( + ArgumentError( + "the data does not fit the model:\n" * + sprint(show, MIME"text/plain"(), required) + ) + ) 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) + +# 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) -# 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) +data_requirements(problem::IDProblem) = data_requirements( + problem.model, problem.data, _problem_shape(problem) +) + +# 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( + "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 -_observation_chain(idproblem::IDProblem) = idproblem.observation_model +@doc raw" +Build the `DynamicPPL.Model` for an [`IDProblem`](@ref). -data_requirements(idproblem::IDProblem, data) = data_requirements( - idproblem, data.y_t, _tspan_length(idproblem) -) +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`: -data_requirements(idproblem::IDProblem) = data_requirements( - idproblem, missing, _tspan_length(idproblem) -) +```julia +using Accessors +refit = @set problem.data = y_new +``` -# 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 -) +# Arguments -_tspan_length(idproblem::IDProblem) = - idproblem.tspan[end] - idproblem.tspan[1] + 1 + - `problem`: the [`IDProblem`](@ref). +" +as_turing_model(problem::IDProblem) = as_turing_model(problem.model, problem.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. +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 + +Base.show(io::IO, ::IDProblem) = print(io, "IDProblem") + +# 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) + blank = count(ismissing, y) + 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") +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::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" + ) 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` 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, since the summary has 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 077e4edf..00000000 --- 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 937dcc4e..00000000 --- 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 ee3d1b99..4c091aac 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 288438e9..00000000 --- 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 efa5e64a..00000000 --- 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 b4138881..00000000 --- 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 c267b47f..d7060c4d 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 @@ -355,7 +357,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 +591,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`, 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/src/utils/turing-methods.jl b/src/utils/turing-methods.jl deleted file mode 100644 index d231fdd9..00000000 --- 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 0b18d22b..bc0fc227 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" @@ -14,11 +13,11 @@ 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" 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 +37,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 e2294d3c..6f3ce248 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 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/compose_strata.jl b/test/unit/compose_strata.jl index 4cf9e1dd..d0ae27e6 100644 --- a/test/unit/compose_strata.jl +++ b/test/unit/compose_strata.jl @@ -107,3 +107,34 @@ 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) + # 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 07290181..75c677dd 100644 --- a/test/unit/inference/inference.jl +++ b/test/unit/inference/inference.jl @@ -1,22 +1,218 @@ -@testitem "IDProblem assembles and simulates a composed model" begin - using ComposableTuringIDModels, Distributions, Random +@testitem "IDProblem pairs a model with its data and needs no length" begin + using ComposableTuringIDModels, Distributions, Random, Accessors + using DynamicPPL: VarInfo Random.seed!(71) - problem = IDProblem( - infection = DirectInfections(; Z = RandomWalk(), initialisation = Normal()), - observation_model = PoissonError(), - tspan = (1, 20) + model = IDModel( + DirectInfections(; Z = RandomWalk(), initialisation = Normal()), + PoissonError() ) - m = as_turing_model(problem, (; y_t = missing)) - sim = m() + 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. + y = sim.generated_y_t + @test keys(VarInfo(as_turing_model(IDProblem(model, y)))) == + keys(VarInfo(as_turing_model(model, y, length(y)))) + + # 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 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 +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) + ) + model = IDModel(infection, obs) + ragged = (cases = fill(5, 30), deaths = fill(1, 40)) + @test_throws ArgumentError IDProblem(model, ragged) + # The guard is an inner constructor, so respecifying into the same mistake + # is refused too. + 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(model, (cases = fill(5, 30), deaths = fill(1, 20))) isa + IDProblem + plain = IDModel(infection, PoissonError()) + @test IDProblem(plain, fill(5, 30)) isa IDProblem + # Both simulation routes stay constructible. + @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. + 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 + 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)) + ) + # 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) + + # 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 + model = IDModel( + DirectInfections(; Z = RandomWalk(), initialisation = Normal()), + 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) + @test_throws ArgumentError data_requirements(problem, (2, 30)) +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(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. + @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(model, Vector{Missing}(missing, 30))) + @test occursin("└─ data: none, 30 time points (simulating from the prior)", blank) + + gappy = render( + 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. + 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( + 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( + split, ( + cases = Vector{Missing}(missing, 30), + deaths = Vector{Missing}(missing, 30), + ) + ) + ) + @test occursin( + "└─ data: none, 30 time points (simulating from the prior)", blank_streams + ) + + 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(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(model, 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(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. + 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. + stratified = IDModel( + DirectInfections(; + Z = Stratify(RandomWalk(), FixedIntercept(0.0)), + initialisation = IID(Normal()) + ), + obs + ) + @test data_requirements(IDProblem(stratified, fill(10, 2, 30))).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 +226,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 +244,20 @@ 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) - - # A Split with named streams and `y_t = missing` builds one stratum per - # name. - 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 + 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) -@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 - ) - 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 + # A Split with named streams over a blank series builds one stratum per + # name, reading the length off the series. + 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 @testitem "forecast rejects a non-positive horizon" begin @@ -190,18 +329,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 + model = IDModel( + DirectInfections(; Z = AR(), initialisation = Normal()), PoissonError() ) - fc = forecast(problem, y, chain, h) + 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(model, 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 +452,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 1ce854db..44fa4f4d 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 db41d558..bdd87127 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(IDModel(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(IDModel(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(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) @test size(pfc, 1) == 20 end diff --git a/test/unit/utils/utils_extra.jl b/test/unit/utils/utils_extra.jl index de59bf12..4625c24b 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,