Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions HISTORY.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
# Breaking updates and feature summaries across releases

## Unreleased
- New `isolated_copy(jprob)` returns a copy of a `JumpProblem` with its own jump state, for
concurrent solves and integrators that are alive at the same time. Unlike `deepcopy`, it
shares the wrapped problem, which makes it much cheaper for problems built with
ModelingToolkit or Catalyst.
- `SortingDirect`, `RDirect`, `DirectCR`, `RSSA` and `RSSACR` now recompute their running
sums of the rates when rounding errors may have made them inaccurate, using a bound on
those errors that they update as the rates change. When every rate became zero, the
Expand Down
1 change: 1 addition & 0 deletions docs/src/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ SSAStepper
SplitCoupledJumpProblem
reset_aggregated_jumps!
remake(::JumpProblem)
isolated_copy
```

## Jump Types
Expand Down
21 changes: 12 additions & 9 deletions docs/src/tutorials/ensembles_and_problem_reuse.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ of every solve. They never copy it. This makes repeated solves fast, but it mean
**one `JumpProblem` supports one active solve or integrator at a time**:

- Repeated serial solves of one problem are safe and fast.
- Concurrent solves, from threads or tasks, need independent copies of the problem.
- Concurrent solves, from threads or tasks, need independent copies of the problem,
made with [`isolated_copy`](@ref).
- Problems created with `remake` share the original's jump state.
- `EnsembleProblem`s create the copies they need for you.

Expand Down Expand Up @@ -81,8 +82,8 @@ end
```

However, the original and remade problems must not be solved concurrently, and must
not be used for integrators that are alive at the same time. Use `deepcopy` when you
need an independent problem.
not be used for integrators that are alive at the same time. Use
[`isolated_copy`](@ref) when you need an independent problem.

## Ensembles

Expand Down Expand Up @@ -168,14 +169,16 @@ between all threads.
## Manual threading

When launching tasks yourself, give each task its own copy of the problem, made once
per task and reused for all of that task's solves:
per task and reused for all of that task's solves. [`isolated_copy`](@ref) copies the
problem's jump state but shares the problem it wraps, which makes it much cheaper than
`deepcopy` for problems built with ModelingToolkit or Catalyst:

```@example reuse
nsims = 1000
chunks = Iterators.partition(1:nsims, cld(nsims, Threads.nthreads()))
tasks = map(chunks) do chunk
Threads.@spawn begin
local_prob = deepcopy(jprob) # one independent copy per task
local_prob = isolated_copy(jprob) # one independent copy per task
[solve(local_prob, SSAStepper()).u[end][1] for _ in chunk]
end
end
Expand All @@ -189,8 +192,8 @@ independent problems:

```@example reuse
Random.seed!(3) # hide
integrator1 = init(deepcopy(jprob), SSAStepper())
integrator2 = init(deepcopy(jprob), SSAStepper())
integrator1 = init(isolated_copy(jprob), SSAStepper())
integrator2 = init(isolated_copy(jprob), SSAStepper())
step!(integrator1)
step!(integrator2)
integrator1.t, integrator2.t
Expand Down Expand Up @@ -286,6 +289,6 @@ serial and threaded runs generally give different trajectories.
| `prob_func` returning a shared problem | Avoid | n/a | No |
| Stateful callbacks in ensembles | Pass to `JumpProblem`, reset in `initialize` | Copied with the problem | Yes |
| Stateful callbacks passed to `solve` | Avoid with threads | Shared | No |
| Manual threads or tasks | `deepcopy` once per task | One per task | Yes |
| Simultaneously alive integrators | `deepcopy` each problem | One per integrator | Yes |
| Manual threads or tasks | `isolated_copy` once per task | One per task | Yes |
| Simultaneously alive integrators | `isolated_copy` for each integrator | One per integrator | Yes |
| `EnsembleDistributed`, `pmap_batch_size > 1` | `safetycopy = true` or `pmap_batch_size = 1` | One per trajectory, or per worker | Yes with these settings |
2 changes: 1 addition & 1 deletion src/JumpProcesses.jl
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ export PureLeaping

