Skip to content

feat(rust): interpolant tables over input parameters and expressions - #6134

Open
BradyPlanden wants to merge 12 commits into
stack/10-diffsol-solverfrom
stack/10a-input-interpolant
Open

BradyPlanden wants to merge 12 commits into
stack/10-diffsol-solverfrom
stack/10a-input-interpolant

Conversation

@BradyPlanden

@BradyPlanden BradyPlanden commented Nov 30, 2026 •

Copy link
Copy Markdown
Member

Description

pybamm.Interpolant takes one scalar symbol per value for 1D linear tables, so a table's values can be input parameters to fit, constants, or any expression. The Rust backend lowers it with a sensitivity per value; CasADi lowers it through interpn_linear.

Interpolant(x, y=[v0, ..., vn], interpolator="linear")
  every value a constant         -> Interpolant1DLinear       the fixed table, as before
  input parameters and constants -> InputInterpolant1DLinear  reads each knot's input in place
  any other scalar expressions   -> ExprInterpolant1DLinear   reads its values from a child vector
  • The new nodes share the fixed table's knot search and blend, so they match it bit for bit. Forward, batched and reverse mode give one sensitivity column per value.
  • Symbolic differentiation, DiffSL export and Python source export raise NotImplementedError, as they cannot represent the table.
  • Speed-ups a 512-knot fitted table exposed: model checks and event set-up visit each shared node once (first solve 1.2 s to 0.22 s), thousands of scalar inputs pack in one NumPy call (2048 inputs: 5.7 ms to 2.3 ms), and branch picks are O(1).

Evidence

  • A symbolic-y table matches the fixed table of its values in Python, CasADi and Rust.
  • Expression tables, and a CompiledModel's rhs Jacobian and df/dp over an input table, match central differences; fitted-value sensitivities match CasADi's.
  • One model set up with and without the shared-node walk gives the same events, segments and solution, bit for bit.

Merge Danger

Door: two-way. Blast radius: models with symbolic y; numeric tables lower as before.

Type of change

New feature and optimizations: 6134.feature.md, 6134.optimization.md, 6134.optimization.1.md.

Key checklist

  • No style issues: pre-commit run
  • Unit tests pass (7408), as do the integration tests (812)
  • Rust: cargo test --all-features, clippy over every feature combination, MSRV 1.89
  • Tests added: Python and Rust tests for each lowering, its sensitivities, and the speed-ups
Rust execution engine stack: proposal #5667, showcase #5732

Each PR builds 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
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
10a #6134 Interpolant over input parameters and expressions ← this PR
10b #6138 pybamm.rust's own errors, array-likes, threads and Ctrl-C
10c #6135 pybamm.rust.inspection; every tape derived in one place
11 #5966 "rust" as the default convert_to_format

@codecov

codecov Bot commented Nov 30, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 98.42%. Comparing base (d5f2cc3) to head (03b1a3a).

Additional details and impacted files
@@                   Coverage Diff                    @@
##           stack/10-diffsol-solver    #6134   +/-   ##
========================================================
  Coverage                    98.41%   98.42%           
========================================================
  Files                          364      364           
  Lines                        39223    39303   +80     
========================================================
+ Hits                         38601    38683   +82     
+ Misses                         622      620    -2     

☔ 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 removed this pull request from stack #6136 November 30, 2026 11:52
@BradyPlanden
BradyPlanden force-pushed the stack/10a-input-interpolant branch from 37619c5 to 27c1b4a Compare November 30, 2026 11:54
@BradyPlanden
BradyPlanden added this pull request to stack #6139 November 30, 2026 11:54
@BradyPlanden BradyPlanden changed the title feat(rust)!: interpolant tables over input parameters and expressions, and pybamm.rust's own errors, array-likes, threads and Ctrl-C feat(rust): interpolant tables over input parameters and expressions Nov 30, 2026
@BradyPlanden
BradyPlanden marked this pull request as ready for review November 30, 2026 12:00
@BradyPlanden
BradyPlanden requested a review from a team as a code owner November 30, 2026 12:00
@github-actions

github-actions Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

ProjectPyBaMM
Branchstack/10a-input-interpolant
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/10a-input-interpolant branch from 27c1b4a to c3e7bd1 Compare November 30, 2026 15:40
@BradyPlanden
BradyPlanden force-pushed the stack/10a-input-interpolant branch from c3e7bd1 to 03b1a3a Compare December 2, 2026 09:22
…f/dp seeding

`active_branch` computes the selector's window in closed form instead of
scanning every branch. The batched `Dispatch` marks each lane's branch in
one pass, out of line from the interpreter loop, so it costs its lanes plus
the blocks they select rather than branches squared times lanes.
`unit_param_columns` zeroes its seed buffers once per assembly and clears
only the seeds each walk set, so `df/dp` no longer costs the square of the
parameter count.
`InputInterpolant1DLinear` reads its ordinates from the packed inputs in
place, sharing the knot search and blend of the fixed-table interpolant so
the two agree bit for bit. Its slope node serves state derivatives and a
tangent node reads the ordinates' parameter seeds, so forward, batched and
reverse mode each give one sensitivity column per ordinate.
`AdjointTape::assemble_row` takes the inputs, since reverse mode reads the
ordinates there.

