Skip to content

feat(rust): evaluate rust models through compiled evaluators - #5960

Merged
BradyPlanden merged 7 commits into
mainfrom
stack/05-rust-generic-evaluators
Nov 25, 2026
Merged

BradyPlanden merged 7 commits into
mainfrom
stack/05-rust-generic-evaluators

Conversation

@BradyPlanden

Copy link
Copy Markdown
Member

Description

Makes "rust" a valid convert_to_format. A rust model's rhs, algebraic, Jacobian, event and initial-condition functions are compiled to Rust and evaluated by ScipySolver, AlgebraicSolver and EIS. The default stays "casadi".

  • Compilation:
    • BaseSolver.process compiles each function into a CompiledFunction on its own ExprGraph. Inputs are registered in stacking order at their widths (rust_graph_with_inputs).
    • RustEvaluator wraps the compiled function with CasADi's (t, y, inputs) calling convention. It has four roles: the value, the Jacobian (a scipy CSC built on first use), a Jacobian-vector product, and jacp, with one column per sensitivity parameter.
  • Inputs:
    • stack_inputs gains convert_to_format="casadi", and returns a flat numpy array for rust models. Every caller passes the model's format (EIS, inside its rust branch, passes "rust"), and a one-argument call behaves as in v26.10.0.
    • Input-dependent discontinuity times and Modulo periods are evaluated through the model's own compiled functions, with the inputs stacked in its format, as its residual is.
    • An input whose number of values differs from its parameter's width raises pybamm.SolverError naming the input. So does a vector-width input that only a variable reads and that has no value, which before raised a bare ValueError from Rust.
  • Root method: a CasADi root method converts a rust model to CasADi with a warning, as it does any model not in CasADi form; feat(rust): solve rust models with IDAKLUSolver #5962 keeps rust models on rust.
  • Other solvers:
    • IDAKLUSolver, CasadiSolver and CasadiAlgebraicSolver convert rust models to CasADi, with a warning; feat(rust): solve rust models with IDAKLUSolver #5962 adds IDAKLU's Rust path.
    • EIS evaluates the model's Jacobian through Rust. Its output Jacobian is still built with CasADi.
  • Default-path edits: the ScipySolver event wrapper returns np.asarray(...).item(), and EIS calls .sparse() only on CasADi Jacobians, so a python or jax model's Jacobian goes to csc_matrix as it is.
  • Unused here: validate_rust_sensitivity_widths is added in this PR, and feat(rust): solve rust models with IDAKLUSolver #5962 calls it.

Not supported in this PR:

  • return_jacp_stacked raises SolverError, before anything is lowered or compiled.
  • Consistent initialisation's root solve, in NonlinearSolver, still builds its residual with CasADi, so no DAE solver keeps a rust model until feat(rust): solve rust models with IDAKLUSolver #5962.
  • ScipySolver sensitivities raise NotImplementedError, as on main.

Type of change

New feature, under ## Features in CHANGELOG.md.

Key checklist

  • No style issues: pre-commit run
  • Unit tests pass (N), as do the integration tests (N)
  • Tests added: 28 Python test functions.
    • Evaluator parity: each RustEvaluator role against CasADi on a toy DAE (rtol 1e-12, atol 1e-14), including events, initial conditions and a rectangular Jacobian.
    • Plumbing:
      • stack_inputs for rust models, and called with one argument;
      • the input-width SolverError at widths 1 and 3, and for a missing vector input;
      • return_jacp_stacked rejected before lowering;
      • dense-matrix products (TestDenseMatrixToRust) and the conftest_rust fixtures from feat(rust): lower expression trees with Symbol.to_rust #5959, with rust_backend added here;
      • pickled evaluators.
    • ScipySolver: a solve with inputs and an event, on casadi and rust; a rust model with an input-dependent switch time against the exact solution; numpy inputs reaching the evaluators.
    • Solver parity:
      • AlgebraicSolver on rust against casadi (rtol 1e-8);
      • SPM impedance on rust against casadi (rtol 1e-6).
    • Conversion and serialisation: the CasADi solvers convert and solve a rust model; the default root method keeps the rust format; "rust" round-trips through serialisation.
Rust execution engine stack: proposal #5667, showcase #5732

Each PR is one commit on the one above it.

