Repository navigation
feat: record the noise-free renewal expectation as a generated quantity - #337
seabbs-bot wants to merge 5 commits into
Conversation
Try this Pull Request!Option 1: Julia Package ManagerOpen Julia and type: import Pkg
Pkg.activate(temp=true)
Pkg.add(url="https://github.com/EpiAware/ComposableTuringIDModels.jl", rev="feat/320-renewal-expectation")
using ComposableTuringIDModelsOption 2: Local CheckoutIf you have the repo locally: git checkout feat/320-renewal-expectation
julia --project=. -e "using Pkg; Pkg.instantiate()" |
Benchmark comparison vs baseMinimum time per call. Buckets are PR time as a % of base, so lower is faster (🟢 faster, ⚪ within 5%, 🔴 slower). Counts of benchmarks per bucket:
Evaluation — 9 benchmarks (by time change)
AD gradients — 7 benchmarks (by time change)
|
|
📖 Documentation preview is ready! View the docs for this PR at: https://EpiAware.github.io/ComposableTuringIDModels.jl/previews/PR337/ This preview will be updated automatically when you push new commits. |
Codecov Report✅ All modified and coverable lines are covered by tests.
Flags with carried forward coverage won't be shown. Click here to find out more.
... and 1 file with indirect coverage changes 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
This PR threads a noise-free renewal expectation exp_val/exp_I_t alongside the committed incidence through RenewalStep's scan, exposes it as a := generated quantity from Renewal, and fixes forecast's latent-stream extension to skip generated quantities (which exp_I_t would otherwise break). The mechanism correctly mirrors the existing val/get_state pattern and the forecast fix is sound, but one new test's comment contradicts the code it documents, and several new docstrings describe the committed incidence as "drawn around" the expectation even though no currently implemented modifier is stochastic.
Automated first pass by seabbs-review-bot (Claude sonnet), triggered by: first pass. Not a human review. Comment @seabbs-review-bot to ask for another pass: @seabbs any time, the author's agent once it has pushed changes. Add the no-review label to opt this PR out. Ping @seabbs with any questions.
| using ComposableTuringIDModels: ConstantRenewalStep, RenewalStep, | ||
| SusceptibleDepletion, accumulate_scan, renewal_init_state, | ||
| get_expected_state | ||
| # A plain core has no modifier: the expectation is the draw itself, and the |
There was a problem hiding this comment.
issue This comment says "a plain core has no modifier: the expectation is the draw itself", but good on the next lines is built with a SusceptibleDepletion modifier, and every assertion below (accumulate_scan(good, init, Rt) .<= exp_val, maximum(...) < maximum(exp_val)) checks depletion behaviour, not the no-modifier identity the comment describes. Update the comment to describe what's actually tested, e.g. "With susceptible depletion the committed draw is scaled down by the pool fraction, so it stays at or below the expectation and equals it only while the pool is full."
There was a problem hiding this comment.
Already fixed before this pass landed, and tightened again now. The comment above the SusceptibleDepletion assertions describes depletion, and the no-modifier identity has its own loop over (core, RenewalStep(core, ())) above it. Also split the colon join into two sentences.
| the (log) ``R_t`` path. | ||
| [`ModelShape`](@ref) `n` and returns the named tuple `(; I_t, Z_t, exp_I_t)` | ||
| with `Z_t` the (log) ``R_t`` path and `exp_I_t` the noise-free renewal | ||
| *expectation* — the incidence each step drew around, i.e. the value the |
There was a problem hiding this comment.
suggestion "the incidence each step drew around" (and the same phrasing in docs/src/design.md:119 and src/steps/RenewalStep.jl:247, "the value a stochastic renewal modifier would draw around") implies I_t is a stochastic draw with exp_I_t as its mean. Neither existing modifier is stochastic: SusceptibleDepletion deterministically scales exp_I_t down and ImportedCases deterministically shifts it up. Consider wording this as a deterministic transform ("the incidence before any modifier transforms it") unless a stochastic modifier is meant to be implied as a near-term target.
There was a problem hiding this comment.
Agreed, and taken. Neither shipped modifier is stochastic, so "drew around" was wrong. Renewal's docstring, the scan comment in RenewalStep.jl and docs/src/design.md now all say the same deterministic thing: the incidence reaching the modifier tuple before any modifier transforms it.
Worth flagging that this is narrower than what #320 asks for. #320 wants the incidence entering the first noise modifier, which differs once a deterministic modifier such as SusceptibleDepletion sits ahead of the noise. That is the maintainer's call, so the behaviour is unchanged and the question is written up in the PR body.
|
@seabbs-review-bot |
There was a problem hiding this comment.
The PR threads a new exp_val field through RenewalStep's scan state and exposes it via a new public get_expected_state dispatch function, wired into Renewal's as_turing_model as exp_I_t, with a matching fix so forecast's latent-stream extension skips generated quantities. The design reuses the existing get_state/scan-state pattern correctly, avoids a second scan pass, and is well covered by new tests for the plain, SusceptibleDepletion and ImportedCases cases plus chain and forecast round-trips.
Automated first pass by seabbs-review-bot (Claude sonnet), triggered by: re-review requested by seabbs-bot. Not a human review. Comment @seabbs-review-bot to ask for another pass: @seabbs any time, the author's agent once it has pushed changes. Add the no-review label to opt this PR out. Ping @seabbs with any questions.
| ComposableTuringIDModels.get_expected_state(step, init, result) | ||
| ``` | ||
| " | ||
| function get_expected_state(::RenewalStep, initial_state, state) |
There was a problem hiding this comment.
suggestion get_expected_state is now public with a generic name mirroring get_state, but unlike get_state (which has a default fallback for any AbstractAccumulationStep in accumulate_scan.jl:50) it has no fallback: calling it on any other accumulation step (MAStep, ARStep, LDStep, TimeVaryingLDStep) raises a bare MethodError. This file already has a convention for exactly this gap — _unresolved_modifier (line 66) and MixingStep.jl's _unresolved_mixing (line 52) turn a missing-implementation error into a message naming the type and pointing at what to implement. Consider a similar guard for get_expected_state so a caller of the new public function gets a clear error instead of a bare MethodError.
There was a problem hiding this comment.
Taken, and verified against the source. get_state does have an AbstractAccumulationStep fallback in accumulate_scan.jl, _unresolved_modifier is at RenewalStep.jl:66 and _unresolved_mixing at MixingStep.jl:52, all as cited. get_expected_state now has a fallback on AbstractAccumulationStep that names the type and says only the renewal steps carry an expectation, with a test on an ARStep.
One correction to the list: a MixingStep also reaches it, since MixingStep <: AbstractConstantRenewalStep. An unresolved one now gets the same named error instead of a bare MethodError.
f268b50 to
4907410
Compare
|
THis looks good. A little worried about performance as I think that potentially this will lead to slow downs? Is it also general enoug to allow ie direct infections to be tracked if those are noisy? |
The same noise specification the centred `StochasticRenewal` uses, applied through the renewal modifier seam: `n` standard normals drawn before the scan and the location and scale applied against the expectation inside it, following the `ImportedCases` -> `ImportedRate` pattern. Non-centred is forced rather than chosen — a modifier's priors resolve before the scan and `apply_modifier` is deterministic — and it is the known-worse parameterisation when the observations inform the infections. The docstring says so and points at `StochasticRenewal`. The modifier is still what a stratified stochastic renewal needs, which the centred loop does not cover. Also lands `is_noise`, a trait beside `apply_modifier` marking the modifier that replaces the renewal expectation with a draw, for the generated expected-incidence quantity in #337 to read; and generalises `R_to_r` and `expected_Rt` to both renewal models, which carry the same generation interval. Co-Authored-By: Sam Abbott <contact@samabbott.co.uk> Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UmmqqzQPhrB74RfAv2TqBQ
Closes #320: a stochastic renewal draws its incidence around a renewal expectation that was computed then discarded. The scan step now carries the pre-modifier incidence (exp_val, the force of infection arriving at the modifier tuple) alongside the committed draw, and Renewal.as_turing_model exposes it as exp_I_t, tracked via := as a generated quantity so a chain recovers it as chain[:exp_I_t]. - The RenewalStep state gains exp_val (equal to val with no modifier; the pre-modifier incidence where SusceptibleDepletion or ImportedCases bite). - get_expected_state assembles the expectation series; public, not exported. - Plain ConstantRenewalStep and _PlainRenewalStep report expectation == draw. - Works for the inferred gen_int and stratified (Dims{2}) paths. - Tests: the scan records the expectation; a plain renewal's exp_I_t == I_t; exp_I_t is recoverable from a NUTS chain in a composed IDModel.
exp_I_t (a := generated quantity) lands in the fitted chain as a vector, and forecast's _extend_latent_draws treated every vector chain parameter as an extendable latent stream. But a generated quantity is not a model input: a prior draw of the forecast model never samples it (DynamicPPL's RawValueAccumulator excludes := values), so _assert_factorised and the extension loop KeyError'd on it. Filter resized to keys present in a probe prior draw, and make the get_expected_state docstring example actually call the function on a RenewalStep with SusceptibleDepletion.
The docstring cites ImportedCases as a differing case, so test it: through Renewal's own as_turing_model the committed I_t stays at or above the expectation exp_I_t, with a positive mean difference where the importation bites.
first factorisation sample Telling a `:=` generated quantity from a model input needed a prior draw, but `_assert_factorised` was about to draw 256 more. Hoist a single `_prior_draw` helper, use its result for the membership test and pass it in as the batch's first sample. That drops the extra full model evaluation `forecast` had gained, leaves the RNG stream where it was, and replaces the three copies of the same draw-to-Dict comprehension with one. Cover the two paths the patch left untested: `get_expected_state` on a modifier-free step, and a forecast asserting `exp_I_t` comes back at the horizon length because `predict` recomputes it rather than splicing a tail. Say the expectation's definition once, in `Renewal`'s docstring, instead of four times across the docstring, the design page, the scan comment and `get_expected_state`. Co-Authored-By: Sam Abbott <contact@samabbott.co.uk> Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UmmqqzQPhrB74RfAv2TqBQ
`get_expected_state` is public with a generic name mirroring `get_state`, but unlike `get_state` it had no fallback, so calling it on an `ARStep`, `MAStep`, `LDStep` or `TimeVaryingLDStep` raised a bare `MethodError`. Add the guard this file already uses for `_unresolved_modifier` and `MixingStep`'s `_unresolved_mixing`, and test it. Also drop the wording that implied `I_t` is a stochastic draw with `exp_I_t` as its mean. Neither modifier is stochastic: `SusceptibleDepletion` scales the incidence down and `ImportedCases` shifts it up, both deterministically. Co-Authored-By: Sam Abbott <contact@samabbott.co.uk> Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
4907410 to
30a5f53
Compare
The same noise specification the centred `StochasticRenewal` uses, applied through the renewal modifier seam: `n` standard normals drawn before the scan and the location and scale applied against the expectation inside it, following the `ImportedCases` -> `ImportedRate` pattern. Non-centred is forced rather than chosen — a modifier's priors resolve before the scan and `apply_modifier` is deterministic — and it is the known-worse parameterisation when the observations inform the infections. The docstring says so and points at `StochasticRenewal`. The modifier is still what a stratified stochastic renewal needs, which the centred loop does not cover. Also lands `is_noise`, a trait beside `apply_modifier` marking the modifier that replaces the renewal expectation with a draw, for the generated expected-incidence quantity in #337 to read; and generalises `R_to_r` and `expected_Rt` to both renewal models, which carry the same generation interval. Co-Authored-By: Sam Abbott <contact@samabbott.co.uk> Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UmmqqzQPhrB74RfAv2TqBQ
|
This work is folded into #348 (branch The semantics. This PR captured the force of infection from before the whole modifier tuple. The cost. The forecast fix. Ported as it stood, including the This was opened by a bot. Please ping @seabbs for any questions. |
Closes #320.
A stochastic renewal draws its incidence around a renewal expectation that was computed then discarded.
The expectation never survived into the model's return value, so there was no way to recover it, unlike
RecordExpectedLatentfor latent models.This PR makes
Renewalreturn(; I_t, Z_t, exp_I_t, I_seed), withexp_I_tthe renewal expectation.RenewalStepscan state carriesexp_val, the force of infection arriving at the modifier tuple, alongside the committed drawval.get_expected_stateassembles the expectation series. It is public, not exported, and plain cores report expectation == draw.AbstractAccumulationStephas no expectation, so a fallback names the step rather than raising a bareMethodError, matching_unresolved_modifierand_unresolved_mixing.exp_I_tis tracked via:=as a generated quantity, so a chain recovers it aschain[:exp_I_t].Dims{2}) paths. With no modifierexp_I_t == I_t, and withSusceptibleDepletion/ImportedCasesit differs exactly where the modifier bites.forecastskips:=quantities when extending latent streams. A generated quantity is not a model input, so a prior draw of the forecast model never samples it and the extension loop used toKeyError. One prior draw now serves as both the input probe and the first sample of the factorisation batch, so the check costs no extra model evaluation.Tests: the scan records the expectation alongside the draw; a plain renewal exposes
exp_I_tidentical toI_t(vector and stratified);exp_I_tsits at or belowI_tunder depletion and above it under importation;exp_I_tis recoverable from a NUTS chain in a composedIDModel; a forecast returnsexp_I_tat the horizon length becausepredictrecomputes it;get_expected_stateon a non-renewal step names the step.Open design question for the maintainer
exp_I_there is the incidence reaching the modifier tuple, so it is the force of infection before the whole tuple.Issue #320 asks for the incidence entering the first noise modifier, which is not the same thing once a deterministic modifier such as
SusceptibleDepletionsits ahead of the noise.Under the strict reading the depletion factor would belong inside the expectation rather than outside it.
This PR does not decide that.
The behaviour is left as the pre-tuple force of infection.
PR #348 (open) proposes an
is_noisetrait onAbstractRenewalModifier, which would be the seam for the strict reading: thread the incidence up to the firstis_noisemodifier instead of up to the head of the tuple.Nothing here wires that up.
CI notes
codecov/patchis red on stale data, not on untested code. The only coverage run on this branch that uploaded was for an earlier commit, and the coverage job on the tip was cancelled at the shared workflow's 45-minute cap beforejulia-processcoverageran, so codecov carried the base report forward and read every line added after that upload as a miss. Runningtest/unit/inference/inference.jlandtest/unit/infection_models/renewal_step.jllocally under--code-coverageexecutes all of them:_prior_draw2295 hits,probe9, thehaskeyfilter 68,_assert_factorised9,get_expected_state(::_PlainRenewalStep)1.Documenter / Documentationis red repo-wide, not on this PR. See Documenter runs are cancelled before Julia starts when several branches are active #353. The docs build here is unverified.This was opened by a bot. Please ping @seabbs for any questions.