Skip to content

feat: record the noise-free renewal expectation as a generated quantity - #337

Closed
seabbs-bot wants to merge 5 commits into
mainfrom
feat/320-renewal-expectation
Closed

seabbs-bot wants to merge 5 commits into
mainfrom
feat/320-renewal-expectation

Conversation

@seabbs-bot

@seabbs-bot seabbs-bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Collaborator

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 RecordExpectedLatent for latent models.

This PR makes Renewal return (; I_t, Z_t, exp_I_t, I_seed), with exp_I_t the renewal expectation.

  • The RenewalStep scan state carries exp_val, the force of infection arriving at the modifier tuple, alongside the committed draw val.
  • get_expected_state assembles the expectation series. It is public, not exported, and plain cores report expectation == draw.
  • Any other AbstractAccumulationStep has no expectation, so a fallback names the step rather than raising a bare MethodError, matching _unresolved_modifier and _unresolved_mixing.
  • exp_I_t is tracked via := as a generated quantity, so a chain recovers it as chain[:exp_I_t].
  • Works for the inferred generation-interval and stratified (Dims{2}) paths. With no modifier exp_I_t == I_t, and with SusceptibleDepletion/ImportedCases it differs exactly where the modifier bites.
  • forecast skips := 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 to KeyError. 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_t identical to I_t (vector and stratified); exp_I_t sits at or below I_t under depletion and above it under importation; exp_I_t is recoverable from a NUTS chain in a composed IDModel; a forecast returns exp_I_t at the horizon length because predict recomputes it; get_expected_state on a non-renewal step names the step.

Open design question for the maintainer

exp_I_t here 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 SusceptibleDepletion sits 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_noise trait on AbstractRenewalModifier, which would be the seam for the strict reading: thread the incidence up to the first is_noise modifier instead of up to the head of the tuple.
Nothing here wires that up.

CI notes

  • codecov/patch is 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 before julia-processcoverage ran, so codecov carried the base report forward and read every line added after that upload as a miss. Running test/unit/inference/inference.jl and test/unit/infection_models/renewal_step.jl locally under --code-coverage executes all of them: _prior_draw 2295 hits, probe 9, the haskey filter 68, _assert_factorised 9, get_expected_state(::_PlainRenewalStep) 1.
  • Documenter / Documentation is 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.

@seabbs-bot
seabbs-bot requested a review from seabbs as a code owner August 28, 2026 16:32
@github-actions

Copy link
Copy Markdown
Contributor

Try this Pull Request!

Option 1: Julia Package Manager

Open Julia and type:

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

Option 2: Local Checkout

If you have the repo locally:

git checkout feat/320-renewal-expectation
julia --project=. -e "using Pkg; Pkg.instantiate()"

@github-actions

github-actions Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Benchmark comparison vs base

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

Group 🟢 <50% 🟢 50–75% 🟢 75–95% ⚪ 95–105% 🔴 105–125% 🔴 125–150% 🔴 >150%
Evaluation 2 6 1 · · · ·
ForwardDiff · 1 1 · · · ·
ReverseDiff (tape) 1 1 · · · · ·
Mooncake reverse · 2 · · · · ·
Enzyme reverse 1 · · · · · ·
Evaluation — 9 benchmarks (by time change)
Benchmark base PR time memory
Model evaluation / RandomWalk latent / rand 451.0 ns 210.0 ns 🟢 0.47× ⚪ 1.0×
Model evaluation / AR latent / rand 631.0 ns 310.0 ns 🟢 0.49× ⚪ 1.0×
Model evaluation / RandomWalk latent / forward 420.0 ns 210.0 ns 🟢 0.5× ⚪ 1.0×
Model evaluation / Renewal+NegativeBinomial / forward 4.68 μs 2.37 μs 🟢 0.51× ⚪ 1.04×
Model evaluation / AR latent / forward 530.0 ns 280.0 ns 🟢 0.53× ⚪ 1.0×
Model evaluation / DirectInfections+Poisson / forward 1.12 μs 601.0 ns 🟢 0.54× ⚪ 1.0×
Model evaluation / DirectInfections+Poisson / rand 661.0 ns 370.0 ns 🟢 0.56× ⚪ 1.0×
Model evaluation / Renewal+NegativeBinomial / rand 2.19 μs 1.26 μs 🟢 0.58× 🔴 1.08×
Sampling / NUTS (DirectInfections+Poisson, 50 draws) 89.95 ms 70.84 ms 🟢 0.79× ⚪ 1.0×
AD gradients — 7 benchmarks (by time change)
Benchmark base PR time memory
AD gradients / DirectInfections+Poisson posterior / Enzyme reverse 3.29 μs 1.54 μs 🟢 0.47× ⚪ 1.0×
AD gradients / DirectInfections+Poisson posterior / ReverseDiff (tape) 103.17 μs 51.21 μs 🟢 0.5× ⚪ 1.0×
AD gradients / AR latent logjoint / ReverseDiff (tape) 45.16 μs 22.82 μs 🟢 0.51× ⚪ 1.0×
AD gradients / AR latent logjoint / Mooncake reverse 5.45 μs 2.83 μs 🟢 0.52× ⚪ 1.0×
AD gradients / DirectInfections+Poisson posterior / Mooncake reverse 8.65 μs 4.56 μs 🟢 0.53× ⚪ 1.0×
AD gradients / DirectInfections+Poisson posterior / ForwardDiff 13.84 μs 8.99 μs 🟢 0.65× ⚪ 1.0×
AD gradients / AR latent logjoint / ForwardDiff 8.24 μs 6.82 μs 🟢 0.83× ⚪ 1.0×

