Skip to content

Commit 867656d

Browse files
seabbs-botseabbs
andauthored
fix: guard SafePoisson/_safe_int_floor against non-finite rates (#140) (#279)
Co-authored-by: Sam Abbott <contact@samabbott.co.uk>
1 parent 7a88005 commit 867656d

5 files changed

Lines changed: 108 additions & 3 deletions

File tree

‎src/utils/SafeInt.jl‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,28 @@ const SafeDiscreteUnivariateDistribution = Distributions.Distribution{
1717
Distributions.Univariate, SafeIntValued,
1818
}
1919

20+
@doc raw"
21+
Guard shared by every entry point that floors a `SafePoisson` /
22+
`SafeNegativeBinomial` parameter, quantile or summary statistic to an
23+
integer. Raises a clear `DomainError` naming the offending value for a
24+
non-finite input, instead of letting the eventual `floor`/`Int` conversion
25+
fail with an opaque `InexactError` deep in `Distributions.jl` or `Base`.
26+
"
27+
function _require_finite_for_int(x::Real, caller::AbstractString = "_safe_int_floor")
28+
isfinite(x) || throw(
29+
DomainError(
30+
x,
31+
"$caller: cannot floor a non-finite value to an integer. " *
32+
"This usually means an upstream rate or mean was Inf or NaN " *
33+
"(e.g. an explosive prior draw feeding a SafePoisson or " *
34+
"SafeNegativeBinomial rate)."
35+
)
36+
)
37+
return nothing
38+
end
39+
2040
function _safe_int_floor(x::Real)
41+
_require_finite_for_int(x)
2142
Tf = typeof(x)
2243
if (Tf(typemin(Int)) - one(Tf)) < x < (Tf(typemax(Int)) + one(Tf))
2344
return floor(Int, x)

‎src/utils/SafeNegativeBinomial.jl‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,13 +46,21 @@ Distributions.var(d::SafeNegativeBinomial) = _negbin(d) |> var
4646
Distributions.std(d::SafeNegativeBinomial) = _negbin(d) |> std
4747
Distributions.skewness(d::SafeNegativeBinomial) = _negbin(d) |> skewness
4848
Distributions.kurtosis(d::SafeNegativeBinomial) = _negbin(d) |> kurtosis
49-
Distributions.mode(d::SafeNegativeBinomial) = _negbin(d) |> mode
49+
function Distributions.mode(d::SafeNegativeBinomial)
50+
_require_finite_for_int(d.r, "mode(::SafeNegativeBinomial, ...)")
51+
_require_finite_for_int(d.p, "mode(::SafeNegativeBinomial, ...)")
52+
return _negbin(d) |> mode
53+
end
5054
Distributions.logpdf(d::SafeNegativeBinomial, k::Real) = logpdf(_negbin(d), k)
5155
Distributions.cdf(d::SafeNegativeBinomial, x::Real) = cdf(_negbin(d), x)
5256
Distributions.ccdf(d::SafeNegativeBinomial, x::Real) = ccdf(_negbin(d), x)
5357
Distributions.logcdf(d::SafeNegativeBinomial, x::Real) = logcdf(_negbin(d), x)
5458
Distributions.logccdf(d::SafeNegativeBinomial, x::Real) = logccdf(_negbin(d), x)
55-
Distributions.quantile(d::SafeNegativeBinomial, q::Real) = quantile(_negbin(d), q)
59+
function Distributions.quantile(d::SafeNegativeBinomial, q::Real)
60+
_require_finite_for_int(d.r, "quantile(::SafeNegativeBinomial, ...)")
61+
_require_finite_for_int(d.p, "quantile(::SafeNegativeBinomial, ...)")
62+
return quantile(_negbin(d), q)
63+
end
5664

5765
function Base.rand(rng::AbstractRNG, d::SafeNegativeBinomial)
5866
if isone(d.p)

‎src/utils/SafePoisson.jl‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,10 @@ Distributions.logpdf(d::SafePoisson, x::Real) = logpdf(_poisson(d), x)
3636
Distributions.pdf(d::SafePoisson, x::Integer) = pdf(_poisson(d), x)
3737
Distributions.cdf(d::SafePoisson, x::Integer) = cdf(_poisson(d), x)
3838
Distributions.ccdf(d::SafePoisson, x::Integer) = ccdf(_poisson(d), x)
39-
Distributions.quantile(d::SafePoisson, q::Real) = quantile(_poisson(d), q)
39+
function Distributions.quantile(d::SafePoisson, q::Real)
40+
_require_finite_for_int(d.λ, "quantile(::SafePoisson, ...)")
41+
return quantile(_poisson(d), q)
42+
end
4043

4144
Base.minimum(d::SafePoisson) = 0
4245
Base.maximum(d::SafePoisson) = Inf

‎test/unit/inference/inference.jl‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,30 @@ end
291291
@test all(x -> x isa Integer && x ≥ 0, vec(fc[@varname(y_t[T + 1])]))
292292
end
293293

294+
@testitem "forecast's factorisation probe fails clearly on an explosive prior" tags = [
295+
:sample,
296+
] begin
297+
using ComposableTuringIDModels, Distributions, Turing, Random
298+
Random.seed!(2024)
299+
# An un-damped `DiffLatentModel(RandomWalk())` on `log R_t` is
300+
# prior-explosive: incidence can reach `Inf` on some prior draws, and
301+
# `forecast`'s `_assert_factorised` probe samples the whole model,
302+
# observation included. A non-finite rate reaching `SafePoisson` must
303+
# raise a `DomainError` naming the value, not an `InexactError` from
304+
# deep inside the sampler.
305+
diffrt = DiffLatentModel(model = RandomWalk(), init = [Normal(0.0, 0.2)])
306+
ren = Renewal(
307+
generation_time = Gamma(6.5, 0.62); rt = diffrt,
308+
initialisation = Normal(log(1.0), 0.1)
309+
)
310+
model = IDModel(ren, PoissonError())
311+
y = fill(5, 20)
312+
chain = sample(
313+
as_turing_model(model, y, length(y)), Prior(), 12; progress = false
314+
)
315+
@test_throws DomainError forecast(model, y, chain, 6)
316+
end
317+
294318
@testitem "generated_observables leaves non-chain solutions missing" begin
295319
using ComposableTuringIDModels, Distributions, Random
296320
Random.seed!(76)

‎test/unit/utils/utils_extra.jl‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,3 +95,52 @@ end
9595
A = get_param_array(chn)
9696
@test size(A) == (3, 2)
9797
end
98+
99+
@testitem "_safe_int_floor rejects non-finite input with a clear DomainError" begin
100+
using ComposableTuringIDModels: _safe_int_floor
101+
# A non-finite value must raise a `DomainError` naming the offending value,
102+
# not an `InexactError` from the eventual `BigInt` conversion.
103+
for x in (Inf, -Inf, NaN)
104+
@test_throws DomainError _safe_int_floor(x)
105+
end
106+
# Finite values, including ones outside the `Int` range, are unaffected.
107+
@test _safe_int_floor(3.7) == 3
108+
@test _safe_int_floor(exp(48.0)) == floor(BigInt, exp(48.0))
109+
end
110+
111+
@testitem "SafePoisson and SafeNegativeBinomial reject non-finite rates" begin
112+
using ComposableTuringIDModels, Distributions, Random
113+
Random.seed!(140)
114+
# A non-finite `SafePoisson` rate must raise a `DomainError`.
115+
@test_throws DomainError rand(SafePoisson(Inf))
116+
@test_throws DomainError rand(SafePoisson(NaN))
117+
# `SafeNegativeBinomial` samples through an inner `SafePoisson` whose rate
118+
# is a Gamma mixing draw. Degenerate `r`/`p` make that draw non-finite, so
119+
# it reaches the same guard.
120+
@test_throws DomainError rand(SafeNegativeBinomial(Inf, 0.5))
121+
@test_throws DomainError rand(SafeNegativeBinomial(1.0, 0.0))
122+
end
123+
124+
@testitem "quantile and mode reject non-finite parameters, not just rand" begin
125+
using ComposableTuringIDModels, Distributions
126+
# `quantile` (both types) and `SafeNegativeBinomial`'s `mode` delegate to
127+
# the wrapped `Distributions.Poisson` / `NegativeBinomial`, which floor
128+
# internally without passing through `_safe_int_floor`. They must raise the
129+
# same `DomainError` naming the offending value on a non-finite parameter.
130+
for λ in (Inf, NaN)
131+
@test_throws DomainError quantile(SafePoisson(λ), 0.5)
132+
end
133+
for (r, p) in ((Inf, 0.5), (NaN, 0.5), (1.0, Inf), (1.0, NaN))
134+
@test_throws DomainError quantile(SafeNegativeBinomial(r, p), 0.5)
135+
@test_throws DomainError mode(SafeNegativeBinomial(r, p))
136+
end
137+
# The guard must be transparent for finite parameters: each guarded entry
138+
# point still delegates to the wrapped distribution and returns its value.
139+
for q in (0.1, 0.5, 0.9)
140+
@test quantile(SafePoisson(4.0), q) == quantile(Poisson(4.0), q)
141+
@test quantile(SafeNegativeBinomial(3.0, 0.4), q) ==
142+
quantile(NegativeBinomial(3.0, 0.4), q)
143+
end
144+
@test mode(SafeNegativeBinomial(3.0, 0.4)) ==
145+
mode(NegativeBinomial(3.0, 0.4))
146+
end

0 commit comments

Comments
 (0)