Repository navigation
Add TRBDF2: a native TR-BDF2 solver (C stepper + Cython wrapper, Assimulo events) - #140
Open
hubertus65 wants to merge 10 commits into
Open
hubertus65 wants to merge 10 commits into
hubertus65 wants to merge 10 commits into
Conversation
…not per call
radau5.c counted "unexpected" (recoverable) callback failures in `nunexpect`,
reset only at the start of a radau5 call, and aborted with
RADAU_ERROR_REP_STEP_REJECT ("Repeated unexpected step rejections") once the
total reached 10. For an FMU whose rhs rejects trial points regularly
(e.g. IF97 steam-table region errors on a 318-state power-plant model, or
Modelica.Fluid pipe models), that budget is exhausted within the first
millisecond even though every individual failure is recoverable by halving
the step; CVode handles the same model by shrinking the step each time.
Reset the counter on every accepted step so the limit applies to
consecutive failures only, matching the error message. No other behaviour
changes; tests/ still 330 passed, 5 skipped.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
…ter step, budget 40)
When the model rejects a trial point (a recoverable error from the rhs or the
Jacobian callback), Radau5 halved the step and gave up after 10 consecutive
failures, i.e. after reducing the step by 1024x. CVode quarters the step on a
recoverable rhs failure. On a 318-state combined-cycle plant whose steam-table
functions fail in a region the stage points step into during the first
milliseconds, Radau5 died at t = 0.5-4 ms ("Repeated unexpected step
rejections") in every configuration, while CVode passes.
This makes the factor 0.25 and the budget 40 consecutive failures (both as
named constants). With it, and a finite-difference Jacobian that does not
call the FMU's directional derivatives in that region, Radau5ODE completes
the plant: 1422 steps, 557 Jacobians, 322 s, and the most accurate plant
trajectory of any solver measured against an rtol 1e-8 reference (max
6.7e-4 over 308 plant states, none beyond 1e-3; CVode at the same rtol
3.1e-3). Every other reference model is bit-for-bit unchanged (the path is
only taken on recoverable failures); the Assimulo test suite passes (330).
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PyrxGeWuwCmAH9LishMW6p
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PyrxGeWuwCmAH9LishMW6p
…the numpy.distutils build) setup.py builds the Fortran solvers (Dopri5, RodasODE, Radau5/Radar5 Fortran, LSODAR, ODASSL, DASP3, GLIMDA) only when numpy.distutils imports, which is gone on Python >= 3.12 and broken by setuptools >= 70; the conda-forge package already ships without them. This adds a meson-python build next to setup.py (setup.py is unchanged and still works on Python 3.11): - meson.build / meson.options: options sundials-home, superlu-home, blas-home, lapack-home, fortran (feature), extra-fortran-flags; SUNDIALS version, index size, SuperLU_MT and rtol-vector support are read from sundials_config.h (tools/sundials_config.py) into Cython's compile-time environment exactly as setup.py does. - Cython: tools/cythonize_one.py drives Cython (a version tuple cannot be passed on cython's command line); build-support/ mirrors the sources under the package name in the build tree so that "from assimulo.ode cimport ODE" resolves and each module is compiled as assimulo.<name>, as setup.py's copy to build/assimulo/ did. - f2py: tools/f2py_generate.py runs f2py on each .pyf and creates the wrapper files meson expects when f2py does not emit them; fortranobject.c comes from numpy. DASP3 gets -fdefault-double-8 -fdefault-real-8, GLIMDA links BLAS/LAPACK, Radau5 (C) links SuperLU_MT when given. - Compiler flags match the numpy.distutils build (C: -O2 -fno-strict-aliasing -fwrapv -fno-merge-constants -msse -msse2 -msse3; Fortran: -O3 -funroll-loops -fno-second-underscore --std=legacy), so the numerics are the same: tools/dump_examples.py dumps the trajectories and statistics of all 45 examples, and tests/test_build_equivalence.py (env ASSIMULO_REFERENCE_RESULTS) compares two builds. On Linux/gcc 13 with conda-forge SUNDIALS 7.8 and SuperLU_MT all 136 arrays and statistics are bit-identical between the two builds; pytest: 330 passed, 5 skipped with either. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PyrxGeWuwCmAH9LishMW6p
…without a symlink shim Verified on Python 3.12.14 (conda-forge gcc/gfortran, SUNDIALS 7.8): 330 tests pass and all 45 examples are bit-identical to the Python 3.11 numpy.distutils build. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PyrxGeWuwCmAH9LishMW6p
…ts in plain SuperLU) Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PyrxGeWuwCmAH9LishMW6p
…mulo events) TR-BDF2 (Hosea & Shampine, Appl. Numer. Math. 20, 1996): second order, L-stable, stiffly accurate, one iteration matrix I - d h J for both stages (d = 1 - 1/sqrt(2)). The design follows what the FMU benchmarks of this project showed matters for stiff FMU models: - Jacobian policy as in CVode: the Jacobian is recomputed only on the first step of a segment, after a Newton failure with a stale Jacobian, or after 50 accepted steps; the LU is reused while h stays within [0.9, 1.1] of the h it was formed with (an inexact iteration matrix only slows Newton). Both stages are predicted by extrapolating the previous step's dense output, so Newton starts close. - Error estimate: the embedded third-order weights ((1-w)/3, (3w+1)/3, d/3) filtered with (I - d h J)^-1 (the stiff modification of the paper); Gustafsson PI step control. - Dense output: piecewise cubic Hermite through the three stage points, used by Assimulo's event locator and for communication points; state, time and step events work as with Radau5ODE (one-step mode). - A recoverable rhs/Jacobian failure at a trial point shrinks h by 0.25 and is retried up to 40 consecutive times, as CVode does. - Dense LU with partial pivoting in C; no external linear-algebra dependency. Measured against rtol 1e-8 references on the project's FMU set at rtol 1e-6 (PyFMI, correct event counts everywhere): deviations at CVode's level or better (rectifier 8e-5 vs CVode 6e-5, PWM 6e-6 vs 1e-5, Fourbar1 5e-5 vs 5e-4) -- unlike DifferentialEquations.jl's TRBDF2, which was 100x off on the same models; 1.7-3.6x CVode's steps on the switching models (the cost of a second-order method that honours its tolerance), 2.8x fewer on the time-event-dominated PWM model. Tests: tests/solvers/test_trbdf2.py (10). Both build systems (setup.py and meson) build assimulo.lib.trbdf2ode. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PyrxGeWuwCmAH9LishMW6p
…ce hook Found on the switched-capacitor filter (1200 clock events) and the data-center model through PyFMI: - initial step: Hairer's hinit uses sqrt(|y|/|f|) (the sqrt was missing), the estimate is floored at 1e-8 of the segment, and the first accepted step of a segment may grow by up to 1e4 (CVode's ETAMX1), so a too-small guess right after a switching costs a step, not a "step size too small" failure; - a segment whose remaining length is roundoff returns as completed instead of failing (time events landing on the current time); - the LU is reused (inexact iteration matrix) while h/h_lu stays within [0.9, 1.1]; both stages start from the previous step's dense output; the Newton test checks convergence before divergence, so a converged iterate's roundoff-sized next correction does not count as divergence; - statistics: Newton failures split by divergence / iteration limit; TRBDF2_TRACE=1|2 in the environment traces steps and Newton iterations to stderr for debugging. Cauer (2 s, 40 clock events, rtol 1e-6) now runs in 0.5 s like CVode; the data-center model's first 20 s in 1.6 s vs CVode 0.7 s. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PyrxGeWuwCmAH9LishMW6p
…ratic stage-2 predictor Measured on the reference FMUs at rtol 1e-6 against the rtol 1e-8 references (benchmarks/baselines-ref-1e-8), same event counts as CVode everywhere: - Stage derivatives now come from the stage equations, f_i = (y_i - c_i)/(d h), as in Hosea & Shampine, instead of an rhs call at the converged Newton iterate. For a stiff component the rhs at an iterate that is newton_tol off is wrong by h*lambda times that, and this polluted the FSAL derivative, the TR stage of the next step and the dense output: on the data-center model the stage-1 predictor started 1e2-1e4 tolerances off and Newton failed 854 times in 2440 steps. Now 1419 steps, 0 Newton failures, rhs 16997 -> 4126, Jacobians 420 -> 213, deviation 1.9e-4 -> 3.3e-5; every other model keeps its step count and loses the two rhs calls per step (rectifier 45460 -> 29888, PWM 25169 -> 15722); friction gets CVode's 8 state events instead of a spurious ninth. - The dense output keeps its own copy of the accepted end point: after a rejected step y2/f2 belonged to the rejected attempt and the retry's predictor extrapolated from them (Prothero-Robinson at rtol 1e-6: 13 Newton failures at the iteration limit, now 0). - Finite-difference Jacobians take an rhs call at the base point (f0 is the algebraic derivative now). - Newton divergence is declared at a growth of 2x per iteration (CVode's RDIV) instead of a rate of 0.9, which was tripping on the first iterations from a far-off predictor (rates 0.83, 0.08, 0.002 on converging solves). - Stage-2 predictor: quadratic through y0, y1 with slope f1 (5-8 % fewer rhs than extrapolating the previous step's cubic); stage 1 keeps the cubic extrapolation (explicit Euler fails on the data-center model). - Defaults: newton_tol 0.1 (CVode's), lu_band (0.8, 1.25) (10-50 % fewer LU decompositions, no change in rhs or accuracy; 2.0 costs Newton failures). newton_tol, lu_band, fac1, fac2, fail_factor, fail_max are properties so that PyFMI's TRBDF2_options can set them. - Not changed after measuring: the PI step controller sits at err ~ 0.32 of the tolerance; variants targeting 0.6-0.8 take 10-30 % fewer steps but raise the deviation 1.5-3x (fourbar 4.7e-5 -> 1.4e-4, rectifier 7.7e-5 -> 1.1e-4, beyond the 1e-4 acceptance line). Restarting from the last accepted step after an event instead of hinit: 27 % fewer steps on the data-center model, deviation 8x worse; rejected. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PyrxGeWuwCmAH9LishMW6p
Author
|
I ran extensive tests, and this solver is faster than cvode in some cases, and generally slightly more accurate at the same rtol setting compared to a 100x tighter tolerance reference trajectory: in some cases you could loosen rtol by 10X to get the same deviation against the reference. Some case are a lot faster at the same tolerance. I did extensive tests, but certainly not as many as Modelon has. I am still generating more comparisons. FWIW: this solver was the best from the large set of solvers in Julia's diffeq.jl, but is not translated, but simply implemented from scratch. |
hubertus65
marked this pull request as ready for review
September 22, 2026 21:52
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
A new solver
assimulo.solvers.TRBDF2: TR-BDF2 (Hosea & Shampine, Appl. Numer. Math. 20, 1996)— second order, L-stable, stiffly accurate, one iteration matrix
I - d h Jfor both stages(
d = 1 - 1/√2) — implemented fresh as a C stepper with a thin Cython wrapper, with Assimulodoing the events. Three commits on top of the meson-build and Radau5-failure-policy branches
(see Stacking below).
The design follows what an FMU benchmark study of this project showed matters for stiff
model-exchange models:
failure with a stale Jacobian, or after 50 accepted steps; the LU is reused while
hstayswithin
lu_band = (0.8, 1.25)of thehit was formed with — an inexact iteration matrix onlyslows Newton.
f_i = (y_i - c_i)/(d h), as in the paper,not an rhs call at the converged Newton iterate. For a stiff component the rhs at an iterate
that is
newton_toloff is wrong byh·λtimes that, which pollutes the FSAL derivative, theTR stage of the next step and the dense output.
((1-w)/3, (3w+1)/3, d/3)filtered with(I - d h J)⁻¹(the stiff modification of the paper); Gustafsson PI step control.of the accepted end point, used by Assimulo's event locator and for communication points. State,
time and step events work as with
Radau5ODE(one-step mode).hby 0.25 and is retried up to 40consecutive times, as CVode does.
hinitwith thesqrt(|y|/|f|)form, floored at 1e-8 of the segment,and the first accepted step of a segment may grow by up to 1e4 (CVode's
ETAMX1), so atoo-small guess right after a switching costs a step rather than a "step size too small" failure.
TRBDF2_TRACE=1|2tracessteps and Newton iterations to stderr.
Measured
PyFMI, OCT FMUs, rtol 1e-6 against rtol 1e-8 references, correct event counts on every model
(
frictiongets CVode's 8 state events, not a spurious ninth):Steps: 1.7–3.6× CVode on the switching models (the price of a second-order method that honours its
tolerance), 2.8× fewer on the time-event-dominated PWM model. For contrast,
DifferentialEquations.jl's TRBDF2 was ~100× off on the same models at the same tolerance.
The third commit is where most of the accuracy came from — on a 200-state data-center model:
Newton failures 854/2440 steps → 0 in 1419 steps, rhs 16997 → 4126, Jacobians 420 → 213,
deviation 1.9e-4 → 3.3e-5.
Measured and rejected, so you do not have to ask: a PI controller targeting
err ≈ 0.6–0.8ofthe tolerance takes 10–30 % fewer steps but raises the deviation 1.5–3× (fourbar 4.7e-5 → 1.4e-4,
rectifier 7.7e-5 → 1.1e-4); restarting from the last accepted step after an event instead of
hinittakes 27 % fewer steps on the data-center model with an 8× worse deviation.Tests and build
tests/solvers/test_trbdf2.py(10 tests). Both build systems buildassimulo.lib.trbdf2ode:setup.pyand meson.newton_tol(default 0.1, CVode's),lu_band,fac1,fac2,fail_factor,fail_maxareproperties, so a PyFMI
TRBDF2_optionsdict can set them.Stacking
This branch contains the commits of two other PRs I am opening, because it builds on both:
Review those first; this PR's own content is the last three commits
(
9386e2e,ec286ee,9f35caa). I will rebase onto master once they land, or reorder thestack however you prefer.
Review notes
thirdparty/is touched.rodas.fanddopri5.fstay where they are — this isa fresh tableau-driven implementation, not a transliteration, and they serve as numerical
oracles in the tests.
🤖 Generated with Claude Code
https://claude.ai/code/session_01PyrxGeWuwCmAH9LishMW6p