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
4 changes: 2 additions & 2 deletions docs/docs_config.jl
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ const TUTORIAL_STUBS = [
"reproduction-number.md" =>
"# [The reproduction number from a run](@id tutorial-reproduction-number)",
"latent-processes.md" =>
"# [Latent processes driving R_t](@id tutorial-latent-rt)",
"# [Latent processes driving the reproduction number](@id tutorial-latent-rt)",
"spatial-strata.md" =>
"# [Spatial models](@id tutorial-spatial-strata)",
"time-varying-delays.md" =>
Expand Down Expand Up @@ -252,7 +252,7 @@ const PACKAGE_TUTORIALS = [
"Forecasting" => "getting-started/tutorials/forecasting.md",
"Reproduction number from a run" =>
"getting-started/tutorials/reproduction-number.md",
"Latent processes driving R_t" =>
"Latent processes driving the reproduction number" =>
"getting-started/tutorials/latent-processes.md",
"Spatial models" =>
"getting-started/tutorials/spatial-strata.md",
Expand Down
2 changes: 1 addition & 1 deletion docs/pages.jl
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ pages = [
"Clinical outcomes" => "getting-started/tutorials/clinical-outcomes.md",
"Forecasting" => "getting-started/tutorials/forecasting.md",
"Reproduction number from a run" => "getting-started/tutorials/reproduction-number.md",
"Latent processes driving R_t" => "getting-started/tutorials/latent-processes.md",
"Latent processes driving the reproduction number" => "getting-started/tutorials/latent-processes.md",
"Spatial models" => "getting-started/tutorials/spatial-strata.md",
"Time-varying delays and kernels" => "getting-started/tutorials/time-varying-delays.md",
"Occupancy and capacity" => "getting-started/tutorials/occupancy.md",
Expand Down
4 changes: 2 additions & 2 deletions docs/src/domain-guides/infectious-disease-models.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ Each table maps model features to the code that builds them, with the tutorial t
| Control measure from ``t_0`` to ``t_1`` cutting transmission by ``c`` | ``R_t \big(1 - c\, \mathbb{1}[t_0 \le t \le t_1]\big)``, or any multiplier ``m_t`` as ``R_t m_t`` | the gain `R .* measure` | [Three towns](@ref overview-build) ramps the reduction in over six days |
| Imported cases ``\iota_t`` | ``v_t = R_t \sum_l g_l I_{t-l} + \iota_t`` | `add = ι`, or [`Transform(+, TimeVarying(ι))`](@ref ComposableRecurrences.Transform) after depletion | [Imported cases](@ref tutorial-imports) |
| Instantaneous or effective reproduction number from a run | the infections over the pressure, as the [call table](@ref explanation-calls) gives | `y ./ pressure(r, y; history)`, with [`pressure`](@ref ComposableRecurrences.pressure) | [The reproduction number from a run](@ref tutorial-reproduction-number) |
| Log reproduction number as a latent process | ``\log R_t = \phi \log R_{t-1} + \epsilon_t`` | `Recurrence([φ])(; history, add = ϵ)` | [Latent processes driving R_t](@ref tutorial-latent-rt) |
| Behavioural response to incidence | – | [`Transform`](@ref ComposableRecurrences.Transform), before `Depletion` | [Latent processes driving R_t](@ref tutorial-latent-rt) |
| Log reproduction number as a latent process | ``\log R_t = \phi \log R_{t-1} + \epsilon_t`` | `Recurrence([φ])(; history, add = ϵ)` | [Latent processes driving the reproduction number](@ref tutorial-latent-rt) |
| Behavioural response to incidence | – | [`Transform`](@ref ComposableRecurrences.Transform), before `Depletion` | [Latent processes driving the reproduction number](@ref tutorial-latent-rt) |

Random walks and autoregressions are [recurrences](@ref explanation-time-series), and moving averages are convolutions.

Expand Down
1 change: 1 addition & 0 deletions docs/src/extensions/enzyme.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ round.(gradient(loss, backend, fill(1.1, 4)); digits = 3)
|---|---|---|
| Julia 1.11: zero gradient for a scalar field, such as `b` in `Transform(+, b)`, of an operator built in code Julia cannot infer; warns once | Use Julia 1.12 or later, or build operators in type-stable code | |
| `TypeError: in new, expected Tuple{...}` when a modifier's type depends on a run-time branch | Choose the loss before differentiating: `flag ? (θ -> f(Depletion(N), θ)) : (θ -> f(Depletion(N, Floor()), θ))` | [#314](https://github.com/EpiAware/ComposableRecurrences.jl/issues/314) |
| Zero or short gradients, with no error, for change points joined with `vcat` or `[a; b]`, as in `TimeVarying([1 => h[1]; [t + 1 => h[t] for t in eachindex(h)]])`: Enzyme loses the derivative when it copies a vector whose entries mix integers and floats | Build the pairs in one broadcast, `TimeVarying(Pair.(starts, values))` | |
| `EnzymeRuntimeActivityError` when an operator holds a constant array defined outside the loss | Use runtime activity, as above, or build the array inside the loss | |
| `IllegalTypeAnalysisException` from `hcat`, `vcat` or `[a b]` on a view, as when a run's history is put in front of its output | Pass `include_history = true` to join the history in front, or use `cat(a, b; dims = 2)`, or `collect` the view | [#672](https://github.com/EpiAware/ComposableRecurrences.jl/issues/672), [#299](https://github.com/EpiAware/ComposableRecurrences.jl/issues/299) |
| Julia 1.11 with several threads: reverse mode without runtime activity crashes in the garbage collector when it differentiates a `NoAdjoint` operator | Use `set_runtime_activity(Enzyme.Reverse)`, or drop `NoAdjoint` so the operator takes its rule | [#872](https://github.com/EpiAware/ComposableRecurrences.jl/issues/872) |
Expand Down
2 changes: 1 addition & 1 deletion docs/src/getting-started/tutorials/latent-processes.jl
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# # [Latent processes driving R_t](@id tutorial-latent-rt)
# # [Latent processes driving the reproduction number](@id tutorial-latent-rt)
#
# ## Introduction
#
Expand Down
16 changes: 9 additions & 7 deletions src/kernels/lag_maps.jl
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,11 @@ w_{k,l}(\tau) = \frac{x_{k,l}(\tau)}{\max_\epsilon \sum_{j} x_{k,j}(\tau)},

where ``x_{k,l}(\tau)`` is the weight of the kernel `TimeVarying(x,
Primary())`, the sum runs over all of the kernel's lags, and a total that
is not finite or is at most `eps` is replaced by `eps`, so a cohort whose
weights are all zero keeps weights of zero.
is at most `eps` is replaced by `eps`, so a cohort whose weights are all
zero keeps weights of zero.
A total that is not finite is kept: a `NaN` total gives that cohort
weights of `NaN`, and an infinite one gives zero for its finite entries
and `NaN` for its infinite ones.
Every lag of each cohort enters its total, so for ``n`` cohorts and ``L``
lags a `TimeVarying(h)` argument needs the times up to ``n + L - 1`` in a
[`Convolution`](@ref) and ``n + L`` in a [`Recurrence`](@ref).
Expand Down Expand Up @@ -285,11 +288,10 @@ end

# == The maps along one cohort's lags ==

# A total that is not finite or is at most `eps` is replaced by `eps`, and
# then has no slope.
_safe_on(t) = isfinite(t) && t > eps(typeof(t))
_safe_total(t) = _safe_on(t) ? t : eps(typeof(t))
_safe_slope(t) = _safe_on(t) ? one(t) : zero(t)
# A total at most `eps` is replaced by `eps`, and then has no slope. The
# floor is a `max` of the total, with no branch on its value.
_safe_total(t) = max(t, eps(typeof(t)))
_safe_slope(t) = t > eps(typeof(t)) ? one(t) : zero(t)
Comment thread
seabbs-bot marked this conversation as resolved.
Resolved

# The weights `w` of lags `1:n` from the values `u` of the kernel inside.
function _lag_map!(w, ::Increments, u, n)
Expand Down
4 changes: 4 additions & 0 deletions src/kernels/weights.jl
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ where ``\eta_{k,j}(\tau)`` is the hazard at lag ``j``, any argument of a
first lag the hazard acts at and ``l_0`` is the kernel's first lag (0 in
a [`Convolution`](@ref), 1 in a [`Recurrence`](@ref)).
Lags before `from` have survival one.
The share of a cohort that has left by each lag, its cumulative
distribution, is `1 - Survival(hazard)`, and
`kernel_weights(TimeVarying(1 - Survival(hazard), Primary()), n)` returns
it as a table for `n` cohorts.
A hazard that changes with calendar time is `TimeVarying(h)`, read at the
time ``\tau + j`` each lag lands; one that changes with the lag is a vector
of lag weights.
Expand Down
28 changes: 28 additions & 0 deletions test/ad/scenarios.jl
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,34 @@ end
test_gradients("ReverseDiff (compiled)"; category = :rules)
end

# Recording at zero totals must replay at positive ones, so the floor under
# a `Normalised` kernel's total cannot branch on the total.
@testitem "A compiled tape recorded at a zero total replays at a positive one" tags = [:ad, :reversediff_compiled] begin
using ComposableRecurrences
using ForwardDiff: ForwardDiff
using ReverseDiff: ReverseDiff
CR = ComposableRecurrences
L, T = 4, 9
primary = CR.Primary()
# A table's increments, and a kernel computed entry by entry.
table(θ) = CR.Increments(TimeVarying(reshape(θ, L, T), primary))
walked(θ) = CR.Derived(*, θ[1:L], TimeVarying(θ[(L + 1):(2L + T)]))
kernel(x) = TimeVarying(CR.Normalised(x), primary)
losses = (
θ -> sum(sin, Convolution(kernel(table(θ)))(1:T)),
θ -> sum(sin, transpose(Convolution(kernel(table(θ))))(1:T)),
θ -> sum(sin, Convolution(kernel(walked(θ)))(1:T)),
θ -> sum(sin, CR.kernel_weights(kernel(table(θ)), T)),
)
θ = vec([0.1 * l + 0.02 * sin(t + l) for l in 1:L, t in 1:T])
@testset "loss $i" for (i, loss) in enumerate(losses)
tape = ReverseDiff.compile(ReverseDiff.GradientTape(loss, zero(θ)))
g = ReverseDiff.gradient!(similar(θ), tape, θ)
ref = ForwardDiff.gradient(loss, θ)
@test all(isapprox.(g, ref; rtol = 1.0e-8, atol = 1.0e-12))
end
end

@testitem "Enzyme forward gradients" tags = [:ad, :enzyme, :enzyme_forward] setup = [ADHelpers, GradientChecks] begin
test_gradients("Enzyme forward"; category = :rules)
end
Expand Down
11 changes: 11 additions & 0 deletions test/unit/weights.jl
Original file line number Diff line number Diff line change
Expand Up @@ -513,6 +513,17 @@ end
end
# A total of zero keeps zero weights.
@test iszero(kw(CR.Normalised(Derived(*, 0.0, p))))
# A total that is not finite is not floored. A `NaN` total gives its
# cohort `NaN` weights, an infinite one zero for its finite entries and
# `NaN` for the infinite one, and the other cohorts keep theirs.
F = [0.1 * l + 0.01 * t for l in 1:4, t in 1:3]
F[2, 1] = NaN
F[3, 2] = Inf
K = CR.kernel_weights(computed(CR.Normalised(computed(F))), 3)
@test all(isnan, K[:, 1])
@test iszero(K[[1, 2, 4], 2])
@test isnan(K[3, 2])
@test K[:, 3] ≈ normalised(F[:, 3:3])
# Arithmetic lowers to Derived, and the maps show as their formula.
pmf = CR.Normalised(CR.Increments(cdf))
@test 2.0 * pmf isa Derived && pmf * CR.Survival(p) isa Derived
Expand Down
Loading