Skip to content

docs: simulate and fit the patch-models tutorial - #281

Merged
seabbs merged 4 commits into
mainfrom
docs/patch-models-tutorial
Aug 21, 2026
Merged

seabbs merged 4 commits into
mainfrom
docs/patch-models-tutorial

Conversation

@seabbs-bot

Copy link
Copy Markdown
Collaborator

Summary

docs/src/tutorials/patch-models.md previously only built and inspected
coupled/stratified patch models — it never called sample(), so it never
answered whether any of that machinery is actually identifiable from data.
Related to the general "does this really work" concern behind patch and
strata-mapping design discussions (see #248 for the patch-mixing context).

Brought the tutorial up to the bar set by renewal-negbin.md and
hierarchy-stacked.md:

  • Added a simulate → fit → plot section for the fixed-K coupled,
    partially pooled renewal model (Stratify + Hierarchy + an off-diagonal
    mixing matrix, observed through Split). Fits under NUTS (300 draws,
    ForwardDiff), recovers each patch's R_t path, and plots posterior median
    • 80% band against the simulated truth with CairoMakie.
  • Added a second simulate → fit → table section for Gravity's inferred
    coupling: draws a true (α, β, γ) from the prior, fits, and reports a
    recovery table (no @assert gating, per the GP-tutorial lesson about
    version-coupled tripwires).

Finding worth flagging

The fixed-K coupled fit recovers well: posterior median tracks the true
R_t path in all three patches, 80% credible interval covers the truth in
76% of 72 patch-day cells.

The Gravity fit is a genuine mixed result, reported as-is rather than
tuned away: with only three patches (three off-diagonal K entries), γ
(distance exponent) recovers well and β is roughly captured, but α's
posterior mean overshoots the truth and its 80% interval misses it
entirely. Three patches isn't enough data to identify all three gravity
exponents separately — a real application would need more strata or an
informative prior / fixed exponent.

Verification

Ran every code block in the page (both new sections plus the existing
ones) end-to-end in a single Julia session mirroring Documenter's
@example semantics, with the seed fixed at each simulate step for
reproducibility. Confirmed no errors, and cross-checked the printed
numbers via standalone scripts. Did not run the full task docs /
Documenter build (slow, and the instructions for this task said running
the code directly is what matters).

Test plan

  • task docs-fast (or task docs) builds this page cleanly in CI
  • Reviewer sanity-checks the recovery numbers/plot render as expected

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

The patch-models tutorial never called sample(), so it never answered
whether coupled or stratified patch processes are actually
identifiable from data.

Add two end-to-end sections: fit the fixed-K coupled, partially
pooled renewal under NUTS and recover R_t per patch with a
CairoMakie plot (80% coverage close to nominal), then fit the
Gravity model and check whether its exponents come back out.

The gravity exponents are only partially identifiable from three
patches: gamma (distance) recovers well, beta is roughly captured,
but alpha's posterior misses the true value entirely. That's a
genuine finding, reported as a recovery table rather than papered
over with a looser prior.
@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="docs/patch-models-tutorial")
using ComposableTuringIDModels

Option 2: Local Checkout

If you have the repo locally:

git checkout docs/patch-models-tutorial
julia --project=. -e "using Pkg; Pkg.instantiate()"

@codecov

codecov Bot commented Aug 18, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

