From b19658850623eda7461f63f61093130567c32457 Mon Sep 17 00:00:00 2001 From: Sam Isaacson Date: Wed, 11 Nov 2026 08:37:40 -0500 Subject: [PATCH 1/5] Draw jump times in the numeric type of the time The SSA aggregators drew every waiting time with `randexp(rng)`, a Float64, so `t + randexp(rng) / rate` widened Float32 times (making CCNRM's Float32 time table fail) and gave BigFloat times only Float64 draws; VR_Direct mixed typed and untyped draws. A new `typed_randexp(rng, t)` draws in `typeof(one(t))`, the time's numeric type without units: floating-point types with `randexp(rng, T)`, other numbers (e.g. dual numbers) by converting a Float64 draw. All exponential draws in the aggregators and the VR aggregators use it. For Float64, `randexp(rng, Float64)` is `randexp(rng)`: seeded results are unchanged, and the compiled code of every JumpProcesses method reached from the aggregators is identical (up to stack-slot assignment in four spatial methods), as are timings within run-to-run noise. Co-Authored-By: Claude Opus 5.5 --- HISTORY.md | 8 ++++++++ src/aggregators/ccnrm.jl | 6 +++--- src/aggregators/coevolve.jl | 6 +++--- src/aggregators/direct.jl | 4 ++-- src/aggregators/directcr.jl | 2 +- src/aggregators/frm.jl | 6 +++--- src/aggregators/nrm.jl | 6 +++--- src/aggregators/rdirect.jl | 2 +- src/aggregators/rssa.jl | 4 ++-- src/aggregators/rssacr.jl | 4 ++-- src/aggregators/sortingdirect.jl | 2 +- src/aggregators/ssajump.jl | 8 ++++++++ src/spatial/directcrdirect.jl | 2 +- src/spatial/nsm.jl | 5 +++-- src/variable_rate.jl | 12 ++++++------ test/fp_unknowns.jl | 21 ++++++++++++++++++++- 16 files changed, 67 insertions(+), 31 deletions(-) diff --git a/HISTORY.md b/HISTORY.md index 88e1fe9de..8fbda76ab 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -1,5 +1,13 @@ # Breaking updates and feature summaries across releases +## Unreleased + - Jump times are now drawn in the numeric type of the time, without its units (the type + of `one(t)`), in every SSA aggregator and in `VR_FRM`, `VR_Direct` and `VR_DirectFW`. + `Float32` times are no longer computed in `Float64`, which also lets `CCNRM` solve + problems with `Float32` times (it failed with a `MethodError`), and `BigFloat` times + are drawn at `BigFloat` precision. `Float64` results are unchanged; seeded results can + change for `Float32` and `BigFloat` problems. + ## 10.2.0 - New `isolated_copy(jprob)` returns a `JumpProblem` with its own jump state, for concurrent solves and for integrators that are alive at the same time. It copies only diff --git a/src/aggregators/ccnrm.jl b/src/aggregators/ccnrm.jl index b902a017e..93e2f013a 100644 --- a/src/aggregators/ccnrm.jl +++ b/src/aggregators/ccnrm.jl @@ -125,7 +125,7 @@ function update_dependent_rates!(p::CCNRMJumpAggregation, dep_rxs, executed_jump end else if cur_rates[rx] > zero(eltype(cur_rates)) - update!(ptt, rx, oldtime, t + randexp(rng) / cur_rates[rx]) + update!(ptt, rx, oldtime, t + typed_randexp(rng, t) / cur_rates[rx]) else update!(ptt, rx, oldtime, floatmax(typeof(t))) end @@ -143,7 +143,7 @@ function initialize_rates_and_times!(p::CCNRMJumpAggregation, u, params, t, rng) maj_rates = p.maj_rates @inbounds for i in 1:get_num_majumps(majumps) cur_rates[i] = evalrxrate(u, i, majumps, maj_rates) - pttdata[i] = t + randexp(rng) / cur_rates[i] + pttdata[i] = t + typed_randexp(rng, t) / cur_rates[i] end # Initialize next-reaction times for the constant rates @@ -151,7 +151,7 @@ function initialize_rates_and_times!(p::CCNRMJumpAggregation, u, params, t, rng) idx = get_num_majumps(majumps) + 1 @inbounds for rate in rates cur_rates[idx] = rate(u, params, t) - pttdata[idx] = t + randexp(rng) / cur_rates[idx] + pttdata[idx] = t + typed_randexp(rng, t) / cur_rates[idx] idx += 1 end diff --git a/src/aggregators/coevolve.jl b/src/aggregators/coevolve.jl index c01a402a2..d7da15bf3 100644 --- a/src/aggregators/coevolve.jl +++ b/src/aggregators/coevolve.jl @@ -229,7 +229,7 @@ function accept_next_jump!(p::CoevolveJumpAggregation, integrator, u, params, t) # it was longer than the rateinterval when it was proposed if lrate == typemax(t) urate = get_urate(p, uidx, u, params, t) - s = urate == zero(t) ? typemax(t) : randexp(rng) / urate + s = urate == zero(t) ? typemax(t) : typed_randexp(rng, t) / urate elseif lrate < urate # when the lower and upper bound are the same, then v < 1 = lrate / urate = urate / urate v = rand(rng) * urate @@ -238,7 +238,7 @@ function accept_next_jump!(p::CoevolveJumpAggregation, integrator, u, params, t) rate = get_rate(p, lidx, u, params, t) if v > rate urate = get_urate(p, uidx, u, params, t) - s = urate == zero(t) ? typemax(t) : randexp(rng) / urate + s = urate == zero(t) ? typemax(t) : typed_randexp(rng, t) / urate end end end @@ -305,7 +305,7 @@ function next_time(p::CoevolveJumpAggregation, u, params, t, i, rng) return next_candidate_time!(p, u, params, t, s, lidx), urate end end - s = urate == zero(t) ? typemax(t) : randexp(rng) / urate + s = urate == zero(t) ? typemax(t) : typed_randexp(rng, t) / urate return next_candidate_time!(p, u, params, t, s, lidx), urate end diff --git a/src/aggregators/direct.jl b/src/aggregators/direct.jl index 3083d161e..9b77667bc 100644 --- a/src/aggregators/direct.jl +++ b/src/aggregators/direct.jl @@ -105,7 +105,7 @@ function time_to_next_jump(p::DirectJumpAggregation{T, S, F1}, u, params, end @inbounds sum_rate = cur_rates[end] - sum_rate, randexp(rng) / sum_rate + sum_rate, typed_randexp(rng, t) / sum_rate end # Unrolled at compile time: recursive splatting over `rates...` is only inferred for @@ -147,5 +147,5 @@ function time_to_next_jump(p::DirectJumpAggregation{T, S, F1}, u, params, end @inbounds sum_rate = cur_rates[end] - sum_rate, randexp(rng) / sum_rate + sum_rate, typed_randexp(rng, t) / sum_rate end diff --git a/src/aggregators/directcr.jl b/src/aggregators/directcr.jl index dd56cae4a..584427083 100644 --- a/src/aggregators/directcr.jl +++ b/src/aggregators/directcr.jl @@ -118,7 +118,7 @@ end nomorejumps!(p, p.sum_rate) && return nothing rng = get_rng(integrator) - p.next_jump_time = t + randexp(rng) / p.sum_rate + p.next_jump_time = t + typed_randexp(rng, t) / p.sum_rate if p.next_jump_time < p.end_time p.next_jump = sample(p.rt, p.cur_rates, rng) diff --git a/src/aggregators/frm.jl b/src/aggregators/frm.jl index 79ec8fd55..50dc39c06 100644 --- a/src/aggregators/frm.jl +++ b/src/aggregators/frm.jl @@ -94,7 +94,7 @@ function next_ma_jump(p::FRMJumpAggregation, u, params, t, rng) maj_rates = p.maj_rates @inbounds for i in 1:get_num_majumps(majumps) p.cur_rates[i] = evalrxrate(u, i, majumps, maj_rates) - dt = randexp(rng) / p.cur_rates[i] + dt = typed_randexp(rng, t) / p.cur_rates[i] if dt < ttnj ttnj = dt nextrx = i @@ -112,7 +112,7 @@ function next_constant_rate_jump(p::FRMJumpAggregation{T, S, F1, F2}, u, params, idx = get_num_majumps(p.ma_jumps) + 1 fill_cur_rates(u, params, t, p.cur_rates, idx, p.rates) @inbounds for i in idx:length(p.cur_rates) - dt = randexp(rng) / p.cur_rates[i] + dt = typed_randexp(rng, t) / p.cur_rates[i] if dt < ttnj ttnj = dt nextrx = i @@ -131,7 +131,7 @@ function next_constant_rate_jump(p::FRMJumpAggregation{T, S, F1}, u, params, idx = get_num_majumps(p.ma_jumps) + 1 @inbounds for i in 1:length(p.rates) p.cur_rates[idx] = p.rates[i](u, params, t) - dt = randexp(rng) / p.cur_rates[idx] + dt = typed_randexp(rng, t) / p.cur_rates[idx] if dt < ttnj ttnj = dt nextrx = idx diff --git a/src/aggregators/nrm.jl b/src/aggregators/nrm.jl index 4068dd447..e9f74332b 100644 --- a/src/aggregators/nrm.jl +++ b/src/aggregators/nrm.jl @@ -104,7 +104,7 @@ function update_dependent_rates!(p::NRMJumpAggregation, dep_rxs, executed_jump, end else if cur_rates[rx] > zero(eltype(cur_rates)) - update!(p.pq, rx, t + randexp(rng) / cur_rates[rx]) + update!(p.pq, rx, t + typed_randexp(rng, t) / cur_rates[rx]) else update!(p.pq, rx, typemax(t)) end @@ -123,7 +123,7 @@ function fill_rates_and_get_times!(p::NRMJumpAggregation, u, params, t, rng) maj_rates = p.maj_rates @inbounds for i in 1:get_num_majumps(majumps) cur_rates[i] = evalrxrate(u, i, majumps, maj_rates) - pqdata[i] = t + randexp(rng) / cur_rates[i] + pqdata[i] = t + typed_randexp(rng, t) / cur_rates[i] end # constant rates @@ -131,7 +131,7 @@ function fill_rates_and_get_times!(p::NRMJumpAggregation, u, params, t, rng) idx = get_num_majumps(majumps) + 1 @inbounds for rate in rates cur_rates[idx] = rate(u, params, t) - pqdata[idx] = t + randexp(rng) / cur_rates[idx] + pqdata[idx] = t + typed_randexp(rng, t) / cur_rates[idx] idx += 1 end diff --git a/src/aggregators/rdirect.jl b/src/aggregators/rdirect.jl index 2c211ffa7..2536f6bd8 100644 --- a/src/aggregators/rdirect.jl +++ b/src/aggregators/rdirect.jl @@ -111,7 +111,7 @@ function generate_jumps!(p::RDirectJumpAggregation, integrator, u, params, t) p.counter = counter p.next_jump = rx - p.next_jump_time = t + randexp(rng) / sum_rate + p.next_jump_time = t + typed_randexp(rng, t) / sum_rate nothing end diff --git a/src/aggregators/rssa.jl b/src/aggregators/rssa.jl index 97e4c8c3c..ec2adc697 100644 --- a/src/aggregators/rssa.jl +++ b/src/aggregators/rssa.jl @@ -114,7 +114,7 @@ function generate_jumps!(p::RSSAJumpAggregation, integrator, u, params, t) jidx = linear_search(cur_rate_high, r) # the search finds no jump only if the sum exceeds the sum of the rate bounds iszero(jidx) && ((sum_rate, jidx) = resum_and_search!(p, rng)) - rerl += randexp(rng) + rerl += typed_randexp(rng, t) nrejected = 0 @inbounds while rejectrx(ma_jumps, num_majumps, rates, cur_rate_high, cur_rate_low, rng, u, jidx, params, t, p.maj_rates) @@ -129,7 +129,7 @@ function generate_jumps!(p::RSSAJumpAggregation, integrator, u, params, t) r = rand(rng) * sum_rate jidx = linear_search(cur_rate_high, r) iszero(jidx) && ((sum_rate, jidx) = resum_and_search!(p, rng)) - rerl += randexp(rng) + rerl += typed_randexp(rng, t) end p.next_jump = jidx diff --git a/src/aggregators/rssacr.jl b/src/aggregators/rssacr.jl index d3f2c92e9..cc768c3eb 100644 --- a/src/aggregators/rssacr.jl +++ b/src/aggregators/rssacr.jl @@ -140,7 +140,7 @@ function generate_jumps!(p::RSSACRJumpAggregation, integrator, u, params, t) jidx = sample(rt, cur_rate_high, rng) # sampling finds no jump only if the sums exceed the sum of the rate bounds iszero(jidx) && ((sum_rate, jidx) = resum_and_sample!(p, rng)) - rerl += randexp(rng) + rerl += typed_randexp(rng, t) nrejected = 0 while rejectrx(ma_jumps, num_majumps, rates, cur_rate_high, cur_rate_low, rng, u, jidx, params, t, p.maj_rates) @@ -154,7 +154,7 @@ function generate_jumps!(p::RSSACRJumpAggregation, integrator, u, params, t) # sample candidate reaction jidx = sample(rt, cur_rate_high, rng) iszero(jidx) && ((sum_rate, jidx) = resum_and_sample!(p, rng)) - rerl += randexp(rng) + rerl += typed_randexp(rng, t) end p.next_jump = jidx diff --git a/src/aggregators/sortingdirect.jl b/src/aggregators/sortingdirect.jl index 143f89fd3..9ee8da3fc 100644 --- a/src/aggregators/sortingdirect.jl +++ b/src/aggregators/sortingdirect.jl @@ -97,7 +97,7 @@ function generate_jumps!(p::SortingDirectJumpAggregation, integrator, u, params, nomorejumps!(p, p.sum_rate) && return nothing rng = get_rng(integrator) - p.next_jump_time = t + randexp(rng) / p.sum_rate + p.next_jump_time = t + typed_randexp(rng, t) / p.sum_rate # search for next jump if p.next_jump_time < p.end_time diff --git a/src/aggregators/ssajump.jl b/src/aggregators/ssajump.jl index 0ffd1dcff..3a40d38ce 100644 --- a/src/aggregators/ssajump.jl +++ b/src/aggregators/ssajump.jl @@ -24,6 +24,14 @@ function DiscreteCallback(c::AbstractSSAJumpAggregator) DiscreteCallback(c, c, initialize = c, save_positions = c.save_positions) end +# An exponential random variate in the numeric type of the time `t` without its units +# (`one(t)`), so that `t + typed_randexp(rng, t) / rate` keeps the type of `t`. Floating +# point types are drawn in that type; other numbers, such as dual numbers, convert a `Float64` +# draw. +@inline typed_randexp(rng, t) = _typed_randexp(rng, typeof(one(t))) +@inline _typed_randexp(rng, ::Type{T}) where {T <: AbstractFloat} = randexp(rng, T) +@inline _typed_randexp(rng, ::Type{T}) where {T} = convert(T, randexp(rng)) + ########### The following routines are templates for all SSAs ########### ########### Generally they should not need to be overloaded. ########### diff --git a/src/spatial/directcrdirect.jl b/src/spatial/directcrdirect.jl index f2528f170..35d82c1aa 100644 --- a/src/spatial/directcrdirect.jl +++ b/src/spatial/directcrdirect.jl @@ -91,7 +91,7 @@ end # calculate the next jump / jump time function generate_jumps!(p::DirectCRDirectJumpAggregation, integrator, params, u, t) rng = get_rng(integrator) - p.next_jump_time = t + randexp(rng) / p.rt.gsum + p.next_jump_time = t + typed_randexp(rng, t) / p.rt.gsum p.next_jump_time >= p.end_time && return nothing site = sample(p.rt, p.site_rates, rng) p.next_jump = sample_jump_direct(p, site, rng) diff --git a/src/spatial/nsm.jl b/src/spatial/nsm.jl index 97102620f..8a0eab3cf 100644 --- a/src/spatial/nsm.jl +++ b/src/spatial/nsm.jl @@ -117,7 +117,8 @@ function fill_rates_and_get_times!(aggregation::NSMJumpAggregation, integrator, @inbounds for site in 1:num_nodes update_rx_rates!(rx_rates, rxs, integrator, site) update_hop_rates!(hop_rates, species, u, site, spatial_system) - pqdata[site] = t + randexp(rng) / (total_site_rate(rx_rates, hop_rates, site)) + pqdata[site] = t + + typed_randexp(rng, t) / (total_site_rate(rx_rates, hop_rates, site)) end aggregation.pq = MutableBinaryMinHeap(pqdata) @@ -155,7 +156,7 @@ update the time of site in the priority queue function update_site_time!(p::NSMJumpAggregation, site, t, rng) site_rate = (total_site_rate(p.rx_rates, p.hop_rates, site)) if site_rate > zero(typeof(site_rate)) - update!(p.pq, site, t + randexp(rng) / site_rate) + update!(p.pq, site, t + typed_randexp(rng, t) / site_rate) else update!(p.pq, site, typemax(t)) end diff --git a/src/variable_rate.jl b/src/variable_rate.jl index 6d4e33df8..439b949c2 100644 --- a/src/variable_rate.jl +++ b/src/variable_rate.jl @@ -297,7 +297,7 @@ end function (c::VR_FRMEventCallback)(integrator) c.affect!(integrator) rng = get_rng(integrator) - integrator.u.jump_u[c.idx] = -randexp(rng, typeof(integrator.t)) + integrator.u.jump_u[c.idx] = -typed_randexp(rng, integrator.t) nothing end @@ -305,7 +305,7 @@ end function (c::VR_FRMEventCallback)(cb, u, t, integrator) check_vr_frm_state_length(integrator, cb.idxs - c.idx) rng = get_rng(integrator) - integrator.u.jump_u[c.idx] = -randexp(rng, typeof(integrator.t)) + integrator.u.jump_u[c.idx] = -typed_randexp(rng, integrator.t) derivative_discontinuity!(integrator, true) nothing end @@ -371,7 +371,7 @@ function (c::VR_FRMVectorCallback)(integrator, events) for (k, i) in enumerate(c.jump_idxs) iszero(events[k]) && continue vr_frm_affect!(c.affects, k, integrator) - integrator.u.jump_u[i] = -randexp(rng, typeof(integrator.t)) + integrator.u.jump_u[i] = -typed_randexp(rng, integrator.t) end nothing end @@ -384,7 +384,7 @@ function (c::VR_FRMVectorCallback)(cb, u, t, integrator) rng = get_rng(integrator) jump_u = integrator.u.jump_u for i in eachindex(jump_u) - jump_u[i] = -randexp(rng, typeof(integrator.t)) + jump_u[i] = -typed_randexp(rng, integrator.t) end derivative_discontinuity!(integrator, true) end @@ -619,7 +619,7 @@ function initialize_vr_direct_cache!(cache::VR_DirectEventCache, u, t, integrato rng = get_rng(integrator) cache.prev_time = t cache.current_time = t - cache.prev_threshold = randexp(rng, eltype(integrator.t)) + cache.prev_threshold = typed_randexp(rng, integrator.t) cache.current_threshold = cache.prev_threshold cache.total_rate = zero(integrator.t) cache.cum_rate_sum .= 0 @@ -916,7 +916,7 @@ function (cache::VR_DirectEventCache)(integrator) execute_affect!(cache, integrator, jump_idx) cache.prev_time = t - cache.current_threshold = randexp(rng) + cache.current_threshold = typed_randexp(rng, t) cache.prev_threshold = cache.current_threshold cache.current_time = t # the integral up to the jump is used up, and the next step starts at the jump diff --git a/test/fp_unknowns.jl b/test/fp_unknowns.jl index 0c26fc680..0d4b4c661 100644 --- a/test/fp_unknowns.jl +++ b/test/fp_unknowns.jl @@ -1,4 +1,4 @@ -using Test, JumpProcesses, SciMLBase, StableRNGs +using Test, JumpProcesses, SciMLBase, StableRNGs, ForwardDiff rng = StableRNG(12345) @@ -50,3 +50,22 @@ function test(rng) # @test abs(Ymeans[i] - Ymeans[1]) < (.1 * Ymeans[1]) # end end + +# Jump times are drawn in the numeric type of the time (issue #674) +@testset "Exponential draws in the time's type" begin + typed_randexp = JumpProcesses.typed_randexp + @test typed_randexp(StableRNG(1), 1.0) == JumpProcesses.randexp(StableRNG(1)) + @test typed_randexp(StableRNG(1), 1.0f0) == + Float32(JumpProcesses.randexp(StableRNG(1))) + for t in (1.0f0, 1.0, big(1.0)) + @test typed_randexp(rng, t) isa typeof(t) + end + @test typed_randexp(rng, ForwardDiff.Dual(1.0, 1.0)) isa ForwardDiff.Dual + + # CCNRM's time table holds times of the problem's type + maj = MassActionJump([10.0f0, 1.0f0], [Pair{Int, Int}[], [1 => 1]], [ + [1 => 1], [1 => -1]]) + dprob = DiscreteProblem([0], (0.0f0, 10.0f0)) + sol = solve(JumpProblem(dprob, CCNRM(), maj), SSAStepper(); rng) + @test eltype(sol.t) == Float32 +end From 88c3acaa50d7b66c7d93b5cd6185637c55952f22 Mon Sep 17 00:00:00 2001 From: Sam Isaacson Date: Wed, 11 Nov 2026 08:37:50 -0500 Subject: [PATCH 2/5] Build Float32 and BigFloat priority tables in DirectCR, RSSACR and DirectCRDirect Ported from #716 (issue #674). The composition-rejection aggregators computed their minimum rate as `2.0^minexponent`, a Float64, so building a problem with Float32 or BigFloat rates failed with a MethodError. The minimum rate is now in the rates' type. For Float32, the default minimum rate 2^-40 is also below eps(Float32), which `priortogid` maps to group 1, so the initial table (maxpriority = 2 * minrate) would get no groups and a zero maxpriority, and growing it to fit a rate would loop forever: `PriorityTable` now keeps at least the three base groups {0}, (0, minpriority) and [minpriority, 2 * minpriority). For Float64, 2 * minrate is above eps, so the table already had three groups; both changes run only when a JumpProblem is built, and seeded results and the compiled solve code are unchanged. #716's `convert`s in `update!(::PriorityTimeTable)` aren't needed, since times are now drawn in the time's type. Tests: Float32 priority tables (from #716); Float32 and BigFloat solves with every SSA aggregator (except RDirect for BigFloat), NSM and DirectCRDirect, checking the mean; and isolated_copy of unsolved BigFloat DirectCR and RSSACR problems. Co-Authored-By: ChrisRackauckas-Claude <224351616+ChrisRackauckas-Claude@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- HISTORY.md | 3 ++ src/aggregators/directcr.jl | 2 +- src/aggregators/prioritytable.jl | 4 +++ src/aggregators/rssacr.jl | 2 +- src/spatial/directcrdirect.jl | 2 +- test/fp_unknowns.jl | 39 ++++++++++++++++++++---- test/isolated_copy.jl | 6 ++-- test/table_test.jl | 52 ++++++++++++++++++++++++++++++++ 8 files changed, 98 insertions(+), 12 deletions(-) diff --git a/HISTORY.md b/HISTORY.md index 8fbda76ab..0646957aa 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -7,6 +7,9 @@ problems with `Float32` times (it failed with a `MethodError`), and `BigFloat` times are drawn at `BigFloat` precision. `Float64` results are unchanged; seeded results can change for `Float32` and `BigFloat` problems. + - `DirectCR`, `RSSACR` and the spatial `DirectCRDirect` can now build problems with + `Float32` or `BigFloat` rates and times (they failed with a `MethodError`). `RDirect` + still can't build problems with `BigFloat` rates. ## 10.2.0 - New `isolated_copy(jprob)` returns a `JumpProblem` with its own jump state, for diff --git a/src/aggregators/directcr.jl b/src/aggregators/directcr.jl index 584427083..25022e390 100644 --- a/src/aggregators/directcr.jl +++ b/src/aggregators/directcr.jl @@ -46,7 +46,7 @@ function DirectCRJumpAggregation(nj::Int, njt::T, et::T, crs::Vector{T}, sr::T, minexponent = exponent(minrate) # use the largest power of two that is <= the passed in minrate - minrate = 2.0^minexponent + minrate = T(2)^minexponent ratetogroup = rate -> priortogid(rate, minexponent) # construct an empty initial priority table -- we'll reset this in init diff --git a/src/aggregators/prioritytable.jl b/src/aggregators/prioritytable.jl index 6572a3e1d..0059d75a0 100644 --- a/src/aggregators/prioritytable.jl +++ b/src/aggregators/prioritytable.jl @@ -128,6 +128,10 @@ function PriorityTable(priortogid::Function, priorities::AbstractVector, minprio maxpriority) numgroups = priortogid(maxpriority) numgroups -= one(typeof(numgroups)) + # `priortogid` maps priorities at or below `eps` to group 1, so when minpriority + # itself is below `eps` (e.g. Float32, where 2^-40 < eps(Float32)) this can give + # fewer than the three base groups {0}, (0,minpriority), [minpriority,2*minpriority). + numgroups = max(numgroups, 3) pidtype = typeof(numgroups) ptype = eltype(priorities) groups = Vector{PriorityGroup{ptype, Vector{pidtype}}}() diff --git a/src/aggregators/rssacr.jl b/src/aggregators/rssacr.jl index cc768c3eb..e8f252591 100644 --- a/src/aggregators/rssacr.jl +++ b/src/aggregators/rssacr.jl @@ -56,7 +56,7 @@ function RSSACRJumpAggregation(nj::Int, njt::F, et::F, crs::Vector{F}, sum_rate: minexponent = exponent(minrate) # use the largest power of two that is <= the passed in minrate - minrate = 2.0^minexponent + minrate = F(2)^minexponent ratetogroup = rate -> priortogid(rate, minexponent) # construct an empty initial priority table -- we'll reset this in init diff --git a/src/spatial/directcrdirect.jl b/src/spatial/directcrdirect.jl index 35d82c1aa..4c5001191 100644 --- a/src/spatial/directcrdirect.jl +++ b/src/spatial/directcrdirect.jl @@ -36,7 +36,7 @@ function DirectCRDirectJumpAggregation(nj::SpatialJump{J}, njt::T, et::T, rx_rat minexponent = exponent(minrate) # use the largest power of two that is <= the passed in minrate - minrate = 2.0^minexponent + minrate = T(2)^minexponent ratetogroup = rate -> priortogid(rate, minexponent) # construct an empty initial priority table -- we'll reset this in init diff --git a/test/fp_unknowns.jl b/test/fp_unknowns.jl index 0d4b4c661..80ee131e0 100644 --- a/test/fp_unknowns.jl +++ b/test/fp_unknowns.jl @@ -61,11 +61,38 @@ end @test typed_randexp(rng, t) isa typeof(t) end @test typed_randexp(rng, ForwardDiff.Dual(1.0, 1.0)) isa ForwardDiff.Dual +end - # CCNRM's time table holds times of the problem's type - maj = MassActionJump([10.0f0, 1.0f0], [Pair{Int, Int}[], [1 => 1]], [ - [1 => 1], [1 => -1]]) - dprob = DiscreteProblem([0], (0.0f0, 10.0f0)) - sol = solve(JumpProblem(dprob, CCNRM(), maj), SSAStepper(); rng) - @test eltype(sol.t) == Float32 +# Float32 and BigFloat times and rates (issue #674): DirectCR, RSSACR, CCNRM and +# DirectCRDirect failed to build or run with them before. +# 10, ∅ --> X +# 1, X --> ∅ +# X(10) is close to Poisson(10) distributed when X(0) = 0. +@testset "Solves with $T times" for T in (Float32, BigFloat) + Nsims = (T == Float32) ? 1000 : 250 + tol = 5 * sqrt(10 / Nsims) + maj = MassActionJump(T[10, 1], [Pair{Int, Int}[], [1 => 1]], [[1 => 1], [1 => -1]]) + dprob = DiscreteProblem([0], (zero(T), T(10))) + # RDirect can't build problems with BigFloat rates yet + aggs = (T == BigFloat) ? filter(!=(RDirect()), JumpProcesses.JUMP_AGGREGATORS) : + JumpProcesses.JUMP_AGGREGATORS + for agg in aggs + jprob = JumpProblem(dprob, agg, maj; save_positions = (false, false)) + sol = solve(jprob, SSAStepper(); rng) + @test eltype(sol.t) == T + Xmean = sum(solve(jprob, SSAStepper(); rng)[1, end] for _ in 1:Nsims) / Nsims + @test abs(Xmean - 10) < tol + end + + # the same reactions at each of two sites, with hopping between them + u0 = zeros(Int, 1, 2) + for agg in (NSM(), DirectCRDirect()) + jprob = JumpProblem(DiscreteProblem(u0, (zero(T), T(10))), agg, maj; + hopping_constants = fill(one(T), size(u0)), spatial_system = CartesianGrid((2,)), + save_positions = (false, false)) + sol = solve(jprob, SSAStepper(); rng) + @test eltype(sol.t) == T + Xmean = sum(sum(solve(jprob, SSAStepper(); rng).u[end]) for _ in 1:Nsims) / Nsims + @test abs(Xmean - 20) < 2 * tol + end end diff --git a/test/isolated_copy.jl b/test/isolated_copy.jl index 5c23a9d87..97a80071b 100644 --- a/test/isolated_copy.jl +++ b/test/isolated_copy.jl @@ -296,10 +296,10 @@ end # A fresh aggregator's buffers are allocated with `undef`, so for `BigFloat` and `BigInt` they # hold unassigned entries until the first `init`; these problems are copied unsolved. -# (`DirectCR`, `RSSACR` and `RDirect` can't build problems with `BigFloat` times yet.) +# (`RDirect` can't build problems with `BigFloat` times yet.) @testset "Copies of unsolved problems with BigFloat times: $(nameof(typeof(aggregator))), \ - massaction = $massaction" for aggregator in (Direct(), DirectFW(), - SortingDirect(), RSSA(), FRM(), FRMFW(), NRM(), Coevolve(), CCNRM()), + massaction = $massaction" for aggregator in (Direct(), DirectFW(), DirectCR(), + SortingDirect(), RSSA(), RSSACR(), FRM(), FRMFW(), NRM(), Coevolve(), CCNRM()), massaction in (true, false) jprob = ab_jprob(aggregator; massaction, T = BigFloat) diff --git a/test/table_test.jl b/test/table_test.jl index 1cf01f4c1..11b49ab6a 100644 --- a/test/table_test.jl +++ b/test/table_test.jl @@ -97,3 +97,55 @@ DJ.rebuild!(ptt, mintime, timestep) @test ptt.groups[18].numpids == 1 @test ptt.groups[21].numpids == 1 @test ptt.pidtogroup[1] == (0, 0) + +##### Float32 tests (issue #674) +minpriority32 = Float32(2.0)^exponent(Float32(1e-12)) +maxpriority32 = Float32(2.0)^exponent(Float32(1e12)) +priorities32 = [Float32(1e-13), 0.99f0 * minpriority32, minpriority32, Float32(1.01e-4), + Float32(1e-4), 5.0f0, 0.0f0, Float32(1e10)] +mingid32 = exponent(minpriority32) +ptog32 = priority -> DJ.priortogid(priority, mingid32) +pt32 = DJ.PriorityTable(ptog32, priorities32, minpriority32, maxpriority32) +@test typeof(pt32.minpriority) == Float32 +@test typeof(pt32.maxpriority) == Float32 +@test typeof(pt32.groups[1].maxpriority) == Float32 + +# insert a priority far above the initial maxpriority (table must grow, not hang) +push!(priorities32, Float32(1e20)) +DJ.insert!(pt32, length(priorities32), priorities32[end]) +@test pt32.groups[end].pids[end] == length(priorities32) + +# update across groups +DJ.update!(pt32, 5, priorities32[5], 8.0f0) +priorities32[5] = 8.0f0 + +# sample returns valid ids and groupsum tracks the priorities +rng32 = StableRNG(12345) +samp = DJ.sample(pt32, priorities32, rng32) +@test 1 <= samp <= length(priorities32) +DJ.resum!(pt32, priorities32) +@test isapprox(DJ.groupsum(pt32), sum(Float64.(priorities32)); rtol = 1e-6) + +# table built the way DirectCR builds it (maxpriority = 2*minpriority below +# eps(Float32)): this hung pre-fix, as the constructor collapsed to zero groups and +# zero maxpriority, spinning `padtable!` forever on `0 * 2` +crmin = Float32(2)^exponent(Float32(1e-12)) +crtog = priority -> DJ.priortogid(priority, exponent(crmin)) +crpt = DJ.PriorityTable(crtog, zeros(Float32, 1), crmin, 2 * crmin) +@test DJ.numgroups(crpt) == 3 +@test typeof(crpt.maxpriority) == Float32 +@test crpt.maxpriority > 0 +DJ.insert!(crpt, 1, 10.0f0) +@test DJ.groupsum(crpt) == 10.0f0 +DJ.insert!(crpt, 2, 0.0f0) +@test DJ.sample(crpt, Float32[10.0f0, 0.0f0], rng32) == 1 + +# PriorityTimeTable with Float32 times +times32 = Float32[2.0, 8.0, 13.0, 15.0, 74.0] +ptt32 = DJ.PriorityTimeTable(times32, 0.0f0, 1.5f0 / 16) +@test DJ.getfirst(ptt32) == (1, 2.0f0) +DJ.update!(ptt32, 1, times32[1], 20.0f0) +@test ptt32.times[1] == 20.0f0 +@test DJ.getfirst(ptt32) == (2, 8.0f0) +DJ.update!(ptt32, 1, 20.0f0, 70.0f0) # newtime outside the window +@test ptt32.pidtogroup[1] == (0, 0) From a9f5ae04fa2503bbe98159d33de3d948056e35c2 Mon Sep 17 00:00:00 2001 From: Sam Isaacson Date: Wed, 11 Nov 2026 23:04:34 -0500 Subject: [PATCH 3/5] Tighten the Float32/BigFloat solve tests' tolerances Test the sample means to 4 standard deviations of a Poisson mean, with 4000 Float32 and 1000 BigFloat simulations: within 2% (Float32) and 4% (BigFloat) of the mean of X(10), where they were within 5% and 10%. The two-site spatial totals used twice the one-site tolerance, about 7 standard deviations; they now use their own, sqrt(20 / Nsims). All the current means are within 1.2 standard deviations. Co-Authored-By: Claude Opus 5.5 --- test/fp_unknowns.jl | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/test/fp_unknowns.jl b/test/fp_unknowns.jl index 80ee131e0..52dea1614 100644 --- a/test/fp_unknowns.jl +++ b/test/fp_unknowns.jl @@ -67,10 +67,10 @@ end # DirectCRDirect failed to build or run with them before. # 10, ∅ --> X # 1, X --> ∅ -# X(10) is close to Poisson(10) distributed when X(0) = 0. +# X(10) is close to Poisson(10) distributed when X(0) = 0, so its sample mean is tested to +# within 4 standard deviations, sqrt(10 / Nsims). @testset "Solves with $T times" for T in (Float32, BigFloat) - Nsims = (T == Float32) ? 1000 : 250 - tol = 5 * sqrt(10 / Nsims) + Nsims = (T == Float32) ? 4000 : 1000 maj = MassActionJump(T[10, 1], [Pair{Int, Int}[], [1 => 1]], [[1 => 1], [1 => -1]]) dprob = DiscreteProblem([0], (zero(T), T(10))) # RDirect can't build problems with BigFloat rates yet @@ -81,10 +81,11 @@ end sol = solve(jprob, SSAStepper(); rng) @test eltype(sol.t) == T Xmean = sum(solve(jprob, SSAStepper(); rng)[1, end] for _ in 1:Nsims) / Nsims - @test abs(Xmean - 10) < tol + @test abs(Xmean - 10) < 4 * sqrt(10 / Nsims) end - # the same reactions at each of two sites, with hopping between them + # the same reactions at each of two sites, with hopping between them: the total is close + # to Poisson(20) distributed u0 = zeros(Int, 1, 2) for agg in (NSM(), DirectCRDirect()) jprob = JumpProblem(DiscreteProblem(u0, (zero(T), T(10))), agg, maj; @@ -93,6 +94,6 @@ end sol = solve(jprob, SSAStepper(); rng) @test eltype(sol.t) == T Xmean = sum(sum(solve(jprob, SSAStepper(); rng).u[end]) for _ in 1:Nsims) / Nsims - @test abs(Xmean - 20) < 2 * tol + @test abs(Xmean - 20) < 4 * sqrt(20 / Nsims) end end From cb1a0bef4d84361a2c0359f4d01e83f203b5e781 Mon Sep 17 00:00:00 2001 From: Sam Isaacson Date: Wed, 11 Nov 2026 23:54:05 -0500 Subject: [PATCH 4/5] Fix spatial BigFloat rates and extreme rates in the rejection tables From the second review of #718: - NSM and DirectCRDirect stored reaction rates as Float64 (`RxRates`), so a BigFloat rate below floatmin(Float64) rounded to zero and its reaction never fired. `RxRates` now takes the rate type, and both use the time's type, as the other aggregators do; the two-argument constructor still makes Float64 rates. - DirectCR, RSSACR and DirectCRDirect took the exponent of a `minrate` keyword before converting it to the rates' type: with `minrate = 1e-50` and Float32 rates, the minimum rate became zero and growing the table looped forever. `minrate` is now converted first and raised to at least floatmin(T) (converting 1e-50 to Float32 gives zero, whose exponent is an error); rates that small are in the table's lowest group either way. - A rate of at least 2^exponent(floatmax(T)) (e.g. 2f0^127) is in the group whose upper bound overflows to Inf, so `sample` could never accept it. `padtable!` caps a new group's rejection bound at floatmax(T), while the table's `maxpriority` still reaches Inf. The constructor never makes that group, since its groups end below `maxpriority`. This also affected Float64, on master too. - `typed_randexp` draws floating-point times in their own type without `one(t)`, which allocated a BigFloat per draw (~93 bytes). - The Float32 table-growth test inserted id 1 twice; it now updates it, and checks `resum!`. Float64 results are unchanged (seeded paths identical to master in 18 cases), and the compiled solve code is identical except `padtable!`, which runs only when a table grows. Co-Authored-By: Claude Opus 5.5 --- HISTORY.md | 8 ++++++ src/aggregators/directcr.jl | 4 ++- src/aggregators/prioritytable.jl | 8 +++++- src/aggregators/rssacr.jl | 4 ++- src/aggregators/ssajump.jl | 3 ++- src/spatial/directcrdirect.jl | 6 +++-- src/spatial/nsm.jl | 2 +- src/spatial/reaction_rates.jl | 12 ++++----- test/fp_unknowns.jl | 46 ++++++++++++++++++++++++++++++++ test/table_test.jl | 26 +++++++++++++++++- 10 files changed, 105 insertions(+), 14 deletions(-) diff --git a/HISTORY.md b/HISTORY.md index 0646957aa..83cf1ec61 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -10,6 +10,14 @@ - `DirectCR`, `RSSACR` and the spatial `DirectCRDirect` can now build problems with `Float32` or `BigFloat` rates and times (they failed with a `MethodError`). `RDirect` still can't build problems with `BigFloat` rates. + - `NSM` and `DirectCRDirect` now compute reaction rates in the type of the time, as the + other aggregators do, instead of `Float64`: a `BigFloat` rate below `floatmin(Float64)` + rounded to zero, so its reaction never fired. Seeded results can change for spatial + problems with `Float32` times. + - `DirectCR`, `RSSACR` and `DirectCRDirect` no longer hang on a rate of at least + `2^exponent(floatmax(T))` for rates of type `T` (e.g. `2.0^1023`), or on a `minrate` + keyword below `floatmin(T)` (e.g. `1e-50` with `Float32` rates, now raised to + `floatmin(T)`). ## 10.2.0 - New `isolated_copy(jprob)` returns a `JumpProblem` with its own jump state, for diff --git a/src/aggregators/directcr.jl b/src/aggregators/directcr.jl index 25022e390..3e2b2f419 100644 --- a/src/aggregators/directcr.jl +++ b/src/aggregators/directcr.jl @@ -42,7 +42,9 @@ function DirectCRJumpAggregation(nj::Int, njt::T, et::T, crs::Vector{T}, sr::T, maxrate = convert(T, Inf), kwargs...) where {T, S, F1, F2} - # mapping from jump rate to group id + # mapping from jump rate to group id, in the rates' type; a minrate below its smallest + # normal number (e.g. 1e-50 with Float32 rates, which converts to zero) is raised to it + minrate = max(convert(T, minrate), floatmin(T)) minexponent = exponent(minrate) # use the largest power of two that is <= the passed in minrate diff --git a/src/aggregators/prioritytable.jl b/src/aggregators/prioritytable.jl index 0059d75a0..e71ba0a02 100644 --- a/src/aggregators/prioritytable.jl +++ b/src/aggregators/prioritytable.jl @@ -178,6 +178,12 @@ end pt.gsum end +# The rejection bound of the group of priorities below `maxpriority`. For the group of the +# largest finite priorities, `maxpriority` overflows to Inf, against which `sample` would +# never accept, so the bound is capped at `floatmax`. The table's `maxpriority` is not capped: +# it reaches Inf, so the table stops growing. +@inline rejection_bound(maxpriority) = min(maxpriority, floatmax(typeof(maxpriority))) + """ Adds extra groups to the table to accommodate a new maxpriority. """ @@ -187,7 +193,7 @@ function padtable!(pt::PriorityTable, pid, priority) while priority >= maxpriority maxpriority *= 2 - push!(groups, PriorityGroup{pidtype}(maxpriority)) + push!(groups, PriorityGroup{pidtype}(rejection_bound(maxpriority))) push!(gsums, zero(eltype(gsums))) end pt.maxpriority = maxpriority diff --git a/src/aggregators/rssacr.jl b/src/aggregators/rssacr.jl index e8f252591..9231c23c6 100644 --- a/src/aggregators/rssacr.jl +++ b/src/aggregators/rssacr.jl @@ -52,7 +52,9 @@ function RSSACRJumpAggregation(nj::Int, njt::F, et::F, crs::Vector{F}, sum_rate: ulow = similar(u) uhigh = similar(u) - # mapping from jump rate to group id + # mapping from jump rate to group id, in the rates' type; a minrate below its smallest + # normal number (e.g. 1e-50 with Float32 rates, which converts to zero) is raised to it + minrate = max(convert(F, minrate), floatmin(F)) minexponent = exponent(minrate) # use the largest power of two that is <= the passed in minrate diff --git a/src/aggregators/ssajump.jl b/src/aggregators/ssajump.jl index 3a40d38ce..accbe4069 100644 --- a/src/aggregators/ssajump.jl +++ b/src/aggregators/ssajump.jl @@ -27,7 +27,8 @@ end # An exponential random variate in the numeric type of the time `t` without its units # (`one(t)`), so that `t + typed_randexp(rng, t) / rate` keeps the type of `t`. Floating # point types are drawn in that type; other numbers, such as dual numbers, convert a `Float64` -# draw. +# draw. Floating point times skip `one(t)`, which allocates for `BigFloat`. +@inline typed_randexp(rng, t::AbstractFloat) = randexp(rng, typeof(t)) @inline typed_randexp(rng, t) = _typed_randexp(rng, typeof(one(t))) @inline _typed_randexp(rng, ::Type{T}) where {T <: AbstractFloat} = randexp(rng, T) @inline _typed_randexp(rng, ::Type{T}) where {T} = convert(T, randexp(rng)) diff --git a/src/spatial/directcrdirect.jl b/src/spatial/directcrdirect.jl index 4c5001191..82d5a9539 100644 --- a/src/spatial/directcrdirect.jl +++ b/src/spatial/directcrdirect.jl @@ -32,7 +32,9 @@ function DirectCRDirectJumpAggregation(nj::SpatialJump{J}, njt::T, et::T, rx_rat num_specs, minrate = convert(T, MINJUMPRATE), dependencies, kwargs...) where {J, T, RX, HOP, SS} - # mapping from jump rate to group id + # mapping from jump rate to group id, in the rates' type; a minrate below its smallest + # normal number (e.g. 1e-50 with Float32 rates, which converts to zero) is raised to it + minrate = max(convert(T, minrate), floatmin(T)) minexponent = exponent(minrate) # use the largest power of two that is <= the passed in minrate @@ -71,7 +73,7 @@ function aggregate(aggregator::DirectCRDirect, starting_state, p, t, end_time, next_jump = SpatialJump{Int}(typemax(Int), typemax(Int), typemax(Int)) #a placeholder next_jump_time = typemax(typeof(end_time)) - rx_rates = RxRates(num_sites(spatial_system), majumps) + rx_rates = RxRates(num_sites(spatial_system), majumps, typeof(end_time)) hop_rates = HopRates(hopping_constants, spatial_system) site_rates = zeros(typeof(end_time), num_sites(spatial_system)) diff --git a/src/spatial/nsm.jl b/src/spatial/nsm.jl index 8a0eab3cf..1e0d66d7f 100644 --- a/src/spatial/nsm.jl +++ b/src/spatial/nsm.jl @@ -59,7 +59,7 @@ function aggregate(aggregator::NSM, starting_state, p, t, end_time, constant_jum next_jump = SpatialJump{Int}(typemax(Int), typemax(Int), typemax(Int)) #a placeholder next_jump_time = typemax(typeof(end_time)) - rx_rates = RxRates(num_sites(spatial_system), majumps) + rx_rates = RxRates(num_sites(spatial_system), majumps, typeof(end_time)) hop_rates = HopRates(hopping_constants, spatial_system) NSMJumpAggregation(next_jump, next_jump_time, end_time, rx_rates, hop_rates, diff --git a/src/spatial/reaction_rates.jl b/src/spatial/reaction_rates.jl index d67da1832..80299ba00 100644 --- a/src/spatial/reaction_rates.jl +++ b/src/spatial/reaction_rates.jl @@ -28,15 +28,15 @@ end shared_fields(::Type{<:RxRates}) = (:ma_jumps,) """ - RxRates(num_sites::Int, ma_jumps::M) where {M} + RxRates(num_sites::Int, ma_jumps::M, ::Type{F} = Float64) where {M, F} -initializes RxRates with zero rates +initializes RxRates with zero rates of type `F` """ -function RxRates(num_sites::Int, ma_jumps::M) where {M} +function RxRates(num_sites::Int, ma_jumps::M, ::Type{F} = Float64) where {M, F} numrxjumps = get_num_majumps(ma_jumps) - rates = zeros(Float64, numrxjumps, num_sites) - maj_rates = Vector{Float64}(undef, numrxjumps) - RxRates{Float64, M}(rates, vec(sum(rates, dims = 1)), ma_jumps, maj_rates) + rates = zeros(F, numrxjumps, num_sites) + maj_rates = Vector{F}(undef, numrxjumps) + RxRates{F, M}(rates, vec(sum(rates, dims = 1)), ma_jumps, maj_rates) end num_rxs(rx_rates::RxRates) = get_num_majumps(rx_rates.ma_jumps) diff --git a/test/fp_unknowns.jl b/test/fp_unknowns.jl index 52dea1614..59288ca00 100644 --- a/test/fp_unknowns.jl +++ b/test/fp_unknowns.jl @@ -97,3 +97,49 @@ end @test abs(Xmean - 20) < 4 * sqrt(20 / Nsims) end end + +# Spatial reaction rates are in the time's type: a BigFloat rate below floatmin(Float64) +# rounded to zero, so the reaction never fired. +@testset "Spatial BigFloat rates below floatmin(Float64)" begin + maj = MassActionJump([big"1e-400"], [[1 => 1]], [[1 => -1]]) + tspan = (big(0.0), big"1e401") + sol = solve(JumpProblem(DiscreteProblem([1], tspan), Direct(), maj), SSAStepper(); + rng = StableRNG(1)) + for agg in (NSM(), DirectCRDirect()) + jprob = JumpProblem(DiscreteProblem(reshape([1], 1, 1), tspan), agg, maj; + hopping_constants = zeros(BigFloat, 1, 1), spatial_system = CartesianGrid((1,))) + ssol = solve(jprob, SSAStepper(); rng = StableRNG(1)) + @test ssol.u[end][1] == 0 + # the first draw gives the same jump time as Direct's + @test ssol.t[2] == sol.t[2] + end +end + +# Rates at the ends of the numeric range for the rejection (priority) tables, which hung +@testset "Rejection tables with extreme $T rates" for T in (Float32, Float64) + # a minrate below floatmin(T), given as a Float64 + maj = MassActionJump(T[10, 1], [Pair{Int, Int}[], [1 => 1]], [[1 => 1], [1 => -1]]) + for agg in (DirectCR(), RSSACR()) + jprob = JumpProblem(DiscreteProblem([0], (zero(T), T(10))), agg, maj; + minrate = 1e-50) + @test solve(jprob, SSAStepper(); rng).u[end][1] > 0 + end + jprob = JumpProblem(DiscreteProblem(zeros(Int, 1, 2), (zero(T), T(10))), + DirectCRDirect(), maj; hopping_constants = ones(T, 1, 2), + spatial_system = CartesianGrid((2,)), minrate = 1e-50) + @test sum(solve(jprob, SSAStepper(); rng).u[end]) > 0 + + # the largest finite power of two as a rate, until 10 jumps are expected + rate = T(2)^exponent(floatmax(T)) + maj = MassActionJump([rate], [Pair{Int, Int}[]], [[1 => 1]]) + tspan = (zero(T), 10 / rate) + for agg in (DirectCR(), RSSACR()) + jprob = JumpProblem(DiscreteProblem([0], tspan), agg, maj; + save_positions = (false, false)) + @test solve(jprob, SSAStepper(); rng).u[end][1] > 0 + end + jprob = JumpProblem(DiscreteProblem(zeros(Int, 1, 1), tspan), DirectCRDirect(), maj; + hopping_constants = zeros(T, 1, 1), spatial_system = CartesianGrid((1,)), + save_positions = (false, false)) + @test solve(jprob, SSAStepper(); rng).u[end][1] > 0 +end diff --git a/test/table_test.jl b/test/table_test.jl index 11b49ab6a..09cab999c 100644 --- a/test/table_test.jl +++ b/test/table_test.jl @@ -135,10 +135,34 @@ crpt = DJ.PriorityTable(crtog, zeros(Float32, 1), crmin, 2 * crmin) @test DJ.numgroups(crpt) == 3 @test typeof(crpt.maxpriority) == Float32 @test crpt.maxpriority > 0 -DJ.insert!(crpt, 1, 10.0f0) +DJ.update!(crpt, 1, 0.0f0, 10.0f0) @test DJ.groupsum(crpt) == 10.0f0 DJ.insert!(crpt, 2, 0.0f0) @test DJ.sample(crpt, Float32[10.0f0, 0.0f0], rng32) == 1 +DJ.resum!(crpt, Float32[10.0f0, 0.0f0]) +@test DJ.groupsum(crpt) == 10.0f0 + +# the largest finite priorities: their group's upper bound, 2^(emax + 1), overflows to Inf, +# so its rejection bound is capped at floatmax, while the table's maxpriority reaches Inf so +# that it stops growing +for T in (Float32, Float64) + local minp = T(2)^exponent(T(1e-12)) + local tog = priority -> DJ.priortogid(priority, exponent(minp)) + local priors = T[1, 0] + local pt = DJ.PriorityTable(tog, priors, minp, 2 * minp) + priors[1] = T(2)^exponent(floatmax(T)) + DJ.update!(pt, 1, one(T), priors[1]) + @test pt.maxpriority == T(Inf) + @test pt.groups[end].maxpriority == floatmax(T) + @test DJ.sample(pt, priors, rng32) == 1 + @test DJ.sample(pt.groups[end], priors, rng32) == 1 + + # a table built with that priority (the constructor's groups end below it) + pt = DJ.PriorityTable(tog, priors, minp, priors[1]) + @test pt.maxpriority == T(Inf) + @test pt.groups[end].maxpriority == floatmax(T) + @test DJ.sample(pt, priors, rng32) == 1 +end # PriorityTimeTable with Float32 times times32 = Float32[2.0, 8.0, 13.0, 15.0, 74.0] From 49901d4f73b33fc08fa5829f9641a9dc4476c8d9 Mon Sep 17 00:00:00 2001 From: Sam Isaacson Date: Thu, 12 Nov 2026 11:16:16 -0500 Subject: [PATCH 5/5] Raise the rejection tables' minimum rate to eps(T) From the fourth review of #718. Rates at or below eps(T) all go in the tables' first group, so a smaller minrate only adds empty groups, one per power of two: with minrate = floatmin(BigFloat) (2^-1073741824 on Julia 1.13), a rate of 1 maps to group about 1.07e9, and growing the table to it exhausts memory. DirectCR, RSSACR and DirectCRDirect now raise minrate to at least eps(T), replacing the floatmin(T) floor. The Float64 and BigFloat defaults (2^-40) are unchanged; the Float32 default rises to eps(Float32) = 2^-23, which removes 17 empty groups and leaves seeded paths unchanged. The suggested upper bound, floatmax(T) / 2, is left out: a minrate of 2f0^127 fails at construction (DomainError), and clamping it to 2^126 puts every ordinary rate in one group rejection-sampled against 2^126, so a solve with rates [10, 1] doesn't finish. Co-Authored-By: Claude Opus 5.5 --- HISTORY.md | 8 +++++--- src/aggregators/directcr.jl | 7 ++++--- src/aggregators/rssacr.jl | 7 ++++--- src/spatial/directcrdirect.jl | 7 ++++--- test/fp_unknowns.jl | 21 ++++++++++++++++++++- 5 files changed, 37 insertions(+), 13 deletions(-) diff --git a/HISTORY.md b/HISTORY.md index 83cf1ec61..adc49e7f0 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -15,9 +15,11 @@ rounded to zero, so its reaction never fired. Seeded results can change for spatial problems with `Float32` times. - `DirectCR`, `RSSACR` and `DirectCRDirect` no longer hang on a rate of at least - `2^exponent(floatmax(T))` for rates of type `T` (e.g. `2.0^1023`), or on a `minrate` - keyword below `floatmin(T)` (e.g. `1e-50` with `Float32` rates, now raised to - `floatmin(T)`). + `2^exponent(floatmax(T))` for rates of type `T` (e.g. `2.0^1023`), or on a tiny + `minrate` keyword (e.g. `1e-50` with `Float32` rates, or `floatmin(BigFloat)`). `minrate` + is now raised to at least `eps(T)`, since rates at or below `eps(T)` already share the + tables' first group; for `Float32` rates this raises the default from `2^-40` to + `eps(Float32)`. ## 10.2.0 - New `isolated_copy(jprob)` returns a `JumpProblem` with its own jump state, for diff --git a/src/aggregators/directcr.jl b/src/aggregators/directcr.jl index 3e2b2f419..49cf426b4 100644 --- a/src/aggregators/directcr.jl +++ b/src/aggregators/directcr.jl @@ -42,9 +42,10 @@ function DirectCRJumpAggregation(nj::Int, njt::T, et::T, crs::Vector{T}, sr::T, maxrate = convert(T, Inf), kwargs...) where {T, S, F1, F2} - # mapping from jump rate to group id, in the rates' type; a minrate below its smallest - # normal number (e.g. 1e-50 with Float32 rates, which converts to zero) is raised to it - minrate = max(convert(T, minrate), floatmin(T)) + # mapping from jump rate to group id, in the rates' type. Rates at or below eps(T) all go + # in the table's first group, so a smaller minrate only adds empty groups, one per power + # of two (about 10^9 for floatmin(BigFloat)): it is raised to eps(T) + minrate = max(convert(T, minrate), eps(T)) minexponent = exponent(minrate) # use the largest power of two that is <= the passed in minrate diff --git a/src/aggregators/rssacr.jl b/src/aggregators/rssacr.jl index 9231c23c6..3d29abdbe 100644 --- a/src/aggregators/rssacr.jl +++ b/src/aggregators/rssacr.jl @@ -52,9 +52,10 @@ function RSSACRJumpAggregation(nj::Int, njt::F, et::F, crs::Vector{F}, sum_rate: ulow = similar(u) uhigh = similar(u) - # mapping from jump rate to group id, in the rates' type; a minrate below its smallest - # normal number (e.g. 1e-50 with Float32 rates, which converts to zero) is raised to it - minrate = max(convert(F, minrate), floatmin(F)) + # mapping from jump rate to group id, in the rates' type. Rates at or below eps(F) all go + # in the table's first group, so a smaller minrate only adds empty groups, one per power + # of two (about 10^9 for floatmin(BigFloat)): it is raised to eps(F) + minrate = max(convert(F, minrate), eps(F)) minexponent = exponent(minrate) # use the largest power of two that is <= the passed in minrate diff --git a/src/spatial/directcrdirect.jl b/src/spatial/directcrdirect.jl index 82d5a9539..4e4de97db 100644 --- a/src/spatial/directcrdirect.jl +++ b/src/spatial/directcrdirect.jl @@ -32,9 +32,10 @@ function DirectCRDirectJumpAggregation(nj::SpatialJump{J}, njt::T, et::T, rx_rat num_specs, minrate = convert(T, MINJUMPRATE), dependencies, kwargs...) where {J, T, RX, HOP, SS} - # mapping from jump rate to group id, in the rates' type; a minrate below its smallest - # normal number (e.g. 1e-50 with Float32 rates, which converts to zero) is raised to it - minrate = max(convert(T, minrate), floatmin(T)) + # mapping from jump rate to group id, in the rates' type. Rates at or below eps(T) all go + # in the table's first group, so a smaller minrate only adds empty groups, one per power + # of two (about 10^9 for floatmin(BigFloat)): it is raised to eps(T) + minrate = max(convert(T, minrate), eps(T)) minexponent = exponent(minrate) # use the largest power of two that is <= the passed in minrate diff --git a/test/fp_unknowns.jl b/test/fp_unknowns.jl index 59288ca00..b55dbbf1c 100644 --- a/test/fp_unknowns.jl +++ b/test/fp_unknowns.jl @@ -117,7 +117,7 @@ end # Rates at the ends of the numeric range for the rejection (priority) tables, which hung @testset "Rejection tables with extreme $T rates" for T in (Float32, Float64) - # a minrate below floatmin(T), given as a Float64 + # a minrate below eps(T), given as a Float64 (zero once converted to Float32) maj = MassActionJump(T[10, 1], [Pair{Int, Int}[], [1 => 1]], [[1 => 1], [1 => -1]]) for agg in (DirectCR(), RSSACR()) jprob = JumpProblem(DiscreteProblem([0], (zero(T), T(10))), agg, maj; @@ -143,3 +143,22 @@ end save_positions = (false, false)) @test solve(jprob, SSAStepper(); rng).u[end][1] > 0 end + +# The rejection tables' minimum rate is at least eps(T): rates at or below it share the first +# group, and a smaller one only adds empty groups (about 10^9 for floatmin(BigFloat)). Only the +# stored value is checked, since a solve with ~10^9 groups would exhaust memory. +@testset "Minimum rate of rejection tables, $T" for T in (Float32, Float64, BigFloat) + maj = MassActionJump(T[10, 1], [Pair{Int, Int}[], [1 => 1]], [[1 => 1], [1 => -1]]) + # (keywords, expected minimum rate); the default, 2^-40, is below eps(Float32) only + cases = (((;), max(T(2)^-40, eps(T))), ((; minrate = floatmin(T)), eps(T))) + for (kw, minpriority) in cases + for agg in (DirectCR(), RSSACR()) + jprob = JumpProblem(DiscreteProblem([0], (zero(T), T(10))), agg, maj; kw...) + @test jprob.discrete_jump_aggregation.rt.minpriority == minpriority + end + jprob = JumpProblem(DiscreteProblem(zeros(Int, 1, 2), (zero(T), T(10))), + DirectCRDirect(), maj; hopping_constants = ones(T, 1, 2), + spatial_system = CartesianGrid((2,)), kw...) + @test jprob.discrete_jump_aggregation.rt.minpriority == minpriority + end +end