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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion lib/OrdinaryDiffEqCore/Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ SciMLLogging = "2"
SciMLOperators = "1.24.3"
SciMLStructures = "1.7"
SparseArrays = "1"
StaticArrays = "1.9.18"
SymbolicIndexingInterface = "0.3.43"
Test = "<0.0.1, 1"
TruncatedStacktraces = "1.4"
Expand All @@ -114,11 +115,12 @@ Pkg = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f"
SafeTestsets = "1bc83da4-3b8d-516f-aca4-4fe02f6d838f"
SciMLTesting = "09d9d899-5365-40a9-917a-5f67fddea283"
SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"
StaticArrays = "90137ffa-7385-5640-81b9-e52037218182"
Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
Unitful = "1986cc42-f94f-5a68-af5c-568840ba703d"

[targets]
test = ["DiffEqDevTools", "Enzyme", "SafeTestsets", "SparseArrays", "Test", "Pkg", "OrdinaryDiffEqBDF", "OrdinaryDiffEqFIRK", "OrdinaryDiffEqRosenbrock", "OrdinaryDiffEqTsit5", "DifferentiationInterface", "SciMLTesting", "Unitful"]
test = ["DiffEqDevTools", "Enzyme", "SafeTestsets", "SparseArrays", "Test", "Pkg", "OrdinaryDiffEqBDF", "OrdinaryDiffEqFIRK", "OrdinaryDiffEqRosenbrock", "OrdinaryDiffEqTsit5", "DifferentiationInterface", "SciMLTesting", "StaticArrays", "Unitful"]

[sources]
DiffEqBase = {path = "../DiffEqBase"}
Expand Down
2 changes: 1 addition & 1 deletion lib/OrdinaryDiffEqCore/src/disco.jl
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ function find_discontinuity(integrator)
continue
end
disco_prob = disco_probs[idx]
disco_zero = disco_prob.f.f.obj.x
disco_zero = _disco_zero(disco_prob.f.f)
_load_disco_state!(disco_zero, dt, uprev, u, k, t, p)
if (i isa VectorContinuousCallback)
len_cb = i.len::Int
Expand Down
95 changes: 78 additions & 17 deletions lib/OrdinaryDiffEqCore/src/solve.jl
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,74 @@
end
_set_disco_index!(z::zero_func_struct, ind) = (z.ind = ind; nothing)

function _disco_zero_func(i, u, _dt, uprev, k, cache, save_idxs, differential_vars, f, tprev, p)
u₁ = (u isa AbstractArray) ? similar(u) : zero(u)
out, out_low, out_high = if i isa VectorContinuousCallback
arr = (u isa AbstractArray) ? similar(u, i.len) : zeros(typeof(u), i.len)
arr, similar(arr), similar(arr)
else
nothing, zeros(Float64, 1), zeros(Float64, 1)
end
return zero_func_struct(
u₁, i, _dt, uprev, u, k, cache, save_idxs, differential_vars, 1, out, out_low,
out_high, f, tprev, p
)
end

# The type every discontinuity problem holds as its function: under `FullSpecialize`,
# the zero function's own type, or a small `Union` of them when the continuous
# callbacks differ in type; otherwise, and whenever that type is not concrete (or there
# is no continuous callback to take it from), the `FunctionWrapper` type.
const DISCO_ZERO_WRAPPER = FunctionWrapper{Float64, Tuple{Float64, SciMLBase.NullParameters}}

