From 91ae97031d50a666535bfb3950e5b9e6147144eb Mon Sep 17 00:00:00 2001 From: ChrisRackauckas-Claude Date: Sat, 5 Sep 2026 08:08:23 -0400 Subject: [PATCH 1/5] 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 --- Project.toml | 2 +- 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 +++ 11 files changed, 267 insertions(+), 15 deletions(-) create mode 100644 test/massaction_fixed_tau_kernel.jl create mode 100644 test/massaction_leaping.jl diff --git a/Project.toml b/Project.toml index f1c846740..29aa4c04c 100644 --- a/Project.toml +++ b/Project.toml @@ -1,7 +1,7 @@ name = "JumpProcesses" uuid = "ccbc3e58-028d-4f4c-8cd5-9ae44345cda5" authors = ["Chris Rackauckas "] -version = "9.32.3" +version = "9.33.0" [deps] ADTypes = "47edcb42-4c32-4615-8424-f2b9edc5f35b" 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 b51b6b151..528daf203 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 ae4a751adbe6021274925f8cf8381ec02074c162 Mon Sep 17 00:00:00 2001 From: ChrisRackauckas-Claude Date: Sat, 12 Sep 2026 05:14:12 -0400 Subject: [PATCH 2/5] 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 2d0e64814..be0cd2fd9 100644 --- a/docs/src/jump_types.md +++ b/docs/src/jump_types.md @@ -494,3 +494,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 528daf203..9fbf1f863 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 +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 c11b9fbef5e88f1b23b8890359cc19ab691d6525 Mon Sep 17 00:00:00 2001 From: ChrisRackauckas-Claude Date: Sat, 5 Sep 2026 06:06:14 -0400 Subject: [PATCH 3/5] Document GPU ensembles and tau-leaping solver interfaces 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/pages.jl | 2 + docs/src/jump_solve.md | 108 +++++++------- docs/src/jump_types.md | 6 +- .../tutorials/discrete_stochastic_example.md | 5 + docs/src/tutorials/gpu.md | 117 +++++++++++++++ docs/src/tutorials/tau_leaping.md | 135 ++++++++++++++++++ src/simple_regular_solve.jl | 8 +- 7 files changed, 329 insertions(+), 52 deletions(-) create mode 100644 docs/src/tutorials/gpu.md create mode 100644 docs/src/tutorials/tau_leaping.md diff --git a/docs/pages.jl b/docs/pages.jl index 1f973f241..641857c2d 100644 --- a/docs/pages.jl +++ b/docs/pages.jl @@ -3,6 +3,8 @@ pages = ["index.md", "Tutorials" => Any["tutorials/simple_poisson_process.md", "tutorials/discrete_stochastic_example.md", + "tutorials/tau_leaping.md", + "tutorials/gpu.md", "tutorials/point_process_simulation.md", "tutorials/jump_diffusion.md", "tutorials/spatial.md"], diff --git a/docs/src/jump_solve.md b/docs/src/jump_solve.md index 3488d50e8..98c789fe0 100644 --- a/docs/src/jump_solve.md +++ b/docs/src/jump_solve.md @@ -15,10 +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 -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. +τ-leaping methods can be defined as `RegularJump`s or `MassActionJump`s, with +`PureLeaping()` as the common mass-action interface (see the table below). There are special algorithms available for efficiently simulating an exact, pure `JumpProblem` (i.e., a `JumpProblem` over a `DiscreteProblem`). `SSAStepper()` @@ -36,10 +34,12 @@ usually faster, it only supports discrete events (`DiscreteCallback`s), for pure jump problems requiring continuous events (`ContinuousCallback`s) the less performant `FunctionMap` time-stepper can be used. -If there is a `RegularJump`, then inexact τ-leaping methods must be used. The -current recommended method is `TauLeaping` if one needs adaptivity, events, etc. -If one only needs the most barebones fixed time-step leaping method, then -`SimpleTauLeaping` can have performance benefits. +For a pure mass-action model, use `SimpleExplicitTauLeaping` for adaptive explicit +leaping, or one of the implicit methods below for stiff systems. For custom +`RegularJump` rates and updates, use `SimpleTauLeaping` for fixed steps or +StochasticDiffEq's `TauLeaping` for adaptive steps. See the +[tau-leaping tutorial](@ref tau_leaping_tutorial) for examples and the +[GPU tutorial](@ref gpu_ensembles) for ensemble execution. ## Special Methods for Pure Jump Problems @@ -66,26 +66,62 @@ algorithms are optimized for pure jump problems. interpolation, and can therefore exactly evaluate the sampled solution path at any time when only saving the post-jump state for each jump. -## RegularJump Compatible Methods +## Tau-Leaping Methods + +All tau-leaping methods below accept the same +`JumpProblem(prob, PureLeaping(), mass_action_jump)`, with `prob` a +`DiscreteProblem`. Some also accept a `RegularJump` for more general rates and +count-based updates. + +| Package | Algorithm | Jump representation | Step selection | +|:--------|:----------|:--------------------|:---------------| +| JumpProcesses | [`SimpleTauLeaping`](@ref) | `MassActionJump` or `RegularJump` | Fixed; requires `dt` | +| JumpProcesses | [`SimpleExplicitTauLeaping`](@ref) | `MassActionJump` | Adaptive explicit; `epsilon` | +| JumpProcesses | [`SimpleImplicitTauLeaping`](@ref) | `MassActionJump` | Adaptive implicit; `epsilon` | +| JumpProcesses | [`SimpleTrapezoidalLeaping`](@ref) | `MassActionJump` | Adaptive implicit trapezoidal; `epsilon` | +| JumpProcesses | [`SimpleAdaptiveTauLeaping`](@ref) | `MassActionJump` | Switches explicit/implicit; `epsilon` | +| StochasticDiffEq | `TauLeaping` | `MassActionJump` or `RegularJump` | Adaptive with post-leap estimates | +| StochasticDiffEq | `CaoTauLeaping` | `MassActionJump` or `RegularJump` | Adaptive Cao step selection | +| StochasticDiffEq | `ImplicitTauLeaping` | `MassActionJump` or `RegularJump` | Implicit; fixed steps with `dt`, `adaptive = false` | +| StochasticDiffEq | `ThetaTrapezoidalTauLeaping` | `MassActionJump` or `RegularJump` | Implicit theta-trapezoidal; fixed steps with `dt`, `adaptive = false` | -### StochasticDiffEq.jl - -These methods support mixing with event handling, other jump types, and all of -the features of the normal differential equation solvers. +### JumpProcesses.jl - - `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. +The `Simple*` methods listed above are streamlined solvers for pure jump problems: +construct a `DiscreteProblem` and use `PureLeaping()` as the aggregator. The +adaptive mass-action methods require a `MassActionJump`. All methods construct +the rates and stoichiometric updates from it without a user-written +`RegularJump`. They support `saveat`, `save_start`, and `save_end`. + +`SimpleImplicitTauLeaping` takes the deterministic part of a leap implicitly. +`SimpleTrapezoidalLeaping` averages current and new-state propensities in that +implicit solve. `SimpleAdaptiveTauLeaping` switches between explicit and implicit +steps based on a stiffness estimate. Its default implicit method is +`SimpleImplicitTauLeaping()`; select the trapezoidal formulation with +`implicit_alg = SimpleTrapezoidalLeaping()`. The default stiffness test uses the +spread of propensities; `eigenvalue_check = true` uses the drift Jacobian instead. +See the algorithm docstrings for the remaining tuning parameters. + +Smaller `epsilon` values generally select smaller leaps. This is a step-selection +parameter, not a guarantee of a specified error in an observable or distribution. +Check convergence of the quantities of interest as the leap size is reduced. +Fixed-step `SimpleTauLeaping` does not reject leaps that produce negative +populations, so choosing an appropriate `dt` is especially important. -For fixed steps with the implicit methods, pass `dt` and `adaptive = false`. +### StochasticDiffEq.jl -### JumpProcesses.jl +Load `StochasticDiffEq` to use its algorithms. These methods accept a +`MassActionJump` through `PureLeaping()`, or the same +[`RegularJump`](@ref) rate/count-update interface as `SimpleTauLeaping`, with +ordinary differential-equation integrator facilities such as callbacks. When +mixing regular jumps with separately aggregated jumps, select an aggregator such +as `Direct()` for those additional jumps; `PureLeaping()` bypasses aggregation. - - `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. +The similarly named implicit methods in the two packages are separate algorithms +with different formulations and options. In particular, +`StochasticDiffEq.ImplicitTauLeaping` is not an alias for +`JumpProcesses.SimpleImplicitTauLeaping`, and `ThetaTrapezoidalTauLeaping` is not +`SimpleTrapezoidalLeaping`. ## Regular Jump Diffusion Compatible Methods @@ -96,29 +132,3 @@ 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. diff --git a/docs/src/jump_types.md b/docs/src/jump_types.md index be0cd2fd9..1e3431c9c 100644 --- a/docs/src/jump_types.md +++ b/docs/src/jump_types.md @@ -55,8 +55,10 @@ These methods can be much faster as they do not need to simulate the realization of every individual jump event. τ-leaping methods trade accuracy for speed, and are best used when a set of jumps do not make significant changes to the processes' state and/or rates over the course of one time-step (i.e., during a -leap interval). A single [`RegularJump`](@ref) is used to encode jumps for -τ-leaping algorithms. While τ-leaping methods can be proven to converge in the +leap interval). A single [`RegularJump`](@ref) encodes custom rates and count-based +updates for τ-leaping algorithms. All tau-leaping methods accept a +[`MassActionJump`](@ref) directly through `PureLeaping()`; see +[Tau-Leaping Methods](@ref jump_solve). While τ-leaping methods can be proven to converge in the limit that the time-step approaches zero, their accuracy can be highly dependent on the chosen time-step. As a rule of thumb, if changes to the state variable `u` during a time-step (i.e., leap interval) are "minimal" compared to the size of diff --git a/docs/src/tutorials/discrete_stochastic_example.md b/docs/src/tutorials/discrete_stochastic_example.md index 99db5078d..afb69c92f 100644 --- a/docs/src/tutorials/discrete_stochastic_example.md +++ b/docs/src/tutorials/discrete_stochastic_example.md @@ -936,3 +936,8 @@ we use as follows: sol = solve(jump_prob, SimpleTauLeaping(); dt = 0.001) plot(sol; label = ["S(t)" "I(t)" "R(t)"]) ``` + +For adaptive explicit, implicit, and switching methods using `MassActionJump`, +and for the StochasticDiffEq solvers using this same `RegularJump` interface, +continue with the [tau-leaping tutorial](@ref tau_leaping_tutorial). +The [GPU tutorial](@ref gpu_ensembles) covers running ensembles on a GPU. diff --git a/docs/src/tutorials/gpu.md b/docs/src/tutorials/gpu.md new file mode 100644 index 000000000..4b899e61d --- /dev/null +++ b/docs/src/tutorials/gpu.md @@ -0,0 +1,117 @@ +# [GPU ensembles](@id gpu_ensembles) + +JumpProcesses provides [`EnsembleGPUKernel`](@ref) to run independent pure-jump +trajectories in parallel, with one trajectory per device thread. It uses +KernelAbstractions and Adapt; load both packages as well as your GPU backend. +The examples below use CUDA and require a working CUDA installation. They are +not executed during the documentation build. + +## Supported solvers and inputs + +| Solver | Jump representation | Required solve options | +|:-------|:--------------------|:-----------------------| +| `SSAStepper()` | `MassActionJump` | `trajectories`, `saveat` | +| `SimpleExplicitTauLeaping()` | `MassActionJump` | `trajectories`, `saveat` | +| `SimpleTauLeaping()` | `MassActionJump` or `RegularJump` | `trajectories`, `dt` | + +All three paths require a `DiscreteProblem`. `SSAStepper` simulates individual +reaction events exactly; the other two introduce tau-leaping error. There are no +`EnsembleGPUKernel` implementations for `SimpleImplicitTauLeaping`, +`SimpleTrapezoidalLeaping`, `SimpleAdaptiveTauLeaping`, or StochasticDiffEq's +tau-leaping algorithms. + +## Mass-action ensembles + +Construct the problem using ordinary host arrays. The ensemble implementation +transfers the reaction data to the device and returns solutions that can be +inspected on the CPU. + +```julia +using JumpProcesses, KernelAbstractions, Adapt, CUDA, Statistics + +maj = MassActionJump( + [0.1 / 1000.0, 0.01], + [[1 => 1, 2 => 1], [2 => 1]], + [[1 => -1, 2 => 1], [2 => -1, 3 => 1]] +) +prob = DiscreteProblem([999.0, 10.0, 0.0], (0.0, 250.0)) +jprob = JumpProblem(prob, PureLeaping(), maj) + +sol = solve( + EnsembleProblem(jprob), SimpleExplicitTauLeaping(; epsilon = 0.01), + EnsembleGPUKernel(CUDABackend()); trajectories = 10_000, saveat = 10.0 +) +mean(solution.u[end][3] for solution in sol.u) +``` + +`epsilon` controls adaptive leap selection. `saveat` specifies the output grid, +not a fixed leap size; the kernel shortens leaps to land on the next save time. +The SSA and adaptive explicit kernels require `saveat` (an interval or collection +of times), and support `save_start` and `save_end`. + +For an exact SSA ensemble of the same model, construct a problem with an SSA +aggregator and change the time-stepper: + +```julia +ssa_prob = JumpProblem(prob, Direct(), maj) +ssa_sol = solve( + EnsembleProblem(ssa_prob), SSAStepper(), EnsembleGPUKernel(CUDABackend()); + trajectories = 10_000, saveat = 10.0 +) +``` + +The `SSAStepper` and `SimpleExplicitTauLeaping` GPU kernels do not accept +`RegularJump`, `ConstantRateJump`, `VariableRateJump`, user callbacks, or an +ensemble `prob_func`. They share the +same initial condition and reaction data across trajectories. Use a CPU ensemble +such as `EnsembleThreads()` if these restrictions do not fit the model. + +## Fixed-step ensembles + +Use the same mass-action `jprob` from the first example with fixed steps: + +```julia +fixed_sol = solve( + EnsembleProblem(jprob), SimpleTauLeaping(), EnsembleGPUKernel(CUDABackend()); + trajectories = 10_000, dt = 0.1 +) +``` + +### More general rates with RegularJump + +The `SimpleTauLeaping` GPU kernel additionally supports the same `RegularJump` +interface as its CPU counterpart. Its rate and update functions must compile for the GPU: +use device-compatible operations and parameters, and write updates in place. + +```julia +using JumpProcesses, KernelAbstractions, Adapt, CUDA + +function rate!(out, u, p, t) + out[1] = p * u[1] / (1 + u[1]) + return nothing +end + +function change!(du, u, p, t, counts, mark) + du[1] = -counts[1] + du[2] = counts[1] + return nothing +end + +rj = RegularJump(rate!, change!, 1) +prob = DiscreteProblem([1000.0, 0.0], (0.0, 1.0), 100.0) +jprob = JumpProblem(prob, PureLeaping(), rj) +sol = solve( + EnsembleProblem(jprob), SimpleTauLeaping(), EnsembleGPUKernel(CUDABackend()); + trajectories = 10_000, dt = 0.01 +) +``` + +This fixed-step kernel saves the step grid; do not rely on the SSA and adaptive +explicit kernels' `saveat` controls here. Use a `dt` that divides the simulation interval. +It does not reject negative populations, and marked jumps, callbacks, and +per-trajectory problem customization are not supported by this path. + +`EnsembleGPUKernel()` without an explicit backend currently selects +KernelAbstractions' CPU backend. Pass `CUDABackend()` to request CUDA execution. +Other KernelAbstractions backends also need compatible device random-number +support; backend availability alone does not establish solver support. diff --git a/docs/src/tutorials/tau_leaping.md b/docs/src/tutorials/tau_leaping.md new file mode 100644 index 000000000..c062dfa9f --- /dev/null +++ b/docs/src/tutorials/tau_leaping.md @@ -0,0 +1,135 @@ +# [Tau-leaping with mass-action and regular jumps](@id tau_leaping_tutorial) + +Tau-leaping approximates many individual reaction events by a single update over +an interval. It introduces discretization error in addition to Monte Carlo +sampling error. Compare ensembles and repeat with smaller steps or tighter +step-selection parameters when assessing accuracy. + +## Adaptive mass-action methods + +JumpProcesses' adaptive leaping solvers accept a `MassActionJump` directly. Here a +reversible conversion is coupled to a slower irreversible reaction: + +```@example tau +using JumpProcesses + +maj = MassActionJump( + [100.0, 100.0, 0.1], + [[1 => 1], [2 => 1], [1 => 1]], + [[1 => -1, 2 => 1], [1 => 1, 2 => -1], [1 => -1, 3 => 1]] +) +prob = DiscreteProblem([100.0, 100.0, 0.0], (0.0, 1.0)) +jprob = JumpProblem(prob, PureLeaping(), maj) + +explicit_sol = solve(jprob, SimpleExplicitTauLeaping(; epsilon = 0.01); saveat = 0.1) +implicit_sol = solve(jprob, SimpleImplicitTauLeaping(); saveat = 0.1) +trapezoidal_sol = solve(jprob, SimpleTrapezoidalLeaping(); saveat = 0.1) +switching_sol = solve(jprob, SimpleAdaptiveTauLeaping(); saveat = 0.1) +nothing # hide +``` + +The explicit method adapts its leap size. The implicit and trapezoidal methods +also adapt their leap sizes, and perform a nonlinear solve at each step. The +switching method chooses an explicit or implicit step from its stiffness test; +"adaptive" in its name refers to this switching, not just step-size adaptation. +An implicit step costs more, so it is useful when stiffness restricts explicit +steps severely. + +Select the alternative implicit formulation and stiffness test as follows: + +```@example tau +alg = SimpleAdaptiveTauLeaping(; + implicit_alg = SimpleTrapezoidalLeaping(), eigenvalue_check = true +) +sol = solve(jprob, alg; saveat = 0.1) + +using Test +for solution in (explicit_sol, implicit_sol, trapezoidal_sol, switching_sol, sol) + @test solution.t == collect(0.0:0.1:1.0) + @test all(u -> all(>=(0), u), solution.u) + @test all(u -> sum(u) ≈ 200.0, solution.u) +end +nothing # hide +``` + +These solvers require a pure mass-action model over a `DiscreteProblem`; do not +add a `RegularJump` or separately aggregated jumps to this problem. + +## Reusing the mass-action problem with StochasticDiffEq + +The same `jprob` also works with `SimpleTauLeaping` and StochasticDiffEq's +leaping solvers. No conversion to a user-written `RegularJump` is needed: + +```@example tau +using StochasticDiffEq + +fixed_sol = solve(jprob, SimpleTauLeaping(); dt = 0.001) +tau_sol = solve(jprob, TauLeaping(); dt = 0.001) +cao_sol = solve(jprob, CaoTauLeaping(); dt = 0.001) +sde_implicit_sol = solve(jprob, ImplicitTauLeaping(); dt = 0.001, adaptive = false) +theta_sol = solve( + jprob, ThetaTrapezoidalTauLeaping(); dt = 0.001, adaptive = false +) + +for solution in (fixed_sol, tau_sol, cao_sol, sde_implicit_sol, theta_sol) + @test successful_retcode(solution) + @test solution.t[end] ≈ 1.0 + @test all(u -> sum(u) ≈ 200.0, solution.u) +end +nothing # hide +``` + +## More general rates with RegularJump + +`SimpleTauLeaping` and StochasticDiffEq's tau-leaping solvers accept +`RegularJump(rate!, change!, numjumps)`. `rate!` writes every propensity into its +output, and `change!` writes the **increment**, not the new state, associated with +the reaction counts. For example, a conversion with a saturating rate from the +first species to the second is: + +```@example regular_tau +using JumpProcesses, StochasticDiffEq + +function rate!(out, u, p, t) + out[1] = p * u[1] / (1 + u[1]) + return nothing +end + +function change!(du, u, p, t, counts, mark) + du[1] = -counts[1] + du[2] = counts[1] + return nothing +end + +rj = RegularJump(rate!, change!, 1) +prob = DiscreteProblem([1000.0, 0.0], (0.0, 1.0), 100.0) +jprob = JumpProblem(prob, PureLeaping(), rj) + +fixed_sol = solve(jprob, SimpleTauLeaping(); dt = 0.01) +adaptive_sol = solve(jprob, TauLeaping(); dt = 0.01) +cao_sol = solve(jprob, CaoTauLeaping(); dt = 0.01) +implicit_sol = solve(jprob, ImplicitTauLeaping(); dt = 0.01, adaptive = false) +theta_sol = solve( + jprob, ThetaTrapezoidalTauLeaping(; theta = 0.5); dt = 0.01, adaptive = false +) + +using Test +for solution in (fixed_sol, adaptive_sol, cao_sol, implicit_sol, theta_sol) + @test solution.t[end] ≈ 1.0 + @test all(u -> sum(u) ≈ 1000.0, solution.u) +end +nothing # hide +``` + +The same `RegularJump` and `JumpProblem` are reused here. The implicit examples +explicitly select fixed stepping; supplying `dt` alone does not disable adaptive +stepping in StochasticDiffEq. The `change!` function must also make sense for the +non-integer rate/drift inputs used by implicit solvers; a linear stoichiometric +update as above satisfies this requirement. + +`MassActionJump` is the common input for all the leaping methods above. +`RegularJump` is an additional option for custom kinetics in `SimpleTauLeaping` +and StochasticDiffEq. JumpProcesses' adaptive mass-action solvers need the +reaction-order and stoichiometric information provided by `MassActionJump`. See +[the solver table](@ref jump_solve) and [GPU support](@ref gpu_ensembles) before +switching algorithms or ensemble backends. diff --git a/src/simple_regular_solve.jl b/src/simple_regular_solve.jl index b052fcace..6e47f8cdf 100644 --- a/src/simple_regular_solve.jl +++ b/src/simple_regular_solve.jl @@ -1103,7 +1103,13 @@ end EnsembleGPUKernel() EnsembleGPUKernel(backend) -Ensemble algorithm marker for GPU execution of tau-leaping ensemble simulations. +Ensemble algorithm for pure-jump simulations with [`SSAStepper`](@ref), +[`SimpleExplicitTauLeaping`](@ref), or [`SimpleTauLeaping`](@ref). + +Load `KernelAbstractions` and `Adapt` to activate the extension, and pass an explicit +backend such as `CUDABackend()` from CUDA for GPU execution. The default is the +KernelAbstractions CPU backend. See [GPU ensembles](@ref gpu_ensembles) for supported +problem representations, required solve options, and limitations. ## Arguments From 4391c382afd9121c7d5321463653af0b03997c03 Mon Sep 17 00:00:00 2001 From: ChrisRackauckas-Claude Date: Sat, 12 Sep 2026 05:18:24 -0400 Subject: [PATCH 4/5] Present tau-leaping methods around a common mass-action model Combine the solver examples around shared kinetics, describe native reaction data handling, and document fixed stepping for the incomplete Cao selector. 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 | 7 ++--- docs/src/tutorials/tau_leaping.md | 50 +++++++++++++------------------ 2 files changed, 23 insertions(+), 34 deletions(-) diff --git a/docs/src/jump_solve.md b/docs/src/jump_solve.md index 98c789fe0..e30a22cab 100644 --- a/docs/src/jump_solve.md +++ b/docs/src/jump_solve.md @@ -81,7 +81,7 @@ count-based updates. | JumpProcesses | [`SimpleTrapezoidalLeaping`](@ref) | `MassActionJump` | Adaptive implicit trapezoidal; `epsilon` | | JumpProcesses | [`SimpleAdaptiveTauLeaping`](@ref) | `MassActionJump` | Switches explicit/implicit; `epsilon` | | StochasticDiffEq | `TauLeaping` | `MassActionJump` or `RegularJump` | Adaptive with post-leap estimates | -| StochasticDiffEq | `CaoTauLeaping` | `MassActionJump` or `RegularJump` | Adaptive Cao step selection | +| StochasticDiffEq | `CaoTauLeaping` | `MassActionJump` or `RegularJump` | Fixed steps with `dt`, `adaptive = false`; adaptive selector incomplete | | StochasticDiffEq | `ImplicitTauLeaping` | `MassActionJump` or `RegularJump` | Implicit; fixed steps with `dt`, `adaptive = false` | | StochasticDiffEq | `ThetaTrapezoidalTauLeaping` | `MassActionJump` or `RegularJump` | Implicit theta-trapezoidal; fixed steps with `dt`, `adaptive = false` | @@ -89,9 +89,8 @@ count-based updates. The `Simple*` methods listed above are streamlined solvers for pure jump problems: construct a `DiscreteProblem` and use `PureLeaping()` as the aggregator. The -adaptive mass-action methods require a `MassActionJump`. All methods construct -the rates and stoichiometric updates from it without a user-written -`RegularJump`. They support `saveat`, `save_start`, and `save_end`. +adaptive mass-action methods require a `MassActionJump`. Each solver uses the stored rate constants and +stoichiometry directly. They support `saveat`, `save_start`, and `save_end`. `SimpleImplicitTauLeaping` takes the deterministic part of a leap implicitly. `SimpleTrapezoidalLeaping` averages current and new-state propensities in that diff --git a/docs/src/tutorials/tau_leaping.md b/docs/src/tutorials/tau_leaping.md index c062dfa9f..03a63f180 100644 --- a/docs/src/tutorials/tau_leaping.md +++ b/docs/src/tutorials/tau_leaping.md @@ -5,13 +5,13 @@ an interval. It introduces discretization error in addition to Monte Carlo sampling error. Compare ensembles and repeat with smaller steps or tighter step-selection parameters when assessing accuracy. -## Adaptive mass-action methods +## Mass-action kinetics -JumpProcesses' adaptive leaping solvers accept a `MassActionJump` directly. Here a -reversible conversion is coupled to a slower irreversible reaction: +Define the kinetics with a `MassActionJump`, then choose a leaping method. Here +a reversible conversion is coupled to a slower irreversible reaction: ```@example tau -using JumpProcesses +using JumpProcesses, StochasticDiffEq, Test maj = MassActionJump( [100.0, 100.0, 0.1], @@ -25,6 +25,19 @@ explicit_sol = solve(jprob, SimpleExplicitTauLeaping(; epsilon = 0.01); saveat = implicit_sol = solve(jprob, SimpleImplicitTauLeaping(); saveat = 0.1) trapezoidal_sol = solve(jprob, SimpleTrapezoidalLeaping(); saveat = 0.1) switching_sol = solve(jprob, SimpleAdaptiveTauLeaping(); saveat = 0.1) +fixed_sol = solve(jprob, SimpleTauLeaping(); dt = 0.001) +tau_sol = solve(jprob, TauLeaping(); dt = 0.001) +cao_sol = solve(jprob, CaoTauLeaping(); dt = 0.001, adaptive = false) +sde_implicit_sol = solve(jprob, ImplicitTauLeaping(); dt = 0.001, adaptive = false) +theta_sol = solve( + jprob, ThetaTrapezoidalTauLeaping(); dt = 0.001, adaptive = false +) + +for solution in (fixed_sol, tau_sol, cao_sol, sde_implicit_sol, theta_sol) + @test successful_retcode(solution) + @test solution.t[end] ≈ 1.0 + @test all(u -> sum(u) ≈ 200.0, solution.u) +end nothing # hide ``` @@ -52,32 +65,9 @@ end nothing # hide ``` -These solvers require a pure mass-action model over a `DiscreteProblem`; do not -add a `RegularJump` or separately aggregated jumps to this problem. - -## Reusing the mass-action problem with StochasticDiffEq - -The same `jprob` also works with `SimpleTauLeaping` and StochasticDiffEq's -leaping solvers. No conversion to a user-written `RegularJump` is needed: - -```@example tau -using StochasticDiffEq - -fixed_sol = solve(jprob, SimpleTauLeaping(); dt = 0.001) -tau_sol = solve(jprob, TauLeaping(); dt = 0.001) -cao_sol = solve(jprob, CaoTauLeaping(); dt = 0.001) -sde_implicit_sol = solve(jprob, ImplicitTauLeaping(); dt = 0.001, adaptive = false) -theta_sol = solve( - jprob, ThetaTrapezoidalTauLeaping(); dt = 0.001, adaptive = false -) - -for solution in (fixed_sol, tau_sol, cao_sol, sde_implicit_sol, theta_sol) - @test successful_retcode(solution) - @test solution.t[end] ≈ 1.0 - @test all(u -> sum(u) ≈ 200.0, solution.u) -end -nothing # hide -``` +The `SimpleExplicitTauLeaping`, `SimpleImplicitTauLeaping`, +`SimpleTrapezoidalLeaping`, and `SimpleAdaptiveTauLeaping` methods require pure +mass-action kinetics over a `DiscreteProblem`. ## More general rates with RegularJump From 0694d22327da00537015055a37d97f46f4a576c1 Mon Sep 17 00:00:00 2001 From: ChrisRackauckas-Claude Date: Sat, 12 Sep 2026 05:29:02 -0400 Subject: [PATCH 5/5] Require native leaping versions in the cross-package guide 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/Project.toml | 4 +++- docs/src/tutorials/tau_leaping.md | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/Project.toml b/docs/Project.toml index c29a7a37d..cd5e81d53 100644 --- a/docs/Project.toml +++ b/docs/Project.toml @@ -14,6 +14,7 @@ Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80" PointProcesses = "af0b7596-9bb0-472a-a012-63904f2b4c55" StableRNGs = "860ef19b-820b-49d6-a774-d7a799459cd3" StochasticDiffEq = "789caeaf-c7a9-5a7d-9973-96adeb23e2a0" +StochasticDiffEqLeaping = "aefaaa88-39f2-4e89-b162-d61b7e8cc81b" [compat] Catalyst = "16" @@ -22,7 +23,7 @@ DifferentialEquations = "7.11, 8.0" Distributions = "0.25" Documenter = "1.1" Graphs = "1.9" -JumpProcesses = "9.13.2" +JumpProcesses = "9.33" SciMLBase = "3" OrdinaryDiffEq = "6.59, 7" OrdinaryDiffEqFunctionMap = "1, 2" @@ -31,3 +32,4 @@ Plots = "1.39" PointProcesses = "0.5" StableRNGs = "1.0" StochasticDiffEq = "6.63, 7" +StochasticDiffEqLeaping = "2.2" diff --git a/docs/src/tutorials/tau_leaping.md b/docs/src/tutorials/tau_leaping.md index 03a63f180..fc908b135 100644 --- a/docs/src/tutorials/tau_leaping.md +++ b/docs/src/tutorials/tau_leaping.md @@ -97,7 +97,7 @@ jprob = JumpProblem(prob, PureLeaping(), rj) fixed_sol = solve(jprob, SimpleTauLeaping(); dt = 0.01) adaptive_sol = solve(jprob, TauLeaping(); dt = 0.01) -cao_sol = solve(jprob, CaoTauLeaping(); dt = 0.01) +cao_sol = solve(jprob, CaoTauLeaping(); dt = 0.01, adaptive = false) implicit_sol = solve(jprob, ImplicitTauLeaping(); dt = 0.01, adaptive = false) theta_sol = solve( jprob, ThetaTrapezoidalTauLeaping(; theta = 0.5); dt = 0.01, adaptive = false