# core problem and timestepping
include("problem.jl")
export JumpProblem, SplitCoupledJumpProblem
export JumpProblem, SplitCoupledJumpProblem, isolated_copy

include("solve.jl")
export init, solve, solve!
Expand Down
97 changes: 94 additions & 3 deletions src/problem.jl
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,8 @@ examples and commonly asked questions.

- Repeated serial solves of one problem are safe, and avoid copying.
- Concurrent solves from multiple threads or tasks, and integrators that are alive at
the same time, each need an independent copy, such as `deepcopy(jprob)`.
the same time, each need an independent copy. [`isolated_copy`](@ref) copies only
the jump state, while `deepcopy(jprob)` also copies the wrapped problem.
- `remake(jprob; ...)` shares the original's jump state, so remade problems are not
independent for concurrent use.
- `EnsembleProblem` supplies isolation. `EnsembleSerial` reuses the problem
Expand Down Expand Up @@ -221,8 +222,8 @@ The new problem shares the original's jump aggregator and jump callbacks rather
copying them. Solvers owned by JumpProcesses re-initialize this state from the problem being
solved at every `init`, so the original and remade problems can be solved one after
another. They must not be solved concurrently, or used for integrators that are alive at
the same time; use `deepcopy` to obtain an independent problem. `SortingDirect`'s learned
search order is also shared.
the same time; use [`isolated_copy`](@ref) to obtain an independent problem.
`SortingDirect`'s learned search order is also shared.
"""
function DiffEqBase.remake(jprob::JumpProblem; u0 = missing, p = missing,
interpret_symbolicmap = true, use_defaults = false, kwargs...)
Expand Down Expand Up @@ -283,6 +284,96 @@ function DiffEqBase.remake(jprob::JumpProblem; u0 = missing, p = missing,
jprob.massaction_jump, jprob.kwargs)
end

"""
isolated_copy(jprob::JumpProblem)

Return a copy of `jprob` with its own jump state, so that it can be solved concurrently with
`jprob`, or used for an integrator that is alive at the same time as one of `jprob`.

## Arguments

- `jprob`: the `JumpProblem` to copy.

## Returns

A `JumpProblem` of the same type as `jprob`, sharing the wrapped problem `jprob.prob`.

## Details

The copy is like `deepcopy(jprob)`, except that it shares the wrapped problem, including its
function, initial condition and parameters. The jump aggregator and its callbacks, the
jumps, and the callbacks passed to the `JumpProblem` constructor are copied, so the copy
starts from the same state as `jprob`, including `SortingDirect`'s learned search order.
For problems built with ModelingToolkit or Catalyst, sharing the wrapped problem makes
`isolated_copy` much cheaper than `deepcopy`.

Since the parameters are shared and solvers alias them by default, a callback that modifies
`integrator.p` also modifies the parameters of `jprob`. To give the copy its own
parameters, use `remake(isolated_copy(jprob); p = new_p)`. Likewise, solves that alias
`u0` modify the shared initial condition. Rate and affect functions should not store
mutable state, since copies may share them.

## Example