function _disco_zero_func_type(f, cbs, u, _dt, uprev, k, cache, save_idxs, differential_vars, tprev, p)
(f isa SciMLBase.AbstractSciMLFunction &&

Check warning on line 75 in lib/OrdinaryDiffEqCore/src/solve.jl

View workflow job for this annotation

GitHub Actions / runic-suggestions / Runic Suggestions

[Runic] reported by reviewdog 🐶 Raw Output: lib/OrdinaryDiffEqCore/src/solve.jl:75:- (f isa SciMLBase.AbstractSciMLFunction && lib/OrdinaryDiffEqCore/src/solve.jl:76:- SciMLBase.specialization(f) === SciMLBase.FullSpecialize) || return DISCO_ZERO_WRAPPER lib/OrdinaryDiffEqCore/src/solve.jl:75:+ ( lib/OrdinaryDiffEqCore/src/solve.jl:76:+ f isa SciMLBase.AbstractSciMLFunction && lib/OrdinaryDiffEqCore/src/solve.jl:77:+ SciMLBase.specialization(f) === SciMLBase.FullSpecialize lib/OrdinaryDiffEqCore/src/solve.jl:78:+ ) || return DISCO_ZERO_WRAPPER
SciMLBase.specialization(f) === SciMLBase.FullSpecialize) || return DISCO_ZERO_WRAPPER
isempty(cbs) && return DISCO_ZERO_WRAPPER
Ts = map(
i -> Base.promote_op(
_disco_zero_func, typeof(i), typeof(u), typeof(_dt), typeof(uprev), typeof(k),
typeof(cache), typeof(save_idxs), typeof(differential_vars), typeof(f),
typeof(tprev), typeof(p)
),
cbs
)
all(isconcretetype, Ts) || return DISCO_ZERO_WRAPPER
Z = Union{Ts...}
# past four types a `Union` is no longer split at the call sites
Z isa Union && length(Base.uniontypes(Z)) > 4 && return DISCO_ZERO_WRAPPER
return Z
end

function _disco_prob_type(::Type{Z}, ::Type{tType}) where {Z, tType}
T = _disco_prob_type1(Z, tType)
isconcretetype(T) && return T
Z isa Union || return IntervalNonlinearProblem
Ts = map(Z1 -> _disco_prob_type1(Z1, tType), Tuple(Base.uniontypes(Z)))
all(isconcretetype, Ts) || return IntervalNonlinearProblem
return Union{Ts...}
end
_disco_prob_type1(::Type{Z}, ::Type{tType}) where {Z, tType} = Base.promote_op(
IntervalNonlinearProblem{false}, _disco_function_type(Z), Vector{tType},
SciMLBase.NullParameters
)
_disco_function_type(::Type{DISCO_ZERO_WRAPPER}) = DISCO_ZERO_WRAPPER
_disco_function_type(::Type{Z}) where {Z} =
Base.promote_op(SciMLBase.IntervalNonlinearFunction{false, SciMLBase.FullSpecialize}, Z)

function _disco_prob(::Type{Z}, zero_func, ::Type{tType}) where {Z, tType}
return IntervalNonlinearProblem{false}(
_disco_function(Z, zero_func), [zero(tType), one(tType)], SciMLBase.NullParameters()
)
end
_disco_function(::Type{Z}, zero_func) where {Z} = Z === DISCO_ZERO_WRAPPER ?
DISCO_ZERO_WRAPPER(zero_func) :
SciMLBase.IntervalNonlinearFunction{false, SciMLBase.FullSpecialize}(zero_func)

# The zero function a discontinuity problem holds, read back from it.
_disco_zero(z::zero_func_struct) = z
_disco_zero(w::FunctionWrapper) = w.obj.x

