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
2 changes: 1 addition & 1 deletion lib/OrdinaryDiffEqCore/Project.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
name = "OrdinaryDiffEqCore"
uuid = "bbf590c4-e513-4bbe-9b18-05decba2e5d8"
authors = ["ParamThakkar123 <paramthakkar864@gmail.com>"]
version = "4.20.1"
version = "4.20.3"

[deps]
ADTypes = "47edcb42-4c32-4615-8424-f2b9edc5f35b"
Expand Down
86 changes: 67 additions & 19 deletions lib/OrdinaryDiffEqCore/src/interp_func.jl
Original file line number Diff line number Diff line change
Expand Up @@ -123,10 +123,12 @@ end
"""
strip_cache(cache)

Return a lightweight copy of `cache` with all fields set to `nothing`, used by
`SciMLBase.strip_interpolation` to drop the (potentially large) working buffers
from a solution's interpolation object before serialization. Has a special path
for [`DefaultCache`](@ref).
Return a lightweight copy of `cache` for `SciMLBase.strip_interpolation`, which
drops function information and working buffers from a solution's interpolation
object before serialization. Fields are set to `nothing` except the tableau
(`tab`, `tabs`, `B_interp`), numbers and fields whose type cannot hold `nothing`,
since the interpolant reads these; kept arrays of non-numbers are emptied.
[`DefaultCache`](@ref) and `CompositeCache` strip each of their sub-caches.

# Developer API

Expand All @@ -135,21 +137,67 @@ should call `solve` and use solution APIs, rather than construct caches or
depend on cache fields and their serialized representation.
"""
function strip_cache(cache)
if !(cache isa OrdinaryDiffEqCore.DefaultCache)
cache = ConstructionBase.constructorof(typeof(cache))(
[
nothing
for name in
fieldnames(typeof(cache))
]...
)
else
# need to do something special for default cache
cache = OrdinaryDiffEqCore.DefaultCache{
Nothing, Nothing, Nothing, Nothing,
Nothing, Nothing, Nothing, Nothing,
}(nothing, nothing, 0, nothing)
T = typeof(cache)
declared = _declared_fieldtypes(T)
eltypevars = map(i -> isdefined(cache, i) ? _nothing_eltype(declared[i], getfield(cache, i)) : nothing, 1:fieldcount(T))
keep = map(1:fieldcount(T)) do i
isdefined(cache, i) || return !_accepts_nothing(declared[i])
value = getfield(cache, i)
return fieldname(T, i) in (:tab, :tabs, :B_interp) || value isa Number ||
!(_accepts_nothing(declared[i]) || eltypevars[i] !== nothing)
end
while true
pinned = findfirst(eachindex(keep)) do j
var = declared[j] isa TypeVar ? declared[j] : eltypevars[j]
return !keep[j] && var !== nothing &&
any(i -> keep[i] && _mentions(declared[i], var), eachindex(keep))
end
pinned === nothing && break
keep[pinned] = true
end
fields = map(1:fieldcount(T)) do i
keep[i] && isdefined(cache, i) && return _strip_kept(fieldname(T, i), getfield(cache, i))
eltypevars[i] === nothing && return nothing
return Array{Nothing}(undef, map(zero, size(getfield(cache, i))))
end
return ConstructionBase.constructorof(T)(fields...)
end

# A field declared `Array{E}` holding non-numbers, with `E` a parameter that admits `nothing`,
# can become an empty `Array{Nothing}` so that `E` no longer names user function types.
_nothing_eltype(declared, value) = value isa Array && !(eltype(value) <: Number) &&
declared isa DataType && declared.name.wrapper === Array &&
declared.parameters[1] isa TypeVar && _accepts_nothing(declared.parameters[1]) ?
declared.parameters[1] : nothing

# Arrays the interpolant does not read, such as per-stage linear solvers, are emptied.
_strip_kept(name, value) = name in (:tab, :tabs) || !(value isa Array) || eltype(value) <: Number ?
value : similar(value, ntuple(_ -> 0, ndims(value)))

function _declared_fieldtypes(T)
wrapper = T.name.wrapper
while wrapper isa UnionAll
wrapper = wrapper.body
end
return fieldtypes(wrapper)
end

_accepts_nothing(declared::TypeVar) = Nothing <: declared.ub
_accepts_nothing(declared) = Nothing <: declared

_mentions(declared, var) = declared === var ||
(declared isa DataType && any(p -> _mentions(p, var), declared.parameters)) ||
(declared isa Union && (_mentions(declared.a, var) || _mentions(declared.b, var)))

function strip_cache(cache::DefaultCache)
names = (:cache1, :cache2, :cache3, :cache4, :cache5, :cache6)
caches = map(n -> isdefined(cache, n) ? strip_cache(getfield(cache, n)) : nothing, names)
types = map((c, n) -> isdefined(cache, n) ? typeof(c) : Nothing, caches, names)
stripped = DefaultCache{types..., Nothing, Nothing}(nothing, nothing, cache.current, nothing)
foreach((c, n) -> isdefined(cache, n) && setfield!(stripped, n, c), caches, names)
return stripped
end

return cache
function strip_cache(cache::CompositeCache)
return CompositeCache(map(strip_cache, cache.caches), nothing, cache.current)
end
95 changes: 95 additions & 0 deletions test/InterfaceI/ode_strip_test.jl
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
using OrdinaryDiffEq, Test
using OrdinaryDiffEqSDIRK
using OrdinaryDiffEqBDF: QNDF
using OrdinaryDiffEqFIRK: RadauIIA5, AdaptiveRadau
using OrdinaryDiffEqLowOrderRK: BS5
using OrdinaryDiffEqExplicitRK: ExplicitRK, constructTsit5ExplicitRK
using OrdinaryDiffEqExtrapolation: ImplicitEulerExtrapolation
import SciMLBase

function lorenz!(du, u, p, t)
Expand Down Expand Up @@ -48,3 +53,93 @@ end
end

@test_throws SciMLBase.LazyInterpolationException SciMLBase.strip_solution(vern_sol)

@testset "Composite Solution Stripping" begin
composite_sol = solve(prob, AutoTsit5(Rosenbrock23()))
@test all(==(1), composite_sol.alg_choice)
stripped_sol = SciMLBase.strip_solution(composite_sol)
@test isnothing(stripped_sol.interp.f)
@test isnothing(stripped_sol.interp.cache.choice_function)
@test isnothing(stripped_sol.interp.cache.caches[2].jac_config)
@test stripped_sol(0.33) == composite_sol(0.33)
@test SciMLBase.strip_solution(solve(prob, AutoVern7(Rosenbrock23(); lazy = false))) isa ODESolution
end

@testset "Stripped solutions interpolate like the original" begin
lorenz(u, p, t) = (du = similar(u); lorenz!(du, u, p, t); du)
ts = range(tspan...; length = 101)
algs = (
Rosenbrock23(), Rodas5P(), FBDF(), QNDF(), RadauIIA5(), AdaptiveRadau(),
BS5(lazy = false), DefaultODEAlgorithm(lazy = Val(false)),
AutoTsit5(Rosenbrock23()), AutoVern7(Rodas5P(); lazy = false),
ExplicitRK(tableau = constructTsit5ExplicitRK()),
)
for f in (lorenz!, lorenz), alg in algs
sol = solve(ODEProblem(f, u0, tspan), alg)
stripped_sol = SciMLBase.strip_solution(sol)
@test isnothing(stripped_sol.interp.f)
@test all(isapprox(stripped_sol(t), sol(t); rtol = 1.0e-12) for t in ts)
end

holds(x, y, seen = IdDict()) = x === y || (
!(x isa Union{Module, Type}) && !haskey(seen, x) && (
seen[x] = true;
x isa Array ? any(i -> isassigned(x, i) && holds(x[i], y, seen), eachindex(x)) :
any(i -> isdefined(x, i) && holds(getfield(x, i), y, seen), 1:nfields(x))
)
)
parameter_rate(t) = 1.0
growth = ODEProblem((du, u, p, t) -> (du .= p.rate(t) .* u), [1.0], (0.0, 1.0), (rate = parameter_rate,))
ts = range(0.013, 0.987; length = 50)
for alg in (AdaptiveRadau(), RadauIIA5(), DefaultODEAlgorithm(lazy = Val(false)))
sol = solve(growth, alg; reltol = 1.0e-10, abstol = 1.0e-10)
stripped_sol = SciMLBase.strip_solution(sol; strip_alg = true)
@test !holds(stripped_sol.interp, parameter_rate)
@test all(stripped_sol(t) == sol(t) for t in ts)
end
sol = SciMLBase.strip_solution(solve(growth, DefaultODEAlgorithm(lazy = Val(false)); reltol = 1.0e-10, abstol = 1.0e-10))
@test maximum(t -> abs(sol(t)[1] - exp(t)), ts) < 1.0e-11
end

using Serialization
roundtrip_rate(t) = 1.0
roundtrip_rhs!(du, u, p, t) = (du .= -p.rate(t) .* u)
roundtrip_rhs(u, p, t) = -p.rate(t) .* u
@testset "Stripped solutions deserialize without the RHS or p defined" begin
p = (rate = roundtrip_rate,)
cases = (
(ODEProblem{true, SciMLBase.FullSpecialize}(roundtrip_rhs!, [1.0], (0.0, 1.0), p), DefaultODEAlgorithm(lazy = Val(false))),
(ODEProblem(roundtrip_rhs, [1.0], (0.0, 1.0), p), DefaultODEAlgorithm(lazy = Val(false))),
(ODEProblem(roundtrip_rhs!, [1.0], (0.0, 1.0), p), AdaptiveRadau()),
(ODEProblem(roundtrip_rhs!, [1.0], (0.0, 1.0), p), ImplicitEulerExtrapolation()),
(ODEProblem(roundtrip_rhs!, [1.0], (0.0, 1.0), p), RadauIIA5()),
(ODEProblem(roundtrip_rhs!, [1.0], (0.0, 1.0), p), Rodas5P()),
(ODEProblem(roundtrip_rhs!, [1.0], (0.0, 1.0), p), FBDF()),
(ODEProblem(roundtrip_rhs!, [1.0], (0.0, 1.0), p), Tsit5()),
)
ts = range(0.013, 0.987; length = 20)
dir = mktempdir()
sols = map(enumerate(cases)) do (i, (prob, alg))
sol = solve(prob, alg)
serialize(joinpath(dir, "$i.jls"), SciMLBase.strip_solution(sol; strip_alg = true))
sol
end
script = """
using OrdinaryDiffEq, OrdinaryDiffEqFIRK, OrdinaryDiffEqExtrapolation, Serialization
for i in 1:$(length(cases))
result = try
sol = deserialize(joinpath($(repr(dir)), "\$i.jls"))
[sol(t) for t in $(repr(collect(ts)))]
catch err
sprint(showerror, err)
end
serialize(joinpath($(repr(dir)), "\$i.out"), result)
end
"""
run(`$(Base.julia_cmd()) --project=$(Base.active_project()) -e $script`)
for (i, sol) in enumerate(sols)
result = deserialize(joinpath(dir, "$i.out"))
@test result isa Vector
@test result ≈ sol.(ts) rtol = 1.0e-12
end
end
Loading