# PR Adds
0 #5954 Function.create_copy keeps the function's class
0b #5955 CasADi's RegPower and uniform-grid interpolant lookups match evaluate
1 #5956 pybamm-core: expression graph, typed IR, interpreters, forward-mode AD
2 #5957 pybamm-core: CompiledModel, coloured Jacobians, the C ABI
3 #5958 pybamm.rust bindings, built into the pybamm wheel
4 #5959 Symbol.to_rust
5 #5960 convert_to_format = "rust" for ScipySolver, AlgebraicSolver and EIS ← this PR
6 #5961 pybammsolvers: IDAKLU over the C ABI
7 #5962 IDAKLUSolver on rust models
8 #5963 variables and sensitivities read in Rust
9 #5964 pybamm-core: diffsol DAE solver
10 #5965 pybamm.DiffsolSolver
11 #5966 "rust" as the default convert_to_format

@codecov

codecov Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.09375% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 98.36%. Comparing base (fd500c5) to head (ef18ee7).

Files with missing lines Patch % Lines
packages/pybamm/src/pybamm/solvers/base_solver.py 92.06% 5 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #5960      +/-   ##
==========================================
- Coverage   98.37%   98.36%   -0.02%     
==========================================
  Files         360      362       +2     
  Lines       38052    38160     +108     
==========================================
+ Hits        37433    37535     +102     
- Misses        619      625       +6     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@BradyPlanden
BradyPlanden force-pushed the stack/05-rust-generic-evaluators branch from db04e34 to 45bbd36 Compare October 28, 2026 09:55
@BradyPlanden
BradyPlanden force-pushed the stack/05-rust-generic-evaluators branch 2 times, most recently from 67e6c0a to 3e4986e Compare October 28, 2026 15:28
@BradyPlanden
BradyPlanden force-pushed the stack/05-rust-generic-evaluators branch from 3e4986e to b408f4d Compare October 29, 2026 08:01
@BradyPlanden
BradyPlanden marked this pull request as ready for review October 29, 2026 08:55
@BradyPlanden
BradyPlanden requested a review from a team as a code owner October 29, 2026 08:55
@github-actions

github-actions Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

ProjectPyBaMM
Branchstack/05-rust-generic-evaluators
Testbedbare-metal

⚠️ WARNING: Truncated view!

The full continuous benchmarking report exceeds the maximum length allowed on this platform.

🐰 View full continuous benchmarking report in Bencher

🔗 Link this project to GitHub

@BradyPlanden
BradyPlanden force-pushed the stack/05-rust-generic-evaluators branch from b408f4d to d158fdb Compare October 29, 2026 17:26
@BradyPlanden
BradyPlanden force-pushed the stack/05-rust-generic-evaluators branch from d158fdb to b6dcf91 Compare November 17, 2026 11:24
@BradyPlanden
BradyPlanden force-pushed the stack/05-rust-generic-evaluators branch 2 times, most recently from 294503a to 99e7905 Compare November 19, 2026 13:30

@martinjrobins martinjrobins left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks @BradyPlanden, looks great. most of the comments below are pre-existing bugs or notes for the future

@BradyPlanden
BradyPlanden force-pushed the stack/05-rust-generic-evaluators branch from 3cc29df to 4f75b78 Compare November 24, 2026 11:24
Base automatically changed from stack/04-to-rust-lowering to main November 24, 2026 13:01
@BradyPlanden
BradyPlanden force-pushed the stack/05-rust-generic-evaluators branch 2 times, most recently from f0d8c4a to 98df1e1 Compare November 24, 2026 14:04
"rust" is a valid convert_to_format; BaseSolver.process builds
RustEvaluators; ScipySolver, AlgebraicSolver and EIS run on them.
#6056 lets a solver take events on the state derivatives: `process` gives
the CasADi functions `y_dot` as a fourth input when `use_state_derivatives`
is set, and otherwise refuses an expression reading `y_dot` as it converts.
The Rust branch ignored the flag, so an event on `x.diff(pybamm.t)` compiled
for a solver that never supplies `y_dot` and failed only when evaluated.

It now raises the same `ValueError` as the CasADi conversion when the
compiled function reads `y_dot` and the flag is unset, and a "func"
`RustEvaluator` passes a fourth argument on as `y_dot`, as the CasADi
function takes it.
…uested

