diff --git a/HISTORY.md b/HISTORY.md index 88e1fe9de..adc49e7f0 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -1,5 +1,26 @@ # 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. + - `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 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 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..49cf426b4 100644 --- a/src/aggregators/directcr.jl +++ b/src/aggregators/directcr.jl @@ -42,11 +42,14 @@ 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. 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 - 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 @@ -118,7 +121,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/prioritytable.jl b/src/aggregators/prioritytable.jl index 6572a3e1d..e71ba0a02 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}}}() @@ -174,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. """ @@ -183,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/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..3d29abdbe 100644 --- a/src/aggregators/rssacr.jl +++ b/src/aggregators/rssacr.jl @@ -52,11 +52,14 @@ 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. 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 - 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 @@ -140,7 +143,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 +157,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..accbe4069 100644 --- a/src/aggregators/ssajump.jl +++ b/src/aggregators/ssajump.jl @@ -24,6 +24,15 @@ 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. 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)) + ########### 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..4e4de97db 100644 --- a/src/spatial/directcrdirect.jl +++ b/src/spatial/directcrdirect.jl @@ -32,11 +32,14 @@ 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. 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 - 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 @@ -71,7 +74,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)) @@ -91,7 +94,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..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, @@ -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/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/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..b55dbbf1c 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,115 @@ 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 +end + +# 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, 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) ? 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 + 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) < 4 * sqrt(10 / Nsims) + end + + # 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; + 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) < 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 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; + 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 + +# 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 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..09cab999c 100644 --- a/test/table_test.jl +++ b/test/table_test.jl @@ -97,3 +97,79 @@ 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.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] +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)