Repository navigation
Add ARKODE: SUNDIALS ARKStep (DIRK / ERK / imex) as an Assimulo solver - #141
Draft
hubertus65 wants to merge 30 commits into
Draft
hubertus65 wants to merge 30 commits into
hubertus65 wants to merge 30 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
…ARKODE rootfinding New module assimulo.solvers.arkode (src/solvers/arkode.pyx, declarations in src/lib/arkode_includes.pxd), built by Meson and setup.py when SUNDIALS >= 7.1 with arkode/arkode.h is found. Only the stepper-independent ARKode* API is used (ARKStepCreate and ARKStepSetTableName are the exceptions); the CVode callbacks (cv_rhs, cv_jac, cv_jacv, cv_root, cv_err) and ProblemData are reused unchanged since the ARKODE callback signatures are CVode's. - method = "implicit" (ARKStep, DIRK table, Newton, dense direct solver with the problem Jacobian if usejac, or SPGMR with jacv) or "explicit" (ERK). The table comes from 'order' (ARKODE's default table of that order) or 'table' (a name such as ARKODE_TRBDF2_3_3_2). Method-defining options are applied once per memory block: ARKStep frees its Butcher tables on ARKodeSetOrder/ARKStepSetTableName and re-creates them on a first initialization only, not on ARKodeReset (this crashed in arkStep_TakeStep_Z on the second simulate); changing order, table, method, interpolant_degree, linear_solver or external_event_detection recreates the memory. - Events as CVode: ARKODE rootfinding by default (ARKodeRootInit, ARK_ROOT_RETURN, ARKodeGetRootInfo), external_event_detection for Assimulo's locator; after an event ARKodeReset(t, y) keeps the method and its counters, tolerances are re-applied (nominals may change), and the first step is re-estimated unless restart_h = "keep". Time events are stop times (ARK_TSTOP_RETURN). One-step mode, dense output via ARKodeGetDky. - Statistics: nsteps, nstepattempts, nerrfails, nfcns (explicit + implicit), nfcnjacs, njacs, njacvecs, nlus, nniters, nnfails, nconvfails, nstatefcns, nstateevents; ARKODE's counters are cumulative over the memory block, so increments are stored. maxsteps is enforced per integrate call (ARKODE's counts per ARKodeEvolve call, which is one step here). - Defaults from a Van der Pol (mu 1e6, rtol 1e-6) sweep: predictor 1 (dense-output extrapolation; ARKODE's default 0 = y_n needs 2.4x the steps and 3x the rhs), max_nonlin_iters 4 (60 % fewer Jacobians than 3), deduce_implicit_rhs on (the algebraic stage derivative that fixed the native TRBDF2), order 4, nonlin_conv_coef 0.1. Van der Pol with these: 568 steps, 8365 rhs, 65 Jacobians; with the ARKODE_TRBDF2_3_3_2 table 3206 steps, 19211 rhs, 130 Jacobians. - Prothero-Robinson shows the DIRK order reduction (order 3: global error 30x rtol at rtol 1e-6; order 4: 0.6x): the test allows a factor 100. 17 tests in tests/solvers/test_arkode.py (both event locators, time events, switches, explicit mode, dense output, method changes between runs, statistics over events, option validation); 357 pass in total. 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
…dules in solvers.__all__ Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PyrxGeWuwCmAH9LishMW6p
…roduce negative statistics increments Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PyrxGeWuwCmAH9LishMW6p
… (ARKodeSetLSetupFrequency / SetJacEvalFrequency / SetDeltaGammaMax) For the Newton-failure study on the data-center model (448 convergence failures in 1780 attempts with ARKODE's defaults 20 / 51 / 0.2). Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PyrxGeWuwCmAH9LishMW6p
Sweep on the reference FMUs at rtol 1e-6 (benchmarks/exp_arkode_sweep*.sh, baselines-arkode-sweep/). With order 4 (ESDIRK436L2SA) the data-center model went from 1558 steps / 15069 rhs / 654 Jacobians / 448 Newton failures / 17.7 s to 1077 / 7598 / 213 / 7.1 s; friction 713 -> 698 steps, rhs -6 %; rectifier 1214 -> 1191, Cauer 49327 -> 47754 steps with 3355 -> 11 error test failures; the truck pays +20 % rhs. Order 3 (ESDIRK325L2SA) is close on the data-center model but needs 1.8x the steps on friction/rectifier and 2x on Cauer; order 5 tables fail the data-center model and report spurious rectifier events (100 / 64 instead of 62); order 2 (SDIRK-2-1-2) is far behind. max_nonlin_iters, lsetup_frequency and nonlin_conv_coef are neutral or worse. ARKODE's TRBDF2 table vs the native TRBDF2 on the rectifier: 6084 steps / 33724 rhs / 424 Jacobians vs 7513 / 29888 / 170. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PyrxGeWuwCmAH9LishMW6p
…owth, max_efail_growth, max_cfail_growth For the Newton-failure cycle on the absorption-plant FMU (order 4: 732 convergence failures in 664 steps; step cut by 4 after each, regrown by up to 20x, cut again). Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PyrxGeWuwCmAH9LishMW6p
The generic arr2nv() of sundials_callbacks.pxi creates a new SUNContext on every call and never frees it; ARKODE called it at every (re)initialization and event. Each new context also re-creates the SUNLogger from the environment, which reopens SUNLOGGER_*_FILENAME with "w+" and truncates the log of the previous segment -- a debugging build could only show the last segment. _arr2nv() uses self.ctx instead; the generic helper stays for CVode/IDA. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PyrxGeWuwCmAH9LishMW6p
…A5b) On a rhs with a state-dependent jump and no event indicator (the absorption plant's all-or-nothing condensation) Newton fails on 74 % of the ESDIRK4 steps whatever the Jacobian, the trajectory chatters and reports spurious events; CVode's shorter BDF steps and a 2-stage ESDIRK get through. New options fallback_table (default ARKODE_TRBDF2_3_3_2, None disables), fallback_conv_fail_rate (0.3) and fallback_window (50 step attempts): when the rate of steps failed by nonlinear convergence over a window exceeds the threshold, the memory block is recreated with the fallback table at the current point (last step size kept) and the run continues with it, once per simulation, logged and shown in the statistics; fallback_time records when. Absorption plant: 64 -> 10 state events, 521 -> 310 s. Six tests on a sliding-mode problem. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PyrxGeWuwCmAH9LishMW6p
… failure of the fallback table The step-solve failure counter of ARKODE also counts steps failed by a recoverable rhs failure at a stage (the FMU's own solver failing at a trial point, ccpp's IF97 zone); those are the model's failures, not the method's. ProblemData now counts the recoverable rhs failures returned by cv_rhs and the fallback rate excludes them (threshold 0.25). If the fallback table then fails hard (flag -3/-4: ccpp at t = 1479 s, error test at hmin where ESDIRK4 passes), the run switches back to the user's table at that point, once (fallback_return_time). Plant: fires at t = 7e-6, 10 events, 282 s; ccpp: fallback at t = 17, back at t = 1479, completes with 23 events; the other ten FMUs unchanged. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PyrxGeWuwCmAH9LishMW6p
ARKODE's default dense-output degree is the method order. At order 5 the quintic Hermite interpolant needs extra rhs evaluations at every output point (bouncing ball: 700 rhs for 19 steps against 178 with the cubic; explicit order 5: 653 against 123, Dopri5 60) and reports spurious events under rootfinding (rectifier: 100 or 64 events for 62). Orders <= 4 are unchanged to the digit; accuracy at order 5 is unchanged on the four non-stiff FMUs at rtol 1e-6 and 1e-9. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PyrxGeWuwCmAH9LishMW6p
…ed step SPRKStepCreate(f1, f2) with two callbacks that evaluate the problem's rhs and mask it into the momentum part (f1) and the position part (f2), the split given by q_states (indices or a boolean mask of the position states); fixed_h sets the fixed step, compensated_sums the Kahan sums, order (1-6, 8, 10) or table (ARKODE_SPRK_*) the method; no adaptivity or tolerances, rootfinding on SPRKStep's Lagrange interpolant. Kepler (e = 0.6): order 4 at h = 0.01 keeps the energy within 3.3e-6 over 1000 orbits. Four tests. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PyrxGeWuwCmAH9LishMW6p
…ents on problems without state events maxsteps was enforced per integrate call in one-step mode (PyFMI's mode), which CVode never does there; long-horizon models with more than 10000 steps between events failed with ARK_TOO_MUCH_WORK. It now applies per ARKodeEvolve call as ARKODE defines it, i.e. between output points in normal mode only. state_event_info() asked ARKodeGetRootInfo on a problem without event indicators when a step event occurred (ARK_MEM_NULL). Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PyrxGeWuwCmAH9LishMW6p
Every initialization of the SUNDIALS memory, every interpolation and error getter, and every arr2nv() conversion created its own SUNContext and never freed it: a leak per event and per call, and -- since SUNDIALS 7 -- a SUNLogger re-created from the environment each time, which reopens the SUNLOGGER_*_FILENAME files with "w+" and truncates any log written for debugging at every event. The context is now created once in __cinit__, freed in __dealloc__ and passed to the vector helpers; the error handler is pushed onto it once instead of at every (re)initialization. Results are unchanged. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PyrxGeWuwCmAH9LishMW6p (cherry picked from commit e89d446)
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PyrxGeWuwCmAH9LishMW6p
…es, then to the previous Jacobian A user Jacobian the model refuses (a recoverable callback failure: a nonlinear block that does not converge at a perturbed state, a bracketing failure) was retried at a smaller h like a refused rhs -- but the Jacobian is formed at the accepted base point, which does not move with h, so the retry refused again until the failure budget ended the run (TRBDF2_ERROR_REPEATED_FAILURE). form_jacobian() now replaces a refused user Jacobian by the stepper's own forward differences through rhs, which perturb differently (CVode's route on the same models), and if those are refused too keeps the previous Jacobian when there is one (Newton decides; the caller counts it as fresh, so a Newton failure shrinks h instead of re-forming). Only with nothing to fall back on does the refusal reach the step loop as a recoverable failure. A new Jacobian is built in a scratch matrix so a refusal halfway through leaves the previous one intact. Two counters: njacfails (user Jacobian refused, differences used), njacstale (both refused, previous kept); two tests. Found on DataCenter.Examples.Systems.StandardChillerSystem / ChillerWithEconomizerSystem (30-day runs, no directional derivatives, PyFMI's finite-difference Jacobian): the FMU's nonlinear block 7 (chiller.TEvaEnt) refused a perturbed state; PyFMI's side of the fix is in its trbdf2-support branch (a recoverable jac callback, the kink guard's probe guarded). Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PyrxGeWuwCmAH9LishMW6p
…4 |t| DataCenter.Examples.Systems.SetPointOptimization ended with 'step size too small' at t = 3110: a sampled input step there drives chillerWSEplant.chwFcSplit.flowFractions on a nanosecond time scale (CVode gets through with 272 steps from h = 4.5e-13 inside the first millisecond, PyFMI's dynamic diagnostics), and TRBDF2's error estimate was one halving from acceptance (7.6e3 -> 463 -> 12.6 at h = 7.8e-10 / 1.6e-10 / 3.1e-11, falling as h^2.2) when the floor of 1e-14 |t| = 3.1e-11 ended the run. The floor is now 8 DBL_EPSILON max(|t|, 1) -- t + h still distinguishable from t, as CVode's CV_TOO_CLOSE test. Measured: the run completes, 6716 steps / 2.9 s against CVode's 5660 / 1.9 s at rtol 1e-6, 283 accepted steps through [3110, 3115) (CVode 281), one state event (CVode 1), every signal within 3e-4 of range of the 1e-8 reference. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PyrxGeWuwCmAH9LishMW6p
…ver (linear_solver='BLOCK') The problem provides rhs_implicit/rhs_explicit (full-length, zero outside the part); ARKStep gets the pair as fe/fi, Newton runs on the implicit part with the problem's jac as its Jacobian. Tables: ARKODE's ARK pairs by order (2-5) or by name (a (dirk, erk) pair, or the DIRK name with the ERK partner derived). When the implicit states fall into blocks whose derivatives do not depend on each other's states (a vehicle body, explicit, carrying several suspensions that only interact through it), problem.implicit_blocks with linear_solver='BLOCK' replaces the dense LU by one small LU per block plus the substitution of the coupling columns to the outside states: sum(n_b^3) instead of n^3, the dense solution to rounding. It is a custom direct SUNLinearSolver on the dense SUNMatrix ARKLS already fills (SUNDlsMat GETRF/GETRS per block). Every setup checks the matrix against the declared structure and refuses it with the offending entry named (block_check, block_check_tol), since an FMU's dependency structure can change at an event. Measured on a slow cart with k stiff, mutually decoupled spring-damper units (k = 4, rtol 1e-6, vs Radau5 1e-10): implicit order 4 960 steps / 5.7e-5, imex order 4 286 steps / 1.4e-4, imex BLOCK 430 steps at the same counts as imex DENSE (+-1 %). The ARK436 pair's embedded estimate is optimistic on the k = 1 case (7e-3 at a quarter of the DIRK's steps) and converges with the tolerance (2.6e-6 at rtol 1e-8); order 5 is 100x more accurate at 2x the steps -- recorded, not tuned. sundials_includes.pxd: SUNLinearSolver_Ops.lastflag returns sunindextype (the header's type; the field was declared long int and never used). Examples bit-identical to the distutils reference (45/45); 381 tests. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PyrxGeWuwCmAH9LishMW6p
…alize, not only at construction PyFMI sets the partition on the problem after creating the solver (FMIODE2.set_implicit_partition from ARKODE_options); with the callbacks captured in __init__ only, the first evolve dereferenced a NULL callback. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PyrxGeWuwCmAH9LishMW6p
…fail_max) ARKStep returns ARK_UNREC_RHSFUNC_ERR for a recoverable rhs failure at any directly evaluated stage -- every explicit stage of an ERK or ARK pair, the first stage of an ESDIRK -- and retries only the failures inside Newton (arkode_arkstep.c, TakeStep_Z). A DIRK survives an FMU refusing trial points (IF97 assertions on the SuperCriticalRankine400MWe plant) because the refusals happen in Newton; the imex and explicit methods died at the first one (flag -11 at t = 1.7 on that plant). The wrapper now restarts at the caller's last point (the last accepted step in one-step mode, the last output point otherwise -- ARKODE's own current point can lie beyond a pending output time, which a reset there makes unreachable) with the step reduced by fail_factor (0.25), up to fail_max (40) consecutive times: the Radau5/TRBDF2 policy. New statistics key nrhsfails. Tests: a problem whose explicit part refuses points outside a band that a large first step's stage values leave (imex and explicit methods), fail_max = 0 surfaces the error, option validation. 384 pass. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PyrxGeWuwCmAH9LishMW6p
Author
|
This is experimental still, and needs more work. Consider this a hobby project so far. However, I am convinced that with the right "massaging" of how to split e.g. fast and slow modes, and automating the difficulties with scripting, that this can be quite useful. |
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.ARKODEwrapping SUNDIALS ARKODE's ARKStep through thestepper-independent
ARKode*API (SUNDIALS ≥ 7.1): a diagonally implicit table (orders 2–5,L-stable at every order) with Newton and a dense linear solver on the problem's Jacobian or
Jacobian-vector products (SPGMR), or an explicit table (orders 2–9); ARKODE's rootfinding for
state events or Assimulo's locator;
ARKodeResetafter events with the first stepre-estimated; dense output; step attempts and convergence-failed steps in the statistics. Built
by the Meson build when
arkode/arkode.his found (sundials_arkodein the link list),otherwise skipped. Ten commits on top of the TRBDF2 branch, each self-contained.
69f5dd3src/solvers/arkode.pyx,src/lib/arkode_includes.pxd, 17 tests (tests/solvers/test_arkode.py), build hookscdc7c4e085369ddoc/sphinx/source/markup.py), modules insolvers.__all__7b04ffeARKodeResetzeroes (root evaluations) no longer produce negative increments6ec5233b78386a76bcbfblsetup_frequency,jac_eval_frequency,delta_gamma_max) and the step-size bounds (safety,max_growth,max_first_growth,max_efail_growth,max_cfail_growth); defaults from a sweep on 12 FMUs:predictor = 2,delta_gamma_max = 0.05,max_nonlin_iters = 4,deduce_implicit_rhs = True889bbb1SUNContext(the sharedarr2nv()helper creates and leaks a context per call, and each new context re-opens theSUNLOGGER_*files, truncating a debugging log)d143d9ebb5378ffallback_table,fallback_conv_fail_rate,fallback_window) when Newton fails on most steps — a rhs with a state-dependent jump and no event indicator — with a bounce-back to the user's table if the fallback fails hard; Newton failures counted apart from recoverable rhs failures (ProblemData.nrhsfails)Things learned that the code relies on
ARKodeSetOrder/ARKStepSetTableNamefree ARKStep's Butcher tables and re-create them on afirst initialization only, never on
ARKodeReset: the method-defining options are applied onceper memory block and changing them recreates the block (else a segfault on the second
simulate).ARKodeResetkeeps the step size and most counters and zeroes the root-evaluation counter;maxstepscounts perARKodeEvolvecall, so one-step mode enforces it perintegratecall.predictors on Van der Pol;
deduce_implicit_rhsis essential for models whose rhs is solvedto a tolerance internally (FMUs: without it the step size collapses).
rootfinding;
interpolant_degree = 3fixes it (order 4 does not need it).Measured (PyFMI, OCT FMUs, rtol 1e-6, against rtol 1e-8 references; steps / rhs / Jacobians / state events)
Deviations from the references at Radau5's level (friction 1.3e-5, rectifier 9e-6, clutches
2e-6). ARKODE running the TRBDF2 table lands within 10–25 % of Assimulo's native TRBDF2 stepper
on every model (a cross-validation of both). A 224-model comparison on Modelon-library and
Buildings examples is in
docs/shootout-extended.md.Tests:
pytest tests/363 passed, 6 skipped (Python 3.11, conda-forge SUNDIALS 7.9.0).Addendum (2026-09-21): imex and the block-diagonal Newton solver
method = "imex"runs ARKStep's additive pairs (orders 2–5) on a rhs the problemsplits as
rhs_implicit + rhs_explicit;jacis then the implicit part'sJacobian.
linear_solver = "BLOCK"usesproblem.implicit_blocks(index sets ofimplicit states whose derivatives are independent of each other's states — several
fast subsystems that only interact through the explicit part) to factor the Newton
matrix block by block, a custom direct
SUNLinearSolveron the denseSUNMatrix;every setup verifies the declared structure and refuses the matrix with the
offending entry named. Tests: a slow cart carrying k stiff decoupled units
(BLOCK reproduces DENSE's run), wrong blocks, events, tables.
nfcns_implicitis a new statistics key.
Stacking
This branch sits on top of three other PRs I am opening and carries their commits:
arkode/arkode.his found;(
86133d0,fcab674) fix TRBDF2 rather than ARKODE;and it repeats the single commit of #135 (One SUNContext per solver object) as
f76698e,which ARKODE's vector allocation depends on.
Its own content is the ARKODE commits listed in the table above plus the imex/BLOCK addendum.
Review it last; I will rebase onto master as the others land, or split it further if you prefer
the imex/BLOCK part as a separate PR.
Review notes
change TRBDF2 only.
thirdparty/is touched.arkode/arkode.his present (sundials_arkodein the link list) andskipped otherwise, so a SUNDIALS without ARKODE still builds.
🤖 Generated with Claude Code
https://claude.ai/code/session_01PyrxGeWuwCmAH9LishMW6p