Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
9 changes: 0 additions & 9 deletions docs/src/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,6 @@ poisson_model = IDModel(
negbin_model = IDModel(
DirectInfections(; Z = latent, initialisation = Normal()),
NegativeBinomialError())
nothing # hide
```

## Composing accumulation steps
Expand All @@ -153,9 +152,7 @@ a step-composing helper — pass the modifier and it is composed onto the step:
```@example design
gen_int = [0.2, 0.3, 0.5]

# A renewal process with a fixed population of 1000 and susceptible depletion.
depleting = Renewal(gen_int, SusceptibleDepletion(1000.0); rt = RandomWalk())
nothing # hide
```

A scan step is a deterministic function, so a modifier that needs *sampled*
Expand All @@ -168,12 +165,8 @@ renewal model tests what a modifier is. [`ImportedCases`](@ref) is the worked
example, and modifiers apply in the order given:

```@example design
# Susceptible depletion, then importation added on top of the depleted
# incidence with its rate estimated. The importation prior is on the
# unconstrained scale, mapped onto a positive rate by the modifier.
seeded = Renewal(gen_int, SusceptibleDepletion(1000.0),
ImportedCases(Normal(0.0, 1.0)); rt = RandomWalk())
nothing # hide
```

The generation time is a slot like any other, so a modifier composes onto a
Expand All @@ -182,10 +175,8 @@ The discretisation keywords stay available alongside the modifiers, which keeps
one discretisation path rather than a second one written outside the package.

```@example design
# The same modifier on a Gamma generation time discretised to 15 days.
discretised = Renewal(Gamma(2, 1.5), SusceptibleDepletion(1000.0);
D_gen = 15.0, rt = RandomWalk())
nothing # hide
```

See [Renewal modifiers](@ref renewal-modifiers) for what each contributes to a fitted model.
Expand Down
5 changes: 3 additions & 2 deletions src/ComposableTuringIDModels.jl
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,9 @@ export SqExponentialKernel, Matern32Kernel, Matern52Kernel, spectral_density,
# --- latent modifiers / manipulators / combinations / broadcasting ---
export TransformLatentModel, PrefixLatentModel, RecordExpectedLatent,
CombineLatentModels, ConcatLatentModels, BroadcastLatentModel,
RepeatEach, RepeatBlock, broadcast_rule, broadcast_n, broadcast_dayofweek,
broadcast_weekly, equal_dimensions, arma, arima, Hierarchy,
RepeatEach, RepeatBlock, InWindow, broadcast_rule, broadcast_n,
broadcast_dayofweek, broadcast_weekly, broadcast_window, equal_dimensions,
arma, arima, Hierarchy,
Stratify, Replicate

# --- infection models ---
Expand Down
10 changes: 8 additions & 2 deletions src/base/prettyprinting.jl
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,12 @@ function _component_children(model::AbstractComposableModel)
return children
end

# The label a node shows in the tree. A component whose behaviour is set by a
# non-component field rather than by its own type overrides this, so the tree
# says which behaviour it is. Non-component fields are otherwise leaves the tree
# never reaches.
_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)
Expand All @@ -60,7 +66,7 @@ function _print_component_tree(io::IO, children, prefix::AbstractString)
is_last = i == n
print(
io, '\n', prefix, is_last ? "└─ " : "├─ ",
role, ": ", nameof(typeof(child))
role, ": ", _node_label(child)
)
child_prefix = string(prefix, is_last ? " " : "│ ")
_print_component_tree(io, _component_children(child), child_prefix)
Expand All @@ -71,7 +77,7 @@ end
# Rich (REPL / `display`) rendering: the concrete component name followed by the
# recursive, indented component tree.
function Base.show(io::IO, ::MIME"text/plain", model::AbstractComposableModel)
print(io, nameof(typeof(model)))
print(io, _node_label(model))
_print_component_tree(io, _component_children(model), "")
return nothing
end
Expand Down
12 changes: 12 additions & 0 deletions src/latent_models/manipulators/broadcast/LatentModel.jl
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,18 @@ function BroadcastLatentModel(
return BroadcastLatentModel(model, period, broadcast_rule)
end

# How a rule appears in a model tree. The default is the rule's name; a rule
# carrying a field that distinguishes it from another of the same type overrides
# this. Built here rather than from `show`, which module-qualifies the name
# outside the package's own scope.
_rule_label(rule::AbstractBroadcastRule) = string(nameof(typeof(rule)))

# What a `BroadcastLatentModel` does is set by its rule, not by its own type, so
# the tree label carries the rule. Without it a day-of-week effect and a
# windowed effect print identically.
_node_label(m::BroadcastLatentModel) =
string(nameof(typeof(m)), "(", _rule_label(m.broadcast_rule), ")")

@model function as_turing_model(model::BroadcastLatentModel, n::Int)
m = broadcast_n(model.broadcast_rule, n, model.period)
latent_period ~ as_turing_submodel(model.model, m)
Expand Down
32 changes: 32 additions & 0 deletions src/latent_models/manipulators/broadcast/helpers.jl
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,35 @@ broadcast_weekly(RandomWalk())
function broadcast_weekly(model::AbstractLatentModel)
return BroadcastLatentModel(model, 7, RepeatBlock())
end

@doc raw"
Build a [`BroadcastLatentModel`](@ref) for an effect confined to an index window.

The result is a latent model that equals `model` on `window` and zero everywhere else, so summing it onto a base path with [`CombineLatentModels`](@ref) gives an effect that is active only over the window.

The `model` slot is a PATH slot, which is what lets one helper serve both a fixed and an estimated effect.

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 This paragraph repeats content already stated in three places: BroadcastLatentModel's own docstring (LatentModel.jl:67-70) covers the PATH-slot/auto-wrap behaviour, InWindow's docstring (rules.jl:44-58) covers the window semantics, and design.md's new 'How it is built' section restates both again. Trim broadcast_window's docstring to what is specific to the helper (that it composes BroadcastLatentModel with InWindow) and link to BroadcastLatentModel/InWindow for the shared behaviour, rather than re-explaining it a third time.

A bare `Distribution` is wrapped in an [`Intercept`](@ref), giving one estimated level held across the window.
A [`FixedIntercept`](@ref) gives a known constant.
A process gives an effect that varies within the window, generated over `length(window)` steps rather than over the whole series.

Windows touching either end of the series are ordinary cases here.

# Arguments

- `model`: the latent model generating the effect inside the window.
- `window`: the index window the effect applies on.

# Examples
```@example broadcast_window
using ComposableTuringIDModels, Distributions
base = RandomWalk(; init = Normal(0, 0.1), ϵ_t = IID(Normal(0, 0.05)))
windowed = CombineLatentModels([base, broadcast_window(Normal(1, 0.2), 20:30)])
rand(as_turing_model(windowed, 40))
```
"
function broadcast_window(model, window::AbstractUnitRange{<:Integer})
# `period` is meaningless for `InWindow`, which reads its length from the
# window, so it is fixed at the smallest value `BroadcastLatentModel`
# accepts rather than exposed as an argument.
return BroadcastLatentModel(model, 1, InWindow(window))
end
43 changes: 43 additions & 0 deletions src/latent_models/manipulators/broadcast/rules.jl
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,46 @@ function broadcast_rule(::RepeatBlock, latent, n, period)
broadcast_latent = [latent[j] for j in 1:length(latent) for _ in 1:period]
return broadcast_latent[1:n]
end

@doc raw"
Broadcast rule that places the latent process on a declared index window and
returns zero at every index outside it.

The inner process is generated over `length(window)` steps, so it costs nothing
outside the window and its own dynamics run only across it.

# Examples
```@example InWindow
using ComposableTuringIDModels
broadcast_rule(InWindow(2:3), [1.0, 2.0], 5, 1)
```

## Fields

- `window`: the index window the process is placed on.
"
struct InWindow{R <: AbstractUnitRange{<:Integer}} <: AbstractBroadcastRule
"The index window the process is placed on."
window::R

function InWindow(window::AbstractUnitRange{<:Integer})
@assert !isempty(window) "window must contain at least one index"
@assert first(window) >= 1 "window must start at index 1 or later"
return new{typeof(window)}(window)
end
end

# The window is what distinguishes one `InWindow` from another, so it belongs in
# the label.
_rule_label(rule::InWindow) = string(nameof(typeof(rule)), "(", rule.window, ")")

broadcast_n(rule::InWindow, n, period) = length(rule.window)

function broadcast_rule(rule::InWindow, latent, n, period)
w = rule.window
@assert last(w) <= n "window $w must lie within 1:$n"
@assert length(latent) == length(w) "length(latent) must equal length(window)"
offset = first(w) - 1
z = zero(eltype(latent))
return [i in w ? latent[i - offset] : z for i in 1:n]
end
155 changes: 155 additions & 0 deletions test/unit/latent_models/windowed.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
@testitem "InWindow places a series on its window and zeroes the rest" begin
using ComposableTuringIDModels
@test broadcast_n(InWindow(20:30), 40, 1) == 11
@test broadcast_rule(InWindow(2:3), [1.0, 2.0], 5, 1) == [0.0, 1.0, 2.0, 0.0, 0.0]
# A window touching either end needs no special case.
@test broadcast_rule(InWindow(1:2), [1.0, 2.0], 4, 1) == [1.0, 2.0, 0.0, 0.0]
@test broadcast_rule(InWindow(3:4), [1.0, 2.0], 4, 1) == [0.0, 0.0, 1.0, 2.0]
# The whole series is a window too.
@test broadcast_rule(InWindow(1:3), [1.0, 2.0, 3.0], 3, 1) == [1.0, 2.0, 3.0]
@test_throws AssertionError InWindow(3:2)
@test_throws AssertionError InWindow(0:2)
@test_throws AssertionError broadcast_rule(InWindow(3:4), [1.0, 2.0], 3, 1)
end

@testitem "broadcast_window confines an effect to its window" begin
using ComposableTuringIDModels, Distributions, Random
base = RandomWalk(; init = Normal(0, 0.1), ϵ_t = IID(Normal(0, 0.05)))
win = 20:30
outside = setdiff(1:40, win)

# A known effect size lands exactly on the window.
fixed = CombineLatentModels(
[base, broadcast_window(FixedIntercept(2.0), win)], ["", "Window"]
)
Random.seed!(101)
plain = as_turing_model(base, 40)()
Random.seed!(101)
shifted = as_turing_model(fixed, 40)()
@test shifted .- plain ≈ 2.0 .* in.(1:40, Ref(win))

# An estimated effect size contributes exactly zero outside the window.
est = CombineLatentModels(
[base, broadcast_window(Normal(1, 0.2), win)], ["", "Window"]
)
Random.seed!(102)
combined = as_turing_model(est, 40)()
Random.seed!(102)
inner_only = as_turing_model(base, 40)()
@test length(combined) == 40
@test combined[outside] ≈ inner_only[outside]
@test all(combined[win] .!= inner_only[win])
# The effect draws one parameter under the prefix it was given.
@test string.(keys(rand(as_turing_model(est, 40)))) ==
["init", "ϵ_t", "Window.intercept"]
end

@testitem "broadcast_window accepts a window touching either end" begin
using ComposableTuringIDModels, Distributions, Random
base = RandomWalk(; init = Normal(0, 0.1), ϵ_t = IID(Normal(0, 0.05)))
# This is where a segment-partitioning composition cannot go, because the
# segment on the untouched side has length zero.
for win in (1:10, 31:40, 1:40)
model = CombineLatentModels(
[base, broadcast_window(FixedIntercept(3.0), win)], ["", "Window"]
)
Random.seed!(103)
plain = as_turing_model(base, 40)()
Random.seed!(103)
shifted = as_turing_model(model, 40)()
@test shifted .- plain ≈ 3.0 .* in.(1:40, Ref(win))
end
end

@testitem "a windowed process is generated over the window only" begin
using ComposableTuringIDModels, Distributions, Random
# A process member varies within the window and draws its own parameters
# under the prefix, sized by the window rather than by the series.
inner = RandomWalk(; init = Normal(), ϵ_t = IID(Normal(0, 0.1)))
model = CombineLatentModels(
[FixedIntercept(0.0), broadcast_window(inner, 20:30)], ["", "Window"]
)
Random.seed!(104)
path = as_turing_model(model, 40)()
@test length(path) == 40
@test all(iszero, path[setdiff(1:40, 20:30)])
@test length(unique(path[20:30])) > 1
names = string.(keys(rand(as_turing_model(model, 40))))
@test "Window.init" in names
@test "Window.ϵ_t" in names
end

@testitem "broadcast_window shows its window in the model tree" begin
using ComposableTuringIDModels, Distributions
tree = sprint(
show, MIME"text/plain"(), broadcast_window(Normal(1, 0.2), 20:30)
)
@test occursin("BroadcastLatentModel(InWindow(20:30))", tree)
# The label carries the rule for every broadcast model, so two rules that
# behave differently no longer print the same.
weekly = sprint(show, MIME"text/plain"(), broadcast_weekly(RandomWalk()))
@test occursin("BroadcastLatentModel(RepeatBlock)", weekly)
end

@testitem "the from-scratch composition matches broadcast_window" begin
using ComposableTuringIDModels, Distributions, Random
# An index-reading transform summed on by `CombineLatentModels` is the
# route the helper replaces, and the docs still show it. For a constant
# effect the two give the same path.
base = RandomWalk(; init = Normal(0, 0.1), ϵ_t = IID(Normal(0, 0.05)))
win = 20:30
helper = CombineLatentModels(
[base, broadcast_window(FixedIntercept(2.0), win)], ["", "Window"]
)
manual = CombineLatentModels(
[
base,
TransformLatentModel(
FixedIntercept(2.0), x -> x .* in.(eachindex(x), Ref(win))
),
], ["", "Window"]
)
Random.seed!(105)
from_helper = as_turing_model(helper, 40)()
Random.seed!(105)
from_manual = as_turing_model(manual, 40)()
@test from_helper ≈ from_manual
# With an estimated effect the manual route draws its parameter under the
# same prefixed name, so a model can move to the helper without renaming.
est_manual = CombineLatentModels(
[
base,
TransformLatentModel(
Intercept(Normal(1, 0.2)),
x -> x .* in.(eachindex(x), Ref(win))
),
], ["", "Window"]
)
est_helper = CombineLatentModels(
[base, broadcast_window(Normal(1, 0.2), win)], ["", "Window"]
)
@test string.(keys(rand(as_turing_model(est_manual, 40)))) ==
string.(keys(rand(as_turing_model(est_helper, 40))))
end

@testitem "a windowed effect multiplies under an exp transform" begin
using ComposableTuringIDModels, Distributions, Random
# `CombineLatentModels` sums, so a multiplicative window is the same
# composition in log space. The documented form is asserted here rather
# than left as a claim on the page.
base = RandomWalk(; init = Normal(0, 0.1), ϵ_t = IID(Normal(0, 0.05)))
win = 20:30
multiplied = TransformLatentModel(
CombineLatentModels(
[base, broadcast_window(FixedIntercept(log(2)), win)], ["", "Window"]
), x -> exp.(x)
)
plain = TransformLatentModel(base, x -> exp.(x))
Random.seed!(106)
with_window = as_turing_model(multiplied, 40)()
Random.seed!(106)
without = as_turing_model(plain, 40)()
ratio = with_window ./ without
@test ratio[win] ≈ fill(2.0, length(win))
@test ratio[setdiff(1:40, win)] ≈ ones(40 - length(win))
end
Loading