```julia
# One copy per task, each with its own parameters
tasks = map([1.0, 2.0, 3.0]) do birth_rate
Threads.@spawn solve(remake(isolated_copy(jprob); p = [birth_rate, 0.1]), SSAStepper())
end
sols = fetch.(tasks)
```
"""
function isolated_copy(jprob::JumpProblem)
state = JumpState((jprob.discrete_jump_aggregation, jprob.jump_callback,
jprob.constant_jumps, jprob.variable_jumps, jprob.regular_jump,
jprob.massaction_jump, jprob.kwargs))
agg, cbs, crjs, vrjs, rj, maj, kwargs = deepcopy(state).fields
remaker_of(jprob)(jprob.prob, jprob.aggregator, agg, cbs, crjs, vrjs, rj, maj, kwargs)
end

# The fields of a `JumpProblem` other than the wrapped problem and the aggregator, copied
# together so that the copied callbacks use the copied aggregation
struct JumpState{F <: Tuple}
fields::F
end

# A deep copy of a `FunctionWrapper` keeps calling the original object through a raw
# pointer, so the wrappers in the jump state are shared instead. Solves don't mutate them.
function Base.deepcopy_internal(state::JumpState, stackdict::IdDict)
share_function_wrappers!(stackdict, state.fields, IdSet{Any}())
JumpState(Base.deepcopy_internal(state.fields, stackdict))
end

function share_function_wrappers!(stackdict, wrapper::FunctionWrappers.FunctionWrapper,
seen)
stackdict[wrapper] = wrapper
nothing
end

function share_function_wrappers!(stackdict, x::Array, seen)
(isbitstype(eltype(x)) || x in seen) && return nothing
push!(seen, x)
for i in eachindex(x)
isassigned(x, i) && share_function_wrappers!(stackdict, x[i], seen)
end
nothing
end

# Wrappers are only stored in JumpProcesses' own types and in SciMLBase callbacks
function share_function_wrappers!(stackdict, x, seen)
(x isa Union{Tuple, NamedTuple} || is_jump_state_type(x)) || return nothing
if ismutable(x)
x in seen && return nothing
push!(seen, x)
end
for i in 1:nfields(x)
isdefined(x, i) && share_function_wrappers!(stackdict, getfield(x, i), seen)
end
nothing
end

is_jump_state_type(x) = parentmodule(typeof(x)) in (JumpProcesses, SciMLBase)

DiffEqBase.isinplace(::JumpProblem{iip}) where {iip} = iip
JumpProblem(prob::JumpProblem) = prob

Expand Down
164 changes: 164 additions & 0 deletions test/isolated_copy.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
using JumpProcesses, OrdinaryDiffEq, SciMLBase, Test

# `isolated_copy` gives a problem its own jump state while sharing the wrapped problem.
# Copies must behave like independent problems (`deepcopy`), also when used at the same
# time as the original.

path(sol) = (sol.t, sol.u)

# A <-> B, as mass-action or constant-rate jumps
function ab_jprob(aggregator; massaction = true, kwargs...)
prob = DiscreteProblem([12, 8], (0.0, 5.0), [0.7, 0.4])
reactant_stoch = [[1 => 1], [2 => 1]]
net_stoch = [[1 => -1, 2 => 1], [1 => 1, 2 => -1]]
if massaction
maj = MassActionJump(reactant_stoch, net_stoch; param_idxs = [1, 2])
return JumpProblem(prob, aggregator, maj; kwargs...)
end

ab!(integrator) = (integrator.u[1] -= 1; integrator.u[2] += 1; nothing)
ba!(integrator) = (integrator.u[1] += 1; integrator.u[2] -= 1; nothing)
jumps = (ConstantRateJump((u, p, t) -> p[1] * u[1], ab!),
ConstantRateJump((u, p, t) -> p[2] * u[2], ba!))
JumpProblem(prob, aggregator, jumps...; dep_graph = [[1, 2], [1, 2]],
vartojumps_map = [[1], [2]], jumptovars_map = [[1, 2], [1, 2]], kwargs...)
end

# Steps two integrators in turn before finishing both, so that both are alive at once
function interleaved_paths(prob1, prob2, alg; seeds = (1, 2), nsteps = 10)
integrators = (init(prob1, alg; seed = seeds[1]), init(prob2, alg; seed = seeds[2]))
for _ in 1:nsteps
foreach(step!, integrators)
end
foreach(solve!, integrators)
map(integrator -> path(integrator.sol), integrators)
end

# Stops a simulation after `n` jumps; its counter is callback state
function stop_after_jumps(n)
njumps = Ref(0)
reset!(cb, u, t, integrator) = (njumps[] = 0)
function affect!(integrator)
njumps[] += 1
njumps[] >= n && terminate!(integrator)
end
DiscreteCallback((u, t, integrator) -> true, affect!; initialize = reset!)
end

@testset "Shares the wrapped problem and copies the jump state" begin
jprob = ab_jprob(Direct(); callback = stop_after_jumps(5), tstops = [1.0])
jcopy = isolated_copy(jprob)

@test jcopy isa typeof(jprob)
@test jcopy.prob === jprob.prob
@test jcopy.aggregator === jprob.aggregator
@test jcopy.discrete_jump_aggregation !== jprob.discrete_jump_aggregation
@test jcopy.jump_callback !== jprob.jump_callback
@test jcopy.kwargs[:callback] !== jprob.kwargs[:callback]
@test jcopy.kwargs[:tstops] == jprob.kwargs[:tstops]

# The copied callback uses the copied aggregation, also in integrators
jump_cb = only(jcopy.jump_callback.discrete_callbacks)
@test jump_cb.condition === jcopy.discrete_jump_aggregation
@test init(jcopy, SSAStepper()).cb.condition === jcopy.discrete_jump_aggregation

# A remade copy shares the copy's jump state, not the original's
remade = remake(jcopy; p = [1.0, 1.0])
@test remade.discrete_jump_aggregation === jcopy.discrete_jump_aggregation
@test remade.prob.p == [1.0, 1.0]
@test jprob.prob.p == [0.7, 0.4]
end

@testset "Integrators alive at the same time: $(nameof(typeof(aggregator))), \
massaction = $massaction" for aggregator in JumpProcesses.JUMP_AGGREGATORS,
massaction in (true, false)

jprob = ab_jprob(aggregator; massaction)
refs = map(seed -> path(solve(deepcopy(jprob), SSAStepper(); seed)), (1, 2))

# `jprob` stays unsolved until the last check: SortingDirect's learned order is copied
copies = (isolated_copy(jprob), isolated_copy(jprob))
@test interleaved_paths(copies..., SSAStepper()) == refs
@test interleaved_paths(jprob, isolated_copy(jprob), SSAStepper()) == refs
end

@testset "ODE problems with variable-rate jumps: $(nameof(typeof(vr_aggregator)))" for vr_aggregator in (VR_FRM(), VR_Direct(), VR_DirectFW())

# Growth of u[1], with births of u[2] at rate u[1] and resets of u[1] at a constant rate
f!(du, u, p, t) = (du[1] = p[1] * u[1]; du[2] = 0; nothing)
oprob = ODEProblem(f!, [1.0, 0.0], (0.0, 3.0), [0.5])
birth = VariableRateJump((u, p, t) -> u[1],
integrator -> (integrator.u[2] += 1; nothing))
reset = ConstantRateJump((u, p, t) -> 1.0,
integrator -> (integrator.u[1] = 1.0; nothing))
jprob = JumpProblem(oprob, Direct(), birth, reset; vr_aggregator)

refs = map(seed -> path(solve(deepcopy(jprob), Tsit5(); seed)), (1, 2))
@test interleaved_paths(jprob, isolated_copy(jprob), Tsit5(); nsteps = 3) == refs
end

@testset "Concurrent solves" begin
for jprob in (ab_jprob(SortingDirect()), ab_jprob(NRM(); massaction = false))
refs = [path(solve(deepcopy(jprob), SSAStepper(); seed)) for seed in 1:8]
tasks = [Threads.@spawn path(solve(isolated_copy(jprob), SSAStepper(); seed))
for seed in 1:8]
@test fetch.(tasks) == refs
end
end

@testset "Callbacks passed to the JumpProblem are copied" begin
birth = MassActionJump([[0 => 1]], [[1 => 1]]; param_idxs = [1])
jprob = JumpProblem(DiscreteProblem([0], (0.0, 100.0), [1.0]), Direct(), birth;
callback = stop_after_jumps(5))

# A shared counter would stop both simulations early
(_, u1), (_, u2) = interleaved_paths(jprob, isolated_copy(jprob), SSAStepper();
nsteps = 3)
@test u1[end] == u2[end] == [5]
end

@testset "Copies don't depend on the original's memory" begin
# Function-wrapper aggregators store the rates in wrappers that call through pointers
function rate_seen_by_copy()
k = 2.0
rate = (u, p, t) -> k
jprob = JumpProblem(DiscreteProblem([0], (0.0, 1.0)), DirectFW(),
ConstantRateJump(rate, integrator -> (integrator.u[1] += 1; nothing)))
isolated_copy(jprob)
end
copies = [rate_seen_by_copy() for _ in 1:20]
for _ in 1:5
GC.gc(true)
junk = [fill(-1.0, 4) for _ in 1:10_000]
end
rate_at_start(jprob) = only(jprob.discrete_jump_aggregation.rates)(jprob.prob.u0,
jprob.prob.p, 0.0)
@test all(==(2.0) ∘ rate_at_start, copies)
end

@testset "Spatial aggregators: $(nameof(typeof(aggregator)))" for aggregator in (
NSM(), DirectCRDirect())

# A + B <--> C on a line of three sites
majumps = MassActionJump([0.5, 1.0], [[1 => 1, 2 => 1], [3 => 1]],
[[1 => -1, 2 => -1, 3 => 1], [1 => 1, 2 => 1, 3 => -1]])
u0 = zeros(Int, 3, 3)
u0[:, 2] .= [20, 20, 0]
prob = DiscreteProblem(u0, (0.0, 2.0), [0.5, 1.0])
jprob = JumpProblem(prob, aggregator, majumps; hopping_constants = fill(1.0, size(u0)),
spatial_system = CartesianGrid((3,)))

refs = map(seed -> path(solve(deepcopy(jprob), SSAStepper(); seed)), (1, 2))
@test interleaved_paths(jprob, isolated_copy(jprob), SSAStepper()) == refs
end

@testset "PureLeaping" begin
maj = MassActionJump([[1 => 1], [2 => 1]], [[1 => -1, 2 => 1], [1 => 1, 2 => -1]];
param_idxs = [1, 2])
jprob = JumpProblem(DiscreteProblem([12, 8], (0.0, 5.0), [0.7, 0.4]), PureLeaping(),
maj)
jcopy = isolated_copy(jprob)
@test jcopy.prob === jprob.prob
@test path(solve(jcopy, SimpleExplicitTauLeaping(); seed = 1)) ==
path(solve(deepcopy(jprob), SimpleExplicitTauLeaping(); seed = 1))
end
5 changes: 3 additions & 2 deletions test/qa.jl
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,9 @@ run_qa(
# Names not (yet) declared public in their owner package's released API.
all_qualified_accesses_are_public = (;
ignore = (
# Base / Base.Broadcast / Base.FastMath internals
Symbol("@pure"), :BroadcastStyle, :Broadcasted, :Cartesian,
# Base / Base.Broadcast / Base.FastMath internals; `deepcopy_internal` is
# extended to customise `deepcopy`, as its docstring describes
Symbol("@pure"), :BroadcastStyle, :Broadcasted, :Cartesian, :deepcopy_internal,
:DefaultArrayStyle, :FastMath, :Unknown, :result_style, :sqrt_fast,
# SciMLBase non-public
:ConstantInterpolation, :DISCRETE_INPLACE_DEFAULT,
Expand Down
2 changes: 2 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ end
@time @safetestset "Stochastic dispatch tests" begin include("stochastic_dispatch.jl") end
@time @safetestset "Jump-diffusion replay and jump state" begin include("jump_diffusion_state.jl") end
@time @safetestset "Jump-state ownership and alias controls" begin include("jump_state_ownership.jl") end
@time @safetestset "isolated_copy" begin include("isolated_copy.jl") end
@time @safetestset "Ensemble Uniqueness test" begin include("ensemble_uniqueness.jl") end
@time @safetestset "Ensemble Problem Tests" begin include("ensemble_problems.jl") end
@time @safetestset "A + B <--> C" begin include("reversible_binding.jl") end
Expand All @@ -75,6 +76,7 @@ end
if GROUP == "All" || GROUP == "ThreadSafety"
@time @safetestset "Thread Safety test (threaded)" begin include("thread_safety.jl") end
@time @safetestset "Jump-state ownership (threaded)" begin include("jump_state_ownership.jl") end
@time @safetestset "isolated_copy (threaded)" begin include("isolated_copy.jl") end
end

if GROUP == "CUDA"
Expand Down