Skip to content
7 changes: 7 additions & 0 deletions HISTORY.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# Breaking updates and feature summaries across releases

## 10.3.0

- `SimpleTauLeaping` consumes native `MassActionJump` rates and stoichiometry
on CPU and in KernelAbstractions kernels, with solver-owned working rates.
- Public `massaction_rates!`, `massaction_stoichiometry_mul!`, and
`massaction_drift!` operations support downstream leaping solvers.

## 10.2.0
- New `isolated_copy(jprob)` returns a `JumpProblem` with its own jump state, for
concurrent solves and for integrators that are alive at the same time. It copies only
Expand Down
2 changes: 1 addition & 1 deletion Project.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
name = "JumpProcesses"
uuid = "ccbc3e58-028d-4f4c-8cd5-9ae44345cda5"
authors = ["Chris Rackauckas <accounts@chrisrackauckas.com>"]
version = "10.2.0"
version = "10.3.0"

[deps]
ADTypes = "47edcb42-4c32-4615-8424-f2b9edc5f35b"
Expand Down
46 changes: 44 additions & 2 deletions docs/src/jump_solve.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ faster as they only simulate the total number of jumps over each leap interval,
and thus do not need to simulate the realization of every single jump. Jumps for
use with exact simulation methods can be defined as `ConstantRateJump`s,
`MassActionJump`s, and/or `VariableRateJump`. Jumps for use with inexact
τ-leaping methods should be defined as `RegularJump`s.
JumpProcesses τ-leaping methods can be defined as `MassActionJump`s with
`PureLeaping()`.
`SimpleTauLeaping` and StochasticDiffEq's leaping algorithms also accept
`RegularJump`s for more general rates and count-based updates.

There are special algorithms available for efficiently simulating an exact, pure
`JumpProblem` (i.e., a `JumpProblem` over a `DiscreteProblem`). `SSAStepper()`
Expand Down Expand Up @@ -103,10 +106,16 @@ These methods support mixing with event handling, other jump types, and all of
the features of the normal differential equation solvers.

- `TauLeaping`: an adaptive tau-leaping algorithm with post-leap estimates.
- `CaoTauLeaping`: use fixed steps (`dt`, `adaptive = false`); its adaptive step selector is incomplete.
- `ImplicitTauLeaping`: implicit tau-leaping.
- `ThetaTrapezoidalTauLeaping`: implicit theta-trapezoidal tau-leaping.

For fixed steps with the implicit methods, pass `dt` and `adaptive = false`.

### JumpProcesses.jl

- `SimpleTauLeaping`: a tau-leaping algorithm for pure `RegularJump` `JumpProblem`s.
- `SimpleTauLeaping`: fixed-step leaping for pure `MassActionJump` or `RegularJump`
`JumpProblem`s constructed with `PureLeaping()`.
Requires a choice of `dt`.
- `RegularSSA`: a version of SSA for pure `RegularJump` `JumpProblem`s.

Expand All @@ -119,3 +128,36 @@ and the jump process has designed a regular jump.

- `EM`: Explicit Euler-Maruyama.
- `ImplicitEM`: Implicit Euler-Maruyama. See the SDE solvers page for more details.

## Common mass-action input

The same mass-action problem can be used with JumpProcesses' fixed-step, adaptive
explicit, implicit, trapezoidal, and switching solvers:

```@example common_massaction
using JumpProcesses

maj = MassActionJump([0.1], [[1 => 1]], [[1 => -1, 2 => 1]])
prob = DiscreteProblem([1000.0, 0.0], (0.0, 1.0))
jprob = JumpProblem(prob, PureLeaping(), maj)

fixed_sol = solve(jprob, SimpleTauLeaping(); dt = 0.01)
explicit_sol = solve(jprob, SimpleExplicitTauLeaping())
implicit_sol = solve(jprob, SimpleImplicitTauLeaping())
trapezoidal_sol = solve(jprob, SimpleTrapezoidalLeaping())
switching_sol = solve(jprob, SimpleAdaptiveTauLeaping())
nothing # hide
```

`SimpleTauLeaping` and `SimpleExplicitTauLeaping` support this mass-action input
with `EnsembleGPUKernel`. The fixed-step kernel requires `dt`; the adaptive
explicit kernel requires `saveat`. Implicit and switching GPU kernels are not
provided. `SimpleTauLeaping` also supports device-compatible `RegularJump`
functions; the adaptive explicit GPU kernel requires mass-action kinetics.

