Skip to content
Merged
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
10 changes: 10 additions & 0 deletions HISTORY.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
# Breaking updates and feature summaries across releases

## Unreleased
- 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
the jump aggregator's working data and rebuilds the jump callbacks around it, sharing
everything else, including the wrapped problem, the jumps and the stored callbacks, so it
is much cheaper than `deepcopy`, especially for problems built with ModelingToolkit or
Catalyst. StochasticDiffEq's copies of the jump state (`alias_jumps = false`, the
default off thread 1) now use it. The docs no longer recommend `deepcopy`, which
copies `p`, `u0` and the stored callbacks too, but with `FunctionWrapper`-based
aggregators can call the original problem's rate and affect functions and needs the
original kept alive.
- `VR_Direct` and `VR_DirectFW` no longer also simulate the bounded `VariableRateJump`s
that `Coevolve` handles. In problems with both bounded and general `VariableRateJump`s,
those bounded jumps fired twice as often.
Expand Down
4 changes: 3 additions & 1 deletion Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ FastBroadcast = "1.3.2, 1"
ForwardDiff = "0.10.36, 1"
FunctionWrappers = "1.1.3"
Graphs = "1.14.0"
InteractiveUtils = "1"
KernelAbstractions = "0.9.36"
LinearAlgebra = "1"
LinearSolve = "5.2"
Expand Down Expand Up @@ -76,6 +77,7 @@ Adapt = "79e6a3ab-5dfb-504d-930d-738a2a938a0e"
DiffEqCallbacks = "459566f4-90b8-5000-8ac3-15dfb0a30def"
FastBroadcast = "7034ab61-46d4-4ed7-9d0f-46aef9175898"
ForwardDiff = "f6369f11-7733-5829-9624-2563aa707210"
InteractiveUtils = "b77e0a4c-d291-57a0-90e8-8db25a27a240"
KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1ce7c"
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
LinearSolve = "7ed4a6bd-45f5-4d41-b270-4a48e9bafcae"
Expand All @@ -94,4 +96,4 @@ StochasticDiffEqLeaping = "aefaaa88-39f2-4e89-b162-d61b7e8cc81b"
Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40"

[targets]
test = ["Adapt", "DiffEqCallbacks", "FastBroadcast", "ForwardDiff", "KernelAbstractions", "LinearAlgebra", "LinearSolve", "OrdinaryDiffEq", "OrdinaryDiffEqBDF", "OrdinaryDiffEqFunctionMap", "Pkg", "SafeTestsets", "SciMLTesting", "StableRNGs", "Statistics", "StochasticDiffEq", "StochasticDiffEqCore", "StochasticDiffEqImplicit", "StochasticDiffEqLeaping", "Test"]
test = ["Adapt", "DiffEqCallbacks", "FastBroadcast", "ForwardDiff", "InteractiveUtils", "KernelAbstractions", "LinearAlgebra", "LinearSolve", "OrdinaryDiffEq", "OrdinaryDiffEqBDF", "OrdinaryDiffEqFunctionMap", "Pkg", "SafeTestsets", "SciMLTesting", "StableRNGs", "Statistics", "StochasticDiffEq", "StochasticDiffEqCore", "StochasticDiffEqImplicit", "StochasticDiffEqLeaping", "Test"]
7 changes: 5 additions & 2 deletions docs/src/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ SSAStepper
SplitCoupledJumpProblem
reset_aggregated_jumps!
remake(::JumpProblem)
isolated_copy
```

## Jump Types
Expand Down Expand Up @@ -136,7 +137,8 @@ Consequently:
- Repeated serial solves of one problem are safe and avoid any copying.
- One `JumpProblem` supports one active solve or integrator at a time.
Concurrent solves from threads or tasks, and integrators that are alive at the
same time, each need an independent copy, such as `deepcopy(jprob)`.
same time, each need an independent copy, such as
[`isolated_copy(jprob)`](@ref isolated_copy), which copies only the jump state.
- [`remake`](@ref remake(::JumpProblem)) 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 @@ -332,7 +334,8 @@ around the problem's own jump callbacks, which `init` re-initializes. `__jump_in
raises the removed-`alias_jump` error and forwards `alias` unchanged to the
underlying solver. JumpProcesses still defines the transitional
`resetted_jump_problem` and `reset_jump_problem!` helpers for released
StochasticDiffEq versions, but no longer calls them itself.
StochasticDiffEq versions, but no longer calls them itself; `resetted_jump_problem`
returns an [`isolated_copy`](@ref).

