Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
7c3d30c
feat: pybamm.DiffsolSolver
BradyPlanden Sep 22, 2026
20051ff
chore(rust): adapt the solver bindings to PyO3 0.30
BradyPlanden Nov 14, 2026
1a0acf1
fix(rust): raise with_time_derivative's errors from PreparedSolver
BradyPlanden Nov 16, 2026
ce94950
fix(rust): raise a solver panic as RuntimeError
BradyPlanden Nov 16, 2026
44e52ff
docs: DiffsolSolver's events cannot read time derivatives
BradyPlanden Nov 21, 2026
3a2d360
refactor: drop DiffsolSolver's relaxed sensitivity retry
BradyPlanden Nov 21, 2026
a0e3293
feat: DiffsolSolver takes diffsol 0.20's options
BradyPlanden Nov 21, 2026
33cb82f
feat: DiffsolSolver's sensitivity_error_control, off by default
BradyPlanden Nov 21, 2026
1720986
fix: DiffsolSolver reads a model's atol
BradyPlanden Nov 21, 2026
b586431
feat: DiffsolSolver takes store_first_last
BradyPlanden Nov 21, 2026
812fb81
refactor: make DiffsolSolver's arguments after the tolerances keyword…
BradyPlanden Nov 21, 2026
c5d6b72
fix: point DiffsolSolver's unsupported-expression errors at IDAKLUSolver
BradyPlanden Nov 21, 2026
8a5863a
docs: correct PreparedSolver's stop-time, y_event and defaults docs
BradyPlanden Nov 21, 2026
30cb935
feat: DiffsolSolver defaults to IDAKLUSolver's rtol of 1e-4
BradyPlanden Nov 21, 2026
e4aeaee
test: state the Hermite derivative error the knots carry
BradyPlanden Nov 21, 2026
4cc19a6
test: a breakpoint resolves a jump only the sensitivities see
BradyPlanden Nov 21, 2026
f713352
feat(rust): let a caller stop a solve between steps
BradyPlanden Nov 26, 2026
3a2e651
refactor(rust): lower each model into one graph, compiled once
BradyPlanden Nov 27, 2026
bc0dbbf
refactor(rust): prepare diffsol over the model's CompiledModel
BradyPlanden Nov 27, 2026
086a51d
refactor(rust): read a Rust model's variables on its graph
BradyPlanden Nov 27, 2026
6f7ed5e
fix(rust): compile a model's graph whole or not at all, on its own in…
BradyPlanden Nov 27, 2026
99f626e
refactor(rust): hand each integrator its CompiledModel, and initial c…
BradyPlanden Nov 27, 2026
a243d03
fix(rust): keep diffsol's state until its PreparedSolver is made
BradyPlanden Nov 28, 2026
522793a
fix(rust): apply the sensitivity atol factor to algebraic states too
BradyPlanden Nov 28, 2026
b2d7394
fix(rust): store yp on any output grid, as IDAKLU does
BradyPlanden Nov 28, 2026
a981ae4
refactor(rust): factorise a single solve's LU serially, as IDAKLU does
BradyPlanden Nov 28, 2026
37d6de5
refactor(rust): compile dF/dt with the model, from its simplified graph
BradyPlanden Nov 28, 2026
a900964
refactor(rust): one PreparedSolver constructor taking one validated c…
BradyPlanden Nov 28, 2026
dddb695
refactor(rust): check a batch's widths in the binding that can mismat…
BradyPlanden Nov 28, 2026
d39d35f
refactor: drop three redundant lines from DiffsolSolver
BradyPlanden Nov 28, 2026
5f0a86d
test: Python tests that can fail, and tests for two untested fixes
BradyPlanden Nov 28, 2026
49fffed
test: a parallel DiffsolSolver sensitivity sweep, and an invalid request
BradyPlanden Nov 30, 2026
532e55d
refactor(rust): build diffsol's integrator after the base set-up
BradyPlanden Dec 2, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/5965.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added `pybamm.DiffsolSolver`, which integrates rust models entirely in Rust, releasing the GIL. Like `IDAKLUSolver`, it finds consistent initial conditions, solves input sets on `num_threads` threads, and computes forward sensitivities natively, under error control with `sensitivity_error_control`.
5 changes: 5 additions & 0 deletions docs/source/api/solvers/diffsol_solver.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Diffsol Solver
==============

.. autoclass:: pybamm.DiffsolSolver
:members:
1 change: 1 addition & 0 deletions docs/source/api/solvers/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ Solvers
.. toctree::

