Repository navigation
Fix tstop overshoot error and super dense time event triggers - #2869
ChrisRackauckas merged 3 commits into
Conversation
Updated Implementation with Simplified LogicRefined the approach based on feedback to make it much cleaner: Simplified Flag Detectionif original_dt < distance_to_tstop
integrator.next_step_tstop = false # Normal step
else
integrator.next_step_tstop = true # Tstop snap mode
integrator.tstop_target = integrator.tdir * tdir_tstop
endClean Separation of Concerns
Key InsightWhen This eliminates all the floating-point precision issues while maintaining the existing code structure and flow. |
✅ Comprehensive Test Suite AddedAdded extensive tests to Test Coverage
Key Assertions
These tests specifically target the scenarios mentioned in the issue and ensure robust handling of all edge cases. |
✅ Test Dependencies FixedAdded proper imports to using OrdinaryDiffEq, Test, Random, StaticArrays, DiffEqCallbacksDependencies Added:
Test Status:
The comprehensive test suite will run as part of the "Tstops Tests" in the Interface test group. |
|
I really don't think this is a good AI issue. This is very tricky code and I would appreciate it remaining correct. |
|
This is actually a rather simple solution to it. It didn't come up with the solution though, it went down some weird floating point rabbit hole. This solution of just using a flag is rather simple |
9484879 to
c168d78
Compare
917b03f to
9daadcd
Compare
9daadcd to
1f5cd7c
Compare
99b1e5b to
43567d0
Compare
43567d0 to
982989f
Compare
Fix for Failing TestsThe loop condition in
The FixChanged line 612 in - while integrator.tdir * integrator.t <= first_tstop
+ while integrator.tdir * integrator.t < first_tstopThis restores the original loop behavior while preserving the tstop flag mechanism. Tests Verified Locally
🤖 Generated with Claude Code |
f2c4a26 to
cddbea0
Compare
9b8a7ac to
6dc77d3
Compare
Fixes SciML#2752 where StaticArrays trigger "Integrator stepped past tstops" errors due to floating-point precision differences in tstop distance calculations between StaticArrays and regular Arrays. Instead of relying solely on floating-point epsilon correction to snap to tstops, this adds a flag-based mechanism: - Add `next_step_tstop` flag and `tstop_target` to ODEIntegrator - `modify_dt_for_tstops!` sets the flag when dt is reduced for a tstop - `handle_tstop_step!` skips perform_step! for tiny dt (< eps(t)) - `fixed_t_for_tstop_error!` snaps exactly to tstop_target when flagged, with the original 100*eps correction retained as fallback - `solve!` loop uses the flag to exit the inner loop after tstop snap - Prevent duplicate tstops at tspan end by using strict `<` in filtering - Restore original dt before step controller when snapping to tstop Co-Authored-By: Chris Rackauckas <[email protected]>
6dc77d3 to
95dacaa
Compare
Rebased and cleaned upRebased the branch onto current master (was 283 commits behind). The 14 iterative commits have been squashed into a single clean commit. Changes from the previous version:
Test results (local, Julia 1.12):
|
…ibility DDEIntegrator in DelayDiffEq.jl doesn't have the new next_step_tstop and tstop_target fields. Replace direct field access with accessor functions that fall back to safe defaults for non-ODEIntegrator types. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude Opus 4.6 <[email protected]>
CI Fix: DDEIntegrator compatibility (commit 937dbdf)CI showed 8 failures caused by our changes — all with the same root cause: Fix: Added accessor functions with fallback defaults:
This way DDEIntegrator gracefully falls back to the old behavior (no flag-based snapping) without requiring a companion PR to DelayDiffEq.jl. Remaining CI failures (all pre-existing on master):
|
The flag-based tstop snapping covers all cases where we're stepping towards a tstop. The old 100*eps correction is dead code since modify_dt_for_tstops! always sets the flag when dt is shortened. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
Cool. Got it to now just all be a state machine instead of any floating point handling. 🤞 that passes all tests, but everything I checked worked. |
When solving with a fixed-dt method (e.g. `solve(prob, Euler(); dt = 0.1)`), the accumulated `t + dt + dt + ...` drifts and used to produce a spurious trailing step at `1 - eps` followed by `1.0`. PR SciML#2869 removed the `100eps(tstop)` snap hack that previously masked this in `fixed_t_for_floatingpoint_error!`. Two coordinated changes restore the expected 11-step result without reintroducing the old hack: 1. `_ode_init` expands `tstops` to `tspan[1]:dt:tspan[end]` when the user specifies `dt` for a fixed-time method and did not supply their own `tstops`/`d_discontinuities`. Julia's range semantics use TwicePrecision internally, so each range element is the exact floating-point representative of `k*dt` and lands on `tspan[end]` cleanly. The expansion is skipped whenever the user supplied any tstops, which preserves the existing "continue at dtcache between user tstops" behavior that tests like `sol.t == [0, 1/3, 1/2, 5/6, 1]` depend on. 2. `modify_dt_for_tstops!` compares `dt` against `distance_to_tstop` with a small floating-point tolerance (`100 * eps(max(t, tstop))`). Without this tolerance, `dtcache = 0.1` reads as strictly less than a `distance_to_tstop` of `0.10000000000000009` and the integrator takes a full step that overshoots the tstop by one ulp, then takes a matching tiny corrective step. The tolerance guard is gated on `isfinite(tdir_tstop) && isfinite(integrator.t)` so that semi-infinite `tspan = (0.0, Inf)` integrations still work. Adds a regression test covering forward, reverse, and non-evenly-dividing `dt` on `tspan = (0.0, 1.0)`. Fixes the PositiveIntegrators.jl CI failure noted in NumericalMathematics/PositiveIntegrators.jl#192 where `solve(prob, Euler(); dt = 0.1)` began returning 12 steps instead of 11. Co-Authored-By: Chris Rackauckas <[email protected]>
When solving with a fixed-dt method (e.g. `solve(prob, Euler(); dt = 0.1)`), the accumulated `t + dt + dt + ...` drifts past `tspan[end]` by one ulp, producing a spurious trailing micro-step. PR SciML#2869 removed the `100eps(tstop)` snap hack that previously masked this. Fix: for non-adaptive, dtchangeable algorithms with no user-supplied tstops / d_discontinuities / callbacks, expand `tstops` to the range `tspan[1]:dt:tspan[end]` whose TwicePrecision arithmetic gives exact floating-point tstops, and inflate `dt` by 10 ulps so that `modify_dt_for_tstops!` always takes the tstop branch and snaps `t` exactly via `fixed_t_for_tstop_error!`. The expansion is intentionally skipped for adaptive algorithms (even when used with `adaptive=false`), `CompositeAlgorithm`, non-finite tspans, and any solve with callbacks — preserving all existing stepping semantics in those cases. Adds a regression test covering forward, reverse, and non-evenly- dividing `dt` on `tspan = (0.0, 1.0)`. Fixes the PositiveIntegrators.jl CI failure noted in NumericalMathematics/PositiveIntegrators.jl#192. Co-Authored-By: Chris Rackauckas <[email protected]>
When solving with a fixed-dt method (e.g. `solve(prob, Euler(); dt = 0.1)`), the accumulated `t + dt + dt + ...` drifts past `tspan[end]` by one ulp, producing a spurious trailing micro-step. PR SciML#2869 removed the old `100eps(tstop)` snap in `fixed_t_for_floatingpoint_error!` that masked this. Fix: add a floating-point tolerance (`100 * eps(max(|t|, |tstop|))`) to the `dt < distance_to_tstop` comparison in `modify_dt_for_tstops!`. When `dt ≈ distance` within rounding the integrator now takes the tstop branch, and `fixed_t_for_tstop_error!` snaps `t` to the exact tstop value — eliminating the extra step. Adds a regression test covering forward, reverse, and non-evenly- dividing `dt` on `tspan = (0.0, 1.0)`. Fixes the PositiveIntegrators.jl CI failure noted in NumericalMathematics/PositiveIntegrators.jl#192. Co-Authored-By: Chris Rackauckas <[email protected]>
When solving with a fixed-dt method (e.g. `solve(prob, Euler(); dt = 0.1)`), the accumulated `t + dt + dt + ...` drifts past `tspan[end]` by one ulp, producing a spurious trailing micro-step. PR #2869 removed the old `100eps(tstop)` snap in `fixed_t_for_floatingpoint_error!` that masked this. Fix: add a floating-point tolerance (`100 * eps(max(|t|, |tstop|))`) to the `dt < distance_to_tstop` comparison in `modify_dt_for_tstops!`. When `dt ≈ distance` within rounding the integrator now takes the tstop branch, and `fixed_t_for_tstop_error!` snaps `t` to the exact tstop value — eliminating the extra step. Adds a regression test covering forward, reverse, and non-evenly- dividing `dt` on `tspan = (0.0, 1.0)`. Fixes the PositiveIntegrators.jl CI failure noted in NumericalMathematics/PositiveIntegrators.jl#192. Co-authored-by: ChrisRackauckas-Claude <[email protected]>
) * Restore the controller's step after a step shortened onto a tstop `_loopfooter!` restores the step the controller proposed before `modify_dt_for_tstops!` shortened it to land on a tstop, so that the next step is not grown from the (much shorter) landing step. Since `modify_dt_for_tstops!` also runs in `apply_step!` (#3096), it runs twice per accepted step and the second call records the already shortened `dt` in `dtpropose`, so the restore (#2869) restored the shortened step: after a stop placed 1% into a step, the next step was 0.1× the controller's proposal (the PI controller's `qmax` growth from the landing step). Record the step before either call in a new `dt_before_tstop` field and resume with it after the landing step. The landing step's error may shrink it but not grow it: scaling the restored step by the landing step's factor (up to `qmax`× on the strength of a tiny step's tiny error) overshoots, with more rejections and larger errors at matched tolerance. Callbacks of the landing step now see the accepted step in `integrator.dt`, so the current-step interpolant spans [tprev, t] (#4655). Periodic tstops cost fewer steps at equal tolerance (u' = -u, stops every 0.11, 1e-8: Tsit5 199 → 151, Rodas5P 171 → 136); at matched achieved error the effect on small test problems is mostly within ±10%, larger where stops are dense relative to the step size. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * Keep the accepted step in the controller hooks after a tstop landing The landing step used to overwrite integrator.dt with the unshortened step before step_accept_controller!, so controllers that record the step (Nordsieck tau, PredictiveController dtacc) stored a step that was never taken. Controllers now see the accepted step. The unshortened step is applied afterwards, in _resume_dt_after_tstop, and only when: - modify_dt_for_tstops! actually shortened the step (an exact stop at the end of the proposed step leaves the proposal alone); - no discontinuity cap applies to the next step; - the integrator records dt_before_tstop (DelayDiffEq's integrator keeps the controller's own proposal); - resumes_dt_after_tstop(alg) holds. The new public trait is false for NordsieckBDF and DNordsieckBDF, which regrow within their own step-ratio limit, as CVODE does. The controller's step factor from the landing step then may shrink the unshortened step but not grow it, and the result is never smaller than the controller's own proposal. dt_before_tstop is clamped to dtmax. OrdinaryDiffEqCore 4.21.0 (new public trait, changed step sequences with tstops); OrdinaryDiffEqBDF 2.4.15 requires it. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude <[email protected]> Agent-Harness: Claude Code 2.1.332 Agent-Model: claude-opus-5-5 Agent-Job: SciML__OrdinaryDiffEq.jl__4751--20261126T152703Z-claude-claude-opus-5-5 Agent-Session: local session a5a71e23-1cd4-4ab9-83fc-6b9c0f657a5b (no session URL) * Test that PredictiveController records the accepted step after a tstop landing The landing step's `dtacc` must be the step actually taken, not the step the controller asked for before it was shortened onto the tstop. On 11daadf it was 100x the accepted step for both RadauIIA5 (core PredictiveController path) and AdaptiveRadau (the FIRK override); af36792 fixed both. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_018GADJLyZrg1HGFBsU9ht7f * Make tstop step resumption opt-in and follow the active composite member The next step after a step shortened onto a tstop resumes the pre-shortening proposal only with the new `resume_dt_after_tstop = true` solve/init keyword (default false). By default the controller's proposal from the accepted landing step stands, so `qmax` bounds the growth: with `PIController(Tsit5(); qmax = 2)` and a 2^-16 landing step the next step is 2^-15, and a transient right after the stop is resolved again. `_dt_shortened_for_tstop` queries `get_current_resumes_dt_after_tstop`, which for a `CompositeAlgorithm` evaluates `resumes_dt_after_tstop` on the member selected by `cache.current` instead of the wrapper. DiffEqBase accepts the keyword alongside `stage_limiter`/`step_limiter` in its keyword check, and OrdinaryDiffEqCore requires DiffEqBase 7.22. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude <[email protected]> Agent-Harness: Claude Code 2.1.332 Agent-Model: claude-opus-5-5 Agent-Job: SciML__OrdinaryDiffEq.jl__4751--20261126T203233Z-claude-claude-opus-5-5 Agent-Session: local session 28d82478-4548-4435-9492-bfb0bfbba8bd (no session URL) * Test the PredictiveController dtacc on a first-step and an interior tstop Use exact dyadic steps (u' = 1, dt = dtmax = 0.125) with a stop 2^-16 into the first step and 2^-16 past the first step, and compare `dtacc` with the accepted step exactly, with and without `resume_dt_after_tstop`. The first-step case fails on master, which records 0.125 for RadauIIA5 and AdaptiveRadau; both cases failed before the controllers saw the accepted step. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_018GADJLyZrg1HGFBsU9ht7f * Accept resume_dt_after_tstop only for algorithms that consume it The DiffEqBase keyword check exempted resume_dt_after_tstop for every solver, so MethodOfSteps silently accepted a keyword it ignores. The check now receives the selected algorithm and exempts the names returned by the new documented hook DiffEqBase.solver_specific_kwargs(alg), which OrdinaryDiffEqCore specializes for OrdinaryDiffEqAlgorithm and DAEAlgorithm. stage_limiter and step_limiter stay exempt for all solvers. Tests: DelayDiffEq init and solve reject the keyword under KeywordArgError; solve and init with default algorithm selection accept it. The controller docs describe the default growth from the accepted step and the short-transient caveat of the opt-in. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude <[email protected]> Agent-Harness: Claude Code 2.1.332 Agent-Model: claude-opus-5-5 Agent-Job: SciML__OrdinaryDiffEq.jl__4751--20261126T231403Z-claude-claude-opus-5-5 Agent-Session: local session 55017f2f-bc8c-4359-b190-2a0fbcdef634 (no session URL) * Opt AN5 out of step resumption after tstops With resume_dt_after_tstop = true, AN5 restarted across a resizing tstop returned an 8% endpoint error with a Success retcode. AN5 now keeps its established restart step, like the Nordsieck BDF methods. The resize cases run with both option values. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude <[email protected]> Agent-Harness: Claude Code 2.1.332 Agent-Model: claude-opus-5-5 Agent-Job: SciML__OrdinaryDiffEq.jl__4751--20261127T040210Z-claude-claude-opus-5-5 Agent-Session: local session 9d3a9ca6-424c-4f05-b24a-c1cc817d53b2 (no session URL) * Source the checkout's DiffEqBase in the Feagin and IMEXMultistep QA envs Both QA environments source the checkout's OrdinaryDiffEqCore, which now requires DiffEqBase 7.22 for solver_specific_kwargs, but resolved their direct DiffEqBase dependency from the registry, where the newest release is 7.21.6. Resolution failed before any QA assertion ran. Sourcing DiffEqBase from the checkout matches the ExplicitRK, ExponentialRK, HighOrderRK and SSPRK QA environments. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude <[email protected]> Agent-Harness: Claude Code 2.1.332 Agent-Model: claude-opus-5-5 Agent-Job: SciML__OrdinaryDiffEq.jl__4751--20261127T053510Z-claude-claude-opus-5-5 Agent-Session: local session e30f946c-684d-4eed-93ca-bc001612e0e0 (no session URL) * Restore the accepted dt before callbacks after the accept hook A custom `step_accept_controller!` may compute its proposal by mutating `integrator.dt`. Without the restore, callbacks and `current_interpolant` saw the proposed interval instead of the completed step, so dense output inside the callback was evaluated with the wrong normalization. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude <[email protected]> Agent-Harness: Claude Code 2.1.332 Agent-Model: claude-opus-5-5 Agent-Job: SciML__OrdinaryDiffEq.jl__4751--20261127T161917Z-claude-claude-opus-5-5 Agent-Session: local session 0b0c5333-f2ce-4681-bd0a-be20af559a69 (no session URL) --------- Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]> Co-authored-by: ChrisRackauckas-Claude <[email protected]> Co-authored-by: opencode <[email protected]>
Summary
Fixes issue #2752 where
StaticArraystrigger "Something went wrong. Integrator stepped past tstops but the algorithm was dtchangeable" errors due to tiny floating-point precision differences in tstop distance calculations.Root Cause Analysis
The bug occurs because:
abs(tdir_tstop - tdir_t)produce slightly different results (differences ~1e-15 to 1e-21)100*eps(t)floating-point correction thresholdhandle_tstop!detects overshoot whendtchangeable=trueand throws errorSolution: Flag-Based Exact Tstop Handling
Instead of relying on floating-point precision for tstop stepping, this implementation uses a flag-based approach:
Key Changes:
Add Flag Mechanism
next_step_tstop::Bool- flag when next step should land exactly on tstoptstop_target::tType- exact target time for tstop landingEnhanced
modify_dt_for_tstops!next_step_tstop = trueand stores exact target intstop_targeteps(t)), sets minimal non-zero dtNew
handle_tstop_step!Functionperform_step!whennext_step_tstop = trueModified Stepping Loop
next_step_tstop ? handle_tstop_step!() : perform_step!()Algorithm Flow Comparison
Before (Problematic):
After (Robust):
Advantages
✅ Eliminates Root Cause: No floating-point precision dependence
✅ Exact Tstop Landing: Guaranteed precision regardless of array type
✅ Performance: Avoids wasted computation on tiny steps
✅ Backward Compatible: No changes to existing API
✅ Robust: Works identically for StaticArrays and regular Arrays
✅ Clean Architecture: Clear separation of tstop vs normal stepping logic
Files Modified
lib/OrdinaryDiffEqCore/src/integrators/type.jl- Add integrator fieldslib/OrdinaryDiffEqCore/src/solve.jl- Initialize fields and modify stepping looplib/OrdinaryDiffEqCore/src/integrators/integrator_utils.jl- Enhanced tstop logictest/tstop_flag_tests.jl- Test framework for new functionalityTest Plan
Breaking Changes
None. This is a pure enhancement that maintains existing API compatibility.
🤖 Generated with Claude Code