Output variables always ask `process` for a stacked jacp, so
`BaseSolver(output_variables=[...])` refused a rust model even with no
sensitivities requested. CasADi reads the flag only when sensitivities are
on, and the Rust branch now does the same.
The Rust vector-input check ran after the loop that disables observability
for each missing input. Observability cannot be re-enabled, so a refused
call left the model unobservable even once a later solve supplied every
input. The check now runs before that loop.
Replaces the per-format branch with the idiom the algebraic, scipy and
IDAKLU solvers use: `stack_inputs` for a stacked-input format, the dict
otherwise. The new test solves with two inputs, in both orders, on both
backends, and checks the impedances agree.
Converting a StateVector without `y`, or a StateVectorDot without `y_dot`,
raised ValueError on CasADi, and the Rust branch copied it to match. Both
backends now raise pybamm.ModelError, as StateVectorDot.diff already does
for a second time derivative.

BREAKING CHANGE: code catching ValueError from these conversions, including
solution.observe of a time derivative, must catch pybamm.ModelError.
Annotates `input_names` as an iterable of names and the return as an
`ExprGraph`, and documents both.
@BradyPlanden
BradyPlanden force-pushed the stack/05-rust-generic-evaluators branch from 98df1e1 to ef18ee7 Compare November 25, 2026 10:36

@martinjrobins martinjrobins left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

all good, happy to merge

@BradyPlanden
BradyPlanden added this pull request to the merge queue Nov 25, 2026
Merged via the queue into main with commit 264520f Nov 25, 2026
60 of 62 checks passed
@BradyPlanden
BradyPlanden deleted the stack/05-rust-generic-evaluators branch November 25, 2026 16:39
BradyPlanden added a commit that referenced this pull request Dec 2, 2026
Annotates each method's arguments and return, and the lowered expressions it
holds, as #5960's review asked of rust_graph_with_inputs. sensitivity_indices
casts the graph's index to int, since it has already refused unknown names.
GHzytp pushed a commit to GHzytp/PyBaMM that referenced this pull request Dec 3, 2026
* feat(rust): solve rust models with IDAKLUSolver

CompiledModel/EvaluatorPool bindings, RustModelLowering, the IDAKLU rust
set-up and the Rust-backed NonlinearSolver.

* chore(rust): name CompiledModel's bindings for PyO3 0.30 and the lint table

`CompiledModel._rebuild` keeps its Python name through
`#[pyo3(name = ...)]`, as PyO3 0.30 trips `used_underscore_items` on an
underscored Rust name. `sparsity_pattern` and `csc_sparsity_pattern`
cannot fail, so they return their arrays directly now that the workspace
no longer allows `unnecessary_wraps`.

* chore(rust): drop a missing_const_for_fn allow nothing trips

Clippy no longer suggests `const` for the `nnz` getter, so the allow
suppressed nothing.

* perf(rust): let the core validate build_from_parts' roots

`CompiledModel::new` and `set_observables` validate every root they lower, so the binding's own pass walked each root twice.

* fix(rust): hand the Newton solver its evaluator pool

Pass the pool itself to `StandaloneNewtonSolver`, which now owns it, and drop `_NonlinearSolverSetup`'s keepalive slot. A test that built two solvers from one evaluator address now gives each its own pool, as the pool's hand-out-once rule requires.

* feat(rust): upsample rust models in IDAKLUSolver

`upsampling_tolerance` now reaches `convert_to_format = "rust"` models, which
raised a `SolverError` instead. The variable choice that `_upsampling_fcn`
made for CasADi, by name, scale and whether it is an algebraic state, moves
into `_upsampling_variable`, which both backends call. The Rust path lowers
that variable into the `CompiledModel`'s upsampling output, so IDAKLU places
the same points for either backend, and a test holds a model's `t_additive`
to the CasADi one.

`CompiledModel.from_expr` takes an `upsampling_expr`, `upsampling_len` and an
`upsampling` view expose it, and pickling keeps its root. `test_scale` checks
the function each backend compiled, and main's newer IDAKLU tests
(upsampling, non-finite residuals, sensitivity error control and the
iterative linear solver) run on both formats. The Rust check that `solve`
pre-empts for vector-width sensitivities is reached through `set_up`.

* fix(rust): keep a compiled model's inputs as compiled

A `CompiledModel`'s views copied the graph's input registry on first
access. Once another input was registered on the graph, as lowering a
symbol with a new input for `Solution.observe` does, the views refused
the model's `p`, and so did unpickling, since core rebuilt the registry
from the whole restored arena. Views also took the registry's packed
width, so a model widened with `n_inputs=` had views that refused its
own `p`.