base_solver
diffsol_solver
dummy_solver
scipy_solver
jax_solver
Expand Down
7 changes: 5 additions & 2 deletions docs/source/developer/rust_idaklu_build.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ variables to configure.
- `pybamm-python` implements `pybamm.rust`, which provides the Python API over
the Rust code in `pybamm-core`, which compiles expressions into evaluable
functions and sparse Jacobians.
- `pybamm.rust` also lowers a discretised model to a `CompiledModel` for the
IDAKLU solver.
- `pybamm.rust` also lowers a discretised model to a `CompiledModel`, which the
IDAKLU solver takes, and drives the diffsol solver.
- pybammsolvers does **not** link against the Rust core (the package
dependency only flows the other way). Instead, `CompiledModel.evaluator()`
hands IDAKLU each evaluator in a Python capsule named
Expand Down Expand Up @@ -122,6 +122,9 @@ cd packages/pybamm-rust && cargo test --workspace

# Battery models' expressions and IDAKLU solves on Rust against CasADi (from the repo root)
uv run --group dev pytest packages/pybamm/tests/integration/test_rust_model_parity.py

# Diffsol solver unit tests
uv run --group dev pytest packages/pybamm/tests/unit/test_solvers/test_diffsol_solver.py
```

## Checking the ABI version
Expand Down
1 change: 1 addition & 0 deletions packages/pybamm-rust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions packages/pybamm-rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ rust-version = "1.89"
# Versions both crates use; each crate pins the rest itself.
[workspace.dependencies]
bincode = "1"
rayon = "1"

[workspace.lints.rust]
unsafe_code = "warn"
Expand Down
2 changes: 1 addition & 1 deletion packages/pybamm-rust/pybamm-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ serde = { version = "1", features = ["derive"], optional = true }
bincode = { workspace = true, optional = true }
diffsol = { version = "0.20.0", optional = true, default-features = false, features = ["faer"] }
faer = { version = "0.24", optional = true }
rayon = { version = "1", optional = true }
rayon = { workspace = true, optional = true }

[target.'cfg(target_arch = "x86_64")'.dependencies]
# Compiles matrix products for the detected instruction set, so `accumulate` needs no `unsafe`.
Expand Down
4 changes: 4 additions & 0 deletions packages/pybamm-rust/pybamm-core/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,10 @@ pub enum CoreError {
got: f64,
},

/// The solve's interrupt asked it to stop before it finished.
#[error("the solve was interrupted")]
Interrupted,

/// The integrator or its linear algebra panicked; the message is the panic's own.
#[error("the solver panicked: {0}")]
SolverPanic(String),
Expand Down
81 changes: 81 additions & 0 deletions packages/pybamm-rust/pybamm-core/src/solver/batch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@ impl PreparedSolver {

#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};

use super::*;
use crate::solver::solve::Interrupt;
use crate::solver::solve::SolverConfig;
use crate::solver::test_fixtures::{decay_with_output_and_event, structurally_singular_dae};
use crate::test_support::{bits, block_bits};
Expand Down Expand Up @@ -198,4 +201,82 @@ mod tests {
}
}
}

/// Reads as interrupted from its `after`-th poll on, counting every poll.
#[derive(Debug)]
struct InterruptAfter {
polls: AtomicUsize,
after: usize,
}

impl Interrupt for InterruptAfter {
fn interrupted(&self) -> bool {
self.polls.fetch_add(1, Ordering::Relaxed) >= self.after
}
}

#[test]
fn an_interrupt_stops_a_solve_between_steps() {
let solver = prepared();
let times = t_eval();
let (y0, inputs) = ([1.0], [0.4]);
let set = InputSet::new(&y0, &inputs);
let full = solver
.solve(SolveRequest::new(&times), set)
.expect("solve failed");
let interrupt = InterruptAfter {
polls: AtomicUsize::new(0),
after: 3,
};

let err = solver
.solve(SolveRequest::new(&times).with_interrupt(&interrupt), set)
.expect_err("an interrupted solve finished");

assert!(matches!(err, CoreError::Interrupted), "{err:?}");
let polls = interrupt.polls.load(Ordering::Relaxed);
assert!(
polls < full.statistics.solver.number_of_steps,
"stopped after {polls} polls, not before the full solve's steps"
);
}

#[test]
fn an_unset_interrupt_leaves_the_solve_bit_identical() {
let solver = prepared();
let times = t_eval();
let (y0, inputs) = ([1.0], [0.4]);
let set = InputSet::new(&y0, &inputs);
let flag = AtomicBool::new(false);

let plain = solver
.solve(SolveRequest::new(&times), set)
.expect("solve failed");
let watched = solver
.solve(SolveRequest::new(&times).with_interrupt(&flag), set)
.expect("solve failed");

assert_same_outcome(&watched, &plain, "unset interrupt");
}

#[test]
fn an_interrupt_stops_every_set_of_a_batch() {
let solver = prepared();
let times = t_eval();
let rates = rates(6);
let y0 = [1.0];
let sets = sets(&y0, &rates);
let flag = AtomicBool::new(true);
let request = SolveRequest::new(&times).with_interrupt(&flag);

let batched = run_in_pool(3, || solver.solve_batch(request, &sets));

assert_eq!(batched.len(), sets.len());
for (i, result) in batched.into_iter().enumerate() {
assert!(
matches!(result, Err(CoreError::Interrupted)),
"set {i} ran past the interrupt"
);
}
}
}
2 changes: 1 addition & 1 deletion packages/pybamm-rust/pybamm-core/src/solver/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
//! diffsol applies `RhsOp::jac_mul_inplace` and `MassOp::gemv_inplace` to `S`, one lane per
//! parameter; every other callback expects one lane, read with `lane` or `lane_mut`.

pub mod batch;
mod batch;
mod equations;
mod init;
mod mass;
Expand Down
69 changes: 68 additions & 1 deletion packages/pybamm-rust/pybamm-core/src/solver/solve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use std::cell::RefCell;
use std::ops::Range;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Instant;

use diffsol::matrix::sparse_faer::FaerSparseMat;
Expand Down Expand Up @@ -81,6 +82,31 @@ pub enum Termination {
},
}

impl Termination {
/// The flag the solver boundary carries: `0` completed, `1` event root.
pub const fn as_flag(self) -> i32 {
match self {
Self::Completed => 0,
Self::Event { .. } => 1,
}
}

pub const fn event_time(self) -> Option<f64> {
match self {
Self::Completed => None,
Self::Event { t, .. } => Some(t),
}
}

/// The registration index of the event whose root ended the solve.
pub const fn event_index(self) -> Option<usize> {
match self {
Self::Completed => None,
Self::Event { index, .. } => Some(index),
}
}
}

/// What one solve returns, whichever payloads were asked for.
///
/// On an event root, `t` ends at the root time rather than the last requested point.
Expand Down Expand Up @@ -116,6 +142,20 @@ fn sens_blocks(s: &FaerVec<f64>) -> Vec<Vec<f64>> {
lanes(s).map(<[f64]>::to_vec).collect()
}

/// Asks a running solve to stop; a solve polls it before every integration step.
///
/// A solve that sees it set returns [`CoreError::Interrupted`], so in a batch every set
/// still running stops too.
pub trait Interrupt: Sync + std::fmt::Debug {
fn interrupted(&self) -> bool;
}

impl Interrupt for AtomicBool {
fn interrupted(&self) -> bool {
self.load(Ordering::Relaxed)
}
}

/// What to integrate over and which payloads to report.
#[derive(Clone, Copy, Debug)]
#[must_use]
Expand All @@ -128,6 +168,8 @@ pub struct SolveRequest<'a> {
pub outputs: bool,
/// Solve the forward-sensitivity system, seeded per set by [`InputSet::y0_sens`].
pub sensitivities: bool,
/// Polled before every step; the solve stops once it reads as interrupted.
pub interrupt: Option<&'a dyn Interrupt>,
}

impl<'a> SolveRequest<'a> {
Expand All @@ -138,6 +180,7 @@ impl<'a> SolveRequest<'a> {
t_stop: &[],
outputs: false,
sensitivities: false,
interrupt: None,
}
}

Expand All @@ -158,6 +201,12 @@ impl<'a> SolveRequest<'a> {
self.sensitivities = true;
self
}

/// Stop with [`CoreError::Interrupted`] once `interrupt` reads as interrupted.
pub const fn with_interrupt(mut self, interrupt: &'a dyn Interrupt) -> Self {
self.interrupt = Some(interrupt);
self
}
}

/// One input set of a solve: where the state starts and what the parameters are.
Expand Down Expand Up @@ -480,6 +529,9 @@ impl PreparedSolver {
request: SolveRequest<'_>,
set: InputSet<'_>,
) -> Result<SolveOutcome, CoreError> {
if interrupted(request.interrupt) {
return Err(CoreError::Interrupted);
}
let times = TimePlan::new(request.t_eval, request.t_stop)?;
self.validate_args(set.y0, set.inputs)?;
if request.sensitivities {
Expand Down Expand Up @@ -1244,7 +1296,13 @@ fn integrate<'a, S: OdeSolverMethod<'a, Equations<'a>>>(
request.sensitivities,
&solver.state(),
);
let termination = drive_segments(&mut solver, times, &mut recorder, restart)?;
let termination = drive_segments(
&mut solver,
times,
&mut recorder,
request.interrupt,
restart,
)?;
statistics.solver = solver.get_statistics().clone();
Ok(recorder.finish(termination, &solver.state(), statistics))
}
Expand All @@ -1256,6 +1314,7 @@ fn drive_segments<'a, S: OdeSolverMethod<'a, Equations<'a>>>(
solver: &mut S,
times: TimePlan<'_>,
recorder: &mut Recorder<'_>,
interrupt: Option<&dyn Interrupt>,
mut restart: impl FnMut(&mut S, f64) -> Result<(), CoreError>,
) -> Result<Termination, CoreError> {
let t_eval = times.eval;
Expand Down Expand Up @@ -1285,6 +1344,9 @@ fn drive_segments<'a, S: OdeSolverMethod<'a, Equations<'a>>>(
grant_step_budget(solver);
solver.set_stop_time(t_eval[last])?;
loop {
if interrupted(interrupt) {
return Err(CoreError::Interrupted);
}
let reason = solver.step()?;
let drain_until = match reason {
OdeSolverStopReason::InternalTimestep | OdeSolverStopReason::TstopReached => {
Expand Down Expand Up @@ -1319,6 +1381,11 @@ fn drive_segments<'a, S: OdeSolverMethod<'a, Equations<'a>>>(
Ok(Termination::Completed)
}

/// Whether `interrupt` asks the solve to stop.
fn interrupted(interrupt: Option<&dyn Interrupt>) -> bool {
interrupt.is_some_and(Interrupt::interrupted)
}

/// Give `solver` its whole step budget again, from the steps it has taken so far.
///
/// diffsol counts the budget over a solver's life and refreshes it this way for adjoint
Expand Down
4 changes: 3 additions & 1 deletion packages/pybamm-rust/pybamm-python/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,16 @@ name = "_core"
crate-type = ["cdylib"]

[features]
default = ["serialize"]
default = ["serialize", "diffsol"]
serialize = ["pybamm-core/serialize", "dep:bincode"]
diffsol = ["pybamm-core/diffsol", "dep:rayon"]

[dependencies]
pybamm-core = { path = "../pybamm-core", default-features = false }
pyo3 = { version = "0.30" }
numpy = "0.30"
bincode = { workspace = true, optional = true }
rayon = { workspace = true, optional = true }

[lints]
workspace = true
11 changes: 9 additions & 2 deletions packages/pybamm-rust/pybamm-python/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,18 @@ pub fn graph_err_to_py(err: GraphError) -> PyErr {
}
}

/// Map a refused graph as [`graph_err_to_py`] does, and any other core error to a
/// `ValueError`: a caller-argument or invalid-data problem.
/// Map a core error to `RuntimeError` for integration failures and a refused graph as
/// [`graph_err_to_py`] does, else `ValueError`.
pub fn core_err_to_py(err: CoreError) -> PyErr {
match err {
CoreError::Graph(graph) => graph_err_to_py(graph),
#[cfg(feature = "diffsol")]
CoreError::Diffsol(source) => {
pyo3::exceptions::PyRuntimeError::new_err(format!("diffsol error: {source}"))
},
failure @ CoreError::SolverPanic(_) => {
pyo3::exceptions::PyRuntimeError::new_err(failure.to_string())
},
other => PyValueError::new_err(other.to_string()),
}
}
13 changes: 13 additions & 0 deletions packages/pybamm-rust/pybamm-python/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@ mod expr;
mod function_metadata;
mod jacobian;
mod model;
#[cfg(feature = "diffsol")]
mod rayon_pool;
mod scratch_pool;
#[cfg(feature = "diffsol")]
mod solver;

#[pymodule]
#[pyo3(name = "_core")]
Expand All @@ -24,5 +28,14 @@ fn core_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<jacobian::CompiledJacobian>()?;
m.add_class::<model::CompiledModel>()?;

#[cfg(feature = "diffsol")]
{
m.add_class::<solver::PreparedSolver>()?;
m.add_class::<solver::SolverStatistics>()?;
m.add_class::<solver::SolveOutcome>()?;
m.add_function(wrap_pyfunction!(solver::default_solver_options, m)?)?;
m.add_function(wrap_pyfunction!(rayon_pool::pool_ids, m)?)?;
}

Ok(())
}
Loading
Loading