From 3710d7281c07a136f8b3af9acc84da9806b6cb6f Mon Sep 17 00:00:00 2001 From: Sam Isaacson Date: Sun, 8 Nov 2026 07:50:02 -0500 Subject: [PATCH 1/4] Add isolated_copy: a JumpProblem with its own jump state MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `isolated_copy(jprob)` returns a problem that can be solved concurrently with `jprob`, or used for an integrator alive at the same time as one of its, and shares everything that solvers don't modify: the wrapped problem, the jumps and their functions, the dependency maps and the stored callbacks. Each aggregator lists its working fields; the copy rebuilds it through its default constructor from copies of those fields and its other fields as they are, and rebuilds the jump callbacks around it (a new VR_Direct cache; VR_FRM's callbacks are reused). No closure or FunctionWrapper is copied. `resetted_jump_problem`, which StochasticDiffEq calls for `alias_jumps = false` (the default off thread 1), now returns an `isolated_copy` instead of a `deepcopy`. The docs recommend `isolated_copy` over `deepcopy`, and give `deepcopy`'s limitations with FunctionWrapper-based aggregators. Replaces #711, whose tests of concurrent and interleaved use are adapted here. Co-Authored-By: Kaan Öcal <26488673+kaandocal@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- HISTORY.md | 10 + docs/src/api.md | 7 +- docs/src/faq.md | 2 +- docs/src/jump_types.md | 2 +- docs/src/migration.md | 5 +- .../tutorials/ensembles_and_problem_reuse.md | 38 +- src/JumpProcesses.jl | 4 + src/isolated_copy.jl | 164 ++++++++ src/problem.jl | 15 +- src/solve.jl | 2 +- test/isolated_copy.jl | 351 ++++++++++++++++++ test/runtests.jl | 2 + 12 files changed, 581 insertions(+), 21 deletions(-) create mode 100644 src/isolated_copy.jl create mode 100644 test/isolated_copy.jl diff --git a/HISTORY.md b/HISTORY.md index 0143fc3bf..4ebaff1ea 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -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. diff --git a/docs/src/api.md b/docs/src/api.md index ab305211d..90743202b 100644 --- a/docs/src/api.md +++ b/docs/src/api.md @@ -15,6 +15,7 @@ SSAStepper SplitCoupledJumpProblem reset_aggregated_jumps! remake(::JumpProblem) +isolated_copy ``` ## Jump Types @@ -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 @@ -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` diff --git a/docs/src/faq.md b/docs/src/faq.md index 7462829c1..9feab4a63 100644 --- a/docs/src/faq.md +++ b/docs/src/faq.md @@ -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 diff --git a/docs/src/jump_types.md b/docs/src/jump_types.md index 75f9891ba..21264e1de 100644 --- a/docs/src/jump_types.md +++ b/docs/src/jump_types.md @@ -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. diff --git a/docs/src/migration.md b/docs/src/migration.md index a0d84997a..8b689b613 100644 --- a/docs/src/migration.md +++ b/docs/src/migration.md @@ -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 @@ -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. diff --git a/docs/src/tutorials/ensembles_and_problem_reuse.md b/docs/src/tutorials/ensembles_and_problem_reuse.md index 72e75a2f0..ae117ab88 100644 --- a/docs/src/tutorials/ensembles_and_problem_reuse.md +++ b/docs/src/tutorials/ensembles_and_problem_reuse.md @@ -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. @@ -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 @@ -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 @@ -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 @@ -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. @@ -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) ``` @@ -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 | diff --git a/src/JumpProcesses.jl b/src/JumpProcesses.jl index fd4a25c66..08f04b478 100644 --- a/src/JumpProcesses.jl +++ b/src/JumpProcesses.jl @@ -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") diff --git a/src/isolated_copy.jl b/src/isolated_copy.jl new file mode 100644 index 000000000..319ea1977 --- /dev/null +++ b/src/isolated_copy.jl @@ -0,0 +1,164 @@ +# `isolated_copy`: a copy of a `JumpProblem` with its own jump state and everything else +# shared. Each type that holds jump state lists the fields that solvers modify, its working +# fields; the copy rebuilds an object through its default constructor from copies of those +# fields and the other fields as they are. + +# The fields of a type that solvers modify, which `isolated_copy` copies. Every other field is +# shared with the copy. +function working_fields end + +const DIRECT_WORKING_FIELDS = (:next_jump, :prev_jump, :next_jump_time, :end_time, + :cur_rates, :sum_rate, :maj_rates) +const RSSA_WORKING_FIELDS = (:next_jump, :prev_jump, :next_jump_time, :end_time, + :cur_rate_low, :cur_rate_high, :sum_rate, :maj_rates, :ulow, :uhigh, :sum_rate_err) +const SPATIAL_WORKING_FIELDS = (:next_jump, :prev_jump, :next_jump_time, :end_time, + :rx_rates, :hop_rates) + +working_fields(::Type{<:DirectJumpAggregation}) = DIRECT_WORKING_FIELDS +working_fields(::Type{<:FRMJumpAggregation}) = DIRECT_WORKING_FIELDS +function working_fields(::Type{<:SortingDirectJumpAggregation}) + (DIRECT_WORKING_FIELDS..., :jump_search_order, :jump_search_idx, :sum_rate_err) +end +function working_fields(::Type{<:DirectCRJumpAggregation}) + (DIRECT_WORKING_FIELDS..., :minrate, :maxrate, :rt, :sum_rate_err) +end +working_fields(::Type{<:NRMJumpAggregation}) = (DIRECT_WORKING_FIELDS..., :pq) +working_fields(::Type{<:CCNRMJumpAggregation}) = (DIRECT_WORKING_FIELDS..., :ptt) +function working_fields(::Type{<:CoevolveJumpAggregation}) + (DIRECT_WORKING_FIELDS..., :pq, :cur_lrates) +end +function working_fields(::Type{<:RDirectJumpAggregation}) + (DIRECT_WORKING_FIELDS..., :max_rate, :counter, :sum_rate_err) +end +working_fields(::Type{<:RSSAJumpAggregation}) = RSSA_WORKING_FIELDS +function working_fields(::Type{<:RSSACRJumpAggregation}) + (RSSA_WORKING_FIELDS..., :minrate, :maxrate, :rt) +end +working_fields(::Type{<:NSMJumpAggregation}) = (SPATIAL_WORKING_FIELDS..., :pq) +function working_fields(::Type{<:DirectCRDirectJumpAggregation}) + (SPATIAL_WORKING_FIELDS..., :site_rates, :rt) +end +working_fields(::Type{<:RxRates}) = (:rates, :sum_rates, :maj_rates) +working_fields(::Type{<:AbstractHopRates}) = (:rates, :sum_rates) +function working_fields(::Type{<:VR_DirectEventCache}) + (:prev_time, :prev_threshold, :current_time, :current_threshold, :total_rate, + :cum_rate_sum, :rate_fit) +end +function working_fields(::Type{<:TotalRateFit}) + (:panel_starts, :panel_ends, :panel_integrals, :panel_end_integrals, :panel_coefs, + :rate_samples, :rate_coefs) +end +working_fields(::Type{<:PriorityGroup}) = (:maxpriority, :numpids, :pids) +function working_fields(::Type{<:PriorityTable}) + (:minpriority, :maxpriority, :groups, :gsums, :gsum, :pidtogroup) +end +function working_fields(::Type{<:PriorityTimeTable}) + (:groups, :pidtogroup, :times, :timegrouper, :minbin, :steps, :maxtime) +end + +# A new object of the type of `x`, from copies of its working fields and its other fields as +# they are. Every type with `working_fields` keeps its default positional constructor. +@generated function copy_working_state(x::T) where {T} + wf = working_fields(T) + args = map(fieldnames(T)) do name + field = :(getfield(x, $(QuoteNode(name)))) + name in wf ? :(copy_working($field)) : field + end + return :(T($(args...))) +end + +# Copies of working fields. There is deliberately no fallback, so that a working field of a +# new type must be given a method here. +copy_working(x::Union{Number, Nothing, SpatialJump, TimeGrouper}) = x +copy_working(x::AbstractArray) = isbitstype(eltype(x)) ? copy(x) : map(copy_working, x) +# DataStructures' heap holds only numbers +copy_working(x::MutableBinaryMinHeap) = deepcopy(x) +function copy_working(x::Union{RxRates, AbstractHopRates, TotalRateFit, PriorityGroup, + PriorityTable, PriorityTimeTable}) + copy_working_state(x) +end + +fresh_aggregator(::Nothing) = nothing +fresh_aggregator(agg::AbstractSSAJumpAggregator) = copy_working_state(agg) + +# The jump callbacks of a copy, rebuilt around its new aggregator. `vjumps` are the variable +# rate jumps that the `VR_Direct` and `VR_DirectFW` caches handle. +function isolated_jump_callback(cbs::CallbackSet, agg, vjumps) + CallbackSet( + map(cb -> isolated_jump_callback(cb, agg, vjumps), cbs.continuous_callbacks)..., + map(cb -> isolated_jump_callback(cb, agg, vjumps), cbs.discrete_callbacks)...) +end +function isolated_jump_callback(cb::Union{DiscreteCallback, ContinuousCallback}, agg, vjumps) + isolated_jump_callback(cb.condition, cb, agg, vjumps) +end +isolated_jump_callback(cb, agg, vjumps) = cb +function isolated_jump_callback(::AbstractSSAJumpAggregator, ::DiscreteCallback, agg, vjumps) + DiscreteCallback(agg) +end +function isolated_jump_callback(cache::VR_DirectEventCache, ::ContinuousCallback, agg, + vjumps) + build_variable_integcallback(copy_working_state(cache), vjumps) +end +# `VR_FRM`'s callbacks keep their state in the integrator's `u.jump_u`, so they are shared +isolated_jump_callback(condition, cb, agg, vjumps) = cb + +""" + isolated_copy(jprob::JumpProblem) + +Return a `JumpProblem` with its own jump state, sharing everything else with `jprob`. + +The copy shares no state that JumpProcesses' solvers modify, so it can be solved +concurrently with `jprob`, or used for an integrator that is alive at the same time as one of +`jprob`'s. Since it does not copy the wrapped problem or the jumps, it is much cheaper than +`deepcopy(jprob)`, especially for problems built with ModelingToolkit or Catalyst. + +The copy has a new jump aggregator, with copies of the aggregator's working data (such as the +current rates and its priority queue or table), and new jump callbacks built around it, +including a new cache for `VR_Direct` and `VR_DirectFW`. It shares everything else with +`jprob`: + + - the wrapped problem `jprob.prob`, including its function, `u0`, `p` and `tspan`; + - the jumps, with their rate and affect functions; + - the dependency graphs; + - the callbacks and `tstops` passed to the `JumpProblem` constructor. + +The copy starts from `jprob`'s current working data, which solvers re-initialize at every +`init`, so it doesn't matter whether `jprob` was solved before. The one exception is +`SortingDirect`'s learned search order, which the copy keeps. + +A copy may be taken between `step!` calls of an integrator of `jprob`, in the same task. Do +not take one while another thread is solving `jprob`. + +## What the copy does not isolate + + - `p` and `u0`. Solvers may alias them, so a callback that modifies `integrator.p` can also + modify `jprob.prob.p`. Use `remake(isolated_copy(jprob); p = new_p)` to give the copy its + own parameters. With `alias_u0 = true`, an integrator's state is `jprob.prob.u0`, so a copy + initialized after it has run starts from that integrator's current state. + - State captured by rate, affect or callback functions. Pass callbacks with such state to + `init` or `solve` instead of storing them in the problem. + - A noise process passed to an `SDEProblem` with `noise`. StochasticDiffEq copies each + solve's noise back into `prob.noise`, so copies that share it must not be solved + concurrently. Give a copy its own with + `remake(isolated_copy(jprob); prob = remake(jprob.prob; noise = new_noise))`. + +`deepcopy(jprob)` also copies `p`, `u0`, the stored callbacks and the wrapped problem, at a +much higher cost; see [`JumpProblem`](@ref) for its limitations. + +## 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) + agg = fresh_aggregator(jprob.discrete_jump_aggregation) + jump_callback = isolated_jump_callback(jprob.jump_callback, agg, jprob.variable_jumps) + remaker_of(jprob)(jprob.prob, jprob.aggregator, agg, jump_callback, + jprob.constant_jumps, jprob.variable_jumps, jprob.regular_jump, + jprob.massaction_jump, jprob.kwargs) +end diff --git a/src/problem.jl b/src/problem.jl index 7d0a87611..549ebc2dc 100644 --- a/src/problem.jl +++ b/src/problem.jl @@ -108,7 +108,16 @@ 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) gives a copy + with its own jump state that shares everything else, including `p`, `u0` and the + stored callbacks. + - `deepcopy(jprob)` also copies the wrapped problem, `p`, `u0` and the stored + callbacks, at a much higher cost. For jumps whose functions are stored in + `FunctionWrapper`s (the `ConstantRateJump`s of every aggregator except `Direct` and + `FRM`, the bounded `VariableRateJump`s of `Coevolve`, and the `VariableRateJump`s of + `VR_DirectFW`), the copy may call the original's rate and affect functions, so it + does not isolate state that they capture, and the original problem must stay + referenced for as long as the copy is used. - `remake(jprob; ...)` shares the original's jump state, so remade problems are not independent for concurrent use. - `EnsembleProblem` supplies isolation. `EnsembleSerial` reuses the problem @@ -227,8 +236,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...) diff --git a/src/solve.jl b/src/solve.jl index b6a5553de..19f874d55 100644 --- a/src/solve.jl +++ b/src/solve.jl @@ -114,7 +114,7 @@ end # itself no longer calls these. The seed argument is accepted but no longer used to # reseed aggregator RNGs (RNG state is now managed by the integrator). function resetted_jump_problem(_jump_prob, seed = nothing) - deepcopy(_jump_prob) + isolated_copy(_jump_prob) end function reset_jump_problem!(jump_prob, seed = nothing) diff --git a/test/isolated_copy.jl b/test/isolated_copy.jl new file mode 100644 index 000000000..d61316d07 --- /dev/null +++ b/test/isolated_copy.jl @@ -0,0 +1,351 @@ +using JumpProcesses, OrdinaryDiffEq, StochasticDiffEq, SciMLBase, Test +using JumpProcesses: working_fields + +# `isolated_copy` gives a problem its own jump state and shares everything else. The tests of +# integrators alive at the same time, variable-rate jumps, threaded solves, spatial +# aggregators, independence from the original's memory and `PureLeaping` are adapted from +# those by Kaan Öcal in #711. + +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!)) + dependencies = JumpDependencies(; dep_graph = [[1, 2], [1, 2]], + vartojumps_map = [[1], [2]], jumptovars_map = [[1, 2], [1, 2]]) + JumpProblem(prob, aggregator, jumps...; dependencies, 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, + kwargs1 = (;), kwargs2 = (;)) + integrators = (init(prob1, alg; seed = seeds[1], kwargs1...), + init(prob2, alg; seed = seeds[2], kwargs2...)) + 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 + +# Growth of u[1], with births of u[2] at rate u[1] and resets of u[1] at a constant rate +function growth_jprob(vr_aggregator) + 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)) + JumpProblem(oprob, Direct(), birth, reset; vr_aggregator) +end + +# The fields that `isolated_copy` shares for each aggregator. With the working fields they +# must cover every field, so that a new field has to be classified. +const COMMON_SHARED = (:ma_jumps, :rates, :affects!, :save_positions) +const SPATIAL_SHARED = (:rates, :affects!, :save_positions, :dependencies, :spatial_system, + :numspecies) +const SHARED_FIELDS = Dict( + :DirectJumpAggregation => COMMON_SHARED, + :FRMJumpAggregation => COMMON_SHARED, + :SortingDirectJumpAggregation => (COMMON_SHARED..., :dependencies), + :DirectCRJumpAggregation => (COMMON_SHARED..., :dependencies, :ratetogroup), + :RSSAJumpAggregation => (COMMON_SHARED..., :brackets, :dependencies, :bracket_data), + :RSSACRJumpAggregation => (COMMON_SHARED..., :brackets, :dependencies, :bracket_data, + :ratetogroup), + :NRMJumpAggregation => (COMMON_SHARED..., :dependencies), + :CCNRMJumpAggregation => (COMMON_SHARED..., :dependencies), + :CoevolveJumpAggregation => (COMMON_SHARED..., :dependencies, :lrates, :urates, + :rateintervals, :haslratevec), + :RDirectJumpAggregation => (COMMON_SHARED..., :dependencies, :counter_threshold), + :NSMJumpAggregation => SPATIAL_SHARED, + :DirectCRDirectJumpAggregation => (SPATIAL_SHARED..., :ratetogroup)) + +# Working fields are copies (values of bits types are copied by construction); every other +# field is the original's +function test_copied_and_shared_fields(orig, copied) + T = typeof(orig) + @test typeof(copied) === T + @test copied !== orig + for name in fieldnames(T) + x, y = getfield(orig, name), getfield(copied, name) + if name in working_fields(T) + @test isbits(x) || x !== y + else + @test x === y + end + end +end + +# Priority tables (`rt`, `ptt`) are copied down to their groups +function test_copied_tables(agg, agg_copy) + for name in (:rt, :ptt) + hasfield(typeof(agg), name) || continue + table, table_copy = getfield(agg, name), getfield(agg_copy, name) + test_copied_and_shared_fields(table, table_copy) + @test length(table.groups) == length(table_copy.groups) + for (group, group_copy) in zip(table.groups, table_copy.groups) + test_copied_and_shared_fields(group, group_copy) + @test group.pids == group_copy.pids + end + end +end + +# The fields of the problem that every copy shares +const SHARED_PROBLEM_FIELDS = (:prob, :aggregator, :constant_jumps, :variable_jumps, + :regular_jump, :massaction_jump, :kwargs) + +@testset "Shares the jumps and copies the jump state: $(nameof(typeof(aggregator))), \ + massaction = $massaction" for aggregator in JumpProcesses.JUMP_AGGREGATORS, + massaction in (true, false) + + jprob = ab_jprob(aggregator; massaction, callback = stop_after_jumps(5), tstops = [1.0]) + jcopy = isolated_copy(jprob) + + @test jcopy isa typeof(jprob) + for name in SHARED_PROBLEM_FIELDS + @test getfield(jcopy, name) === getfield(jprob, name) + end + + agg = jprob.discrete_jump_aggregation + T = typeof(agg) + shared = SHARED_FIELDS[nameof(T)] + @test Set(fieldnames(T)) == Set((working_fields(T)..., shared...)) + @test isempty(intersect(working_fields(T), shared)) + test_copied_and_shared_fields(agg, jcopy.discrete_jump_aggregation) + test_copied_tables(agg, jcopy.discrete_jump_aggregation) + + # The copied callback uses the copied aggregation, also in integrators + jump_cb = only(jcopy.jump_callback.discrete_callbacks) + @test jump_cb.condition === jump_cb.affect! === jump_cb.initialize === + 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 "Copies of a problem with a live integrator: $(nameof(typeof(aggregator)))" for aggregator in JumpProcesses.JUMP_AGGREGATORS + jprob = ab_jprob(aggregator; massaction = false) + fresh = isolated_copy(jprob) + ref = path(solve(isolated_copy(jprob), SSAStepper(); seed = 1)) + + integrator = init(jprob, SSAStepper(); seed = 1) + for _ in 1:5 + step!(integrator) + end + live_copy = isolated_copy(jprob) + if aggregator isa SortingDirect + # the copy keeps the order learned so far + @test live_copy.discrete_jump_aggregation.jump_search_order == + jprob.discrete_jump_aggregation.jump_search_order + else + @test path(solve(live_copy, SSAStepper(); seed = 2)) == + path(solve(fresh, SSAStepper(); seed = 2)) + end + + # A copy whose integrator has another type wraps the affects for that type, which must + # leave the original integrator's wrappers alone + other = init(isolated_copy(jprob), SSAStepper(); seed = 3, saveat = 0.5, + callback = DiscreteCallback((u, t, integrator) -> false, integrator -> nothing)) + @test typeof(other) != typeof(integrator) + solve!(other) + + # The original integrator continues as if no copy had been made + solve!(integrator) + @test path(integrator.sol) == ref +end + +@testset "ODE problems with variable-rate jumps: $(nameof(typeof(vr_aggregator)))" for vr_aggregator in (VR_FRM(), VR_Direct(), VR_DirectFW()) + jprob = growth_jprob(vr_aggregator) + jcopy = isolated_copy(jprob) + + @test jcopy isa typeof(jprob) + for name in SHARED_PROBLEM_FIELDS + @test getfield(jcopy, name) === getfield(jprob, name) + end + vr_cb = only(jprob.jump_callback.continuous_callbacks) + vr_cb_copy = only(jcopy.jump_callback.continuous_callbacks) + if vr_aggregator isa VR_FRM + # its callbacks keep their state in the integrator's `u.jump_u` + @test vr_cb_copy === vr_cb + else + cache, cache_copy = vr_cb.condition, vr_cb_copy.condition + @test vr_cb_copy.affect! === cache_copy + test_copied_and_shared_fields(cache, cache_copy) + test_copied_and_shared_fields(cache.rate_fit, cache_copy.rate_fit) + @test (vr_cb_copy.save_positions, vr_cb_copy.abstol, vr_cb_copy.reltol) == + (vr_cb.save_positions, vr_cb.abstol, vr_cb.reltol) + end + + refs = map(seed -> path(solve(deepcopy(jprob), Tsit5(); seed)), (1, 2)) + @test interleaved_paths(jprob, isolated_copy(jprob), Tsit5(); nsteps = 3) == refs + + # A copy taken between the steps of a live integrator + integrator = init(jprob, Tsit5(); seed = 1) + foreach(_ -> step!(integrator), 1:3) + @test path(solve(isolated_copy(jprob), Tsit5(); seed = 2)) == refs[2] + solve!(integrator) + @test path(integrator.sol) == refs[1] +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 + + # Jump-ODE problems, whose copies share the wrapped `ODEProblem` + for vr_aggregator in (VR_FRM(), VR_Direct()) + jprob = growth_jprob(vr_aggregator) + refs = [path(solve(deepcopy(jprob), Tsit5(); seed)) for seed in 1:8] + tasks = [Threads.@spawn path(solve(isolated_copy(jprob), Tsit5(); seed)) + for seed in 1:8] + @test fetch.(tasks) == refs + end +end + +@testset "Callbacks passed to the JumpProblem are shared" begin + birth = MassActionJump([[0 => 1]], [[1 => 1]]; param_idxs = [1]) + dprob = DiscreteProblem([0], (0.0, 100.0), [1.0]) + jprob = JumpProblem(dprob, Direct(), birth; callback = stop_after_jumps(5)) + @test isolated_copy(jprob).kwargs[:callback] === jprob.kwargs[:callback] + + # Callbacks with state passed to `init` are not, so each simulation stops at its own + # fifth jump + jprob = JumpProblem(dprob, Direct(), birth) + (_, u1), (_, u2) = interleaved_paths(jprob, isolated_copy(jprob), SSAStepper(); + nsteps = 3, kwargs1 = (; callback = stop_after_jumps(5)), + kwargs2 = (; callback = stop_after_jumps(5))) + @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 = [Ref(-1.0) for _ in 1:200_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,))) + jcopy = isolated_copy(jprob) + + agg = jprob.discrete_jump_aggregation + T = typeof(agg) + shared = SHARED_FIELDS[nameof(T)] + @test Set(fieldnames(T)) == Set((working_fields(T)..., shared...)) + test_copied_and_shared_fields(agg, jcopy.discrete_jump_aggregation) + test_copied_and_shared_fields(agg.rx_rates, jcopy.discrete_jump_aggregation.rx_rates) + test_copied_and_shared_fields(agg.hop_rates, jcopy.discrete_jump_aggregation.hop_rates) + test_copied_tables(agg, jcopy.discrete_jump_aggregation) + + refs = map(seed -> path(solve(deepcopy(jprob), SSAStepper(); seed)), (1, 2)) + @test interleaved_paths(jprob, isolated_copy(jprob), SSAStepper()) == refs +end + +@testset "Jump-diffusions, through `resetted_jump_problem`" begin + f!(du, u, p, t) = (du .= 0; nothing) + g!(du, u, p, t) = (du .= 0.1; nothing) + sprob = SDEProblem(f!, g!, [10.0, 5.0], (0.0, 2.0), [0.7, 0.4]) + ab!(integrator) = (integrator.u[1] -= 1; integrator.u[2] += 1; nothing) + ba!(integrator) = (integrator.u[1] += 1; integrator.u[2] -= 1; nothing) + jprob = JumpProblem(sprob, Direct(), + ConstantRateJump((u, p, t) -> p[1] * max(u[1], 0), ab!), + ConstantRateJump((u, p, t) -> p[2] * max(u[2], 0), ba!)) + + jcopy = JumpProcesses.resetted_jump_problem(jprob, nothing) + @test jcopy.prob === jprob.prob + @test jcopy.discrete_jump_aggregation !== jprob.discrete_jump_aggregation + + # `alias_jumps = false` solves a copy, leaving the problem's jump state alone + rates = copy(jprob.discrete_jump_aggregation.cur_rates) + sol_copy = solve(jprob, SRIW1(); seed = 1, + alias = SciMLBase.SDEAliasSpecifier(alias_jumps = false)) + @test isequal(jprob.discrete_jump_aggregation.cur_rates, rates) + sol = solve(jprob, SRIW1(); seed = 1, + alias = SciMLBase.SDEAliasSpecifier(alias_jumps = true)) + @test path(sol_copy) == path(sol) +end + +@testset "With `alias_u0 = true`, a copy starts from the integrator's current state" begin + jprob = ab_jprob(Direct()) + integrator = init(jprob, SSAStepper(); seed = 1, + alias = SciMLBase.DiscreteAliasSpecifier(alias_u0 = true)) + foreach(_ -> step!(integrator), 1:5) + @test integrator.u === jprob.prob.u0 + @test init(isolated_copy(jprob), SSAStepper(); seed = 2).u == integrator.u +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 !== jprob + @test all(name -> getfield(jcopy, name) === getfield(jprob, name), + fieldnames(typeof(jprob))) + @test path(solve(jcopy, SimpleExplicitTauLeaping(); seed = 1)) == + path(solve(deepcopy(jprob), SimpleExplicitTauLeaping(); seed = 1)) +end diff --git a/test/runtests.jl b/test/runtests.jl index e1a93d359..a31874971 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -53,6 +53,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 @@ -76,6 +77,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" From 0d2ac6c0cadb643df645a34bc42a576a1c71de3d Mon Sep 17 00:00:00 2001 From: Sam Isaacson Date: Sun, 8 Nov 2026 08:05:09 -0500 Subject: [PATCH 2/4] Rename the test's ab!/ba! affects, which the typos check flags Co-Authored-By: Claude Opus 5.5 --- test/isolated_copy.jl | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/test/isolated_copy.jl b/test/isolated_copy.jl index d61316d07..91fec0736 100644 --- a/test/isolated_copy.jl +++ b/test/isolated_copy.jl @@ -18,10 +18,10 @@ function ab_jprob(aggregator; massaction = true, kwargs...) 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!)) + a_to_b!(integrator) = (integrator.u[1] -= 1; integrator.u[2] += 1; nothing) + b_to_a!(integrator) = (integrator.u[1] += 1; integrator.u[2] -= 1; nothing) + jumps = (ConstantRateJump((u, p, t) -> p[1] * u[1], a_to_b!), + ConstantRateJump((u, p, t) -> p[2] * u[2], b_to_a!)) dependencies = JumpDependencies(; dep_graph = [[1, 2], [1, 2]], vartojumps_map = [[1], [2]], jumptovars_map = [[1, 2], [1, 2]]) JumpProblem(prob, aggregator, jumps...; dependencies, kwargs...) @@ -308,11 +308,11 @@ end f!(du, u, p, t) = (du .= 0; nothing) g!(du, u, p, t) = (du .= 0.1; nothing) sprob = SDEProblem(f!, g!, [10.0, 5.0], (0.0, 2.0), [0.7, 0.4]) - ab!(integrator) = (integrator.u[1] -= 1; integrator.u[2] += 1; nothing) - ba!(integrator) = (integrator.u[1] += 1; integrator.u[2] -= 1; nothing) + a_to_b!(integrator) = (integrator.u[1] -= 1; integrator.u[2] += 1; nothing) + b_to_a!(integrator) = (integrator.u[1] += 1; integrator.u[2] -= 1; nothing) jprob = JumpProblem(sprob, Direct(), - ConstantRateJump((u, p, t) -> p[1] * max(u[1], 0), ab!), - ConstantRateJump((u, p, t) -> p[2] * max(u[2], 0), ba!)) + ConstantRateJump((u, p, t) -> p[1] * max(u[1], 0), a_to_b!), + ConstantRateJump((u, p, t) -> p[2] * max(u[2], 0), b_to_a!)) jcopy = JumpProcesses.resetted_jump_problem(jprob, nothing) @test jcopy.prob === jprob.prob From 7e22eac8775f04df41d0128bbe94aeae5025381a Mon Sep 17 00:00:00 2001 From: Sam Isaacson Date: Mon, 9 Nov 2026 08:53:39 -0500 Subject: [PATCH 3/4] Declare the fields isolated_copy shares next to each type; keep fresh buffers From review: copying arrays of non-bits numbers element by element read the unassigned entries of a fresh aggregator's buffers (`Vector{BigFloat}(undef, n)`), so `isolated_copy` threw `UndefRefError` for unsolved problems with `BigFloat` times or `BigInt` states. Arrays of numbers are now copied as containers. Each type that holds jump state now declares, next to its definition, the fields that hold definitions (`shared_fields`), and `isolated_copy` copies every other field. A field nobody classified is copied, or makes `isolated_copy` throw with an explanation if its type can't be copied, instead of being shared by mistake; this caught `TimeGrouper`, which isn't a bits type with `BigFloat` times. The generated rebuild now calls `shared_fields` from the generated code rather than in the generator, so declarations made in other packages are seen. Copy times are unchanged. Tests copy unsolved problems with BigFloat times for each aggregator that supports them, a BigInt state with RSSA and BigFloat ODEs with VR_Direct and VR_DirectFW, and check that every aggregator and hopping-rate type declares its shared fields. Co-Authored-By: Claude Opus 5.5 --- src/aggregators/ccnrm.jl | 5 ++ src/aggregators/coevolve.jl | 6 ++ src/aggregators/direct.jl | 5 ++ src/aggregators/directcr.jl | 5 ++ src/aggregators/frm.jl | 5 ++ src/aggregators/nrm.jl | 5 ++ src/aggregators/prioritytable.jl | 8 +++ src/aggregators/rdirect.jl | 5 ++ src/aggregators/rssa.jl | 6 ++ src/aggregators/rssacr.jl | 6 ++ src/aggregators/sortingdirect.jl | 5 ++ src/aggregators/ssajump.jl | 21 +++++++ src/isolated_copy.jl | 92 +++++++-------------------- src/spatial/directcrdirect.jl | 6 ++ src/spatial/hop_rates.jl | 24 +++++++ src/spatial/nsm.jl | 5 ++ src/spatial/reaction_rates.jl | 2 + src/variable_rate.jl | 4 ++ test/isolated_copy.jl | 103 +++++++++++++++++++------------ 19 files changed, 209 insertions(+), 109 deletions(-) diff --git a/src/aggregators/ccnrm.jl b/src/aggregators/ccnrm.jl index 8e944fff7..b902a017e 100644 --- a/src/aggregators/ccnrm.jl +++ b/src/aggregators/ccnrm.jl @@ -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, diff --git a/src/aggregators/coevolve.jl b/src/aggregators/coevolve.jl index f0068df44..c01a402a2 100644 --- a/src/aggregators/coevolve.jl +++ b/src/aggregators/coevolve.jl @@ -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...) diff --git a/src/aggregators/direct.jl b/src/aggregators/direct.jl index 061318c0a..3083d161e 100644 --- a/src/aggregators/direct.jl +++ b/src/aggregators/direct.jl @@ -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) diff --git a/src/aggregators/directcr.jl b/src/aggregators/directcr.jl index 8bbb9fc6e..dd56cae4a 100644 --- a/src/aggregators/directcr.jl +++ b/src/aggregators/directcr.jl @@ -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) diff --git a/src/aggregators/frm.jl b/src/aggregators/frm.jl index 8a4c7e2bf..79ec8fd55 100644 --- a/src/aggregators/frm.jl +++ b/src/aggregators/frm.jl @@ -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) diff --git a/src/aggregators/nrm.jl b/src/aggregators/nrm.jl index f36cda039..4068dd447 100644 --- a/src/aggregators/nrm.jl +++ b/src/aggregators/nrm.jl @@ -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, diff --git a/src/aggregators/prioritytable.jl b/src/aggregators/prioritytable.jl index 620a062c9..6572a3e1d 100644 --- a/src/aggregators/prioritytable.jl +++ b/src/aggregators/prioritytable.jl @@ -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 @@ -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 @@ -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 @@ -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) diff --git a/src/aggregators/rdirect.jl b/src/aggregators/rdirect.jl index a76caa3ff..2c211ffa7 100644 --- a/src/aggregators/rdirect.jl +++ b/src/aggregators/rdirect.jl @@ -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) diff --git a/src/aggregators/rssa.jl b/src/aggregators/rssa.jl index 488e35562..97e4c8c3c 100644 --- a/src/aggregators/rssa.jl +++ b/src/aggregators/rssa.jl @@ -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) diff --git a/src/aggregators/rssacr.jl b/src/aggregators/rssacr.jl index f54f22ad4..d3f2c92e9 100644 --- a/src/aggregators/rssacr.jl +++ b/src/aggregators/rssacr.jl @@ -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) diff --git a/src/aggregators/sortingdirect.jl b/src/aggregators/sortingdirect.jl index 3eff3057f..143f89fd3 100644 --- a/src/aggregators/sortingdirect.jl +++ b/src/aggregators/sortingdirect.jl @@ -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) diff --git a/src/aggregators/ssajump.jl b/src/aggregators/ssajump.jl index 7d10ce9aa..0ffd1dcff 100644 --- a/src/aggregators/ssajump.jl +++ b/src/aggregators/ssajump.jl @@ -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 diff --git a/src/isolated_copy.jl b/src/isolated_copy.jl index 319ea1977..7307da620 100644 --- a/src/isolated_copy.jl +++ b/src/isolated_copy.jl @@ -1,82 +1,34 @@ # `isolated_copy`: a copy of a `JumpProblem` with its own jump state and everything else -# shared. Each type that holds jump state lists the fields that solvers modify, its working -# fields; the copy rebuilds an object through its default constructor from copies of those -# fields and the other fields as they are. - -# The fields of a type that solvers modify, which `isolated_copy` copies. Every other field is -# shared with the copy. -function working_fields end - -const DIRECT_WORKING_FIELDS = (:next_jump, :prev_jump, :next_jump_time, :end_time, - :cur_rates, :sum_rate, :maj_rates) -const RSSA_WORKING_FIELDS = (:next_jump, :prev_jump, :next_jump_time, :end_time, - :cur_rate_low, :cur_rate_high, :sum_rate, :maj_rates, :ulow, :uhigh, :sum_rate_err) -const SPATIAL_WORKING_FIELDS = (:next_jump, :prev_jump, :next_jump_time, :end_time, - :rx_rates, :hop_rates) - -working_fields(::Type{<:DirectJumpAggregation}) = DIRECT_WORKING_FIELDS -working_fields(::Type{<:FRMJumpAggregation}) = DIRECT_WORKING_FIELDS -function working_fields(::Type{<:SortingDirectJumpAggregation}) - (DIRECT_WORKING_FIELDS..., :jump_search_order, :jump_search_idx, :sum_rate_err) -end -function working_fields(::Type{<:DirectCRJumpAggregation}) - (DIRECT_WORKING_FIELDS..., :minrate, :maxrate, :rt, :sum_rate_err) -end -working_fields(::Type{<:NRMJumpAggregation}) = (DIRECT_WORKING_FIELDS..., :pq) -working_fields(::Type{<:CCNRMJumpAggregation}) = (DIRECT_WORKING_FIELDS..., :ptt) -function working_fields(::Type{<:CoevolveJumpAggregation}) - (DIRECT_WORKING_FIELDS..., :pq, :cur_lrates) -end -function working_fields(::Type{<:RDirectJumpAggregation}) - (DIRECT_WORKING_FIELDS..., :max_rate, :counter, :sum_rate_err) -end -working_fields(::Type{<:RSSAJumpAggregation}) = RSSA_WORKING_FIELDS -function working_fields(::Type{<:RSSACRJumpAggregation}) - (RSSA_WORKING_FIELDS..., :minrate, :maxrate, :rt) -end -working_fields(::Type{<:NSMJumpAggregation}) = (SPATIAL_WORKING_FIELDS..., :pq) -function working_fields(::Type{<:DirectCRDirectJumpAggregation}) - (SPATIAL_WORKING_FIELDS..., :site_rates, :rt) -end -working_fields(::Type{<:RxRates}) = (:rates, :sum_rates, :maj_rates) -working_fields(::Type{<:AbstractHopRates}) = (:rates, :sum_rates) -function working_fields(::Type{<:VR_DirectEventCache}) - (:prev_time, :prev_threshold, :current_time, :current_threshold, :total_rate, - :cum_rate_sum, :rate_fit) -end -function working_fields(::Type{<:TotalRateFit}) - (:panel_starts, :panel_ends, :panel_integrals, :panel_end_integrals, :panel_coefs, - :rate_samples, :rate_coefs) -end -working_fields(::Type{<:PriorityGroup}) = (:maxpriority, :numpids, :pids) -function working_fields(::Type{<:PriorityTable}) - (:minpriority, :maxpriority, :groups, :gsums, :gsum, :pidtogroup) -end -function working_fields(::Type{<:PriorityTimeTable}) - (:groups, :pidtogroup, :times, :timegrouper, :minbin, :steps, :maxtime) -end - -# A new object of the type of `x`, from copies of its working fields and its other fields as -# they are. Every type with `working_fields` keeps its default positional constructor. +# shared. Each type that holds jump state declares, next to its definition, the fields that +# hold definitions (`shared_fields`, see aggregators/ssajump.jl); the copy rebuilds an object +# through its default constructor from those fields as they are and copies of all the others. + +# A new object of the type of `x`, sharing its `shared_fields` and copying its other fields. +# Every type with `shared_fields` keeps its default positional constructor. The generator +# only reads the field names: `shared_fields` is called by the generated code, where it folds +# to a constant, so that declarations made in other packages, after this one loads, are seen. +# (Building the fields with `ntuple` instead allocated more for some types, such as +# `PriorityTable`.) @generated function copy_working_state(x::T) where {T} - wf = working_fields(T) - args = map(fieldnames(T)) do name + fields = map(fieldnames(T)) do name field = :(getfield(x, $(QuoteNode(name)))) - name in wf ? :(copy_working($field)) : field + :($(QuoteNode(name)) in shared_fields(T) ? $field : copy_working($field)) end - return :(T($(args...))) + return :(T($(fields...))) end -# Copies of working fields. There is deliberately no fallback, so that a working field of a -# new type must be given a method here. -copy_working(x::Union{Number, Nothing, SpatialJump, TimeGrouper}) = x +# Copies of the fields that solvers modify. Numbers, `BigFloat`s included, are never modified +# in place, so they are shared; arrays of numbers are copied as containers, which keeps the +# unassigned entries of fresh buffers (`Vector{BigFloat}(undef, n)`) unassigned. +copy_working(x::Number) = x +copy_working(x::AbstractArray{<:Number}) = copy(x) copy_working(x::AbstractArray) = isbitstype(eltype(x)) ? copy(x) : map(copy_working, x) # DataStructures' heap holds only numbers copy_working(x::MutableBinaryMinHeap) = deepcopy(x) -function copy_working(x::Union{RxRates, AbstractHopRates, TotalRateFit, PriorityGroup, - PriorityTable, PriorityTimeTable}) - copy_working_state(x) -end +# Values of bits types are copied by value. Any other type must declare its `shared_fields`, +# so that a field nobody classified is copied, or makes `isolated_copy` throw, but is never +# shared by mistake. +copy_working(x) = isbits(x) ? x : copy_working_state(x) fresh_aggregator(::Nothing) = nothing fresh_aggregator(agg::AbstractSSAJumpAggregator) = copy_working_state(agg) diff --git a/src/spatial/directcrdirect.jl b/src/spatial/directcrdirect.jl index bc15eb8fc..f2528f170 100644 --- a/src/spatial/directcrdirect.jl +++ b/src/spatial/directcrdirect.jl @@ -50,6 +50,12 @@ function DirectCRDirectJumpAggregation(nj::SpatialJump{J}, njt::T, et::T, rx_rat rt, ratetogroup) end +# the fields that `isolated_copy` shares; it copies the others (see `shared_fields`) +function shared_fields(::Type{<:DirectCRDirectJumpAggregation}) + (:rates, :affects!, :save_positions, :dependencies, :spatial_system, + :numspecies, :ratetogroup) +end + ############################# Required Functions ############################## # creating the JumpAggregation structure (function wrapper-based constant jumps) function aggregate(aggregator::DirectCRDirect, starting_state, p, t, end_time, diff --git a/src/spatial/hop_rates.jl b/src/spatial/hop_rates.jl index 8154c8567..a609a82f1 100644 --- a/src/spatial/hop_rates.jl +++ b/src/spatial/hop_rates.jl @@ -138,6 +138,8 @@ struct HopRatesGraphDs{F} <: AbstractHopRates """ sum_rates::Vector{F} end +# the fields that `isolated_copy` shares; it copies the others (see `shared_fields`) +shared_fields(::Type{<:HopRatesGraphDs}) = (:hopping_constants,) function Base.show(io::IO, ::MIME"text/plain", hop_rates::HopRatesGraphDs) num_specs, num_sites = size(hop_rates.rates) @@ -184,6 +186,8 @@ struct HopRatesGraphDsi{F} <: AbstractHopRates """ sum_rates::Vector{F} end +# the fields that `isolated_copy` shares; it copies the others (see `shared_fields`) +shared_fields(::Type{<:HopRatesGraphDsi}) = (:hopping_constants,) function Base.show(io::IO, ::MIME"text/plain", hop_rates::HopRatesGraphDsi) num_specs, num_sites = size(hop_rates.rates) @@ -230,6 +234,8 @@ struct HopRatesGraphDsij{F} <: AbstractHopRates """ sum_rates::Vector{F} end +# the fields that `isolated_copy` shares; it copies the others (see `shared_fields`) +shared_fields(::Type{<:HopRatesGraphDsij}) = (:hop_const_cumulative_sums,) function Base.show(io::IO, ::MIME"text/plain", hop_rates::HopRatesGraphDsij) num_specs, num_sites = size(hop_rates.rates) @@ -281,6 +287,8 @@ struct HopRatesGridDsij{F} <: AbstractHopRates """ sum_rates::Vector{F} end +# the fields that `isolated_copy` shares; it copies the others (see `shared_fields`) +shared_fields(::Type{<:HopRatesGridDsij}) = (:hop_const_cumulative_sums,) function Base.show(io::IO, ::MIME"text/plain", hop_rates::HopRatesGridDsij) num_specs, num_sites = size(hop_rates.rates) @@ -345,6 +353,10 @@ struct HopRatesGraphDsLij{F} <: AbstractHopRates """ sum_rates::Vector{F} end +# the fields that `isolated_copy` shares; it copies the others (see `shared_fields`) +function shared_fields(::Type{<:HopRatesGraphDsLij}) + (:species_hop_constants, :hop_const_cumulative_sums) +end function Base.show(io::IO, ::MIME"text/plain", hop_rates::HopRatesGraphDsLij) num_specs, @@ -402,6 +414,10 @@ struct HopRatesGridDsLij{F} <: AbstractHopRates """ sum_rates::Vector{F} end +# the fields that `isolated_copy` shares; it copies the others (see `shared_fields`) +function shared_fields(::Type{<:HopRatesGridDsLij}) + (:species_hop_constants, :hop_const_cumulative_sums) +end function Base.show(io::IO, ::MIME"text/plain", hop_rates::HopRatesGridDsLij) num_specs, @@ -464,6 +480,10 @@ struct HopRatesGraphDsiLij{F} <: AbstractHopRates """ sum_rates::Vector{F} end +# the fields that `isolated_copy` shares; it copies the others (see `shared_fields`) +function shared_fields(::Type{<:HopRatesGraphDsiLij}) + (:species_hop_constants, :hop_const_cumulative_sums) +end function Base.show(io::IO, ::MIME"text/plain", hop_rates::HopRatesGraphDsiLij) num_specs, num_sites = size(hop_rates.species_hop_constants) @@ -515,6 +535,10 @@ struct HopRatesGridDsiLij{F} <: AbstractHopRates """ sum_rates::Vector{F} end +# the fields that `isolated_copy` shares; it copies the others (see `shared_fields`) +function shared_fields(::Type{<:HopRatesGridDsiLij}) + (:species_hop_constants, :hop_const_cumulative_sums) +end function Base.show(io::IO, ::MIME"text/plain", hop_rates::HopRatesGridDsiLij) num_specs, diff --git a/src/spatial/nsm.jl b/src/spatial/nsm.jl index e5110541f..97102620f 100644 --- a/src/spatial/nsm.jl +++ b/src/spatial/nsm.jl @@ -39,6 +39,11 @@ function NSMJumpAggregation( num_specs) end +# the fields that `isolated_copy` shares; it copies the others (see `shared_fields`) +function shared_fields(::Type{<:NSMJumpAggregation}) + (:rates, :affects!, :save_positions, :dependencies, :spatial_system, :numspecies) +end + ############################# Required Functions ############################## # creating the JumpAggregation structure (function wrapper-based constant jumps) function aggregate(aggregator::NSM, starting_state, p, t, end_time, constant_jumps, diff --git a/src/spatial/reaction_rates.jl b/src/spatial/reaction_rates.jl index b4854f44c..d67da1832 100644 --- a/src/spatial/reaction_rates.jl +++ b/src/spatial/reaction_rates.jl @@ -24,6 +24,8 @@ struct RxRates{F, M} """ maj_rates::Vector{F} end +# the fields that `isolated_copy` shares; it copies the others (see `shared_fields`) +shared_fields(::Type{<:RxRates}) = (:ma_jumps,) """ RxRates(num_sites::Int, ma_jumps::M) where {M} diff --git a/src/variable_rate.jl b/src/variable_rate.jl index eb1f57f90..6d4e33df8 100644 --- a/src/variable_rate.jl +++ b/src/variable_rate.jl @@ -552,6 +552,8 @@ struct TotalRateFit{T} # the interpolant's integral over [-1, 1] is ∑ₖ integral_weights[k + 1] cₖ integral_weights::Vector{T} end +# the fields that `isolated_copy` shares; it copies the others (see `shared_fields`) +shared_fields(::Type{<:TotalRateFit}) = (:nodes, :transform, :integral_weights) function TotalRateFit{T}() where {T} n = NUM_CHEB_NODES @@ -583,6 +585,8 @@ mutable struct VR_DirectEventCache{T, F1, F2} cum_rate_sum::Vector{T} rate_fit::TotalRateFit{T} end +# the fields that `isolated_copy` shares; it copies the others (see `shared_fields`) +shared_fields(::Type{<:VR_DirectEventCache}) = (:rate_funcs, :affect_funcs) # `vjumps` are the jumps the cache handles: the variable rate jumps not handled by the SSA # aggregator (`Coevolve` takes the bounded ones) diff --git a/test/isolated_copy.jl b/test/isolated_copy.jl index 91fec0736..5c23a9d87 100644 --- a/test/isolated_copy.jl +++ b/test/isolated_copy.jl @@ -1,5 +1,6 @@ using JumpProcesses, OrdinaryDiffEq, StochasticDiffEq, SciMLBase, Test -using JumpProcesses: working_fields +using JumpProcesses: shared_fields +using InteractiveUtils: subtypes # `isolated_copy` gives a problem its own jump state and shares everything else. The tests of # integrators alive at the same time, variable-rate jumps, threaded solves, spatial @@ -8,9 +9,10 @@ using JumpProcesses: working_fields 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]) +# A <-> B, as mass-action or constant-rate jumps, with state type `U` and time and parameter +# type `T` +function ab_jprob(aggregator; massaction = true, U = Int, T = Float64, kwargs...) + prob = DiscreteProblem(U[12, 8], (zero(T), T(5)), T[0.7, 0.4]) reactant_stoch = [[1 => 1], [2 => 1]] net_stoch = [[1 => -1, 2 => 1], [1 => 1, 2 => -1]] if massaction @@ -51,9 +53,9 @@ function stop_after_jumps(n) end # Growth of u[1], with births of u[2] at rate u[1] and resets of u[1] at a constant rate -function growth_jprob(vr_aggregator) +function growth_jprob(vr_aggregator; T = Float64) 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]) + oprob = ODEProblem(f!, T[1.0, 0.0], (zero(T), T(3)), T[0.5]) birth = VariableRateJump((u, p, t) -> u[1], integrator -> (integrator.u[2] += 1; nothing)) reset = ConstantRateJump((u, p, t) -> 1.0, @@ -61,39 +63,21 @@ function growth_jprob(vr_aggregator) JumpProblem(oprob, Direct(), birth, reset; vr_aggregator) end -# The fields that `isolated_copy` shares for each aggregator. With the working fields they -# must cover every field, so that a new field has to be classified. -const COMMON_SHARED = (:ma_jumps, :rates, :affects!, :save_positions) -const SPATIAL_SHARED = (:rates, :affects!, :save_positions, :dependencies, :spatial_system, - :numspecies) -const SHARED_FIELDS = Dict( - :DirectJumpAggregation => COMMON_SHARED, - :FRMJumpAggregation => COMMON_SHARED, - :SortingDirectJumpAggregation => (COMMON_SHARED..., :dependencies), - :DirectCRJumpAggregation => (COMMON_SHARED..., :dependencies, :ratetogroup), - :RSSAJumpAggregation => (COMMON_SHARED..., :brackets, :dependencies, :bracket_data), - :RSSACRJumpAggregation => (COMMON_SHARED..., :brackets, :dependencies, :bracket_data, - :ratetogroup), - :NRMJumpAggregation => (COMMON_SHARED..., :dependencies), - :CCNRMJumpAggregation => (COMMON_SHARED..., :dependencies), - :CoevolveJumpAggregation => (COMMON_SHARED..., :dependencies, :lrates, :urates, - :rateintervals, :haslratevec), - :RDirectJumpAggregation => (COMMON_SHARED..., :dependencies, :counter_threshold), - :NSMJumpAggregation => SPATIAL_SHARED, - :DirectCRDirectJumpAggregation => (SPATIAL_SHARED..., :ratetogroup)) - -# Working fields are copies (values of bits types are copied by construction); every other -# field is the original's +# The fields in `shared_fields` are the original's; every other field is a copy (numbers, +# which are never modified in place, are shared, and values of bits types are copied by +# value) function test_copied_and_shared_fields(orig, copied) T = typeof(orig) @test typeof(copied) === T @test copied !== orig + @test allunique(shared_fields(T)) + @test issubset(shared_fields(T), fieldnames(T)) for name in fieldnames(T) x, y = getfield(orig, name), getfield(copied, name) - if name in working_fields(T) - @test isbits(x) || x !== y - else + if name in shared_fields(T) @test x === y + else + @test isbits(x) || x isa Number || x !== y end end end @@ -116,6 +100,19 @@ end const SHARED_PROBLEM_FIELDS = (:prob, :aggregator, :constant_jumps, :variable_jumps, :regular_jump, :massaction_jump, :kwargs) +@testset "Every aggregator declares the fields it shares" begin + fallback = which(shared_fields, Tuple{Type{Nothing}}) + own(types) = filter(T -> parentmodule(T) === JumpProcesses, types) + for T in own([subtypes(JumpProcesses.AbstractSSAJumpAggregator); + subtypes(JumpProcesses.AbstractHopRates)]) + @test which(shared_fields, Tuple{Type{T}}) !== fallback + @test issubset(shared_fields(T), fieldnames(T)) + end + + # An object of a type that declares nothing is never shared by mistake + @test_throws ArgumentError JumpProcesses.copy_working(Ref(1.0)) +end + @testset "Shares the jumps and copies the jump state: $(nameof(typeof(aggregator))), \ massaction = $massaction" for aggregator in JumpProcesses.JUMP_AGGREGATORS, massaction in (true, false) @@ -129,10 +126,6 @@ const SHARED_PROBLEM_FIELDS = (:prob, :aggregator, :constant_jumps, :variable_ju end agg = jprob.discrete_jump_aggregation - T = typeof(agg) - shared = SHARED_FIELDS[nameof(T)] - @test Set(fieldnames(T)) == Set((working_fields(T)..., shared...)) - @test isempty(intersect(working_fields(T), shared)) test_copied_and_shared_fields(agg, jcopy.discrete_jump_aggregation) test_copied_tables(agg, jcopy.discrete_jump_aggregation) @@ -292,9 +285,6 @@ end jcopy = isolated_copy(jprob) agg = jprob.discrete_jump_aggregation - T = typeof(agg) - shared = SHARED_FIELDS[nameof(T)] - @test Set(fieldnames(T)) == Set((working_fields(T)..., shared...)) test_copied_and_shared_fields(agg, jcopy.discrete_jump_aggregation) test_copied_and_shared_fields(agg.rx_rates, jcopy.discrete_jump_aggregation.rx_rates) test_copied_and_shared_fields(agg.hop_rates, jcopy.discrete_jump_aggregation.hop_rates) @@ -304,6 +294,41 @@ end @test interleaved_paths(jprob, isolated_copy(jprob), SSAStepper()) == refs end +# A fresh aggregator's buffers are allocated with `undef`, so for `BigFloat` and `BigInt` they +# hold unassigned entries until the first `init`; these problems are copied unsolved. +# (`DirectCR`, `RSSACR` and `RDirect` can't build problems with `BigFloat` times yet.) +@testset "Copies of unsolved problems with BigFloat times: $(nameof(typeof(aggregator))), \ + massaction = $massaction" for aggregator in (Direct(), DirectFW(), + SortingDirect(), RSSA(), FRM(), FRMFW(), NRM(), Coevolve(), CCNRM()), + massaction in (true, false) + + jprob = ab_jprob(aggregator; massaction, T = BigFloat) + jcopy = isolated_copy(jprob) + test_copied_and_shared_fields(jprob.discrete_jump_aggregation, + jcopy.discrete_jump_aggregation) + @test path(solve(jcopy, SSAStepper(); seed = 1)) == + path(solve(deepcopy(jprob), SSAStepper(); seed = 1)) +end + +@testset "Copies of unsolved problems with BigInt states and BigFloat ODEs" begin + jprob = ab_jprob(RSSA(); U = BigInt) + jcopy = isolated_copy(jprob) + @test jcopy.discrete_jump_aggregation.ulow !== jprob.discrete_jump_aggregation.ulow + @test path(solve(jcopy, SSAStepper(); seed = 1)) == + path(solve(deepcopy(jprob), SSAStepper(); seed = 1)) + + for vr_aggregator in (VR_Direct(), VR_DirectFW()) + jprob = growth_jprob(vr_aggregator; T = BigFloat) + jcopy = isolated_copy(jprob) + cache = only(jprob.jump_callback.continuous_callbacks).condition + cache_copy = only(jcopy.jump_callback.continuous_callbacks).condition + test_copied_and_shared_fields(cache, cache_copy) + test_copied_and_shared_fields(cache.rate_fit, cache_copy.rate_fit) + @test path(solve(jcopy, Tsit5(); seed = 1)) == + path(solve(deepcopy(jprob), Tsit5(); seed = 1)) + end +end + @testset "Jump-diffusions, through `resetted_jump_problem`" begin f!(du, u, p, t) = (du .= 0; nothing) g!(du, u, p, t) = (du .= 0.1; nothing) From edd8d1848d31310e9e45bfdbdb4a56a1645b4ecb Mon Sep 17 00:00:00 2001 From: Sam Isaacson Date: Mon, 9 Nov 2026 10:57:19 -0500 Subject: [PATCH 4/4] Declare InteractiveUtils as a test dependency test/isolated_copy.jl uses `subtypes` to check that every aggregator declares its shared fields; Pkg.test only loads declared test dependencies, so the ThreadSafety jobs stopped with "Package InteractiveUtils not found". Co-Authored-By: Claude Opus 5.5 --- Project.toml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Project.toml b/Project.toml index fdbd5290a..29da40edc 100644 --- a/Project.toml +++ b/Project.toml @@ -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" @@ -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" @@ -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"]