For **tau-leaping**, JumpProcesses defines a custom `DiffEqBase.solve` that
bypasses the standard `__solve`/`__init` pathway. It calls `resolve_rng`
Expand Down
2 changes: 1 addition & 1 deletion docs/src/faq.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ to combine `remake` with `EnsembleProblem`s safely.
Not directly. Solvers owned by JumpProcesses reuse a `JumpProblem`'s jump
aggregator and callbacks rather than copying them, so one problem supports one
active solve or integrator at a time. For concurrent solves, give each task its
own `deepcopy` of the problem, made once per task and reused for that task's
own [`isolated_copy`](@ref) of the problem, made once per task and reused for that task's
solves, or use an `EnsembleProblem`, which makes these copies for you. Problems
created with `remake` share the original's jump state and are not independent.
See [Jump state ownership and problem reuse](@ref jump_state_ownership) and the
Expand Down
2 changes: 1 addition & 1 deletion docs/src/jump_types.md
Original file line number Diff line number Diff line change
Expand Up @@ -473,7 +473,7 @@ including parameter-mapped mass-action working rates, from the problem being
solved, and `remake` does not overwrite rates in a shared parameter-mapped
definition. The original and remade problems must not be solved concurrently, or
used for integrators that are alive at the same time; create independent copies
with `deepcopy` instead. See the
with [`isolated_copy`](@ref) instead. See the
[ensembles and problem reuse tutorial](@ref ensembles_problem_reuse).
`SortingDirect` also retains its learned search order, so a reused problem can
have different initial sampling state even with the same seed.
Expand Down
5 changes: 3 additions & 2 deletions docs/src/migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ end
chunks = Iterators.partition(1:n, cld(n, Threads.nthreads()))
tasks = map(chunks) do idxs
Threads.@spawn begin
local_prob = deepcopy(jprob)
local_prob = isolated_copy(jprob) # deepcopy(jprob) before JumpProcesses 10.2
[solve(local_prob, SSAStepper()) for _ in idxs]
end
end
Expand All @@ -170,7 +170,8 @@ An `EnsembleProblem` already provides this isolation: `EnsembleThreads` with
`safetycopy = false` copies the problem once per spawned task, and
`safetycopy = true` copies it before every trajectory. Problems created with
`remake` share the original's jump state, so they are not independent copies;
use `deepcopy` instead. The same applies to integrators from `init` that are
use [`isolated_copy`](@ref) (JumpProcesses 10.2 and later) or `deepcopy` instead. The
same applies to integrators from `init` that are
alive at the same time. See the
[ensembles and problem reuse tutorial](@ref ensembles_problem_reuse) for details.

Expand Down
38 changes: 27 additions & 11 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,17 @@ 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 only
the problem's jump state and shares everything else, including the problem it wraps,
which makes it much cheaper than `deepcopy`, especially 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,13 +193,23 @@ 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
```

This is the pattern for agent-based models with one integrator per agent: keep one
problem as a template that is never solved itself, and give each agent
`init(remake(isolated_copy(template); u0, p), alg)`. A copy may also be taken from a
problem whose integrator is alive, between its steps, for example when an agent divides.

A copy shares `p`, `u0` and the callbacks stored in the problem with the original. Give
it its own parameters with `remake(isolated_copy(jprob); p = new_p)`, and pass callbacks
that keep state to `init` or `solve` rather than to `JumpProblem`. `deepcopy` copies
these too, at a much higher cost; see [`JumpProblem`](@ref) for its limitations.

## Distributed ensembles

`EnsembleDistributed()` sends the problem to each worker. With `safetycopy = false` and
Expand Down Expand Up @@ -252,6 +266,8 @@ using StochasticDiffEqHighOrder
sol = solve(sde_jprob, SRIW1(); alias = SciMLBase.SDEAliasSpecifier(alias_jumps = false))
```

The copy is an [`isolated_copy`](@ref) of the problem.

The guidance above still applies: do not rely on these copies to make shared problems
safe for concurrent use.

Expand All @@ -265,8 +281,8 @@ a copy of a problem that has never been solved:

```@example reuse
sd_jprob = JumpProblem(dprob, SortingDirect(), maj; save_positions = (false, false))
fresh = deepcopy(sd_jprob) # never solved
replay(seed) = solve(deepcopy(fresh), SSAStepper(); seed).u
fresh = isolated_copy(sd_jprob) # never solved
replay(seed) = solve(isolated_copy(fresh), SSAStepper(); seed).u
replay(42) == replay(42)
```

Expand All @@ -286,6 +302,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 |
4 changes: 4 additions & 0 deletions src/JumpProcesses.jl
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,10 @@ export NSM
include("spatial/directcrdirect.jl")
export DirectCRDirect

# after every type that holds jump state
include("isolated_copy.jl")
export isolated_copy

