Skip to content

Commit d5d7758

Browse files
committed
reconcile(observations): fold #266 into main's newer observation handling
Keep main's #272/#302 observation-error and forecast files (which superseded the branch's older right-alignment), keep the branch's new feature file requirements.jl, and consolidate the observation tests. Also fixes two pre-existing main defects exposed by the rebase's test run: - observations.jl had a missing 'end' between two @testItems, so the second never ran as its own testitem (main's own CI was failing on this). - the stale #272 NamedTuple test asserted gaps were sampled as latents; they are marginalised out, matching the implementation and the newer gap tests.
1 parent e4ceef4 commit d5d7758

10 files changed

Lines changed: 576 additions & 676 deletions

File tree

‎src/compose.jl‎

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -72,19 +72,30 @@ even once every entry is concrete. Conditioning on that makes DynamicPPL
7272
`deepcopy` the argument on every evaluation, which Enzyme cannot differentiate
7373
in reverse mode. Narrowing avoids both the copy and the failure.
7474
75-
A genuinely partially-missing vector (some entries observed, some `missing`)
76-
is split into a [`MissingObservations`](@ref) carrier instead: a concrete
77-
value vector plus a presence mask, neither of which admits `Missing` in its
78-
type. A fully missing vector, a partially- or fully-missing matrix (the
79-
strata data a data-driven [`Split`](@ref) reads shape from), and a scalar
80-
`missing`, are returned unchanged, and so is an array whose element type is
81-
already concrete. A `NamedTuple` of streams is narrowed field-wise, so each
75+
A vector with any `missing` in it is split into a [`MissingObservations`](@ref)
76+
carrier instead: a concrete value vector plus a presence mask, neither of which
77+
admits `Missing` in its type. This is also what detaches the data from the
78+
caller: the carrier is scored by reading it, so a blank's draw can never be
79+
written back into the array that was handed over. Data reached through a
80+
`NamedTuple` field or a struct field is not a model argument, so this is the
81+
only thing standing between it and the `y_t[i] ~ …` sugar's `setindex!!`.
82+
83+
A partially- or fully-missing matrix (the strata data a data-driven
84+
[`Split`](@ref) reads shape from) and a scalar `missing` are returned
85+
unchanged, and so is an array whose element type is already concrete. A
86+
`Vector{Missing}` is returned unchanged too: it carries no value type to build
87+
a carrier from, and nothing can be written into it either (the sugar widens it
88+
into a fresh array). A `NamedTuple` of streams is narrowed field-wise, so each
8289
per-stream submodel receives a concrete vector (or a `MissingObservations`
8390
carrier).
8491
8592
[`as_turing_model(::IDModel, y_t, n)`](@ref as_turing_model) applies this to
86-
its `y_t` automatically. It is exposed for data built elsewhere by simulating
87-
from a prior.
93+
its `y_t` automatically, and so does every observation model that reads its
94+
series out of a `NamedTuple` or a struct. It is exposed for data built
95+
elsewhere by simulating from a prior.
96+
97+
A gap in a fitted series is marginalised out, as described under
98+
[`MissingObservations`](@ref).
8899
89100
# Arguments
90101
@@ -98,8 +109,13 @@ end
98109
function concrete_observations(y::AbstractVector)
99110
eltype(y) >: Missing || return y
100111
any(ismissing, y) || return identity.(y)
101-
all(ismissing, y) && return y
102112
T = nonmissingtype(eltype(y))
113+
# A `Vector{Missing}` (`T === Union{}`) has no value type to put in the
114+
# carrier, and nothing can be written into it either, so leave it. Any
115+
# other element type without a `zero` is copied instead: the copy is what
116+
# gets written into, so the caller's array is still out of reach.
117+
T === Union{} && return y
118+
(isconcretetype(T) && T <: Number) || return copy(y)
103119
present = .!ismissing.(y)
104120
value = identity.(coalesce.(y, zero(T)))
105121
return MissingObservations(value, present)

‎src/observation_models/ObservationErrorModels/BinomialError.jl‎

Lines changed: 37 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,15 @@ where `N` is a scalar `Integer` (the same trials at every time point) or an
3434
`y = missing` while still supplying `N`, e.g.
3535
`y_t = (y = missing, N = fill(20, n))`.
3636
37+
A per-time-point `N` is right-aligned against the expected series in the same
38+
way the observed successes are, so it can be given with one entry per
39+
observation or one per expected value. Both put the same trials on the same
40+
time points; only the unused head differs. `N` must be long enough to cover
41+
every scored time point (the overlap of the two series). This matters for a
42+
[`Split`](@ref) branch whose lead-in is shorter than its neighbours': it gets
43+
more expected values than the caller has observations, and its `N` does not
44+
have to be padded to match.
45+
3746
This follows the same `NamedTuple`-data pattern as a [`Split`](@ref) stream: the
3847
shared [`define_y_t`](@ref) hook unpacks the `y` field that every error model
3948
scores, and `BinomialError` additionally reads the `N` field it needs.
@@ -54,35 +63,55 @@ struct BinomialError <: AbstractObservationErrorModel end
5463
define_y_t(::BinomialError, y_t, Y_t) = define_y_t(PoissonError(), y_t, Y_t)
5564

5665
# Resolve the number of trials carried in the data to a per-time-point vector.
66+
# A scalar is broadcast across the expected series; a vector is taken as given
67+
# and aligned by `_trial_dist`.
5768
_binomial_trials(N::Integer, n) = fill(N, n)
58-
function _binomial_trials(N::AbstractVector{<:Integer}, n)
59-
@assert length(N) == n "The number-of-trials vector `N` (length $(length(N))) must match the expected-observation series length ($n)"
60-
return N
69+
_binomial_trials(N::AbstractVector{<:Integer}, n) = N
70+
71+
# Build the per-time-point trials distribution, right-aligning the trials
72+
# against the expected series exactly as the observations are aligned. `n_diff`
73+
# shifts the trials so their last entry pairs with the last expected step, which
74+
# makes the two natural shapes — one entry per observation, or one per expected
75+
# value — put the same trials on the same time points, and leaves the head of
76+
# whichever runs longer unused. Trials that do not reach back to the first
77+
# scored step are rejected rather than quietly shifted.
78+
function _trial_dist(obs_model, p_t, N, diff_t)
79+
n = length(p_t)
80+
N_t = _binomial_trials(N, n)
81+
first_step = first(_scored_steps(diff_t, p_t))
82+
n_diff = length(N_t) - n
83+
@assert first_step + n_diff >= 1 "The number of trials `N` (length $(length(N_t))) must cover every scored time point: $(n - first_step + 1) are needed to score $(n + diff_t) observations against $n expected values"
84+
return _TrialDist(obs_model, p_t, N_t, n_diff)
6185
end
6286

6387
@model function as_turing_model(obs_model::BinomialError, y_t, Y_t)
6488
@assert y_t isa NamedTuple&&haskey(y_t, :N) "BinomialError needs `y_t` to be a NamedTuple carrying the number of trials, e.g. `(y = successes, N = trials)` (use `y = missing` to simulate)"
6589

66-
# Read the number of trials from the data.
67-
N_t = _binomial_trials(y_t.N, length(Y_t))
90+
# Read the number of trials from the data before `y_t` is rebound to the
91+
# observed successes below.
92+
N = y_t.N
6893

6994
# `Y_t` is the success probability; clamp away from 0/1 to avoid a degenerate
7095
# likelihood, mirroring the count families' `Y_t .+ 1e-6` nudge.
7196
p_t = clamp.(Y_t, 1.0e-6, 1 - 1.0e-6)
72-
dist = _TrialDist(obs_model, p_t, N_t)
7397

74-
y = y_t.y
98+
# The successes always arrive in a `NamedTuple` field, so they are never a
99+
# model argument DynamicPPL copies: `_scored_series` detaches them from the
100+
# caller's data before anything is scored.
101+
y = _scored_series(obs_model, y_t, Y_t)
75102
if y isa MissingObservations
76103
diff_t = length(y.value) - length(Y_t)
104+
dist = _trial_dist(obs_model, p_t, N, diff_t)
77105
y_t, __varinfo__ = _score_missing_observations!!(
78106
__model__.context, __varinfo__, y, diff_t, Y_t, dist
79107
)
80108
else
81109
# Rebind `y_t` to the observed successes (the same name, so DynamicPPL
82110
# conditions on it when concrete).
83-
y_t = define_y_t(obs_model, y_t, Y_t)
111+
y_t = y
84112

85113
diff_t = length(y_t) - length(Y_t)
114+
dist = _trial_dist(obs_model, p_t, N, diff_t)
86115

87116
for i in _scored_steps(diff_t, Y_t)
88117
y_t[i + diff_t] ~ dist(i)

‎src/observation_models/ObservationErrorModels/methods.jl‎

Lines changed: 84 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,10 @@ and a longer `Y_t` has its head left unobserved (run-in the data does not
3434
cover). Expected values are nudged by a tiny constant to avoid degenerate error
3535
distributions.
3636
37+
A series with only *some* entries missing is fitted to the entries it has,
38+
the absent ones being marginalised out as described under
39+
[`MissingObservations`](@ref).
40+
3741
The error family supplies [`generate_observation_error_priors`](@ref) (sampled
3842
as a submodel) and [`observation_error`](@ref) (the per-time-point distribution).
3943
@@ -50,89 +54,99 @@ lets a [`Split`](@ref) thread one stream's expectation into another.
5054
# A concrete callable rather than a closure: a closure defined in a model
5155
# body captures boxed locals, costing a dynamic dispatch per scored entry.
5256
dist = _ErrorDist(obs_model, pad_Y_t, priors)
53-
y = y_t isa NamedTuple ? y_t.y : y_t
57+
y = _scored_series(obs_model, y_t, Y_t)
5458
if y isa MissingObservations
5559
diff_t = length(y.value) - length(Y_t)
5660
y_t, __varinfo__ = _score_missing_observations!!(
5761
__model__.context, __varinfo__, y, diff_t, Y_t, dist
5862
)
5963
else
60-
# Extract the count series scored by this model (plain vector, or
61-
# `missing`, replaced by a length-`Y_t` vector of `missing`).
62-
# Rebinding `y_t` keeps DynamicPPL treating the entries as conditioned
63-
# observations.
64-
y_t = define_y_t(obs_model, y_t, Y_t)
64+
# The count series scored by this model (plain vector, or `missing`,
65+
# replaced by a length-`Y_t` vector of `missing`). Rebinding `y_t`
66+
# keeps DynamicPPL treating the entries as conditioned observations.
67+
y_t = y
6568

6669
diff_t = length(y_t) - length(Y_t)
6770

68-
# Every entry in range is scored, including a `missing` one. Sampling
69-
# the blanks is what `forecast` relies on: it pads the series with
70-
# `missing` over the horizon and reads the drawn values back out of the
71-
# chain. Skipping them would drop the horizon from the output.
71+
# Every entry is scored, including a `missing` one, so the blanks are
72+
# drawn. That is how a predictive draw is taken from a fully missing
73+
# series, and how `forecast` fills a horizon appended to a matrix (a
74+
# matrix is never split into a carrier). A partially-missing vector
75+
# conditioned through `IDModel` arrives as a `MissingObservations`
76+
# carrier above instead, which decides per entry.
7277
for i in _scored_steps(diff_t, Y_t)
7378
y_t[i + diff_t] ~ dist(i)
7479
end
7580
end
7681
return (; y_t, expected = Y_t)
7782
end
7883

79-
# Score every entry of a `MissingObservations` carrier against a per-time-point
80-
# distribution, without ever building a `Union{Missing,T}` value.
84+
# Score the observed entries of a `MissingObservations` carrier against a
85+
# per-time-point distribution, without tilde-ing against a `Union{Missing,T}`
86+
# value.
87+
#
88+
# An absent entry is missing at random, so it drops out of the likelihood: it is
89+
# skipped, not sampled. Imputing one as a latent would be the wrong mechanism
90+
# rather than merely an expensive one — there is nothing to infer at a point
91+
# that contributes no likelihood term. Skipping is also what keeps a discrete
92+
# stream samplable (a sampled count would be a latent that HMC has to link, and
93+
# a count distribution has no bijector to link it with) and keeps the gradient
94+
# dimension of a continuous stream down to the parameters that carry
95+
# information. Predictive values at the gaps are generated after fitting, by
96+
# replaying the posterior through the model; `forecast` builds its horizon that
97+
# way.
98+
#
99+
# A skipped entry comes back as `missing`, so the series returned below is a
100+
# `Union{Missing,T}` array wherever the observations have gaps. Making it
101+
# concrete would be a change to the observation contract rather than to this
102+
# loop.
81103
#
82104
# `y_t[i] ~ dist` decides sample-vs-observe by checking `y_t[i] === missing` at
83-
# run time, which needs a value that can actually hold `missing` at that lens.
84-
# Building one freshly inside a model body — the only safe way to do it, since
85-
# reusing the model's stored argument across evaluations would let one draw's
86-
# sample leak into the next — is exactly the array Enzyme's reverse-mode type
87-
# analysis cannot compile. Driving `DynamicPPL.tilde_observe!!` and
88-
# `DynamicPPL.tilde_assume!!` directly off the carrier's own concrete `present`
89-
# mask needs no such value: every array touched on the AD-active path stays
90-
# plainly typed. `value` is copied so a fresh draw is taken on every evaluation
91-
# rather than mutating the model's stored argument in place.
105+
# run time, which needs a value that can actually hold `missing` at that lens,
106+
# and building one inside a model body is exactly the array Enzyme's
107+
# reverse-mode type analysis cannot compile. Driving
108+
# `DynamicPPL.tilde_observe!!` directly off the carrier's own concrete `present`
109+
# mask needs no such value: every array the likelihood touches stays plainly
110+
# typed, and the model's stored argument is never written to.
92111
#
93-
# Returns the scored series (a plain `Vector`, the observed entries as given
94-
# and the rest overwritten with their fresh draws) and the updated `VarInfo`.
112+
# Returns the scored series (the observed entries as given, the absent ones
113+
# `missing`) and the updated `VarInfo`.
95114
function (d::_ErrorDist)(i)
96115
return observation_error(
97-
d.obs_model, d.pad_Y_t[i], map(p -> _at(p, i), values(d.priors))...
116+
d.obs_model, d.pad_Y_t[i], map(p -> at(p, i), values(d.priors))...
98117
)
99118
end
100119

101-
(d::_TrialDist)(i) = observation_error(d.obs_model, d.p_t[i], d.N_t[i])
120+
function (d::_TrialDist)(i)
121+
return observation_error(d.obs_model, d.p_t[i], d.N_t[i + d.n_diff])
122+
end
102123

103124
function _score_missing_observations!!(
104125
context, varinfo, y::MissingObservations, diff_t, Y_t, dist
105126
)
106127
n = length(y.value)
107-
# A sampled draw's type follows the AD backend (e.g. a `ForwardDiff.Dual`,
108-
# not a `Float64`), which is not known until `tilde_assume!!` returns, so
109-
# `scored` is untyped until every entry is in. Narrowing it with the final
110-
# `identity.()` (the same idiom `concrete_observations` uses) keeps this
111-
# step off the model's stored arguments — it runs after every tilde call has
112-
# already accumulated its log-probability, so it is not part of what Enzyme
128+
# `scored` mixes the observed values with `missing` at the gaps, so it is
129+
# untyped until every entry is in. Narrowing it with the final `identity.()`
130+
# (the same idiom `concrete_observations` uses) keeps this step off the
131+
# model's stored arguments — it runs after every tilde call has already
132+
# accumulated its log-probability, so it is not part of what Enzyme
113133
# differentiates.
114134
scored = Vector{Any}(undef, n)
115-
# `template` is the top-level `y_t` array itself (what the `y_t[idx] ~ ...`
116-
# sugar would splice in): it tells `VarInfo` storage the real type/length to
117-
# allocate for `y_t`'s entries, instead of growing an untyped array on the
118-
# fly the way `NoTemplate()` would.
119135
for i in _scored_steps(diff_t, Y_t)
120136
idx = i + diff_t
137+
# A gap reaches no tilde at all, so it costs neither a `VarName` nor a
138+
# `VarInfo` entry.
139+
y.present[idx] || continue
121140
vn = DynamicPPL.VarName{:y_t}(DynamicPPL.Index((idx,), NamedTuple()))
122-
if y.present[idx]
123-
val = y.value[idx]
124-
_, varinfo = DynamicPPL.tilde_observe!!(
125-
context, dist(i), val, vn, y.value, varinfo
126-
)
127-
else
128-
val, varinfo = DynamicPPL.tilde_assume!!(
129-
context, dist(i), vn, y.value, varinfo
130-
)
131-
end
141+
val = y.value[idx]
142+
_, varinfo = DynamicPPL.tilde_observe!!(
143+
context, dist(i), val, vn, y.value, varinfo
144+
)
132145
scored[idx] = val
133146
end
134-
# Entries outside the scored window (reached when `Y_t` is shorter than
135-
# `y_t`, e.g. a delay convolution) are never scored; keep them as given.
147+
# Left unassigned above: every marginalised gap, and any entry outside the
148+
# scored window (reached when `Y_t` is shorter than `y_t`, e.g. a delay
149+
# convolution, and so never scored). Keep both as given.
136150
for idx in 1:n
137151
isassigned(scored, idx) && continue
138152
scored[idx] = y.present[idx] ? y.value[idx] : missing
@@ -186,6 +200,29 @@ end
186200
_restore_missing(y) = y
187201
_restore_missing(y::MissingObservations) = map((v, p) -> p ? v : missing, y.value, y.present)
188202

203+
# The series an error model scores, detached from the caller's data.
204+
#
205+
# A series reached through a `NamedTuple` field is not one of the model's
206+
# arguments, so DynamicPPL never handles it: it is neither copied nor promoted,
207+
# and the `y_t[i] ~ …` sugar writes a blank's draw straight into the caller's
208+
# array. From the next evaluation on that entry is no longer `missing`, so it
209+
# is scored as data — frozen at whatever the first draw produced, and never a
210+
# tracked latent. [`concrete_observations`](@ref) — the same narrowing an
211+
# `IDModel` applies to its own `y_t` — is what detaches it: a series with any
212+
# blank in it becomes a [`MissingObservations`](@ref) carrier, which
213+
# `_score_missing_observations!!` scores by reading only.
214+
#
215+
# A series passed as the model's own `y_t` argument needs none of this:
216+
# DynamicPPL has already copied it. Neither does one an `IDModel` narrowed at
217+
# construction, which arrives as a carrier or a concrete vector and is returned
218+
# by the first branch below without touching the data.
219+
_scored_series(obs_model, y_t, Y_t) = define_y_t(obs_model, y_t, Y_t)
220+
_scored_series(obs_model, y_t::MissingObservations, Y_t) = y_t
221+
function _scored_series(obs_model, y_t::NamedTuple, Y_t)
222+
y_t.y isa MissingObservations && return y_t.y
223+
return concrete_observations(define_y_t(obs_model, y_t, Y_t))
224+
end
225+
189226
@doc raw"
190227
Generate the priors required by an observation-error model. Returns a named
191228
tuple consumed by [`observation_error`](@ref). The default is an empty tuple.

‎src/observation_models/modifiers/LatentDelay.jl‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,14 @@ _delay_timevarying(::UncertainDelay{P, F, T, TV}) where {P, F, T, TV} = TV
326326
# it sizes it from the CONVOLVED series it actually reads. Sizing it here
327327
# instead would simulate a series as long as the input, with the lead-in at
328328
# its head coming back as `missing` rather than not coming back at all.
329+
#
330+
# An aggregation is the exception. Its reporting windows are fixed calendar
331+
# objects read off the length of `y_t`, and it right-aligns a shorter `Y_t`
332+
# against them, so it needs the series on the INPUT calendar rather than the
333+
# convolved one. Sizing it here is what supplies that calendar.
334+
if ismissing(y_t) && _needs_input_calendar(obs_model.model)
335+
y_t = Vector{Missing}(missing, length(Y_t))
336+
end
329337
spec = obs_model.delay
330338
n = length(Y_t)
331339

0 commit comments

Comments
 (0)