Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
82 changes: 82 additions & 0 deletions docs/src/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,88 @@ negbin_model = IDModel(
nothing # hide
```

## [An effect confined to a window](@id windowed-effect)

[`broadcast_window`](@ref) builds a latent model that equals its inner model on a declared index window and zero everywhere else.
Summing it onto a base path with [`CombineLatentModels`](@ref) gives an effect that is active only over that window.

```@example design
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)], ["", "Window"]
)
keys(rand(as_turing_model(windowed, 40)))
```

The inner slot is a PATH slot, so one helper covers a known effect and an estimated one.
A [`FixedIntercept`](@ref) gives a constant.
A bare `Distribution` gives one estimated level held across the window.
A process gives an effect that varies within the window, and it is generated over the window rather than over the whole series.

```@example design
known = broadcast_window(FixedIntercept(2.0), 20:30)
varying = broadcast_window(RandomWalk(), 20:30)
nothing # hide
```

Windows stack by adding members, and each keeps its own prefix.

```@example design
stacked = CombineLatentModels(
[
base,
broadcast_window(Normal(1.5, 0.1), 1:5),
broadcast_window(Normal(2, 0.1), 20:30),
], ["", "Early", "Late"]
)
keys(rand(as_turing_model(stacked, 40)))
```

A window touching either end of the series is an ordinary case.
The window is part of the broadcast rule, so it shows in the model tree.

```@example design
broadcast_window(Normal(1, 0.2), 1:10)
```

A latent process and a parameter prior share one role, so a windowed effect drops into a per-step parameter slot.
Here an [`AR`](@ref) is more strongly damped over the window and constant outside it.

```@example design
shifted = AR(
damp = CombineLatentModels(
[FixedIntercept(0.4), broadcast_window(Normal(0.4, 0.01), 20:30)],
["", "Shift"]
), ϵ_t = IID(Normal(0, 0.1))
)
keys(rand(as_turing_model(shifted, 40)))
```

### How it is built

[`broadcast_window`](@ref) is a [`BroadcastLatentModel`](@ref) under an [`InWindow`](@ref) rule, in the same way that [`broadcast_dayofweek`](@ref) is one under [`RepeatEach`](@ref).
The rule asks for a series as long as the window and places it, so nothing is drawn for the indices outside.

Without the helper the same effect is a transform that reads the index, summed on by [`CombineLatentModels`](@ref).
This generates the effect over the whole series and then masks it, so it is the longer route for a process, but it shows what the helper is doing.

```@example design
manual = CombineLatentModels(
[
base,
TransformLatentModel(
Intercept(Normal(1, 0.2)),
x -> x .* in.(eachindex(x), Ref(20:30))
),
], ["", "Window"]
)
keys(rand(as_turing_model(manual, 40)))
```

[`CombineLatentModels`](@ref) sums, so a multiplicative window effect on a positive path is the same composition in log space, wrapped in an `exp` transform.

## Composing accumulation steps

The recurrences that drive the time series — a random walk, an autoregression, a
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
133 changes: 133 additions & 0 deletions test/unit/latent_models/windowed.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
@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
Loading