@github-actions

Copy link
Copy Markdown
Contributor

📖 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

codecov Bot commented Aug 28, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

Flag Coverage Δ
ad-enzyme-forward 63.45% <45.00%> (-2.41%) ⬇️
ad-enzyme-reverse 61.89% <45.00%> (-2.20%) ⬇️
ad-forwarddiff 62.31% <45.00%> (-0.09%) ⬇️
ad-mooncake-forward 62.31% <45.00%> (-0.09%) ⬇️
ad-mooncake-reverse 62.31% <45.00%> (-2.30%) ⬇️
ad-reversediff 62.48% <45.00%> (-0.11%) ⬇️
ad-reversediff-compiled 62.48% <45.00%> (-0.11%) ⬇️
unit 94.05% <100.00%> (+0.03%) ⬆️

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

Files with missing lines Coverage Δ
src/infection_models/Renewal.jl 100.00% <100.00%> (ø)
src/inference/forecast.jl 98.24% <100.00%> (+0.06%) ⬆️
src/steps/RenewalStep.jl 93.65% <100.00%> (+0.66%) ⬆️
src/steps/RenewalSteps.jl 100.00% <100.00%> (ø)

... and 1 file with indirect coverage changes

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

@seabbs-review-bot seabbs-review-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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."

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/infection_models/Renewal.jl Outdated
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 seabbs-review-bot Bot added the llm-reviewed Reviewed by seabbs-review-bot label Sep 2, 2026
@seabbs-bot

Copy link
Copy Markdown
Collaborator Author

@seabbs-review-bot

@seabbs-review-bot seabbs-review-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/steps/RenewalStep.jl
ComposableTuringIDModels.get_expected_state(step, init, result)
```
"
function get_expected_state(::RenewalStep, initial_state, state)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@seabbs

seabbs commented Sep 2, 2026

Copy link
Copy Markdown
Member

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?

seabbs-bot added a commit that referenced this pull request Sep 2, 2026
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
seabbs-bot and others added 5 commits September 3, 2026 18:23
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>
@seabbs-bot
seabbs-bot force-pushed the feat/320-renewal-expectation branch from 4907410 to 30a5f53 Compare September 3, 2026 18:11
seabbs-bot added a commit that referenced this pull request Sep 3, 2026
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
@seabbs seabbs closed this Sep 4, 2026
@seabbs-bot

Copy link
Copy Markdown
Collaborator Author

This work is folded into #348 (branch 289-noise) rather than reopened here.
Two things changed on the way in, and the forecast fix went across unchanged.

The semantics. This PR captured the force of infection from before the whole modifier tuple.
#320 asks for the value apply_modifier receives as its incidence argument, which is EpiSewer's iota.
Under (SusceptibleDepletion, InfectionNoise) those differ: the true expectation is (S/N) * foi, so this PR overstated it by the susceptible fraction.
#348's is_noise trait is the seam that separates them, and it had no consumer until now.
_thread_modifiers there carries the incidence entering the first modifier that draws, alongside the committed one.

The cost. exp_I_t := ... on every Renewal evaluates its right-hand side on every model evaluation, through duals, for a reporting-only quantity.
It is opt-in now, through RecordExpectedInfections(model), which follows RecordExpectedLatent and RecordExpectedObs.
The seam it reads through has an honest default, so wrapping a DirectInfections records I_t rather than erroring, which answers the generality question by construction.
Measured gradient times and allocations for the wrapped and unwrapped paths are in #348's body.

The forecast fix. Ported as it stood, including the _prior_draw hoist that reuses one prior draw as both the membership probe and _assert_factorised's first sample, and its test.
It is load-bearing: on 289-noise exp_I_t shows up among a chain's FlexiChains.Parameter keys and never in a prior draw, so without the guard _extend_latent_draws throws a KeyError.

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

llm-reviewed Reviewed by seabbs-review-bot

Projects

None yet

Development

Successfully merging this pull request may close these issues.

No way to record the noise-free renewal expectation as a generated quantity

2 participants