# coupling
include("coupled_array.jl")
include("coupling.jl")
Expand Down
5 changes: 5 additions & 0 deletions src/aggregators/ccnrm.jl
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ function CCNRMJumpAggregation(nj::Int, njt::T, et::T, crs::Vector{T}, sr::T,
dependencies, ptt)
end

# the fields that `isolated_copy` shares; it copies the others (see `shared_fields`)
function shared_fields(::Type{<:CCNRMJumpAggregation})
(:ma_jumps, :rates, :affects!, :save_positions, :dependencies)
end

############################# Required Functions ##############################
# creating the JumpAggregation structure (function wrapper-based constant jumps)
function aggregate(aggregator::CCNRM, u, p, t, end_time, constant_jumps,
Expand Down
6 changes: 6 additions & 0 deletions src/aggregators/coevolve.jl
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,12 @@ function (p::CoevolveJumpAggregation{
nothing
end

# the fields that `isolated_copy` shares; it copies the others (see `shared_fields`)
function shared_fields(::Type{<:CoevolveJumpAggregation})
(:ma_jumps, :rates, :affects!, :save_positions, :dependencies, :lrates,
:urates, :rateintervals, :haslratevec)
end

# creating the JumpAggregation structure (tuple-based variable jumps)
function aggregate(aggregator::Coevolve, u, p, t, end_time, constant_jumps,
ma_jumps, save_positions; dependencies, variable_jumps = nothing, kwargs...)
Expand Down
5 changes: 5 additions & 0 deletions src/aggregators/direct.jl
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ function DirectJumpAggregation(nj::Int, njt::T, et::T, crs::Vector{T}, sr::T, ma
rs, affs!, sps)
end

# the fields that `isolated_copy` shares; it copies the others (see `shared_fields`)
function shared_fields(::Type{<:DirectJumpAggregation})
(:ma_jumps, :rates, :affects!, :save_positions)
end

############################# Required Functions #############################

# creating the JumpAggregation structure (tuple-based constant jumps)
Expand Down
5 changes: 5 additions & 0 deletions src/aggregators/directcr.jl
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,11 @@ function DirectCRJumpAggregation(nj::Int, njt::T, et::T, crs::Vector{T}, sr::T,
ratetogroup, zero(sr))
end

# the fields that `isolated_copy` shares; it copies the others (see `shared_fields`)
function shared_fields(::Type{<:DirectCRJumpAggregation})
(:ma_jumps, :rates, :affects!, :save_positions, :dependencies, :ratetogroup)
end

############################# Required Functions ##############################

# creating the JumpAggregation structure (function wrapper-based constant jumps)
Expand Down
5 changes: 5 additions & 0 deletions src/aggregators/frm.jl
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ function FRMJumpAggregation(nj::Int, njt::T, et::T, crs::Vector{T}, sr::T, maj::
rs, affs!, sps)
end

# the fields that `isolated_copy` shares; it copies the others (see `shared_fields`)
function shared_fields(::Type{<:FRMJumpAggregation})
(:ma_jumps, :rates, :affects!, :save_positions)
end

############################# Required Functions #############################

# creating the JumpAggregation structure (tuple-based constant jumps)
Expand Down
5 changes: 5 additions & 0 deletions src/aggregators/nrm.jl
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ function NRMJumpAggregation(nj::Int, njt::T, et::T, crs::Vector{T}, sr::T,
dependencies, pq)
end

# the fields that `isolated_copy` shares; it copies the others (see `shared_fields`)
function shared_fields(::Type{<:NRMJumpAggregation})
(:ma_jumps, :rates, :affects!, :save_positions, :dependencies)
end

############################# Required Functions ##############################
# creating the JumpAggregation structure (function wrapper-based constant jumps)
function aggregate(aggregator::NRM, u, p, t, end_time, constant_jumps,
Expand Down
8 changes: 8 additions & 0 deletions src/aggregators/prioritytable.jl
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ mutable struct PriorityGroup{T, W <: AbstractVector}
pids::W
end
PriorityGroup{U}(maxpriority::T) where {T, U} = PriorityGroup(maxpriority, 0, Vector{U}())
# the fields that `isolated_copy` shares; it copies the others (see `shared_fields`)
shared_fields(::Type{<:PriorityGroup}) = ()

@inline function insert!(pg::PriorityGroup, pid)
(; numpids, pids) = pg
Expand Down Expand Up @@ -115,6 +117,8 @@ mutable struct PriorityTable{F, S, T, U <: Function} <: AbstractPriorityTable
"""
priortogid::U
end
# the fields that `isolated_copy` shares; it copies the others (see `shared_fields`)
shared_fields(::Type{<:PriorityTable}) = (:priortogid,)

"""
Setup table from a vector of priorities. The id
Expand Down Expand Up @@ -398,6 +402,8 @@ struct TimeGrouper{T <: Number}
mintime::T
binwidth::T
end
# the fields that `isolated_copy` shares; it copies the others (see `shared_fields`)
shared_fields(::Type{<:TimeGrouper}) = ()

@inline function (t::TimeGrouper{T})(time::T) where {T}
return floor(Int, (time - t.mintime) / t.binwidth) + 1
Expand All @@ -414,6 +420,8 @@ mutable struct PriorityTimeTable{T, F <: Int}
binwidthconst::F
numbinsconst::F
end
# the fields that `isolated_copy` shares; it copies the others (see `shared_fields`)
shared_fields(::Type{<:PriorityTimeTable}) = (:binwidthconst, :numbinsconst)

# Construct the time table with the default optimal bin width and number of bins.
# DEFAULT NUMBINS: 20 * √length(times)
Expand Down
5 changes: 5 additions & 0 deletions src/aggregators/rdirect.jl
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ function RDirectJumpAggregation(nj::Int, njt::T, et::T, crs::Vector{T}, sr::T, m
Int(counter_threshold), zero(sr))
end

# the fields that `isolated_copy` shares; it copies the others (see `shared_fields`)
function shared_fields(::Type{<:RDirectJumpAggregation})
(:ma_jumps, :rates, :affects!, :save_positions, :dependencies, :counter_threshold)
end

############################# Required Functions #############################

# creating the JumpAggregation structure (tuple-based constant jumps)
Expand Down
6 changes: 6 additions & 0 deletions src/aggregators/rssa.jl
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,12 @@ function RSSAJumpAggregation(nj::Int, njt::T, et::T, crs::Vector{T}, sr::T,
uhigh, zero(sr))
end

# the fields that `isolated_copy` shares; it copies the others (see `shared_fields`)
function shared_fields(::Type{<:RSSAJumpAggregation})
(:ma_jumps, :rates, :affects!, :brackets, :save_positions, :dependencies,
:bracket_data)
end

############################# Required Functions ##############################

# creating the JumpAggregation structure (function wrapper-based constant jumps)
Expand Down
6 changes: 6 additions & 0 deletions src/aggregators/rssacr.jl
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,12 @@ function RSSACRJumpAggregation(nj::Int, njt::F, et::F, crs::Vector{F}, sum_rate:
rt, ratetogroup, zero(sum_rate))
end

# the fields that `isolated_copy` shares; it copies the others (see `shared_fields`)
function shared_fields(::Type{<:RSSACRJumpAggregation})
(:ma_jumps, :rates, :affects!, :brackets, :save_positions, :dependencies,
:bracket_data, :ratetogroup)
end

############################# Required Functions ##############################

# creating the JumpAggregation structure (function wrapper-based constant jumps)
Expand Down
5 changes: 5 additions & 0 deletions src/aggregators/sortingdirect.jl
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ function SortingDirectJumpAggregation(nj::Int, njt::T, et::T, crs::Vector{T}, sr
zero(Int), zero(sr))
end

# the fields that `isolated_copy` shares; it copies the others (see `shared_fields`)
function shared_fields(::Type{<:SortingDirectJumpAggregation})
(:ma_jumps, :rates, :affects!, :save_positions, :dependencies)
end

############################# Required Functions ##############################

# creating the JumpAggregation structure (function wrapper-based constant jumps)
Expand Down
21 changes: 21 additions & 0 deletions src/aggregators/ssajump.jl
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,27 @@ end
# initialize!
# execute_jumps!
# generate_jumps!
# shared_fields

"""
shared_fields(::Type{T})

Names of the fields of `T` that hold definitions, which solvers never modify: the rates,
affects and dependency maps of an aggregator, for example. [`isolated_copy`](@ref) shares
these fields with the copy and copies every other field (see `copy_working` in
`isolated_copy.jl`).

Every aggregator, and every type that a solve modifies inside one (rate tables, priority
queues and tables), must define a method next to its definition. A field missing from the
list is copied, or makes `isolated_copy` throw if its type can't be copied, so it is never
shared by mistake.
"""
function shared_fields(::Type{T}) where {T}
throw(ArgumentError("`isolated_copy` can't copy an object of type $T: define \
`JumpProcesses.shared_fields(::Type{<:$(nameof(T))})` listing its fields that \
solvers never modify, or list the field that holds it as shared in the type \
that contains it."))
end

@inline function makewrapper(::Type{T}, aff) where {T}
# rewrap existing wrappers
Expand Down
Loading
Loading