Views now take core's registry, which is the one the model compiled
with, and the model's input width; `FunctionMetadata` carries that width
and a view's pickle keeps it. The model pickles how many nodes the graph
held when compiled, and `_rebuild` compiles from that prefix of the
restored graph, which nodes appended since cannot change. The mass
matrix travels as one CSR triple, keeping the pickle tuple within
PyO3's twelve elements.

* feat(rust): IDAKLU events on time derivatives of rust models

`x.diff(pybamm.t)`, for CasADi models. Rust models now have them too.

`CompiledModel.events_read_y_dot` says which events read `y_dot`, and each
event's `CompiledFunction` view now reports it in `uses_y_dot`, where views
assumed no observable could read it. The Rust IDAKLU set-up keeps it as
`events_read_yp`, as the CasADi set-up does, and hands it to
`create_rust_solver_group`. After a solve, `_termination_event_values`
evaluates the solve's own event tapes at the state and yp it stopped at,
for the check at the initial conditions and for `closest_event_idx`.

Outputs and the upsampling variable are given no `y_dot`, as on CasADi, and
the lowering now refuses one that reads it with CasADi's error rather than
the compiled model's.

breakpoint with output variables, where the Rust backend's staged outputs
needed flushing.

* refactor(rust): type RustModelLowering

Annotates each method's arguments and return, and the lowered expressions it
holds, as pybamm-team#5960's review asked of rust_graph_with_inputs. sensitivity_indices
casts the graph's index to int, since it has already refused unknown names.

* refactor(rust): hand each solver an evaluator capsule, not a pool address

`EvaluatorPool.as_ptr` gave C++ an integer address, and the solver group or
Newton solver had to keep the pool alive for as long as it used it.
`CompiledModel.evaluator()` instead returns a new evaluator over the model's
tapes in a `pybamm.rust.evaluator` capsule, which the solver claims and then
owns. A capsule nothing claimed frees its evaluator, and one already claimed
is refused.

`IDAKLUSolver` builds one capsule per solver, and `NonlinearSolver` one for
its Newton solver, which now takes `rust_evaluator`. `EvaluatorPool` is gone,
and the developer guide and crate README describe the capsule handoff and the
frozen-layout rule in place of symbol resolution.

* chore: fold the Rust IDAKLU parity entries into the feature's

Upsampling and events on time derivatives are part of what solving
Rust models with IDAKLUSolver brings, which this PR's entry announces;
no release has reached the Rust backend for them to change.

* test(rust): lengthen the per-state arrays with an overcounted state count

pybamm-team#5961 now refuses an atol or rhs_alg_id whose length is not
number_of_states before Rust sees the model. The test that overcounts
number_of_states lengthens both by one too, so the count still reaches
the Rust model's own check.

* refactor(rust): lower each model into one graph, compiled once

A Rust model was lowered several times over. Each integrator compiled
its CompiledModel through its own copy of the recipe, NonlinearSolver
compiled a second one for its Newton step, and process() gave every
symbol it compiled a graph of its own: the initial conditions,
discontinuity times and step state mappers of every solve, and every
part a solver other than IDAKLU read. Two class flags chose the path.

A model now keeps one RustModelLowering, made by RustModelLowering.of
and kept while its input names stay the same; a copy or pickle of the
model drops it. BaseSolver.set_up compiles the model's CompiledModel on
it for every solver: the residual, the algebraic block of a DAE, the
termination events, the df/dp of any sensitivities, the output
variables and the upsampling output a solver's _upsampling_variable
names. The generic rhs_eval, algebraic_eval and rhs_algebraic_eval,
their Jacobians and the termination events are views of it, as
RustEvaluator now takes a view's rows and a prepared Jacobian.
process(), the EIS output Jacobian and NonlinearSolver compile on the
same graph, and NonlinearSolver reuses the model's CompiledModel rather
than compiling its own. A model without states compiles over an empty
mass matrix.

A ScipySolver set-up of an SPM builds one graph rather than six. A DFN
set up for a Newton initialisation compiles one CompiledModel rather
than two, in 2.7 ms rather than 4.4 ms.

* fix(rust): compile a model's graph whole or not at all, on its own inputs

