diff --git a/HISTORY.md b/HISTORY.md index 88e1fe9de..20dc05830 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -1,5 +1,12 @@ # Breaking updates and feature summaries across releases +## 10.3.0 + + - `SimpleTauLeaping` consumes native `MassActionJump` rates and stoichiometry + on CPU and in KernelAbstractions kernels, with solver-owned working rates. + - Public `massaction_rates!`, `massaction_stoichiometry_mul!`, and + `massaction_drift!` operations support downstream leaping solvers. + ## 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/Project.toml b/Project.toml index 019c0088d..de4ff0391 100644 --- a/Project.toml +++ b/Project.toml @@ -1,7 +1,7 @@ name = "JumpProcesses" uuid = "ccbc3e58-028d-4f4c-8cd5-9ae44345cda5" authors = ["Chris Rackauckas "] -version = "10.2.0" +version = "10.3.0" [deps] ADTypes = "47edcb42-4c32-4615-8424-f2b9edc5f35b" diff --git a/docs/src/jump_solve.md b/docs/src/jump_solve.md index c9d51aceb..a142ed9b6 100644 --- a/docs/src/jump_solve.md +++ b/docs/src/jump_solve.md @@ -15,7 +15,10 @@ faster as they only simulate the total number of jumps over each leap interval, and thus do not need to simulate the realization of every single jump. Jumps for use with exact simulation methods can be defined as `ConstantRateJump`s, `MassActionJump`s, and/or `VariableRateJump`. Jumps for use with inexact -τ-leaping methods should be defined as `RegularJump`s. +JumpProcesses τ-leaping methods can be defined as `MassActionJump`s with +`PureLeaping()`. +`SimpleTauLeaping` and StochasticDiffEq's leaping algorithms also accept +`RegularJump`s for more general rates and count-based updates. There are special algorithms available for efficiently simulating an exact, pure `JumpProblem` (i.e., a `JumpProblem` over a `DiscreteProblem`). `SSAStepper()` @@ -103,10 +106,16 @@ These methods support mixing with event handling, other jump types, and all of the features of the normal differential equation solvers. - `TauLeaping`: an adaptive tau-leaping algorithm with post-leap estimates. + - `CaoTauLeaping`: use fixed steps (`dt`, `adaptive = false`); its adaptive step selector is incomplete. + - `ImplicitTauLeaping`: implicit tau-leaping. + - `ThetaTrapezoidalTauLeaping`: implicit theta-trapezoidal tau-leaping. + +For fixed steps with the implicit methods, pass `dt` and `adaptive = false`. ### JumpProcesses.jl - - `SimpleTauLeaping`: a tau-leaping algorithm for pure `RegularJump` `JumpProblem`s. + - `SimpleTauLeaping`: fixed-step leaping for pure `MassActionJump` or `RegularJump` + `JumpProblem`s constructed with `PureLeaping()`. Requires a choice of `dt`. - `RegularSSA`: a version of SSA for pure `RegularJump` `JumpProblem`s. @@ -119,3 +128,36 @@ and the jump process has designed a regular jump. - `EM`: Explicit Euler-Maruyama. - `ImplicitEM`: Implicit Euler-Maruyama. See the SDE solvers page for more details. + +## Common mass-action input + +The same mass-action problem can be used with JumpProcesses' fixed-step, adaptive +explicit, implicit, trapezoidal, and switching solvers: + +```@example common_massaction +using JumpProcesses + +maj = MassActionJump([0.1], [[1 => 1]], [[1 => -1, 2 => 1]]) +prob = DiscreteProblem([1000.0, 0.0], (0.0, 1.0)) +jprob = JumpProblem(prob, PureLeaping(), maj) + +fixed_sol = solve(jprob, SimpleTauLeaping(); dt = 0.01) +explicit_sol = solve(jprob, SimpleExplicitTauLeaping()) +implicit_sol = solve(jprob, SimpleImplicitTauLeaping()) +trapezoidal_sol = solve(jprob, SimpleTrapezoidalLeaping()) +switching_sol = solve(jprob, SimpleAdaptiveTauLeaping()) +nothing # hide +``` + +`SimpleTauLeaping` and `SimpleExplicitTauLeaping` support this mass-action input +with `EnsembleGPUKernel`. The fixed-step kernel requires `dt`; the adaptive +explicit kernel requires `saveat`. Implicit and switching GPU kernels are not +provided. `SimpleTauLeaping` also supports device-compatible `RegularJump` +functions; the adaptive explicit GPU kernel requires mass-action kinetics. + +With `SimpleTauLeaping` and `EnsembleGPUKernel`, a custom `prob_func` must +preserve the template time span, state dimension, and mass-action rate constants +and stoichiometry. Initial populations may vary; `RegularJump` rates can read +per-trajectory parameters. Parameter storage must be device-compatible, such as +tuples or static arrays. Parameter-mapped mass-action jumps support the default +ensemble problem function. diff --git a/docs/src/jump_types.md b/docs/src/jump_types.md index 21264e1de..0dd5916f5 100644 --- a/docs/src/jump_types.md +++ b/docs/src/jump_types.md @@ -570,3 +570,16 @@ as will trying to update either `p` or `tspan` while passing a new COEVOLVE: a joint point process model for information diffusion and network evolution, Journal of Machine Learning Research 18(1), 1305–1353 (2017). doi: 10.5555/3122009.3122050. + +## Mass-action operations for solver authors + +`JumpProblem` preserves `MassActionJump` data. Solvers can use the rate constants +and stoichiometry directly and choose their own storage and evaluation strategy. +The following operations support CPU solver implementations; GPU solvers should +prepare a device-compatible representation during solver initialization. + +```@docs +massaction_rates! +massaction_stoichiometry_mul! +massaction_drift! +``` diff --git a/ext/JumpProcessesKernelAbstractionsExt.jl b/ext/JumpProcessesKernelAbstractionsExt.jl index 948c8740c..9635b258d 100644 --- a/ext/JumpProcessesKernelAbstractionsExt.jl +++ b/ext/JumpProcessesKernelAbstractionsExt.jl @@ -75,10 +75,53 @@ function SciMLBase.__solve(ensembleprob::SciMLBase.AbstractEnsembleProblem, # Validate that this is a PureLeaping JumpProblem JumpProcesses.validate_pure_leaping_inputs(jump_prob, alg) || - error("SimpleTauLeaping can only be used with PureLeaping JumpProblems with only non-RegularJumps.") - prob = jump_prob.prob + error("SimpleTauLeaping requires a PureLeaping JumpProblem with a MassActionJump or a RegularJump.") + + # Mass-action rate constants are uploaded once from the template jump. A + # RegularJump rate closure still receives each trajectory's `p`, but a + # parameter-mapped MassActionJump cannot refresh those rates per trajectory. + if jump_prob.regular_jump === nothing && + JumpProcesses.using_params(jump_prob.massaction_jump) && + ensembleprob.prob_func !== SciMLBase.DEFAULT_PROB_FUNC + error("EnsembleGPUKernel with SimpleTauLeaping does not support MassActionJump \ + rate constants that depend on parameters (`param_idxs` / `param_mapper`) \ + together with a custom `prob_func`. Those rates are taken once from the \ + template problem and ignore per-trajectory `p`. Use a RegularJump whose \ + rate reads `p`, or a CPU ensemble algorithm such as EnsembleSerial.") + end - probs = [remake(jump_prob) for _ in 1:trajectories] + template_tspan = jump_prob.prob.tspan + template_state_dim = length(jump_prob.prob.u0) + template_massaction = jump_prob.regular_jump === nothing ? + deepcopy(JumpProcesses.massaction_data(jump_prob.massaction_jump)) : nothing + probs = map(1:trajectories) do i + ctx = SciMLBase.EnsembleContext(i, 1, 0, nothing, nothing, nothing) + _prob = ensembleprob.safetycopy ? deepcopy(jump_prob) : jump_prob + trajectory = ensembleprob.prob_func(_prob, ctx) + length(trajectory.prob.u0) == template_state_dim || throw( + ArgumentError( + "EnsembleGPUKernel with SimpleTauLeaping requires prob_func to preserve the template state dimension." + ) + ) + trajectory.prob.tspan == template_tspan || throw( + ArgumentError( + "EnsembleGPUKernel with SimpleTauLeaping requires prob_func to preserve the template tspan." + ) + ) + JumpProcesses.validate_pure_leaping_inputs(trajectory, alg) || + throw(ArgumentError("prob_func must return a PureLeaping JumpProblem with a MassActionJump or a RegularJump.")) + (trajectory.regular_jump === nothing) == (template_massaction !== nothing) || + throw(ArgumentError("prob_func must preserve the template jump representation.")) + if template_massaction !== nothing + isequal(JumpProcesses.massaction_data(trajectory.massaction_jump), template_massaction) || + throw( + ArgumentError( + "EnsembleGPUKernel with SimpleTauLeaping requires prob_func to preserve MassActionJump rate constants and stoichiometry." + ) + ) + end + trajectory + end # Run vectorized solve ts, @@ -129,6 +172,29 @@ struct JumpData{R, C} numjumps::Int end +Adapt.@adapt_structure JumpData + +gpu_num_jumps(jump::JumpData) = jump.numjumps +leaping_rates!(out, jump::JumpData, u, p, t) = jump.rate(out, u, p, t) +leaping_change!(du, jump::JumpData, u, p, t, counts) = jump.c(du, u, p, t, counts, nothing) + +function leaping_rates!(out, jump::GPUMassActionJump, u, p, t) + for j in eachindex(out) + out[j] = gpu_evalrxrate(u, j, jump, eltype(out)) + end + return nothing +end + +function leaping_change!(du, jump::GPUMassActionJump, u, p, t, counts) + fill!(du, zero(eltype(du))) + for j in eachindex(counts) + for k in jump.ns_offsets[j]:(jump.ns_offsets[j + 1] - 1) + du[jump.ns_species[k]] += jump.ns_coeffs[k] * counts[j] + end + end + return nothing +end + # SimpleTauLeaping kernel @kernel function simple_tau_leaping_kernel( @Const(probs_data), _us, _ts, dt, @Const(rj_data), @@ -150,9 +216,7 @@ end tspan = prob_data.tspan # Extract jump data - rate = rj_data.rate - num_jumps = rj_data.numjumps - c = rj_data.c + num_jumps = gpu_num_jumps(rj_data) # Initialize current_u from u0 @inbounds for k in 1:length(u0) @@ -177,7 +241,7 @@ end tprev = tspan[1] + (j-2) * dt # Compute rates and scale by dt - rate(rate_cache, current_u, p, tprev) + leaping_rates!(rate_cache, rj_data, current_u, p, tprev) rate_cache .*= dt # Poisson sampling @@ -186,7 +250,7 @@ end end # Apply changes - c(local_dc, current_u, p, tprev, counts, nothing) + leaping_change!(local_dc, rj_data, current_u, p, tprev, counts) current_u .+= local_dc # Store results @@ -202,7 +266,11 @@ function vectorized_solve(probs, prob::JumpProblem, alg::SimpleTauLeaping; backend, trajectories, dt, kwargs...) # Extract common jump data rj = prob.regular_jump - rj_data = JumpData(rj.rate, rj.c, rj.numjumps) + rj_data = if rj === nothing + GPUMassActionJump(prob.massaction_jump, prob.prob.p, backend, float(eltype(prob.prob.tspan))) + else + JumpData(rj.rate, rj.c, rj.numjumps) + end # Extract trajectory-specific data without static typing probs_data = [TrajectoryData(SA{eltype(p.prob.u0)}[p.prob.u0...], p.prob.p, p.prob.tspan) @@ -218,7 +286,7 @@ function vectorized_solve(probs, prob::JumpProblem, alg::SimpleTauLeaping; dt = Float64(dt) n_steps = Int((tspan[2] - tspan[1]) / dt) + 1 n_trajectories = length(probs) - num_jumps = rj_data.numjumps + num_jumps = gpu_num_jumps(rj_data) # Validate dimensions @assert state_dim > 0 "Dimension of state must be positive" @@ -230,7 +298,7 @@ function vectorized_solve(probs, prob::JumpProblem, alg::SimpleTauLeaping; # Pre-allocate thread-local buffers current_u_buf = allocate(backend, eltype(prob.prob.u0), (state_dim, n_trajectories)) - rate_cache_buf = allocate(backend, eltype(prob.prob.u0), (num_jumps, n_trajectories)) + rate_cache_buf = allocate(backend, float(eltype(prob.prob.u0)), (num_jumps, n_trajectories)) counts_buf = allocate(backend, eltype(prob.prob.u0), (num_jumps, n_trajectories)) local_dc_buf = allocate(backend, eltype(prob.prob.u0), (state_dim, n_trajectories)) diff --git a/src/JumpProcesses.jl b/src/JumpProcesses.jl index 08f04b478..23b0430d8 100644 --- a/src/JumpProcesses.jl +++ b/src/JumpProcesses.jl @@ -65,6 +65,7 @@ const USE_SORTINGDIRECT_THRESHOLD = 200 include("jumps.jl") export ConstantRateJump, VariableRateJump, RegularJump, MassActionJump, JumpSet, RateBounds +export massaction_rates!, massaction_stoichiometry_mul!, massaction_drift! include("massaction_rates.jl") @@ -133,6 +134,11 @@ problem construction. - `PureLeaping` is currently intended for tau-leaping algorithms such as [`SimpleTauLeaping`](@ref) and [`SimpleExplicitTauLeaping`](@ref). + - A `MassActionJump` can be passed directly to all tau-leaping algorithms in + JumpProcesses. The problem preserves its mass-action + representation so each solver can use the rate constants and stoichiometry directly. + - `SimpleTauLeaping` additionally accepts a `RegularJump` for more general rates + and updates. - Spatial jump problems are not supported by the `PureLeaping` construction path. ## Examples diff --git a/src/massaction_rates.jl b/src/massaction_rates.jl index 716e7217d..1c6c970e6 100644 --- a/src/massaction_rates.jl +++ b/src/massaction_rates.jl @@ -158,3 +158,126 @@ function add_self_dependencies!(dg; dosort = true) end end end + +materialize_leaping_jump(jump::MassActionJump, p, ::Type{T}) where {T} = jump +function materialize_leaping_jump( + jump::MassActionJump{Nothing, <:AbstractArray{<:Pair}}, p, ::Type{T} + ) where {T} + return materialize_leaping_jump(check_majump_type(jump), p, T) +end +function materialize_leaping_jump(jump::MassActionJump{Nothing}, p, ::Type{T}) where {T} + constants = Vector{T}(undef, get_num_majumps(jump)) + fill_scaled_rates!(constants, jump, p) + return MassActionJump( + constants, jump.reactant_stoch, jump.net_stoch; + scale_rates = false, useiszero = false, nocopy = true + ) +end + +@inline massaction_data(jump::MassActionJump) = ( + jump.scaled_rates, jump.reactant_stoch, jump.net_stoch, +) +@inline massaction_data(jump::MassActionJump{<:Number}) = ( + (jump.scaled_rates,), (jump.reactant_stoch,), (jump.net_stoch,), +) +@inline massaction_data(jump::MassActionJump{Nothing, <:AbstractArray{<:Pair}}) = ( + jump.scaled_rates, (jump.reactant_stoch,), (jump.net_stoch,), +) + +""" + massaction_rates!(rates, jump::MassActionJump, u; p = nothing) + +Write each reaction propensity at populations `u` into `rates`. Uses the stored, +combinatorially scaled rate constants and falling factorial rate laws. A reaction +with insufficient reactants has zero propensity. `rates` must have one entry per +reaction and must not alias `u` or the jump's data. For parameter-mapped jumps, +pass the current parameters as `p`; scaled working rates are materialized for +this call without mutating the jump definition. +""" +function massaction_rates!(rates, jump::MassActionJump, u; p = nothing) + working_jump = materialize_leaping_jump(jump, p, eltype(rates)) + constants, reactants, _ = massaction_data(working_jump) + for j in eachindex(constants) + rates[j] = massaction_propensity(constants, reactants, u, j, eltype(rates)) + end + return rates +end + +""" + massaction_propensity(constants, reactants, u, j, T) + +Propensity of reaction `j` at populations `u`, using combinatorially scaled +`constants` and falling-factorial rate laws from `reactants`. Products promote +the population and constant types with the destination scalar type `T`. + +If any reactant population is strictly below the reaction order for that +species, the propensity is zero rather than negative. Under tau-leaping this +means an overshoot that drives a population below zero (or below the order) +stays there for that reaction: the propensity remains zero, so further leaps +cannot pull the population back through this channel. +""" +@inline function massaction_propensity(constants, reactants, u, j, ::Type{T}) where {T} + rate = one(T) * one(eltype(u)) * one(constants[j]) + for (species, order) in reactants[j] + population = u[species] + population <= order - 1 && return zero(rate) + for k in 0:(order - 1) + rate *= population - k + end + end + return rate * constants[j] +end + +""" + massaction_stoichiometry_mul!(du, jump::MassActionJump, counts) + +Overwrite `du` with the net stoichiometry times the reaction vector `counts`. +`counts` may contain reaction counts or propensities and must have one entry per +reaction. `du` must have one entry per species and must not alias `counts` or the +jump's data. +""" +function massaction_stoichiometry_mul!(du, jump::MassActionJump, counts) + fill!(du, zero(eltype(du))) + _, _, stoichiometry = massaction_data(jump) + for j in eachindex(stoichiometry) + count = one(eltype(du)) * counts[j] + for (species, coefficient) in stoichiometry[j] + du[species] += coefficient * count + end + end + return du +end + +""" + massaction_drift!(du, jump::MassActionJump, u; p = nothing) + +Overwrite `du` with the mass-action drift, the net stoichiometry times the +propensities at `u`. Evaluates and accumulates each reaction without allocating +an intermediate propensity vector. Supports automatic differentiation through +`u` when `du` can store the resulting scalar type. `du` must have one entry per +species and must not alias `u` or the jump's data. For parameter-mapped jumps, pass the current parameters as `p`, +as for [`massaction_rates!`](@ref). +""" +function massaction_drift!(du, jump::MassActionJump, u; p = nothing) + fill!(du, zero(eltype(du))) + working_jump = materialize_leaping_jump(jump, p, eltype(du)) + constants, reactants, stoichiometry = massaction_data(working_jump) + for j in eachindex(constants) + rate = massaction_propensity(constants, reactants, u, j, eltype(du)) + for (species, coefficient) in stoichiometry[j] + du[species] += coefficient * rate + end + end + return du +end + +leaping_rates!(out, jump::MassActionJump, u, p, t) = massaction_rates!(out, jump, u) +leaping_rates!(out, jump::RegularJump, u, p, t) = jump.rate(out, u, p, t) +function leaping_change!(du, jump::MassActionJump, u, p, t, counts, mark) + return massaction_stoichiometry_mul!(du, jump, counts) +end +function leaping_change!(du, jump::RegularJump, u, p, t, counts, mark) + return jump.c(du, u, p, t, counts, mark) +end +leaping_num_jumps(jump::MassActionJump) = get_num_majumps(jump) +leaping_num_jumps(jump::RegularJump) = jump.numjumps diff --git a/src/simple_regular_solve.jl b/src/simple_regular_solve.jl index 5faf26b2a..440c9d3ea 100644 --- a/src/simple_regular_solve.jl +++ b/src/simple_regular_solve.jl @@ -1,10 +1,13 @@ """ SimpleTauLeaping() -Fixed-step tau-leaping algorithm for pure [`RegularJump`](@ref) problems. +Fixed-step tau-leaping algorithm for pure [`MassActionJump`](@ref) or +[`RegularJump`](@ref) problems. -Use `SimpleTauLeaping` with `JumpProblem(prob, PureLeaping(), regular_jump)` and pass -the timestep through the `dt` keyword to `solve`. +Use `SimpleTauLeaping` with `JumpProblem(prob, PureLeaping(), jump)`, where `jump` is +a `MassActionJump` or a `RegularJump`, and pass the timestep through `dt` to `solve`. +Both representations also support `EnsembleGPUKernel`; custom regular-jump rate +and update functions must be compatible with the selected device. ## Keyword Arguments @@ -264,12 +267,15 @@ function validate_pure_leaping_inputs(jump_prob::JumpProblem, alg) JumpProblem, i.e. call JumpProblem(::DiscreteProblem, PureLeaping(),...). \ Passing $(jump_prob.aggregator) is deprecated and will be removed in the next breaking release." end - isempty(jump_prob.jump_callback.continuous_callbacks) && + return jump_prob.prob isa DiscreteProblem && + isempty(jump_prob.jump_callback.continuous_callbacks) && isempty(jump_prob.jump_callback.discrete_callbacks) && isempty(jump_prob.constant_jumps) && isempty(jump_prob.variable_jumps) && - get_num_majumps(jump_prob.massaction_jump) == 0 && + xor( + get_num_majumps(jump_prob.massaction_jump) > 0, jump_prob.regular_jump !== nothing + ) end function validate_pure_leaping_inputs( @@ -333,17 +339,16 @@ function DiffEqBase.solve(jump_prob::JumpProblem, alg::SimpleTauLeaping; dt = error("dt is required for SimpleTauLeaping."), saveat = nothing, save_start = nothing, save_end = nothing) validate_pure_leaping_inputs(jump_prob, alg) || - error("SimpleTauLeaping can only be used with PureLeaping JumpProblems with only RegularJumps.") + error("SimpleTauLeaping requires a PureLeaping JumpProblem with a MassActionJump or a RegularJump.") prob = jump_prob.prob _rng = resolve_rng(rng, seed) rj = jump_prob.regular_jump - rate = rj.rate # rate function rate(out,u,p,t) - numjumps = rj.numjumps # used for size information (# of jump processes) - c = rj.c # matrix-free operator c(u_buffer, uprev, tprev, counts, p, mark) + jump = rj === nothing ? materialize_leaping_jump(jump_prob.massaction_jump, prob.p, float(eltype(prob.u0))) : rj + numjumps = leaping_num_jumps(jump) - if !isnothing(rj.mark_dist) == nothing # https://github.com/JuliaDiffEq/DifferentialEquations.jl/issues/250 + if rj !== nothing && !isnothing(rj.mark_dist) error("Mark distributions are currently not supported in SimpleTauLeaping") end @@ -375,10 +380,10 @@ function DiffEqBase.solve(jump_prob::JumpProblem, alg::SimpleTauLeaping; for i in 2:n tprev = tspan[1] + (i - 2) * dt t_new = tprev + dt - rate(rate_cache, uprev, p, tprev) + leaping_rates!(rate_cache, jump, uprev, p, tprev) rate_cache .*= dt counts .= pois_rand.((_rng,), rate_cache) - c(du, uprev, p, tprev, counts, mark) + leaping_change!(du, jump, uprev, p, tprev, counts, nothing) u_new .= du .+ uprev # Save logic — only allocate (via copy) when actually saving diff --git a/test/massaction_fixed_tau_kernel.jl b/test/massaction_fixed_tau_kernel.jl new file mode 100644 index 000000000..b0abb2e56 --- /dev/null +++ b/test/massaction_fixed_tau_kernel.jl @@ -0,0 +1,135 @@ +using JumpProcesses, KernelAbstractions, Adapt, Test, Statistics + +function test_massaction_fixed_tau_kernel(backend) + @testset "Fixed-step mass-action kernel ($T)" for T in (Float64, Int) + maj = MassActionJump([0.2], [[1 => 1]], [[1 => -1, 2 => 1]]) + jp = JumpProblem(DiscreteProblem(T[1001, 0], (0.0, 1.0)), PureLeaping(), maj) + sol = solve( + EnsembleProblem(jp), SimpleTauLeaping(), EnsembleGPUKernel(backend); + trajectories = 2000, dt = 0.01 + ) + @test length(sol.u) == 2000 + @test all(s -> successful_retcode(s), sol.u) + @test all(s -> s.t[end] ≈ 1.0, sol.u) + @test all(s -> all(u -> sum(u) ≈ 1001, s.u), sol.u) + @test mean(s.u[end][1] for s in sol.u) ≈ 1001 * (1 - 0.2 * 0.01)^100 rtol = 0.01 + + births = MassActionJump([10.0], [Pair{Int, Int}[]], [[1 => 1]]) + jp = JumpProblem(DiscreteProblem(T[0], (0.0, 1.0)), PureLeaping(), births) + sol = solve( + EnsembleProblem(jp), SimpleTauLeaping(), EnsembleGPUKernel(backend); + trajectories = 2000, dt = 0.01 + ) + @test mean(s.u[end][1] for s in sol.u) ≈ 10 rtol = 0.05 + end + + # Parameter-mapped MassActionJump rates are uploaded once from the template + # problem; a custom `prob_func` that varies `p` cannot refresh them, unlike + # RegularJump rates which receive per-trajectory `p`. + @testset "Parameter-dependent mass-action rates with prob_func" begin + maj = MassActionJump([[1 => 1]], [[1 => -1]]; param_idxs = [1]) + jp = JumpProblem(DiscreteProblem([50.0], (0.0, 1.0), [0.2]), PureLeaping(), maj) + varying = EnsembleProblem( + jp; + prob_func = (prob, ctx) -> remake(prob; p = [0.1 * ctx.sim_id]) + ) + err = try + solve( + varying, SimpleTauLeaping(), EnsembleGPUKernel(backend); + trajectories = 2, dt = 0.1 + ) + nothing + catch e + e + end + @test err isa ErrorException + @test occursin("param_idxs", err.msg) || occursin("param_mapper", err.msg) + @test occursin("prob_func", err.msg) + end + + # RegularJump rates read per-trajectory `p` from `prob_func`. First-order + # decay A --k--> ∅ with leap mean u0 * (1 - k*dt)^(t/dt). + @testset "RegularJump per-trajectory p via prob_func" begin + rate! = (out, u, p, t) -> (out[1] = p[1] * u[1]; nothing) + change! = (du, u, p, t, counts, mark) -> (du[1] = -counts[1]; nothing) + rj = RegularJump(rate!, change!, 1) + u0 = 1000.0 + tspan = (0.0, 1.0) + dt = 0.01 + nsteps = Int((tspan[2] - tspan[1]) / dt) + jp = JumpProblem(DiscreteProblem([u0], tspan, (0.0,)), PureLeaping(), rj) + @test isbitstype(typeof(jp.prob.p)) + n_per = 2000 + function prob_func(prob, ctx) + # first n_per trajectories use p=0, the rest use p=1 + remake(prob; p = (ctx.sim_id <= n_per ? 0.0 : 1.0,)) + end + @test isbitstype(typeof(prob_func(jp, (; sim_id = n_per + 1)).prob.p)) + sol = solve( + EnsembleProblem(jp; prob_func), SimpleTauLeaping(), + EnsembleGPUKernel(backend); trajectories = 2 * n_per, dt + ) + mean0 = mean(s.u[end][1] for s in sol.u[1:n_per]) + mean1 = mean(s.u[end][1] for s in sol.u[(n_per + 1):end]) + @test mean0 ≈ u0 atol = 1.0e-8 + # E[u] ≈ u0 * (1 - p*dt)^nsteps with p = 1 → 1000 * 0.99^100 ≈ 366.032 + @test mean1 ≈ u0 * (1 - dt)^nsteps rtol = 0.02 + end + @testset "Custom trajectory spans" begin + rj = RegularJump( + (out, u, p, t) -> fill!(out, 0), + (du, u, p, t, counts, mark) -> fill!(du, 0), 1 + ) + jp = JumpProblem(DiscreteProblem([0.0], (0.0, 0.2)), PureLeaping(), rj) + varying_dimensions = EnsembleProblem( + jp; + prob_func = (prob, ctx) -> remake(prob; u0 = zeros(ctx.sim_id)) + ) + @test_throws ArgumentError solve( + varying_dimensions, SimpleTauLeaping(), + EnsembleGPUKernel(backend); trajectories = 2, dt = 0.1 + ) + for tspan in ((0.0, 0.1), (0.0, 0.4), (0.1, 0.3)) + varying = EnsembleProblem( + jp; + prob_func = (prob, ctx) -> remake(prob; tspan) + ) + @test_throws ArgumentError solve( + varying, SimpleTauLeaping(), + EnsembleGPUKernel(backend); trajectories = 2, dt = 0.1 + ) + end + end + + @testset "Custom mass-action data" begin + births(rate) = MassActionJump([rate], [Pair{Int, Int}[]], [[1 => 1]]) + dp = DiscreteProblem([0.0], (0.0, 0.2)) + jp = JumpProblem(dp, PureLeaping(), births(0.0)) + alternatives = ( + births(1000.0), + MassActionJump([0.0], [[1 => 1]], [[1 => 1]]), + MassActionJump([0.0], [Pair{Int, Int}[]], [[1 => -1]]), + ) + for maj in alternatives + varying = EnsembleProblem( + jp; prob_func = (prob, ctx) -> + ctx.sim_id == 1 ? prob : JumpProblem(dp, PureLeaping(), maj) + ) + @test_throws ArgumentError solve( + varying, SimpleTauLeaping(), + EnsembleGPUKernel(backend); trajectories = 2, dt = 0.1 + ) + end + unchanged = EnsembleProblem( + jp; prob_func = (prob, ctx) -> + remake(prob; u0 = [Float64(ctx.sim_id)]) + ) + sol = solve( + unchanged, SimpleTauLeaping(), EnsembleGPUKernel(backend); + trajectories = 2, dt = 0.1 + ) + @test all(successful_retcode, sol.u) + @test [s.u[end][1] for s in sol.u] == [1.0, 2.0] + end + return nothing +end diff --git a/test/massaction_leaping.jl b/test/massaction_leaping.jl new file mode 100644 index 000000000..63da520a7 --- /dev/null +++ b/test/massaction_leaping.jl @@ -0,0 +1,175 @@ +using JumpProcesses, Test, ForwardDiff + +regular_leaping_algs = (SimpleTauLeaping(),) + +@testset "Mass-action input for regular leaping solvers" begin + maj = MassActionJump( + [0.02, 0.1], [[1 => 2], [2 => 1]], + [[1 => -2, 2 => 1], [1 => 2, 2 => -1]] + ) + prob = DiscreteProblem([40.0, 20.0], (0.0, 0.2)) + function rate!(out, u, p, t) + out[1] = u[1] * max(u[1] - 1, 0) * 0.01 + out[2] = 0.1 * u[2] + nothing + end + function change!(du, u, p, t, counts, mark) + du[1] = -2 * counts[1] + 2 * counts[2] + du[2] = counts[1] - counts[2] + nothing + end + rj = RegularJump(rate!, change!, 2) + for alg in regular_leaping_algs, + adaptive in (false,) + @testset "$(nameof(typeof(alg))), adaptive=$adaptive" begin + actual = JumpProblem(prob, PureLeaping(), maj) + reference = JumpProblem(prob, PureLeaping(), rj) + opts = alg isa SimpleTauLeaping ? (; dt = 0.005, seed = 123) : + (; dt = 0.005, seed = 123, adaptive) + sol = solve(actual, alg; opts...) + ref = solve(reference, alg; opts...) + @test successful_retcode(sol) + @test sol.t == ref.t + @test sol.u == ref.u + @test all(u -> u[1] + 2u[2] ≈ 80, sol.u) + end + end +end + +@testset "Native mass-action operations" begin + for scale_rates in (true, false) + maj = MassActionJump( + [2.0, 6.0], [Pair{Int, Int}[], [1 => 3]], + [[1 => 1], [1 => -3, 2 => 1]]; scale_rates + ) + jp = JumpProblem(DiscreteProblem([5.0, 0.0], (0.0, 1.0)), PureLeaping(), maj) + @test jp.regular_jump === nothing + out = fill(NaN, 2) + massaction_rates!(out, jp.massaction_jump, [5.0, 0.0]) + @test out == [2.0, scale_rates ? 60.0 : 360.0] + massaction_rates!(out, jp.massaction_jump, [1.0, 0.0]) + @test out == [2.0, 0.0] + du = fill(NaN, 2) + massaction_stoichiometry_mul!(du, jp.massaction_jump, [4.0, 2.0]) + @test du == [-2.0, 2.0] + u = [5.0, 0.0] + massaction_rates!(out, jp.massaction_jump, u) + massaction_stoichiometry_mul!(du, jp.massaction_jump, out) + @test massaction_drift!(zeros(2), jp.massaction_jump, u) == du + jac = ForwardDiff.jacobian(u) do x + massaction_drift!(similar(x), jp.massaction_jump, x) + end + factor = scale_rates ? 1.0 : 6.0 + @test jac == [-141.0factor 0.0; 47.0factor 0.0] + end + maj = MassActionJump([[1 => 1]], [[1 => -1, 2 => 1]]; param_idxs = [1]) + jp = JumpProblem(DiscreteProblem([20.0, 0.0], (0.0, 1.0), [0.1]), PureLeaping(), maj) + remade = remake(jp; p = [0.3]) + out = zeros(1) + massaction_rates!(out, remade.massaction_jump, remade.prob.u0; p = remade.prob.p) + @test out == [6.0] + @test massaction_drift!( + zeros(2), remade.massaction_jump, remade.prob.u0; + p = remade.prob.p + ) == [-6.0, 6.0] + @test remade.massaction_jump.scaled_rates === nothing + @test successful_retcode(solve(remade, SimpleTauLeaping(); dt = 0.01, seed = 123)) + @test remade.regular_jump === nothing + oprob = ODEProblem((du, u, p, t) -> fill!(du, 0), [20.0, 0.0], (0.0, 1.0), [0.1]) + ojp = JumpProblem(oprob, PureLeaping(), maj) + @test ojp.regular_jump === nothing + @test_throws ErrorException solve(ojp, SimpleTauLeaping(); dt = 0.01) +end + +@testset "General regular rates remain supported" begin + rate!(out, u, p, t) = (out[1] = 100 * u[1] / (1 + u[1])) + function change!(du, u, p, t, counts, mark) + du[1] = -counts[1] + du[2] = counts[1] + nothing + end + jp = JumpProblem( + DiscreteProblem([100.0, 0.0], (0.0, 0.1)), + PureLeaping(), RegularJump(rate!, change!, 1) + ) + for alg in regular_leaping_algs + opts = alg isa SimpleTauLeaping ? (; dt = 0.001, seed = 42) : + (; dt = 0.001, seed = 42, adaptive = false) + sol = solve(jp, alg; opts...) + @test successful_retcode(sol) + @test sol.u[end][2] > 0 + @test all(u -> sum(u) ≈ 100, sol.u) + end +end + +@testset "Single-reaction mass-action operations" begin + for (rate, reactants, net) in ( + (6.0, [1 => 3], [1 => -3, 2 => 1]), + (2.0, Pair{Int, Int}[], [1 => 1]), + ) + single = MassActionJump(rate, reactants, net) + vector = MassActionJump([rate], [reactants], [net]) + u = [5.0, 0.0] + @test massaction_rates!(zeros(1), single, u) == massaction_rates!(zeros(1), vector, u) + @test massaction_stoichiometry_mul!(zeros(2), single, [2.0]) == + massaction_stoichiometry_mul!(zeros(2), vector, [2.0]) + @test massaction_drift!(zeros(2), single, u) == massaction_drift!(zeros(2), vector, u) + end +end + +@testset "Large integer mass-action populations" begin + n = 3_000_000 + for single in (false, true), (rate, scale_rates) in ((1.0, true), (6, true), (1, false)) + reference = Float64(big(n) * (n - 1) * (n - 2)) * (scale_rates ? rate / 6 : rate) + maj = single ? MassActionJump(rate, [1 => 3], [1 => -3]; scale_rates) : + MassActionJump([rate], [[1 => 3]], [[1 => -3]]; scale_rates) + @test only(massaction_rates!(zeros(1), maj, [n])) ≈ reference + @test only(massaction_drift!(zeros(1), maj, [n])) ≈ -3 * reference + end +end + +@testset "Integer reaction counts with floating-point output" begin + maj = MassActionJump([1], [[1 => 1]], [[1 => -3]]; scale_rates = false) + count = typemax(Int) + @test massaction_stoichiometry_mul!(zeros(1), maj, [count]) == [-3 * Float64(count)] +end + +@testset "Single-reaction parameter-mapped operations" begin + for (reactants, net, u, expected_rate, expected_drift) in ( + ([1 => 1], [1 => -1, 2 => 1], [20, 0], 6.0, [-6.0, 6.0]), + ([1 => 3], [1 => -3, 2 => 1], [5, 0], 3.0, [-9.0, 3.0]), + (Pair{Int, Int}[], [1 => 1], [0], 0.3, [0.3]), + ), scale_rates in (true, false) + maj = MassActionJump(reactants, net; param_idxs = 1, scale_rates) + vector = MassActionJump([reactants], [net]; param_idxs = [1], scale_rates) + rate = scale_rates || length(reactants) == 0 ? expected_rate : + expected_rate * factorial(only(reactants).second) + drift = scale_rates || length(reactants) == 0 ? expected_drift : + expected_drift * factorial(only(reactants).second) + @test massaction_rates!(zeros(1), maj, u; p = [0.3]) ≈ [rate] + @test massaction_drift!(zeros(length(u)), maj, u; p = [0.3]) ≈ drift + @test massaction_stoichiometry_mul!(zeros(length(u)), maj, [2.0]) == + massaction_stoichiometry_mul!(zeros(length(u)), vector, [2.0]) + @test massaction_rates!(zeros(1), maj, u; p = [0.6]) ≈ [2rate] + @test maj.scaled_rates === nothing + end +end + +@testset "Integer rate constants in fixed-step leaping" begin + for scale_rates in (true, false) + rate = scale_rates ? 6 : 1 + integer_jump = MassActionJump([rate], [[1 => 3]], [[1 => -3]]; scale_rates) + float_jump = MassActionJump([Float64(rate)], [[1 => 3]], [[1 => -3]]; scale_rates) + prob = DiscreteProblem([3_000_000], (0.0, 1.0e-18)) + actual = solve( + JumpProblem(prob, PureLeaping(), integer_jump), SimpleTauLeaping(); + dt = 1.0e-18, seed = 123 + ) + expected = solve( + JumpProblem(prob, PureLeaping(), float_jump), SimpleTauLeaping(); + dt = 1.0e-18, seed = 123 + ) + @test successful_retcode(actual) + @test actual.u == expected.u + end +end diff --git a/test/runtests.jl b/test/runtests.jl index a31874971..c1beb24b9 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -27,6 +27,7 @@ end @time @safetestset "SSA Aggregator Smoke Tests" begin include("ssa_aggregator_smoke.jl") end @time @safetestset "SortingDirect retained search order" begin include("sortingdirect_reuse.jl") end @time @safetestset "Tau Leaping Tests" begin include("regular_jumps.jl") end + @time @safetestset "Mass-action leaping interface" begin include("massaction_leaping.jl") end @time @safetestset "Simple SSA Callback Test" begin include("ssa_callback_test.jl") end @time @safetestset "SIR Discrete Callback Test" begin include("sir_model.jl") end @time @safetestset "Callback Merging Tests" begin include("callbacks.jl") end @@ -70,6 +71,10 @@ end @time @safetestset "Spatial A + B <--> C" begin include("spatial/ABC.jl") end @time @safetestset "Spatially Varying Reaction Rates" begin include("spatial/spatial_majump.jl") end @time @safetestset "Pure diffusion" begin include("spatial/diffusion.jl") end + @time @safetestset "Fixed-step mass-action kernel on CPU" begin + include("massaction_fixed_tau_kernel.jl") + test_massaction_fixed_tau_kernel(CPU()) + end @time @safetestset "SSA kernel on the CPU backend" begin include("kernelabstractions_ssa.jl") end @time @safetestset "Explicit tau-leaping kernel on the CPU backend" begin include("kernelabstractions_explicit_tau.jl") end end @@ -82,6 +87,11 @@ end if GROUP == "CUDA" activate_gpu_env() + @time @safetestset "GPU fixed-step mass-action kernel" begin + using CUDA + include("massaction_fixed_tau_kernel.jl") + test_massaction_fixed_tau_kernel(CUDABackend()) + end @time @safetestset "GPU Tau Leaping test" begin include("gpu/regular_jumps.jl") end @time @safetestset "GPU SSA test" begin include("gpu/ssa.jl") end @time @safetestset "GPU Explicit Tau Leaping test" begin include("gpu/explicit_tau.jl") end