From 17a09f1117b17ecd6457e2e9166b1cde86d5edf0 Mon Sep 17 00:00:00 2001 From: ChrisRackauckas-Claude Date: Sat, 5 Sep 2026 08:08:23 -0400 Subject: [PATCH 1/6] Accept MassActionJump across tau-leaping solvers Generate the regular rate/update interface for pure discrete mass-action problems and support the fixed-step ensemble kernel. Preserve explicit RegularJump inputs for general kinetics. Co-Authored-By: Chris Rackauckas Co-Authored-By: Codex Agent-Harness: Codex CLI 0.153.4 Agent-Model: gpt-6-astra Agent-Session: local session ID 01a070e6-21f2-7dd3-bf52-2ddaf108ac53 --- docs/src/jump_solve.md | 41 ++++++++++- ext/JumpProcessesKernelAbstractionsExt.jl | 41 ++++++++++- ext/ssa_stepper.jl | 6 +- src/JumpProcesses.jl | 5 ++ src/massaction_rates.jl | 36 +++++++++ src/problem.jl | 11 ++- src/simple_regular_solve.jl | 16 ++-- test/massaction_fixed_tau_kernel.jl | 25 +++++++ test/massaction_leaping.jl | 89 +++++++++++++++++++++++ test/runtests.jl | 10 +++ 10 files changed, 266 insertions(+), 14 deletions(-) create mode 100644 test/massaction_fixed_tau_kernel.jl create mode 100644 test/massaction_leaping.jl diff --git a/docs/src/jump_solve.md b/docs/src/jump_solve.md index 41ac44124..5b63eb396 100644 --- a/docs/src/jump_solve.md +++ b/docs/src/jump_solve.md @@ -15,7 +15,9 @@ 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. +τ-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()` @@ -71,10 +73,17 @@ 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`: adaptive Cao tau selection. + - `ImplicitTauLeaping`: implicit tau-leaping. + - `ThetaTrapezoidalTauLeaping`: implicit theta-trapezoidal tau-leaping. + +All four also accept `JumpProblem(prob, PureLeaping(), mass_action_jump)` directly. +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. @@ -87,3 +96,31 @@ 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, as well as +StochasticDiffEq's leaping solvers: + +```@example common_massaction +using JumpProcesses, StochasticDiffEq + +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()) +regular_sol = solve(jprob, TauLeaping()) +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. diff --git a/ext/JumpProcessesKernelAbstractionsExt.jl b/ext/JumpProcessesKernelAbstractionsExt.jl index 5df7b3876..5e3e1cf17 100644 --- a/ext/JumpProcessesKernelAbstractionsExt.jl +++ b/ext/JumpProcessesKernelAbstractionsExt.jl @@ -27,7 +27,7 @@ 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.") + error("SimpleTauLeaping requires a PureLeaping JumpProblem with a MassActionJump or a RegularJump.") prob = jump_prob.prob probs = [remake(jump_prob) for _ in 1:trajectories] @@ -81,6 +81,36 @@ struct JumpData{R, C} numjumps::Int end +Adapt.@adapt_structure JumpData + +struct GPUMassActionRate{M} + jump::M +end +Adapt.@adapt_structure GPUMassActionRate + +function (rate::GPUMassActionRate)(out, u, p, t) + for j in eachindex(out) + out[j] = gpu_evalrxrate(u, j, rate.jump, eltype(out)) + end + return nothing +end + +struct GPUMassActionChange{M} + jump::M +end +Adapt.@adapt_structure GPUMassActionChange + +function (change::GPUMassActionChange)(du, u, p, t, counts, mark) + fill!(du, zero(eltype(du))) + maj = change.jump + for j in eachindex(counts) + for k in maj.ns_offsets[j]:(maj.ns_offsets[j + 1] - 1) + du[maj.ns_species[k]] += maj.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), @@ -155,7 +185,12 @@ function vectorized_solve(probs, prob::JumpProblem, alg::SimpleTauLeaping; backend, trajectories, seed, dt, kwargs...) # Extract common jump data rj = prob.regular_jump - rj_data = JumpData(rj.rate, rj.c, rj.numjumps) + rj_data = if JumpProcesses.is_massaction_regular_jump(rj, prob.massaction_jump) + maj = GPUMassActionJump(prob.massaction_jump, backend, float(eltype(prob.prob.tspan))) + JumpData(GPUMassActionRate(maj), GPUMassActionChange(maj), rj.numjumps) + 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) @@ -183,7 +218,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/ext/ssa_stepper.jl b/ext/ssa_stepper.jl index 7e6d14823..e14f97fec 100644 --- a/ext/ssa_stepper.jl +++ b/ext/ssa_stepper.jl @@ -221,7 +221,11 @@ function validate_gpu_massaction_inputs(jump_prob::JumpProblem) JumpProcesses.get_num_majumps(jump_prob.massaction_jump) > 0 && isempty(jump_prob.constant_jumps) && isempty(jump_prob.variable_jumps) && - jump_prob.regular_jump === nothing && + ( + jump_prob.regular_jump === nothing || JumpProcesses.is_massaction_regular_jump( + jump_prob.regular_jump, jump_prob.massaction_jump + ) + ) && isempty(jump_prob.jump_callback.continuous_callbacks) && length(jump_prob.jump_callback.discrete_callbacks) <= 1 end diff --git a/src/JumpProcesses.jl b/src/JumpProcesses.jl index 80acf38f1..166df5c8a 100644 --- a/src/JumpProcesses.jl +++ b/src/JumpProcesses.jl @@ -139,6 +139,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 and StochasticDiffEq. The rates and count-based updates are + supplied automatically; no user-written `RegularJump` is required. + - `SimpleTauLeaping` and StochasticDiffEq's leaping algorithms additionally accept + 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 06d4dfa8c..f1824cb27 100644 --- a/src/massaction_rates.jl +++ b/src/massaction_rates.jl @@ -158,3 +158,39 @@ function add_self_dependencies!(dg; dosort = true) end end end + +struct MassActionRate{M} + jump::M +end + +function (rate::MassActionRate)(out, u, p, t) + for j in eachindex(out) + out[j] = evalrxrate(u, j, rate.jump) + end + return nothing +end + +struct MassActionChange{M} + jump::M +end + +function (change::MassActionChange)(du, u, p, t, counts, mark) + fill!(du, zero(eltype(du))) + for j in eachindex(counts) + for (species, coefficient) in change.jump.net_stoch[j] + du[species] += coefficient * counts[j] + end + end + return nothing +end + +function massaction_regular_jump(maj::MassActionJump) + return RegularJump{true}(MassActionRate(maj), MassActionChange(maj), get_num_majumps(maj)) +end + +is_massaction_regular_jump(::Any, maj) = false +function is_massaction_regular_jump( + rj::RegularJump{true, <:MassActionRate, <:MassActionChange}, maj + ) + return rj.rate.jump === maj && rj.c.jump === maj +end diff --git a/src/problem.jl b/src/problem.jl index 008dab179..b0ec4882f 100644 --- a/src/problem.jl +++ b/src/problem.jl @@ -350,13 +350,18 @@ function JumpProblem(prob, aggregator::PureLeaping, jumps::JumpSet; crjs = jumps.constant_jumps vrjs = jumps.variable_jumps - iip = isinplace_jump(prob, jumps.regular_jump) + rj = jumps.regular_jump + if rj === nothing && prob isa DiscreteProblem && get_num_majumps(maj) > 0 + rj = massaction_regular_jump(maj) + end + iip = isinplace_jump(prob, rj) solkwargs = tstops === nothing ? make_kwarg(; callback) : make_kwarg(; callback, tstops) JumpProblem{iip, typeof(prob), typeof(aggregator), typeof(jump_cbs), - typeof(disc_agg), typeof(crjs), typeof(vrjs), typeof(jumps.regular_jump), + typeof(disc_agg), typeof(crjs), typeof(vrjs), typeof(rj), typeof(maj), typeof(rng), typeof(solkwargs)}(prob, aggregator, disc_agg, - jump_cbs, crjs, vrjs, jumps.regular_jump, maj, rng, solkwargs) + jump_cbs, crjs, vrjs, rj, maj, rng, solkwargs + ) end aggregator(jp::JumpProblem{iip, P, A}) where {iip, P, A} = A diff --git a/src/simple_regular_solve.jl b/src/simple_regular_solve.jl index 4e25f6239..93a4b7ae2 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 @@ -241,7 +244,10 @@ function validate_pure_leaping_inputs(jump_prob::JumpProblem, alg) 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 && + ( + get_num_majumps(jump_prob.massaction_jump) == 0 || + is_massaction_regular_jump(jump_prob.regular_jump, jump_prob.massaction_jump) + ) && jump_prob.regular_jump !== nothing end @@ -304,7 +310,7 @@ function DiffEqBase.solve(jump_prob::JumpProblem, alg::SimpleTauLeaping; seed = nothing, 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, rng) = jump_prob (seed !== nothing) && seed!(rng, seed) diff --git a/test/massaction_fixed_tau_kernel.jl b/test/massaction_fixed_tau_kernel.jl new file mode 100644 index 000000000..e6c7804fb --- /dev/null +++ b/test/massaction_fixed_tau_kernel.jl @@ -0,0 +1,25 @@ +using JumpProcesses, KernelAbstractions, Adapt, Test, Statistics + +function test_massaction_fixed_tau_kernel(backend) + return @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 +end diff --git a/test/massaction_leaping.jl b/test/massaction_leaping.jl new file mode 100644 index 000000000..a69384030 --- /dev/null +++ b/test/massaction_leaping.jl @@ -0,0 +1,89 @@ +using JumpProcesses, StochasticDiffEq, Test, StableRNGs + +regular_leaping_algs = ( + SimpleTauLeaping(), TauLeaping(), CaoTauLeaping(), + ImplicitTauLeaping(), ThetaTrapezoidalTauLeaping(), +) + +@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 (alg isa Union{TauLeaping, CaoTauLeaping} ? (false, true) : (false,)) + @testset "$(nameof(typeof(alg))), adaptive=$adaptive" begin + actual = JumpProblem(prob, PureLeaping(), maj; rng = StableRNG(123)) + reference = JumpProblem(prob, PureLeaping(), rj; rng = StableRNG(123)) + 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 "Generated mass-action rate and update" 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) + out = fill(NaN, 2) + jp.regular_jump.rate(out, [5.0, 0.0], nothing, 0.0) + @test out == [2.0, scale_rates ? 60.0 : 360.0] + jp.regular_jump.rate(out, [1.0, 0.0], nothing, 0.0) + @test out == [2.0, 0.0] + du = fill(NaN, 2) + jp.regular_jump.c(du, [5.0, 0.0], nothing, 0.0, [4.0, 2.0], nothing) + @test du == [-2.0, 2.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) + remade.regular_jump.rate(out, remade.prob.u0, remade.prob.p, 0.0) + @test out == [6.0] + 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 diff --git a/test/runtests.jl b/test/runtests.jl index c9f655b9e..05e894e77 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -24,6 +24,7 @@ end @time @safetestset "Split Coupled Tests" begin include("splitcoupled.jl") end @time @safetestset "SSA Tests" begin include("ssa_tests.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 @@ -57,12 +58,21 @@ 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 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 From 0a9127721d30036596364c7cf531dddd6d11a552 Mon Sep 17 00:00:00 2001 From: ChrisRackauckas-Claude Date: Sat, 12 Sep 2026 05:14:12 -0400 Subject: [PATCH 2/6] Preserve mass-action data for solver-owned leaping implementations Remove constructor conversion to RegularJump. Use native mass-action data in fixed-step CPU and GPU solves and expose propensity, stoichiometry, and fused drift operations for downstream solvers, including single-reaction inputs. Co-Authored-By: Chris Rackauckas Co-Authored-By: Codex Agent-Harness: Codex CLI 0.153.4 Agent-Model: gpt-6-astra Agent-Session: local session ID 01a070e6-21f2-7dd3-bf52-2ddaf108ac53 --- AGENTS.md | 6 ++ docs/src/jump_solve.md | 12 ++- docs/src/jump_types.md | 13 ++++ ext/JumpProcessesKernelAbstractionsExt.jl | 39 ++++------ ext/ssa_stepper.jl | 6 +- src/JumpProcesses.jl | 9 ++- src/massaction_rates.jl | 91 +++++++++++++++++------ src/problem.jl | 3 - src/simple_regular_solve.jl | 21 +++--- test/massaction_leaping.jl | 45 ++++++++--- 10 files changed, 159 insertions(+), 86 deletions(-) create mode 100644 AGENTS.md diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 000000000..a74ac2687 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,6 @@ +# Jump representations + +Preserve `MassActionJump` in `JumpProblem`. Each solver owns any conversion or +specialization of reaction data. Do not normalize mass-action jumps into +`RegularJump` in the problem constructor; keep general-rate support as a separate +solver path. diff --git a/docs/src/jump_solve.md b/docs/src/jump_solve.md index 5b63eb396..3488d50e8 100644 --- a/docs/src/jump_solve.md +++ b/docs/src/jump_solve.md @@ -15,7 +15,8 @@ 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 can be defined as `MassActionJump`s with `PureLeaping()`. +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. @@ -73,11 +74,10 @@ 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`: adaptive Cao tau selection. + - `CaoTauLeaping`: use fixed steps (`dt`, `adaptive = false`); its adaptive step selector is incomplete. - `ImplicitTauLeaping`: implicit tau-leaping. - `ThetaTrapezoidalTauLeaping`: implicit theta-trapezoidal tau-leaping. -All four also accept `JumpProblem(prob, PureLeaping(), mass_action_jump)` directly. For fixed steps with the implicit methods, pass `dt` and `adaptive = false`. ### JumpProcesses.jl @@ -100,11 +100,10 @@ and the jump process has designed a regular jump. ## Common mass-action input The same mass-action problem can be used with JumpProcesses' fixed-step, adaptive -explicit, implicit, trapezoidal, and switching solvers, as well as -StochasticDiffEq's leaping solvers: +explicit, implicit, trapezoidal, and switching solvers: ```@example common_massaction -using JumpProcesses, StochasticDiffEq +using JumpProcesses maj = MassActionJump([0.1], [[1 => 1]], [[1 => -1, 2 => 1]]) prob = DiscreteProblem([1000.0, 0.0], (0.0, 1.0)) @@ -115,7 +114,6 @@ explicit_sol = solve(jprob, SimpleExplicitTauLeaping()) implicit_sol = solve(jprob, SimpleImplicitTauLeaping()) trapezoidal_sol = solve(jprob, SimpleTrapezoidalLeaping()) switching_sol = solve(jprob, SimpleAdaptiveTauLeaping()) -regular_sol = solve(jprob, TauLeaping()) nothing # hide ``` diff --git a/docs/src/jump_types.md b/docs/src/jump_types.md index 181964d91..efc9eb866 100644 --- a/docs/src/jump_types.md +++ b/docs/src/jump_types.md @@ -505,3 +505,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 5e3e1cf17..c6cb67c86 100644 --- a/ext/JumpProcessesKernelAbstractionsExt.jl +++ b/ext/JumpProcessesKernelAbstractionsExt.jl @@ -83,29 +83,23 @@ end Adapt.@adapt_structure JumpData -struct GPUMassActionRate{M} - jump::M -end -Adapt.@adapt_structure GPUMassActionRate +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 (rate::GPUMassActionRate)(out, u, p, t) +function leaping_rates!(out, jump::GPUMassActionJump, u, p, t) for j in eachindex(out) - out[j] = gpu_evalrxrate(u, j, rate.jump, eltype(out)) + out[j] = gpu_evalrxrate(u, j, jump, eltype(out)) end return nothing end -struct GPUMassActionChange{M} - jump::M -end -Adapt.@adapt_structure GPUMassActionChange - -function (change::GPUMassActionChange)(du, u, p, t, counts, mark) +function leaping_change!(du, jump::GPUMassActionJump, u, p, t, counts) fill!(du, zero(eltype(du))) - maj = change.jump for j in eachindex(counts) - for k in maj.ns_offsets[j]:(maj.ns_offsets[j + 1] - 1) - du[maj.ns_species[k]] += maj.ns_coeffs[k] * counts[j] + 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 @@ -133,9 +127,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) @@ -160,7 +152,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 @@ -169,7 +161,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 @@ -185,9 +177,8 @@ function vectorized_solve(probs, prob::JumpProblem, alg::SimpleTauLeaping; backend, trajectories, seed, dt, kwargs...) # Extract common jump data rj = prob.regular_jump - rj_data = if JumpProcesses.is_massaction_regular_jump(rj, prob.massaction_jump) - maj = GPUMassActionJump(prob.massaction_jump, backend, float(eltype(prob.prob.tspan))) - JumpData(GPUMassActionRate(maj), GPUMassActionChange(maj), rj.numjumps) + rj_data = if rj === nothing + GPUMassActionJump(prob.massaction_jump, backend, float(eltype(prob.prob.tspan))) else JumpData(rj.rate, rj.c, rj.numjumps) end @@ -206,7 +197,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" diff --git a/ext/ssa_stepper.jl b/ext/ssa_stepper.jl index e14f97fec..7e6d14823 100644 --- a/ext/ssa_stepper.jl +++ b/ext/ssa_stepper.jl @@ -221,11 +221,7 @@ function validate_gpu_massaction_inputs(jump_prob::JumpProblem) JumpProcesses.get_num_majumps(jump_prob.massaction_jump) > 0 && isempty(jump_prob.constant_jumps) && isempty(jump_prob.variable_jumps) && - ( - jump_prob.regular_jump === nothing || JumpProcesses.is_massaction_regular_jump( - jump_prob.regular_jump, jump_prob.massaction_jump - ) - ) && + jump_prob.regular_jump === nothing && isempty(jump_prob.jump_callback.continuous_callbacks) && length(jump_prob.jump_callback.discrete_callbacks) <= 1 end diff --git a/src/JumpProcesses.jl b/src/JumpProcesses.jl index 166df5c8a..fdbd4202b 100644 --- a/src/JumpProcesses.jl +++ b/src/JumpProcesses.jl @@ -71,6 +71,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") @@ -140,10 +141,10 @@ 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 and StochasticDiffEq. The rates and count-based updates are - supplied automatically; no user-written `RegularJump` is required. - - `SimpleTauLeaping` and StochasticDiffEq's leaping algorithms additionally accept - a `RegularJump` for more general rates and updates. + 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 f1824cb27..657eea164 100644 --- a/src/massaction_rates.jl +++ b/src/massaction_rates.jl @@ -159,38 +159,87 @@ function add_self_dependencies!(dg; dosort = true) end end -struct MassActionRate{M} - jump::M -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,)) -function (rate::MassActionRate)(out, u, p, t) - for j in eachindex(out) - out[j] = evalrxrate(u, j, rate.jump) +""" + massaction_rates!(rates, jump::MassActionJump, u) + +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. Rate constants must already +be initialized; for parameter-dependent rates, use the mass-action jump stored +in a `JumpProblem`. +""" +function massaction_rates!(rates, jump::MassActionJump, u) + constants, reactants, _ = massaction_data(jump) + for j in eachindex(constants) + rates[j] = massaction_propensity(constants, reactants, u, j) end - return nothing + return rates end -struct MassActionChange{M} - jump::M +@inline function massaction_propensity(constants, reactants, u, j) + rate = one(eltype(u)) + 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 -function (change::MassActionChange)(du, u, p, t, counts, mark) +""" + 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))) - for j in eachindex(counts) - for (species, coefficient) in change.jump.net_stoch[j] + _, _, stoichiometry = massaction_data(jump) + for j in eachindex(stoichiometry) + for (species, coefficient) in stoichiometry[j] du[species] += coefficient * counts[j] end end - return nothing + return du end -function massaction_regular_jump(maj::MassActionJump) - return RegularJump{true}(MassActionRate(maj), MassActionChange(maj), get_num_majumps(maj)) +""" + massaction_drift!(du, jump::MassActionJump, u) + +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. Initialize rate constants as +for [`massaction_rates!`](@ref). +""" +function massaction_drift!(du, jump::MassActionJump, u) + fill!(du, zero(eltype(du))) + constants, reactants, stoichiometry = massaction_data(jump) + for j in eachindex(constants) + rate = massaction_propensity(constants, reactants, u, j) + for (species, coefficient) in stoichiometry[j] + du[species] += coefficient * rate + end + end + return du end -is_massaction_regular_jump(::Any, maj) = false -function is_massaction_regular_jump( - rj::RegularJump{true, <:MassActionRate, <:MassActionChange}, maj - ) - return rj.rate.jump === maj && rj.c.jump === maj -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) +leaping_change!(du, jump::MassActionJump, u, p, t, counts, mark) = + massaction_stoichiometry_mul!(du, jump, counts) +leaping_change!(du, jump::RegularJump, u, p, t, counts, mark) = + jump.c(du, u, p, t, counts, mark) +leaping_num_jumps(jump::MassActionJump) = get_num_majumps(jump) +leaping_num_jumps(jump::RegularJump) = jump.numjumps diff --git a/src/problem.jl b/src/problem.jl index b0ec4882f..66d185e93 100644 --- a/src/problem.jl +++ b/src/problem.jl @@ -351,9 +351,6 @@ function JumpProblem(prob, aggregator::PureLeaping, jumps::JumpSet; vrjs = jumps.variable_jumps rj = jumps.regular_jump - if rj === nothing && prob isa DiscreteProblem && get_num_majumps(maj) > 0 - rj = massaction_regular_jump(maj) - end iip = isinplace_jump(prob, rj) solkwargs = tstops === nothing ? make_kwarg(; callback) : make_kwarg(; callback, tstops) diff --git a/src/simple_regular_solve.jl b/src/simple_regular_solve.jl index 93a4b7ae2..b052fcace 100644 --- a/src/simple_regular_solve.jl +++ b/src/simple_regular_solve.jl @@ -240,15 +240,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 || - is_massaction_regular_jump(jump_prob.regular_jump, jump_prob.massaction_jump) - ) && + xor( + get_num_majumps(jump_prob.massaction_jump) > 0, jump_prob.regular_jump !== nothing + ) end function validate_pure_leaping_inputs( @@ -316,11 +316,10 @@ function DiffEqBase.solve(jump_prob::JumpProblem, alg::SimpleTauLeaping; (seed !== nothing) && seed!(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 ? jump_prob.massaction_jump : 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 @@ -352,10 +351,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_leaping.jl b/test/massaction_leaping.jl index a69384030..50d0911d5 100644 --- a/test/massaction_leaping.jl +++ b/test/massaction_leaping.jl @@ -1,9 +1,6 @@ -using JumpProcesses, StochasticDiffEq, Test, StableRNGs +using JumpProcesses, Test, StableRNGs, ForwardDiff -regular_leaping_algs = ( - SimpleTauLeaping(), TauLeaping(), CaoTauLeaping(), - ImplicitTauLeaping(), ThetaTrapezoidalTauLeaping(), -) +regular_leaping_algs = (SimpleTauLeaping(),) @testset "Mass-action input for regular leaping solvers" begin maj = MassActionJump( @@ -23,7 +20,7 @@ regular_leaping_algs = ( end rj = RegularJump(rate!, change!, 2) for alg in regular_leaping_algs, - adaptive in (alg isa Union{TauLeaping, CaoTauLeaping} ? (false, true) : (false,)) + adaptive in (false,) @testset "$(nameof(typeof(alg))), adaptive=$adaptive" begin actual = JumpProblem(prob, PureLeaping(), maj; rng = StableRNG(123)) reference = JumpProblem(prob, PureLeaping(), rj; rng = StableRNG(123)) @@ -39,28 +36,39 @@ regular_leaping_algs = ( end end -@testset "Generated mass-action rate and update" begin +@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) - jp.regular_jump.rate(out, [5.0, 0.0], nothing, 0.0) + massaction_rates!(out, jp.massaction_jump, [5.0, 0.0]) @test out == [2.0, scale_rates ? 60.0 : 360.0] - jp.regular_jump.rate(out, [1.0, 0.0], nothing, 0.0) + massaction_rates!(out, jp.massaction_jump, [1.0, 0.0]) @test out == [2.0, 0.0] du = fill(NaN, 2) - jp.regular_jump.c(du, [5.0, 0.0], nothing, 0.0, [4.0, 2.0], nothing) + 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) - remade.regular_jump.rate(out, remade.prob.u0, remade.prob.p, 0.0) + massaction_rates!(out, remade.massaction_jump, remade.prob.u0) @test out == [6.0] + @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 @@ -87,3 +95,18 @@ end @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 From 26f76554509c50c0e28fda1392f6b32fdf3c6a17 Mon Sep 17 00:00:00 2001 From: ChrisRackauckas-Claude Date: Sat, 26 Sep 2026 15:59:10 -0400 Subject: [PATCH 3/6] Retain the 9.34 mass-action leaping release entry Co-Authored-By: Chris Rackauckas Co-Authored-By: Codex Agent-Harness: Codex CLI 0.157.1 Agent-Model: gpt-6-luna Agent-Session: local session, transcript at /home/crackauc/sandbox/goals/issue-backlog/adopt/SciML_JumpProcesses.jl-652/log.txt on amdci2.julia.csail.mit.edu --- HISTORY.md | 9 +++++++++ Project.toml | 2 +- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/HISTORY.md b/HISTORY.md index 2929b9f5b..5901498da 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -2,6 +2,15 @@ ## JumpProcesses unreleased (master branch) +## 9.34 + + - Preserve `MassActionJump` in `JumpProblem` for tau-leaping instead of converting + to `RegularJump`. `SimpleTauLeaping` consumes native mass-action rates and + stoichiometry on CPU and in KernelAbstractions kernels; explicit `RegularJump` + input remains supported ([#652](https://github.com/SciML/JumpProcesses.jl/pull/652)). + - Added public `massaction_rates!`, `massaction_stoichiometry_mul!`, and + `massaction_drift!` operations for downstream leaping solvers. + ## 9.33.1 - Fixed `SSAStepper` saving the wrong state at the final requested `saveat` diff --git a/Project.toml b/Project.toml index 9c002e4fc..e293f4ac4 100644 --- a/Project.toml +++ b/Project.toml @@ -1,7 +1,7 @@ name = "JumpProcesses" uuid = "ccbc3e58-028d-4f4c-8cd5-9ae44345cda5" authors = ["Chris Rackauckas "] -version = "9.33.1" +version = "9.34.0" [deps] ADTypes = "47edcb42-4c32-4615-8424-f2b9edc5f35b" From 67a81786c66c88659211a1fcd9fd1ab3647ca5ae Mon Sep 17 00:00:00 2001 From: ChrisRackauckas-Claude Date: Sat, 26 Sep 2026 20:12:14 -0400 Subject: [PATCH 4/6] Address review: drop Runic sweep artifacts and clarify GPU param rates Reject EnsembleGPUKernel SimpleTauLeaping when MassActionJump rates depend on parameters and a custom prob_func would vary p, wire prob_func for per-trajectory RegularJump p, and document that insufficient reactants zero the propensity so tau-leaping undershoots stay put. Co-Authored-By: Chris Rackauckas Co-Authored-By: Cursor Agent Agent-Harness: Cursor Agent CLI Agent-Model: auto Agent-Session: local session, transcript at /home/crackauc/sandbox/goals/issue-backlog/adopt/SciML_JumpProcesses.jl-652/log.txt on amdci2.julia.csail.mit.edu --- ext/JumpProcessesKernelAbstractionsExt.jl | 22 ++++++++++++++++++++-- src/massaction_rates.jl | 12 ++++++++++++ test/massaction_fixed_tau_kernel.jl | 23 ++++++++++++++++++++++- 3 files changed, 54 insertions(+), 3 deletions(-) diff --git a/ext/JumpProcessesKernelAbstractionsExt.jl b/ext/JumpProcessesKernelAbstractionsExt.jl index c6cb67c86..10458f8da 100644 --- a/ext/JumpProcessesKernelAbstractionsExt.jl +++ b/ext/JumpProcessesKernelAbstractionsExt.jl @@ -28,9 +28,27 @@ function SciMLBase.__solve(ensembleprob::SciMLBase.AbstractEnsembleProblem, # Validate that this is a PureLeaping JumpProblem JumpProcesses.validate_pure_leaping_inputs(jump_prob, alg) || error("SimpleTauLeaping requires a PureLeaping JumpProblem with a MassActionJump or a RegularJump.") - prob = jump_prob.prob - probs = [remake(jump_prob) for _ in 1:trajectories] + # 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 + + # Apply `prob_func` so RegularJump rates see per-trajectory `p` (and so + # mass-action trajectories can still vary `u0` / `tspan`). + probs = map(1:trajectories) do i + ctx = SciMLBase.EnsembleContext(i, 1, 0, nothing, nothing, nothing) + _prob = ensembleprob.safetycopy ? deepcopy(jump_prob) : jump_prob + ensembleprob.prob_func(_prob, ctx) + end # Run vectorized solve ts, diff --git a/src/massaction_rates.jl b/src/massaction_rates.jl index 657eea164..c437274f1 100644 --- a/src/massaction_rates.jl +++ b/src/massaction_rates.jl @@ -182,6 +182,18 @@ function massaction_rates!(rates, jump::MassActionJump, u) return rates end +""" + massaction_propensity(constants, reactants, u, j) + +Propensity of reaction `j` at populations `u`, using combinatorially scaled +`constants` and falling-factorial rate laws from `reactants`. + +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) rate = one(eltype(u)) for (species, order) in reactants[j] diff --git a/test/massaction_fixed_tau_kernel.jl b/test/massaction_fixed_tau_kernel.jl index e6c7804fb..525c02d1f 100644 --- a/test/massaction_fixed_tau_kernel.jl +++ b/test/massaction_fixed_tau_kernel.jl @@ -1,7 +1,7 @@ using JumpProcesses, KernelAbstractions, Adapt, Test, Statistics function test_massaction_fixed_tau_kernel(backend) - return @testset "Fixed-step mass-action kernel ($T)" for T in (Float64, Int) + @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( @@ -22,4 +22,25 @@ function test_massaction_fixed_tau_kernel(backend) ) @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 + return nothing end From 087b42c9bec5129ac2b9741658821c7d6027cbf4 Mon Sep 17 00:00:00 2001 From: ChrisRackauckas-Claude Date: Sat, 26 Sep 2026 22:33:35 -0400 Subject: [PATCH 5/6] Address round-2 review: format, RegularJump p test, drop AGENTS.md Revert the non-functional PureLeaping rename/reflow in problem.jl, format new leaping code with JuliaFormatter SciML style, add a RegularJump EnsembleGPUKernel test that varies p via prob_func, and remove AGENTS.md from this PR. Co-Authored-By: Chris Rackauckas Co-Authored-By: Cursor Agent Agent-Harness: Cursor Agent CLI Agent-Model: auto Agent-Session: local session, transcript at /home/crackauc/sandbox/goals/issue-backlog/adopt/SciML_JumpProcesses.jl-652/log.txt on amdci2.julia.csail.mit.edu --- AGENTS.md | 6 ----- ext/JumpProcessesKernelAbstractionsExt.jl | 3 +-- src/massaction_rates.jl | 14 +++++++----- src/problem.jl | 8 +++---- src/simple_regular_solve.jl | 16 +++++++------- test/massaction_fixed_tau_kernel.jl | 27 +++++++++++++++++++++++ 6 files changed, 47 insertions(+), 27 deletions(-) delete mode 100644 AGENTS.md diff --git a/AGENTS.md b/AGENTS.md deleted file mode 100644 index a74ac2687..000000000 --- a/AGENTS.md +++ /dev/null @@ -1,6 +0,0 @@ -# Jump representations - -Preserve `MassActionJump` in `JumpProblem`. Each solver owns any conversion or -specialization of reaction data. Do not normalize mass-action jumps into -`RegularJump` in the problem constructor; keep general-rate support as a separate -solver path. diff --git a/ext/JumpProcessesKernelAbstractionsExt.jl b/ext/JumpProcessesKernelAbstractionsExt.jl index 10458f8da..cd10e1b8f 100644 --- a/ext/JumpProcessesKernelAbstractionsExt.jl +++ b/ext/JumpProcessesKernelAbstractionsExt.jl @@ -103,8 +103,7 @@ 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) +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) diff --git a/src/massaction_rates.jl b/src/massaction_rates.jl index c437274f1..28e2a535c 100644 --- a/src/massaction_rates.jl +++ b/src/massaction_rates.jl @@ -159,10 +159,10 @@ function add_self_dependencies!(dg; dosort = true) end 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) = ( + jump.scaled_rates, jump.reactant_stoch, jump.net_stoch) +@inline massaction_data(jump::MassActionJump{<:Number}) = ( + (jump.scaled_rates,), (jump.reactant_stoch,), (jump.net_stoch,)) """ massaction_rates!(rates, jump::MassActionJump, u) @@ -249,9 +249,11 @@ 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) -leaping_change!(du, jump::MassActionJump, u, p, t, counts, mark) = +function leaping_change!(du, jump::MassActionJump, u, p, t, counts, mark) massaction_stoichiometry_mul!(du, jump, counts) -leaping_change!(du, jump::RegularJump, u, p, t, counts, mark) = +end +function leaping_change!(du, jump::RegularJump, u, p, t, counts, mark) 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/problem.jl b/src/problem.jl index 66d185e93..008dab179 100644 --- a/src/problem.jl +++ b/src/problem.jl @@ -350,15 +350,13 @@ function JumpProblem(prob, aggregator::PureLeaping, jumps::JumpSet; crjs = jumps.constant_jumps vrjs = jumps.variable_jumps - rj = jumps.regular_jump - iip = isinplace_jump(prob, rj) + iip = isinplace_jump(prob, jumps.regular_jump) solkwargs = tstops === nothing ? make_kwarg(; callback) : make_kwarg(; callback, tstops) JumpProblem{iip, typeof(prob), typeof(aggregator), typeof(jump_cbs), - typeof(disc_agg), typeof(crjs), typeof(vrjs), typeof(rj), + typeof(disc_agg), typeof(crjs), typeof(vrjs), typeof(jumps.regular_jump), typeof(maj), typeof(rng), typeof(solkwargs)}(prob, aggregator, disc_agg, - jump_cbs, crjs, vrjs, rj, maj, rng, solkwargs - ) + jump_cbs, crjs, vrjs, jumps.regular_jump, maj, rng, solkwargs) end aggregator(jp::JumpProblem{iip, P, A}) where {iip, P, A} = A diff --git a/src/simple_regular_solve.jl b/src/simple_regular_solve.jl index b052fcace..245ec8e1d 100644 --- a/src/simple_regular_solve.jl +++ b/src/simple_regular_solve.jl @@ -241,14 +241,14 @@ function validate_pure_leaping_inputs(jump_prob::JumpProblem, alg) Passing $(jump_prob.aggregator) is deprecated and will be removed in the next breaking release." end 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) && - xor( - get_num_majumps(jump_prob.massaction_jump) > 0, - jump_prob.regular_jump !== nothing - ) + isempty(jump_prob.jump_callback.continuous_callbacks) && + isempty(jump_prob.jump_callback.discrete_callbacks) && + isempty(jump_prob.constant_jumps) && + isempty(jump_prob.variable_jumps) && + xor( + get_num_majumps(jump_prob.massaction_jump) > 0, + jump_prob.regular_jump !== nothing + ) end function validate_pure_leaping_inputs( diff --git a/test/massaction_fixed_tau_kernel.jl b/test/massaction_fixed_tau_kernel.jl index 525c02d1f..a13bac47a 100644 --- a/test/massaction_fixed_tau_kernel.jl +++ b/test/massaction_fixed_tau_kernel.jl @@ -42,5 +42,32 @@ function test_massaction_fixed_tau_kernel(backend) @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) + 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 + 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 = 1e-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 return nothing end From 590f977aaf2fef00d1d661d350841695b26c4102 Mon Sep 17 00:00:00 2001 From: ChrisRackauckas-Claude Date: Thu, 12 Nov 2026 06:33:19 -0500 Subject: [PATCH 6/6] Fix integer arithmetic and scalar mapped mass-action operations Promote propensity and stoichiometry products with the output scalar type. Normalize single-reaction parameter mappings before materializing working rates. Cover integer constants, large reaction counts, raw parameter mappings, and fixed-seed integer/floating solver equivalence. Co-Authored-By: Chris Rackauckas Co-Authored-By: Codex Agent-Harness: Codex CLI 0.164.0 Agent-Model: gpt-6.1-sol Agent-Session: local fixer job SciML__JumpProcesses.jl__652 (no session URL) --- src/massaction_rates.jl | 24 ++++++++++++----- test/massaction_leaping.jl | 54 +++++++++++++++++++++++++++++++++++--- 2 files changed, 67 insertions(+), 11 deletions(-) diff --git a/src/massaction_rates.jl b/src/massaction_rates.jl index b5790941d..1c6c970e6 100644 --- a/src/massaction_rates.jl +++ b/src/massaction_rates.jl @@ -160,6 +160,11 @@ function add_self_dependencies!(dg; dosort = true) 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) @@ -175,6 +180,9 @@ end @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) @@ -190,16 +198,17 @@ 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) + rates[j] = massaction_propensity(constants, reactants, u, j, eltype(rates)) end return rates end """ - massaction_propensity(constants, reactants, u, j) + 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`. +`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 @@ -207,8 +216,8 @@ 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) - rate = one(eltype(u)) * one(constants[j]) +@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) @@ -231,8 +240,9 @@ 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 * counts[j] + du[species] += coefficient * count end end return du @@ -253,7 +263,7 @@ function massaction_drift!(du, jump::MassActionJump, u; p = nothing) 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) + rate = massaction_propensity(constants, reactants, u, j, eltype(du)) for (species, coefficient) in stoichiometry[j] du[species] += coefficient * rate end diff --git a/test/massaction_leaping.jl b/test/massaction_leaping.jl index 3c1b7fe34..63da520a7 100644 --- a/test/massaction_leaping.jl +++ b/test/massaction_leaping.jl @@ -119,11 +119,57 @@ end @testset "Large integer mass-action populations" begin n = 3_000_000 - reference = Float64(binomial(big(n), 3)) - for single in (false, true) - maj = single ? MassActionJump(1.0, [1 => 3], [1 => -3]) : - MassActionJump([1.0], [[1 => 3]], [[1 => -3]]) + 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