`ExprGraph.interpolant_1d_linear_inputs(x_data, values, child)` builds it
from scalar input parameters registered one after another.
PyBaMM registers inputs in sorted-name order, so a table's knot inputs
are rarely registered in knot order: breakpoint-named knots such as
"R0 at T 1000 [Ohm]" sort before "R0 at T 25 [Ohm]". The table now holds
each knot's registration index and packed offset, so any scalar input
parameters, in any order, can be its ordinates.

The extra indirection costs about 1 ns per lookup: 5-10% on the node's
evaluation, which stays at the fixed-table floor.
`flatten_inputs` converts the values in one call when they share a shape,
as all-scalar inputs do, and concatenates them only otherwise;
`stack_inputs` reuses it. `validate_rust_input_widths` sizes a Python
scalar without `np.size`. On an ECM with 2048 scalar knot inputs, a solve
takes 2.3 ms instead of 5.7 ms.
`y` may be a sequence of scalar symbols, such as input parameters to fit.
They are the interpolant's children after the interpolated one, so
parameter processing, identity and serialisation carry them; values that
all process to constants make an ordinary fixed table.

The Rust backend lowers it through `interpolant_1d_linear_inputs`, and
CasADi through `interpn_linear` over the values. Python evaluation
interpolates the evaluated values. Symbolic differentiation, DiffSL export
and Python source export refuse it, as they cannot represent it.
Python evaluation of an Interpolant with symbolic y evaluated every value
child, so a solve whose extrapolation check reads a 512-knot fitted table
spent 0.7 ms evaluating input parameters it never used. It now evaluates
only the values `interp1d` reads at each point, covering both its
extrapolating path and the `np.interp` path it takes otherwise, and the
result is unchanged bit for bit.
Each knot of an `InputInterpolant1DLinear` reads an `Ordinate`: an input
parameter, or a constant that carries no parameter seed. Tables that fix
some knots and fit the rest keep the in-place read, and the binding takes
constant nodes beside scalar input parameters.
`ExprInterpolant1DLinear` reads its ordinates from a child vector, so a
table's values may be any scalar expressions: slopes summed from fitted
parameters, transformed or scaled inputs, or state-dependent values. Its
tangent is the slope times the argument's tangent plus the same table read
over the values' tangent; reverse mode sends each element's blend weights to
the two values beside it. `const_entries` unions every value's seeds into
each element, as the node is not element-wise. The scalar, adjoint and
batched kernels run out of line, keeping the interpreters' loops as they
were.

`ExprGraph.interpolant_1d_linear` takes numbers, or one scalar `Expr` per
knot: input parameters and constants keep the in-place read, and any other
values build the new node. `interpolant_1d_linear_inputs` is folded into
it, so `pybamm.Interpolant` with symbolic `y` lowers to Rust whatever its
values are, as it does to CasADi.
`Symbol.pre_order(unique=True)` yields each node object once, in the order
of its first occurrence: symbols are immutable, so a repeated object's
subtree has already been yielded. Discretisation shares equal subtrees, so a
tree walk repeats each shared one per use; for a table whose values are
running sums, the walk grows with the square of its knots.

`check_for_time_derivatives` raises on the first offending node, which the
unique walk meets first too. The flux boundary condition check only asks
whether each flux is some divergence's child, which a repeat cannot change;
a test finds a flux whose divergence an equation uses twice. In
`_set_up_events` a repeat adds an event already deduplicated by name and
expression, a constant switch time that `np.unique` drops, or a period whose
stops and restarts change nothing a second time. A test sets up one model
both ways and gets the same events, segments and solution, bit for bit.

A 512-knot ECM table in the slopes formulation first solves in 0.22 s,
not 1.2 s; DFN and SPMe are unchanged.
`ParamRegistry::from_arena` reserved `index_extent() - 1` for every input
interpolant, which underflowed for a table of constants, so unpickling one
failed. It now reserves only for ordinates read from the inputs, and refuses
an ordinate whose slot disagrees with its parameter's, or with another
ordinate's at an index none is registered at, as `ParamSlotConflict`.

`ExprGraph.interpolant_1d_linear` builds the fixed table when every value is
a constant, and validates expression values before it allocates their
`Concat`, so a refused call leaves the graph unchanged.

`pybamm.Interpolant` raises `ShapeError` and `NotImplementedError` for its
symbolic-`y` checks, and its docstring notes that, like a linear table of
fixed values, it cannot be differentiated symbolically.
_to_rust returns before reaching the tables when y is None, but Pyrefly
cannot carry that narrowing into the method, so coerce y as the 2D and 3D
tables already do.
@BradyPlanden
BradyPlanden force-pushed the stack/10a-input-interpolant branch from 03b1a3a to eafe297 Compare December 4, 2026 10:47

This branch has not been deployed

No deployments
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.

1 participant