function (z::zero_func_struct)(θ, p)
iszero(θ) && return z.out_low[z.ind]
isone(θ) && return z.out_high[z.ind]
Expand Down Expand Up @@ -968,29 +1036,22 @@
# rather than built, so no problem is constructed for a solve that has no use for it.
# The zero function reads everything, `p` included, from its own state, so the
# problem carries no parameters and its type does not depend on `p`.
disco_zero_wrapper = FunctionWrapper{Float64, Tuple{Float64, SciMLBase.NullParameters}}
disco_prob_type = Base.promote_op(
IntervalNonlinearProblem{false}, disco_zero_wrapper, Vector{tType},
SciMLBase.NullParameters
# With `FullSpecialize` the problem holds the zero function itself, typed by its
# callback (`_disco_zero_func_type`); otherwise it holds a `FunctionWrapper`, so the
# bracketing solve compiles once whatever the callback.
zero_func_type = _disco_zero_func_type(
f, callbacks_internal.continuous_callbacks, u, _dt, uprev, k, cache, save_idxs,
differential_vars, tprev, p
)
isconcretetype(disco_prob_type) || (disco_prob_type = IntervalNonlinearProblem)
disco_prob_type = _disco_prob_type(zero_func_type, tType)
disco_probs = Vector{disco_prob_type}(undef, num_probs)
idx = 1
for i in callbacks_internal.continuous_callbacks
if i.maybe_discontinuity::Bool
u₁ = (u isa AbstractArray) ? similar(u) : zero(u)
out, out_low, out_high = if i isa VectorContinuousCallback
arr = (u isa AbstractArray) ? similar(u, i.len) : zeros(typeof(u), i.len)
arr, similar(arr), similar(arr)
else
nothing, zeros(Float64, 1), zeros(Float64, 1)
end
zero_func = zero_func_struct(u₁, i, _dt, uprev, u, k, cache, save_idxs, differential_vars, 1, out, out_low, out_high, f, tprev, p)
zero_func_wrapped = disco_zero_wrapper(zero_func)
disco_prob = IntervalNonlinearProblem{false}(
zero_func_wrapped, [zero(tType), one(tType)], SciMLBase.NullParameters()
zero_func = _disco_zero_func(
i, u, _dt, uprev, k, cache, save_idxs, differential_vars, f, tprev, p
)
disco_probs[idx] = disco_prob
disco_probs[idx] = _disco_prob(zero_func_type, zero_func, tType)
idx += 1
end
end
Expand Down
210 changes: 210 additions & 0 deletions lib/OrdinaryDiffEqCore/test/disco_fullspec_tests.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
using OrdinaryDiffEqCore, OrdinaryDiffEqTsit5, SciMLBase, StaticArrays, Test
using OrdinaryDiffEqCore: DEVerbosity, SciMLLogging, zero_func_struct, _disco_zero, DISCO_ZERO_WRAPPER

# FullSpecialize: each discontinuity problem holds its zero function, typed; other
# specializations keep the FunctionWrapper.
f!(du, u, p, t) = (du[1] = 1.0; nothing)
cond(u, t, integrator) = t - 1.0
vcond(out, u, t, integrator) = (out[1] = t - 1.0; out[2] = u[1] - 10.0; nothing)
noop!(integrator) = nothing
vnoop!(integrator, idx) = nothing

# the state after a rejected step of size `dt` from `integ.t` (u' = 1)
function straddle!(integ, dt)
integ.dt = dt
integ.u .= integ.uprev .+ dt
return integ
end

const DYNAMIC = (
:getproperty, :setproperty!, :getindex, :setindex!, :_load_disco_state!,
:_ode_addsteps!, :solve, :_typevar,
)
quiet() = DEVerbosity(SciMLLogging.None())
probs(integ) = OrdinaryDiffEqCore.get_disco_probs(integ.controller_cache)
dynamic_calls(integ) = filter(
only(code_typed(OrdinaryDiffEqCore.find_discontinuity, (typeof(integ),); optimize = true)).first.code
) do st
st isa Expr && st.head === :call && st.args[1] isa GlobalRef && st.args[1].name in DYNAMIC
end

@testset "zero function held typed under FullSpecialize, $spec" for spec in (SciMLBase.FullSpecialize, SciMLBase.AutoSpecialize)
prob = ODEProblem{true, spec}(f!, [0.0], (0.0, 2.0))
for (cb, name) in (
(ContinuousCallback(cond, noop!), "scalar"),
(VectorContinuousCallback(vcond, vnoop!, 2), "vector"),
)
@testset "$name" begin
integ = init(prob, Tsit5(); callback = cb, dt = 0.5, adaptive = false, verbose = quiet())
straddle!(integ, 1.5)
θ = OrdinaryDiffEqCore.find_discontinuity(integ)
@test θ ≈ 2 / 3 atol = 1.0e-8 # the root of t - 1 on the step [0, 1.5]
@test integ.is_disco_step
dp = only(probs(integ))
@test isconcretetype(eltype(probs(integ)))
z = _disco_zero(dp.f.f)
@test z isa zero_func_struct
@test isconcretetype(typeof(z))
if spec === SciMLBase.FullSpecialize
@test dp.f.f === z
@test SciMLBase.specialization(dp.f) === SciMLBase.FullSpecialize
@test isempty(dynamic_calls(integ))
else
@test dp.f.f isa DISCO_ZERO_WRAPPER
end
end
end
end

@testset "vector of callbacks (FullSpecialize)" begin
prob = ODEProblem{true, SciMLBase.FullSpecialize}(f!, [0.0], (0.0, 2.0))
vinteg = init(
prob, Tsit5(); callback = CallbackSet(Any[ContinuousCallback(cond, noop!)], Any[]), dt = 0.5,
adaptive = false, verbose = quiet()
)
straddle!(vinteg, 1.5)
@test OrdinaryDiffEqCore.find_discontinuity(vinteg) ≈ 2 / 3 atol = 1.0e-8
@test only(probs(vinteg)).f.f isa zero_func_struct
end

@testset "kink, detection on and off, $spec" for spec in (SciMLBase.FullSpecialize, SciMLBase.AutoSpecialize)
kink!(du, u, p, t) = (du[1] = u[1] < 1 ? 2u[1] : 5 - 3u[1]; nothing)
kprob = ODEProblem{true, spec}(kink!, [0.1], (0.0, 1.5))
zero_func_calls = Ref(0)
function kcond(u, t, integ)
integ isa zero_func_struct && (zero_func_calls[] += 1)
return u[1] - 1
end
kcb = ContinuousCallback(kcond, noop!)
# a first step of 1.4 straddles the kink at t ≈ 1.15 and is rejected
disco = solve(
kprob, Tsit5(); callback = kcb, reltol = 1.0e-6, dt = 1.4,
controller = OrdinaryDiffEqCore.PIController(Tsit5(); discontinuity_detection = true)
)
@test disco.retcode == ReturnCode.Success
@test zero_func_calls[] > 0
zero_func_calls[] = 0
plain = solve(kprob, Tsit5(); callback = kcb, reltol = 1.0e-6, dt = 1.4)
@test zero_func_calls[] == 0
@test disco.stats.nreject <= plain.stats.nreject
# analytic: u = 0.1exp(2t) up to τ = log(10)/2 where u = 1, then u' = 5 - 3u
τ = log(10) / 2
uref(t) = t <= τ ? 0.1exp(2t) : 5 / 3 - (2 / 3) * exp(-3(t - τ))
@test isapprox(disco(1.5)[1], uref(1.5); rtol = 1.0e-5, atol = 1.0e-8)
@test isapprox(disco.u[end][1], uref(1.5); rtol = 1.0e-5, atol = 1.0e-8)
end

@testset "several callbacks of different types, repeated detection" begin
# time conditions: `straddle!` sets `u` but not the interpolant
prob = ODEProblem{true, SciMLBase.FullSpecialize}(f!, [0.0], (0.0, 2.0))
c08(u, t, integrator) = t - 0.8
c03(u, t, integrator) = t - 0.3
integ = init(
prob, Tsit5(); callback = CallbackSet(map(c -> ContinuousCallback(c, noop!), (c08, c03))...),
dt = 0.5, adaptive = false, verbose = quiet()
)
@test integ.opts.callback.continuous_callbacks isa Tuple
straddle!(integ, 1.0)
@test OrdinaryDiffEqCore.find_discontinuity(integ) ≈ 0.3 atol = 1.0e-8
dps = probs(integ)
@test length(dps) == 2
# two callback types: a two-member Union of problem types, no wrapper
@test eltype(dps) isa Union && length(Base.uniontypes(eltype(dps))) == 2
@test all(dp -> dp.f.f isa zero_func_struct, dps)
@test typeof(dps[1]) !== typeof(dps[2])
straddle!(integ, 0.5)
@test OrdinaryDiffEqCore.find_discontinuity(integ) ≈ 0.6 atol = 1.0e-8
end

@testset "maybe_discontinuity = false still gives a concrete type" begin
prob = ODEProblem{true, SciMLBase.FullSpecialize}(f!, [0.0], (0.0, 2.0))
cb = ContinuousCallback(cond, noop!; maybe_discontinuity = false)
integ = init(prob, Tsit5(); callback = cb, dt = 0.5, adaptive = false, verbose = quiet())
@test isempty(probs(integ))
@test isconcretetype(eltype(probs(integ)))
@test eltype(probs(integ)).parameters[4].parameters[3] <: zero_func_struct
end

warm_bytes(integ) = (OrdinaryDiffEqCore.find_discontinuity(integ); @allocated OrdinaryDiffEqCore.find_discontinuity(integ))

static_f(u, p, t) = SVector(1.0, 2.0)
# `StaticVector`: the zero function interpolates an immutable state into its `MVector`
# buffer (`similar(u)`), so the condition sees an `MVector` there.
static_cond(u::StaticVector, t, integrator) = u[1] - 1.0
function static_vcond(out, u::StaticVector, t, integrator)
out[1] = u[1] - 1.0
out[2] = u[2] - 10.0
return nothing
end

@testset "static array state, $name, $spec" for spec in (SciMLBase.FullSpecialize, SciMLBase.AutoSpecialize),
(name, cb) in (
("scalar", ContinuousCallback(static_cond, noop!)),
("vector", VectorContinuousCallback(static_vcond, vnoop!, 2)),
)

prob = ODEProblem{false, spec}(static_f, SVector(0.0, 0.0), (0.0, 2.0))
integ = init(prob, Tsit5(); callback = cb, dt = 1.5, adaptive = false, verbose = quiet())
OrdinaryDiffEqCore.perform_step!(integ, integ.cache)
@test OrdinaryDiffEqCore.find_discontinuity(integ) ≈ 2 / 3 atol = 1.0e-8
@test integ.is_disco_step
dp = only(probs(integ))
if spec === SciMLBase.FullSpecialize
@test dp.f.f isa zero_func_struct
@test isempty(dynamic_calls(integ))
@info "find_discontinuity warm allocation, static $name" bytes = warm_bytes(integ)
end

kink(u, p, t) = SVector(u[1] < 1 ? 2u[1] : 5 - 3u[1], 0.0)
τ = log(10) / 2
kprob = ODEProblem{false, spec}(kink, SVector(0.1, 0.0), (0.0, 1.5))
disco = solve(
kprob, Tsit5(); callback = cb, reltol = 1.0e-6, dt = 1.4,
controller = OrdinaryDiffEqCore.PIController(Tsit5(); discontinuity_detection = true)
)
@test disco.retcode == ReturnCode.Success
@test isapprox(disco.u[end][1], 5 / 3 - (2 / 3) * exp(-3(1.5 - τ)); rtol = 1.0e-5)
end

@testset "mutable static array state keeps the interpolation buffer" begin
mutable_f!(du, u, p, t) = (du[1] = 1.0; du[2] = 2.0; nothing)
mutable_cond(u::MVector, t, integrator) = u[1] - 1.0
prob = ODEProblem{true, SciMLBase.FullSpecialize}(mutable_f!, MVector(0.0, 0.0), (0.0, 2.0))
integ = init(
prob, Tsit5(); callback = ContinuousCallback(mutable_cond, noop!), dt = 1.5,
adaptive = false, verbose = quiet()
)
OrdinaryDiffEqCore.perform_step!(integ, integ.cache)
@test OrdinaryDiffEqCore.find_discontinuity(integ) ≈ 2 / 3 atol = 1.0e-8
z = only(probs(integ)).f.f
@test z isa zero_func_struct
@test z.u₁ isa MVector{2, Float64}
@test z.u₁ !== integ.u
end

@testset "reinit! keeps the typed problems working" begin
kink!(du, u, p, t) = (du[1] = u[1] < 1 ? 2u[1] : 5 - 3u[1]; nothing)
kprob = ODEProblem{true, SciMLBase.FullSpecialize}(kink!, [0.1], (0.0, 1.5))
calls = Ref(0)
kcb = ContinuousCallback((u, t, integ) -> (integ isa zero_func_struct && (calls[] += 1); u[1] - 1), noop!)
integ = init(
kprob, Tsit5(); callback = kcb, reltol = 1.0e-6, dt = 1.4, verbose = quiet(),
controller = OrdinaryDiffEqCore.PIController(Tsit5(); discontinuity_detection = true)
)
τ = log(10) / 2
uend = 5 / 3 - (2 / 3) * exp(-3(1.5 - τ))
solve!(integ)
@test isapprox(integ.sol.u[end][1], uend; rtol = 1.0e-5)
T = typeof(integ)
for u0 in ([0.1], [0.2])
calls[] = 0
reinit!(integ, u0)
integ.dt = 1.4
solve!(integ)
@test typeof(integ) === T
@test integ.sol.retcode == ReturnCode.Success
τ0 = log(1 / u0[1]) / 2
@test isapprox(integ.sol.u[end][1], 5 / 3 - (2 / 3) * exp(-3(1.5 - τ0)); rtol = 1.0e-5)
@test calls[] > 0
end
end
1 change: 1 addition & 0 deletions lib/OrdinaryDiffEqCore/test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ if TEST_GROUP == "Core" || TEST_GROUP == "ALL"
@time @safetestset "Instability Diagnostics" include("instability_diagnostics_tests.jl")
@time @safetestset "Enzyme Interpolation" include("enzyme_interpolation_tests.jl")
@time @safetestset "Tolerance Default Equality" include("tolerance_default_equality_tests.jl")
@time @safetestset "FullSpecialize discontinuity problems" include("disco_fullspec_tests.jl")
end

# Run QA tests LAST. `JET.test_package` re-evaluates this package's source into a
Expand Down
Loading