With `SimpleTauLeaping` and `EnsembleGPUKernel`, a custom `prob_func` must
preserve the template time span, state dimension, and mass-action rate constants
and stoichiometry. Initial populations may vary; `RegularJump` rates can read
per-trajectory parameters. Parameter storage must be device-compatible, such as
tuples or static arrays. Parameter-mapped mass-action jumps support the default
ensemble problem function.
13 changes: 13 additions & 0 deletions docs/src/jump_types.md
Original file line number Diff line number Diff line change
Expand Up @@ -570,3 +570,16 @@ as will trying to update either `p` or `tspan` while passing a new
COEVOLVE: a joint point process model for information diffusion and network
evolution, Journal of Machine Learning Research 18(1), 1305–1353 (2017). doi:
10.5555/3122009.3122050.

## Mass-action operations for solver authors

`JumpProblem` preserves `MassActionJump` data. Solvers can use the rate constants
and stoichiometry directly and choose their own storage and evaluation strategy.
The following operations support CPU solver implementations; GPU solvers should
prepare a device-compatible representation during solver initialization.

```@docs
massaction_rates!
massaction_stoichiometry_mul!
massaction_drift!
```
90 changes: 79 additions & 11 deletions ext/JumpProcessesKernelAbstractionsExt.jl
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,53 @@ function SciMLBase.__solve(ensembleprob::SciMLBase.AbstractEnsembleProblem,

# Validate that this is a PureLeaping JumpProblem
JumpProcesses.validate_pure_leaping_inputs(jump_prob, alg) ||
error("SimpleTauLeaping can only be used with PureLeaping JumpProblems with only non-RegularJumps.")
prob = jump_prob.prob
error("SimpleTauLeaping requires a PureLeaping JumpProblem with a MassActionJump or a RegularJump.")

# Mass-action rate constants are uploaded once from the template jump. A
# RegularJump rate closure still receives each trajectory's `p`, but a
# parameter-mapped MassActionJump cannot refresh those rates per trajectory.
if jump_prob.regular_jump === nothing &&
JumpProcesses.using_params(jump_prob.massaction_jump) &&
ensembleprob.prob_func !== SciMLBase.DEFAULT_PROB_FUNC
error("EnsembleGPUKernel with SimpleTauLeaping does not support MassActionJump \
rate constants that depend on parameters (`param_idxs` / `param_mapper`) \
together with a custom `prob_func`. Those rates are taken once from the \
template problem and ignore per-trajectory `p`. Use a RegularJump whose \
rate reads `p`, or a CPU ensemble algorithm such as EnsembleSerial.")
end

probs = [remake(jump_prob) for _ in 1:trajectories]
template_tspan = jump_prob.prob.tspan
template_state_dim = length(jump_prob.prob.u0)
template_massaction = jump_prob.regular_jump === nothing ?
deepcopy(JumpProcesses.massaction_data(jump_prob.massaction_jump)) : nothing
probs = map(1:trajectories) do i
ctx = SciMLBase.EnsembleContext(i, 1, 0, nothing, nothing, nothing)
_prob = ensembleprob.safetycopy ? deepcopy(jump_prob) : jump_prob
trajectory = ensembleprob.prob_func(_prob, ctx)
length(trajectory.prob.u0) == template_state_dim || throw(
ArgumentError(
"EnsembleGPUKernel with SimpleTauLeaping requires prob_func to preserve the template state dimension."
)
)
trajectory.prob.tspan == template_tspan || throw(
ArgumentError(
"EnsembleGPUKernel with SimpleTauLeaping requires prob_func to preserve the template tspan."
)
)
JumpProcesses.validate_pure_leaping_inputs(trajectory, alg) ||
throw(ArgumentError("prob_func must return a PureLeaping JumpProblem with a MassActionJump or a RegularJump."))
(trajectory.regular_jump === nothing) == (template_massaction !== nothing) ||
throw(ArgumentError("prob_func must preserve the template jump representation."))
if template_massaction !== nothing
isequal(JumpProcesses.massaction_data(trajectory.massaction_jump), template_massaction) ||
throw(
ArgumentError(
"EnsembleGPUKernel with SimpleTauLeaping requires prob_func to preserve MassActionJump rate constants and stoichiometry."
)
)
end
trajectory
end

# Run vectorized solve
ts,
Expand Down Expand Up @@ -129,6 +172,29 @@ struct JumpData{R, C}
numjumps::Int
end

Adapt.@adapt_structure JumpData

gpu_num_jumps(jump::JumpData) = jump.numjumps
leaping_rates!(out, jump::JumpData, u, p, t) = jump.rate(out, u, p, t)
leaping_change!(du, jump::JumpData, u, p, t, counts) = jump.c(du, u, p, t, counts, nothing)

function leaping_rates!(out, jump::GPUMassActionJump, u, p, t)
for j in eachindex(out)
out[j] = gpu_evalrxrate(u, j, jump, eltype(out))
end
return nothing
end

function leaping_change!(du, jump::GPUMassActionJump, u, p, t, counts)
fill!(du, zero(eltype(du)))
for j in eachindex(counts)
for k in jump.ns_offsets[j]:(jump.ns_offsets[j + 1] - 1)
du[jump.ns_species[k]] += jump.ns_coeffs[k] * counts[j]
end
end
return nothing
end

# SimpleTauLeaping kernel
@kernel function simple_tau_leaping_kernel(
@Const(probs_data), _us, _ts, dt, @Const(rj_data),
Expand All @@ -150,9 +216,7 @@ end
tspan = prob_data.tspan

# Extract jump data
rate = rj_data.rate
num_jumps = rj_data.numjumps
c = rj_data.c
num_jumps = gpu_num_jumps(rj_data)

# Initialize current_u from u0
@inbounds for k in 1:length(u0)
Expand All @@ -177,7 +241,7 @@ end
tprev = tspan[1] + (j-2) * dt

# Compute rates and scale by dt
rate(rate_cache, current_u, p, tprev)
leaping_rates!(rate_cache, rj_data, current_u, p, tprev)
rate_cache .*= dt

# Poisson sampling
Expand All @@ -186,7 +250,7 @@ end
end

# Apply changes
c(local_dc, current_u, p, tprev, counts, nothing)
leaping_change!(local_dc, rj_data, current_u, p, tprev, counts)
current_u .+= local_dc

# Store results
Expand All @@ -202,7 +266,11 @@ function vectorized_solve(probs, prob::JumpProblem, alg::SimpleTauLeaping;
backend, trajectories, dt, kwargs...)
# Extract common jump data
rj = prob.regular_jump
rj_data = JumpData(rj.rate, rj.c, rj.numjumps)
rj_data = if rj === nothing
GPUMassActionJump(prob.massaction_jump, prob.prob.p, backend, float(eltype(prob.prob.tspan)))
else
JumpData(rj.rate, rj.c, rj.numjumps)
end

# Extract trajectory-specific data without static typing
probs_data = [TrajectoryData(SA{eltype(p.prob.u0)}[p.prob.u0...], p.prob.p, p.prob.tspan)
Expand All @@ -218,7 +286,7 @@ function vectorized_solve(probs, prob::JumpProblem, alg::SimpleTauLeaping;
dt = Float64(dt)
n_steps = Int((tspan[2] - tspan[1]) / dt) + 1
n_trajectories = length(probs)
num_jumps = rj_data.numjumps
num_jumps = gpu_num_jumps(rj_data)

# Validate dimensions
@assert state_dim > 0 "Dimension of state must be positive"
Expand All @@ -230,7 +298,7 @@ function vectorized_solve(probs, prob::JumpProblem, alg::SimpleTauLeaping;

# Pre-allocate thread-local buffers
current_u_buf = allocate(backend, eltype(prob.prob.u0), (state_dim, n_trajectories))
rate_cache_buf = allocate(backend, eltype(prob.prob.u0), (num_jumps, n_trajectories))
rate_cache_buf = allocate(backend, float(eltype(prob.prob.u0)), (num_jumps, n_trajectories))
counts_buf = allocate(backend, eltype(prob.prob.u0), (num_jumps, n_trajectories))
local_dc_buf = allocate(backend, eltype(prob.prob.u0), (state_dim, n_trajectories))

Expand Down
6 changes: 6 additions & 0 deletions src/JumpProcesses.jl
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ const USE_SORTINGDIRECT_THRESHOLD = 200

include("jumps.jl")
export ConstantRateJump, VariableRateJump, RegularJump, MassActionJump, JumpSet, RateBounds
export massaction_rates!, massaction_stoichiometry_mul!, massaction_drift!

include("massaction_rates.jl")

Expand Down Expand Up @@ -133,6 +134,11 @@ problem construction.

- `PureLeaping` is currently intended for tau-leaping algorithms such as
[`SimpleTauLeaping`](@ref) and [`SimpleExplicitTauLeaping`](@ref).
- A `MassActionJump` can be passed directly to all tau-leaping algorithms in
JumpProcesses. The problem preserves its mass-action
representation so each solver can use the rate constants and stoichiometry directly.
- `SimpleTauLeaping` additionally accepts a `RegularJump` for more general rates
and updates.
- Spatial jump problems are not supported by the `PureLeaping` construction path.

## Examples
Expand Down
123 changes: 123 additions & 0 deletions src/massaction_rates.jl
Original file line number Diff line number Diff line change
Expand Up @@ -158,3 +158,126 @@ function add_self_dependencies!(dg; dosort = true)
end
end
end

materialize_leaping_jump(jump::MassActionJump, p, ::Type{T}) where {T} = jump
function materialize_leaping_jump(
jump::MassActionJump{Nothing, <:AbstractArray{<:Pair}}, p, ::Type{T}
) where {T}
return materialize_leaping_jump(check_majump_type(jump), p, T)
end
function materialize_leaping_jump(jump::MassActionJump{Nothing}, p, ::Type{T}) where {T}
constants = Vector{T}(undef, get_num_majumps(jump))
fill_scaled_rates!(constants, jump, p)
return MassActionJump(
constants, jump.reactant_stoch, jump.net_stoch;
scale_rates = false, useiszero = false, nocopy = true
)
end

@inline massaction_data(jump::MassActionJump) = (
jump.scaled_rates, jump.reactant_stoch, jump.net_stoch,
)
@inline massaction_data(jump::MassActionJump{<:Number}) = (
(jump.scaled_rates,), (jump.reactant_stoch,), (jump.net_stoch,),
)
@inline massaction_data(jump::MassActionJump{Nothing, <:AbstractArray{<:Pair}}) = (
jump.scaled_rates, (jump.reactant_stoch,), (jump.net_stoch,),
)

"""
massaction_rates!(rates, jump::MassActionJump, u; p = nothing)

Write each reaction propensity at populations `u` into `rates`. Uses the stored,
combinatorially scaled rate constants and falling factorial rate laws. A reaction
with insufficient reactants has zero propensity. `rates` must have one entry per
reaction and must not alias `u` or the jump's data. For parameter-mapped jumps,
pass the current parameters as `p`; scaled working rates are materialized for
this call without mutating the jump definition.
"""
function massaction_rates!(rates, jump::MassActionJump, u; p = nothing)
working_jump = materialize_leaping_jump(jump, p, eltype(rates))
constants, reactants, _ = massaction_data(working_jump)
for j in eachindex(constants)
rates[j] = massaction_propensity(constants, reactants, u, j, eltype(rates))
end
return rates
end

"""
massaction_propensity(constants, reactants, u, j, T)

Propensity of reaction `j` at populations `u`, using combinatorially scaled
`constants` and falling-factorial rate laws from `reactants`. Products promote
the population and constant types with the destination scalar type `T`.

If any reactant population is strictly below the reaction order for that
species, the propensity is zero rather than negative. Under tau-leaping this
means an overshoot that drives a population below zero (or below the order)
stays there for that reaction: the propensity remains zero, so further leaps
cannot pull the population back through this channel.
"""
@inline function massaction_propensity(constants, reactants, u, j, ::Type{T}) where {T}
rate = one(T) * one(eltype(u)) * one(constants[j])
for (species, order) in reactants[j]
population = u[species]
population <= order - 1 && return zero(rate)
for k in 0:(order - 1)
rate *= population - k
end
end
return rate * constants[j]
end

"""
massaction_stoichiometry_mul!(du, jump::MassActionJump, counts)

Overwrite `du` with the net stoichiometry times the reaction vector `counts`.
`counts` may contain reaction counts or propensities and must have one entry per
reaction. `du` must have one entry per species and must not alias `counts` or the
jump's data.
"""
function massaction_stoichiometry_mul!(du, jump::MassActionJump, counts)
fill!(du, zero(eltype(du)))
_, _, stoichiometry = massaction_data(jump)
for j in eachindex(stoichiometry)
count = one(eltype(du)) * counts[j]
for (species, coefficient) in stoichiometry[j]
du[species] += coefficient * count
end
end
return du
end

"""
massaction_drift!(du, jump::MassActionJump, u; p = nothing)

Overwrite `du` with the mass-action drift, the net stoichiometry times the
propensities at `u`. Evaluates and accumulates each reaction without allocating
an intermediate propensity vector. Supports automatic differentiation through
`u` when `du` can store the resulting scalar type. `du` must have one entry per
species and must not alias `u` or the jump's data. For parameter-mapped jumps, pass the current parameters as `p`,
as for [`massaction_rates!`](@ref).
"""
function massaction_drift!(du, jump::MassActionJump, u; p = nothing)
fill!(du, zero(eltype(du)))
working_jump = materialize_leaping_jump(jump, p, eltype(du))
constants, reactants, stoichiometry = massaction_data(working_jump)
for j in eachindex(constants)
rate = massaction_propensity(constants, reactants, u, j, eltype(du))
for (species, coefficient) in stoichiometry[j]
du[species] += coefficient * rate
end
end
return du
end

leaping_rates!(out, jump::MassActionJump, u, p, t) = massaction_rates!(out, jump, u)
leaping_rates!(out, jump::RegularJump, u, p, t) = jump.rate(out, u, p, t)
function leaping_change!(du, jump::MassActionJump, u, p, t, counts, mark)
return massaction_stoichiometry_mul!(du, jump, counts)
end
function leaping_change!(du, jump::RegularJump, u, p, t, counts, mark)
return jump.c(du, u, p, t, counts, mark)
end
leaping_num_jumps(jump::MassActionJump) = get_num_majumps(jump)
leaping_num_jumps(jump::RegularJump) = jump.numjumps
Loading
Loading