The model's lowering outlives a set-up, and four things went wrong with
that. Each compile left its parts on the lowering, through public step
methods any caller could run out of order, and set-up blanked the
model's evaluators before compiling: a set-up that failed left the
model without them, breaking another solver's next solve. An input the
model does not have, met while lowering, was registered on its graph
for good. IDAKLUSolver passed a model with no states, which now
compiles, to C++ that crashed on it. And EIS compiled its output
function at every solve.

compile_model now lowers every part into locals and keeps the
CompiledModel, output lengths and sensitivity names only once the model
compiles; its steps are private, and set-up binds the model's
evaluators only after it. An input parameter lowered into a model's
graph refuses a name outside its inputs with a SolverError, so a set-up
missing an input, or an observed symbol reading one, leaves the graph
as it was. IDAKLUSolver refuses a model with no states. EIS caches its
output function on the lowering.

process() keeps no Jacobian-vector product for a Rust model, and
refuses y_dot, which only its CompiledModel's termination events read.
Set-up of the CasADi, Python and JAX formats moves, unchanged, into
_set_up_part_evaluators.

* docs(rust): say what a failed set-up keeps, and build test models through of

The guide claimed a failed set-up leaves the model as it was; it keeps
the evaluators of its last set-up, as the initial conditions are set
before the CompiledModel compiles. The Newton tests now make their
lowerings with RustModelLowering.of, as source does.

* refactor(rust): hand each integrator its CompiledModel, and initial conditions a graph of their own

The lowering kept the last compile's output lengths and sensitivity
names for IDAKLU and Diffsol to read back, so two solvers setting up
one model at once could read each other's, and it bound the model's
evaluators itself. Initial conditions compiled on the model's graph,
which grew by one node, carried by every pickle, for each initial
state a sweep tried.

compile_model now keeps only the CompiledModel, for the Newton step to
reuse. BaseSolver._set_up_rust_model compiles it, binds the model's
evaluators as its views, and hands it to the solver's
_prepare_integrator, which IDAKLU and Diffsol implement in place of
_set_up_rust and _prepare_solver; output lengths come from the
CompiledModel's outputs and sensitivity names from the model. Initial
conditions, which change from solve to solve, compile on a graph of
their own. IDAKLU refuses a model without states as it checks the
model, before anything compiles, and a Rust set-up returns before the
CasADi path's preparation.

* refactor(rust): check before compiling, and bind a model's evaluators last

IDAKLU refused a model with use_jacobian=False only once the model had
compiled and its evaluators were bound to the new CompiledModel. It now
refuses it as it checks the model, before anything compiles, for both
formats; the remaining option helper is _rust_options, and the CasADi
path's unreachable non-CasADi branch is gone. Set-up prepares the
integrator before it binds the model's evaluators, and IDAKLU builds its
set-up before keeping it, so a refused integrator leaves the model as
its last set-up did.

A Rust model's vars_for_processing carries its lowering, which set-up
hands to _set_up_rust_model and swaps for a lowering of their own for
the initial conditions, so process() finds its lowering one way. Its
sensitivity indices come from the lowering's sensitivity_indices, which
refuses an unknown name rather than dropping it. y_dot is checked once,
on the symbol, before it is lowered, so a refused symbol leaves nothing
in the graph; output and event shapes share one helper.

* chore: drop two set-up comments that restate the code

set_up moves the initial-condition block, so comment-slop counts its two
comments as changed lines, and both only name the call beneath them.

* refactor(rust): IDAKLU sizes itself from the evaluator's own table

IDAKLU's set-up read 15 CompiledModel members in Python and passed 20
arguments to create_rust_solver_group, whose RustFunctions took 15, eight
of them counts the evaluator's FFI table already answers. Each count was
checked three times: in Python, in idaklu.cpp, and in C++ against the
table. The Rust Newton solver took its block split and Jacobian pattern
from Python the same way, with Python shifting the pattern's columns into
the block.

The table now also carries the Jacobian's CSC pattern, each state's IDA
id, the algebraic Jacobian's COO pattern, and which event components read
y_dot, appended within ABI version 2. RustFunctions reads a RustLayout
from its own evaluator and works out the band widths from the pattern, so
create_rust_solver_group takes only the evaluators, atol, rtol, options
and whether to use the algebraic sub-block. It refuses an atol of the
wrong length, evaluators with different counts, and a sub-block that
covers only some of the states the mass matrix marks algebraic. The
Newton solver reads its block from the table and shifts the columns
itself, beside the gather that puts the block at the trailing states.

