Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 0 additions & 10 deletions Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,15 @@ 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"
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"
Expand All @@ -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"
Expand All @@ -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"
Expand Down
2 changes: 2 additions & 0 deletions docs/Project.toml
Original file line number Diff line number Diff line change
@@ -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"
Expand Down Expand Up @@ -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"
Expand Down
3 changes: 2 additions & 1 deletion docs/src/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)'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.
Expand Down
5 changes: 3 additions & 2 deletions docs/src/tutorials/catalyst-ode.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
[`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
Expand Down Expand Up @@ -184,7 +185,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)
Expand Down
41 changes: 27 additions & 14 deletions docs/src/tutorials/delays-dayofweek.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,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
Expand All @@ -119,23 +119,35 @@ 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.
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.
Comment thread
seabbs marked this conversation as resolved.
Resolved

```@example delays
problem = IDProblem(
infection = renewal,
observation_model = observation,
tspan = (1, n))
nothing # hide
problem = IDProblem(renewal, observation, y_obs)
Comment thread
seabbs-bot marked this conversation as resolved.
Resolved
```

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)
Expand Down Expand Up @@ -176,7 +188,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.

Expand Down Expand Up @@ -210,10 +222,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)

fig = Figure(; size = (760, 620))
Expand Down
4 changes: 2 additions & 2 deletions docs/src/tutorials/gaussian-process.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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]
Expand Down
6 changes: 3 additions & 3 deletions docs/src/tutorials/realtime-nowcast.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand Down Expand Up @@ -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

Expand Down
4 changes: 2 additions & 2 deletions docs/src/tutorials/renewal-negbin.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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)
Expand Down
5 changes: 3 additions & 2 deletions docs/src/tutorials/sir-ode.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
[`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
Expand Down Expand Up @@ -188,7 +189,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)
Expand Down
26 changes: 5 additions & 21 deletions src/ComposableTuringIDModels.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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,
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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
12 changes: 10 additions & 2 deletions src/base/prettyprinting.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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

Expand Down
Loading
Loading