Flag Coverage Δ
unit 93.58% <ø> (+0.36%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.
see 9 files with indirect coverage changes

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

@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/PR281/

This preview will be updated automatically when you push new commits.

@seabbs-bot
seabbs-bot marked this pull request as ready for review August 18, 2026 09:49
@seabbs-bot
seabbs-bot requested a review from seabbs as a code owner August 18, 2026 09:49

@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 adds two new sections to the patch-models tutorial that simulate a known truth and fit it under NUTS to check whether the coupled patch process and the gravity model's exponents are recoverable. The Julia is sound and reuses the package's own building blocks correctly, but the quantitative recovery claims (coverage, ranges, which exponent recovers) are asserted only in prose rather than checked in the executed code, unlike the sibling gaussian-process.md tutorial which guards equivalent claims with @assert.

Automated first pass by seabbs-review-bot (Claude sonnet), triggered by: first pass. Not a human review. @seabbs can comment @seabbs-review-bot to re-run it, or add the no-review label to opt this PR out. Ping @seabbs with any questions.

Comment thread docs/src/tutorials/patch-models.md Resolved
Comment thread docs/src/tutorials/patch-models.md Resolved
Comment thread docs/src/tutorials/patch-models.md Resolved
@seabbs

seabbs commented Aug 18, 2026

Copy link
Copy Markdown
Member

This doesn't rely on plotting ehought the readouts of the named tuples are no good. It is really really long and the fitting comes very late in the day. We need to review waht partial pooled is for vs this one adn I think maybe work on deplucating. Lots of text as well

Reuse the credible_bands quantile pattern the sibling tutorials use, applied
per patch to Rt_stack[g, :, :], rather than a second 3D mapslices path. The
bands and coverage80 are unchanged (rmse 0.0327, coverage80 0.764).

Bind coverage80 in the block that computes it and add a covered column to the
gravity recovery table, so the coverage figure and the per-exponent recovery
verdict are computed output rather than numbers typed into prose. The prose
now points at those values instead of asserting them.
@seabbs-bot

Copy link
Copy Markdown
Collaborator Author

Review follow-up

Pushed 0992910. One finding fixed, two rejected on mechanism but addressed on substance.

Fixed — duplicate band computation (Rt_med/Rt_lo/Rt_hi). The 3D dropdims(mapslices(...)) path is gone. The block now defines the same credible_bands(mat; qs) used in gaussian-process.md, applies it per patch to Rt_stack[g, :, :] (already a time × draws matrix), and stacks the columns back into strata × time. median(...; dims = 3) went too, since the 0.5 quantile is the same thing. The numbers are unchanged: rmse = 0.0327, coverage80 = 0.764.

Rejected — @assert gates on the coverage figure and the α/β/γ verdicts. A hard recovery threshold gates the docs build on sampler output. Seeds are fixed, but a Turing, DynamicPPL or Mooncake bump changes RNG consumption, so these are version-coupled tripwires that break the build for reasons unrelated to the page. This repo has already been bitten by that class of problem: docs/src/benchmarks/ad-comparison.jl had to be stubbed behind FORCE_STUB_TUTORIALS in docs/docs_config.jl:26. The gaussian-process.md:175-176 asserts cited as precedent are a known problem scheduled for removal, not a convention to spread. Recovery assertions belong in the test suite, where a failure means something.

But the concern behind them is right, so both claims are now computed rather than narrated:

  • coverage80 is bound in the block that builds the bands and printed in its output; the prose points at it instead of hard-coding "76% of the 72 patch-day cells".
  • recovery gains a covered column, q10 <= true_val <= q90 per exponent, so the recovery verdict is a computed column of the table. The three sentences asserting that γ recovers, β roughly, and α not, are replaced by prose explaining how to read that column.

Verification. Ran all 14 @example blocks of the page end-to-end in one session mirroring Documenter's semantics, on the committed file, with no errors. coverage80 = 0.764, and covered came out false for α, true for β and γ — the same result the removed prose asserted, now produced by the table. Did not run the full Documenter build.

Not approving, not merging.

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

Replace the computed covered column with a figure: one posterior density per
exponent with a dashed line at the value that generated the data. A plot
carries the recovery claim better than a printed verdict and regenerates on
every build, so nothing can go stale. The coverage prose points at the R_t
panel rather than at coverage80.

Build grav_post once and derive the recovery table from it, so the chain
lookup is not written twice.
@seabbs-bot

Copy link
Copy Markdown
Collaborator Author

Revised: plots, not printed numbers

Pushed 97b3a7d, which reverses the remedy in my previous commit. Sam's steer on printing computed figures as block output was "we prefer plots."

The α/β/γ recovery verdict is now a figure. The covered column is gone. In its place, one posterior density per exponent with a dashed line at the value that generated the data, so a reader sees which exponents come back out rather than reading a verdict. It cannot go stale, and it says more than the quantile table does. The prose describes what the figure shows: γ is by far the tightest and brackets its truth, the two population exponents are much more diffuse, and α sits away from its truth altogether. The mechanistic explanation that follows is unchanged.

grav_post is now built once and the recovery table derived from it, so the chain lookup is not written twice — the same point the review made about the band computation.

The coverage claim points at the R_t panel. The prose no longer refers to coverage80; the figure already plots the posterior median and 80% band against the simulated truth for each patch.

The credible_bands fix from the earlier commit is unchanged.

Ran all 15 blocks of the committed page end-to-end, no errors, and rendered the new figure to PNG separately to check the layout before committing (three panels, legend below, no overlap).

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

@seabbs

seabbs commented Aug 19, 2026

Copy link
Copy Markdown
Member

This is not great. Lots of LLMs and recursive text i.e: Each exponent's posterior against the value that generated the data says more than the table does:

It is pretty pointless showing the size of a turing model like that is something of interest.

I think it makes more sense to first show how to build up to the model we are going to fit, simulatiing from each stage with a plot as we go. then fit to sim data as we do now and check recovery. (I think we just have the one fit with recovery not the two). Then discuss with sim the other coupling options we currently have and how to write a custom one with sim. No this is a plain function etc etc etc werid lang

The page ran seven patterns forward, printed their shapes and named-tuple
readouts, and only fitted anything in its last third, twice. It also
re-explained partial pooling and the Split weight matrix, both of which
have their own pages.

Rebuild it as one model gained a layer at a time, simulated and plotted
after each layer, then fitted once. The layers share a seed, so the
mixing-matrix figure is coupled over uncoupled incidence with the Rt
draws held fixed, and the coupling is the only difference in it.

Every shape and readout is replaced by a figure. The gravity section
shows the matrix the exponents imply at three distance exponents rather
than fitting a second model, and a new section writes a coupling as one
renewal_pressure method and simulates from it.

Partial pooling and the weight matrix now link to their own tutorials.
@seabbs-bot

Copy link
Copy Markdown
Collaborator Author

Rewritten to the structure you asked for, in c65a209

Your steer was to build up to the model being fitted, simulating with a plot at
each stage, then fit once and check recovery, then cover the other couplings and
how to write one. The page now does that, and is shorter than before despite
gaining figures.

Structure

  1. Independent patches — Replicate, simulate, plot the three Rₜ paths.
  2. A shared process — Stratify + Hierarchy, plot the paths moving
    together.
  3. Coupling the patches — add mixing = K, and plot coupled over uncoupled
    incidence per patch.
  4. Observing the patches — add Split(NegativeBinomialError(...)), plot the
    simulated counts against their expectation.
  5. Fitting it — one fit, of the model built in stages 1-4, on the data
    simulated in stage 4, with the recovery plot.
  6. Other couplings — Gravity and ImportedCases, simulated and plotted.
  7. Writing a coupling — a renewal_pressure method, simulated and plotted.

Every stage is seeded identically, so the Rₜ draws and the seeding are the same
across stages and the coupling figure isolates the coupling. K is deliberately
one-directional (patch 1 feeds patch 3 hard and patch 2 lightly, nothing feeds
back), so that figure has something to show rather than three lines rising
together.

On your specific points

The named-tuple readouts and the model sizes are gone. Every
size(as_turing_model(...)().I_t), the (Rt_range = ..., y_range = ...) and
(rmse = ..., coverage80 = ...) tuples and the recovery table are removed.
Every block now ends in a figure or in nothing # hide.

The second fit is gone. The gravity section used to draw a truth from the
prior and fit it, a second NUTS run whose finding was mostly "three patches are
not enough data". That is one sentence now. The section shows the shape of the
coupling instead — the matrix gravity implies at three distance exponents, as a
heatmap — which makes the point without a sampler.

Writing a custom coupling is now in the page, with a simulation. A Ring
type and one renewal_pressure method, passed to mixing exactly where the
matrix and the Gravity model went, then simulated against the uncoupled run.

Deduplication. You were right that this overlapped two other pages.

  • Partial pooling is hierarchy-stacked.md's subject. This page uses Stratify
    • Hierarchy and links there instead of re-deriving pooling.
  • "Many-to-one observation: age bands into one stream" restated
    split-observations.md's weight-matrix section, which already covers
    one-to-one, many-to-one and many-to-many with the same W. Cut, with a link
    in its place.

The prose. "Says more than the table does" and that whole register is gone,
as is "this is a plain function". The extension point is now stated as the thing
to do — add a method to renewal_pressure — and then done.

375 lines to 338, with three more figures and one fewer fit.

What I ran

The 15 @example blocks of the committed page, in order, in one module in the
docs environment, mirroring Documenter's semantics, with every returned figure
rendered to PNG so the plotting is exercised rather than only constructed. All
15 pass. The only warning is NUTS reporting 2 divergent transitions out of 300
draws, which the page had before.

I did not run the full Documenter build. Total runtime for the page is about
5 minutes, of which the fit is 4.

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

@seabbs seabbs left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

@seabbs
seabbs enabled auto-merge (squash) August 21, 2026 15:18
@seabbs
seabbs disabled auto-merge August 21, 2026 15:58
@seabbs
seabbs merged commit 076865b into main Aug 21, 2026
18 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants