Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improve PresetTimeCallback #234

Merged
merged 3 commits into from
Oct 21, 2024
Merged
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
26 changes: 9 additions & 17 deletions src/preset_time.jl
Original file line number Diff line number Diff line change
Expand Up @@ -24,28 +24,18 @@ function PresetTimeCallback(tstops, user_affect!;
initialize = SciMLBase.INITIALIZE_DEFAULT,
filter_tstops = true,
sort_inplace = false, kwargs...)

# define an intrinsic version of insorted
# extend a new method to avoid type instability of condition (anonymous function)
_insorted(x::Number, y::Number) = x == y
_insorted(x, v) = insorted(x, v)

if tstops isa AbstractVector
if sort_inplace
sort!(tstops)
else
tstops = sort(tstops)
end
elseif !(tstops isa Number)
if !(tstops isa AbstractVector) && !(tstops isa Number)
throw(ArgumentError("tstops must either be a number or a Vector. Was $tstops"))
end

tstops = tstops isa Number ? [tstops] : (sort_inplace ? sort!(tstops) : sort(tstops))

condition = let
function (u, t, integrator)
if hasproperty(integrator, :dt)
_insorted(t, tstops) && (integrator.t - integrator.dt) != integrator.t
insorted(t, tstops) && (integrator.t - integrator.dt) != integrator.t
else
_insorted(t, tstops)
insorted(t, tstops)
end
end
end
Expand All @@ -64,9 +54,11 @@ function PresetTimeCallback(tstops, user_affect!;
tdir = integrator.tdir
tspan = integrator.sol.prob.tspan
_tstops = tstops[@. tdir * tspan[1] < tdir * tstops < tdir * tspan[2]]
add_tstop!.((integrator,), _tstops)
else
add_tstop!.((integrator,), tstops)
_tstops = tstops
end
for tstop in _tstops
add_tstop!(integrator, tstop)
end
if t ∈ tstops
user_affect!(integrator)
Expand Down
Loading