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/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/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 41ac44124..e30a22cab 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 should be defined as `RegularJump`s. +τ-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()` @@ -33,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 @@ -63,20 +66,61 @@ 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` | 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` | -### 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. +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`. 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 +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. -### JumpProcesses.jl +### StochasticDiffEq.jl - - `SimpleTauLeaping`: a tau-leaping algorithm for pure `RegularJump` `JumpProblem`s. - Requires a choice of `dt`. - - `RegularSSA`: a version of SSA for pure `RegularJump` `JumpProblem`s. +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. + +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 diff --git a/docs/src/jump_types.md b/docs/src/jump_types.md index 181964d91..df62c50eb 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 @@ -505,3 +507,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/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..fc908b135 --- /dev/null +++ b/docs/src/tutorials/tau_leaping.md @@ -0,0 +1,125 @@ +# [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. + +## Mass-action kinetics + +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, StochasticDiffEq, Test + +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) +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 +``` + +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 +``` + +The `SimpleExplicitTauLeaping`, `SimpleImplicitTauLeaping`, +`SimpleTrapezoidalLeaping`, and `SimpleAdaptiveTauLeaping` methods require pure +mass-action kinetics over a `DiscreteProblem`. + +## 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, 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 +) + +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/ext/JumpProcessesKernelAbstractionsExt.jl b/ext/JumpProcessesKernelAbstractionsExt.jl index 5df7b3876..c6cb67c86 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,30 @@ struct JumpData{R, C} numjumps::Int end +Adapt.@adapt_structure JumpData + +gpu_num_jumps(jump::JumpData) = jump.numjumps +leaping_rates!(out, jump::JumpData, u, p, t) = jump.rate(out, u, p, t) +leaping_change!(du, jump::JumpData, u, p, t, counts) = + jump.c(du, u, p, t, counts, nothing) + +function leaping_rates!(out, jump::GPUMassActionJump, u, p, t) + for j in eachindex(out) + out[j] = gpu_evalrxrate(u, j, jump, eltype(out)) + end + return nothing +end + +function leaping_change!(du, jump::GPUMassActionJump, u, p, t, counts) + fill!(du, zero(eltype(du))) + for j in eachindex(counts) + for k in jump.ns_offsets[j]:(jump.ns_offsets[j + 1] - 1) + du[jump.ns_species[k]] += jump.ns_coeffs[k] * counts[j] + end + end + return nothing +end + # SimpleTauLeaping kernel @kernel function simple_tau_leaping_kernel( @Const(probs_data), _us, _ts, dt, @Const(rj_data), @@ -103,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) @@ -130,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 @@ -139,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 @@ -155,7 +177,11 @@ 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 rj === nothing + GPUMassActionJump(prob.massaction_jump, backend, float(eltype(prob.prob.tspan))) + else + JumpData(rj.rate, rj.c, rj.numjumps) + end # Extract trajectory-specific data without static typing probs_data = [TrajectoryData(SA{eltype(p.prob.u0)}[p.prob.u0...], p.prob.p, p.prob.tspan) @@ -171,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" @@ -183,7 +209,7 @@ function vectorized_solve(probs, prob::JumpProblem, alg::SimpleTauLeaping; # Pre-allocate thread-local buffers current_u_buf = allocate(backend, eltype(prob.prob.u0), (state_dim, n_trajectories)) - rate_cache_buf = allocate(backend, eltype(prob.prob.u0), (num_jumps, n_trajectories)) + rate_cache_buf = allocate(backend, float(eltype(prob.prob.u0)), (num_jumps, n_trajectories)) counts_buf = allocate(backend, eltype(prob.prob.u0), (num_jumps, n_trajectories)) local_dc_buf = allocate(backend, eltype(prob.prob.u0), (state_dim, n_trajectories)) diff --git a/src/JumpProcesses.jl b/src/JumpProcesses.jl index 80acf38f1..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") @@ -139,6 +140,11 @@ problem construction. - `PureLeaping` is currently intended for tau-leaping algorithms such as [`SimpleTauLeaping`](@ref) and [`SimpleExplicitTauLeaping`](@ref). + - A `MassActionJump` can be passed directly to all tau-leaping algorithms in + JumpProcesses. The problem preserves its mass-action + representation so each solver can use the rate constants and stoichiometry directly. + - `SimpleTauLeaping` additionally accepts a `RegularJump` for more general rates + and updates. - Spatial jump problems are not supported by the `PureLeaping` construction path. ## Examples diff --git a/src/massaction_rates.jl b/src/massaction_rates.jl index 06d4dfa8c..657eea164 100644 --- a/src/massaction_rates.jl +++ b/src/massaction_rates.jl @@ -158,3 +158,88 @@ function add_self_dependencies!(dg; dosort = true) end 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,)) + +""" + 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 rates +end + +@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 + +""" + massaction_stoichiometry_mul!(du, jump::MassActionJump, counts) + +Overwrite `du` with the net stoichiometry times the reaction vector `counts`. +`counts` may contain reaction counts or propensities and must have one entry per +reaction. `du` must have one entry per species and must not alias `counts` or the +jump's data. +""" +function massaction_stoichiometry_mul!(du, jump::MassActionJump, counts) + fill!(du, zero(eltype(du))) + _, _, stoichiometry = massaction_data(jump) + for j in eachindex(stoichiometry) + for (species, coefficient) in stoichiometry[j] + du[species] += coefficient * counts[j] + end + end + return du +end + +""" + 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 + +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 008dab179..66d185e93 100644 --- a/src/problem.jl +++ b/src/problem.jl @@ -350,13 +350,15 @@ 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 + 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..6e47f8cdf 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 @@ -237,12 +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 && + xor( + get_num_majumps(jump_prob.massaction_jump) > 0, jump_prob.regular_jump !== nothing + ) end function validate_pure_leaping_inputs( @@ -304,17 +310,16 @@ 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) 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 @@ -346,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 @@ -1098,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 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..50d0911d5 --- /dev/null +++ b/test/massaction_leaping.jl @@ -0,0 +1,112 @@ +using JumpProcesses, Test, StableRNGs, ForwardDiff + +regular_leaping_algs = (SimpleTauLeaping(),) + +@testset "Mass-action input for regular leaping solvers" begin + maj = MassActionJump( + [0.02, 0.1], [[1 => 2], [2 => 1]], + [[1 => -2, 2 => 1], [1 => 2, 2 => -1]] + ) + prob = DiscreteProblem([40.0, 20.0], (0.0, 0.2)) + function rate!(out, u, p, t) + out[1] = u[1] * max(u[1] - 1, 0) * 0.01 + out[2] = 0.1 * u[2] + nothing + end + function change!(du, u, p, t, counts, mark) + du[1] = -2 * counts[1] + 2 * counts[2] + du[2] = counts[1] - counts[2] + nothing + end + rj = RegularJump(rate!, change!, 2) + for alg in regular_leaping_algs, + adaptive in (false,) + @testset "$(nameof(typeof(alg))), adaptive=$adaptive" begin + actual = JumpProblem(prob, PureLeaping(), maj; 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 "Native mass-action operations" begin + for scale_rates in (true, false) + maj = MassActionJump( + [2.0, 6.0], [Pair{Int, Int}[], [1 => 3]], + [[1 => 1], [1 => -3, 2 => 1]]; scale_rates + ) + jp = JumpProblem(DiscreteProblem([5.0, 0.0], (0.0, 1.0)), PureLeaping(), maj) + @test jp.regular_jump === nothing + out = fill(NaN, 2) + massaction_rates!(out, jp.massaction_jump, [5.0, 0.0]) + @test out == [2.0, scale_rates ? 60.0 : 360.0] + massaction_rates!(out, jp.massaction_jump, [1.0, 0.0]) + @test out == [2.0, 0.0] + du = fill(NaN, 2) + massaction_stoichiometry_mul!(du, jp.massaction_jump, [4.0, 2.0]) + @test du == [-2.0, 2.0] + u = [5.0, 0.0] + massaction_rates!(out, jp.massaction_jump, u) + massaction_stoichiometry_mul!(du, jp.massaction_jump, out) + @test massaction_drift!(zeros(2), jp.massaction_jump, u) == du + jac = ForwardDiff.jacobian(u) do x + massaction_drift!(similar(x), jp.massaction_jump, x) + end + factor = scale_rates ? 1.0 : 6.0 + @test jac == [-141.0factor 0.0; 47.0factor 0.0] + end + maj = MassActionJump([[1 => 1]], [[1 => -1, 2 => 1]]; param_idxs = [1]) + jp = JumpProblem(DiscreteProblem([20.0, 0.0], (0.0, 1.0), [0.1]), PureLeaping(), maj) + remade = remake(jp; p = [0.3]) + out = zeros(1) + massaction_rates!(out, remade.massaction_jump, remade.prob.u0) + @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 + @test_throws ErrorException solve(ojp, SimpleTauLeaping(); dt = 0.01) +end + +@testset "General regular rates remain supported" begin + rate!(out, u, p, t) = (out[1] = 100 * u[1] / (1 + u[1])) + function change!(du, u, p, t, counts, mark) + du[1] = -counts[1] + du[2] = counts[1] + nothing + end + jp = JumpProblem( + DiscreteProblem([100.0, 0.0], (0.0, 0.1)), + PureLeaping(), RegularJump(rate!, change!, 1) + ) + for alg in regular_leaping_algs + opts = alg isa SimpleTauLeaping ? (; dt = 0.001, seed = 42) : + (; dt = 0.001, seed = 42, adaptive = false) + sol = solve(jp, alg; opts...) + @test successful_retcode(sol) + @test sol.u[end][2] > 0 + @test all(u -> sum(u) ≈ 100, sol.u) + end +end + +@testset "Single-reaction mass-action operations" begin + for (rate, reactants, net) in ( + (6.0, [1 => 3], [1 => -3, 2 => 1]), + (2.0, Pair{Int, Int}[], [1 => 1]), + ) + single = MassActionJump(rate, reactants, net) + vector = MassActionJump([rate], [reactants], [net]) + u = [5.0, 0.0] + @test massaction_rates!(zeros(1), single, u) == massaction_rates!(zeros(1), vector, u) + @test massaction_stoichiometry_mul!(zeros(2), single, [2.0]) == + massaction_stoichiometry_mul!(zeros(2), vector, [2.0]) + @test massaction_drift!(zeros(2), single, u) == massaction_drift!(zeros(2), vector, u) + end +end 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