IDA counts one root per event component, as the flags do, so C++ no
longer refuses a vector event; the lowering still does. The C++ pattern
checks, Python's _csc_bandwidths, and the CompiledModel members that only
fed C++ (has_algebraic, algebraic_jacobian_nnz,
algebraic_jacobian_sparsity_pattern) go, with the tests that faked a
disagreement to reach those checks.

* refactor(rust): a compiled model takes the inputs its graph registered

CompiledModel.from_expr took an n_inputs that could make a model wider
than the inputs its graph registered. Nothing but tests used it: set-up
registers every input a solve stacks when it makes the model's graph,
so the lowering only ever passed the default. Widening is why a
function's metadata carried an input width apart from its registry's,
and why a view's pickle kept it.

from_expr drops n_inputs, and a model now takes the packed width of the
inputs its graph had registered when it compiled, read from the same
prefix of the graph _rebuild compiles from, so its pickle no longer
carries the width. A function's input width is its registry's packed
width, so CompiledFunction._rebuild drops input_width.
RustModelLowering.n_inputs and ExprGraph::params lose their last
callers and go.

* test: run NonlinearSolver's tests on both formats, in one file

The Rust Newton path had a file of its own, test_nonlinear_solver_rust.py,
that copied test_nonlinear_solver.py's root finds, inputs, sparse and
dense modes and pivot tolerance for convert_to_format="rust", and an
integration class, TestRustNewton, with more of the same.

test_nonlinear_solver.py now parametrises every test that solves over
convert_to_format, so the Rust path also gets the time-dependent,
caching, pickling, convergence-failure, logging and eSOH checks it
lacked, and the pivot-tolerance test records what reaches each
format's Newton solver. What only the Rust path has, its refusals and
the evaluator it owns, is TestNonlinearSolverRust in the same file.
Two Rust tests the parametrised ones now cover go: a pure-algebraic
parity test and a solver-only pickle round trip.

* test: compare Rust and CasADi IDAKLU solves in one test, over every model case

Seven files compared Rust and CasADi solves, each with its own model and
asserts: an SPM four times over, a DFN, an event, a cubic OCP, an ECM, a
toy model with inputs, and an SPM with inputs plus outputs or
sensitivities. test_rust_model_parity.py already built twelve battery
models to check their compiled expressions against CasADi.

Its case fixture now solves each model with CasADi at tolerances tight
enough for the backends to agree to 1e-5 of each state's scale, plus
1e-8 for states near zero, and TestSolveParity solves it again on Rust:
termination, event time, states and voltage; output variables
evaluated in the solver; and the sensitivities of a case with inputs.
A cubic-OCP SPM joins the cases, and the guard that the DFN reaches
RegPower moves to them. Seven cases end on an event, which a test pins,
and the Thevenin case reads the ECM's N-D interpolants, so
test_rust_idaklu_spm.py, _dfn.py, _parity.py, _inputs.py and
_all_features.py go, with the SPM and DFN parity classes of
test_convert_to_format_rust.py and the decay sensitivity test.

The Marcus-Hush-Chidsey SPM fails on Rust: its algebraic Newton IC
runs on through a NaN state, where CasADi's KLU set-up fails and IDA's
own initialisation takes over. Its solve tests are strict xfails.

* refactor(rust): build IDAKLU's Rust integrator after the base set-up

The base set-up compiled a Rust model and prepared IDAKLU's integrator
before binding the model's evaluators, the reverse of the CasADi path.
IDAKLUSolver.set_up now builds it after the base set-up, as it does for
CasADi, and the base _prepare_integrator hook is gone. The atol shape
check moves to _check_and_prepare_model_inplace, so a bad tolerance is
refused before anything compiles, in either format.

* test: hold the parity solve's event time to what the solve fixes

test_solve_matches_casadi held the Rust and CasADi event times to
rtol=1e-9, tighter than the solve's own rtol of 1e-8. The backends agree
bit for bit on macOS arm64, but on Linux x86-64 their rounding differs
and the SPM drive cycle's maximum-voltage event lands 2e-8 to 5e-8
apart; the CasADi time itself moved 5e-8 between two CI runs.

A 1% change in rtol moves that event by 1.4e-7 of its time, so the
assert takes rtol=1e-6. A wrong event expression or threshold still
moves it far further.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants