diff --git a/changelog.d/5962.feature.md b/changelog.d/5962.feature.md new file mode 100644 index 0000000000..acadfd60e7 --- /dev/null +++ b/changelog.d/5962.feature.md @@ -0,0 +1 @@ +`IDAKLUSolver` solves `convert_to_format = "rust"` models through a Rust `CompiledModel`, one evaluator per thread, so `num_threads` parallelises input sets. `output_variables` support sensitivities and time integrals, and `NonlinearSolver` compiles its own model. diff --git a/docs/source/developer/rust_idaklu_build.md b/docs/source/developer/rust_idaklu_build.md index b6aca2f216..8cbcd1e6b8 100644 --- a/docs/source/developer/rust_idaklu_build.md +++ b/docs/source/developer/rust_idaklu_build.md @@ -1,8 +1,9 @@ # Building the Rust Backend -This guide covers building the Rust compute core and its Python bindings for -development. Everything lives in this repository's `uv` workspace; there are -no side-by-side clones or environment variables to configure. +This guide covers building the Rust compute core, its Python bindings, and the +Rust-capable IDAKLU solver for development. Everything lives in this +repository's `uv` workspace; there are no side-by-side clones or environment +variables to configure. ## Components @@ -10,12 +11,40 @@ no side-by-side clones or environment variables to configure. |-----------|----------|------------|--------| | `pybamm-core` | `packages/pybamm-rust/pybamm-core` | Cargo | Rust library (rlib) | | `pybamm-python` | `packages/pybamm-rust/pybamm-python` | maturin (via `uv sync`) | `pybamm.rust._core` extension module | +| pybammsolvers | `packages/pybammsolvers` | scikit-build-core / CMake | `idaklu` extension module | **How the pieces connect:** - `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. +- 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 + `pybamm.rust.evaluator`. The capsule holds the evaluator and a pointer to the + function table of the build that made it, and IDAKLU calls only through that + table. Nothing is resolved by symbol name, so `pybamm.rust._core` exports no + FFI symbols. +- IDAKLU claims each capsule by renaming it `pybamm.rust.evaluator.claimed`, + and then owns the evaluator: each solver frees its own, and a claimed + evaluator cannot be handed to a second solver. +- The contract's source of truth is `FfiTable` and `EvaluatorHandle` in + `packages/pybamm-rust/pybamm-core/src/ffi.rs`. The C++ consumer mirrors them + in + `packages/pybammsolvers/src/pybammsolvers/idaklu_source/Expressions/Rust/pybamm_rust_ffi.h`, + and the `test_ffi_abi_contract` drift test compares the two field by field. +- The table leads with its ABI version and its size. IDAKLU refuses an + evaluator of another version, or one whose table is shorter than the one it + reads, before calling anything. +- IDAKLU sizes every buffer Rust reads or writes from the evaluator's own + table: its counts, Jacobian pattern, state ids, algebraic block and which + events read `yp`. Python hands `create_rust_solver_group` the evaluators, + tolerances, options and whether to use the algebraic sub-block for the + initial conditions. IDAKLU checks what it cannot read from the table, such + as `atol`'s length and a sub-block that covers every algebraic state, + raising `ValueError` on a mismatch. ## Prerequisites @@ -38,12 +67,14 @@ git submodule update --init --recursive uv sync --extra all --group dev ``` -Verify the extension imports: +Verify the two halves see each other: ```bash uv run python -c " -from pybamm.rust import ExprGraph -print('Rust bindings:', ExprGraph) +from pybamm.rust import CompiledModel +from pybammsolvers import idaklu +print('Rust bindings:', CompiledModel) +print('Rust FFI available:', hasattr(idaklu, 'create_rust_solver_group')) " ``` @@ -52,11 +83,54 @@ print('Rust bindings:', ExprGraph) `uv`'s cache keys cover the Rust sources, so `uv sync --extra all --group dev` or `uv run` rebuilds `pybamm.rust._core` whenever a `.rs` file changes. +pybammsolvers' cache key is only its `pyproject.toml`. After changing any of +its C++ sources — including `pybamm_rust_ffi.h` — force a rebuild: + +```bash +uv cache clean pybammsolvers +uv sync --extra all --group dev --reinstall-package pybammsolvers +``` + +## Changing the FFI surface + +The drift test parses both sides of the boundary, so the workflow is +mechanical: + +1. Edit `FfiTable` and `FFI_TABLE` in `ffi.rs` and `PybammRustFfi` in + `pybamm_rust_ffi.h` together. The drift test fails on any field the two + tables do not share, in order and type, on an `FFI_TABLE` entry wired to + another entry's function, and on an entry idaklu never calls. +2. Run `cargo test -p pybamm-core --test test_ffi_abi_contract` from + `packages/pybamm-rust/`. The test holds the layout the current ABI version + froze: + - **Appending** table entries passes it unchanged. A pybammsolvers built + against the shorter table reads only the entries it knows, so it keeps + working with the newer core. + - **Any other change** (an entry's signature or meaning, removing or + reordering entries, or the handle's layout) fails it. Bump + `RUST_ABI_VERSION` and `PYBAMM_RUST_ABI_VERSION` together; the test then + prints the new layout to freeze in its place. +3. Rebuild both extensions (previous section). A pybammsolvers built for + another ABI version refuses the evaluator, naming both versions, rather + than corrupting an evaluation. + ## Running tests ```bash # Rust unit + contract tests 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 +``` + +## Checking the ABI version + +`idaklu.rust_abi_version` is the version a pybammsolvers build reads; it must +equal `RUST_ABI_VERSION` in the `ffi.rs` that built `pybamm.rust._core`: + +```bash +uv run python -c "from pybammsolvers import idaklu; print(idaklu.rust_abi_version)" ``` ## Running benchmarks @@ -68,8 +142,32 @@ cd packages/pybamm-rust && cargo bench -p pybamm-core --all-features ## Troubleshooting +### Segfaults in SUNDIALS callbacks + +Crashes during `solve()` (especially in residual/Jacobian callbacks) usually +indicate a **SuiteSparse version mismatch**: the `.idaklu/` build directory +holds a stale build while the submodules (or a Homebrew install picked up via +`@rpath`) moved on. Rebuild the native dependencies from the current +submodules: + +```bash +cd packages/pybammsolvers +rm -rf .idaklu +uv run python install_KLU_Sundials.py +cd ../.. && uv sync --extra all --group dev --reinstall-package pybammsolvers +``` + +Do **not** point the build at Homebrew's suite-sparse; version mismatches +between it and the local SUNDIALS build cause runtime crashes. + ### `pybamm.rust._core` import fails ```bash uv sync --extra all --group dev --reinstall-package pybamm ``` + +### Rust ABI version errors + +pybammsolvers and `pybamm.rust._core` were built for different ABI versions, +or the core's table is older than the one pybammsolvers reads. Rebuild both +extensions from the same tree (see "Rebuilding after changes"). diff --git a/packages/pybamm-rust/README.md b/packages/pybamm-rust/README.md index 18ddc98aa9..f186d32c60 100644 --- a/packages/pybamm-rust/README.md +++ b/packages/pybamm-rust/README.md @@ -23,6 +23,17 @@ differentiate, lower and evaluate. The crate-level doc walks through them, links module, and explains how the Jacobian is assembled (see [Finding your way around](#finding-your-way-around)). +## Who consumes it + +- **IDAKLU**, through the C ABI in `ffi.rs`. `pybammsolvers` cannot link against this + crate, because PyBaMM depends on `pybammsolvers` and not the reverse. So each evaluator + reaches IDAKLU in a Python capsule that also carries the function table of the build + that made it, and IDAKLU calls only through that table. Nothing is resolved by symbol + name, so IDAKLU loads standalone. The table leads with an ABI version, which IDAKLU + must match, and its size: within a version entries are only appended, so a newer core + still works with an older IDAKLU. Bumping the Rust version means bumping the C++ one + in the same change. + ## Building Build through the workspace, not `cargo` or `maturin` directly: @@ -53,7 +64,8 @@ uv run --group dev pytest -m unit packages/pybamm/tests # python side, from r Rust and Python tests cover different things. The Rust suite owns the compiler and interpreter, including property tests that check AD against finite differences and the -split primal/tangent tape against a monolithic one. The Python suite owns the bindings. +split primal/tangent tape against a monolithic one. The Python suite owns parity: the +same model solved through Rust and through CasADi must agree. ## Benchmarking diff --git a/packages/pybamm-rust/pybamm-core/src/ffi.rs b/packages/pybamm-rust/pybamm-core/src/ffi.rs index b9a61d2405..8361401751 100644 --- a/packages/pybamm-rust/pybamm-core/src/ffi.rs +++ b/packages/pybamm-rust/pybamm-core/src/ffi.rs @@ -155,6 +155,10 @@ pub struct FfiTable { pub upsampling_len: unsafe extern "C" fn(*const c_void) -> c_int, pub upsampling_eval: unsafe extern "C" fn(f64, *const f64, *const f64, *mut f64, *mut c_void) -> c_int, + pub jac_pattern: unsafe extern "C" fn(*const c_void, *mut i64, *mut i64) -> c_int, + pub state_ids: unsafe extern "C" fn(*const c_void, *mut f64) -> c_int, + pub alg_jac_pattern: unsafe extern "C" fn(*const c_void, *mut i64, *mut i64) -> c_int, + pub events_read_y_dot: unsafe extern "C" fn(*const c_void, *mut c_int) -> c_int, } #[expect( @@ -198,6 +202,10 @@ pub static FFI_TABLE: FfiTable = FfiTable { events_eval: pybamm_rust_events_eval, upsampling_len: pybamm_rust_upsampling_len, upsampling_eval: pybamm_rust_upsampling_eval, + jac_pattern: pybamm_rust_jac_pattern, + state_ids: pybamm_rust_state_ids, + alg_jac_pattern: pybamm_rust_alg_jac_pattern, + events_read_y_dot: pybamm_rust_events_read_y_dot, }; /// Free a handle from [`EvaluatorHandle::into_raw`], and its evaluator; null is a no-op. @@ -327,6 +335,16 @@ const fn blocks_len(blocks: usize, width: usize) -> usize { .expect("buffer length overflows usize") } +/// Copy `indices` into `out` as C's `int64_t`, panicking (so `ERROR_PANIC`) on a length +/// mismatch or an index past its range. +#[inline] +fn write_indices(out: &mut [i64], indices: &[usize]) { + assert_eq!(out.len(), indices.len(), "index buffer length"); + for (out, &index) in out.iter_mut().zip(indices) { + *out = i64::try_from(index).expect("index exceeds the int64_t range"); + } +} + /// Borrow `len` elements of a caller-provided buffer. /// /// # Safety @@ -918,6 +936,99 @@ pub unsafe extern "C" fn pybamm_rust_upsampling_eval( } } +/// Write the CSC pattern `jac_assemble` fills: `n_states + 1` column pointers and `jac_nnz` row +/// indices, each column's rows ascending. +/// +/// # Safety +/// +/// `colptrs` must hold `n_states + 1` elements and `rowvals` `jac_nnz`. +pub unsafe extern "C" fn pybamm_rust_jac_pattern( + user_data: *const c_void, + colptrs: *mut i64, + rowvals: *mut i64, +) -> c_int { + // SAFETY: the `# Safety` counts size every borrow, and the guard null-checks each pointer. + unsafe { + with_model(user_data, [colptrs.cast(), rowvals.cast()], |model| { + let csc = model.csc_sparsity(); + write_indices( + borrow_slice_mut(colptrs, model.n_states() + 1), + csc.colptr(), + ); + write_indices(borrow_slice_mut(rowvals, model.nnz()), csc.rowind()); + SUCCESS + }) + } +} + +/// Write IDA's `id` for each state: `1.0` differential, `0.0` algebraic. +/// +/// # Safety +/// +/// `ids` must hold `n_states` elements. +pub unsafe extern "C" fn pybamm_rust_state_ids(user_data: *const c_void, ids: *mut f64) -> c_int { + // SAFETY: the `# Safety` counts size every borrow, and the guard null-checks each pointer. + unsafe { + with_model(user_data, [ids.cast()], |model| { + model + .state_kinds() + .write_ida_id(borrow_slice_mut(ids, model.n_states())); + SUCCESS + }) + } +} + +/// Write the COO pattern `alg_jac_assemble` fills, rows indexing the algebraic block and +/// columns the state. Also returns `ERROR_NO_ALG`. +/// +/// # Safety +/// +/// `rows` and `cols` must each hold `alg_jac_nnz` elements. +pub unsafe extern "C" fn pybamm_rust_alg_jac_pattern( + user_data: *const c_void, + rows: *mut i64, + cols: *mut i64, +) -> c_int { + // SAFETY: the `# Safety` counts size every borrow, and the guard null-checks each pointer. + unsafe { + with_model(user_data, [rows.cast(), cols.cast()], |model| { + let Some(block) = model.algebraic() else { + return ERROR_NO_ALG; + }; + let nnz = block.jacobian().nnz(); + let (block_rows, block_cols) = block.jacobian_coo(); + write_indices(borrow_slice_mut(rows, nnz), block_rows); + write_indices(borrow_slice_mut(cols, nnz), block_cols); + SUCCESS + }) + } +} + +/// Write `1` for each event component that reads `y_dot` and `0` for each that does not, in +/// the order `events_eval` writes them. Also returns `ERROR_NO_EVENTS`. +/// +/// # Safety +/// +/// `flags` must hold `total_event_len` elements. +pub unsafe extern "C" fn pybamm_rust_events_read_y_dot( + user_data: *const c_void, + flags: *mut c_int, +) -> c_int { + // SAFETY: the `# Safety` counts size every borrow, and the guard null-checks each pointer. + unsafe { + with_model(user_data, [flags.cast()], |model| { + if model.n_events() == 0 { + return ERROR_NO_EVENTS; + } + let flags = borrow_slice_mut(flags, model.total_event_len()); + for (flag, reads) in flags.iter_mut().zip(model.event_components_read_y_dot()) { + *flag = c_int::from(reads); + } + SUCCESS + }) + } +} + #[cfg(test)] // Each test owns the pointers it passes, so its setup is the safety argument. #[allow(clippy::undocumented_unsafe_blocks)] @@ -1573,7 +1684,7 @@ mod tests { fn statuses_for_null_user_data( input: *const f64, output: *mut f64, - ) -> [(&'static str, c_int); 22] { + ) -> [(&'static str, c_int); 26] { let nil_data = std::ptr::null_mut::(); [ ("pybamm_rust_eval_rhs", unsafe { @@ -1644,6 +1755,18 @@ mod tests { ("pybamm_rust_upsampling_eval", unsafe { pybamm_rust_upsampling_eval(0.0, input, input, output, nil_data) }), + ("pybamm_rust_jac_pattern", unsafe { + pybamm_rust_jac_pattern(std::ptr::null(), output.cast(), output.cast()) + }), + ("pybamm_rust_state_ids", unsafe { + pybamm_rust_state_ids(std::ptr::null(), output) + }), + ("pybamm_rust_alg_jac_pattern", unsafe { + pybamm_rust_alg_jac_pattern(std::ptr::null(), output.cast(), output.cast()) + }), + ("pybamm_rust_events_read_y_dot", unsafe { + pybamm_rust_events_read_y_dot(std::ptr::null(), output.cast()) + }), ] } @@ -1773,4 +1896,109 @@ mod tests { assert_eq!(events(nil, ok), ERROR_NULL_POINTER, "y"); assert_eq!(events(ok_const, nil_mut), ERROR_NULL_POINTER, "output"); } + + #[test] + fn jac_pattern_writes_the_jacobian_in_csc_order() { + // f = [y1, y1] with M = I: entries (0,0), (0,1), (1,1), which CSR would order otherwise. + let mut arena = Arena::new(); + let y = arena.alloc(Node::StateVector { start: 0, end: 2 }); + let y1 = element(&mut arena, y, 1); + let rhs = arena.alloc(Node::Concat(vec![y1, y1])); + let model = evaluator(compile(&arena, rhs, identity_mass_matrix(2), 2, 0)); + let user_data: *const c_void = std::ptr::from_ref(model.as_ref()).cast(); + + let (mut colptrs, mut rowvals) = ([-1_i64; 3], [-1_i64; 3]); + let status = unsafe { + pybamm_rust_jac_pattern(user_data, colptrs.as_mut_ptr(), rowvals.as_mut_ptr()) + }; + assert_eq!(status, SUCCESS); + assert_eq!((colptrs, rowvals), ([0, 1, 3], [0, 0, 1])); + } + + #[test] + fn state_ids_mark_the_states_the_mass_matrix_leaves_out_as_algebraic() { + let model = evaluator(split_algebraic_model()); + let user_data: *const c_void = std::ptr::from_ref(model.as_ref()).cast(); + let mut ids = [f64::NAN; 3]; + assert_eq!( + unsafe { pybamm_rust_state_ids(user_data, ids.as_mut_ptr()) }, + SUCCESS + ); + // M has one entry, on state 0. + assert_eq!(ids.map(f64::to_bits), [1.0_f64, 0.0, 0.0].map(f64::to_bits)); + } + + #[test] + fn alg_jac_pattern_matches_the_order_alg_jac_assemble_fills() { + let model = evaluator(split_algebraic_model()); + let user_data: *const c_void = std::ptr::from_ref(model.as_ref()).cast(); + let (mut rows, mut cols) = ([-1_i64; 4], [-1_i64; 4]); + let status = + unsafe { pybamm_rust_alg_jac_pattern(user_data, rows.as_mut_ptr(), cols.as_mut_ptr()) }; + assert_eq!(status, SUCCESS); + // `test_rust_alg_jac_assemble_success` fills [y2, 1, y1, 2*y2] in this order; columns + // index the state, not the block. + assert_eq!((rows, cols), ([0, 1, 0, 1], [1, 1, 2, 2])); + + let plain = create_test_model(); + let user_data: *const c_void = std::ptr::from_ref(plain.as_ref()).cast(); + let status = + unsafe { pybamm_rust_alg_jac_pattern(user_data, rows.as_mut_ptr(), cols.as_mut_ptr()) }; + assert_eq!(status, ERROR_NO_ALG); + } + + #[test] + fn events_read_y_dot_flags_every_component_of_each_event() { + // A scalar event on y, then a two-component event on y_dot. + let mut arena = Arena::new(); + let y = arena.alloc(Node::StateVector { start: 0, end: 2 }); + let y0 = element(&mut arena, y, 0); + let y_dot = arena.alloc(Node::StateVectorDot { start: 0, end: 2 }); + let mut model = compile(&arena, y, identity_mass_matrix(2), 2, 0); + model + .set_observables(ObservableKind::Events, &arena, &[y0, y_dot]) + .expect("valid events"); + let model = evaluator(model); + let user_data: *const c_void = std::ptr::from_ref(model.as_ref()).cast(); + let mut flags: [c_int; 3] = [-1; 3]; + assert_eq!( + unsafe { pybamm_rust_events_read_y_dot(user_data, flags.as_mut_ptr()) }, + SUCCESS + ); + assert_eq!(flags, [0, 1, 1]); + + let plain = create_test_model(); + let user_data: *const c_void = std::ptr::from_ref(plain.as_ref()).cast(); + assert_eq!( + unsafe { pybamm_rust_events_read_y_dot(user_data, flags.as_mut_ptr()) }, + ERROR_NO_EVENTS + ); + } + + /// The model has no events, so this also pins nulls outranking `ERROR_NO_EVENTS`. + #[test] + fn every_buffer_of_the_layout_queries_is_null_checked() { + let model = evaluator(split_algebraic_model()); + let user_data: *const c_void = std::ptr::from_ref(model.as_ref()).cast(); + let (mut indices, mut values) = ([0_i64; 4], [0.0_f64; 4]); + let ok = indices.as_mut_ptr(); + let nil = std::ptr::null_mut::(); + + let jac_pattern = + |colptrs, rowvals| unsafe { pybamm_rust_jac_pattern(user_data, colptrs, rowvals) }; + assert_eq!(jac_pattern(nil, ok), ERROR_NULL_POINTER, "colptrs"); + assert_eq!(jac_pattern(ok, nil), ERROR_NULL_POINTER, "rowvals"); + + let alg_jac_pattern = + |rows, cols| unsafe { pybamm_rust_alg_jac_pattern(user_data, rows, cols) }; + assert_eq!(alg_jac_pattern(nil, ok), ERROR_NULL_POINTER, "rows"); + assert_eq!(alg_jac_pattern(ok, nil), ERROR_NULL_POINTER, "cols"); + + let state_ids = |ids| unsafe { pybamm_rust_state_ids(user_data, ids) }; + assert_eq!(state_ids(std::ptr::null_mut()), ERROR_NULL_POINTER, "ids"); + assert_eq!(state_ids(values.as_mut_ptr()), SUCCESS); + + let flags = unsafe { pybamm_rust_events_read_y_dot(user_data, std::ptr::null_mut()) }; + assert_eq!(flags, ERROR_NULL_POINTER, "flags"); + } } diff --git a/packages/pybamm-rust/pybamm-core/src/model/observables.rs b/packages/pybamm-rust/pybamm-core/src/model/observables.rs index 91511ceed2..2c1b44cf64 100644 --- a/packages/pybamm-rust/pybamm-core/src/model/observables.rs +++ b/packages/pybamm-rust/pybamm-core/src/model/observables.rs @@ -124,6 +124,16 @@ impl CompiledModel { self.events.reads_y_dot() } + /// Whether each event component reads `y_dot`: each event's flag once per component, so + /// `total_event_len` flags in all. + pub(crate) fn event_components_read_y_dot(&self) -> impl Iterator + '_ { + self.events + .reads_y_dot() + .iter() + .enumerate() + .flat_map(|(i, &reads)| std::iter::repeat_n(reads, self.events.len_at(i))) + } + /// Length of the upsampling observables concatenated: 0 until they are set. #[inline] pub const fn upsampling_len(&self) -> usize { diff --git a/packages/pybamm-rust/pybamm-core/tests/test_ffi_abi_contract.rs b/packages/pybamm-rust/pybamm-core/tests/test_ffi_abi_contract.rs index 456321d947..6ebe5afd8f 100644 --- a/packages/pybamm-rust/pybamm-core/tests/test_ffi_abi_contract.rs +++ b/packages/pybamm-rust/pybamm-core/tests/test_ffi_abi_contract.rs @@ -62,6 +62,8 @@ fn canon(raw: &str) -> String { "c_int" | "int" => "i32", "*const f64" | "const double*" | "const double *" => "*const f64", "*mut f64" | "double*" | "double *" => "*mut f64", + "*mut i64" | "int64_t*" | "int64_t *" => "*mut i64", + "*mut c_int" | "int*" | "int *" => "*mut i32", "*const c_void" | "const void*" | "const void *" => "*const void", "*mut c_void" | "void*" | "void *" => "*mut void", "*mut EvaluatorHandle" | "PybammRustEvaluator*" => "*mut handle", @@ -377,6 +379,10 @@ const FROZEN_TABLE: &[(&str, &str)] = &[ "upsampling_eval", "fn(f64,*const f64,*const f64,*mut f64,*mut void)->i32", ), + ("jac_pattern", "fn(*const void,*mut i64,*mut i64)->i32"), + ("state_ids", "fn(*const void,*mut f64)->i32"), + ("alg_jac_pattern", "fn(*const void,*mut i64,*mut i64)->i32"), + ("events_read_y_dot", "fn(*const void,*mut i32)->i32"), ]; #[test] diff --git a/packages/pybamm-rust/pybamm-python/src/compiled_function.rs b/packages/pybamm-rust/pybamm-python/src/compiled_function.rs index 4c67c15138..309c9d74ca 100644 --- a/packages/pybamm-rust/pybamm-python/src/compiled_function.rs +++ b/packages/pybamm-rust/pybamm-python/src/compiled_function.rs @@ -196,6 +196,43 @@ impl CompiledFunction { Ok(this) } + /// A view sharing an already compiled `expr`, described by `metadata`, whose state extent + /// must fit in `metadata.n_states`. + pub(crate) fn from_shared( + py: Python<'_>, + expr: Arc, + graph: Py, + root: NodeId, + metadata: FunctionMetadata, + ) -> PyResult { + let reads = graph + .try_borrow(py) + .map(|g| ReadExtents::scan(g.arena(), root)) + .map_err(|_| { + PyValueError::new_err( + "from_shared: graph borrow conflict while preparing bundle view", + ) + })?; + // Bundle views carry the full system width, which must cover what the root reads. + resolve_n_states( + reads.n_states(), + Some(metadata.n_states), + metadata.name.as_deref(), + )?; + Ok(Self { + expr, + metadata, + pool: ScratchPool::default(), + graph, + root, + layout: None, + tangent_y: PyOnceLock::new(), + tangent_p: PyOnceLock::new(), + jac_y: PyOnceLock::new(), + jac_p: PyOnceLock::new(), + }) + } + /// Evaluate at one point into `out`, after checking every argument's length. fn eval_inner( &self, @@ -736,12 +773,20 @@ impl CompiledFunction { /// Rebuild from the retained `(graph, root)` (pickle protocol). /// - /// `n_states` is re-pinned exactly so a user-widened system round-trips, and the inputs - /// are cut back to the `vp_len` registration indices the function was compiled with. + /// `n_states` is re-pinned exactly so a user-widened system round-trips, and the inputs are + /// cut back to the `vp_len` registration indices the function was compiled with. #[staticmethod] #[pyo3( name = "_rebuild", - signature = (graph, root, name, n_states, vp_len, output_names = None, output_lens = None) + signature = ( + graph, + root, + name, + n_states, + vp_len, + output_names = None, + output_lens = None, + ) )] #[allow(clippy::too_many_arguments)] fn rebuild( diff --git a/packages/pybamm-rust/pybamm-python/src/evaluator_capsule.rs b/packages/pybamm-rust/pybamm-python/src/evaluator_capsule.rs new file mode 100644 index 0000000000..87772ba31d --- /dev/null +++ b/packages/pybamm-rust/pybamm-python/src/evaluator_capsule.rs @@ -0,0 +1,48 @@ +//! Python capsules that hand a [`ModelEvaluator`] to a C consumer, which claims it. + +use pyo3::ffi; +use pyo3::prelude::*; +use pyo3::types::PyCapsule; + +use pybamm_core::ModelEvaluator; +use pybamm_core::ffi::{EVALUATOR_CAPSULE, EvaluatorHandle, pybamm_rust_release}; + +// A consumer runs the evaluator on its own threads, so it must stay `Send`. +const _: () = { + const fn assert_send() {} + assert_send::(); +}; + +/// Box `evaluator` into a `pybamm.rust.evaluator` capsule, which frees it unless claimed. +#[allow(unsafe_code)] +pub fn evaluator_capsule( + py: Python<'_>, + evaluator: ModelEvaluator, +) -> PyResult> { + let handle = EvaluatorHandle::into_raw(evaluator); + // SAFETY: `handle` is live until released, and only `release_unclaimed` or the consumer + // that renames the capsule releases it. + unsafe { + PyCapsule::new_with_pointer_and_destructor( + py, + handle.cast(), + EVALUATOR_CAPSULE, + Some(release_unclaimed), + ) + } + // SAFETY: no capsule was made, so nothing else holds `handle`. + .inspect_err(|_| unsafe { pybamm_rust_release(handle.as_ptr()) }) +} + +/// Release the capsule's handle, unless a consumer claimed it by renaming the capsule. +#[allow(unsafe_code)] +unsafe extern "C" fn release_unclaimed(capsule: *mut ffi::PyObject) { + let name = EVALUATOR_CAPSULE.as_ptr(); + // SAFETY: CPython passes the capsule it is destroying; `PyCapsule_IsValid` raises nothing, + // and only an unclaimed capsule still holds a handle this side must release. + unsafe { + if ffi::PyCapsule_IsValid(capsule, name) == 1 { + pybamm_rust_release(ffi::PyCapsule_GetPointer(capsule, name).cast()); + } + } +} diff --git a/packages/pybamm-rust/pybamm-python/src/expr.rs b/packages/pybamm-rust/pybamm-python/src/expr.rs index 7d762b93e8..159d497488 100644 --- a/packages/pybamm-rust/pybamm-python/src/expr.rs +++ b/packages/pybamm-rust/pybamm-python/src/expr.rs @@ -1,6 +1,8 @@ // PyO3 bindings require specific argument types that clippy flags incorrectly #![allow(clippy::needless_pass_by_value)] +use std::borrow::Cow; +use std::cmp::Ordering; use std::collections::HashMap; #[cfg(feature = "serialize")] use std::path::PathBuf; @@ -123,6 +125,25 @@ impl ExprGraph { exprs.iter().map(|e| e.get().node_id_in(slf)).collect() } + /// The arena as it stood when it held `n_nodes` nodes, which is a prefix of it, since + /// nodes are only ever appended. + pub(crate) fn arena_at(&self, n_nodes: usize) -> PyResult> { + match n_nodes.cmp(&self.arena.len()) { + Ordering::Equal => Ok(Cow::Borrowed(&self.arena)), + Ordering::Less => { + let mut prefix = Arena::new(); + for id in node_ids(&self.arena).take(n_nodes) { + let _ = prefix.alloc(self.arena[id].clone()); + } + Ok(Cow::Owned(prefix)) + }, + Ordering::Greater => Err(PyValueError::new_err(format!( + "n_nodes={n_nodes} exceeds the graph's {} nodes", + self.arena.len() + ))), + } + } + /// The registry as it stood at `vp_len` registration indices (all of them for `None`), /// refusing a cut that drops an input the expression `reads`. pub(crate) fn registry_at( diff --git a/packages/pybamm-rust/pybamm-python/src/function_metadata.rs b/packages/pybamm-rust/pybamm-python/src/function_metadata.rs index f8687dd70b..11a6dfde22 100644 --- a/packages/pybamm-rust/pybamm-python/src/function_metadata.rs +++ b/packages/pybamm-rust/pybamm-python/src/function_metadata.rs @@ -26,16 +26,17 @@ impl FunctionMetadata { self.name.as_deref().unwrap_or("") } - const fn total_width(&self) -> usize { - self.params.packed_width().get() - } - /// Length of a parameter-direction vector: one entry per registration index, unregistered /// gaps included, so not the packed width. pub(crate) const fn vp_len(&self) -> usize { self.params.index_extent() } + /// Length of the packed `p`: the registry's packed width. + pub(crate) const fn input_width(&self) -> usize { + self.params.packed_width().get() + } + /// Write input `name`'s values into its packed `slot`, from a real number or any array-like /// of exactly `slot.len()` real values. fn write_input(&self, value: &Bound<'_, PyAny>, name: &str, slot: &mut [f64]) -> PyResult<()> { @@ -109,7 +110,7 @@ impl FunctionMetadata { let py = inputs.py(); // A dict is read without `__missing__`, so a defaultdict cannot invent a missing input. let dict = inputs.cast::().ok(); - let mut packed = vec![0.0; self.total_width()]; + let mut packed = vec![0.0; self.input_width()]; for (_, name, slot) in self.params.registered() { let value = match dict { Some(dict) => dict.get_item(name)?, @@ -190,12 +191,11 @@ impl FunctionMetadata { } pub(crate) fn check_p(&self, len: usize) -> PyResult<()> { - let total_width = self.total_width(); - if len != total_width { + if len != self.input_width() { return Err(PyValueError::new_err(format!( "{}: expected {} input values ({} parameters), got {}", self.display_name(), - total_width, + self.input_width(), self.params.n_registered(), len ))); diff --git a/packages/pybamm-rust/pybamm-python/src/lib.rs b/packages/pybamm-rust/pybamm-python/src/lib.rs index c4b85d04bb..65a7070776 100644 --- a/packages/pybamm-rust/pybamm-python/src/lib.rs +++ b/packages/pybamm-rust/pybamm-python/src/lib.rs @@ -8,9 +8,11 @@ use pyo3::prelude::*; mod arrays; mod compiled_function; mod errors; +mod evaluator_capsule; mod expr; mod function_metadata; mod jacobian; +mod model; mod scratch_pool; #[pymodule] @@ -20,6 +22,7 @@ fn core_module(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_class::()?; m.add_class::()?; m.add_class::()?; + m.add_class::()?; Ok(()) } diff --git a/packages/pybamm-rust/pybamm-python/src/model.rs b/packages/pybamm-rust/pybamm-python/src/model.rs new file mode 100644 index 0000000000..92a3889889 --- /dev/null +++ b/packages/pybamm-rust/pybamm-python/src/model.rs @@ -0,0 +1,822 @@ +// PyO3 bindings require specific argument types that clippy flags incorrectly +#![allow(clippy::needless_pass_by_value)] + +use std::sync::Arc; + +use numpy::{PyArray1, PyArrayMethods, PyReadonlyArray1, PyReadwriteArray1}; +use pyo3::exceptions::PyValueError; +use pyo3::prelude::*; +use pyo3::sync::PyOnceLock; +use pyo3::types::{PyCapsule, PyDict}; + +use pybamm_core::model as core_model; +use pybamm_core::{ + CompiledExpr, CsrData, DagRef, ModelEvaluator, NodeId, ObservableKind, ParamIdx, ParamRegistry, + Shape, +}; + +use crate::compiled_function::CompiledFunction; +use crate::errors::core_err_to_py; +use crate::evaluator_capsule::evaluator_capsule; +use crate::expr::{Expr, ExprGraph}; +use crate::function_metadata::FunctionMetadata; +use crate::jacobian::CompiledJacobian; +use crate::scratch_pool::ScratchPool; + +/// The `_rebuild` argument tuple, in its parameter order. +type RebuildArgs = ( + Py, + u32, + Vec, + Vec, + Option, + Option, + Vec, + MassCsr, + usize, + Vec, +); + +/// A mass matrix's CSR `(data, indptr, indices)`. +type MassCsr = (Vec, Vec, Vec); + +/// CSR index entries as `usize`, refusing the negatives an `int64` array admits. +fn csr_indices(values: &[i64], name: &str) -> PyResult> { + values + .iter() + .map(|&x| usize::try_from(x)) + .collect::>() + .map_err(|_| PyValueError::new_err(format!("{name} entries must be non-negative"))) +} + +/// Borrow `array` for writing, refusing one that is read-only or overlaps another argument. +fn writeable<'py>( + method: &str, + name: &str, + array: &Bound<'py, PyArray1>, +) -> PyResult> { + array.try_readwrite().map_err(|err| { + PyValueError::new_err(format!( + "{method}: {name} must be a writeable array that shares no memory with the \ + inputs ({err})" + )) + }) +} + +/// Pair an algebraic root with its variable indices, refusing indices that have no root. +fn algebraic_block( + root: Option, + variable_indices: Vec, +) -> PyResult)>> { + match root { + Some(root) => Ok(Some((root, variable_indices))), + None if variable_indices.is_empty() => Ok(None), + None => Err(PyValueError::new_err( + "algebraic_variable_indices need an algebraic_expr to index", + )), + } +} + +/// The Python face of [`core_model::CompiledModel`], with bundle views over its tapes. +#[pyclass(frozen, module = "pybamm.rust")] +pub struct CompiledModel { + pub(crate) compiled: Arc, + /// Workspaces for the direct `eval_*`/`assemble_*` helpers. + scratch_pool: ScratchPool, + /// Retained derivation source for the bundle views. + graph: Py, + /// How many nodes the graph held when compiled; nodes are only appended, so the graph as + /// compiled, without any input registered since, is its first `n_nodes`. + n_nodes: usize, + rhs_root: NodeId, + output_roots: Vec, + event_roots: Vec, + upsampling_root: Option, + /// The algebraic block's root and its strictly-ascending global state indices. + algebraic: Option<(NodeId, Vec)>, + // Cached so every accessor hands back the same prepared artifact. + rhs_view: PyOnceLock>, + jac_view: PyOnceLock>, + outputs_view: PyOnceLock>>, + events_view: PyOnceLock>>, + upsampling_view: PyOnceLock>>, + algebraic_residual_view: PyOnceLock>>, + algebraic_jacobian_view: PyOnceLock>>, +} + +impl std::fmt::Debug for CompiledModel { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CompiledModel") + .field("n_states", &self.compiled.n_states()) + .field("n_inputs", &self.compiled.input_width().get()) + .field("output_len", &self.compiled.output_len()) + .field("n_colors", &self.compiled.n_colors()) + .finish_non_exhaustive() + } +} + +impl CompiledModel { + /// Run `body` against the artifact and a pooled [`core_model::Workspace`]. + /// + /// The workspace returns to the pool only when `body` does, so no scratch state from an + /// interrupted call survives into the next. + fn with_scratch( + &self, + body: impl FnOnce(&core_model::CompiledModel, &mut core_model::Workspace) -> R, + ) -> R { + let mut workspace = self + .scratch_pool + .acquire(|| self.compiled.create_workspace()); + let result = body(&self.compiled, &mut workspace); + self.scratch_pool.release(workspace); + result + } + + /// Reject `y`, `yp` or packed `inputs` of another length, which would panic in evaluation. + fn check_eval_args( + &self, + method: &str, + y: usize, + yp: Option, + inputs: usize, + ) -> PyResult<()> { + let n_states = self.compiled.n_states(); + let checks = [ + ("y", Some(y), n_states), + ("yp", yp, n_states), + ("inputs", Some(inputs), self.compiled.input_width().get()), + ]; + for (name, got, expected) in checks { + if let Some(got) = got + && got != expected + { + return Err(PyValueError::new_err(format!( + "CompiledModel.{method}: expected {name} of length {expected}, got {got}" + ))); + } + } + Ok(()) + } + + /// One `CompiledFunction` view per observable of `kind`, named `label[i]`. + fn observable_views( + &self, + py: Python<'_>, + kind: ObservableKind, + roots: &[NodeId], + label: &str, + ) -> PyResult>> { + let exprs = self.compiled.observable_exprs(kind); + // Only events may read y_dot + let reads_y_dot = match kind { + ObservableKind::Events => self.compiled.events_read_y_dot(), + ObservableKind::Outputs | ObservableKind::Upsampling => &[], + }; + (exprs.zip(roots).enumerate()) + .map(|(i, (expr, &root))| { + let uses_y_dot = reads_y_dot.get(i).copied().unwrap_or(false); + let name = format!("{label}[{i}]"); + self.shared_view(py, Arc::clone(expr), root, name, uses_y_dot) + }) + .collect() + } + + /// A `CompiledFunction` view of `expr`, compiled from `root`, named `name`. + fn shared_view( + &self, + py: Python<'_>, + expr: Arc, + root: NodeId, + name: String, + uses_y_dot: bool, + ) -> PyResult> { + let metadata = FunctionMetadata { + uses_y_dot, + ..self.view_metadata(expr.output_len(), name) + }; + Py::new( + py, + CompiledFunction::from_shared(py, expr, self.graph.clone_ref(py), root, metadata)?, + ) + } + + /// Build a [`FunctionMetadata`] for a bundle view: the model's states and inputs, no `y_dot`. + fn view_metadata(&self, output_len: usize, name: String) -> FunctionMetadata { + FunctionMetadata { + params: self.compiled.params().clone(), + n_states: self.compiled.n_states(), + // Only events may read y_dot, and their views say so themselves. + uses_y_dot: false, + output_len, + name: Some(name), + } + } + + /// Build from already-resolved roots, the raw CSR mass matrix and the options. + #[allow(clippy::too_many_arguments)] + fn build_from_parts( + py: Python<'_>, + graph: Py, + rhs_root: NodeId, + output_roots: Vec, + event_roots: Vec, + upsampling_root: Option, + algebraic: Option<(NodeId, Vec)>, + mass_data: Vec, + mass_indptr: &[i64], + mass_indices: &[i64], + n_nodes: Option, + sens_param_indices: Vec, + ) -> PyResult { + let sens_param_indices = sens_param_indices + .into_iter() + .map(|index| { + u32::try_from(index).map(ParamIdx::new).map_err(|_| { + PyValueError::new_err(format!( + "sensitivity index {index} names no input parameter" + )) + }) + }) + .collect::>>()?; + // Infer n_states from indptr length + if mass_indptr.is_empty() { + return Err(PyValueError::new_err( + "mass_indptr must have at least 1 element", + )); + } + let n = mass_indptr.len() - 1; + + let indptr = csr_indices(mass_indptr, "mass_indptr")?; + let indices = csr_indices(mass_indices, "mass_indices")?; + let mass = CsrData::try_new(indptr, indices, mass_data, Shape::matrix(n, n)) + .map_err(core_err_to_py)?; + + let g = graph.try_borrow(py).map_err(|_| { + PyValueError::new_err("CompiledModel.build_from_parts: graph borrow conflict") + })?; + let n_nodes = n_nodes.unwrap_or_else(|| g.arena().len()); + let arena = g.arena_at(n_nodes)?; + let mut roots = std::iter::once(rhs_root) + .chain(output_roots.iter().copied()) + .chain(event_roots.iter().copied()) + .chain(upsampling_root) + .chain(algebraic.as_ref().map(|&(root, _)| root)); + if let Some(root) = roots.find(|root| root.index() >= n_nodes) { + return Err(PyValueError::new_err(format!( + "CompiledModel: root {} is not among the {n_nodes} nodes it was compiled from", + root.raw() + ))); + } + // A model takes every input the graph had registered when it compiled + let input_width = ParamRegistry::from_arena(&arena) + .map_err(core_err_to_py)? + .packed_width(); + + let options = core_model::CompiledModelOptions { + sensitivities: &sens_param_indices, + algebraic: algebraic.as_ref().map(|(residual, variable_indices)| { + core_model::AlgebraicBlockSpec { + residual: *residual, + variable_indices, + } + }), + }; + let mut compiled = core_model::CompiledModel::new( + DagRef::new(&arena, rhs_root), + mass, + n, + input_width, + options, + ) + .map_err(core_err_to_py)?; + let families = [ + (ObservableKind::Outputs, output_roots.as_slice()), + (ObservableKind::Events, event_roots.as_slice()), + (ObservableKind::Upsampling, upsampling_root.as_slice()), + ]; + for (kind, roots) in families { + compiled + .set_observables(kind, &arena, roots) + .map_err(core_err_to_py)?; + } + drop(arena); + drop(g); + + Ok(Self { + compiled: Arc::new(compiled), + scratch_pool: ScratchPool::default(), + graph, + n_nodes, + rhs_root, + output_roots, + event_roots, + upsampling_root, + algebraic, + rhs_view: PyOnceLock::new(), + jac_view: PyOnceLock::new(), + outputs_view: PyOnceLock::new(), + events_view: PyOnceLock::new(), + upsampling_view: PyOnceLock::new(), + algebraic_residual_view: PyOnceLock::new(), + algebraic_jacobian_view: PyOnceLock::new(), + }) + } +} + +#[pymethods] +impl CompiledModel { + /// Create a compiled model from an expression graph and a CSR mass matrix. + /// + /// It takes every input the graph has registered, packed in registration order. + #[staticmethod] + #[pyo3(signature = ( + graph, + expr, + mass_data, + mass_indptr, + mass_indices, + sens_param_indices = vec![], + output_exprs = vec![], + algebraic_expr = None, + algebraic_variable_indices = vec![], + event_exprs = vec![], + upsampling_expr = None, + ))] + #[allow(clippy::too_many_arguments)] // PyO3 keyword args, all distinct concerns + fn from_expr( + py: Python<'_>, + graph: Py, + expr: &Expr, + mass_data: PyReadonlyArray1<'_, f64>, + mass_indptr: PyReadonlyArray1<'_, i64>, + mass_indices: PyReadonlyArray1<'_, i64>, + sens_param_indices: Vec, + output_exprs: Vec>, + algebraic_expr: Option<&Expr>, + algebraic_variable_indices: Vec, + event_exprs: Vec>, + upsampling_expr: Option<&Expr>, + ) -> PyResult { + let mass_data: Vec = mass_data.as_slice()?.to_vec(); + let mass_indptr = mass_indptr.as_slice()?; + let mass_indices = mass_indices.as_slice()?; + + let rhs_root = expr.node_id_in(&graph)?; + let output_roots: Vec = output_exprs + .iter() + .map(|e| e.node_id_in(&graph)) + .collect::>()?; + let event_roots: Vec = event_exprs + .iter() + .map(|e| e.node_id_in(&graph)) + .collect::>()?; + let upsampling_root = upsampling_expr.map(|e| e.node_id_in(&graph)).transpose()?; + let algebraic_root = algebraic_expr + .as_ref() + .map(|e| e.node_id_in(&graph)) + .transpose()?; + let algebraic = algebraic_block(algebraic_root, algebraic_variable_indices)?; + + Self::build_from_parts( + py, + graph, + rhs_root, + output_roots, + event_roots, + upsampling_root, + algebraic, + mass_data, + mass_indptr, + mass_indices, + None, + sens_param_indices, + ) + } + + /// Rebuild from the retained graph, roots and mass CSR (pickle protocol). + /// + /// It compiles from the first `n_nodes` nodes of `graph`, the graph it was compiled from, + /// so inputs registered since do not change its inputs. + #[staticmethod] + #[pyo3(name = "_rebuild")] + #[allow(clippy::too_many_arguments)] + fn rebuild( + py: Python<'_>, + graph: Py, + rhs_root: u32, + output_roots: Vec, + event_roots: Vec, + upsampling_root: Option, + algebraic_root: Option, + algebraic_variable_indices: Vec, + mass: MassCsr, + n_nodes: usize, + sens_param_indices: Vec, + ) -> PyResult { + let (rhs_root, output_roots, event_roots, upsampling_root, algebraic_root) = { + let g = graph.try_borrow(py).map_err(|_| { + PyValueError::new_err("CompiledModel._rebuild: graph borrow conflict") + })?; + let checked = |roots: Vec| -> PyResult> { + roots.into_iter().map(|raw| g.checked_root(raw)).collect() + }; + ( + g.checked_root(rhs_root)?, + checked(output_roots)?, + checked(event_roots)?, + upsampling_root.map(|raw| g.checked_root(raw)).transpose()?, + algebraic_root.map(|raw| g.checked_root(raw)).transpose()?, + ) + }; + let algebraic = algebraic_block(algebraic_root, algebraic_variable_indices)?; + let (mass_data, mass_indptr, mass_indices) = mass; + + Self::build_from_parts( + py, + graph, + rhs_root, + output_roots, + event_roots, + upsampling_root, + algebraic, + mass_data, + &mass_indptr, + &mass_indices, + Some(n_nodes), + sens_param_indices, + ) + } + + /// `(callable, args)` pickle pair that rebuilds from the retained graph and roots. + fn __reduce__<'py>( + slf: &Bound<'py, Self>, + py: Python<'py>, + ) -> PyResult<(Bound<'py, PyAny>, RebuildArgs)> { + let this = slf.borrow(); + let rebuild = slf.get_type().getattr("_rebuild")?; + let mass = this.compiled.mass_matrix(); + let (algebraic_root, algebraic_variable_indices) = this + .algebraic + .as_ref() + .map_or((None, Vec::new()), |(root, indices)| { + (Some(root.raw()), indices.clone()) + }); + Ok(( + rebuild, + ( + this.graph.clone_ref(py), + this.rhs_root.raw(), + this.output_roots.iter().map(|r| r.raw()).collect(), + this.event_roots.iter().map(|r| r.raw()).collect(), + this.upsampling_root.map(NodeId::raw), + algebraic_root, + algebraic_variable_indices, + ( + mass.data().to_vec(), + mass.indptr().to_vec(), + mass.indices().to_vec(), + ), + this.n_nodes, + this.compiled + .sens_param_indices() + .iter() + .copied() + .map(ParamIdx::index) + .collect::>(), + ), + )) + } + + /// Primal f(t, y, p) as a shareable `CompiledFunction` view. + #[getter] + fn rhs(&self, py: Python<'_>) -> PyResult> { + self.rhs_view + .get_or_try_init(py, || { + self.shared_view( + py, + self.compiled.primal_expr_arc(), + self.rhs_root, + "rhs".to_string(), + false, + ) + }) + .map(|f| f.clone_ref(py)) + } + + /// Pure df/dy (cj = 0, no mass): the bundle's composed `JacobianData`. + #[getter] + fn jacobian(&self, py: Python<'_>) -> PyResult> { + self.jac_view + .get_or_try_init(py, || { + let metadata = self.view_metadata(self.compiled.output_len(), "rhs".to_string()); + Py::new( + py, + CompiledJacobian::build(self.compiled.jacobian_data(), metadata)?, + ) + }) + .map(|j| j.clone_ref(py)) + } + + /// Output-variable expressions as shareable `CompiledFunction` views. + #[getter] + fn outputs(&self, py: Python<'_>) -> PyResult>> { + let views = self.outputs_view.get_or_try_init(py, || { + self.observable_views(py, ObservableKind::Outputs, &self.output_roots, "output") + })?; + Ok(views.iter().map(|f| f.clone_ref(py)).collect()) + } + + /// Event expressions as shareable `CompiledFunction` views. + #[getter] + fn events(&self, py: Python<'_>) -> PyResult>> { + let views = self.events_view.get_or_try_init(py, || { + self.observable_views(py, ObservableKind::Events, &self.event_roots, "event") + })?; + Ok(views.iter().map(|f| f.clone_ref(py)).collect()) + } + + /// The upsampling output as a shareable `CompiledFunction` view, or `None` without one. + #[getter] + fn upsampling(&self, py: Python<'_>) -> PyResult>> { + let view = self.upsampling_view.get_or_try_init(py, || { + let roots: Vec = self.upsampling_root.into_iter().collect(); + self.observable_views(py, ObservableKind::Upsampling, &roots, "upsampling") + .map(|mut views| views.pop()) + })?; + Ok(view.as_ref().map(|f| f.clone_ref(py))) + } + + /// Algebraic residual g(t, y, p) as a shareable view, or `None` for ODEs. + #[getter] + fn algebraic_residual(&self, py: Python<'_>) -> PyResult>> { + let cached = self.algebraic_residual_view.get_or_try_init(py, || { + let Some((block, &(root, _))) = self.compiled.algebraic().zip(self.algebraic.as_ref()) + else { + return PyResult::Ok(None); + }; + self.shared_view( + py, + Arc::clone(block.residual_expr()), + root, + "algebraic_residual".to_string(), + false, + ) + .map(Some) + })?; + Ok(cached.as_ref().map(|f| f.clone_ref(py))) + } + + /// `dg/dy_alg` as a prepared jacobian (`n_algebraic` x `n_algebraic`), or `None` for ODEs. + #[getter] + fn algebraic_jacobian(&self, py: Python<'_>) -> PyResult>> { + let cached = self.algebraic_jacobian_view.get_or_try_init(py, || { + let Some(block) = self.compiled.algebraic() else { + return PyResult::Ok(None); + }; + let data = Arc::clone(block.jacobian()); + let metadata = self.view_metadata(data.n_rows(), "algebraic_residual".to_string()); + Ok(Some(Py::new(py, CompiledJacobian::build(data, metadata)?)?)) + })?; + Ok(cached.as_ref().map(|j| j.clone_ref(py))) + } + + /// Compute residual r = M*y' - f(t,y) and return as a new array. + fn eval_residual<'py>( + &self, + py: Python<'py>, + t: f64, + y: PyReadonlyArray1<'_, f64>, + yp: PyReadonlyArray1<'_, f64>, + inputs: PyReadonlyArray1<'_, f64>, + ) -> PyResult>> { + let y_slice = y.as_slice()?; + let yp_slice = yp.as_slice()?; + let inputs_slice = inputs.as_slice()?; + self.check_eval_args( + "eval_residual", + y_slice.len(), + Some(yp_slice.len()), + inputs_slice.len(), + )?; + let mut output = vec![0.0; self.compiled.output_len()]; + + self.with_scratch(|compiled, ws| { + compiled.eval_residual(ws, t, y_slice, yp_slice, inputs_slice, &mut output); + }); + + Ok(PyArray1::from_vec(py, output)) + } + + /// Compute residual r = M*y' - f(t,y) into a pre-allocated output array. + fn eval_residual_into( + &self, + t: f64, + y: PyReadonlyArray1<'_, f64>, + yp: PyReadonlyArray1<'_, f64>, + inputs: PyReadonlyArray1<'_, f64>, + output: &Bound<'_, PyArray1>, + ) -> PyResult<()> { + let mut output = writeable("eval_residual_into", "output", output)?; + let y_slice = y.as_slice()?; + let yp_slice = yp.as_slice()?; + let inputs_slice = inputs.as_slice()?; + self.check_eval_args( + "eval_residual_into", + y_slice.len(), + Some(yp_slice.len()), + inputs_slice.len(), + )?; + let output_slice = output.as_slice_mut()?; + + if output_slice.len() < self.compiled.n_states() { + return Err(PyValueError::new_err(format!( + "output array too small: need {} elements, got {}", + self.compiled.n_states(), + output_slice.len() + ))); + } + + self.with_scratch(|compiled, ws| { + compiled.eval_residual(ws, t, y_slice, yp_slice, inputs_slice, output_slice); + }); + Ok(()) + } + + /// Get the number of states in the model. + #[getter] + fn n_states(&self) -> usize { + self.compiled.n_states() + } + + /// Get the packed width of the model's input parameters. + #[getter] + fn n_inputs(&self) -> usize { + self.compiled.input_width().get() + } + + /// Algebraic-state IDs in IDA's convention: `1.0` differential, `0.0` algebraic. + fn algebraic_ids<'py>(&self, py: Python<'py>) -> Bound<'py, PyArray1> { + let n = self.compiled.n_states(); + let mut buf = vec![0.0; n]; + self.compiled.state_kinds().write_ida_id(&mut buf); + PyArray1::from_vec(py, buf) + } + + /// Number of algebraic states in the compiled sub-block, or 0 without one. + #[getter] + fn n_algebraic(&self) -> usize { + self.compiled + .algebraic() + .map_or(0, core_model::AlgebraicBlock::n_variables) + } + + /// Number of forward-sensitivity parameters configured. + #[getter] + fn n_sens_params(&self) -> usize { + self.compiled.n_sens_params() + } + + /// Number of compiled output-variable expressions. + #[getter] + fn n_outputs(&self) -> usize { + self.compiled.n_outputs() + } + + /// Number of compiled event expressions. + #[getter] + fn n_events(&self) -> usize { + self.compiled.n_events() + } + + /// Whether each event reads `y_dot`, in event order. + #[getter] + fn events_read_y_dot(&self) -> Vec { + self.compiled.events_read_y_dot().to_vec() + } + + /// Length of the compiled upsampling output: 0 without one. + #[getter] + fn upsampling_len(&self) -> usize { + self.compiled.upsampling_len() + } + + /// Get the output length of f(t, y). + #[getter] + fn output_len(&self) -> usize { + self.compiled.output_len() + } + + /// CSR `(indptr, indices)` of `df/dy` merged with the mass pattern. + fn sparsity_pattern<'py>( + &self, + py: Python<'py>, + ) -> (Bound<'py, PyArray1>, Bound<'py, PyArray1>) { + let pattern = self.compiled.sparsity(); + let indptr = PyArray1::from_vec(py, pattern.indptr().to_vec()); + let indices = PyArray1::from_vec(py, pattern.indices().to_vec()); + (indptr, indices) + } + + /// Number of colors in the Jacobian coloring, reduced when dense rows are split out. + #[getter] + fn n_colors(&self) -> usize { + self.compiled.n_colors() + } + + /// Assemble J = df/dy - cj*M into a pre-allocated CSC data buffer of length `nnz`. + fn assemble_jacobian_csc_into( + &self, + t: f64, + y: PyReadonlyArray1<'_, f64>, + cj: f64, + inputs: PyReadonlyArray1<'_, f64>, + jac_data: &Bound<'_, PyArray1>, + ) -> PyResult<()> { + let mut jac_data = writeable("assemble_jacobian_csc_into", "jac_data", jac_data)?; + let y_slice = y.as_slice()?; + let inputs_slice = inputs.as_slice()?; + self.check_eval_args( + "assemble_jacobian_csc_into", + y_slice.len(), + None, + inputs_slice.len(), + )?; + let jac_slice = jac_data.as_slice_mut()?; + + let nnz = self.compiled.nnz(); + if jac_slice.len() < nnz { + return Err(PyValueError::new_err(format!( + "jac_data buffer too small: need {nnz} elements, got {}", + jac_slice.len() + ))); + } + + self.with_scratch(|compiled, ws| { + compiled.assemble_jacobian_csc_into(ws, t, y_slice, inputs_slice, cj, jac_slice); + }); + Ok(()) + } + + /// Get the number of non-zeros in the Jacobian. + #[getter] + fn nnz(&self) -> usize { + self.compiled.nnz() + } + + /// Jacobian assembly stats for benchmarking and debug attribution. + fn jacobian_stats<'py>(&self, py: Python<'py>) -> PyResult> { + let stats = self.compiled.jacobian_stats(); + let dict = PyDict::new(py); + dict.set_item("n_colors", stats.n_colors)?; + dict.set_item("nnz", stats.nnz)?; + dict.set_item("n_dense_rows", stats.n_dense_rows)?; + dict.set_item("n_dense_row_candidates", stats.n_dense_row_candidates)?; + dict.set_item("n_constant_entries", stats.n_constant_entries)?; + dict.set_item("n_swept_columns", stats.n_swept_columns)?; + dict.set_item("jac_lane_width", stats.jac_lane_width)?; + dict.set_item("dense_row_entries", stats.dense_row_entries)?; + dict.set_item( + "dense_row_tape_instructions", + stats.dense_row_tape_instructions, + )?; + dict.set_item( + "split_eval_primal_instructions", + stats.split_eval_primal_instructions, + )?; + dict.set_item( + "split_eval_total_instructions", + stats.split_eval_total_instructions, + )?; + dict.set_item( + "split_eval_raw_instructions", + stats.split_eval_raw_instructions, + )?; + dict.set_item("split_eval_dispatch_count", stats.split_eval_dispatch_count)?; + dict.set_item( + "branch_block_lens", + pyo3::types::PyTuple::new(py, &stats.branch_block_lens)?, + )?; + Ok(dict) + } + + /// Get the CSC sparsity pattern as `(colptr, rowind)`. + fn csc_sparsity_pattern<'py>( + &self, + py: Python<'py>, + ) -> (Bound<'py, PyArray1>, Bound<'py, PyArray1>) { + let csc = self.compiled.csc_sparsity(); + let colptr = PyArray1::from_vec(py, csc.colptr().to_vec()); + let rowind = PyArray1::from_vec(py, csc.rowind().to_vec()); + (colptr, rowind) + } + + /// A new evaluator over this model's tapes, with its own scratch, for one solver. + /// + /// It comes in a `pybamm.rust.evaluator` capsule, which a solver claims and then owns. + fn evaluator<'py>(&self, py: Python<'py>) -> PyResult> { + evaluator_capsule( + py, + ModelEvaluator::from_compiled(Arc::clone(&self.compiled)), + ) + } +} diff --git a/packages/pybamm/src/pybamm/expression_tree/input_parameter.py b/packages/pybamm/src/pybamm/expression_tree/input_parameter.py index a26a789878..ac6c9d7d4f 100644 --- a/packages/pybamm/src/pybamm/expression_tree/input_parameter.py +++ b/packages/pybamm/src/pybamm/expression_tree/input_parameter.py @@ -89,6 +89,13 @@ def _to_casadi(self, t, y, y_dot, inputs, casadi_symbols): def _to_rust( self, graph: pybamm.rust.ExprGraph, rust_symbols: dict ) -> pybamm.rust.Expr: + # A model's graph fixes its inputs; another would shift the stacked inputs + input_names = getattr(rust_symbols, "input_names", None) + if input_names is not None and self.name not in input_names: + raise pybamm.SolverError( + f"Input parameter '{self.name}' is not one of the inputs given, " + f"{sorted(input_names)}" + ) return graph.input_parameter(self.name, self._expected_size or 1) def _jac(self, variable: pybamm.StateVector) -> pybamm.Matrix: diff --git a/packages/pybamm/src/pybamm/models/base_model.py b/packages/pybamm/src/pybamm/models/base_model.py index 628be9e70e..c49fccfd80 100644 --- a/packages/pybamm/src/pybamm/models/base_model.py +++ b/packages/pybamm/src/pybamm/models/base_model.py @@ -135,9 +135,9 @@ def __init_subclass__(cls, **kwargs): y0S_list: list[Any] | None initial_conditions_eval: Callable[..., Any] jacp_initial_conditions_eval: Callable[..., Any] | None - rhs_eval: Callable[..., Any] - algebraic_eval: Callable[..., Any] - rhs_algebraic_eval: Callable[..., Any] + rhs_eval: Callable[..., Any] | None + algebraic_eval: Callable[..., Any] | None + rhs_algebraic_eval: Callable[..., Any] | None jac_rhs_eval: Callable[..., Any] | None jac_rhs_action_eval: Callable[..., Any] | None jacp_rhs_eval: Callable[..., Any] | None @@ -193,6 +193,7 @@ def __init__(self, name="Unnamed model"): self._is_standard_form_dae = None # Built on first read by pybamm.solvers.observation.ObserverCache self._observer_cache = None + self._rust_lowering = None self._geometry = pybamm.Geometry({}) self._symbol_processor = SymbolProcessor() self._solution_observable = ModelSolutionObservability.ENABLED @@ -287,14 +288,21 @@ def name(self): def name(self, value): self._name = value + def __getstate__(self) -> dict: + state = self.__dict__.copy() + # A copy or unpickled model lowers to a graph of its own on first use + state["_rust_lowering"] = None + return state + def __setstate__(self, state: dict) -> None: # Pickles from before convert_to_format was a property hold it under the # public name, which the property shadows; copy rather than mutate state. if "convert_to_format" in state: state = dict(state) state["_convert_to_format"] = state.pop("convert_to_format") - # Older pickles carry no observer cache + # Older pickles carry no observer cache or Rust lowering self._observer_cache = None + self._rust_lowering = None self.__dict__.update(state) @property diff --git a/packages/pybamm/src/pybamm/rust/__init__.py b/packages/pybamm/src/pybamm/rust/__init__.py index ec3f957d85..c81bbf1770 100644 --- a/packages/pybamm/src/pybamm/rust/__init__.py +++ b/packages/pybamm/src/pybamm/rust/__init__.py @@ -5,6 +5,7 @@ from pybamm.rust._core import ( CompiledFunction, CompiledJacobian, + CompiledModel, Expr, ExprGraph, ) @@ -12,6 +13,7 @@ __all__ = [ "CompiledFunction", "CompiledJacobian", + "CompiledModel", "Expr", "ExprGraph", ] diff --git a/packages/pybamm/src/pybamm/rust/_core.pyi b/packages/pybamm/src/pybamm/rust/_core.pyi index d860a9006c..41f68dc51d 100644 --- a/packages/pybamm/src/pybamm/rust/_core.pyi +++ b/packages/pybamm/src/pybamm/rust/_core.pyi @@ -2,15 +2,17 @@ from collections.abc import Callable, Mapping, Sequence from os import PathLike -from typing import Literal, TypeAlias, final +from typing import Literal, TypeAlias, TypedDict, final import numpy as np import numpy.typing as npt from scipy.sparse import csc_matrix +from typing_extensions import CapsuleType __all__ = [ "CompiledFunction", "CompiledJacobian", + "CompiledModel", "Expr", "ExprGraph", ] @@ -32,6 +34,24 @@ _TimeGrid: TypeAlias = ( Sequence[float] | npt.NDArray[np.floating] | npt.NDArray[np.integer] ) +class _JacobianStats(TypedDict): + """Assembly stats returned by :meth:`CompiledModel.jacobian_stats`.""" + + n_colors: int + nnz: int + n_dense_rows: int + n_dense_row_candidates: int + n_constant_entries: int + n_swept_columns: int + jac_lane_width: int + dense_row_entries: int + dense_row_tape_instructions: int + split_eval_primal_instructions: int + split_eval_total_instructions: int + split_eval_raw_instructions: int + split_eval_dispatch_count: int + branch_block_lens: tuple[int, ...] + @final class ExprGraph: """Arena of expression nodes; the build surface for every compiled artifact.""" @@ -356,3 +376,155 @@ class CompiledJacobian: def n_dense_rows(self) -> int: ... @property def wrt(self) -> Literal["y", "p"]: ... + +@final +class CompiledModel: + """Compiled DAE bundle: residual/jacobian FFI surface plus shareable views.""" + + @staticmethod + def from_expr( + graph: ExprGraph, + expr: Expr, + mass_data: _FloatArray, + mass_indptr: npt.NDArray[np.int64], + mass_indices: npt.NDArray[np.int64], + sens_param_indices: Sequence[int] = ..., + output_exprs: Sequence[Expr] = ..., + algebraic_expr: Expr | None = None, + algebraic_variable_indices: Sequence[int] = ..., + event_exprs: Sequence[Expr] = ..., + upsampling_expr: Expr | None = None, + ) -> CompiledModel: + """Build from an rhs expression and a CSR mass matrix.""" + + @staticmethod + def _rebuild( + graph: ExprGraph, + rhs_root: int, + output_roots: Sequence[int], + event_roots: Sequence[int], + upsampling_root: int | None, + algebraic_root: int | None, + algebraic_variable_indices: Sequence[int], + mass: tuple[Sequence[float], Sequence[int], Sequence[int]], + n_nodes: int, + sens_param_indices: Sequence[int], + ) -> CompiledModel: + """Rebuild from the first ``n_nodes`` nodes of ``graph``, the graph as compiled. + + ``mass`` is the mass matrix's CSR ``(data, indptr, indices)``. + """ + + def __reduce__( + self, + ) -> tuple[ + Callable[..., CompiledModel], + tuple[ + ExprGraph, + int, + list[int], + list[int], + int | None, + int | None, + list[int], + tuple[list[float], list[int], list[int]], + int, + list[int], + ], + ]: ... + @property + def rhs(self) -> CompiledFunction: + """Primal ``f(t, y, p)`` as a shareable view.""" + + @property + def jacobian(self) -> CompiledJacobian: + """Pure ``df/dy`` (``cj = 0``, no mass), composed over the bundle's tapes.""" + + @property + def outputs(self) -> list[CompiledFunction]: ... + @property + def events(self) -> list[CompiledFunction]: ... + @property + def upsampling(self) -> CompiledFunction | None: + """The upsampling output as a shareable view, or ``None`` without one.""" + + @property + def algebraic_residual(self) -> CompiledFunction | None: + """``g(t, y, p)`` as a shareable view, or ``None`` for ODEs.""" + + @property + def algebraic_jacobian(self) -> CompiledJacobian | None: + """``dg/dy_alg`` (``n_algebraic`` square), or ``None`` for ODEs.""" + + def eval_residual( + self, + t: float, + y: _FloatArray, + yp: _FloatArray, + inputs: _FloatArray, + ) -> _FloatArray: + """DAE residual ``r = M @ yp - f(t, y)`` as a new array (packed inputs only).""" + + def eval_residual_into( + self, + t: float, + y: _FloatArray, + yp: _FloatArray, + inputs: _FloatArray, + output: _FloatArray, + ) -> None: + """DAE residual into pre-allocated ``output`` (length at least ``n_states``).""" + + def assemble_jacobian_csc_into( + self, + t: float, + y: _FloatArray, + cj: float, + inputs: _FloatArray, + jac_data: _FloatArray, + ) -> None: + """Assemble ``df/dy - cj * M`` into a pre-allocated CSC data buffer.""" + + def algebraic_ids(self) -> _FloatArray: + """IDA-convention ids: ``1.0`` differential, ``0.0`` algebraic, per state.""" + + def sparsity_pattern( + self, + ) -> tuple[npt.NDArray[np.uintp], npt.NDArray[np.uintp]]: + """CSR ``(indptr, indices)`` of ``df/dy`` merged with the mass pattern.""" + + def csc_sparsity_pattern( + self, + ) -> tuple[npt.NDArray[np.uintp], npt.NDArray[np.uintp]]: + """CSC ``(colptr, rowind)`` for KLU compatibility.""" + + def jacobian_stats(self) -> _JacobianStats: ... + def evaluator(self) -> CapsuleType: + """A new evaluator for one solver, in a capsule the solver claims and then owns.""" + + @property + def n_states(self) -> int: ... + @property + def n_inputs(self) -> int: + """Packed input width.""" + + @property + def n_algebraic(self) -> int: ... + @property + def n_sens_params(self) -> int: ... + @property + def n_outputs(self) -> int: ... + @property + def n_events(self) -> int: ... + @property + def events_read_y_dot(self) -> list[bool]: + """Whether each event reads ``y_dot``, in event order.""" + + @property + def upsampling_len(self) -> int: ... + @property + def output_len(self) -> int: ... + @property + def n_colors(self) -> int: ... + @property + def nnz(self) -> int: ... diff --git a/packages/pybamm/src/pybamm/simulation/eis_simulation.py b/packages/pybamm/src/pybamm/simulation/eis_simulation.py index a00b814562..20d134d26f 100644 --- a/packages/pybamm/src/pybamm/simulation/eis_simulation.py +++ b/packages/pybamm/src/pybamm/simulation/eis_simulation.py @@ -5,6 +5,7 @@ import pybamm from pybamm.solvers.base_solver import stack_inputs +from pybamm.solvers.rust_lowering import RustModelLowering from .base_simulation import BaseSimulation @@ -207,13 +208,23 @@ def _build_matrix_problem(self, inputs_dict=None): solver.set_up(model, inputs=inputs_dict) y0 = model.concatenated_initial_conditions.evaluate(0, inputs=inputs_dict) - from casadi import MX, Function, jacobian - - y = MX.sym("y", y0.size) - output_expression = outputs.to_casadi(t=0, y=y, inputs=inputs_dict) - self._output_jacobian = Function( - "eis_outputs", [y], [jacobian(output_expression, y)] - )(y0).sparse() + if model.convert_to_format == "rust": + lowering = RustModelLowering.of(model, inputs_dict) + output_function = lowering.cached( + ("eis outputs", outputs.id), + lambda: lowering.function(outputs, "eis_outputs"), + ) + self._output_jacobian = output_function.jacobian("y")( + 0.0, np.ravel(y0), eval_inputs + ) + else: + from casadi import MX, Function, jacobian + + y = MX.sym("y", y0.size) + output_expression = outputs.to_casadi(t=0, y=y, inputs=inputs_dict) + self._output_jacobian = Function( + "eis_outputs", [y], [jacobian(output_expression, y)] + )(y0).sparse() J = model.jac_rhs_algebraic_eval(0, y0, eval_inputs) if model.convert_to_format == "casadi": J = J.sparse() diff --git a/packages/pybamm/src/pybamm/solvers/base_solver.py b/packages/pybamm/src/pybamm/solvers/base_solver.py index de58e6f4f9..f3a2d050bd 100644 --- a/packages/pybamm/src/pybamm/solvers/base_solver.py +++ b/packages/pybamm/src/pybamm/solvers/base_solver.py @@ -7,7 +7,7 @@ import platform import re import warnings -from typing import cast +from typing import TYPE_CHECKING, cast import casadi import numpy as np @@ -19,7 +19,10 @@ from pybamm.expression_tree.binary_operators import _Heaviside from pybamm.expression_tree.input_parameter import DUMMY_INPUT_PARAMETER_VALUE from pybamm.models.base_model import ModelSolutionObservability -from pybamm.solvers.rust_lowering import rust_input_parameter_widths +from pybamm.solvers.rust_lowering import RustModelLowering, rust_input_parameter_widths + +if TYPE_CHECKING: + from pybamm.rust import CompiledModel # CasADi function names allow only letters, digits and single underscores _NOT_IDENTIFIER_CHARS = re.compile(r"[^a-z0-9]+") @@ -183,10 +186,11 @@ def on_failure(self, value): raise ValueError("on_failure must be 'warn', 'error', or 'ignore'") self._on_failure = value - # Keep root solver's failure policy in sync with the parent's - root_method = getattr(self, "_root_method", None) - if isinstance(root_method, pybamm.BaseSolver): - root_method.on_failure = value + # Keep root solvers' failure policy in sync with the parent's + for attribute in ("_root_method", "_rust_root_method"): + root_method = getattr(self, attribute, None) + if isinstance(root_method, pybamm.BaseSolver): + root_method.on_failure = value @property def root_method(self): @@ -195,12 +199,7 @@ def root_method(self): @root_method.setter def root_method(self, method): if method == "nonlinear_solver": - # use the tighter of the two tolerances; a per-state atol contributes - # its tightest entry, since the root solver takes a single tolerance - atol = min(self.root_tol, float(np.min(self.atol))) - method = pybamm.NonlinearSolver( - atol=atol, rtol=self.rtol, on_failure=self.on_failure - ) + method = self._nonlinear_root_solver() elif method == "casadi": warnings.warn( "root_method='casadi' is deprecated and will be removed in a future " @@ -224,6 +223,40 @@ def root_method(self, method): ): raise pybamm.SolverError("Root method must be an algebraic solver") self._root_method = method + self._rust_root_method = None + + def _nonlinear_root_solver(self): + """Build the root method that ``"nonlinear_solver"`` selects.""" + # use the tighter of the two tolerances; a per-state atol contributes + # its tightest entry, since the root solver takes a single tolerance + atol = min(self.root_tol, float(np.min(self.atol))) + return pybamm.NonlinearSolver( + atol=atol, rtol=self.rtol, on_failure=self.on_failure + ) + + def _root_method_for(self, model: pybamm.BaseModel): + """Return the root method that finds consistent states for ``model``. + + A CasADi root method cannot evaluate a rust model, which gets a + ``NonlinearSolver`` instead, kept until ``root_method`` is set again. + + Parameters + ---------- + model : :class:`pybamm.BaseModel` + The model whose consistent states are needed. + + Returns + ------- + :class:`pybamm.BaseSolver` or None + The algebraic solver, or None if there is no root method. + """ + if model.convert_to_format != "rust" or not isinstance( + self.root_method, pybamm.CasadiAlgebraicSolver + ): + return self.root_method + if getattr(self, "_rust_root_method", None) is None: + self._rust_root_method = self._nonlinear_root_solver() + return self._rust_root_method def copy(self): """Returns a copy of the solver""" @@ -232,63 +265,108 @@ def copy(self): new_solver._model_set_up = {} return new_solver - def set_up( - self, - model: pybamm.BaseModel, - inputs: dict | list[dict] | None = None, - t_eval=None, - ics_only=False, - ): - """Unpack model, perform checks, and calculate jacobian. + def _upsampling_variable(self, model) -> tuple[str, pybamm.Symbol] | None: + """The name and expression of the variable to upsample, or None for none.""" + return None + + def _set_up_rust_model( + self, model: pybamm.BaseModel, lowering: RustModelLowering + ) -> None: + """Compile the model's ``CompiledModel`` and bind its evaluators to it. Parameters ---------- model : :class:`pybamm.BaseModel` - The model whose solution to calculate. Must have attributes rhs and - initial_conditions - inputs : dict or list of dict, optional - Any input parameters to pass to the model when solving - t_eval : numeric type, optional - Not used, kept for backwards compatibility. - """ - if isinstance(inputs, dict): - inputs = [inputs] - inputs = inputs or [{}] + The discretised model, with ``convert_to_format='rust'``. + lowering : :class:`pybamm.solvers.rust_lowering.RustModelLowering` + The model's lowering. - if ics_only: - pybamm.logger.info("Start solver set-up, initial_conditions only") - else: - pybamm.logger.info("Start solver set-up") + Raises + ------ + :class:`pybamm.SolverError` + If a sensitivity input is a vector. + """ + if model.calculate_sensitivities: + validate_rust_sensitivity_widths(model, model.calculate_sensitivities) + compiled = lowering.compile_model( + sensitivities=model.calculate_sensitivities, + output_variables=self.output_variables, + time_integral_vars=self._time_integral_vars, + upsampling=self._upsampling_variable(model), + allow_y_dot_events=self.supports_state_derivative_events, + ) + self._bind_rust_evaluators(model, compiled) - self._check_and_prepare_model_inplace(model) + def _bind_rust_evaluators( + self, model: pybamm.BaseModel, compiled: CompiledModel + ) -> None: + """Set the model's generic ``*_eval`` functions to views of ``compiled``. - # set default calculate sensitivities on model - if not hasattr(model, "calculate_sensitivities"): - model.calculate_sensitivities = [] + The right-hand side is the residual's first ``len_rhs`` rows, and its + Jacobian is served only to a solver that uses it. - self._set_up_model_sensitivities_inplace(model) + Parameters + ---------- + model : :class:`pybamm.BaseModel` + The discretised model. + compiled : :class:`pybamm.rust.CompiledModel` + The model's ``CompiledModel``. + """ + from pybamm.solvers.rust_evaluator import RustEvaluator - vars_for_processing = self._get_vars_for_processing(model, inputs[0]) + residual, jacobian = compiled.rhs, compiled.jacobian + use_jacobian = model.use_jacobian + # An ODE's residual is its right-hand side, so needs no row selection + rows = None if model.len_alg == 0 else slice(0, model.len_rhs) + algebraic = compiled.algebraic_residual - # Process initial conditions - initial_conditions, _, jacp_ic, _ = process( - model.concatenated_initial_conditions, - "initial_conditions", - vars_for_processing, - use_jacobian=False, + model.rhs_eval = RustEvaluator(residual, "func", rows=rows) + model.algebraic_eval = ( + None if algebraic is None else RustEvaluator(algebraic, "func") ) - model.initial_conditions_eval = initial_conditions - model.jacp_initial_conditions_eval = jacp_ic - - # set initial conditions - self._set_initial_conditions(model, 0.0, inputs) + model.rhs_algebraic_eval = RustEvaluator(residual, "func") + model.terminate_events_eval = [ + RustEvaluator(event, "func") for event in compiled.events + ] + # Views, so a Jacobian is evaluated only when read + model.jac_rhs_eval = ( + RustEvaluator(residual, "jac", rows=rows, jacobian=jacobian) + if use_jacobian and self.uses_rhs_jacobian + else None + ) + model.jac_algebraic_eval = ( + RustEvaluator(algebraic, "jac") + if algebraic is not None and use_jacobian + else None + ) + model.jac_rhs_algebraic_eval = ( + RustEvaluator(residual, "jac", jacobian=jacobian) if use_jacobian else None + ) + # Nothing reads these for a Rust model: its solvers take the CompiledModel + model.jac_rhs_action_eval = model.jacp_rhs_eval = None + model.jac_algebraic_action_eval = model.jacp_algebraic_eval = None + model.jac_rhs_algebraic_action_eval = model.jacp_rhs_algebraic_eval = None - if ics_only: - pybamm.logger.info("Finish solver set-up") - return + def _set_up_part_evaluators( + self, + model: pybamm.BaseModel, + vars_for_processing: dict, + terminate_events: list, + casadi_switch_events: list, + ) -> None: + """Convert the right-hand side, the algebraic equations and their concatenation. - # Process rhs, algebraic, residual and event expressions - # and wrap in callables + Parameters + ---------- + model : :class:`pybamm.BaseModel` + The discretised model. + vars_for_processing : dict + The variables the conversion uses. + terminate_events : list + The converted termination events. + casadi_switch_events : list + The converted switch events of the CasADi solver's "fast with events". + """ rhs, jac_rhs, jacp_rhs, jac_rhs_action = process( model.concatenated_rhs, "RHS", @@ -317,25 +395,11 @@ def set_up( jac_rhs_algebraic_action, ) = process(rhs_algebraic, "rhs_algebraic", vars_for_processing) - ( - casadi_switch_events, - terminate_events, - interpolant_extrapolation_events, - t_discon_constant_symbols, - discontinuity_events, - discontinuity_periods, - ) = self._set_up_events(model, inputs, vars_for_processing) - - # Add the solver attributes model.rhs_eval = rhs model.algebraic_eval = algebraic model.rhs_algebraic_eval = rhs_algebraic model.terminate_events_eval = terminate_events - model.interpolant_extrapolation_events_eval = interpolant_extrapolation_events - model.discontinuity_events_eval = discontinuity_events - model.discontinuity_periods_eval = discontinuity_periods - model.t_discon_constant_symbols = t_discon_constant_symbols model.jac_rhs_eval = jac_rhs model.jac_rhs_action_eval = jac_rhs_action @@ -349,13 +413,17 @@ def set_up( model.jac_rhs_algebraic_action_eval = jac_rhs_algebraic_action model.jacp_rhs_algebraic_eval = jacp_rhs_algebraic - # Save CasADi functions for the CasADi solver - # Save CasADi functions for solvers that use CasADi - # Note: when we pass to casadi the ode part of the problem must be in - if isinstance(self.root_method, pybamm.CasadiAlgebraicSolver) or isinstance( + # The functions the CasADi solvers and CasADi root method read + if isinstance( + self._root_method_for(model), pybamm.CasadiAlgebraicSolver + ) or isinstance( self, pybamm.CasadiSolver | pybamm.CasadiAlgebraicSolver, ): + rhs, algebraic = ( + cast(casadi.Function, rhs), + cast(casadi.Function, algebraic), + ) # can use DAE solver to solve model with algebraic equations only if len(model.rhs) > 0: t_casadi = vars_for_processing["t_casadi"] @@ -378,27 +446,113 @@ def set_up( model.casadi_sensitivities_rhs = jacp_rhs model.casadi_sensitivities_algebraic = jacp_algebraic - # if output_variables specified then convert functions to casadi - # expressions for evaluation within the respective solver - self.computed_var_fcns = {} - self.computed_dvar_dy_fcns = {} - self.computed_dvar_dp_fcns = {} + def set_up( + self, + model: pybamm.BaseModel, + inputs: dict | list[dict] | None = None, + t_eval=None, + ics_only=False, + ): + """Unpack model, perform checks, and calculate jacobian. + + Parameters + ---------- + model : :class:`pybamm.BaseModel` + The model whose solution to calculate. Must have attributes rhs and + initial_conditions + inputs : dict or list of dict, optional + Any input parameters to pass to the model when solving + t_eval : numeric type, optional + Not used, kept for backwards compatibility. + """ + if isinstance(inputs, dict): + inputs = [inputs] + inputs = inputs or [{}] + + if ics_only: + pybamm.logger.info("Start solver set-up, initial_conditions only") + else: + pybamm.logger.info("Start solver set-up") + + self._check_and_prepare_model_inplace(model) + + # set default calculate sensitivities on model + if not hasattr(model, "calculate_sensitivities"): + model.calculate_sensitivities = [] + + self._set_up_model_sensitivities_inplace(model) + + vars_for_processing = self._get_vars_for_processing(model, inputs[0]) + initial_vars = vars_for_processing + if model.convert_to_format == "rust": + # Initial conditions are replaced between solves; a graph per set-up + # keeps the model's graph from growing with each one + initial_vars = { + **vars_for_processing, + "lowering": RustModelLowering(model, inputs[0]), + } + + initial_conditions, _, jacp_ic, _ = process( + model.concatenated_initial_conditions, + "initial_conditions", + initial_vars, + use_jacobian=False, + ) + model.initial_conditions_eval = initial_conditions + model.jacp_initial_conditions_eval = jacp_ic + + self._set_initial_conditions(model, 0.0, inputs) + + if ics_only: + pybamm.logger.info("Finish solver set-up") + return + + # Check for any ExplicitTimeIntegral or DiscreteTimeSum output variables, + # whose sum node is evaluated in the solver and summed afterwards self._time_integral_vars = {} - function_names = BaseSolver._wrangle_names(self.output_variables) for key in self.output_variables: - # Check for any ExplicitTimeIntegral or DiscreteTimeSum variables processed_time_integral = ( pybamm.ProcessedVariableTimeIntegral.from_pybamm_var( model.get_processed_variable_or_event(key), model.len_rhs_and_alg, ) ) - # We will evaluate the sum node in the solver and sum it afterwards + if processed_time_integral is not None: + self._time_integral_vars[key] = processed_time_integral + + ( + casadi_switch_events, + terminate_events, + interpolant_extrapolation_events, + t_discon_constant_symbols, + discontinuity_events, + discontinuity_periods, + ) = self._set_up_events(model, inputs, vars_for_processing) + model.interpolant_extrapolation_events_eval = interpolant_extrapolation_events + model.discontinuity_events_eval = discontinuity_events + model.discontinuity_periods_eval = discontinuity_periods + model.t_discon_constant_symbols = t_discon_constant_symbols + + self.computed_var_fcns = {} + self.computed_dvar_dy_fcns = {} + self.computed_dvar_dp_fcns = {} + if model.convert_to_format == "rust": + # Its output variables are compiled into the CompiledModel + self._set_up_rust_model(model, vars_for_processing["lowering"]) + pybamm.logger.info("Finish solver set-up") + return + + self._set_up_part_evaluators( + model, vars_for_processing, terminate_events, casadi_switch_events + ) + # Convert any output variables for evaluation within the solver + function_names = BaseSolver._wrangle_names(self.output_variables) + for key in self.output_variables: + processed_time_integral = self._time_integral_vars.get(key) if processed_time_integral is None: var = model.get_processed_variable_or_event(key) else: var = processed_time_integral.sum_node - self._time_integral_vars[key] = processed_time_integral # Generate Casadi function to calculate variable and derivates # to enable sensitivites to be computed within the solver @@ -550,14 +704,17 @@ def _check_and_prepare_model_inplace(self, model): f"Converting {model.name} to CasADi for solving with CasADi solver" ) model.convert_to_format = "casadi" - if ( - isinstance(self.root_method, pybamm.CasadiAlgebraicSolver) - and model.convert_to_format != "casadi" - ): - pybamm.logger.warning( - f"Converting {model.name} to CasADi for calculating ICs with CasADi" - ) - model.convert_to_format = "casadi" + if isinstance(self.root_method, pybamm.CasadiAlgebraicSolver): + if model.convert_to_format == "rust": + pybamm.logger.warning( + f"Calculating ICs of rust model {model.name} with NonlinearSolver " + "instead of the CasADi root method" + ) + elif model.convert_to_format != "casadi": + pybamm.logger.warning( + f"Converting {model.name} to CasADi for calculating ICs with CasADi" + ) + model.convert_to_format = "casadi" @staticmethod def _get_vars_for_processing(model, inputs: dict): @@ -566,7 +723,7 @@ def _get_vars_for_processing(model, inputs: dict): } if model.convert_to_format == "rust": - vars_for_processing.update({"input_names": list(inputs.keys())}) + vars_for_processing["lowering"] = RustModelLowering.of(model, inputs) return vars_for_processing elif model.convert_to_format != "casadi": @@ -686,6 +843,7 @@ def add_discontinuity_event(name, expression): terminate_events = [] interpolant_extrapolation_events = [] discontinuity_events = [] + skip_event_lowering = model.convert_to_format == "rust" for n, event in enumerate(model.events): if event.event_type == pybamm.EventType.DISCONTINUITY: # Evaluated before the solver is called, for each input set @@ -726,6 +884,10 @@ def add_discontinuity_event(name, expression): )[0] # use the actual casadi object as this will go into the rhs casadi_switch_events.append(event_casadi) + elif skip_event_lowering: + # Termination events are the CompiledModel's; nothing reads + # extrapolation events + continue elif event.event_type == pybamm.EventType.TERMINATION: terminate_events.append( process( @@ -837,10 +999,11 @@ def calculate_consistent_state( pybamm.logger.debug("Start calculating consistent states") inputs = inputs or [{}] - if self.root_method is None: + root_method = self._root_method_for(model) + if root_method is None: return model.y0_list try: - root_sols = self.root_method._integrate(model, np.array([time]), inputs) + root_sols = root_method._integrate(model, np.array([time]), inputs) except pybamm.SolverError as e: raise pybamm.SolverError( f"Could not find consistent states: {e.args[0]}" @@ -2535,8 +2698,8 @@ def process( returns Jacobian function wrt the stacked sensitivity parameters instead of jacp use_state_derivatives: bool, optional - whether the CasADi or Rust functions take the state derivatives, `y_dot`, - as a fourth input. Default is False + whether the CasADi functions take the state derivatives, `y_dot`, as a + fourth input; a Rust model refuses it. Default is False Returns ------- @@ -2599,49 +2762,39 @@ def report(string): elif model.convert_to_format == "rust": from pybamm.solvers.rust_evaluator import RustEvaluator - from pybamm.solvers.rust_lowering import reject_y_dot, rust_graph_with_inputs + if use_state_derivatives: + raise pybamm.SolverError( + f"'{name}' cannot read y_dot on a Rust model, whose termination " + "events alone do, in its CompiledModel" + ) if return_jacp_stacked and model.calculate_sensitivities: raise pybamm.SolverError( "return_jacp_stacked is not supported for convert_to_format='rust'. " "Use the per-parameter tuple returned by jacp instead." ) - report(f"Converting {name} to Rust") - input_names = vars_for_processing["input_names"] - - graph = rust_graph_with_inputs(model, input_names) - rust_expr = symbol.to_rust(graph, {}) - - # Full system width, so rectangular sub-groups differentiate wrt all states - cf = graph.compile(rust_expr, name=name, n_states=model.len_rhs_and_alg) - if not use_state_derivatives: - reject_y_dot(cf) + lowering = vars_for_processing["lowering"] + cf = lowering.function(symbol, name) func = RustEvaluator(cf, "func") - + # Derived from the function on its first call + jac = RustEvaluator(cf, "jac") if use_jacobian else None + jac_action = None if model.calculate_sensitivities: report( f"Calculating sensitivities for {name} with respect " f"to parameters {model.calculate_sensitivities} using Rust" ) - # The graph's registry numbers the parameters; `input_names` only filters - sens_indices = [] - for p in model.calculate_sensitivities: - index = graph.input_index(p) - if index is not None and p in input_names: - sens_indices.append(index) - jacp = RustEvaluator(cf, "jacp", sens_indices=sens_indices) + jacp = RustEvaluator( + cf, + "jacp", + sens_indices=lowering.sensitivity_indices( + model.calculate_sensitivities + ), + ) else: jacp = None - if use_jacobian: - report(f"Calculating jacobian for {name} using Rust") - jac = RustEvaluator(cf, "jac") - jac_action = RustEvaluator(cf, "jac_action") - else: - jac = None - jac_action = None - elif model.convert_to_format != "casadi": y = vars_for_processing["y"] jacobian = vars_for_processing["jacobian"] diff --git a/packages/pybamm/src/pybamm/solvers/idaklu_solver.py b/packages/pybamm/src/pybamm/solvers/idaklu_solver.py index ff73cca3bb..94beab12fb 100644 --- a/packages/pybamm/src/pybamm/solvers/idaklu_solver.py +++ b/packages/pybamm/src/pybamm/solvers/idaklu_solver.py @@ -15,6 +15,7 @@ from pybamm.expression_tree.array import to_casadi_dm from pybamm.solvers.base_solver import flatten_inputs, process, stack_inputs from pybamm.solvers.observation import OutputAssembly +from pybamm.solvers.rust_lowering import RustModelLowering _UNSET = object() @@ -322,7 +323,7 @@ class IDAKLUSolver(pybamm.BaseSolver): "t_no_progress": 0.0, } - Note: These options only have an effect if model.convert_to_format == 'casadi' + Note: Options apply to both 'casadi' and 'rust' formats except where noted. """ @@ -376,6 +377,28 @@ def __init__( pybamm.citations.register("Hindmarsh2000") pybamm.citations.register("Hindmarsh2005") + def _rust_options(self) -> dict: + """The solver options for the Rust backend. + + Returns + ------- + dict + A copy of the options, with ``num_solvers`` set to ``num_threads``. + """ + if self._options["compile"]: + pybamm.logger.warning( + "options['compile'] has no effect with convert_to_format='rust', " + "whose model is compiled by the Rust backend." + ) + # One thread per solver avoids OpenMP N_Vectors (slower, not reproducible) + num_threads = self._options["num_threads"] + if self._options.get("num_solvers", num_threads) != num_threads: + pybamm.logger.warning( + "The Rust backend runs one solver per thread; num_solvers is " + f"set to num_threads ({num_threads})." + ) + return {**self._options, "num_solvers": num_threads} + def _combine_options(self, user_options: dict | None) -> dict: user_options = user_options or {} num_solvers = user_options.get("num_threads", 1) @@ -527,13 +550,88 @@ def _check_atol_type( ) return np.ascontiguousarray(values.ravel(), dtype=np.float64) + def _check_and_prepare_model_inplace(self, model): + super()._check_and_prepare_model_inplace(model) + if not model.use_jacobian: + raise pybamm.SolverError("KLU requires the Jacobian") + # IDA needs a state to integrate; its C++ set-up would crash without one + if model.len_rhs_and_alg == 0: + raise pybamm.SolverError( + f"IDAKLUSolver cannot integrate '{model.name}', which has no states; " + "use pybamm.DummySolver" + ) + # Checked here, before set-up converts or compiles the model's equations + self._check_atol_type(getattr(model, "atol", self.atol), model) + + def _set_up_rust_integrator(self, model, compiled): + """Set up the IDA solver group over a Rust model's ``CompiledModel``. + + Parameters + ---------- + model : :class:`pybamm.BaseModel` + The discretised model, with ``convert_to_format='rust'``. + compiled : :class:`pybamm.rust.CompiledModel` + The model's ``CompiledModel``. + """ + options = self._rust_options() + sensitivity_names = list(model.calculate_sensitivities) + output_lens = [output.output_len for output in compiled.outputs] + + if self._options["hermite_reduction_factor"] > 1.0 and sensitivity_names: + warnings.warn( + "Setting hermite_reduction_factor > 1.0 is not currently supported " + "with sensitivities. The hermite_reduction_factor option will be " + "ignored.", + pybamm.SolverWarning, + stacklevel=2, + ) + + # One evaluator per parallel solver, all sharing the compiled model's tape + rust_evaluators = [compiled.evaluator() for _ in range(options["num_solvers"])] + # Each evaluator gives IDAKLU its own model's sizes, patterns and state ids + solver = idaklu.create_rust_solver_group( + rust_evaluators=rust_evaluators, + atol=self._check_atol_type(getattr(model, "atol", self.atol), model), + rtol=self.rtol, + options=options, + # The sub-block Newton IC needs a standard-form DAE + algebraic_subblock=( + self._options.get("newton_mode", "auto") == "auto" + and model.is_standard_form_dae + ), + ) + self._setup = { + "solver": solver, + "rust_model": compiled, + "rust_evaluators": rust_evaluators, + "sensitivity_names": sensitivity_names, + "number_of_sensitivity_parameters": compiled.n_sens_params, + "output_assembly": OutputAssembly.dense( + self.output_variables, + output_lens, + time_integrals=self._time_integral_vars, + ), + # Same keys as the CasADi setup, for `_post_process_solution` and `spy` + "num_of_events": compiled.n_events, + "events_read_yp": compiled.events_read_y_dot, + "upsampling": compiled.upsampling_len > 0, + "ids": np.asarray(compiled.algebraic_ids(), dtype=np.float64), + } + def set_up(self, model, inputs=None, t_eval=None, ics_only=False): - if model.convert_to_format != "casadi": + if model.convert_to_format not in ("casadi", "rust"): pybamm.logger.warning( f"Converting {model.name} to CasADi for solving with IDAKLUSolver" ) model.convert_to_format = "casadi" base_set_up_return = super().set_up(model, inputs, t_eval, ics_only) + if ics_only: + return base_set_up_return + if model.convert_to_format == "rust": + # The base set-up compiled the model and bound its evaluators + compiled = RustModelLowering.current(model).compiled + self._set_up_rust_integrator(model, compiled) + return base_set_up_return if isinstance(inputs, list): # for setup, just use first input dict @@ -553,25 +651,12 @@ def set_up(self, model, inputs=None, t_eval=None, ics_only=False): y0 = y0.full() y0 = y0.flatten() - if ics_only: - return base_set_up_return - - if model.convert_to_format != "casadi": - msg = "The python-idaklu solver has been deprecated." - warnings.warn(msg, DeprecationWarning, stacklevel=2) - raise pybamm.SolverError( - f"Unsupported option for convert_to_format={model.convert_to_format}" - ) - mass_matrix = model.mass_matrix.entries # construct residuals function by binding inputs # TODO: do we need densify here? rhs_algebraic = model.rhs_algebraic_eval - if not model.use_jacobian: - raise pybamm.SolverError("KLU requires the Jacobian") - # need to provide jacobian_rhs_alg - cj * mass_matrix t_casadi = casadi.MX.sym("t") y_casadi = casadi.MX.sym("y", model.len_rhs_and_alg) @@ -830,32 +915,41 @@ def set_up(self, model, inputs=None, t_eval=None, ics_only=False): return base_set_up_return - def _upsampling_fcn(self, model, inputs_dict): - """``g(t, y, p)``: the model's scalar ``upsampling_variable`` divided - by its scale, or by 1 if it has none. + def _upsampling_variable(self, model) -> tuple[str, pybamm.Symbol] | None: + """The name of the model's ``upsampling_variable`` and ``g(t, y, p)``, + that variable divided by its scale, or by 1 if it has none. - Empty if upsampling is off, or the variable is missing or an algebraic + None if upsampling is off, or the variable is missing or an algebraic state, which the integrator's error test already resolves. """ - empty = casadi.Function("empty_upsampling", [], []) name = getattr(model, "upsampling_variable", "Voltage [V]") if self._options["upsampling_tolerance"] is None: - return empty + return None if name not in model.variables: pybamm.logger.warning( f"upsampling_tolerance is set but model '{model.name}' has no " f"'{name}' variable, so no points are added. Set the model's " "`upsampling_variable` to the name of a scalar variable." ) - return empty + return None variable = model.variables[name] if model.is_algebraic_state(variable): - return empty + return None scale = getattr(variable, "scale", None) if not (isinstance(scale, pybamm.Symbol) and scale.is_constant()): scale = 1 + return name, model.get_processed_variable_or_event(name) / scale + + def _upsampling_fcn(self, model, inputs_dict): + """``g(t, y, p)`` from :meth:`_upsampling_variable` as a CasADi function, + empty without one. + """ + upsampling = self._upsampling_variable(model) + if upsampling is None: + return casadi.Function("empty_upsampling", [], []) + name, symbol = upsampling upsampling_fcn = process( - model.get_processed_variable_or_event(name) / scale, + symbol, pybamm.BaseSolver._wrangle_name(name), self._get_vars_for_processing(model, inputs_dict), use_jacobian=False, @@ -899,7 +993,7 @@ def _integrate( """ Overloads the _integrate method from BaseSolver to use the IDAKLU solver """ - if model.convert_to_format != "casadi": # pragma: no cover + if model.convert_to_format not in ("casadi", "rust"): # pragma: no cover raise pybamm.SolverError("Unsupported IDAKLU solver configuration.") inputs_list = inputs_list or [{}] @@ -973,6 +1067,24 @@ def _check_event_violation_on_initialisation(self, *args, **kwargs): # The solver checks events at t0 itself, after its consistent initialisation return + def _termination_event_values(self, model, sol, y_event, inputs_dict): + """The termination events at the time, state and yp a solve stopped at.""" + t_event = float(sol.t[-1]) + y_event = np.asarray(y_event).reshape(-1) + if model.convert_to_format == "rust": + inputs = stack_inputs(inputs_dict, "rust") + # The solve's own event tapes, as rootfn_casadi is for CasADi + return np.array( + [ + event(t_event, y_event, inputs, sol.yp_term).item() + for event in self._setup["rust_model"].events + ] + ) + rootfn = self._setup["rootfn_casadi"] + return np.asarray( + rootfn(t_event, y_event, flatten_inputs(inputs_dict), sol.yp_term) + ).reshape(-1) + def _post_process_solution(self, sol, model, integration_time, inputs_dict, t_eval): number_of_sensitivity_parameters = self._setup[ "number_of_sensitivity_parameters" @@ -991,15 +1103,9 @@ def _post_process_solution(self, sol, model, integration_time, inputs_dict, t_ev event_values = None if sol.flag == _IDA_ROOT_RETURN and self._setup["num_of_events"] > 0: - rootfn = self._setup["rootfn_casadi"] - event_values = np.asarray( - rootfn( - float(sol.t[-1]), - np.asarray(y_event).reshape(-1), - flatten_inputs(inputs_dict), - sol.yp_term, - ) - ).reshape(-1) + event_values = self._termination_event_values( + model, sol, y_event, inputs_dict + ) # One step and an event: it was triggered at t0. The solver checks the # events not reading yp first, before its first step gives yp if number_of_timesteps == 1 and event_values is not None: @@ -1239,10 +1345,10 @@ def _sensitivity_consistent_initialization(self, y0, ydot0, y0S, time, inputs_di """ - if isinstance(y0S, casadi.DM): + if isinstance(y0S, casadi.DM | np.ndarray): y0S = (y0S,) - if isinstance(y0S[0], casadi.DM): + if y0S and isinstance(y0S[0], casadi.DM): y0S = (x.full() for x in y0S) y0S = [x.flatten() for x in y0S] @@ -1431,10 +1537,16 @@ def get_jacobian_sparsity(self) -> csc_matrix: setup = getattr(self, "_setup", None) if setup is None: raise pybamm.SolverError("Solver not set up. Call set_up() first.") - indptr = setup["jac_times_cjmass_colptrs"] - indices = setup["jac_times_cjmass_rowvals"] - nnz = setup["jac_times_cjmass_nnz"] - n = setup["number_of_states"] + if "rust_model" in setup: + rust_model = setup["rust_model"] + indptr, indices = rust_model.csc_sparsity_pattern() + nnz = rust_model.nnz + n = rust_model.n_states + else: + indptr = setup["jac_times_cjmass_colptrs"] + indices = setup["jac_times_cjmass_rowvals"] + nnz = setup["jac_times_cjmass_nnz"] + n = setup["number_of_states"] data = np.ones(nnz) return csc_matrix((data, indices, indptr), shape=(n, n)) diff --git a/packages/pybamm/src/pybamm/solvers/nonlinear_solver.py b/packages/pybamm/src/pybamm/solvers/nonlinear_solver.py index 18f5b0ccb2..e398eb740b 100644 --- a/packages/pybamm/src/pybamm/solvers/nonlinear_solver.py +++ b/packages/pybamm/src/pybamm/solvers/nonlinear_solver.py @@ -12,6 +12,7 @@ _check_klu_pivot_tolerance, casadi_to_idaklu_function, ) +from pybamm.solvers.rust_lowering import RustModelLowering _DEFAULT_OPTIONS = { "compile": False, @@ -20,24 +21,60 @@ class _NonlinearSolverSetup: - """Pickle-safe wrapper around StandaloneNewtonSolver""" + """Pickle-safe wrapper around StandaloneNewtonSolver. - __slots__ = ["_setup"] + Parameters + ---------- + setup : idaklu.StandaloneNewtonSolver + The C++ solver. + n_alg : int + Number of algebraic variables the solver was built for. + n_params : int + Length of the stacked ``[y_diff; inputs]`` vector its functions read. + """ + + __slots__ = ["_n_alg", "_n_params", "_setup"] - def __init__(self, setup: idaklu.StandaloneNewtonSolver): + def __init__( + self, + setup: idaklu.StandaloneNewtonSolver, + n_alg: int, + n_params: int, + ): self._setup = setup + self._n_alg = n_alg + self._n_params = n_params def __bool__(self): + # Falsy after unpickling, so the caller rebuilds instead of using a dangling ptr return self._setup is not None def __getstate__(self): - return {"_setup": None} + return dict.fromkeys(self.__slots__) def __setstate__(self, state): - self._setup = None + for name in self.__slots__: + setattr(self, name, None) - def solve_batch(self, *args, **kwargs): - return self._setup.solve_batch(*args, **kwargs) + def solve_batch(self, t_eval, y0_alg, p_vec, logger=None): + """Solve at each of ``t_eval``, after checking the buffer lengths C++ reads. + + Raises + ------ + pybamm.SolverError + If ``y0_alg`` or ``p_vec`` differs in length from the set-up sizes. + """ + # C++ reads these at the set-up sizes, so a short buffer would be overrun + for name, array, expected in ( + ("y0_alg", y0_alg, self._n_alg), + ("[y_diff; inputs]", p_vec, self._n_params), + ): + if array.size != expected: + raise pybamm.SolverError( + f"The Newton solver was set up for a {name} of length {expected} " + f"but got {array.size}; the inputs must keep their set-up widths" + ) + return self._setup.solve_batch(t_eval, y0_alg, p_vec, logger=logger) class NonlinearSolver(pybamm.BaseSolver): @@ -106,6 +143,16 @@ def __init__( ) _check_klu_pivot_tolerance(self._options["klu_pivot_tolerance"]) + def __getstate__(self): + # Rust artifacts in _model_set_up are unpicklable; solve() rebuilds them + state = self.__dict__.copy() + state["_model_set_up"] = {} + return state + + def __setstate__(self, state): + self.__dict__.update(state) + self._model_set_up = {} + @staticmethod def _check_tolerance(value): if value < 0: @@ -147,6 +194,9 @@ def _set_up_root_solver(self, model, inputs_dict, t_eval): experiment (e.g. each unique step model) get independently sized Newton solvers without one stomping on another's cache. """ + if model.convert_to_format == "rust": + return self._set_up_root_solver_rust(model, inputs_dict) + pybamm.logger.info(f"Start building {self.name}") y0 = model.y0_list[0] @@ -188,9 +238,57 @@ def _set_up_root_solver(self, model, inputs_dict, t_eval): if self._options["compile"]: res_fn, jac_fn = aot_compile([res_fn, jac_fn]) - return self._build_newton_solver(res_fn, jac_fn, len_alg) + return self._build_newton_solver(res_fn, jac_fn, len_alg, len_rhs + inputs_len) + + def _set_up_root_solver_rust(self, model, inputs_dict): + """Build the Rust-backed standalone Newton solver.""" + pybamm.logger.info(f"Start building {self.name} (rust)") + if self._options["compile"]: + raise pybamm.SolverError( + "options['compile'] is CasADi-only; not supported with " + "convert_to_format='rust'" + ) + len_rhs = 0 if model.rhs == {} else model.len_rhs + # An oversized y0 means sensitivity-extended states, unsupported here + y0_list = getattr(model, "y0_list", None) + if y0_list and model.len_rhs_and_alg != np.asarray(y0_list[0]).shape[0]: + raise pybamm.SolverError( + "The Rust Newton root solver does not support " + "sensitivity-extended states; use convert_to_format='casadi' " + "for this configuration" + ) + + # Set-up compiles the model with its algebraic block; a model that has not + # been set up, or was unpickled, compiles it here + lowering = RustModelLowering.of(model, inputs_dict) + rust_model = lowering.compiled or lowering.compile_model() + len_alg = model.len_rhs_and_alg - len_rhs + # Solves split y0 at len_rhs, and C++ gathers at the Rust model's own split + if (rust_model.n_states, rust_model.n_algebraic) != ( + len_rhs + len_alg, + len_alg, + ): + raise pybamm.SolverError( + f"The Rust model has {rust_model.n_states} states, " + f"{rust_model.n_algebraic} of them algebraic, but the Newton solver " + f"expects {len_rhs + len_alg} and {len_alg}" + ) + + # The evaluator gives the Newton solver its block's split and Jacobian pattern + _setup = idaklu.StandaloneNewtonSolver( + rust_evaluator=rust_model.evaluator(), + atol=np.full(len_alg, float(self.atol)).tolist(), + rtol=float(self.rtol), + step_tol=float(self.step_tol), + max_iter=int(self.max_iter), + max_backtracks=int(self.max_backtracks), + eps_newt=float(self.eps_newt), + use_sparse=bool(self.use_sparse), + klu_pivot_tolerance=float(self._options["klu_pivot_tolerance"]), + ) + return _NonlinearSolverSetup(_setup, len_alg, len_rhs + rust_model.n_inputs) - def _build_newton_solver(self, res_fn, jac_fn, len_alg): + def _build_newton_solver(self, res_fn, jac_fn, len_alg, n_params): _setup = idaklu.StandaloneNewtonSolver( residual=casadi_to_idaklu_function(res_fn), jacobian=casadi_to_idaklu_function(jac_fn), @@ -203,7 +301,7 @@ def _build_newton_solver(self, res_fn, jac_fn, len_alg): use_sparse=bool(self.use_sparse), klu_pivot_tolerance=float(self._options["klu_pivot_tolerance"]), ) - return _NonlinearSolverSetup(_setup) + return _NonlinearSolverSetup(_setup, len_alg, n_params) def _integrate_single(self, model, t_eval, inputs_dict, y0): inputs_dict = inputs_dict or {} diff --git a/packages/pybamm/src/pybamm/solvers/observation.py b/packages/pybamm/src/pybamm/solvers/observation.py index 0e6be86d8c..f4879af6c0 100644 --- a/packages/pybamm/src/pybamm/solvers/observation.py +++ b/packages/pybamm/src/pybamm/solvers/observation.py @@ -144,8 +144,8 @@ class OutputAssembly: A solve run with ``output_variables`` propagates no state trajectory: the solver evaluates the requested variables itself and returns one row per - non-zero of each variable's CasADi function, in variable order, so a vector - variable spans several consecutive rows. + non-zero of each variable's CasADi function (per value, for :meth:`dense`), + in variable order, so a vector variable spans several consecutive rows. Parameters ---------- @@ -167,18 +167,43 @@ def __init__( time_integrals: Mapping[str, pybamm.ProcessedVariableTimeIntegral] | None = None, ): - self._names = tuple(names) - self._casadi_fns = {name: casadi_fns[name] for name in self._names} - self._time_integrals = dict(time_integrals or {}) + names = tuple(names) + self._casadi_fns = {name: casadi_fns[name] for name in names} lens = [] # name -> sparsity of the variables whose rows are sparse self._sparse = {} - for name in self._names: + for name in names: sparsity = self._casadi_fns[name].sparsity_out(0) lens.append(sparsity.nnz()) if sparsity.nnz() != sparsity.numel(): self._sparse[name] = sparsity - offsets = list(accumulate(lens, initial=0)) + self._set_layout(names, lens, time_integrals) + + @classmethod + def dense( + cls, + names: Sequence[str], + lens: Sequence[int], + *, + time_integrals: Mapping[str, pybamm.ProcessedVariableTimeIntegral] + | None = None, + ) -> OutputAssembly: + """The layout of a payload that carries every value of each variable.""" + assembly = cls.__new__(cls) + assembly._casadi_fns = {} + assembly._sparse = {} + assembly._set_layout(tuple(names), lens, time_integrals) + return assembly + + def _set_layout(self, names, lens, time_integrals) -> None: + if len(names) != len(lens): + raise pybamm.SolverError( + f"Output layout mismatch: {len(names)} output variables but " + f"{len(lens)} row lengths." + ) + self._names = names + self._time_integrals = dict(time_integrals or {}) + offsets = list(accumulate((int(length) for length in lens), initial=0)) self._n_rows = offsets[-1] # One slice of payload rows per output variable self._rows = tuple(slice(start, end) for start, end in pairwise(offsets)) @@ -241,7 +266,7 @@ def attach( ) variable = pybamm.ProcessedVariableComputed( [model.get_processed_variable_or_event(name)], - [self._casadi_fns[name]], + [self._casadi_fns.get(name)], [values], solution, time_integral=time_integral, diff --git a/packages/pybamm/src/pybamm/solvers/rust_evaluator.py b/packages/pybamm/src/pybamm/solvers/rust_evaluator.py index 7c5c5e3bf7..3fa41efeea 100644 --- a/packages/pybamm/src/pybamm/solvers/rust_evaluator.py +++ b/packages/pybamm/src/pybamm/solvers/rust_evaluator.py @@ -20,7 +20,7 @@ def _as_1d(arr: npt.ArrayLike) -> npt.NDArray[np.float64]: class RustEvaluator: - """Role-specific view over a per-group ``CompiledFunction``. + """Role-specific view over a ``CompiledFunction``. Parameters ---------- @@ -28,23 +28,32 @@ class RustEvaluator: The compiled function to evaluate. role : str ``"func"`` (given ``y_dot`` as a fourth argument if it reads it), - ``"jac"`` (scipy CSC), ``"jac_action"`` or ``"jacp"`` (one ``df/dp_i`` - column per ``sens_indices`` entry, as CasADi's ``jacp``). + ``"jac"`` (scipy CSC) or ``"jacp"`` (one ``df/dp_i`` column per + ``sens_indices`` entry, as CasADi's ``jacp``). sens_indices : list of int, optional Graph input indices of the sensitivity parameters, read by ``"jacp"``. + rows : slice, optional + The rows of ``cf``'s output to return; all of them by default. + jacobian : :class:`pybamm.rust.CompiledJacobian`, optional + An already prepared ``d(cf)/dy`` for ``"jac"``; derived from ``cf`` on first + use otherwise. """ def __init__( self, cf: CompiledFunction, - role: Literal["func", "jac", "jac_action", "jacp"], + role: Literal["func", "jac", "jacp"], sens_indices: list[int] | None = None, + *, + rows: slice | None = None, + jacobian: CompiledJacobian | None = None, ) -> None: self._cf = cf self._role = role self._sens_indices = sens_indices - # Derived lazily on the first jac/jacp call - self._jac: CompiledJacobian | None = None + self._rows = rows + # Derived lazily on the first jac/jacp call unless given + self._jac: CompiledJacobian | None = jacobian def __getstate__(self) -> dict: state = self.__dict__.copy() @@ -56,6 +65,9 @@ def _jacobian(self, wrt: Literal["y", "p"]) -> CompiledJacobian: self._jac = self._cf.jacobian(wrt) return self._jac + def _select(self, value): + return value if self._rows is None else value[self._rows] + def __call__( self, t: float, @@ -74,32 +86,26 @@ def __call__( inputs : array-like The stacked input values. v : array-like, optional - The vector a ``"jac_action"`` multiplies, or the state derivatives - ``y_dot`` of a ``"func"`` that reads them. + The state derivatives ``y_dot``, for a ``"func"`` that reads them. Returns ------- numpy.ndarray, scipy.sparse.csc_matrix or tuple of numpy.ndarray - A column for ``"func"`` and ``"jac_action"``, the sparse Jacobian for - ``"jac"``, and one column per sensitivity parameter for ``"jacp"``. + A column for ``"func"``, the sparse Jacobian for ``"jac"``, and one + column per sensitivity parameter for ``"jacp"``. Raises ------ pybamm.SolverError - If a ``"jac_action"`` evaluator gets no ``v``, or a ``"jacp"`` evaluator - has no ``sens_indices``. + If a ``"jacp"`` evaluator has no ``sens_indices``. """ t, y, p = float(t), _as_1d(y), _as_1d(inputs) if self._role == "func": y_dot = None if v is None else _as_1d(v) - return np.asarray(self._cf(t, y, p, y_dot)).reshape(-1, 1) + return self._select(np.asarray(self._cf(t, y, p, y_dot)).reshape(-1, 1)) if self._role == "jac": - return self._jacobian("y")(t, y, p) - if self._role == "jac_action": - if v is None: - raise pybamm.SolverError("A 'jac_action' evaluator needs the vector v") - return np.asarray(self._cf.jvp(t, y, p, _as_1d(v))).reshape(-1, 1) + return self._select(self._jacobian("y")(t, y, p)) if self._sens_indices is None: raise pybamm.SolverError("A 'jacp' evaluator needs sens_indices") - dense = self._jacobian("p")(t, y, p).toarray() + dense = self._select(self._jacobian("p")(t, y, p).toarray()) return tuple(dense[:, i].reshape(-1, 1) for i in self._sens_indices) diff --git a/packages/pybamm/src/pybamm/solvers/rust_lowering.py b/packages/pybamm/src/pybamm/solvers/rust_lowering.py index f9cf79842b..f820bc75b8 100644 --- a/packages/pybamm/src/pybamm/solvers/rust_lowering.py +++ b/packages/pybamm/src/pybamm/solvers/rust_lowering.py @@ -1,15 +1,18 @@ -"""Rust expression graphs for a discretised model.""" +"""The one Rust graph of a discretised model, and the functions compiled on it.""" from __future__ import annotations -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any, cast + +import numpy as np +import numpy.typing as npt import pybamm if TYPE_CHECKING: - from collections.abc import Iterable + from collections.abc import Callable, Iterable - from pybamm.rust import CompiledFunction, ExprGraph + from pybamm.rust import CompiledFunction, CompiledModel, Expr def rust_input_parameter_widths(model: pybamm.BaseModel) -> dict[str, int]: @@ -17,44 +20,394 @@ def rust_input_parameter_widths(model: pybamm.BaseModel) -> dict[str, int]: return {ip.name: ip._expected_size or 1 for ip in model.input_parameters} -def reject_y_dot(function: CompiledFunction) -> None: - """Refuse a compiled function that reads the state derivatives, ``y_dot``. +# CasADi's error for a conversion without y_dot, raised alike on the Rust backend +_Y_DOT_REQUIRED = ( + "Must provide a 'y_dot' for converting state vectors differentiated " + "in time, e.g. by `symbol.diff(pybamm.t)`" +) + + +def _reject_y_dot(symbol: pybamm.Symbol) -> None: + """Refuse ``symbol`` if it reads the state derivatives, ``y_dot``. Raises ------ :class:`pybamm.ModelError` - If ``function`` reads ``y_dot``, as the CasADi conversion does without it. + If ``symbol`` contains a time derivative of a state, as the CasADi + conversion does without ``y_dot``. + """ + if symbol.has_symbol_of_classes(pybamm.StateVectorDot): + raise pybamm.ModelError(_Y_DOT_REQUIRED) + + +def _shape(symbol: pybamm.Symbol) -> tuple[int, ...]: + """The shape of ``symbol``, from a shape-only walk. + + ``Symbol.shape`` would evaluate the whole expression numerically. """ - if function.uses_y_dot: - raise pybamm.ModelError( - "Must provide a 'y_dot' for converting state vectors differentiated " - "in time, e.g. by `symbol.diff(pybamm.t)`" + return np.shape(symbol.evaluate_for_shape()) + + +def residual_symbol(model: pybamm.BaseModel) -> pybamm.Symbol: + """The solver's residual: the right-hand side, then any algebraic block.""" + if model.len_rhs == 0: + return model.concatenated_algebraic + if model.len_alg > 0: + return pybamm.numpy_concatenation( + model.concatenated_rhs, model.concatenated_algebraic ) + return model.concatenated_rhs + + +class _LoweredSymbols(dict): + """A memo of lowered symbols, by symbol id, for a graph with fixed inputs. + + An input parameter lowered with it refuses to register a name outside + :attr:`input_names` on its graph. + + Parameters + ---------- + input_names : iterable of str + The names of the graph's input parameters. + """ + def __init__(self, input_names: Iterable[str]): + super().__init__() + self.input_names = frozenset(input_names) -def rust_graph_with_inputs( - model: pybamm.BaseModel, input_names: Iterable[str] -) -> ExprGraph: - """Build an ``ExprGraph`` with ``input_names`` registered in stacking order. - Registration precedes any lowering so graph input indices match that order. +class RustModelLowering: + """The Rust graph of one discretised model, and the functions compiled on it. + + Its ``CompiledModel`` and its standalone functions share one memo of lowered + symbols, so each symbol is lowered once. The graph registers the model's inputs + when it is made, and refuses any other. Parameters ---------- model : :class:`pybamm.BaseModel` - The discretised model whose input parameter widths are registered. + The discretised model. input_names : iterable of str Input parameter names, in the order the inputs are stacked. - - Returns - ------- - :class:`pybamm.rust.ExprGraph` - A graph with each input registered at its packed width. """ - from pybamm.rust import ExprGraph - graph = ExprGraph() - widths = rust_input_parameter_widths(model) - for name in input_names: - graph.input_parameter(name, widths.get(name, 1)) - return graph + def __init__(self, model: pybamm.BaseModel, input_names: Iterable[str]): + from pybamm.rust import ExprGraph + + self.model = model + self.input_name_order = list(input_names) + self.graph = ExprGraph() + widths = rust_input_parameter_widths(model) + # Registered before any lowering, so graph input indices follow this order + for name in self.input_name_order: + self.graph.input_parameter(name, widths.get(name, 1)) + self._symbols = _LoweredSymbols(self.input_name_order) + self._cache: dict = {} + #: The model's ``CompiledModel``, from the last :meth:`compile_model`, or None. + self.compiled: CompiledModel | None = None + + @classmethod + def of( + cls, model: pybamm.BaseModel, input_names: Iterable[str] + ) -> RustModelLowering: + """The lowering of ``model``, made on first use. + + The model's lowering is replaced when the input names differ from its own, + in which case its stacked inputs would mean something else. + + Parameters + ---------- + model : :class:`pybamm.BaseModel` + The discretised model. + input_names : iterable of str + Input parameter names, in the order the inputs are stacked. + + Returns + ------- + :class:`RustModelLowering` + """ + names = list(input_names) + lowering = cls.current(model) + if lowering is None or lowering.input_name_order != names: + lowering = cls(model, names) + model._rust_lowering = lowering + return lowering + + @staticmethod + def current(model: pybamm.BaseModel) -> RustModelLowering | None: + """The lowering :meth:`of` last made for ``model``, or None.""" + return getattr(model, "_rust_lowering", None) + + @property + def n_states(self) -> int: + """The model's number of states.""" + return self.model.len_rhs_and_alg + + def lower(self, symbol: pybamm.Symbol) -> Expr: + """Lower one symbol into this graph, reusing already-lowered subtrees. + + Raises + ------ + :class:`pybamm.SolverError` + If ``symbol`` reads an input parameter the graph does not register. + """ + return symbol.to_rust(self.graph, self._symbols) + + def cached(self, key: Any, build: Callable[[], Any]) -> Any: + """The value cached under ``key`` for this graph, built on first use.""" + if key not in self._cache: + self._cache[key] = build() + return self._cache[key] + + def function( + self, + symbol: pybamm.Symbol, + name: str, + *, + n_states: int | None = None, + ) -> CompiledFunction: + """Compile ``symbol`` on this graph, outside the ``CompiledModel``. + + Parameters + ---------- + symbol : :class:`pybamm.Symbol` + The expression to compile. + name : str + The compiled function's name. + n_states : int, optional + Length of the state vector it reads; the model's by default. + + Returns + ------- + :class:`pybamm.rust.CompiledFunction` + + Raises + ------ + :class:`pybamm.ModelError` + If it reads the state derivatives, ``y_dot``. + """ + _reject_y_dot(symbol) + return self.graph.compile( + self.lower(symbol), + name=name, + n_states=self.n_states if n_states is None else n_states, + ) + + def outputs_function( + self, symbols: dict[str, pybamm.Symbol], *, n_states: int | None = None + ) -> CompiledFunction: + """Compile named ``symbols`` on this graph into one function of their rows. + + Raises + ------ + :class:`pybamm.ModelError` + If any of them reads the state derivatives, ``y_dot``. + """ + for symbol in symbols.values(): + _reject_y_dot(symbol) + return self.graph.compile_outputs( + {name: self.lower(symbol) for name, symbol in symbols.items()}, + n_states=self.n_states if n_states is None else n_states, + ) + + def compile_model( + self, + *, + sensitivities: Iterable[str] | None = None, + output_variables: Iterable[str] = (), + time_integral_vars: dict[str, pybamm.ProcessedVariableTimeIntegral] + | None = None, + upsampling: tuple[str, pybamm.Symbol] | None = None, + allow_y_dot_events: bool = True, + ) -> CompiledModel: + """Compile the model's ``CompiledModel``, kept as :attr:`compiled` once it has. + + It holds the residual, the algebraic block of a DAE, the termination events + and the ``df/dp`` of ``sensitivities``, plus any output variables and + upsampling output. + + Parameters + ---------- + sensitivities : iterable of str, optional + Inputs to differentiate with respect to. + output_variables : iterable of str, optional + Variables the solver evaluates itself. + time_integral_vars : dict, optional + The time integrals among ``output_variables``, which lower their + ``sum_node``. + upsampling : tuple, optional + The upsampling variable's name and the expression it reads. + allow_y_dot_events : bool, optional + Whether termination events may read ``y_dot``. Default is True. + + Returns + ------- + :class:`pybamm.rust.CompiledModel` + + Raises + ------ + :class:`pybamm.SolverError` + If a sensitivity is not an input, an output variable is a tensor field, + or the upsampling output or a termination event is not scalar. + :class:`pybamm.ModelError` + If an output, the upsampling output or, unless ``allow_y_dot_events``, + a termination event reads the state derivatives, ``y_dot``. + """ + from pybamm.rust import CompiledModel + + residual = self.lower(residual_symbol(self.model)) + algebraic_expr, algebraic_indices = self._lower_algebraic_block() + sens_param_indices = self.sensitivity_indices(sensitivities or []) + output_exprs = self._lower_outputs(output_variables, time_integral_vars or {}) + upsampling_expr = ( + None if upsampling is None else self._lower_upsampling(*upsampling) + ) + event_exprs = self._lower_termination_events(allow_y_dot_events) + data, indptr, indices = self._mass_matrix_csr() + compiled = CompiledModel.from_expr( + self.graph, + residual, + data, + indptr, + indices, + sens_param_indices=sens_param_indices, + output_exprs=output_exprs, + algebraic_expr=algebraic_expr, + algebraic_variable_indices=algebraic_indices, + event_exprs=event_exprs, + upsampling_expr=upsampling_expr, + ) + self.compiled = compiled + return compiled + + def _lower_algebraic_block(self) -> tuple[Expr | None, list[int]]: + """Lower the algebraic sub-block a Newton initialisation solves.""" + model = self.model + if model.len_alg == 0: + return None, [] + expr = self.lower(model.concatenated_algebraic) + return expr, list(range(model.len_rhs, model.len_rhs_and_alg)) + + def sensitivity_indices(self, sensitivity_names: Iterable[str]) -> list[int]: + """Map sensitivity names to graph input indices. + + Parameters + ---------- + sensitivity_names : iterable of str + Inputs to differentiate with respect to. + + Returns + ------- + list of int + The graph input index of each name, in order. + + Raises + ------ + :class:`pybamm.SolverError` + If a name is not one of the inputs this lowering was built with. + """ + sensitivity_names = list(sensitivity_names) + unknown = [ + name for name in sensitivity_names if name not in self.input_name_order + ] + if unknown: + raise pybamm.SolverError( + f"Sensitivities were requested for {unknown}, but the model's " + f"inputs are {self.input_name_order}" + ) + # Registration ordered the graph's inputs as the solver stacks them + return [cast(int, self.graph.input_index(name)) for name in sensitivity_names] + + def _lower_outputs( + self, + output_variables: Iterable[str], + time_integral_vars: dict[str, pybamm.ProcessedVariableTimeIntegral], + ) -> list[Expr]: + """Lower the output variables. + + Raises + ------ + pybamm.SolverError + If an output variable is a tensor field. + pybamm.ModelError + If an output variable reads the state derivatives, ``y_dot``. + """ + exprs = [] + for name in output_variables: + time_integral = time_integral_vars.get(name) + if time_integral is not None: + symbol = time_integral.sum_node + else: + symbol = self.model.get_processed_variable_or_event(name) + if isinstance(symbol, pybamm.TensorField): + raise pybamm.SolverError( + f"Output variable '{name}' is a tensor field, which cannot be " + "read back from a Solution. Request a scalar component with " + "pybamm.Component instead." + ) + _reject_y_dot(symbol) + exprs.append(self.lower(symbol)) + return exprs + + def _lower_upsampling(self, name: str, symbol: pybamm.Symbol) -> Expr: + """Lower ``symbol``, the upsampling output read from the variable ``name``. + + Raises + ------ + pybamm.SolverError + If ``symbol`` is not scalar. + pybamm.ModelError + If ``symbol`` reads the state derivatives, ``y_dot``. + """ + if np.prod(_shape(symbol)) != 1: + raise pybamm.SolverError( + f"upsampling_tolerance needs a scalar variable, got '{name}'" + ) + _reject_y_dot(symbol) + return self.lower(symbol) + + def _lower_termination_events(self, allow_y_dot: bool) -> list[Expr]: + """Lower every termination event expression, for root-finding. + + Raises + ------ + pybamm.SolverError + If an event expression is not scalar. + pybamm.ModelError + If an event reads the state derivatives, ``y_dot``, and ``allow_y_dot`` + is False. + """ + events = [ + event + for event in self.model.events + if event.event_type == pybamm.EventType.TERMINATION + ] + for event in events: + shape = _shape(event.expression) + if np.prod(shape) != 1: + raise pybamm.SolverError( + f"Termination event '{event.name}' has shape " + f"{shape}, but a root function must be scalar. " + "Reduce it with pybamm.min or pybamm.max." + ) + if not allow_y_dot: + _reject_y_dot(event.expression) + return [self.lower(event.expression) for event in events] + + def _mass_matrix_csr( + self, + ) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.int64], npt.NDArray[np.int64]]: + """The mass matrix as the ``(data, indptr, indices)`` CSR triple. + + A model without one, as discretisation leaves a model with no states, has + the empty matrix. + """ + from scipy.sparse import csr_matrix + + mass_matrix = self.model.mass_matrix + mass = csr_matrix((0, 0)) if mass_matrix is None else mass_matrix.entries + return ( + mass.data.astype(np.float64), + mass.indptr.astype(np.int64), + mass.indices.astype(np.int64), + ) diff --git a/packages/pybamm/tests/integration/dfn_ab_harness.py b/packages/pybamm/tests/integration/dfn_ab_harness.py new file mode 100644 index 0000000000..7c1b472cde --- /dev/null +++ b/packages/pybamm/tests/integration/dfn_ab_harness.py @@ -0,0 +1,126 @@ +"""DFN A/B harness: CasADi expression tree vs Rust DAG.""" + +from __future__ import annotations + +import numbers +from dataclasses import dataclass + +import numpy as np + +import pybamm +from pybamm.solvers.rust_lowering import residual_symbol + + +@dataclass +class DFNAB: + """Matched CasADi/Rust DFN pair; `p` holds inputs in declaration order.""" + + n_states: int + npts: int + y0: np.ndarray + inputs_dict: dict[str, float] + inputs_array: np.ndarray + casadi_residual: object + casadi_jacobian: object + rust_model: object + csc_colptrs: np.ndarray + csc_rowinds: np.ndarray + nnz: int + + +def _make_var_pts(model: pybamm.BaseModel, npts: int) -> dict: + """Override scalar var_pts with `npts`; preserve direction grids (y, z).""" + out = {} + for k, v in model.default_var_pts.items(): + if isinstance(v, numbers.Number) and v > 1 and k not in {"y", "z"}: + out[k] = npts + else: + out[k] = v + return out + + +def build_dfn_ab( + npts: int = 20, + *, + with_input_current: bool = True, + parameter_set: str = "Chen2020", +) -> DFNAB: + """Build a discretised DFN and matched CasADi/Rust evaluation pair.""" + from pybamm.rust import CompiledModel, ExprGraph + + model = pybamm.lithium_ion.DFN() + model.events = [] # Only the residual and Jacobian are compared + + param = pybamm.ParameterValues(parameter_set) + if with_input_current: + param["Current function [A]"] = pybamm.InputParameter("I") + inputs_dict = {"I": 0.5} + else: + inputs_dict = {} + + var_pts = _make_var_pts(model, npts) + + model.convert_to_format = "casadi" + sim = pybamm.Simulation( + model, + parameter_values=param, + var_pts=var_pts, + solver=pybamm.IDAKLUSolver(), + ) + sim.build() + built = sim.built_model + + sim.solver.set_up(built, inputs=inputs_dict) + + n_states = built.len_rhs_and_alg + inputs_array = np.array( + [float(inputs_dict[k]) for k in inputs_dict], dtype=np.float64 + ) + y0 = np.asarray(built.y0.full() if hasattr(built.y0, "full") else built.y0).reshape( + -1 + ) + + # The residual a solver's set-up lowers, lowered here without a solver + graph = ExprGraph() + rhs_expr = residual_symbol(built).to_rust(graph, {}) + + mass = built.mass_matrix.entries # scipy CSR + rust_model = CompiledModel.from_expr( + graph, + rhs_expr, + mass.data.astype(np.float64), + mass.indptr.astype(np.int64), + mass.indices.astype(np.int64), + ) + + csc_colptrs, csc_rowinds = rust_model.csc_sparsity_pattern() + + return DFNAB( + n_states=n_states, + npts=npts, + y0=y0, + inputs_dict=inputs_dict, + inputs_array=inputs_array, + casadi_residual=built.rhs_algebraic_eval, + casadi_jacobian=built.jac_rhs_algebraic_eval, + rust_model=rust_model, + csc_colptrs=np.asarray(csc_colptrs, dtype=np.int64), + csc_rowinds=np.asarray(csc_rowinds, dtype=np.int64), + nnz=int(rust_model.nnz), + ) + + +def sample_state( + ab: DFNAB, *, perturb: float = 0.0, seed: int | None = None +) -> np.ndarray: + """Return `ab.y0` optionally perturbed by `perturb * randn(n_states)`.""" + if perturb <= 0: + return ab.y0.copy() + rng = np.random.default_rng(seed) + return ab.y0 + perturb * rng.standard_normal(ab.n_states) + + +def casadi_jacobian_dense(ab: DFNAB, t: float, y: np.ndarray) -> np.ndarray: + """Convert CasADi sparse Jacobian to a dense numpy array (for parity).""" + J = ab.casadi_jacobian(t, y, ab.inputs_array) + return np.asarray(J) diff --git a/packages/pybamm/tests/integration/test_convert_to_format_rust.py b/packages/pybamm/tests/integration/test_convert_to_format_rust.py index 05c3a4a144..5469450954 100644 --- a/packages/pybamm/tests/integration/test_convert_to_format_rust.py +++ b/packages/pybamm/tests/integration/test_convert_to_format_rust.py @@ -1,3 +1,4 @@ +import numpy as np import pytest import pybamm @@ -29,3 +30,40 @@ def test_default_root_method_keeps_the_rust_format(self): solver._check_and_prepare_model_inplace(model) assert model.convert_to_format == "rust" assert isinstance(solver.root_method, pybamm.NonlinearSolver) + + def test_dae_consistent_ic_parity_rust_newton_vs_casadi(self): + from tests.unit.test_solvers.test_process_rust import _toy_dae + + y0 = {} + for fmt in ("casadi", "rust"): + model = _toy_dae(fmt) + model.initial_conditions = { + k: v for k, v in model.initial_conditions.items() + } + solver = pybamm.IDAKLUSolver( + root_method="nonlinear_solver", options={"calc_ic": False} + ) + solver.set_up(model, inputs=[{"a": 0.5}]) + solver._set_consistent_initialization(model, 0.0, [{"a": 0.5}]) + y0[fmt] = np.asarray(model.y0_list[0]).ravel() + np.testing.assert_allclose(y0["rust"], y0["casadi"], rtol=1e-8) + + def test_casadi_root_method_solves_a_rust_model_without_being_replaced(self): + model = pybamm.BaseModel() + u = pybamm.Variable("u") + v = pybamm.Variable("v") + a = pybamm.InputParameter("a") + model.rhs = {u: -a * u} + model.algebraic = {v: 2 * u - v} + model.initial_conditions = {u: 1.0, v: 0.0} # v is inconsistent + pybamm.Discretisation().process_model(model) + model.convert_to_format = "rust" + + solver = pybamm.IDAKLUSolver(root_method="casadi", options={"calc_ic": False}) + solver.solve(model, [0, 1], inputs={"a": 0.5}) + + np.testing.assert_allclose( + np.asarray(model.y0_list[0]).ravel(), [1.0, 2.0], rtol=1e-6 + ) + assert model.convert_to_format == "rust" + assert isinstance(solver.root_method, pybamm.CasadiAlgebraicSolver) diff --git a/packages/pybamm/tests/integration/test_rust_adjoint_dense_rows.py b/packages/pybamm/tests/integration/test_rust_adjoint_dense_rows.py new file mode 100644 index 0000000000..80e77a16c9 --- /dev/null +++ b/packages/pybamm/tests/integration/test_rust_adjoint_dense_rows.py @@ -0,0 +1,52 @@ +"""End-to-end coverage for Rust adjoint dense-row assembly.""" + +import numpy as np + +import pybamm + + +class TestRustAdjointDenseRows: + def test_spme_uses_one_adjoint_sweep_for_voltage_row(self): + # Voltage-as-a-state gives SPMe the dense voltage row this test targets. + model = pybamm.lithium_ion.SPMe(options={"voltage as a state": "true"}) + model.convert_to_format = "rust" + simulation = pybamm.Simulation(model) + solution = simulation.solve(np.linspace(0.0, 600.0, 20)) + + stats = simulation.solver._setup["rust_model"].jacobian_stats() + assert stats["n_dense_rows"] == 1 + assert stats["dense_row_tape_instructions"] > 0 + assert stats["dense_row_entries"] > stats["n_colors"] + + t = np.linspace(0.0, 600.0, 25) + np.testing.assert_allclose( + solution["Voltage [V]"](t), + solution["Voltage expression [V]"](t), + rtol=1e-5, + atol=1e-5, + ) + + def test_pouch_cv_hold_folds_its_constraint_row(self): + model = pybamm.lithium_ion.DFN( + {"current collector": "potential pair", "dimensionality": 2} + ) + model.convert_to_format = "rust" + simulation = pybamm.Simulation( + model, + var_pts={"x_n": 4, "x_s": 4, "x_p": 4, "r_n": 4, "r_p": 4, "y": 8, "z": 8}, + experiment=pybamm.Experiment(["Hold at 4.1 V until C/20"]), + ) + simulation.build_for_experiment() + built = next( + m + for key, m in simulation.steps_to_built_models.items() + if key.startswith("Voltage") + ) + solver = pybamm.IDAKLUSolver() + solver.set_up(built, inputs={}, t_eval=np.array([0.0, 1.0])) + + stats = solver._setup["rust_model"].jacobian_stats() + # The linear CV row folds to constants: no reverse pass, no colour per column. + assert stats["n_dense_rows"] == 0 + assert 10 * stats["n_colors"] < stats["n_swept_columns"] + assert stats["jac_lane_width"] > 1 diff --git a/packages/pybamm/tests/integration/test_rust_idaklu.py b/packages/pybamm/tests/integration/test_rust_idaklu.py new file mode 100644 index 0000000000..f3123b2471 --- /dev/null +++ b/packages/pybamm/tests/integration/test_rust_idaklu.py @@ -0,0 +1,348 @@ +"""Rust `CompiledModel` Jacobian parity against CasADi, for IDAKLU.""" + +import numpy as np +import pytest +from scipy.sparse import diags, eye + +import pybamm + +casadi = pytest.importorskip("casadi") + +try: + from pybamm.rust import CompiledModel, ExprGraph +except ImportError: + pytest.skip( + "Rust extension not available. Build with: uv sync", + allow_module_level=True, + ) + + +class TestRustIDAKLUJacobianParity: + @staticmethod + def build_diffusion_reaction_expr(n_states: int): + """Build ``f(y) = D * L @ y + k * exp(-y/T) * (1 - y)``, mimicking SPM/DFN.""" + sv = pybamm.StateVector(slice(0, n_states)) + t = pybamm.Time() + D = pybamm.InputParameter("diffusivity") + k = pybamm.InputParameter("rate_constant") + T = pybamm.InputParameter("temperature") + + diag_data = [ + np.ones(n_states) * -2, + np.ones(n_states - 1), + np.ones(n_states - 1), + ] + laplacian = diags(diag_data, [0, -1, 1], format="csr") + L = pybamm.Matrix(laplacian) + + diffusion = D * (L @ sv) + + reaction = ( + k + * pybamm.exp(-sv / T) + * (pybamm.Scalar(1.0) - sv) + * (pybamm.Scalar(1.0) + pybamm.Scalar(0.01) * t) + ) + + return diffusion + reaction + + @staticmethod + def build_stiff_ode_expr(n_states: int): + """Build a stiff ODE ``f(y) = -A @ y + nonlinear_source(y)``.""" + sv = pybamm.StateVector(slice(0, n_states)) + t = pybamm.Time() + alpha = pybamm.InputParameter("alpha") + beta = pybamm.InputParameter("beta") + + diag_main = np.linspace(1.0, 1000.0, n_states) + diag_off = np.ones(n_states - 1) * 0.1 + A_sparse = diags([diag_main, -diag_off, -diag_off], [0, -1, 1], format="csr") + A = pybamm.Matrix(A_sparse) + + linear = -alpha * (A @ sv) + + nonlinear = ( + beta + * pybamm.tanh(sv) + * pybamm.exp(-pybamm.Scalar(0.01) * sv * sv) + * (pybamm.Scalar(1.0) + pybamm.Scalar(0.001) * t) + ) + + return linear + nonlinear + + @staticmethod + def _build_casadi_functions(expr, n_states: int, inputs: dict): + """Build CasADi functions for RHS and Jacobian-vector product.""" + t_sym = casadi.MX.sym("t") + y_sym = casadi.MX.sym("y", n_states) + y_dot_sym = casadi.MX.sym("y_dot", 0) + inputs_sym = {name: casadi.MX.sym(name) for name in inputs} + + casadi_symbols = { + "t": t_sym, + "y": y_sym, + "y_dot": y_dot_sym, + "inputs": inputs_sym, + } + f_casadi = expr.to_casadi(t_sym, y_sym, y_dot_sym, inputs_sym, casadi_symbols) + + func_inputs = [t_sym, y_sym, *inputs_sym.values()] + f_fn = casadi.Function("f", func_inputs, [f_casadi]) + + jac_expr = casadi.jacobian(f_casadi, y_sym) + jac_fn = casadi.Function("jacobian_fn", func_inputs, [jac_expr]) + + # Jacobian-vector product: J @ v - cj * M @ v (M = I for this test) + v_sym = casadi.MX.sym("v", n_states) + cj_sym = casadi.MX.sym("cj") + jac_action = casadi.jtimes(f_casadi, y_sym, v_sym) - cj_sym * v_sym + jac_inputs = [t_sym, y_sym, *inputs_sym.values(), cj_sym, v_sym] + jac_action_fn = casadi.Function("jac_action", jac_inputs, [jac_action]) + + return f_fn, jac_fn, jac_action_fn + + @staticmethod + def _build_rust_model(expr, n_states: int): + """Build Rust CompiledModel from PyBaMM expression.""" + graph = ExprGraph() + rust_symbols = {} + rust_expr = expr.to_rust(graph, rust_symbols) + + mass = eye(n_states, format="csr") + model = CompiledModel.from_expr( + graph, + rust_expr, + mass.data.astype(np.float64), + mass.indptr.astype(np.int64), + mass.indices.astype(np.int64), + ) + return model + + @pytest.mark.parametrize("n_states", [10, 50, 100]) + def test_rhs_parity_diffusion_reaction(self, n_states): + inputs = {"diffusivity": 1e-5, "rate_constant": 1.0, "temperature": 298.15} + expr = self.build_diffusion_reaction_expr(n_states) + + f_fn, _, _ = self._build_casadi_functions(expr, n_states, inputs) + rust_model = self._build_rust_model(expr, n_states) + + rng = np.random.default_rng(0) + y = rng.standard_normal(n_states) * 0.1 + 0.5 + t = 0.5 + inputs_arr = np.array([inputs[name] for name in inputs]) + + casadi_result = np.array(f_fn(t, y, *inputs.values())).flatten() + rust_result = np.array(rust_model.rhs(t, y, inputs_arr)) + + np.testing.assert_allclose(rust_result, casadi_result, rtol=1e-10, atol=1e-14) + + @pytest.mark.parametrize("n_states", [10, 50, 100]) + def test_rhs_parity_stiff_ode(self, n_states): + inputs = {"alpha": 1.0, "beta": 0.5} + expr = self.build_stiff_ode_expr(n_states) + + f_fn, _, _ = self._build_casadi_functions(expr, n_states, inputs) + rust_model = self._build_rust_model(expr, n_states) + + rng = np.random.default_rng(0) + y = rng.standard_normal(n_states) * 0.1 + 0.5 + t = 0.5 + inputs_arr = np.array([inputs[name] for name in inputs]) + + casadi_result = np.array(f_fn(t, y, *inputs.values())).flatten() + rust_result = np.array(rust_model.rhs(t, y, inputs_arr)) + + np.testing.assert_allclose(rust_result, casadi_result, rtol=1e-10, atol=1e-14) + + @pytest.mark.parametrize("n_states", [10, 50, 100]) + def test_jac_mul_parity(self, n_states): + inputs = {"diffusivity": 1e-5, "rate_constant": 1.0, "temperature": 298.15} + expr = self.build_diffusion_reaction_expr(n_states) + + _, _, jac_action_fn = self._build_casadi_functions(expr, n_states, inputs) + rust_model = self._build_rust_model(expr, n_states) + + rng = np.random.default_rng(0) + y = rng.standard_normal(n_states) * 0.1 + 0.5 + v = rng.standard_normal(n_states) + t = 0.5 + cj = 1.0 + inputs_arr = np.array([inputs[name] for name in inputs]) + + casadi_result = np.array(jac_action_fn(t, y, *inputs.values(), cj, v)).flatten() + J = rust_model.jacobian(t, y, inputs_arr) + M = eye(n_states, format="csr") + rust_result = np.array(J @ v - cj * (M @ v)) + + np.testing.assert_allclose(rust_result, casadi_result, rtol=1e-9, atol=1e-12) + + @pytest.mark.parametrize("n_states", [10, 50]) + def test_assembled_jacobian_parity(self, n_states): + inputs = {"diffusivity": 1e-5, "rate_constant": 1.0, "temperature": 298.15} + expr = self.build_diffusion_reaction_expr(n_states) + + _, jac_fn, _ = self._build_casadi_functions(expr, n_states, inputs) + rust_model = self._build_rust_model(expr, n_states) + + rng = np.random.default_rng(0) + y = rng.standard_normal(n_states) * 0.1 + 0.5 + t = 0.5 + inputs_arr = np.array([inputs[name] for name in inputs]) + + casadi_jac = np.array(jac_fn(t, y, *inputs.values())) + + # model.jacobian is the pure df/dy. + J = rust_model.jacobian(t, y, inputs_arr) + rust_jac = J.toarray() + + np.testing.assert_allclose(rust_jac, casadi_jac, rtol=1e-9, atol=1e-12) + + @pytest.mark.parametrize("n_states", [10, 50]) + def test_assembled_jacobian_with_cj(self, n_states): + inputs = {"diffusivity": 1e-5, "rate_constant": 1.0, "temperature": 298.15} + expr = self.build_diffusion_reaction_expr(n_states) + + _, jac_fn, _ = self._build_casadi_functions(expr, n_states, inputs) + rust_model = self._build_rust_model(expr, n_states) + + rng = np.random.default_rng(0) + y = rng.standard_normal(n_states) * 0.1 + 0.5 + t = 0.5 + cj = 1.5 + inputs_arr = np.array([inputs[name] for name in inputs]) + + casadi_jac = np.array(jac_fn(t, y, *inputs.values())) + expected_jac = casadi_jac - cj * np.eye(n_states) + + J = rust_model.jacobian(t, y, inputs_arr) + M = eye(n_states, format="csr") + rust_jac = (J - cj * M).toarray() + + np.testing.assert_allclose(rust_jac, expected_jac, rtol=1e-9, atol=1e-12) + + @pytest.mark.parametrize("n_states", [10, 50]) + def test_jacobian_jvp_consistency(self, n_states): + """Matrix-free tangent JVP agrees with the coloured-assembly Jacobian.""" + inputs = {"diffusivity": 1e-5, "rate_constant": 1.0, "temperature": 298.15} + expr = self.build_diffusion_reaction_expr(n_states) + rust_model = self._build_rust_model(expr, n_states) + + rng = np.random.default_rng(0) + y = rng.standard_normal(n_states) * 0.1 + 0.5 + v = rng.standard_normal(n_states) + t = 0.5 + inputs_arr = np.array([inputs[name] for name in inputs]) + + jvp_result = rust_model.rhs.jvp(t, y, inputs_arr, v) + + J = rust_model.jacobian(t, y, inputs_arr) + assembled_result = np.asarray(J @ v) + + np.testing.assert_allclose(jvp_result, assembled_result, rtol=1e-9, atol=1e-12) + + def test_sparsity_pattern_structure(self): + n_states = 20 + expr = self.build_diffusion_reaction_expr(n_states) + rust_model = self._build_rust_model(expr, n_states) + + indptr, indices = rust_model.sparsity_pattern() + indptr = np.array(indptr) + indices = np.array(indices) + + assert len(indptr) == n_states + 1, "indptr should have n_states + 1 elements" + assert indptr[0] == 0, "indptr should start at 0" + assert indptr[-1] == len(indices), "indptr[-1] should equal nnz" + + assert np.all(indices >= 0), "all indices should be non-negative" + assert np.all(indices < n_states), "all indices should be < n_states" + + def test_residual_evaluation(self): + n_states = 20 + inputs = {"diffusivity": 1e-5, "rate_constant": 1.0, "temperature": 298.15} + expr = self.build_diffusion_reaction_expr(n_states) + + f_fn, _, _ = self._build_casadi_functions(expr, n_states, inputs) + rust_model = self._build_rust_model(expr, n_states) + + rng = np.random.default_rng(0) + y = rng.standard_normal(n_states) * 0.1 + 0.5 + yp = rng.standard_normal(n_states) * 0.01 + t = 0.5 + inputs_arr = np.array([inputs[name] for name in inputs]) + + # Residual is M*y' - f with M = I. + f_val = np.array(f_fn(t, y, *inputs.values())).flatten() + expected_residual = yp - f_val + + rust_residual = np.array(rust_model.eval_residual(t, y, yp, inputs_arr)) + + np.testing.assert_allclose( + rust_residual, expected_residual, rtol=1e-10, atol=1e-14 + ) + + @pytest.mark.parametrize("n_states", [10, 50, 100]) + def test_into_methods_match_allocating(self, n_states): + inputs = {"diffusivity": 1e-5, "rate_constant": 1.0, "temperature": 298.15} + expr = self.build_diffusion_reaction_expr(n_states) + rust_model = self._build_rust_model(expr, n_states) + + rng = np.random.default_rng(0) + y = rng.standard_normal(n_states) * 0.1 + 0.5 + v = rng.standard_normal(n_states) + yp = rng.standard_normal(n_states) * 0.01 + t = 0.5 + cj = 1.0 + inputs_arr = np.array([inputs[name] for name in inputs]) + + rhs_output = np.zeros(rust_model.output_len) + residual_output = np.zeros(rust_model.n_states) + + rhs_alloc = np.array(rust_model.rhs(t, y, inputs_arr)) + rust_model.rhs.eval_into(t, y, inputs_arr, rhs_output) + np.testing.assert_array_equal(rhs_output, rhs_alloc) + + # The Jacobian has no _into variant; two forms of (J - cj*M) @ v must agree. + M = eye(n_states, format="csr") + J = rust_model.jacobian(t, y, inputs_arr) + jvp_via_matmul = np.array(J @ v - cj * (M @ v)) + jvp_via_sparse = np.array((J - cj * M) @ v) + np.testing.assert_allclose( + jvp_via_matmul, jvp_via_sparse, rtol=1e-14, atol=1e-14 + ) + + res_alloc = np.array(rust_model.eval_residual(t, y, yp, inputs_arr)) + rust_model.eval_residual_into(t, y, yp, inputs_arr, residual_output) + np.testing.assert_array_equal(residual_output, res_alloc) + + def test_varying_time_values(self): + n_states = 20 + inputs = {"diffusivity": 1e-5, "rate_constant": 1.0, "temperature": 298.15} + expr = self.build_diffusion_reaction_expr(n_states) + + f_fn, _, _ = self._build_casadi_functions(expr, n_states, inputs) + rust_model = self._build_rust_model(expr, n_states) + + rng = np.random.default_rng(0) + y = rng.standard_normal(n_states) * 0.1 + 0.5 + inputs_arr = np.array([inputs[name] for name in inputs]) + + for t in [0.0, 0.1, 0.5, 1.0, 10.0, 100.0]: + casadi_result = np.array(f_fn(t, y, *inputs.values())).flatten() + rust_result = np.array(rust_model.rhs(t, y, inputs_arr)) + np.testing.assert_allclose( + rust_result, + casadi_result, + rtol=1e-10, + atol=1e-14, + err_msg=f"Mismatch at t={t}", + ) + + def test_model_properties(self): + n_states = 25 + expr = self.build_diffusion_reaction_expr(n_states) + rust_model = self._build_rust_model(expr, n_states) + + assert rust_model.n_states == n_states + assert rust_model.output_len == n_states + assert rust_model.n_colors > 0 + assert rust_model.n_colors <= n_states diff --git a/packages/pybamm/tests/integration/test_rust_idaklu_dae.py b/packages/pybamm/tests/integration/test_rust_idaklu_dae.py new file mode 100644 index 0000000000..40fe87e1d6 --- /dev/null +++ b/packages/pybamm/tests/integration/test_rust_idaklu_dae.py @@ -0,0 +1,79 @@ +"""DFN-driven Rust IDAKLU DAE parity tests.""" + +import numpy as np +import pytest + +from tests.integration.dfn_ab_harness import ( + build_dfn_ab, + casadi_jacobian_dense, + sample_state, +) + +pytest.importorskip("casadi") + + +@pytest.fixture(scope="module") +def ab_small(): + """Small DFN (npts=5), still mixed RHS/algebraic.""" + return build_dfn_ab(npts=5) + + +def _assemble_rust_jacobian_dense(ab, t, y, cj=0.0): + """Run Rust assembled Jacobian and reconstruct dense (n,n) numpy matrix.""" + jac_data = np.zeros(ab.nnz) + ab.rust_model.assemble_jacobian_csc_into(t, y, cj, ab.inputs_array, jac_data) + Jr = np.zeros((ab.n_states, ab.n_states)) + for col in range(ab.n_states): + for k in range(ab.csc_colptrs[col], ab.csc_colptrs[col + 1]): + Jr[ab.csc_rowinds[k], col] = jac_data[k] + return Jr + + +class TestRustIDAKLUDAE: + def test_dfn_set_up_succeeds(self, ab_small): + assert ab_small.n_states > 50, "DFN should yield > 50 states even at npts=5" + ids = np.asarray(ab_small.rust_model.algebraic_ids()) + jac_stats = ab_small.rust_model.jacobian_stats() + assert ids.shape == (ab_small.n_states,) + # Both differential (1) and algebraic (0) rows, and nothing else + np.testing.assert_array_equal(np.unique(ids), [0.0, 1.0]) + assert jac_stats["n_colors"] > 0 + assert jac_stats["nnz"] == ab_small.nnz + + def test_dfn_residual_parity(self, ab_small): + rng = np.random.default_rng(7) + for _ in range(3): + y = sample_state(ab_small, perturb=1e-3, seed=rng.integers(0, 1 << 32)) + rc = np.asarray( + ab_small.casadi_residual(0.0, y, ab_small.inputs_array) + ).reshape(-1) + rr = ab_small.rust_model.rhs(0.0, y, ab_small.inputs_array) + np.testing.assert_allclose(rr, rc, rtol=1e-10, atol=1e-12) + + def test_dfn_jacobian_alg_rows_parity(self, ab_small): + y = sample_state(ab_small) + Jc = casadi_jacobian_dense(ab_small, 0.0, y) + Jr = _assemble_rust_jacobian_dense(ab_small, 0.0, y) + ids = np.asarray(ab_small.rust_model.algebraic_ids()) + alg_mask = np.isclose(ids, 0.0) + np.testing.assert_allclose(Jr[alg_mask], Jc[alg_mask], rtol=1e-10, atol=1e-12) + + def test_dfn_jacobian_rhs_rows_parity(self, ab_small): + y = sample_state(ab_small) + Jc = casadi_jacobian_dense(ab_small, 0.0, y) + Jr = _assemble_rust_jacobian_dense(ab_small, 0.0, y) + ids = np.asarray(ab_small.rust_model.algebraic_ids()) + rhs_mask = np.isclose(ids, 1.0) + np.testing.assert_allclose(Jr[rhs_mask], Jc[rhs_mask], rtol=1e-10, atol=1e-12) + + def test_dfn_jacobian_nonzero_cj_merges_mass(self, ab_small): + """DFN mass is diag(algebraic_ids), so J(cj) must equal J(0) - cj * M.""" + y = sample_state(ab_small) + cj = 1.5 + J0 = _assemble_rust_jacobian_dense(ab_small, 0.0, y) + Jcj = _assemble_rust_jacobian_dense(ab_small, 0.0, y, cj=cj) + + ids = np.asarray(ab_small.rust_model.algebraic_ids()) + np.testing.assert_array_equal(np.unique(ids), [0.0, 1.0]) + M = np.diag(ids) + np.testing.assert_allclose(Jcj, J0 - cj * M, rtol=1e-12, atol=1e-12) diff --git a/packages/pybamm/tests/integration/test_rust_idaklu_outputs.py b/packages/pybamm/tests/integration/test_rust_idaklu_outputs.py new file mode 100644 index 0000000000..6571888477 --- /dev/null +++ b/packages/pybamm/tests/integration/test_rust_idaklu_outputs.py @@ -0,0 +1,69 @@ +"""Rust `CompiledModel` output expressions on a synthetic ODE.""" + +import numpy as np +import pytest + +import pybamm + +pytest.importorskip("casadi") + +try: + from pybamm.rust import CompiledModel, ExprGraph +except ImportError: + pytest.skip( + "Rust extension not available. Build with: uv sync", + allow_module_level=True, + ) + + +def _build_decay_model_with_outputs(): + """ODE: dy/dt = -k*y, output: 2*y. Uses StateVector to bypass discretization.""" + graph = ExprGraph() + rust_symbols: dict = {} + + y = pybamm.StateVector(slice(0, 1)) + k = pybamm.InputParameter("k") + rhs_sym = -k * y + output_sym = 2 * y + + rhs_expr = rhs_sym.to_rust(graph, rust_symbols) + output_expr = output_sym.to_rust(graph, rust_symbols) + + return graph, rhs_expr, output_expr + + +class TestRustCompiledModelOutputs: + def test_pycompiled_model_eval_output_matches_analytical(self): + graph, rhs_expr, output_expr = _build_decay_model_with_outputs() + + mass_data = np.ones(1) + mass_indptr = np.array([0, 1], dtype=np.int64) + mass_indices = np.array([0], dtype=np.int64) + + model = CompiledModel.from_expr( + graph, + rhs_expr, + mass_data, + mass_indptr, + mass_indices, + output_exprs=[output_expr], + ) + + assert model.n_outputs == 1 + assert [f.output_len for f in model.outputs] == [1] + + rhs = model.rhs(0.0, np.asarray([3.0]), np.asarray([1.0])) + np.testing.assert_allclose(rhs, [-3.0], atol=1e-12) + + out = model.outputs[0](0.0, np.asarray([3.0]), np.asarray([1.0])) + np.testing.assert_allclose(out, [6.0], atol=1e-12) + + def test_pycompiled_model_no_outputs_default(self): + graph = ExprGraph() + y = graph.state_vector(0, 1) + mass_data = np.ones(1) + mass_indptr = np.array([0, 1], dtype=np.int64) + mass_indices = np.array([0], dtype=np.int64) + model = CompiledModel.from_expr(graph, y, mass_data, mass_indptr, mass_indices) + assert model.n_outputs == 0 + assert [f.output_len for f in model.outputs] == [] diff --git a/packages/pybamm/tests/integration/test_rust_idaklu_sens.py b/packages/pybamm/tests/integration/test_rust_idaklu_sens.py new file mode 100644 index 0000000000..0b8f6635e6 --- /dev/null +++ b/packages/pybamm/tests/integration/test_rust_idaklu_sens.py @@ -0,0 +1,168 @@ +"""Parity test: Rust IDAKLU forward sensitivities vs CasADi.""" + +import numpy as np +import pytest + +import pybamm + +pytest.importorskip("casadi") + + +DECOUPLED_RATES = {"p0": 0.3, "p1": 1.7, "p2": 0.9} + + +def _build_decoupled_decay_model(names): + """Decoupled decays dy_i/dt = -p_i * y_i, so dy_i/dp_j = 0 for i != j.""" + model = pybamm.BaseModel() + states = [pybamm.Variable(f"y{i}") for i in range(len(names))] + model.rhs = { + y: -pybamm.InputParameter(name) * y + for y, name in zip(states, names, strict=True) + } + model.initial_conditions = dict.fromkeys(states, pybamm.Scalar(1.0)) + return model + + +def _build_coupled_model(): + """Every parameter drives every state, so no sensitivity column is sparse.""" + model = pybamm.BaseModel() + u = pybamm.Variable("u") + v = pybamm.Variable("v") + a = pybamm.InputParameter("a") + b = pybamm.InputParameter("b") + c = pybamm.InputParameter("c") + model.rhs = {u: -(a + b + c) * u + b * v, v: -(a + 2 * b + 3 * c) * v + c * u} + model.initial_conditions = {u: 1.0, v: 2.0} + return model + + +class TestRustIDAKLUSensitivities: + def test_multi_param_sensitivity_columns_land_in_their_own_parameter(self): + """A stride or ordering slip in the df/dp scatter would swap parameter columns.""" + names = list(DECOUPLED_RATES) + n_states = len(names) + t_interp = np.linspace(0, 2, 9) + + model = _build_decoupled_decay_model(names) + model.convert_to_format = "rust" + pybamm.Discretisation().process_model(model) + sol = pybamm.IDAKLUSolver(atol=1e-10, rtol=1e-10).solve( + model, + [0, 2], + inputs=DECOUPLED_RATES, + calculate_sensitivities=names, + t_interp=t_interp, + ) + + # Pin the state order the sensitivity assertions below index against. + for i, name in enumerate(names): + np.testing.assert_allclose( + sol.y[i, :], + np.exp(-DECOUPLED_RATES[name] * sol.t), + rtol=1e-6, + atol=1e-8, + err_msg=f"state {i} is not the decay driven by '{name}'", + ) + + for i, name in enumerate(names): + expected = np.zeros((len(sol.t), n_states)) + expected[:, i] = -sol.t * np.exp(-DECOUPLED_RATES[name] * sol.t) + np.testing.assert_allclose( + np.asarray(sol.sensitivities[name]).reshape(len(sol.t), n_states), + expected, + rtol=1e-5, + atol=1e-8, + err_msg=f"'{name}' sensitivity landed on the wrong state", + ) + + def test_multi_param_dense_sensitivities_match_casadi(self): + """With no structural zeros, only a value comparison catches a wrong stride.""" + inputs = {"a": 0.4, "b": 0.25, "c": 0.15} + t_interp = np.linspace(0, 3, 13) + + sols = {} + for backend in ("casadi", "rust"): + model = _build_coupled_model() + model.convert_to_format = backend + pybamm.Discretisation().process_model(model) + sols[backend] = pybamm.IDAKLUSolver(atol=1e-10, rtol=1e-10).solve( + model, + [0, 3], + inputs=inputs, + calculate_sensitivities=list(inputs), + t_interp=t_interp, + ) + + np.testing.assert_allclose( + sols["rust"].y, sols["casadi"].y, rtol=1e-6, atol=1e-9 + ) + + per_param = {} + for name in inputs: + rust_sens = np.asarray(sols["rust"].sensitivities[name]) + per_param[name] = rust_sens + np.testing.assert_allclose( + rust_sens, + np.asarray(sols["casadi"].sensitivities[name]), + rtol=1e-5, + atol=1e-8, + err_msg=f"sensitivity mismatch for parameter '{name}'", + ) + + # Parity only discriminates if the columns actually differ from each other. + for lhs, rhs in (("a", "b"), ("a", "c"), ("b", "c")): + assert not np.allclose( + per_param[lhs], per_param[rhs], rtol=1e-3, atol=1e-6 + ), f"columns '{lhs}' and '{rhs}' are too alike to detect a swap" + + +class TestRustInitialSensitivities: + """Algebraic-state sensitivities at t0, at tolerances near roundoff.""" + + INPUT = "Current function [A]" + + @staticmethod + def _model(): + parameter_values = pybamm.ParameterValues("Chen2020") + parameter_values.update({"Current function [A]": "[input]"}) + simulation = pybamm.Simulation( + pybamm.lithium_ion.DFN({"contact resistance": "true"}), + parameter_values=parameter_values, + var_pts={"x_n": 6, "x_s": 5, "x_p": 6, "r_n": 8, "r_p": 8}, + ) + simulation.build() + model = simulation.built_model + model.convert_to_format = "rust" + return model + + @pytest.mark.parametrize("newton_mode", ["auto", "full"]) + def test_algebraic_sensitivities_at_t0_match_finite_differences(self, newton_mode): + model = self._model() + solver = pybamm.IDAKLUSolver( + rtol=1e-11, atol=1e-13, options={"newton_mode": newton_mode} + ) + n_states = model.len_rhs_and_alg + algebraic = slice(model.len_rhs, n_states) + for current in (4.5, 4.875, 5.0, 5.125, 5.375, 5.5): + solution = solver.solve( + model, + [0, 1], + inputs={self.INPUT: current}, + calculate_sensitivities=True, + ) + # Stored time-major, so the first rows are the states at t0 + sensitivity = solution.sensitivities[self.INPUT][:n_states, 0] + + step = 1e-3 * current + plus, minus = ( + solver.solve(model, [0, 1], inputs={self.INPUT: current + sign * step}) + for sign in (1, -1) + ) + expected = (plus.y[algebraic, 0] - minus.y[algebraic, 0]) / (2 * step) + np.testing.assert_allclose( + sensitivity[algebraic], + expected, + rtol=0, + atol=1e-5 * np.abs(expected).max(), + err_msg=f"current {current}", + ) diff --git a/packages/pybamm/tests/integration/test_rust_model_parity.py b/packages/pybamm/tests/integration/test_rust_model_parity.py index f9d83af9fd..c92a9307a5 100644 --- a/packages/pybamm/tests/integration/test_rust_model_parity.py +++ b/packages/pybamm/tests/integration/test_rust_model_parity.py @@ -1,6 +1,7 @@ -"""CasADi parity of compiled expressions from full battery models.""" +"""CasADi parity of full battery models' compiled expressions and solves.""" import functools +from typing import NamedTuple import casadi import numpy as np @@ -32,6 +33,24 @@ def _with_inputs(): return parameter_values +def _cubic_ocp(): + parameter_values = pybamm.ParameterValues("Chen2020") + sto = np.linspace(0.0, 1.0, 200) + for electrode in ("Negative", "Positive"): + name = f"{electrode} electrode OCP [V]" + ocp = parameter_values[name] + values = [float(ocp(pybamm.Scalar(x)).evaluate()) for x in sto] + # CasADi names its spline after the interpolant, and takes only identifiers + parameter_values[name] = functools.partial( + pybamm.Interpolant, + sto, + np.array(values), + name=f"U_{electrode[0].lower()}", + interpolator="cubic", + ) + return parameter_values + + def _marcus_hush_chidsey(): parameter_values = pybamm.ParameterValues("Chen2020") parameter_values.update( @@ -66,6 +85,7 @@ def _marcus_hush_chidsey(): "lead-acid Full": (pybamm.lead_acid.Full, {}, None, {}), "SPM drive cycle": (pybamm.lithium_ion.SPM, {}, _drive_cycle, {}), "SPM with inputs": (pybamm.lithium_ion.SPM, {}, _with_inputs, _INPUTS), + "SPM cubic OCP": (pybamm.lithium_ion.SPM, {}, _cubic_ocp, {}), "SPM Marcus-Hush-Chidsey": ( pybamm.lithium_ion.SPM, {"intercalation kinetics": "Marcus-Hush-Chidsey"}, @@ -75,6 +95,50 @@ def _marcus_hush_chidsey(): "Thevenin": (pybamm.equivalent_circuit.Thevenin, {}, None, {}), } +# The solve's own tolerances, tight so the backends agree to well within the asserts +_SOLVER_TOLERANCES = {"rtol": 1e-8, "atol": 1e-10} +_T_INTERP = np.linspace(0, 3600, 61) +_CASES_WITH_INPUTS = [name for name, (*_, inputs) in _MODELS.items() if inputs] +# The cases whose discharge ends on a termination event +_EVENT_CASES = { + "DFN SEI and plating", + "MPM", + "SPM drive cycle", + "SPM with inputs", + "SPM cubic OCP", + "SPM Marcus-Hush-Chidsey", + "Thevenin", +} + + +def _solve(name, convert_to_format, *, output_variables=None, **kwargs): + """Solve case ``name`` in ``convert_to_format`` to its end or its event.""" + model_class, options, parameter_values, inputs = _MODELS[name] + model = model_class(options) + model.convert_to_format = convert_to_format + simulation = pybamm.Simulation( + model, + parameter_values=None if parameter_values is None else parameter_values(), + solver=pybamm.IDAKLUSolver( + output_variables=output_variables, **_SOLVER_TOLERANCES + ), + ) + solution = simulation.solve([0, 3600], inputs=inputs, t_interp=_T_INTERP, **kwargs) + return simulation, solution + + +def _states(solution): + """The solution's states, one column per time.""" + return np.hstack(solution.all_ys) + + +class _Case(NamedTuple): + name: str + model: pybamm.BaseModel + inputs: dict + points: list + solution: pybamm.Solution + def _casadi_functions(exprs, n, input_names): """CasADi functions of ``(t, y, p)`` for the values of ``exprs`` and, when @@ -110,25 +174,28 @@ def _assert_close(actual, expected, scale, message): @pytest.fixture(scope="module", params=list(_MODELS)) def case(request): - """A built model, its inputs, and states along its discharge with their times.""" - model_class, options, parameter_values, inputs = _MODELS[request.param] - model = model_class(options) - # The reference states come from CasADi, whatever the default format - model.convert_to_format = "casadi" - sim = pybamm.Simulation( - model, - parameter_values=None if parameter_values is None else parameter_values(), - ) - solution = sim.solve([0, 3600], inputs=inputs) + """A built model and its CasADi solve, with states along it and their times.""" + name = request.param + # The reference comes from CasADi, whatever the default format + simulation, solution = _solve(name, "casadi") # Start, middle and end: states that start at zero move, and late branches open indices = (0, len(solution.t) // 2, -1) - points = [(solution.t[i], np.asarray(solution.y[:, i]).ravel()) for i in indices] - return sim.built_model, inputs, points + states = _states(solution) + points = [(solution.t[i], states[:, i]) for i in indices] + return _Case(name, simulation.built_model, _MODELS[name][3], points, solution) + + +def _assert_states_close(actual, expected): + """Assert each state agrees to 1e-5 of its largest magnitude along the solve, + plus 1e-8, as a state near zero is held only to the solver's atol.""" + assert actual.shape == expected.shape + scale = np.max(np.abs(expected), axis=1, keepdims=True) + 1e-3 + np.testing.assert_allclose(actual / scale, expected / scale, rtol=0, atol=1e-5) class TestModelParity: def test_equations_match_casadi(self, case): - model, inputs, points = case + model, inputs, points = case.model, case.inputs, case.points # The solver evaluates each equation against the full state vector n = model.concatenated_initial_conditions.size equations = { @@ -185,7 +252,7 @@ def test_equations_match_casadi(self, case): ) def test_variables_and_events_match_casadi(self, case): - model, inputs, points = case + model, inputs, points = case.model, case.inputs, case.points n = model.concatenated_initial_conditions.size outputs = {name: model.get_processed_variable(name) for name in model.variables} outputs.update( @@ -229,6 +296,74 @@ def output_jacobians(name): ) _assert_close(actual, desired, terms, f"{name} at t={t}") + def test_the_dfn_reads_reg_power(self): + # Guards that the cases still reach the Rust RegPower lowering + model_class, options, _, _ = _MODELS["DFN"] + simulation = pybamm.Simulation(model_class(options)) + simulation.build() + model = simulation.built_model + equations = (model.concatenated_rhs, model.concatenated_algebraic) + assert any( + equation.has_symbol_of_classes(pybamm.expression_tree.functions.RegPower) + for equation in equations + ) + + +class TestSolveParity: + def test_the_cases_end_where_expected(self, case): + # Guards that the solves still compare termination events + ends_on_an_event = case.solution.termination.startswith("event") + assert ends_on_an_event == (case.name in _EVENT_CASES) + + def test_solve_matches_casadi(self, case): + _, solution = _solve(case.name, "rust") + reference = case.solution + assert solution.termination == reference.termination + # A 1% change in the solve's rtol moves the drive cycle's event by 1.4e-7 of its + # time, so the backends' rounding differences can move it as far + np.testing.assert_allclose(solution.t[-1], reference.t[-1], rtol=1e-6) + _assert_states_close(_states(solution), _states(reference)) + np.testing.assert_allclose( + solution["Voltage [V]"](reference.t[:-1]), + reference["Voltage [V]"](reference.t[:-1]), + rtol=0, + atol=1e-7, + ) + + def test_output_variables_match_casadi(self, case): + # Rust evaluates these in the solver; CasADi's come from its full states + names = ["Voltage [V]", "Current [A]"] + _, solution = _solve(case.name, "rust", output_variables=names) + reference = case.solution + assert solution.termination == reference.termination + for name in names: + np.testing.assert_allclose( + solution[name](reference.t[:-1]), + reference[name](reference.t[:-1]), + rtol=1e-7, + atol=1e-9, + err_msg=name, + ) + + @pytest.mark.parametrize("name", _CASES_WITH_INPUTS) + def test_sensitivities_match_casadi(self, name): + sensitivities = { + convert_to_format: _solve( + name, convert_to_format, calculate_sensitivities=True + )[1].sensitivities + for convert_to_format in ("casadi", "rust") + } + for input_name in _MODELS[name][3]: + reference = np.asarray(sensitivities["casadi"][input_name]) + scale = np.max(np.abs(reference)) + 1e-12 + np.testing.assert_allclose( + np.asarray(sensitivities["rust"][input_name]) / scale, + reference / scale, + rtol=0, + atol=1e-5, + err_msg=input_name, + ) + class TestSPMParity: @pytest.fixture(scope="class") diff --git a/packages/pybamm/tests/shared.py b/packages/pybamm/tests/shared.py index 7306ff5182..ba0f08253e 100644 --- a/packages/pybamm/tests/shared.py +++ b/packages/pybamm/tests/shared.py @@ -437,16 +437,19 @@ def get_base_model_with_battery_geometry(**kwargs): return model -def get_broken_input_model(): +def get_broken_input_model(convert_to_format=None): """Return the discretised model ``dv/dt = -sqrt(k) * v``. - Its residual is NaN for any input ``k < 0``, whatever the state. + Its residual is NaN for any input ``k < 0``, whatever the state. Without + ``convert_to_format`` it keeps the model's default format. """ model = pybamm.BaseModel() v = pybamm.Variable("v") model.rhs = {v: -pybamm.sqrt(pybamm.InputParameter("k")) * v} model.initial_conditions = {v: 1.0} model.variables = {"v": v} + if convert_to_format is not None: + model.convert_to_format = convert_to_format pybamm.Discretisation().process_model(model) return model @@ -632,3 +635,48 @@ def concatenated_states(states): if isinstance(states[0], casadi.DM | casadi.MX): return casadi.horzcat(*states) return np.hstack(states) + + +POUCH_OPTIONS = {"current collector": "potential pair", "dimensionality": 2} +POUCH_PTS = {"x_n": 4, "x_s": 4, "x_p": 4, "r_n": 4, "r_p": 4, "y": 8, "z": 8} + + +def build_rust_model(model, var_pts=None): + """Set up `model` on the Rust backend, returning its built model and core.""" + model.convert_to_format = "rust" + sim = pybamm.Simulation(model, var_pts=var_pts) + sim.build() + sim.solver.set_up(sim.built_model, inputs=[{}]) + return sim.built_model, sim.solver._setup["rust_model"] + + +def dense_rust_jacobian(built_model, rust_model): + """Assemble the Rust merged CSC at `y0` and scatter it dense.""" + import numpy as np + from scipy import sparse + + n = built_model.len_rhs_and_alg + y = np.ascontiguousarray(np.asarray(built_model.y0_list[0]).flatten().astype(float)) + jac_data = np.zeros(rust_model.nnz) + rust_model.assemble_jacobian_csc_into(0.0, y, 0.0, np.array([]), jac_data) + colptr, rowind = rust_model.csc_sparsity_pattern() + dense = sparse.csc_matrix( + (jac_data, np.asarray(rowind), np.asarray(colptr)), shape=(n, n) + ).toarray() + return y, dense + + +def dense_casadi_jacobian(model, y, var_pts=None): + """The same Jacobian off the CasADi backend, for a value comparison.""" + import casadi + import numpy as np + + model.convert_to_format = "casadi" + sim = pybamm.Simulation(model, var_pts=var_pts) + sim.build() + sim.solver.set_up(sim.built_model, inputs=[{}]) + return np.array( + sim.built_model.jac_rhs_algebraic_eval( + casadi.DM(0.0), casadi.DM(y), casadi.DM(np.zeros((0, 1))) + ) + ) diff --git a/packages/pybamm/tests/unit/test_experiments/test_simulation_with_experiment.py b/packages/pybamm/tests/unit/test_experiments/test_simulation_with_experiment.py index e96276c8c4..2719417dd3 100644 --- a/packages/pybamm/tests/unit/test_experiments/test_simulation_with_experiment.py +++ b/packages/pybamm/tests/unit/test_experiments/test_simulation_with_experiment.py @@ -5,6 +5,7 @@ import re from datetime import datetime from types import SimpleNamespace +from typing import NamedTuple import casadi import numpy as np @@ -19,25 +20,67 @@ def _default_timespan(self, value): return 1 -def _unified_rhs_jac_n_instructions(unique_step_strings): - """rhs_algebraic and jacobian top-function instruction counts for a unified-mode - SPM experiment with the given distinct steps.""" +class _TopFunctionSize(NamedTuple): + """A unified-model top function's instruction count and its control-flow nodes.""" + + n_instructions: int + n_control_flow: int + + @property + def always_run_work(self) -> int: + return self.n_instructions - self.n_control_flow + + +def _casadi_switch_calls(fn): + """How many of ``fn``'s instructions call another function; its Switch is one.""" + return sum( + 1 for k in range(fn.n_instructions()) if fn.instruction_id(k) == casadi.OP_CALL + ) + + +def _unified_rhs_jac_n_instructions(unique_step_strings, convert_to_format): + """Unified-model residual and Jacobian top-function sizes for one backend.""" experiment = pybamm.Experiment([tuple(unique_step_strings)]) + model = pybamm.lithium_ion.SPM() + model.convert_to_format = convert_to_format sim = pybamm.Simulation( - pybamm.lithium_ion.SPM(), + model, experiment=experiment, solver=pybamm.IDAKLUSolver(), experiment_model_mode="unified", ) sim.solve() assert sim._experiment_uses_unified_model - model = sim._built_experiment_model + if convert_to_format == "casadi": + model = sim._built_experiment_model + return tuple( + _TopFunctionSize(fn.n_instructions(), _casadi_switch_calls(fn)) + for fn in (model.rhs_algebraic_eval, model.jac_rhs_algebraic_eval) + ) + + model = sim._built_experiment_solver._setup["rust_model"] + stats = model.jacobian_stats() return ( - model.rhs_algebraic_eval.n_instructions(), - model.jac_rhs_algebraic_eval.n_instructions(), + _TopFunctionSize(model.rhs.n_instructions, model.rhs.n_dispatches), + _TopFunctionSize( + stats["split_eval_total_instructions"], stats["split_eval_dispatch_count"] + ), ) +def _assert_no_always_run_growth(base, extended, what): + """Assert adding control modes did not grow the always-run tape.""" + assert extended.always_run_work <= base.always_run_work, ( + f"{what} grew the always-run tape: {base} -> {extended}" + ) + + +def _native_jacobian_instruction_count(sim): + """Instruction count for IDAKLU's Rust-native Jacobian artifact.""" + model = sim._built_experiment_solver._setup["rust_model"] + return model.jacobian_stats()["split_eval_total_instructions"] + + def _largest_generated_fn_lines(fn): """Body-line count of the largest ``casadi_fN`` in ``fn``'s generated C.""" gen = casadi.CodeGenerator("probe", {"with_header": False}) @@ -666,37 +709,57 @@ def max_conditional_branches(model): assert set(indices) == set(range(1, n_unique + 1)) assert indices == [(i % n_unique) + 1 for i in range(len(indices))] - def test_unified_switch_top_functions_flat_in_unique_steps(self): - # Per-branch dispatch keeps the top rhs/jac flat in unique step count. + @pytest.mark.parametrize("convert_to_format", ["casadi", "rust"]) + def test_unified_switch_top_functions_flat_in_unique_steps(self, convert_to_format): rhs_1, jac_1 = _unified_rhs_jac_n_instructions( - [f"Discharge at {0.4 + 0.1 * i:.2f}C for 10 s" for i in range(1)] + [f"Discharge at {0.4 + 0.1 * i:.2f}C for 10 s" for i in range(1)], + convert_to_format, ) rhs_8, jac_8 = _unified_rhs_jac_n_instructions( - [f"Discharge at {0.4 + 0.1 * i:.2f}C for 10 s" for i in range(8)] + [f"Discharge at {0.4 + 0.1 * i:.2f}C for 10 s" for i in range(8)], + convert_to_format, ) - assert rhs_8 <= rhs_1 + 2, ( - f"unified rhs top function grows with unique steps: {rhs_1} -> {rhs_8}" + _assert_no_always_run_growth(rhs_1, rhs_8, "8 unique steps in the rhs") + _assert_no_always_run_growth(jac_1, jac_8, "8 unique steps in the jac") + + @pytest.mark.parametrize("convert_to_format", ["casadi", "rust"]) + def test_unified_active_branch_independent_of_other_modes(self, convert_to_format): + rhs_cc, jac_cc = _unified_rhs_jac_n_instructions( + ["Discharge at 1C for 10 s"], convert_to_format ) - assert jac_8 <= jac_1 + 2, ( - f"unified jac top function grows with unique steps: {jac_1} -> {jac_8}" + rhs_multi, jac_multi = _unified_rhs_jac_n_instructions( + [ + "Discharge at 1C for 10 s", + "Charge at 0.5C until 4.2 V", + "Hold at 4.2 V until C/50", + ], + convert_to_format, ) + _assert_no_always_run_growth(rhs_cc, rhs_multi, "adding modes to the rhs") + _assert_no_always_run_growth(jac_cc, jac_multi, "adding modes to the jac") - def test_unified_active_branch_independent_of_other_modes(self): - # Each mode is a separate branch function, so adding modes doesn't grow the top - # rhs/jac and inactive modes aren't evaluated during an active step. - rhs_cc, jac_cc = _unified_rhs_jac_n_instructions(["Discharge at 1C for 10 s"]) + @pytest.mark.parametrize("convert_to_format", ["casadi", "rust"]) + def test_unified_voltage_and_power_modes_share_no_active_work( + self, convert_to_format + ): + # Voltage and power both need the voltage expression, so CSE shares that + # cone; without privatisation it is unowned and stays in the always-run tape. + rhs_cc, jac_cc = _unified_rhs_jac_n_instructions( + ["Discharge at 1C for 10 s"], convert_to_format + ) rhs_multi, jac_multi = _unified_rhs_jac_n_instructions( [ "Discharge at 1C for 10 s", - "Charge at 0.5C until 4.2 V", "Hold at 4.2 V until C/50", - ] + "Discharge at 5 W for 10 s", + ], + convert_to_format, ) - assert rhs_multi <= rhs_cc + 2, ( - f"adding modes grew the rhs top function: {rhs_cc} -> {rhs_multi}" + _assert_no_always_run_growth( + rhs_cc, rhs_multi, "voltage+power modes in the rhs" ) - assert jac_multi <= jac_cc + 2, ( - f"adding modes grew the jac top function: {jac_cc} -> {jac_multi}" + _assert_no_always_run_growth( + jac_cc, jac_multi, "voltage+power modes in the jac" ) def test_unified_switch_matches_legacy_voltage(self): @@ -723,15 +786,14 @@ def voltage(mode): assert voltage("unified") == pytest.approx(voltage("legacy"), abs=1e-6) - def test_unified_control_row_jacobian_is_sparse(self): - # CasADi declares a Switch's jacobian structurally dense, so the control - # equation would otherwise be a full-bandwidth row and balloon KLU work. The - # solver projects it back onto the true (union-of-branches) sparsity; assert no - # jacobian row spans the full bandwidth. + @pytest.mark.parametrize("convert_to_format", ["casadi", "rust"]) + def test_unified_control_row_jacobian_is_sparse(self, convert_to_format): from collections import Counter + model = pybamm.lithium_ion.DFN() + model.convert_to_format = convert_to_format sim = pybamm.Simulation( - pybamm.lithium_ion.DFN(), + model, experiment=pybamm.Experiment( [("Discharge at 1C until 3.3 V", "Hold at 3.3 V until C/20")] ), @@ -739,9 +801,16 @@ def test_unified_control_row_jacobian_is_sparse(self): experiment_model_mode="unified", ) sim.solve() - sparsity = sim._built_experiment_model.jac_rhs_algebraic_eval.sparsity_out(0) - n = sparsity.size2() - densest_row_nnz = max(Counter(sparsity.get_triplet()[0]).values()) + if convert_to_format == "casadi": + jacobian = sim._built_experiment_model.jac_rhs_algebraic_eval + sparsity = jacobian.sparsity_out(0) + rows = sparsity.get_triplet()[0] + n = sparsity.size2() + else: + model = sim._built_experiment_solver._setup["rust_model"] + _, rows = model.csc_sparsity_pattern() + n = model.rhs.n_states + densest_row_nnz = max(Counter(rows).values()) assert densest_row_nnz <= n // 2, ( f"a jacobian row has {densest_row_nnz}/{n} nonzeros (near full bandwidth); " "the control-row union-sparsity projection did not take effect" @@ -793,27 +862,30 @@ def test_non_unified_model_jacobian_is_plain_casadi(self): model.build_casadi_jacobian(expr, x), casadi.jacobian(expr, x), 20 ) - def test_unified_aot_compile_bounded_in_unique_steps(self): - # -O3 is superlinear in single-function size, so per-branch dispatch must keep - # the largest generated jac function flat as unique steps grow. Deterministic. - def largest_jac_fn_lines(n): + @pytest.mark.parametrize("convert_to_format", ["casadi", "rust"]) + def test_unified_aot_compile_bounded_in_unique_steps(self, convert_to_format): + def jacobian_size(n): ops = [f"Discharge at {0.4 + 0.1 * i:.2f}C for 10 s" for i in range(n)] + model = pybamm.lithium_ion.SPMe() + model.convert_to_format = convert_to_format sim = pybamm.Simulation( - pybamm.lithium_ion.SPMe(), + model, experiment=pybamm.Experiment([tuple(ops)]), solver=pybamm.IDAKLUSolver(), experiment_model_mode="unified", ) sim.solve() - return _largest_generated_fn_lines( - sim._built_experiment_model.jac_rhs_algebraic_eval - ) + if convert_to_format == "casadi": + return _largest_generated_fn_lines( + sim._built_experiment_model.jac_rhs_algebraic_eval + ) + return _native_jacobian_instruction_count(sim) - big_2 = largest_jac_fn_lines(2) - big_8 = largest_jac_fn_lines(8) + big_2 = jacobian_size(2) + big_8 = jacobian_size(8) assert big_8 <= big_2 + 50, ( - "largest unified jac function grew with unique steps: " - f"{big_2} -> {big_8} lines (per-branch dispatch should keep it flat)" + "unified Jacobian compilation grew with equivalent steps: " + f"{big_2} -> {big_8}" ) def test_experiment_state_mapper_has_full_state_size_for_2d_current_collector(self): @@ -1241,8 +1313,15 @@ def test_skip_ok(self): sol = sim.solve() assert sol.termination == "Event exceeded in initial conditions" - def test_skip_ok_with_multiple_infeasible_terminations_in_unified_model(self): + @pytest.mark.parametrize( + ("convert_to_format", "solver_class"), + [("casadi", pybamm.CasadiSolver), ("rust", pybamm.IDAKLUSolver)], + ) + def test_skip_ok_with_multiple_infeasible_terminations_in_unified_model( + self, convert_to_format, solver_class + ): model = pybamm.lithium_ion.SPM() + model.convert_to_format = convert_to_format experiment = pybamm.Experiment( [ pybamm.step.Current( @@ -1256,7 +1335,7 @@ def test_skip_ok_with_multiple_infeasible_terminations_in_unified_model(self): sim = pybamm.Simulation( model, experiment=experiment, - solver=pybamm.CasadiSolver(), + solver=solver_class(), experiment_model_mode="unified", ) diff --git a/packages/pybamm/tests/unit/test_rust_boundary_validation.py b/packages/pybamm/tests/unit/test_rust_boundary_validation.py index 8419cee505..5f34bd127a 100644 --- a/packages/pybamm/tests/unit/test_rust_boundary_validation.py +++ b/packages/pybamm/tests/unit/test_rust_boundary_validation.py @@ -5,7 +5,7 @@ import numpy as np import pytest -from pybamm.rust import ExprGraph +from pybamm.rust import CompiledModel, ExprGraph class TestStateVectorValidation: @@ -308,6 +308,277 @@ def test_an_unsupported_graph_raises(self, tmp_path): assert not (tmp_path / "dag.bin").exists() +def _identity_mass(n): + return ( + np.ones(n), + np.arange(n + 1, dtype=np.int64), + np.arange(n, dtype=np.int64), + ) + + +def _algebraic_mass(n): + """CSR triple for the ``n x n`` zero matrix: every state algebraic.""" + return ( + np.zeros(0), + np.zeros(n + 1, dtype=np.int64), + np.zeros(0, dtype=np.int64), + ) + + +class TestCompiledModelWidthValidation: + """``sens_param_indices`` are registration indices; ``n_inputs`` is packed width.""" + + @staticmethod + def _graph_with_a_vector_input(): + # Registration indices 0 ("wide", width 3) and 1 ("k"): packed width 4. + g = ExprGraph() + y = g.state_vector(0, 2) + g.input_parameter("wide", 3) + k = g.input_parameter("k") + return g, g.mul(k, y) + + def test_sens_index_past_the_last_input_raises(self): + g, rhs = self._graph_with_a_vector_input() + data, indptr, indices = _identity_mass(2) + # Inside the packed width (4), past the last registration index (1). + for bad in (2, 3): + with pytest.raises(ValueError, match=r"names no input parameter"): + CompiledModel.from_expr( + g, + rhs, + data, + indptr, + indices, + sens_param_indices=[bad], + ) + + def test_sens_index_naming_a_real_input_still_works(self): + g, rhs = self._graph_with_a_vector_input() + data, indptr, indices = _identity_mass(2) + model = CompiledModel.from_expr( + g, rhs, data, indptr, indices, sens_param_indices=[1] + ) + assert model.n_sens_params == 1 + + def test_sens_index_naming_a_vector_input_raises(self): + g, rhs = self._graph_with_a_vector_input() + data, indptr, indices = _identity_mass(2) + with pytest.raises(ValueError, match=r"names an input of width 3"): + CompiledModel.from_expr( + g, rhs, data, indptr, indices, sens_param_indices=[0] + ) + + def test_repeated_sens_index_raises(self): + g, rhs = self._graph_with_a_vector_input() + data, indptr, indices = _identity_mass(2) + with pytest.raises(ValueError, match=r"more than once"): + CompiledModel.from_expr( + g, rhs, data, indptr, indices, sens_param_indices=[1, 1] + ) + + def test_a_model_takes_every_input_the_graph_registers(self): + # "wide" is registered but never read, and still takes its packed slots. + g = ExprGraph() + y = g.state_vector(0, 2) + k = g.input_parameter("k") + g.input_parameter("wide", 3) + data, indptr, indices = _identity_mass(2) + model = CompiledModel.from_expr(g, g.mul(k, y), data, indptr, indices) + assert model.n_inputs == 4 + assert model.rhs.input_names == ("k", "wide") + + def test_a_rhs_reading_y_dot_raises(self): + g = ExprGraph() + rhs = g.sub(g.state_vector(0, 2), g.state_vector_dot(0, 2)) + data, indptr, indices = _identity_mass(2) + with pytest.raises(ValueError, match=r"reads y_dot"): + CompiledModel.from_expr(g, rhs, data, indptr, indices) + + def test_n_states_below_the_residual_extent_raises(self): + # n_states is inferred from the mass matrix, so a 2x2 mass declares 2. + g = ExprGraph() + wide = g.state_vector(0, 8) + data, indptr, indices = _identity_mass(2) + with pytest.raises(ValueError, match=r"below the .* state"): + CompiledModel.from_expr(g, g.neg(wide), data, indptr, indices) + + def test_output_below_the_declared_state_count_raises(self): + g = ExprGraph() + narrow = g.state_vector(0, 2) + wide = g.state_vector(0, 8) + data, indptr, indices = _identity_mass(2) + with pytest.raises(ValueError, match=r"below the .* state"): + CompiledModel.from_expr( + g, g.neg(narrow), data, indptr, indices, output_exprs=[wide] + ) + + def test_algebraic_variable_index_outside_the_state_count_raises(self): + g = ExprGraph() + y = g.state_vector(0, 2) + data, indptr, indices = _algebraic_mass(2) + with pytest.raises(ValueError, match=r"algebraic variable index 2"): + CompiledModel.from_expr( + g, + g.neg(y), + data, + indptr, + indices, + algebraic_expr=g.neg(y), + algebraic_variable_indices=[0, 2], + ) + + @pytest.mark.parametrize("given", [[1, 0], [1, 1], [0, 0, 1]]) + def test_unordered_or_repeated_algebraic_variable_indices_raise(self, given): + g = ExprGraph() + y = g.state_vector(0, 2) + data, indptr, indices = _algebraic_mass(2) + with pytest.raises(ValueError, match=r"strictly ascending"): + CompiledModel.from_expr( + g, + g.neg(y), + data, + indptr, + indices, + algebraic_expr=g.neg(y), + algebraic_variable_indices=given, + ) + + def test_non_square_algebraic_block_raises(self): + # The C++ Newton drivers factorise the block as n_alg x n_alg. + g = ExprGraph() + y = g.state_vector(0, 2) + data, indptr, indices = _algebraic_mass(2) + with pytest.raises(ValueError, match=r"2 residual rows but 1 variable"): + CompiledModel.from_expr( + g, + g.neg(y), + data, + indptr, + indices, + algebraic_expr=g.neg(y), + algebraic_variable_indices=[0], + ) + + def test_algebraic_variable_index_naming_a_differential_state_raises(self): + g = ExprGraph() + y = g.state_vector(0, 2) + data, indptr, indices = _identity_mass(2) + with pytest.raises(ValueError, match=r"index 0 names a differential state"): + CompiledModel.from_expr( + g, + g.neg(y), + data, + indptr, + indices, + algebraic_expr=g.neg(y), + algebraic_variable_indices=[0, 1], + ) + + def test_algebraic_variable_indices_without_an_algebraic_expr_raise(self): + g = ExprGraph() + y = g.state_vector(0, 2) + data, indptr, indices = _algebraic_mass(2) + with pytest.raises(ValueError, match=r"need an algebraic_expr"): + CompiledModel.from_expr( + g, g.neg(y), data, indptr, indices, algebraic_variable_indices=[0, 1] + ) + + def test_event_below_the_declared_state_count_raises(self): + g = ExprGraph() + narrow = g.state_vector(0, 2) + wide = g.state_vector(0, 8) + data, indptr, indices = _identity_mass(2) + with pytest.raises(ValueError, match=r"below the .* state"): + CompiledModel.from_expr( + g, g.neg(narrow), data, indptr, indices, event_exprs=[wide] + ) + + def test_a_residual_shorter_than_the_state_count_raises(self): + g = ExprGraph() + data, indptr, indices = _identity_mass(2) + with pytest.raises(ValueError, match=r"residual has 1 rows but n_states=2"): + CompiledModel.from_expr(g, g.scalar(1.0), data, indptr, indices) + + +class TestCompiledModelEvalValidation: + """The direct evaluators reject lengths that evaluation would index past.""" + + @staticmethod + def _model(): + g = ExprGraph() + k = g.input_parameter("k") + return CompiledModel.from_expr( + g, g.mul(k, g.state_vector(0, 2)), *_identity_mass(2) + ) + + @pytest.mark.parametrize( + ("y", "yp", "inputs", "name"), + [ + (np.zeros(0), np.zeros(2), np.ones(1), "y"), + (np.zeros(3), np.zeros(2), np.ones(1), "y"), + (np.zeros(2), np.zeros(1), np.ones(1), "yp"), + (np.zeros(2), np.zeros(2), np.ones(0), "inputs"), + (np.zeros(2), np.zeros(2), np.ones(2), "inputs"), + ], + ) + def test_residual_rejects_a_wrong_length(self, y, yp, inputs, name): + model = self._model() + with pytest.raises(ValueError, match=rf"expected {name} of length"): + model.eval_residual(0.0, y, yp, inputs) + with pytest.raises(ValueError, match=rf"expected {name} of length"): + model.eval_residual_into(0.0, y, yp, inputs, np.zeros(2)) + + @pytest.mark.parametrize( + ("y", "inputs", "name"), + [ + (np.zeros(1), np.ones(1), "y"), + (np.zeros(2), np.ones(0), "inputs"), + ], + ) + def test_jacobian_assembly_rejects_a_wrong_length(self, y, inputs, name): + model = self._model() + with pytest.raises(ValueError, match=rf"expected {name} of length"): + model.assemble_jacobian_csc_into(0.0, y, 1.0, inputs, np.zeros(model.nnz)) + + def test_a_non_contiguous_state_raises(self): + model = self._model() + with pytest.raises(TypeError, match=r"contiguous"): + model.eval_residual(0.0, np.arange(4.0)[::2], np.zeros(2), np.ones(1)) + + def test_a_read_only_output_buffer_raises(self): + model = self._model() + output = np.zeros(2) + output.flags.writeable = False + jac_data = np.zeros(model.nnz) + jac_data.flags.writeable = False + with pytest.raises(ValueError, match=r"output must be a writeable array"): + model.eval_residual_into(0.0, np.ones(2), np.zeros(2), np.ones(1), output) + with pytest.raises(ValueError, match=r"jac_data must be a writeable array"): + model.assemble_jacobian_csc_into(0.0, np.ones(2), 1.0, np.ones(1), jac_data) + + def test_an_output_buffer_sharing_memory_with_an_input_raises(self): + model = self._model() + y = np.ones(2) + with pytest.raises(ValueError, match=r"output must be a writeable array"): + model.eval_residual_into(0.0, y, np.zeros(2), np.ones(1), y) + jac_data = np.ones(model.nnz) + with pytest.raises(ValueError, match=r"jac_data must be a writeable array"): + model.assemble_jacobian_csc_into( + 0.0, jac_data[:2], 1.0, np.ones(1), jac_data + ) + + output = np.zeros(2) + model.eval_residual_into(0.0, y, np.zeros(2), np.array([3.0]), output) + np.testing.assert_allclose(output, [-3.0, -3.0]) + + def test_matching_lengths_still_evaluate(self): + model = self._model() + residual = model.eval_residual( + 0.0, np.array([1.0, 2.0]), np.zeros(2), np.array([3.0]) + ) + np.testing.assert_allclose(residual, [-3.0, -6.0]) + + class TestInputRegistration: def test_re_registering_a_name_reuses_its_slot(self): g = ExprGraph() @@ -337,3 +608,17 @@ def test_re_registering_a_name_at_another_width_raises(self): ValueError, match=r"'k' re-registered with width 3.*width 2" ): g.input_parameter("k", 3) + + def test_a_pickled_graph_rebuilds_its_registry_from_the_arena(self): + g = ExprGraph() + y = g.state_vector(0, 2) + g.input_parameter("wide", 3) + k = g.input_parameter("k") + data, indptr, indices = _identity_mass(2) + model = CompiledModel.from_expr(g, g.mul(k, y), data, indptr, indices) + + restored = pickle.loads(pickle.dumps(g)) + assert restored.n_inputs() == g.n_inputs() == model.n_inputs + # The restored registry still knows its names rather than restarting at index 0. + restored.input_parameter("wide", 3) + assert restored.n_inputs() == 4 diff --git a/packages/pybamm/tests/unit/test_rust_extension_loading.py b/packages/pybamm/tests/unit/test_rust_extension_loading.py index e5b51b1540..25545f5262 100644 --- a/packages/pybamm/tests/unit/test_rust_extension_loading.py +++ b/packages/pybamm/tests/unit/test_rust_extension_loading.py @@ -5,4 +5,5 @@ class TestFacadeExports: def test_core_is_importable_through_the_facade(self): + assert pybamm.rust.CompiledModel is not None assert pybamm.rust.ExprGraph is not None diff --git a/packages/pybamm/tests/unit/test_rust_function_api.py b/packages/pybamm/tests/unit/test_rust_function_api.py index 4903db5990..0d96717124 100644 --- a/packages/pybamm/tests/unit/test_rust_function_api.py +++ b/packages/pybamm/tests/unit/test_rust_function_api.py @@ -777,6 +777,150 @@ def reported(n_branches): assert reported(2) == reported(6) +class TestCompiledModelBundle: + def _setup(self, sens_param_indices=()): + from pybamm.rust import CompiledModel + + g = ExprGraph() + a = g.input_parameter("a") + y0 = g.state_vector(0, 1) + y1 = g.state_vector(1, 2) + rhs = g.concat([g.mul(a, y1), g.neg(y0)]) + out = g.mul(y0, y1) + event = g.sub(y0, g.scalar(10.0)) + mass = np.array([1.0, 1.0]) + indptr = np.array([0, 1, 2], dtype=np.int64) + indices = np.array([0, 1], dtype=np.int64) + model = CompiledModel.from_expr( + g, + rhs, + mass, + indptr, + indices, + sens_param_indices=list(sens_param_indices), + output_exprs=[out], + event_exprs=[event], + ) + return g, model + + def _check_views(self, model, p): + y = np.array([1.0, 2.0]) + np.testing.assert_array_equal(model.rhs(0.0, y, p), [6.0, -1.0]) + np.testing.assert_array_equal(model.outputs[0](0.0, y, p), [2.0]) + np.testing.assert_array_equal(model.events[0](0.0, y, p), [-9.0]) + np.testing.assert_allclose( + model.jacobian(0.0, y, p).toarray(), [[0.0, 3.0], [-1.0, 0.0]] + ) + + def test_views_keep_the_inputs_the_model_was_compiled_with(self): + # A later lowering, such as Solution.observe, can register inputs on the graph. + g, model = self._setup() + g.input_parameter("late") + self._check_views(model, np.array([3.0])) + assert model.rhs.input_names == ("a",) + with pytest.raises(ValueError, match=r"rhs: expected 1 input values"): + model.rhs(0.0, np.array([1.0, 2.0]), np.array([3.0, 0.0])) + restored = pickle.loads(pickle.dumps(model.rhs)) + assert restored.input_names == ("a",) + np.testing.assert_array_equal( + restored(0.0, np.array([1.0, 2.0]), np.array([3.0])), [6.0, -1.0] + ) + + def test_a_late_input_survives_a_pickle_round_trip(self): + g, model = self._setup(sens_param_indices=[0]) + g.input_parameter("late") + restored = pickle.loads(pickle.dumps(model)) + assert restored.n_inputs == 1 + assert restored.n_sens_params == 1 + assert restored.__reduce__()[1][1:] == model.__reduce__()[1][1:] + self._check_views(restored, np.array([3.0])) + + def test_rebuild_refuses_a_node_count_that_misses_a_root_or_the_graph(self): + g, model = self._setup() + rebuild, args = model.__reduce__() + before, after = args[:8], args[9:] + with pytest.raises(ValueError, match=r"root \d+ is not among the 1 nodes"): + rebuild(*before, 1, *after) + too_many = g.n_nodes + 1 + with pytest.raises( + ValueError, match=rf"n_nodes={too_many} exceeds the graph's {g.n_nodes}" + ): + rebuild(*before, too_many, *after) + + def test_rhs_view(self): + _, model = self._setup() + f = model.rhs + y = np.array([1.0, 2.0]) + p = np.array([3.0]) + np.testing.assert_array_equal(f(0.0, y, p), [6.0, -1.0]) + assert f.n_states == 2 + + def test_jacobian_view_is_pure_df_dy(self): + _, model = self._setup() + J = model.jacobian + mat = J(0.0, np.array([1.0, 2.0]), np.array([3.0])) + # df/dy = [[0, a], [-1, 0]] — no mass, no cj + np.testing.assert_allclose(mat.toarray(), [[0.0, 3.0], [-1.0, 0.0]]) + + def test_outputs_and_events_views(self): + _, model = self._setup() + (out_fn,) = model.outputs + (event_fn,) = model.events + y = np.array([1.0, 2.0]) + p = np.array([3.0]) + np.testing.assert_array_equal(out_fn(0.0, y, p), [2.0]) + np.testing.assert_array_equal(event_fn(0.0, y, p), [-9.0]) + + def test_algebraic_views_none_for_ode(self): + _, model = self._setup() + assert model.algebraic_residual is None + assert model.algebraic_jacobian is None + + def test_algebraic_jacobian_view_is_the_algebraic_block_of_df_dy(self): + model = pybamm.lithium_ion.DFN() + model.convert_to_format = "rust" + sim = pybamm.Simulation(model) + sim.build() + built = sim.built_model + sim.solver.set_up(built, inputs=[{}]) + rust_model = sim.solver._setup["rust_model"] + n_rhs, n_algebraic = built.len_rhs, rust_model.n_algebraic + assert n_algebraic == built.len_alg > 0 + + view = rust_model.algebraic_jacobian + assert view.shape == (n_algebraic, n_algebraic) + # The algebraic rows of the residual are g, so their algebraic columns are dg/dy_alg + y0 = built.concatenated_initial_conditions.evaluate(0, inputs={}).ravel() + full = rust_model.jacobian(0.0, y0, {}) + np.testing.assert_allclose( + view(0.0, y0, {}).toarray(), + full[n_rhs:, n_rhs:].toarray(), + rtol=1e-12, + atol=1e-12, + ) + + def test_views_are_cached_objects(self): + _, model = self._setup() + assert model.rhs is model.rhs + assert model.jacobian is model.jacobian + assert model.outputs[0] is model.outputs[0] + assert model.events[0] is model.events[0] + + def test_kept_solver_surface(self): + _, model = self._setup() + assert model.n_states == 2 + assert model.nnz >= 2 + assert model.n_colors >= 1 + assert repr(model.evaluator()).startswith( + ' list[tuple[int, float]]: """ Compute the integral L2 WRMS error between two Hermite-interpolated solutions @@ -87,6 +100,13 @@ def integrand(t, itp_base, itp_red, atol_vec, rtol): return wrms_values +@pytest.fixture(params=["casadi", "rust"]) +def model_format(request, monkeypatch): + """Give every model the test builds each backend's format by default.""" + monkeypatch.setattr(pybamm.BaseModel, "_DEFAULT_CONVERT_TO_FORMAT", request.param) + return request.param + + @pytest.fixture def decay_model(): """Discretised ``du/dt = -a u``, with ``a`` as the only input parameter.""" @@ -99,7 +119,7 @@ def decay_model(): return model -def _part_way_failure_model(): +def _part_way_failure_model(convert_to_format="casadi"): """Discretised ``du/dt = sqrt(k - t)``, with ``k`` as the only input parameter. Its residual is NaN once ``t > k``, so a solve past ``t = k > 0`` fails @@ -111,6 +131,7 @@ def _part_way_failure_model(): model.initial_conditions = {u: 0} model.variables = {"u": u} pybamm.Discretisation().process_model(model) + model.convert_to_format = convert_to_format return model @@ -195,36 +216,104 @@ def test_multiple_inputs(self): rtol=1e-4, ) - def test_every_failing_input_set_is_named(self): - model = get_broken_input_model() + def test_multiple_inputs_rust_solves_in_parallel(self): + model = _rust_decay_model() + + t_eval = [0, 1] + t_interp = np.linspace(t_eval[0], t_eval[-1], 10) + inputs_list = [{"rate": 0.01 * (i + 1)} for i in range(4)] + + solver = pybamm.IDAKLUSolver(rtol=1e-10, atol=1e-10, options={"num_threads": 4}) + batched_solutions = solver.solve( + model, t_eval, inputs=inputs_list, t_interp=t_interp + ) + + sequential_solver = pybamm.IDAKLUSolver(rtol=1e-10, atol=1e-10) + for inputs, batched in zip(inputs_list, batched_solutions, strict=True): + sequential = sequential_solver.solve( + model, t_eval, inputs=inputs, t_interp=t_interp + ) + np.testing.assert_array_equal(batched.t, sequential.t) + np.testing.assert_allclose( + batched.y[0], sequential.y[0], rtol=1e-8, atol=1e-10 + ) + + @pytest.mark.parametrize( + ("num_threads", "num_solvers"), [(4, None), (4, 1), (4, 2), (1, 1)] + ) + def test_rust_runs_one_solver_per_thread(self, num_threads, num_solvers): + # Equal counts give one thread per solver, avoiding OpenMP N_Vectors. + model = _rust_decay_model() + + options = {"num_threads": num_threads} + if num_solvers is not None: + options["num_solvers"] = num_solvers + solver = pybamm.IDAKLUSolver(rtol=1e-5, atol=1e-5, options=options) + solver.solve(model, [0, 1], inputs=[{"rate": 0.01 * (i + 1)} for i in range(4)]) + + # The override is scoped to the rust set-up; the user's options are kept + assert solver._options["num_threads"] == num_threads + assert solver._options["num_solvers"] == (num_solvers or num_threads) + assert len(solver._setup["rust_evaluators"]) == num_threads + + def test_rust_logs_that_compile_has_no_effect(self, caplog): + solver = pybamm.IDAKLUSolver(options={"compile": True}) + with caplog.at_level(logging.WARNING, logger=pybamm.logger.name): + solver.solve(_rust_decay_model(), [0, 1], inputs={"rate": 0.1}) + assert "options['compile'] has no effect" in caplog.text + + def test_each_rust_solver_claims_its_own_evaluator(self): + solver = pybamm.IDAKLUSolver(options={"num_threads": 3}) + solver.set_up(_rust_decay_model(with_input=False)) + capsules = solver._setup["rust_evaluators"] + + assert len(capsules) == 3 + # A claim renames the capsule, which then leaves the evaluator to its solver + for capsule in capsules: + assert repr(capsule).startswith( + ' -1 is violated before the first step model = self._state_derivative_event_model( - {"derivative event": lambda y, z: z.diff(pybamm.t) + 1} + {"derivative event": lambda y, z: z.diff(pybamm.t) + 1}, + convert_to_format=convert_to_format, ) solver = pybamm.IDAKLUSolver( options={"calc_ic": calc_ic}, output_variables=output_variables @@ -1771,7 +2128,10 @@ def test_state_derivative_event_violated_at_initial_conditions( (lambda y: y - 0.5, r"IDASolve at t0"), ], ) - def test_state_derivative_event_with_failed_first_step(self, plain_event, match): + @pytest.mark.parametrize("convert_to_format", ["casadi", "rust"]) + def test_state_derivative_event_with_failed_first_step( + self, convert_to_format, plain_event, match + ): model = pybamm.BaseModel() y = pybamm.Variable("y") z = pybamm.Variable("z") @@ -1783,24 +2143,30 @@ def test_state_derivative_event_with_failed_first_step(self, plain_event, match) pybamm.Event("plain", plain_event(y)), pybamm.Event("derivative", y.diff(pybamm.t) + 10), ] + model.convert_to_format = convert_to_format pybamm.Discretisation().process_model(model) with pytest.raises(pybamm.SolverError, match=match): pybamm.IDAKLUSolver().solve(model, [0, 5]) - def test_state_derivative_event_at_t0_precedes_root_in_first_step(self): + @pytest.mark.parametrize("convert_to_format", ["casadi", "rust"]) + def test_state_derivative_event_at_t0_precedes_root_in_first_step( + self, convert_to_format + ): # z' = -2 at t0 violates z' > -1 there, ahead of y's root at 1e-10 model = self._state_derivative_event_model( { "in step": lambda y, z: y - (1 - 1e-10), "derivative event": lambda y, z: z.diff(pybamm.t) + 1, - } + }, + convert_to_format=convert_to_format, ) with pytest.raises( pybamm.SolverError, match=r"\['derivative event'\] are non-positive" ): pybamm.IDAKLUSolver().solve(model, [0, 5]) - def test_state_derivative_event_after_step_change(self): + @pytest.mark.parametrize("convert_to_format", ["casadi", "rust"]) + def test_state_derivative_event_after_step_change(self, convert_to_format): # q' = -I jumps when the algebraic current I steps from 0 to I_app at t0 model = pybamm.BaseModel() q = pybamm.Variable("q") @@ -1809,6 +2175,7 @@ def test_state_derivative_event_after_step_change(self): model.algebraic = {current: current - pybamm.InputParameter("I_app")} model.initial_conditions = {q: 1, current: 0} model.events = [pybamm.Event("dq/dt < -1", q.diff(pybamm.t) + 1)] + model.convert_to_format = convert_to_format pybamm.Discretisation().process_model(model) solver = pybamm.IDAKLUSolver() solution = solver.solve(model, [0, 1], inputs={"I_app": 0.5}) @@ -1816,29 +2183,35 @@ def test_state_derivative_event_after_step_change(self): with pytest.raises(pybamm.SolverError, match=r"non-positive at initial"): solver.solve(model, [0, 1], inputs={"I_app": 2}) - def test_state_derivative_event_restart_keeps_stats(self): + @pytest.mark.parametrize("convert_to_format", ["casadi", "rust"]) + def test_state_derivative_event_restart_keeps_stats(self, convert_to_format): # y's root at 1e-10 is crossed in the first step, retaken after a restart model = self._state_derivative_event_model( - {"in step": lambda y, z: y - (1 - 1e-10) + 1e-20 * z.diff(pybamm.t)} + {"in step": lambda y, z: y - (1 - 1e-10) + 1e-20 * z.diff(pybamm.t)}, + convert_to_format=convert_to_format, ) solution = pybamm.IDAKLUSolver().solve(model, [0, 5]) # the discarded step counts too assert solution.solver_statistics.number_of_steps == 2 - def test_state_derivative_event_not_named_before_first_step(self): + @pytest.mark.parametrize("convert_to_format", ["casadi", "rust"]) + def test_state_derivative_event_not_named_before_first_step( + self, convert_to_format + ): # 'plain' stops the solve before the first step gives yp, so 'derivative', # which reads z' = 0 from the initial yp, is not named model = self._state_derivative_event_model( { "plain": lambda y, z: y - 2, "derivative": lambda y, z: -z.diff(pybamm.t) - 1, - } + }, + convert_to_format=convert_to_format, ) with pytest.raises(pybamm.SolverError, match=r"Events \['plain'\] are"): pybamm.IDAKLUSolver().solve(model, [0, 5]) @staticmethod - def _current_jump_model(events, jump=1.5, strict=False): + def _current_jump_model(events, jump=1.5, strict=False, convert_to_format="casadi"): # I jumps from 0.5 to 2 at the breakpoint t = 0.2, and so does -q'; # with strict, it jumps just after 0.2 model = pybamm.BaseModel() @@ -1852,17 +2225,21 @@ def _current_jump_model(events, jump=1.5, strict=False): model.events = [ pybamm.Event(name, fn(q, current)) for name, fn in events.items() ] + model.convert_to_format = convert_to_format pybamm.Discretisation().process_model(model) return model + @pytest.mark.parametrize("convert_to_format", ["casadi", "rust"]) @pytest.mark.parametrize("with_derivative_event", [False, True]) - def test_event_violated_after_breakpoint(self, with_derivative_event): + def test_event_violated_after_breakpoint( + self, convert_to_format, with_derivative_event + ): # IDA finds no sign change in an event already violated after a # breakpoint, whether or not another event reads yp events = {"I < 1.5": lambda q, current: 1.5 - current} if with_derivative_event: events["dq/dt > -100"] = lambda q, current: q.diff(pybamm.t) + 100 - model = self._current_jump_model(events) + model = self._current_jump_model(events, convert_to_format=convert_to_format) solution = pybamm.IDAKLUSolver().solve(model, np.array([0, 0.2, 1])) assert solution.termination == "final time" @@ -1896,13 +2273,15 @@ def test_compiled_state_derivative_event(self): assert solution.termination == "event: dq/dt > -1" assert solution.t[-1] == pytest.approx(0.2) - def test_event_violated_after_breakpoint_is_named(self): + @pytest.mark.parametrize("convert_to_format", ["casadi", "rust"]) + def test_event_violated_after_breakpoint_is_named(self, convert_to_format): # q' + 1 = -1 at the restart is further from zero than the other event model = self._current_jump_model( { "dq/dt > -1": lambda q, current: q.diff(pybamm.t) + 1, "always positive": lambda q, current: 0.01 + 0 * q, - } + }, + convert_to_format=convert_to_format, ) solution = pybamm.IDAKLUSolver().solve(model, np.array([0, 0.2, 1])) assert solution.termination == "event: dq/dt > -1" @@ -1917,12 +2296,14 @@ def test_event_violated_after_breakpoint_is_named(self): (None, {"calc_ic": False}), ], ) + @pytest.mark.parametrize("convert_to_format", ["casadi", "rust"]) def test_state_derivative_event_violated_after_breakpoint( - self, output_variables, options + self, convert_to_format, output_variables, options ): # q' = -2 just after the breakpoint violates q' > -1 there model = self._current_jump_model( - {"dq/dt > -1": lambda q, current: q.diff(pybamm.t) + 1} + {"dq/dt > -1": lambda q, current: q.diff(pybamm.t) + 1}, + convert_to_format=convert_to_format, ) solver = pybamm.IDAKLUSolver(output_variables=output_variables, options=options) solution = solver.solve(model, np.array([0, 0.2, 1])) @@ -1944,14 +2325,16 @@ def test_state_derivative_event_violated_after_breakpoint( solution.all_yps[-1][:, -1], [-2, 0], rtol=1e-6, atol=1e-8 ) + @pytest.mark.parametrize("convert_to_format", ["casadi", "rust"]) @pytest.mark.parametrize("output_variables", [None, ["I"]]) def test_state_derivative_event_violated_after_breakpoint_sensitivities( - self, output_variables + self, convert_to_format, output_variables ): # dI/djump is 1 once the breakpoint's reinitialisation has applied the jump model = self._current_jump_model( {"dq/dt > -1": lambda q, current: q.diff(pybamm.t) + 1}, jump=pybamm.InputParameter("jump"), + convert_to_format=convert_to_format, ) solver = pybamm.IDAKLUSolver(output_variables=output_variables) solution = solver.solve( @@ -1966,13 +2349,17 @@ def test_state_derivative_event_violated_after_breakpoint_sensitivities( np.ravel(final["I"].sensitivities["jump"])[-1], 1, rtol=1e-6 ) - def test_state_derivative_event_violated_when_starting_at_a_discontinuity(self): + @pytest.mark.parametrize("convert_to_format", ["casadi", "rust"]) + def test_state_derivative_event_violated_when_starting_at_a_discontinuity( + self, convert_to_format + ): # t > 0.2 adds a t_eval point a float after t0 = 0.2, where IDA restarts # after its first step, and q' = -2 there violates q' > -1 model = self._current_jump_model( {"dq/dt > -1": lambda q, current: q.diff(pybamm.t) + 1}, jump=pybamm.InputParameter("jump"), strict=True, + convert_to_format=convert_to_format, ) solution = pybamm.IDAKLUSolver().solve( model, [0.2, 1], inputs={"jump": 1.5}, calculate_sensitivities=True @@ -1986,7 +2373,10 @@ def test_state_derivative_event_violated_when_starting_at_a_discontinuity(self): np.ravel(solution["I"].sensitivities["jump"]), [0, 1], atol=1e-6 ) - def test_state_derivative_event_with_inputs_threads_and_sensitivities(self): + @pytest.mark.parametrize("convert_to_format", ["casadi", "rust"]) + def test_state_derivative_event_with_inputs_threads_and_sensitivities( + self, convert_to_format + ): # y' = -k y < -0.5 until y = 0.5 / k, at t = ln(2 k) / k model = pybamm.BaseModel() y = pybamm.Variable("y") @@ -1995,6 +2385,7 @@ def test_state_derivative_event_with_inputs_threads_and_sensitivities(self): model.initial_conditions = {y: 1} model.variables = {"y": y} model.events = [pybamm.Event("dy/dt > -0.5", -0.5 - y.diff(pybamm.t))] + model.convert_to_format = convert_to_format pybamm.Discretisation().process_model(model) solver = pybamm.IDAKLUSolver( rtol=1e-8, atol=1e-8, options={"num_threads": 2, "num_solvers": 2} @@ -2024,9 +2415,11 @@ def test_state_derivative_event_with_inputs_threads_and_sensitivities(self): "model_class", [pybamm.lithium_ion.SPM, pybamm.lithium_ion.SPMe, pybamm.lithium_ion.DFN], ) - def test_voltage_derivative_event(self, model_class): + @pytest.mark.parametrize("convert_to_format", ["casadi", "rust"]) + def test_voltage_derivative_event(self, convert_to_format, model_class): # dV/dt by the chain rule through the observable's states, at 1C discharge model = model_class() + model.convert_to_format = convert_to_format voltage = model.variables["Voltage [V]"] model.events.append( pybamm.Event("dV/dt > -1e-4 V/s", -voltage.diff(pybamm.t) - 1e-4) @@ -2047,7 +2440,8 @@ def test_voltage_derivative_event(self, model_class): ) np.testing.assert_allclose(slope, -1e-4, rtol=1e-2) - def test_state_derivative_termination_in_experiment(self): + @pytest.mark.parametrize("convert_to_format", ["casadi", "rust"]) + def test_state_derivative_termination_in_experiment(self, convert_to_format): def current_settled(threshold): return pybamm.step.CustomTermination( f"|dI/dt| < {threshold} A/s", @@ -2064,7 +2458,9 @@ def current_settled(threshold): pybamm.step.voltage(4.1, termination=current_settled(1e-5)), ] ) - sim = pybamm.Simulation(pybamm.lithium_ion.SPM(), experiment=experiment) + model = pybamm.lithium_ion.SPM() + model.convert_to_format = convert_to_format + sim = pybamm.Simulation(model, experiment=experiment) solution = sim.solve() assert len(solution.cycles) == 2 @@ -2074,6 +2470,27 @@ def current_settled(threshold): current = hold["Current [A]"](t) np.testing.assert_allclose(np.abs(np.gradient(current, t)[-1]), 1e-5, rtol=0.05) + @pytest.mark.parametrize( + ("output_variables", "options"), + [(["dy/dt"], None), (None, {"upsampling_tolerance": 1e-3})], + ) + @pytest.mark.parametrize("convert_to_format", ["casadi", "rust"]) + def test_a_time_derivative_output_needs_y_dot( + self, convert_to_format, output_variables, options + ): + # Unlike an event, an output or the upsampling variable is given no y_dot + model = pybamm.BaseModel() + y = pybamm.Variable("y") + model.rhs = {y: -y} + model.initial_conditions = {y: 1} + model.variables = {"y": y, "dy/dt": y.diff(pybamm.t)} + model.upsampling_variable = "dy/dt" + model.convert_to_format = convert_to_format + pybamm.Discretisation().process_model(model) + solver = pybamm.IDAKLUSolver(output_variables=output_variables, options=options) + with pytest.raises(pybamm.ModelError, match=r"Must provide a 'y_dot'"): + solver.solve(model, [0, 1]) + def test_pickle_roundtrip_preserves_closest_event_idx(self): # The pickle drops _setup; the next solve rebuilds it from the model. import pickle @@ -2105,6 +2522,265 @@ def test_pickle_roundtrip_preserves_closest_event_idx(self): "closest_event_idx after a root return" ) + def test_closest_event_idx_set_after_root_return_rust(self): + model = pybamm.lithium_ion.SPM() + model.convert_to_format = "rust" + cycle = ( + "Discharge at 1C until 3.0 V", + "Charge at 1C until 4.2 V", + "Hold at 4.2 V until C/50", + ) + sim = pybamm.Simulation( + model, + experiment=pybamm.Experiment([cycle] * 2, period=300), + solver=pybamm.IDAKLUSolver(output_variables=["Voltage [V]"]), + ) + sim.solve() + + event_steps = [ + step + for cycle_sol in sim.solution.cycles + for step in cycle_sol.steps + if step.termination.startswith("event:") + ] + assert event_steps, "expected at least one event-terminated step" + for step in event_steps: + assert step.all_models[-1].convert_to_format == "rust" + assert step.closest_event_idx is not None, ( + f"event-terminated step {step.termination!r} has " + f"closest_event_idx=None — BaseSolver will fall back to " + f"per-step Python event re-evaluation" + ) + terminate_events = [ + e + for e in step.all_models[-1].events + if e.event_type == pybamm.EventType.TERMINATION + ] + picked = terminate_events[step.closest_event_idx].name + assert step.termination == f"event: {picked}", ( + f"closest_event_idx={step.closest_event_idx} resolves to " + f"{picked!r}, but step.termination is {step.termination!r}" + ) + + @staticmethod + def _rust_model_with_a_vector_event(): + model = pybamm.BaseModel() + v = pybamm.Variable("v", domain="negative electrode") + model.rhs = {v: -v} + model.initial_conditions = {v: pybamm.Scalar(1.0)} + model.variables = {"v": v} + model.events = [pybamm.Event("Vector event", v - 0.5)] + geometry = {"negative electrode": {"x_n": {"min": 0.0, "max": 1.0}}} + submesh_types = {"negative electrode": pybamm.Uniform1DSubMesh} + mesh = pybamm.Mesh(geometry, submesh_types, {"x_n": 4}) + spatial_methods = {"negative electrode": pybamm.FiniteVolume()} + pybamm.Discretisation(mesh, spatial_methods).process_model(model) + model.convert_to_format = "rust" + return model + + @pytest.mark.parametrize("convert_to_format", ["casadi", "rust"]) + def test_a_model_without_states_is_refused(self, convert_to_format): + model = pybamm.BaseModel() + model.variables = {"x": 2 * pybamm.t} + model.convert_to_format = convert_to_format + pybamm.Discretisation().process_model(model) + + with pytest.raises(pybamm.SolverError, match=r"no states"): + pybamm.IDAKLUSolver().solve(model, [0, 1]) + + def test_vector_event_is_rejected_rust(self): + model = self._rust_model_with_a_vector_event() + with pytest.raises(pybamm.SolverError, match=r"'Vector event' has shape"): + pybamm.IDAKLUSolver().solve(model, [0, 1]) + + def test_rust_backend_rejects_a_vector_upsampling_output_past_the_lowering( + self, monkeypatch + ): + # IDAKLU evaluates the upsampling output into one scalar, so a vector would overrun it + def lower_without_the_scalar_check(lowering, name, symbol): + return lowering.lower(symbol) + + monkeypatch.setattr( + RustModelLowering, "_lower_upsampling", lower_without_the_scalar_check + ) + model = self._rust_model_with_a_vector_event() + model.events = [] + model.upsampling_variable = "v" + solver = pybamm.IDAKLUSolver(options={"upsampling_tolerance": 1e-3}) + with pytest.raises(ValueError, match=r"upsampling output has 4 components"): + solver.solve(model, [0, 1]) + + @staticmethod + def _rust_dae_model(): + model = pybamm.BaseModel() + u = pybamm.Variable("u") + v = pybamm.Variable("v") + model.rhs = {u: -v} + model.algebraic = {v: v - 2 * u} + model.initial_conditions = {u: 1, v: 2} + model.convert_to_format = "rust" + pybamm.Discretisation().process_model(model) + return model + + def test_rust_solver_group_refuses_an_atol_of_another_length(self, monkeypatch): + # IDA reads one tolerance per state, at the count the evaluator gives + idaklu = pybamm.solvers.idaklu_solver.idaklu + + class ShortAtolIdaklu: + def __getattr__(self, name): + return getattr(idaklu, name) + + def create_rust_solver_group(self, **kwargs): + return idaklu.create_rust_solver_group( + **{**kwargs, "atol": kwargs["atol"][:-1]} + ) + + monkeypatch.setattr(pybamm.solvers.idaklu_solver, "idaklu", ShortAtolIdaklu()) + with pytest.raises( + ValueError, match=r"atol has length 1 but the Rust model has 2 states\." + ): + pybamm.IDAKLUSolver().solve(self._rust_dae_model(), [0, 1]) + + def test_rust_solver_group_refuses_evaluators_of_different_models( + self, monkeypatch + ): + # The group sizes every solver's results from its first evaluator + idaklu = pybamm.solvers.idaklu_solver.idaklu + other = RustModelLowering.of(_rust_decay_model(with_input=False), []) + other_evaluator = other.compile_model().evaluator() + + class MixedIdaklu: + def __getattr__(self, name): + return getattr(idaklu, name) + + def create_rust_solver_group(self, **kwargs): + first, *_ = kwargs["rust_evaluators"] + return idaklu.create_rust_solver_group( + **{**kwargs, "rust_evaluators": [first, other_evaluator]} + ) + + monkeypatch.setattr(pybamm.solvers.idaklu_solver, "idaklu", MixedIdaklu()) + solver = pybamm.IDAKLUSolver(options={"num_threads": 2}) + with pytest.raises(ValueError, match=r"evaluator 1 differs from evaluator 0\."): + solver.solve(self._rust_dae_model(), [0, 1]) + + def test_rust_backend_refuses_a_sub_block_over_only_some_algebraic_states( + self, monkeypatch + ): + # IDAKLU sizes the IC sub-block from the mass matrix, and Rust writes the + # block's residual into it + def lower_only_the_last_state(lowering): + model = lowering.model + last = list(model.algebraic.values())[-1] + return lowering.lower(last), [model.len_rhs_and_alg - 1] + + monkeypatch.setattr( + RustModelLowering, "_lower_algebraic_block", lower_only_the_last_state + ) + model = pybamm.BaseModel() + u, v, w = (pybamm.Variable(name) for name in "uvw") + model.rhs = {u: -v} + model.algebraic = {v: v - 2 * u, w: w - u} + model.initial_conditions = {u: 1, v: 2, w: 1} + model.convert_to_format = "rust" + pybamm.Discretisation().process_model(model) + with pytest.raises( + ValueError, match=r"block covers 1 of the 2 states its mass matrix marks" + ): + pybamm.IDAKLUSolver().solve(model, [0, 1]) + + def test_rust_jacobian_sparsity_is_the_compiled_pattern(self): + solver = pybamm.IDAKLUSolver() + solver.set_up(self._rust_dae_model()) + compiled = solver._setup["rust_model"] + colptrs, rowvals = compiled.csc_sparsity_pattern() + + sparsity = solver.get_jacobian_sparsity() + + assert sparsity.shape == (compiled.n_states, compiled.n_states) + np.testing.assert_array_equal(sparsity.indptr, colptrs) + np.testing.assert_array_equal(sparsity.indices, rowvals) + + def test_rust_fused_events_parity_with_casadi(self): + # SPMe has >= 2 termination events, so Rust evaluates them via the fused tape. + def _solve(fmt): + params = pybamm.ParameterValues("Chen2020") + params["Lower voltage cut-off [V]"] = 3.5 + model = pybamm.lithium_ion.SPMe() + model.convert_to_format = fmt + sim = pybamm.Simulation( + model, parameter_values=params, solver=pybamm.IDAKLUSolver() + ) + return sim.solve(np.linspace(0, 3600, 100)) + + sol_rust = _solve("rust") + sol_casadi = _solve("casadi") + + assert sol_rust.termination.startswith("event:"), ( + f"expected an event to fire, got {sol_rust.termination!r}" + ) + assert sol_rust.termination == sol_casadi.termination + assert sol_rust.closest_event_idx == sol_casadi.closest_event_idx + np.testing.assert_allclose( + float(sol_rust.t_event[0]), float(sol_casadi.t_event[0]), rtol=1e-4 + ) + + def test_rust_events_survive_compiled_model_pickle(self): + import pickle + + model = pybamm.lithium_ion.SPMe() + model.convert_to_format = "rust" + sim = pybamm.Simulation(model, solver=pybamm.IDAKLUSolver()) + sol = sim.solve(np.linspace(0, 3600, 10)) + + rust_model = sim._solver._setup["rust_model"] + assert rust_model.n_events >= 2 # fusion is active + + y = np.ascontiguousarray(sol.all_ys[0][:, 0], dtype=np.float64) + p = np.zeros(rust_model.n_inputs, dtype=np.float64) + t = float(sol.all_ts[0][0]) + before = [np.asarray(fn(t, y, p)).ravel() for fn in rust_model.events] + + restored = pickle.loads(pickle.dumps(rust_model)) + assert restored.n_events == rust_model.n_events + after = [np.asarray(fn(t, y, p)).ravel() for fn in restored.events] + for a, b in zip(before, after, strict=True): + np.testing.assert_array_equal(a, b) + + def test_rust_upsamples_at_the_times_casadi_does(self): + # Through the C ABI and IDAKLU, against the CasADi path + t_additive = {} + for convert_to_format in ["casadi", "rust"]: + model = pybamm.BaseModel() + x = pybamm.Variable("x") + model.rhs = {x: -x} + model.initial_conditions = {x: 20} + # The input reaches only the upsampling variable + model.variables = {"x": x, "kx": pybamm.InputParameter("k") * x} + model.upsampling_variable = "kx" + model.convert_to_format = convert_to_format + solver = pybamm.IDAKLUSolver(options={"upsampling_tolerance": 1e-4}) + solution = solver.solve(model, [0, 3], inputs={"k": 0.3}) + t_additive[convert_to_format] = solution.t_additive + assert t_additive["rust"].size > 0 + np.testing.assert_allclose(t_additive["rust"], t_additive["casadi"], rtol=1e-12) + + def test_rust_upsampling_survives_compiled_model_pickle(self): + import pickle + + model = pybamm.lithium_ion.SPM() + model.convert_to_format = "rust" + solver = pybamm.IDAKLUSolver(options={"upsampling_tolerance": 1e-3}) + sim = pybamm.Simulation(model, solver=solver) + sim.solve([0, 600]) + + rust_model = sim._solver._setup["rust_model"] + assert rust_model.upsampling_len == 1 + restored = pickle.loads(pickle.dumps(rust_model)) + assert restored.upsampling_len == 1 + # Past the graph, the rebuild arguments name the same roots, upsampling's included + assert restored.__reduce__()[1][1:] == rust_model.__reduce__()[1][1:] + def test_simulation_period(self): model = pybamm.lithium_ion.DFN() parameter_values = pybamm.ParameterValues("Chen2020") @@ -2579,6 +3255,17 @@ def test_hermite_reduction_factor_incompatible(self): with pytest.warns(pybamm.SolverWarning, match="not currently supported"): sim.solve([0, 1], inputs={"I": 1.0}, calculate_sensitivities=True) + def test_hermite_reduction_factor_sensitivities_warning_rust(self): + # Regression: _set_up_rust skipped the hermite_reduction_factor warning. + model_sens = pybamm.lithium_ion.SPM() + model_sens.convert_to_format = "rust" + param = model_sens.default_parameter_values + param["Current function [A]"] = pybamm.InputParameter("I") + solver = pybamm.IDAKLUSolver(options={"hermite_reduction_factor": 2.0}) + sim = pybamm.Simulation(model_sens, parameter_values=param, solver=solver) + with pytest.warns(pybamm.SolverWarning, match="not currently supported"): + sim.solve([0, 1], inputs={"I": 1.0}, calculate_sensitivities=True) + def test_reduce_solution_basic(self): """Test basic post-hoc reduce_solution: fewer points, finite yps, bounded error.""" model = pybamm.lithium_ion.SPM() @@ -2629,13 +3316,15 @@ def test_reduce_solution_metadata(self): for rte, ste in zip(reduced.all_t_evals, sol.all_t_evals, strict=True): np.testing.assert_array_equal(rte, ste) - def test_get_jacobian_sparsity(self): + @pytest.mark.parametrize("convert_to_format", ["casadi", "rust"]) + def test_get_jacobian_sparsity(self, convert_to_format): model = pybamm.BaseModel() u = pybamm.Variable("u") v = pybamm.Variable("v") model.rhs = {u: 0.1 * v} model.algebraic = {v: 1 - v} model.initial_conditions = {u: 0, v: 1} + model.convert_to_format = convert_to_format disc = pybamm.Discretisation() disc.process_model(model) @@ -2653,13 +3342,15 @@ def test_get_jacobian_sparsity_not_set_up(self): with pytest.raises(pybamm.SolverError, match="Solver not set up"): solver.get_jacobian_sparsity() - def test_spy(self): + @pytest.mark.parametrize("convert_to_format", ["casadi", "rust"]) + def test_spy(self, convert_to_format): model = pybamm.BaseModel() u = pybamm.Variable("u") v = pybamm.Variable("v") model.rhs = {u: 0.1 * v} model.algebraic = {v: 1 - v} model.initial_conditions = {u: 0, v: 1} + model.convert_to_format = convert_to_format disc = pybamm.Discretisation() disc.process_model(model) @@ -2797,6 +3488,300 @@ def test_solution_user_options_survive_pickle(self, tmp_path): loaded["2u"].entries, sol["2u"].entries, rtol=1e-12, atol=1e-12 ) + def test_idaklu_dispatch_is_flag_driven(self): + with pytest.raises(TypeError): + pybamm.IDAKLUSolver(evaluator="rust") + from tests.unit.test_solvers.test_process_rust import _toy_dae + + model = _toy_dae("rust") + solver = pybamm.IDAKLUSolver() + solver.set_up(model, inputs=[{"a": 0.5}]) + assert "rust_model" in solver._setup + assert model.convert_to_format == "rust" + + def test_idaklu_rust_output_sensitivities_set_up_ok(self): + from tests.unit.test_solvers.test_process_rust import _toy_dae + + model = _toy_dae("rust") + model.calculate_sensitivities = ["a"] + solver = pybamm.IDAKLUSolver(output_variables=["u"]) + solver.set_up(model, inputs=[{"a": 0.5}]) + assert model.convert_to_format == "rust" + + def test_idaklu_rust_output_values_ok_without_sens(self): + from tests.unit.test_solvers.test_process_rust import _toy_dae + + model = _toy_dae("rust") + solver = pybamm.IDAKLUSolver(output_variables=["u"]) + solver.set_up(model, inputs=[{"a": 0.5}]) + assert model.convert_to_format == "rust" + + def test_rhs_dot_consistent_init_rust_inputs(self): + # Regression: inputs must be stacked, not handed to the RustEvaluator as a dict. + from tests.unit.test_solvers.test_process_rust import _toy_dae + + model = _toy_dae("rust") + solver = pybamm.IDAKLUSolver() + solver.set_up(model, inputs=[{"a": 0.5}]) + y0 = np.asarray(model.y0_list[0]).ravel() + ydot0 = solver._rhs_dot_consistent_initialization(y0, model, 0.0, {"a": 0.5}) + assert ydot0.shape == y0.shape + + def test_sensitivity_consistent_init_gate_fires_for_rust(self): + from tests.unit.test_solvers.test_process_rust import _toy_dae + + model = _toy_dae("rust") + model.calculate_sensitivities = ["a"] + solver = pybamm.IDAKLUSolver() + solver.set_up(model, inputs=[{"a": 0.5}]) + solver._set_consistent_initialization(model, 0.0, [{"a": 0.5}]) + # 1 sens param: y0full should be len_rhs_and_alg * 2 + assert model.y0full[0].shape[0] == model.len_rhs_and_alg * 2 + + +class TestIDAKLUNativeObservation: + def _solve(self, convert_to_format, calculate_sensitivities=False, t_interp=None): + model = pybamm.lithium_ion.SPM() + geometry = model.default_geometry + param = model.default_parameter_values + if calculate_sensitivities: + param.update({"Current function [A]": "[input]"}) + param.process_model(model) + param.process_geometry(geometry) + mesh = pybamm.Mesh(geometry, model.default_submesh_types, model.default_var_pts) + disc = pybamm.Discretisation(mesh, model.default_spatial_methods) + disc.process_model(model) + model.convert_to_format = convert_to_format + solver = pybamm.IDAKLUSolver() + t_eval = [0, 3600] + sol = solver.solve( + model, + t_eval, + t_interp=t_interp, + inputs={"Current function [A]": 0.68} if calculate_sensitivities else None, + calculate_sensitivities=calculate_sensitivities, + ) + return sol, solver + + def test_offgrid_values_match_casadi(self): + t_interp = np.linspace(0, 3600, 97) + cas, _ = self._solve("casadi", t_interp=t_interp) + rust, _ = self._solve("rust", t_interp=t_interp) + for name in [ + "Terminal voltage [V]", + "X-averaged negative particle concentration [mol.m-3]", + ]: + np.testing.assert_allclose( + rust[name](t_interp), cas[name](t_interp), rtol=1e-6, atol=1e-6 + ) + + def _solve_output_vars( + self, convert_to_format, output_variables, model=None, inputs=None, var_pts=None + ): + if model is None: + model = pybamm.lithium_ion.SPM() + geometry = model.default_geometry + param = model.default_parameter_values + if inputs is None: + inputs = {"Current function [A]": 0.68} + param.update({key: "[input]" for key in inputs}) + param.process_model(model) + param.process_geometry(geometry) + mesh = pybamm.Mesh( + geometry, model.default_submesh_types, var_pts or model.default_var_pts + ) + disc = pybamm.Discretisation(mesh, model.default_spatial_methods) + disc.process_model(model) + model.convert_to_format = convert_to_format + solver = pybamm.IDAKLUSolver(output_variables=output_variables) + # The lowerings step differently, so t_interp puts both on one grid. + sol = solver.solve( + model, + [0, 3600], + inputs=inputs, + calculate_sensitivities=True, + t_interp=np.linspace(0, 3600, 100), + ) + return sol, solver + + def test_output_variables_sensitivities_match_casadi(self): + ov = ["Terminal voltage [V]"] + cas, _ = self._solve_output_vars("casadi", ov) + rust, _ = self._solve_output_vars("rust", ov) + np.testing.assert_allclose( + rust["Terminal voltage [V]"].sensitivities["Current function [A]"], + cas["Terminal voltage [V]"].sensitivities["Current function [A]"], + rtol=1e-5, + atol=1e-6, + ) + + def test_output_variables_sensitivities_match_casadi_spme(self): + ov = ["Terminal voltage [V]"] + cas, _ = self._solve_output_vars("casadi", ov, model=pybamm.lithium_ion.SPMe()) + rust, _ = self._solve_output_vars("rust", ov, model=pybamm.lithium_ion.SPMe()) + np.testing.assert_allclose( + rust["Terminal voltage [V]"].sensitivities["Current function [A]"], + cas["Terminal voltage [V]"].sensitivities["Current function [A]"], + rtol=1e-5, + atol=1e-6, + ) + + def test_output_variables_sensitivities_match_casadi_dfn(self): + # A coarse mesh bounds the cost of the heavier DFN solve. + ov = ["Terminal voltage [V]"] + var_pts = {"x_n": 10, "x_s": 10, "x_p": 10, "r_n": 5, "r_p": 5} + cas, _ = self._solve_output_vars( + "casadi", ov, model=pybamm.lithium_ion.DFN(), var_pts=var_pts + ) + rust, _ = self._solve_output_vars( + "rust", ov, model=pybamm.lithium_ion.DFN(), var_pts=var_pts + ) + np.testing.assert_allclose( + rust["Terminal voltage [V]"].sensitivities["Current function [A]"], + cas["Terminal voltage [V]"].sensitivities["Current function [A]"], + rtol=1e-5, + atol=1e-6, + ) + + def test_output_variables_multi_param_sensitivities_match_casadi(self): + # Params arrive reversed from the sorted yS column order, exposing mislabelling. + ov = ["Terminal voltage [V]"] + inputs = { + "Negative electrode active material volume fraction": 0.6, + "Current function [A]": 0.68, + } + cas, _ = self._solve_output_vars("casadi", ov, inputs=inputs) + rust, _ = self._solve_output_vars("rust", ov, inputs=inputs) + for name in inputs: + np.testing.assert_allclose( + rust["Terminal voltage [V]"].sensitivities[name], + cas["Terminal voltage [V]"].sensitivities[name], + rtol=1e-5, + atol=1e-6, + err_msg=f"sensitivity mismatch for param '{name}'", + ) + + def test_multi_output_multi_param_sensitivities_match_casadi(self): + # A transposed (output, param) write agrees on the diagonal; both must be > 1. + ov = ["Terminal voltage [V]", "Discharge capacity [A.h]"] + inputs = { + "Negative electrode active material volume fraction": 0.6, + "Current function [A]": 0.68, + } + cas, _ = self._solve_output_vars("casadi", ov, inputs=inputs) + rust, _ = self._solve_output_vars("rust", ov, inputs=inputs) + for var in ov: + for name in inputs: + np.testing.assert_allclose( + rust[var].sensitivities[name], + cas[var].sensitivities[name], + rtol=1e-5, + atol=1e-6, + err_msg=f"sensitivity mismatch for '{var}', parameter '{name}'", + ) + + def test_output_variables_time_integral_sensitivities_match_casadi(self): + ov = ["Discharge capacity [A.h]"] + cas, _ = self._solve_output_vars("casadi", ov) + rust, _ = self._solve_output_vars("rust", ov) + np.testing.assert_allclose( + rust["Discharge capacity [A.h]"].sensitivities["Current function [A]"], + cas["Discharge capacity [A.h]"].sensitivities["Current function [A]"], + rtol=1e-5, + atol=1e-6, + ) + + def test_output_variables_sensitivities_no_casadi_compiled(self): + ov = ["Terminal voltage [V]"] + rust, solver = self._solve_output_vars("rust", ov) + assert solver.computed_var_fcns == {} + assert solver.computed_dvar_dy_fcns == {} + assert solver.computed_dvar_dp_fcns == {} + assert "var_fcns" not in solver._setup + assert "dvar_dy_idaklu_fcns" not in solver._setup + assert "dvar_dp_idaklu_fcns" not in solver._setup + assert rust.variables_returned is True + + @staticmethod + def _discretise_spm(convert_to_format, as_input=False): + model = pybamm.lithium_ion.SPM() + geometry = model.default_geometry + param = model.default_parameter_values + if as_input: + param.update({"Current function [A]": "[input]"}) + param.process_model(model) + param.process_geometry(geometry) + mesh = pybamm.Mesh(geometry, model.default_submesh_types, model.default_var_pts) + disc = pybamm.Discretisation(mesh, model.default_spatial_methods) + disc.process_model(model) + model.convert_to_format = convert_to_format + return model + + def test_output_variables_stay_aligned_across_the_batch_window(self): + # 200 points cross the Rust FFI's 128-point batched-evaluation window. + t_interp = np.linspace(0, 3600, 200) + names = [ + "Voltage [V]", + "Negative particle surface concentration [mol.m-3]", + ] + + def solve(output_variables): + model = self._discretise_spm("rust") + solver = pybamm.IDAKLUSolver(output_variables=output_variables) + return solver.solve(model, [0, 3600], t_interp=t_interp) + + full = solve(None) + outputs_only = solve(names) + for name in names: + np.testing.assert_allclose( + np.asarray(outputs_only[name](t_interp)), + np.asarray(full[name](t_interp)), + rtol=1e-7, + atol=1e-9, + err_msg=name, + ) + + def test_output_variables_genuine_time_integral_matches_casadi(self): + # remove_independent_variables_from_rhs makes capacity a genuine time integral. + def solve(convert_to_format): + model = pybamm.lithium_ion.SPM() + geometry = model.default_geometry + param = model.default_parameter_values + param.update({"Current function [A]": "[input]"}) + param.process_model(model) + param.process_geometry(geometry) + mesh = pybamm.Mesh( + geometry, model.default_submesh_types, model.default_var_pts + ) + disc = pybamm.Discretisation( + mesh, + model.default_spatial_methods, + remove_independent_variables_from_rhs=True, + ) + disc.process_model(model) + model.convert_to_format = convert_to_format + solver = pybamm.IDAKLUSolver(output_variables=["Discharge capacity [A.h]"]) + return solver.solve( + model, + [0, 3600], + inputs={"Current function [A]": 0.68}, + calculate_sensitivities=True, + ) + + cas = solve("casadi") + rust = solve("rust") + name = "Discharge capacity [A.h]" + assert rust[name].data.shape == (1,) + np.testing.assert_allclose( + rust[name].data, cas[name].data, rtol=1e-6, atol=1e-8 + ) + np.testing.assert_allclose( + rust[name].sensitivities["Current function [A]"], + cas[name].sensitivities["Current function [A]"], + rtol=1e-6, + atol=1e-8, + ) + class TestIDAKLUSensitivityScales: """IDAS ``pbar``, the scale of each differentiated parameter.""" @@ -2884,13 +3869,16 @@ def spy(*args, **kwargs): solver.solve(model, [0, 1], **solve_kwargs) np.testing.assert_allclose(seen["pbar"], [[1e-14], [1e3]]) - def test_each_input_set_is_solved_at_its_own_scale(self): + @pytest.mark.parametrize("convert_to_format", ["casadi", "rust"]) + def test_each_input_set_is_solved_at_its_own_scale(self, convert_to_format): # a = s is one problem in different units, so pbar = |a| hands IDAS the # same scaled system; powers of two make that scaling exact. scales = [2.0**-47, 2.0**10] + model = self._rescalable_model() + model.convert_to_format = convert_to_format solver = pybamm.IDAKLUSolver(rtol=1e-8, atol=1e-8) solutions = solver.solve( - self._rescalable_model(), + model, [0, 3], inputs=[{"a": scale, "s": scale} for scale in scales], calculate_sensitivities=["a"], @@ -2905,15 +3893,20 @@ def test_each_input_set_is_solved_at_its_own_scale(self): tiny, -solutions[0].t * np.exp(-solutions[0].t), rtol=1e-5, atol=1e-7 ) - def test_a_tight_dfn_diffusivity_gradient_matches_finite_differences(self): + @pytest.mark.parametrize("convert_to_format", ["casadi", "rust"]) + def test_a_tight_dfn_diffusivity_gradient_matches_finite_differences( + self, convert_to_format + ): # D_p is 4e-15, so dy/dD_p reaches ~1e14: at the unit scale no absolute # tolerance can hold that column and the corrector fails to converge. name = "Positive particle diffusivity [m2.s-1]" parameter_values = pybamm.ParameterValues("Chen2020") nominal = parameter_values[name] parameter_values[name] = pybamm.InputParameter("D_p") + model = pybamm.lithium_ion.DFN() + model.convert_to_format = convert_to_format simulation = pybamm.Simulation( - pybamm.lithium_ion.DFN(), + model, parameter_values=parameter_values, solver=pybamm.IDAKLUSolver(rtol=1e-10, atol=1e-10), ) @@ -3048,6 +4041,16 @@ def test_a_wrong_width_model_atol_is_rejected(self): with pytest.raises(pybamm.SolverError, match=r"shape \(3,\) but \(2,\)"): self._steps(model, 1e-6) + @pytest.mark.parametrize("convert_to_format", ["casadi", "rust"]) + def test_a_wrong_width_atol_is_refused_before_the_model_converts( + self, convert_to_format + ): + model = self._two_state_model() + model.convert_to_format = convert_to_format + with pytest.raises(pybamm.SolverError, match=r"shape \(3,\) but \(2,\)"): + pybamm.IDAKLUSolver(atol=np.full(3, 1e-6)).set_up(model) + assert getattr(model, "rhs_eval", None) is None + @pytest.mark.parametrize( "atol", [ @@ -3288,6 +4291,7 @@ def test_iterative_linear_solver_statistics( assert stats.number_of_nonlinear_solver_iterations >= stats.number_of_steps +@pytest.mark.usefixtures("model_format") class TestUpsampling: @staticmethod def _solve(options=None, **solver_kwargs): @@ -3354,6 +4358,29 @@ def test_t_additive(self): rtol=1e-5, ) + def test_each_thread_upsamples_its_own_input_set(self): + parameter_values = pybamm.ParameterValues("Chen2020") + parameter_values["Current function [A]"] = "[input]" + inputs = [{"Current function [A]": current} for current in (5.0, 10.0)] + + def solve(inputs, num_threads): + solver = pybamm.IDAKLUSolver( + options={"upsampling_tolerance": 1e-4, "num_threads": num_threads} + ) + sim = pybamm.Simulation( + pybamm.lithium_ion.SPM(), + parameter_values=parameter_values, + solver=solver, + ) + return sim.solve([0, 3600], inputs=inputs) + + together = solve(inputs, num_threads=2) + alone = [solve(one, num_threads=1) for one in inputs] + # The two currents place different points, so swapped evaluators would show + assert not np.array_equal(alone[0].t_additive, alone[1].t_additive) + for parallel, serial in zip(together, alone, strict=True): + np.testing.assert_array_equal(parallel.t_additive, serial.t_additive) + def test_resolves_voltage_linear_interpolant(self): reference = self._solve(rtol=1e-10, atol=1e-12) errors = [] @@ -3370,23 +4397,25 @@ def test_resolves_voltage_linear_interpolant(self): assert errors[1] < 1.5e-3 assert errors[2] < 1.5e-4 - def test_scale(self): + def test_scale(self, model_format): model = pybamm.BaseModel() x = pybamm.Variable("x", scale=10) model.rhs = {x: -x} model.initial_conditions = {x: 20} model.variables = {"x": x, "2x": 2 * x} - model.upsampling_variable = "x" - solver = pybamm.IDAKLUSolver(options={"upsampling_tolerance": 1e-3}) - solver.solve(model, [0, 1]) - upsampling_fcn = solver._upsampling_fcn(model, {}) - y0 = model.concatenated_initial_conditions.evaluate() - np.testing.assert_allclose(float(upsampling_fcn(0, y0, [])), 2.0) - # A variable without a scale is used as is - model.upsampling_variable = "2x" - upsampling_fcn = solver._upsampling_fcn(model, {}) - np.testing.assert_allclose(float(upsampling_fcn(0, y0, [])), 40.0) + for name, expected in [("x", 2.0), ("2x", 40.0)]: + model.upsampling_variable = name + solver = pybamm.IDAKLUSolver(options={"upsampling_tolerance": 1e-3}) + solver.solve(model, [0, 1]) + y0 = model.concatenated_initial_conditions.evaluate() + # The function the backend compiled, not the symbol it was given + if model_format == "rust": + upsampling = solver._setup["rust_model"].upsampling + value = upsampling(0.0, y0.ravel(), np.zeros(0)) + else: + value = solver._upsampling_fcn(model, {})(0, y0, []) + np.testing.assert_allclose(np.asarray(value).item(), expected) def test_sensitivities(self): parameter_values = pybamm.ParameterValues("Chen2020") @@ -3460,17 +4489,17 @@ def test_skips_algebraic_and_missing_variables(self, caplog): charge, hold = experiment.steps solver = sim._get_built_experiment_solver(charge) model = sim._get_built_experiment_model(charge) - assert solver._upsampling_fcn(model, {}).n_out() == 1 + assert solver._upsampling_variable(model) is not None model.upsampling_variable = "Not a variable" with caplog.at_level(logging.WARNING, logger="pybamm.logger"): - assert solver._upsampling_fcn(model, {}).n_out() == 0 + assert solver._upsampling_variable(model) is None assert "no 'Not a variable' variable" in caplog.text # In a voltage hold the current is an algebraic state solver = sim._get_built_experiment_solver(hold) model = sim._get_built_experiment_model(hold) assert model.upsampling_variable == "Current [A]" - assert solver._upsampling_fcn(model, {}).n_out() == 0 + assert solver._upsampling_variable(model) is None def test_t_additive_survives_saving_and_joining(self, tmp_path): experiment = pybamm.Experiment( @@ -3567,6 +4596,7 @@ def _inconsistent_dae_model(): return model +@pytest.mark.usefixtures("model_format") class TestIDAKLUNonFiniteResiduals: """A NaN or inf residual makes IDAS cut the step rather than accept it.""" @@ -3691,6 +4721,7 @@ def test_an_infinite_sensitivity_residual_fails(self): ) +@pytest.mark.usefixtures("model_format") class TestIDAKLUFullNewtonIterativeLinearSolver: """``newton_mode="full"`` with an iterative linear solver, which IDA must set up before its linear solver can be driven.""" @@ -3742,6 +4773,7 @@ def test_initial_conditions_and_solution( ) +@pytest.mark.usefixtures("model_format") class TestIDAKLUSensitivityErrorControl: """The ``sensitivity_error_control`` option.""" diff --git a/packages/pybamm/tests/unit/test_solvers/test_nonlinear_solver.py b/packages/pybamm/tests/unit/test_solvers/test_nonlinear_solver.py index 89017871cf..e72944ba4e 100644 --- a/packages/pybamm/tests/unit/test_solvers/test_nonlinear_solver.py +++ b/packages/pybamm/tests/unit/test_solvers/test_nonlinear_solver.py @@ -1,5 +1,6 @@ """Tests for pybamm.NonlinearSolver (C++ Newton algebraic solver wrapper).""" +import gc import logging import pickle @@ -7,6 +8,27 @@ import pytest import pybamm +from pybamm.solvers.nonlinear_solver import _NonlinearSolverSetup +from pybamm.solvers.rust_lowering import RustModelLowering + +FORMATS = pytest.mark.parametrize("convert_to_format", ["casadi", "rust"]) + + +def _discretised(model, convert_to_format): + """Discretise ``model`` in place and set its format.""" + pybamm.Discretisation().process_model(model) + model.convert_to_format = convert_to_format + return model + + +def _root_model(residual, initial, convert_to_format): + """A discretised model with one algebraic state, ``var``, a root of ``residual``.""" + var = pybamm.Variable("var") + model = pybamm.BaseModel() + model.algebraic = {var: residual(var)} + model.initial_conditions = {var: initial} + model.variables = {"var": var} + return _discretised(model, convert_to_format) class TestNonlinearSolver: @@ -42,92 +64,63 @@ def test_an_unknown_option_is_rejected(self): "klu_pivot_tolerance": 0.1, } - def test_simple_root_find(self): - var = pybamm.Variable("var") - model = pybamm.BaseModel() - model.algebraic = {var: var + 2} - model.initial_conditions = {var: 2} - - disc = pybamm.Discretisation() - disc.process_model(model) - - solver = pybamm.NonlinearSolver() - solution = solver.solve(model, np.linspace(0, 1, 10)) - np.testing.assert_array_almost_equal(solution.all_ys[0], -2, decimal=8) - - def test_solve_with_input(self): - var = pybamm.Variable("var") - model = pybamm.BaseModel() - model.algebraic = {var: var + pybamm.InputParameter("param")} - model.initial_conditions = {var: 2} + @FORMATS + def test_simple_root_find(self, convert_to_format): + model = _root_model(lambda var: var + 2, 2, convert_to_format) + solution = pybamm.NonlinearSolver().solve(model, np.linspace(0, 1, 10)) + np.testing.assert_allclose(solution.all_ys[0], -2, atol=1e-8) - disc = pybamm.Discretisation() - disc.process_model(model) - - solver = pybamm.NonlinearSolver() - solution = solver.solve( - model, - np.linspace(0, 1, 10), - inputs={"param": 7}, + @FORMATS + def test_solve_with_input(self, convert_to_format): + model = _root_model( + lambda var: var + pybamm.InputParameter("param"), 2, convert_to_format + ) + solution = pybamm.NonlinearSolver().solve( + model, np.linspace(0, 1, 10), inputs={"param": 7} ) - np.testing.assert_array_almost_equal(solution.all_ys[0], -7, decimal=8) + np.testing.assert_allclose(solution.all_ys[0], -7, atol=1e-8) - def test_model_solver_with_time(self): + @FORMATS + def test_model_solver_with_time(self, convert_to_format): model = pybamm.BaseModel() var1 = pybamm.Variable("var1") var2 = pybamm.Variable("var2") model.algebraic = {var1: var1 - 3 * pybamm.t, var2: 2 * var1 - var2} model.initial_conditions = {var1: pybamm.Scalar(1), var2: pybamm.Scalar(4)} model.variables = {"var1": var1, "var2": var2} - - disc = pybamm.Discretisation() - disc.process_model(model) + _discretised(model, convert_to_format) t_eval = np.linspace(0, 1) - solver = pybamm.NonlinearSolver() - solution = solver.solve(model, t_eval) + solution = pybamm.NonlinearSolver().solve(model, t_eval) sol = np.vstack((3 * t_eval, 6 * t_eval)) np.testing.assert_allclose(solution.all_ys[0], sol, rtol=1e-7, atol=1e-6) np.testing.assert_allclose( - solution["var1"].data.flatten(), - sol[0, :], - rtol=1e-7, - atol=1e-6, + solution["var1"](t_eval), sol[0, :], rtol=1e-7, atol=1e-6 ) np.testing.assert_allclose( - solution["var2"].data.flatten(), - sol[1, :], - rtol=1e-7, - atol=1e-6, + solution["var2"](t_eval), sol[1, :], rtol=1e-7, atol=1e-6 ) - def test_model_solver_with_time_not_changing(self): + @FORMATS + def test_model_solver_with_time_not_changing(self, convert_to_format): model = pybamm.BaseModel() var1 = pybamm.Variable("var1") var2 = pybamm.Variable("var2") model.algebraic = {var1: var1 - 3, var2: 2 * var1 - var2} model.initial_conditions = {var1: pybamm.Scalar(1), var2: pybamm.Scalar(4)} model.variables = {"var1": var1, "var2": var2} - - disc = pybamm.Discretisation() - disc.process_model(model) + _discretised(model, convert_to_format) t_eval = np.linspace(0, 1) - solver = pybamm.NonlinearSolver() - solution = solver.solve(model, t_eval) + solution = pybamm.NonlinearSolver().solve(model, t_eval) sol = np.vstack((3 + 0 * t_eval, 6 + 0 * t_eval)) np.testing.assert_allclose(solution.all_ys[0], sol, rtol=1e-7, atol=1e-6) - def test_solver_caching(self): - var = pybamm.Variable("var") - model = pybamm.BaseModel() - model.algebraic = {var: var + 2} - model.initial_conditions = {var: 2} - - disc = pybamm.Discretisation() - disc.process_model(model) + @FORMATS + def test_solver_caching(self, convert_to_format): + model = _root_model(lambda var: var + 2, 2, convert_to_format) solver = pybamm.NonlinearSolver() solver.solve(model, [0]) @@ -137,66 +130,61 @@ def test_solver_caching(self): solver.solve(model, [0]) assert model.algebraic_root_solver is cached_solver - def test_pickle_round_trip(self): - var = pybamm.Variable("var") - model = pybamm.BaseModel() - model.algebraic = {var: var + 3} - model.initial_conditions = {var: 0} - - disc = pybamm.Discretisation() - disc.process_model(model) + @FORMATS + def test_pickle_round_trip(self, convert_to_format): + model = _root_model(lambda var: var + 3, 0, convert_to_format) solver = pybamm.NonlinearSolver() sol_pre = solver.solve(model, [0]) - np.testing.assert_array_almost_equal(sol_pre.all_ys[0], -3, decimal=8) - # Sanity: live C++ solver was built and attached to the model. + np.testing.assert_allclose(sol_pre.all_ys[0], -3, atol=1e-8) assert model.algebraic_root_solver - # Pickle the model alongside the solver: BaseSolver caches the - # model object identity in ``_model_set_up``, so reusing the same - # solver requires the same (unpickled) model instance. The native - # Newton solver attached to the model is dropped on pickle and - # rebuilt lazily on the next solve. + # BaseSolver keys its set-ups by model identity, so the model travels with + # the solver; its native Newton solver is dropped and rebuilt on solve restored_solver, restored_model = pickle.loads(pickle.dumps((solver, model))) assert not restored_model.algebraic_root_solver sol_post = restored_solver.solve(restored_model, [0]) - np.testing.assert_array_almost_equal(sol_post.all_ys[0], -3, decimal=8) + np.testing.assert_allclose(sol_post.all_ys[0], -3, atol=1e-8) assert restored_model.algebraic_root_solver - def test_sparse_and_dense_modes(self): - model_sparse = pybamm.BaseModel() - var_s = pybamm.Variable("var") - model_sparse.algebraic = {var_s: var_s - 5} - model_sparse.initial_conditions = {var_s: 1} - pybamm.Discretisation().process_model(model_sparse) - - model_dense = pybamm.BaseModel() - var_d = pybamm.Variable("var") - model_dense.algebraic = {var_d: var_d - 5} - model_dense.initial_conditions = {var_d: 1} - pybamm.Discretisation().process_model(model_dense) - + @FORMATS + def test_sparse_and_dense_modes(self, convert_to_format): t_eval = np.linspace(0, 1, 5) - sol_s = pybamm.NonlinearSolver(use_sparse=True).solve(model_sparse, t_eval) - sol_d = pybamm.NonlinearSolver(use_sparse=False).solve(model_dense, t_eval) + solutions = [ + pybamm.NonlinearSolver(use_sparse=use_sparse).solve( + _root_model(lambda var: var - 5, 1, convert_to_format), t_eval + ) + for use_sparse in (True, False) + ] + np.testing.assert_allclose( + solutions[0].all_ys[0], solutions[1].all_ys[0], atol=1e-10 + ) - np.testing.assert_allclose(sol_s.all_ys[0], sol_d.all_ys[0], atol=1e-10) + @FORMATS + def test_klu_pivot_tolerance(self, convert_to_format, monkeypatch): + nonlinear_solver = pybamm.solvers.nonlinear_solver + idaklu = nonlinear_solver.idaklu + received = [] - def test_klu_pivot_tolerance(self): - model = pybamm.BaseModel() - var = pybamm.Variable("var") - model.algebraic = {var: var**3 - 8} - model.initial_conditions = {var: 1} - pybamm.Discretisation().process_model(model) + class RecordingIdaklu: + def __getattr__(self, name): + return getattr(idaklu, name) + def StandaloneNewtonSolver(self, **kwargs): + received.append(kwargs["klu_pivot_tolerance"]) + return idaklu.StandaloneNewtonSolver(**kwargs) + + monkeypatch.setattr(nonlinear_solver, "idaklu", RecordingIdaklu()) t_eval = np.linspace(0, 1, 5) solutions = [ - pybamm.NonlinearSolver(options={"klu_pivot_tolerance": value}).solve( - model, t_eval - ) + pybamm.NonlinearSolver( + use_sparse=True, options={"klu_pivot_tolerance": value} + ).solve(_root_model(lambda var: var**3 - 8, 1, convert_to_format), t_eval) for value in [0.001, 1.0] ] + + np.testing.assert_array_equal(received, [0.001, 1.0]) np.testing.assert_allclose(solutions[0].all_ys[0], 2, rtol=1e-6) np.testing.assert_allclose( solutions[1].all_ys[0], solutions[0].all_ys[0], rtol=1e-10 @@ -205,7 +193,8 @@ def test_klu_pivot_tolerance(self): with pytest.raises(pybamm.SolverError, match="klu_pivot_tolerance"): pybamm.NonlinearSolver(options={"klu_pivot_tolerance": 2.0}) - def test_matches_casadi_algebraic_solver(self): + @FORMATS + def test_matches_casadi_algebraic_solver(self, convert_to_format): from pybamm.models.full_battery_models.lithium_ion.electrode_soh import ( _ElectrodeSOH, ) @@ -215,6 +204,7 @@ def test_matches_casadi_algebraic_solver(self): esoh_model = _ElectrodeSOH(param=li_param) parameter_values.process_model(esoh_model) + esoh_model.convert_to_format = convert_to_format Q_n = parameter_values.evaluate(li_param.n.Q_init) Q_p = parameter_values.evaluate(li_param.p.Q_init) @@ -229,6 +219,7 @@ def test_matches_casadi_algebraic_solver(self): model2 = _ElectrodeSOH(param=li_param) parameter_values.process_model(model2) + model2.convert_to_format = "casadi" sol_casadi = pybamm.CasadiAlgebraicSolver(tol=1e-10).solve( model2, [0], @@ -240,15 +231,7 @@ def test_matches_casadi_algebraic_solver(self): ) def test_used_in_composite_solver(self): - model = pybamm.BaseModel() - var = pybamm.Variable("var") - model.algebraic = {var: var - 7} - model.initial_conditions = {var: pybamm.Scalar(1)} - model.variables = {"var": var} - - disc = pybamm.Discretisation() - disc.process_model(model) - + model = _root_model(lambda var: var - 7, pybamm.Scalar(1), "casadi") composite = pybamm.CompositeSolver( [ pybamm.NonlinearSolver(), @@ -258,15 +241,9 @@ def test_used_in_composite_solver(self): solution = composite.solve(model) np.testing.assert_allclose(solution.all_ys[0], 7, rtol=1e-6) - def test_convergence_failure_raises(self): - var = pybamm.Variable("var") - model = pybamm.BaseModel() - model.algebraic = {var: var**2 + 1} - model.initial_conditions = {var: 2} - - disc = pybamm.Discretisation() - disc.process_model(model) - + @FORMATS + def test_convergence_failure_raises(self, convert_to_format): + model = _root_model(lambda var: var**2 + 1, 2, convert_to_format) solver = pybamm.NonlinearSolver(max_iter=50) with pytest.raises(pybamm.SolverError, match="Could not find acceptable"): solver.solve(model, [0]) @@ -287,15 +264,9 @@ def test_a_failed_solve_returns_the_last_iterate(self): for solution in (warned, ignored): np.testing.assert_array_equal(solution["var"](0.0), -1.0) - def test_debug_log_reports_newton_iterations(self, caplog): - var = pybamm.Variable("var") - model = pybamm.BaseModel() - model.algebraic = {var: var**3 - 2} - model.initial_conditions = {var: 1} - - disc = pybamm.Discretisation() - disc.process_model(model) - + @FORMATS + def test_debug_log_reports_newton_iterations(self, convert_to_format, caplog): + model = _root_model(lambda var: var**3 - 2, 1, convert_to_format) solver = pybamm.NonlinearSolver() with caplog.at_level(logging.DEBUG, logger=pybamm.logger.name): solver.solve(model, [0]) @@ -304,3 +275,216 @@ def test_debug_log_reports_newton_iterations(self, caplog): assert any(m.startswith("Newton solve at t =") for m in messages) assert any(m.startswith("Newton iter") for m in messages) assert any(m.startswith("Newton converged") for m in messages) + + +class TestNonlinearSolverRust: + """The Rust Newton path: what it refuses, and the evaluator it owns.""" + + _NEWTON_OPTIONS = { + "rtol": 1e-4, + "step_tol": 1e-4, + "max_iter": 100, + "max_backtracks": 5, + "eps_newt": 0.33, + "use_sparse": True, + } + + @staticmethod + def _input_model(n_vars=1): + model = pybamm.BaseModel() + param = pybamm.InputParameter("param") + for i in range(n_vars): + var = pybamm.Variable(f"var{i}") + model.algebraic[var] = var + param + model.initial_conditions[var] = pybamm.Scalar(2) + return _discretised(model, "rust") + + @staticmethod + def _quadratic_model(convert_to_format): + # Roots at 1 and 2 for a = 3; Newton from 3 converges to 2 + return _root_model( + lambda var: var**2 - pybamm.InputParameter("a") * var + 2, + 3.0, + convert_to_format, + ) + + def test_matches_casadi_newton(self): + y = { + convert_to_format: pybamm.NonlinearSolver() + .solve(self._quadratic_model(convert_to_format), [0], inputs={"a": 3.0}) + .all_ys[0] + for convert_to_format in ("casadi", "rust") + } + np.testing.assert_allclose(y["rust"], y["casadi"], rtol=1e-10) + np.testing.assert_allclose(y["rust"], 2.0, rtol=1e-8) + + def test_compile_option_is_rejected(self): + model = _root_model(lambda var: var + 2, 2, "rust") + solver = pybamm.NonlinearSolver(options={"compile": True}) + with pytest.raises(pybamm.SolverError, match=r"CasADi-only"): + solver.solve(model, np.linspace(0, 1, 5)) + + def test_sensitivity_extended_states_are_rejected(self): + model = self._input_model() + # A sensitivity-extended state block reaches the root solver as a longer y0 + model.y0_list = [np.zeros(model.len_rhs_and_alg + 1)] + + solver = pybamm.NonlinearSolver() + with pytest.raises(pybamm.SolverError, match=r"sensitivity-extended"): + solver._set_up_root_solver_rust(model, {"param": 7.0}) + + @pytest.mark.parametrize( + ("y0_alg", "p_vec", "match"), + [ + ([2.0], [], r"\[y_diff; inputs\] of length 1 but got 0"), + ([2.0], [7.0, 1.0], r"\[y_diff; inputs\] of length 1 but got 2"), + ([2.0, 2.0], [7.0], r"y0_alg of length 1 but got 2"), + ], + ) + def test_buffers_of_another_length_are_rejected(self, y0_alg, p_vec, match): + # C++ reads both at the set-up lengths, so a short one would be overrun + setup = pybamm.NonlinearSolver()._set_up_root_solver_rust( + self._input_model(), {"param": 7.0} + ) + with pytest.raises(pybamm.SolverError, match=match): + setup.solve_batch(np.zeros(1), np.array(y0_alg), np.array(p_vec)) + success, y = setup.solve_batch(np.zeros(1), np.array([2.0]), np.array([7.0])) + assert success + np.testing.assert_allclose(y, -7.0) + + def test_a_rust_model_of_another_size_is_rejected(self, monkeypatch): + other = RustModelLowering.of( + self._input_model(n_vars=2), {"param": 7.0} + ).compile_model() + monkeypatch.setattr( + RustModelLowering, "compile_model", lambda lowering, **kwargs: other + ) + + solver = pybamm.NonlinearSolver() + with pytest.raises( + pybamm.SolverError, match=r"has 2 states, 2 of them algebraic.*1 and 1" + ): + solver._set_up_root_solver_rust(self._input_model(), {"param": 7.0}) + + def test_a_rust_newton_solver_takes_only_atol_s_size_from_python(self): + # The evaluator gives the block's size and pattern, so atol is all left to check + from pybammsolvers import idaklu + + lowering = RustModelLowering.of(self._input_model(n_vars=2), {"param": 7.0}) + rust_model = lowering.compile_model() + # Each solver claims and owns its evaluator, so one cannot serve two + evaluator = rust_model.evaluator() + idaklu.StandaloneNewtonSolver( + rust_evaluator=evaluator, atol=[1e-6] * 2, **self._NEWTON_OPTIONS + ) + with pytest.raises(ValueError, match=r"already claimed by a solver"): + idaklu.StandaloneNewtonSolver( + rust_evaluator=evaluator, atol=[1e-6] * 2, **self._NEWTON_OPTIONS + ) + + with pytest.raises( + ValueError, + match=r"atol has length 1 but the Rust model has 2 algebraic states\.", + ): + idaklu.StandaloneNewtonSolver( + rust_evaluator=rust_model.evaluator(), + atol=[1e-6], + **self._NEWTON_OPTIONS, + ) + + def test_a_rust_newton_solver_refuses_a_model_without_algebraic_states(self): + from pybammsolvers import idaklu + + model = pybamm.BaseModel() + var = pybamm.Variable("var") + model.rhs = {var: -var} + model.initial_conditions = {var: 1} + rust_model = RustModelLowering.of( + _discretised(model, "rust"), [] + ).compile_model() + + with pytest.raises(ValueError, match=r"has no algebraic block for the Newton"): + idaklu.StandaloneNewtonSolver( + rust_evaluator=rust_model.evaluator(), atol=[], **self._NEWTON_OPTIONS + ) + + def test_a_rust_newton_solver_refuses_a_bare_address(self): + from pybammsolvers import idaklu + + with pytest.raises( + ValueError, match=r"expected a 'pybamm\.rust\.evaluator' capsule, got int" + ): + idaklu.StandaloneNewtonSolver( + rust_evaluator=0xDEAD0, atol=[1e-8], **self._NEWTON_OPTIONS + ) + + def test_a_rust_newton_solver_owns_its_evaluator(self): + setup = pybamm.NonlinearSolver()._set_up_root_solver_rust( + self._quadratic_model("rust"), {"a": 3.0} + ) + # Only the C++ solver still holds the evaluator it claimed + gc.collect() + success, y = setup.solve_batch( + np.array([0.0]), np.array([3.0]), np.array([3.0]) + ) + assert success + np.testing.assert_allclose(y[:, 0], [2.0], rtol=1e-6) + + def test_a_rust_newton_set_up_pickles_to_inert(self): + # The C++ Newton set-up owns the evaluator it claimed, which cannot travel + setup = pybamm.NonlinearSolver()._set_up_root_solver_rust( + self._quadratic_model("rust"), {"a": 3.0} + ) + assert bool(setup) is True + restored = pickle.loads(pickle.dumps(setup)) + assert isinstance(restored, _NonlinearSolverSetup) + assert restored._setup is None + assert bool(restored) is False + + def test_a_dae_s_algebraic_states_solve_at_its_differential_states( + self, monkeypatch + ): + # Without calc_ic, set-up's Newton solve holds the trailing algebraic state: + # v - 2u = 0 at u = 1 + set_ups = [] + set_up = pybamm.NonlinearSolver._set_up_root_solver_rust + + def recording_set_up(solver, model, inputs_dict): + set_ups.append(model.len_rhs) + return set_up(solver, model, inputs_dict) + + monkeypatch.setattr( + pybamm.NonlinearSolver, "_set_up_root_solver_rust", recording_set_up + ) + model = pybamm.BaseModel() + u = pybamm.Variable("u") + v = pybamm.Variable("v") + model.rhs = {u: -v} + model.algebraic = {v: v - 2 * u} + model.initial_conditions = {u: 1, v: 5} + _discretised(model, "rust") + + solution = pybamm.IDAKLUSolver(options={"calc_ic": False}).solve(model, [0, 1]) + + assert set_ups == [1] + np.testing.assert_allclose(solution.all_ys[0][:, 0], [1.0, 2.0], rtol=1e-6) + + def test_a_dae_matches_casadi_newton(self): + # A Newton solve of the trailing algebraic block, behind the rhs states + t_eval = np.linspace(0, 1, 20) + ys = {} + for convert_to_format in ("casadi", "rust"): + model = pybamm.BaseModel() + u = pybamm.Variable("u") + w = pybamm.Variable("w") + a = pybamm.InputParameter("a") + model.rhs = {u: -a * u} + model.algebraic = {w: w**2 - a * w + 2 * u} + model.initial_conditions = {u: 1.0, w: 3.0} + _discretised(model, convert_to_format) + solver = pybamm.IDAKLUSolver( + rtol=1e-8, atol=1e-10, root_method="nonlinear_solver" + ) + solution = solver.solve(model, t_eval, inputs={"a": 3.0}, t_interp=t_eval) + ys[convert_to_format] = np.hstack(solution.all_ys) + np.testing.assert_allclose(ys["rust"], ys["casadi"], rtol=1e-6) diff --git a/packages/pybamm/tests/unit/test_solvers/test_observation_layout.py b/packages/pybamm/tests/unit/test_solvers/test_observation_layout.py index e7e88acd92..1f9d9068cf 100644 --- a/packages/pybamm/tests/unit/test_solvers/test_observation_layout.py +++ b/packages/pybamm/tests/unit/test_solvers/test_observation_layout.py @@ -128,6 +128,26 @@ def test_sensitivities_of_the_wrong_shape_are_rejected(self, solution): sensitivity_names=["a", "b"], ) + def test_a_dense_layout_attaches_without_casadi_functions(self, solution): + model = solution.all_models[0] + lens = [ + int(np.prod(model.get_processed_variable_or_event(name).shape)) + for name in self._NAMES + ] + assembly = OutputAssembly.dense(self._NAMES, lens) + data = np.tile(np.arange(assembly.n_rows, dtype=float), (len(solution.t), 1)) + assembly.attach(solution, data) + + assert solution["Voltage [V]"].base_variables_casadi == [None] + np.testing.assert_allclose( + solution[self._NAMES[1]].entries[:, 0], np.arange(1.0, 21.0) + ) + np.testing.assert_allclose(solution["Current [A]"].entries, 21.0) + + def test_a_dense_layout_needs_one_length_per_name(self): + with pytest.raises(pybamm.SolverError, match=r"Output layout mismatch"): + OutputAssembly.dense(["Voltage [V]", "Current [A]"], [1]) + def test_a_solve_without_sensitivities_leaves_an_empty_mapping(self, solution): # Empty, not None: an outputs-only solve keeps no state to compute them from assembly, data = self._assembly(solution, ["Voltage [V]"]) diff --git a/packages/pybamm/tests/unit/test_solvers/test_process_rust.py b/packages/pybamm/tests/unit/test_solvers/test_process_rust.py index b40821cec1..33a9d66cd1 100644 --- a/packages/pybamm/tests/unit/test_solvers/test_process_rust.py +++ b/packages/pybamm/tests/unit/test_solvers/test_process_rust.py @@ -242,14 +242,26 @@ def test_jac_returns_scipy_csc(self): assert scipy.sparse.issparse(jac) np.testing.assert_allclose(jac.toarray(), [[3.0, -1.0], [1.0, -4.0]]) - def test_jac_action_matches_jac_matvec(self): + def test_rows_select_the_output_rows(self): from pybamm.solvers.rust_evaluator import RustEvaluator cf = self._cf() - y, p, v = np.array([1.5, -2.0]), np.array([3.0]), np.array([0.3, 0.7]) - jv = RustEvaluator(cf, "jac_action")(0.0, y, p, v) - full = RustEvaluator(cf, "jac")(0.0, y, p).toarray() @ v - np.testing.assert_allclose(jv.ravel(), full) + y, p = np.array([1.5, -2.0]), np.array([3.0]) + rows = slice(1, 2) + np.testing.assert_allclose( + RustEvaluator(cf, "func", rows=rows)(0.0, y, p), [[5.5]] + ) + jac = RustEvaluator(cf, "jac", rows=rows)(0.0, y, p) + np.testing.assert_allclose(jac.toarray(), [[1.0, -4.0]]) + + def test_a_prepared_jacobian_is_used_as_given(self): + from pybamm.solvers.rust_evaluator import RustEvaluator + + cf = self._cf() + prepared = cf.jacobian("y") + ev = RustEvaluator(cf, "jac", jacobian=prepared) + ev(0.0, np.array([1.5, -2.0]), np.array([3.0])) + assert ev._jac is prepared def test_jacp_tuple_per_param(self): from pybamm.solvers.rust_evaluator import RustEvaluator @@ -261,13 +273,11 @@ def test_jacp_tuple_per_param(self): assert isinstance(out, tuple) and len(out) == 1 np.testing.assert_allclose(out[0].ravel(), [1.5, 0.0]) - def test_jac_action_without_v_and_jacp_without_indices_raise(self): + def test_jacp_without_indices_raises(self): from pybamm.solvers.rust_evaluator import RustEvaluator cf = self._cf() y, p = np.array([1.5, -2.0]), np.array([3.0]) - with pytest.raises(pybamm.SolverError, match="needs the vector v"): - RustEvaluator(cf, "jac_action")(0.0, y, p) with pytest.raises(pybamm.SolverError, match="needs sens_indices"): RustEvaluator(cf, "jacp")(0.0, y, p) @@ -296,6 +306,13 @@ def _jacp_as_list(result): return [np.asarray(j).ravel() for j in result] +def _dense(value): + """A CasADi or Rust evaluator's output as a dense array.""" + if isinstance(value, casadi.DM): + return np.asarray(value.full()) + return value.toarray() if scipy.sparse.issparse(value) else np.asarray(value) + + def _toy_dae(convert_to_format): model = pybamm.BaseModel() u = pybamm.Variable("u") @@ -334,31 +351,30 @@ def _stack(self, fmt, inputs): return casadi.vertcat(*inputs.values()) return np.array(list(inputs.values()), dtype=np.float64) - def test_rhs_algebraic_func_jac_action_jacp(self, pair): - from pybamm.solvers.base_solver import process + def test_the_model_views_match_casadi(self): + from pybamm.solvers.base_solver import BaseSolver t, y, inputs = 0.3, np.array([1.1, 0.4]), {"a": 0.5} results = {} - for fmt, (_model, vars_, rhs_alg) in pair.items(): - func, jac, jacp, jac_action = process(rhs_alg, "rhs_algebraic", vars_) + for fmt in ("casadi", "rust"): + model = _toy_dae(fmt) + BaseSolver().set_up(model, inputs=[inputs]) p = self._stack(fmt, inputs) - jac_mat = jac(t, y, p) results[fmt] = { - "f": np.asarray(func(t, y, p)).ravel(), - "jac": np.asarray( - jac_mat.toarray() if hasattr(jac_mat, "toarray") else jac_mat - ), - "jv": np.asarray(jac_action(t, y, p, np.array([0.2, -0.3]))).ravel(), - "jacp": _jacp_as_list(jacp(t, y, p)), + name: _dense(getattr(model, name)(t, y, p)) + for name in ( + "rhs_eval", + "algebraic_eval", + "rhs_algebraic_eval", + "jac_rhs_eval", + "jac_algebraic_eval", + "jac_rhs_algebraic_eval", + ) } - for key in ("f", "jac", "jv"): + for name, value in results["rust"].items(): np.testing.assert_allclose( - results["rust"][key], results["casadi"][key], rtol=1e-12, atol=1e-14 + value, results["casadi"][name], rtol=1e-12, atol=1e-14, err_msg=name ) - for r, c in zip( - results["rust"]["jacp"], results["casadi"]["jacp"], strict=True - ): - np.testing.assert_allclose(r, c, rtol=1e-12, atol=1e-14) def test_event_and_ic_eval_only(self, pair): from pybamm.solvers.base_solver import process @@ -385,21 +401,25 @@ def test_event_and_ic_eval_only(self, pair): def test_state_derivative_event_matches_casadi(self, pair): from pybamm.solvers.base_solver import process + from pybamm.solvers.rust_lowering import RustModelLowering t, y, y_dot = 0.0, np.array([1.0, 2.0]), np.array([-1.5, 0.5]) - vals = {} u, v = pybamm.StateVector(slice(0, 1)), pybamm.StateVector(slice(1, 2)) - for fmt, (_model, vars_, _) in pair.items(): - event = process( - 1 + u.diff(pybamm.t) * v, - "event_0", - vars_, - use_jacobian=False, - use_state_derivatives=True, - )[0] - p = self._stack(fmt, {"a": 0.5}) - vals[fmt] = float(np.asarray(event(t, y, p, y_dot)).item()) - assert vals["rust"] == pytest.approx(vals["casadi"], rel=1e-12) + expression = 1 + u.diff(pybamm.t) * v + p = {fmt: self._stack(fmt, {"a": 0.5}) for fmt in pair} + _, vars_, _ = pair["casadi"] + event = process( + expression, "event_0", vars_, use_jacobian=False, use_state_derivatives=True + )[0] + rust_model = pair["rust"][0] + rust_model.events = [pybamm.Event("event_0", expression)] + compiled = RustModelLowering.of(rust_model, {"a": 0.5}).compile_model() + + rust_value = compiled.events[0](t, y, p["rust"], y_dot) + casadi_value = event(t, y, p["casadi"], y_dot) + assert float(np.asarray(rust_value).item()) == pytest.approx( + float(np.asarray(casadi_value).item()), rel=1e-12 + ) @pytest.mark.parametrize("fmt", ["casadi", "rust"]) def test_state_derivative_event_needs_state_derivatives(self, pair, fmt): @@ -410,35 +430,43 @@ def test_state_derivative_event_needs_state_derivatives(self, pair, fmt): with pytest.raises(pybamm.ModelError, match=r"Must provide a 'y_dot'"): process(expression, "event_0", vars_, use_jacobian=False) - def test_rectangular_group_jacobian_matches_casadi(self, pair): - from pybamm.solvers.base_solver import process - t, y = 0.3, np.array([1.1, 0.4]) - mats = {} - for fmt, (model, vars_, _) in pair.items(): - _, jac, _, jac_action = process(model.concatenated_rhs, "RHS", vars_) - assert jac is not None and jac_action is not None - p = self._stack(fmt, inputs={"a": 0.5}) - jm = jac(t, y, p) - mats[fmt] = np.asarray(jm.toarray() if hasattr(jm, "toarray") else jm) - np.testing.assert_allclose(mats["rust"], mats["casadi"], rtol=1e-12, atol=1e-14) +class TestRustModelSetUp: + def test_every_solver_views_its_evaluators_from_the_compiled_model(self): + from pybamm.solvers.base_solver import BaseSolver + from pybamm.solvers.rust_lowering import RustModelLowering + model = _toy_dae("rust") -class TestProcessRustDuplication: - def test_lazy_jac_not_built_for_uncalled_groups(self): - from pybamm.solvers.base_solver import BaseSolver, process - from pybamm.solvers.rust_evaluator import RustEvaluator + BaseSolver().set_up(model, inputs=[{"a": 0.5}]) + + compiled = RustModelLowering.current(model).compiled + assert model.rhs_eval._cf is compiled.rhs + assert model.rhs_algebraic_eval._cf is compiled.rhs + assert model.algebraic_eval._cf is compiled.algebraic_residual + assert model.jac_rhs_algebraic_eval._jac is compiled.jacobian + assert model.jac_rhs_action_eval is None + assert model.jacp_rhs_eval is None + + def test_rust_output_block_skipped(self, monkeypatch): + from pybamm.solvers.base_solver import BaseSolver model = _toy_dae("rust") - model.calculate_sensitivities = [] - vars_ = BaseSolver._get_vars_for_processing(model, {"a": 0.5}) - _, jac, _, jac_action = process(model.concatenated_rhs, "RHS", vars_) - assert ( - isinstance(jac, RustEvaluator) - and jac._jac is None - and jac_action is not None + solver = BaseSolver(output_variables=["u"]) + + monkeypatch.setattr( + BaseSolver, "_set_initial_conditions", lambda *a, **kw: None + ) + monkeypatch.setattr( + BaseSolver, + "_set_up_events", + lambda *a, **kw: ([], [], [], {}, [], []), ) + solver.set_up(model, inputs=[{"a": 0.5}]) + + assert solver.computed_var_fcns == {} + class TestStackedInputPredicate: def test_stack_inputs_rust_is_ndarray(self): @@ -479,6 +507,25 @@ def test_casadi_solver_converts_rust_model_with_a_warning(self, caplog): assert model.convert_to_format == "casadi" assert "Converting" in caplog.text + def test_casadi_root_method_is_kept_while_rust_models_use_newton(self): + class _DaeSolver(pybamm.BaseSolver): + def _run(self, *a, **kw): # pragma: no cover + raise NotImplementedError + + model = _toy_dae("rust") + solver = _DaeSolver() + solver.root_method = "casadi" + solver._check_and_prepare_model_inplace(model) + assert isinstance(solver.root_method, pybamm.CasadiAlgebraicSolver) + assert model.convert_to_format == "rust" # never silently forced + + newton = solver._root_method_for(model) + assert isinstance(newton, pybamm.NonlinearSolver) + assert solver._root_method_for(model) is newton + assert solver._root_method_for(_toy_dae("casadi")) is solver.root_method + solver.on_failure = "warn" + assert newton.on_failure == "warn" + @pytest.mark.parametrize("width", [1, 3]) def test_an_input_of_another_width_is_a_solver_error(self, width): model = pybamm.BaseModel() @@ -524,20 +571,35 @@ def test_a_vector_input_only_variables_use_must_be_given(self): np.testing.assert_allclose(solution.y, 1.0, rtol=1e-6, atol=1e-6) assert model.solution_observable_status == enabled - def test_return_jacp_stacked_is_rejected_before_compiling(self, monkeypatch): - from pybamm.solvers import rust_lowering + def test_process_derives_a_jacobian_on_its_first_call(self): from pybamm.solvers.base_solver import BaseSolver, process model = _toy_dae("rust") - model.calculate_sensitivities = ["a"] + model.calculate_sensitivities = [] vars_ = BaseSolver._get_vars_for_processing(model, {"a": 0.5}) + _, jac, _, jac_action = process(model.concatenated_rhs, "RHS", vars_) - def no_lowering(*args, **kwargs): # pragma: no cover - raise AssertionError("lowered before rejecting return_jacp_stacked") + assert jac._jac is None and jac_action is None + value = jac(0.0, np.array([3.0, 4.0]), np.array([0.5])) + np.testing.assert_allclose(value.toarray(), [[-2.0, 0.5]]) + + @pytest.mark.parametrize( + ("option", "match"), + [ + ("use_state_derivatives", r"cannot read y_dot"), + ("return_jacp_stacked", r"return_jacp_stacked"), + ], + ) + def test_process_refuses_what_a_rust_model_does_not_convert(self, option, match): + from pybamm.solvers.base_solver import BaseSolver, process - monkeypatch.setattr(rust_lowering, "rust_graph_with_inputs", no_lowering) - with pytest.raises(pybamm.SolverError, match=r"return_jacp_stacked"): - process(model.concatenated_rhs, "RHS", vars_, return_jacp_stacked=True) + model = _toy_dae("rust") + model.calculate_sensitivities = ["a"] + vars_ = BaseSolver._get_vars_for_processing(model, {"a": 0.5}) + nodes = vars_["lowering"].graph.n_nodes + with pytest.raises(pybamm.SolverError, match=match): + process(model.concatenated_rhs, "RHS", vars_, **{option: True}) + assert vars_["lowering"].graph.n_nodes == nodes def test_return_jacp_stacked_without_sensitivities_compiles(self): # Output variables always pass return_jacp_stacked, with or without sensitivities @@ -768,6 +830,27 @@ def test_rebuild_rejects_names_without_lengths(self): with pytest.raises(ValueError, match=r"output_names and output_lens"): CompiledFunction._rebuild(graph, expr.id, None, None, 0, ["y"]) + def test_compiled_model_pickle_roundtrip(self): + import pickle + + model = pybamm.BaseModel() + u = pybamm.Variable("u") + v = pybamm.Variable("v") + model.rhs = {u: 0.1 * v} + model.algebraic = {v: 2 * u - v} + model.initial_conditions = {u: 0, v: 0} + model.convert_to_format = "rust" + disc = pybamm.Discretisation() + disc.process_model(model) + solver = pybamm.IDAKLUSolver() + solver.solve(model, np.array([0.0, 1.0])) + rm = solver._setup["rust_model"] + rm2 = pickle.loads(pickle.dumps(rm)) + assert rm2.nnz == rm.nnz + np.testing.assert_array_equal( + rm2.csc_sparsity_pattern()[0], rm.csc_sparsity_pattern()[0] + ) + def test_rust_evaluator_pickle_rederives_jacobian(self): import pickle diff --git a/packages/pybamm/tests/unit/test_solvers/test_rust_jacobian_assembly_cost.py b/packages/pybamm/tests/unit/test_solvers/test_rust_jacobian_assembly_cost.py new file mode 100644 index 0000000000..f6db56f8bc --- /dev/null +++ b/packages/pybamm/tests/unit/test_solvers/test_rust_jacobian_assembly_cost.py @@ -0,0 +1,141 @@ +"""Budgets on the tangent-tape walks one Jacobian assembly costs.""" + +import numpy as np +import pytest + +import pybamm +from tests.shared import POUCH_OPTIONS, POUCH_PTS, build_rust_model + + +def sweeps_per_assembly(stats): + """Batched colour sweeps plus one reverse pass per split dense row.""" + batched = -(-stats["n_colors"] // stats["jac_lane_width"]) + return batched + stats["n_dense_rows"] + + +def _stats_for_model(model, var_pts=None): + """`(jacobian_stats, n_states)` for a plainly built model.""" + built, rust_model = build_rust_model(model, var_pts) + return rust_model.jacobian_stats(), built.len_rhs_and_alg + + +def _stats_for_step(model, step, var_pts, key_prefix): + """`(jacobian_stats, n_states)` for one experiment step's own model.""" + model.convert_to_format = "rust" + sim = pybamm.Simulation( + model, var_pts=var_pts, experiment=pybamm.Experiment([step]) + ) + sim.build_for_experiment() + built = next( + m for key, m in sim.steps_to_built_models.items() if key.startswith(key_prefix) + ) + solver = pybamm.IDAKLUSolver() + solver.set_up(built, inputs={}, t_eval=np.array([0.0, 1.0])) + return solver._setup["rust_model"].jacobian_stats(), built.len_rhs_and_alg + + +PLAIN_CASES = [ + ("SPM", lambda: pybamm.lithium_ion.SPM(), None, 1), + ("SPMe", lambda: pybamm.lithium_ion.SPMe(), None, 3), + ( + "SPMe-voltage-as-a-state", + lambda: pybamm.lithium_ion.SPMe({"voltage as a state": "true"}), + None, + 4, + ), + ("DFN", lambda: pybamm.lithium_ion.DFN(), None, 3), + ( + "DFN-fine", + lambda: pybamm.lithium_ion.DFN(), + {"x_n": 30, "x_s": 30, "x_p": 30, "r_n": 30, "r_p": 30}, + 3, + ), +] + +STEP_CASES = [ + ("pouch-2plus1D-CC", POUCH_OPTIONS, "Discharge at 1C until 2.7 V", "CRate", 3), + ("pouch-2plus1D-CV", POUCH_OPTIONS, "Hold at 4.1 V until C/20", "Voltage", 4), + ( + "pouch-1plus1D-CV", + {"current collector": "potential pair", "dimensionality": 1}, + "Hold at 4.1 V until C/20", + "Voltage", + 3, + ), +] + + +class TestAssemblySweepBudget: + @pytest.mark.parametrize( + ("name", "build", "var_pts", "budget"), + PLAIN_CASES, + ids=[case[0] for case in PLAIN_CASES], + ) + def test_plain_model_stays_within_sweep_budget(self, name, build, var_pts, budget): + stats, _ = _stats_for_model(build(), var_pts) + assert sweeps_per_assembly(stats) <= budget, ( + f"{name} assembles in {sweeps_per_assembly(stats)} sweeps " + f"(budget {budget}): {stats}" + ) + + @pytest.mark.parametrize( + ("name", "options", "step", "prefix", "budget"), + STEP_CASES, + ids=[case[0] for case in STEP_CASES], + ) + def test_experiment_step_stays_within_sweep_budget( + self, name, options, step, prefix, budget + ): + var_pts = POUCH_PTS if options["dimensionality"] == 2 else None + if options["dimensionality"] == 1: + var_pts = {"x_n": 4, "x_s": 4, "x_p": 4, "r_n": 4, "r_p": 4, "z": 10} + stats, _ = _stats_for_step( + pybamm.lithium_ion.DFN(options), step, var_pts, prefix + ) + assert sweeps_per_assembly(stats) <= budget, ( + f"{name} assembles in {sweeps_per_assembly(stats)} sweeps " + f"(budget {budget}): {stats}" + ) + + +class TestNoWideRowEscapesTheSplit: + def test_a_constraint_row_never_sets_the_colour_count(self): + stats, _ = _stats_for_step( + pybamm.lithium_ion.DFN(POUCH_OPTIONS), + "Hold at 4.1 V until C/20", + POUCH_PTS, + "Voltage", + ) + # Split or folded, the CV row must not force a colour per column it reads. + assert 10 * stats["n_colors"] < stats["n_swept_columns"] + + def test_batching_engages_on_a_multi_colour_model(self): + for stats, _ in ( + _stats_for_model(pybamm.lithium_ion.DFN()), + _stats_for_step( + pybamm.lithium_ion.DFN(POUCH_OPTIONS), + "Hold at 4.1 V until C/20", + POUCH_PTS, + "Voltage", + ), + ): + assert stats["n_colors"] > 1 + assert stats["jac_lane_width"] > 1 + + +class TestConstantEntriesCarryTheirWeight: + def test_a_dfn_proves_most_of_its_entries_constant(self): + stats, n_states = _stats_for_model(pybamm.lithium_ion.DFN()) + assert stats["n_constant_entries"] > stats["nnz"] // 2 + assert stats["n_swept_columns"] < n_states + + def test_the_pouch_stops_colouring_against_its_constant_rows(self): + stats, n_states = _stats_for_step( + pybamm.lithium_ion.DFN(POUCH_OPTIONS), + "Discharge at 1C until 2.7 V", + POUCH_PTS, + "CRate", + ) + assert stats["n_constant_entries"] > stats["nnz"] // 10 + # Wholly constant current-collector columns are never seeded. + assert stats["n_swept_columns"] < n_states diff --git a/packages/pybamm/tests/unit/test_solvers/test_rust_jacobian_batching.py b/packages/pybamm/tests/unit/test_solvers/test_rust_jacobian_batching.py new file mode 100644 index 0000000000..52f5b61235 --- /dev/null +++ b/packages/pybamm/tests/unit/test_solvers/test_rust_jacobian_batching.py @@ -0,0 +1,77 @@ +"""Coloured Jacobian assembly batches its tangent sweeps without changing values.""" + +import numpy as np +import pytest + +import pybamm +from tests.shared import ( + POUCH_OPTIONS, + POUCH_PTS, + build_rust_model, + dense_casadi_jacobian, + dense_rust_jacobian, +) + +pytest.importorskip("casadi") + + +class TestLaneWidth: + def test_a_dfn_batches_its_colour_sweeps(self): + _, rust_model = build_rust_model(pybamm.lithium_ion.DFN()) + stats = rust_model.jacobian_stats() + assert stats["n_colors"] > 1 + assert stats["jac_lane_width"] > 1 + + def test_a_single_colour_model_stays_scalar(self): + # Nonlinear, so the one entry is genuinely swept rather than folded. + model = pybamm.BaseModel() + model.convert_to_format = "rust" + var = pybamm.Variable("var") + model.rhs = {var: -(var**2)} + model.initial_conditions = {var: 1.0} + solver = pybamm.IDAKLUSolver() + solver.set_up(model, inputs=[{}]) + stats = solver._setup["rust_model"].jacobian_stats() + assert stats["n_colors"] == 1 + assert stats["jac_lane_width"] == 1 + + def test_a_linear_model_needs_no_colour_at_all(self): + model = pybamm.BaseModel() + model.convert_to_format = "rust" + var = pybamm.Variable("var") + model.rhs = {var: -var} + model.initial_conditions = {var: 1.0} + solver = pybamm.IDAKLUSolver(rtol=1e-10, atol=1e-10) + solver.set_up(model, inputs=[{}]) + stats = solver._setup["rust_model"].jacobian_stats() + assert stats["n_colors"] == 0 + assert stats["n_swept_columns"] == 0 + assert stats["n_constant_entries"] == 1 + + t = np.linspace(0, 1, 5) + solution = solver.solve(model, t_eval=[0, 1], t_interp=t) + np.testing.assert_allclose(solution["var"](t), np.exp(-t), rtol=1e-7, atol=1e-7) + + +class TestAssembledValues: + def test_batched_assembly_matches_casadi(self): + built, rust_model = build_rust_model(pybamm.lithium_ion.DFN()) + assert rust_model.jacobian_stats()["jac_lane_width"] > 1 + + y, got = dense_rust_jacobian(built, rust_model) + want = dense_casadi_jacobian(pybamm.lithium_ion.DFN(), y) + np.testing.assert_allclose(got, want, rtol=1e-10, atol=1e-10) + + def test_pouch_assembly_matches_casadi(self): + """The pouch is the model whose colouring the constant split changes.""" + var_pts = POUCH_PTS | {"y": 4, "z": 4} + built, rust_model = build_rust_model( + pybamm.lithium_ion.DFN(POUCH_OPTIONS), var_pts + ) + stats = rust_model.jacobian_stats() + assert stats["n_constant_entries"] > 0 + assert stats["n_swept_columns"] < built.len_rhs_and_alg + + y, got = dense_rust_jacobian(built, rust_model) + want = dense_casadi_jacobian(pybamm.lithium_ion.DFN(POUCH_OPTIONS), y, var_pts) + np.testing.assert_allclose(got, want, rtol=1e-10, atol=1e-10) diff --git a/packages/pybamm/tests/unit/test_solvers/test_rust_lowering.py b/packages/pybamm/tests/unit/test_solvers/test_rust_lowering.py new file mode 100644 index 0000000000..07b4bb5103 --- /dev/null +++ b/packages/pybamm/tests/unit/test_solvers/test_rust_lowering.py @@ -0,0 +1,349 @@ +"""Invariants every Rust-backed solver's model lowering must share.""" + +import numpy as np +import pytest + +import pybamm +from pybamm.solvers.rust_lowering import RustModelLowering + +_VECTOR_VAR = "Negative particle surface concentration [mol.m-3]" +_OUTPUTS = ["Voltage [V]", _VECTOR_VAR, "Current [A]"] + + +def _built_model(with_input=False, options=None): + """Build an SPM pinned to the Rust format, not the ambient default.""" + model = pybamm.lithium_ion.SPM(options) + model.convert_to_format = "rust" + params = model.default_parameter_values + if with_input: + params["Current function [A]"] = "[input]" + sim = pybamm.Simulation(model, parameter_values=params) + sim.build() + built = sim.built_model + built.convert_to_format = "rust" + return built + + +def _termination_events(model): + return [ + event + for event in model.events + if event.event_type == pybamm.EventType.TERMINATION + ] + + +class TestOutputLengths: + def test_lengths_are_the_flattened_component_counts(self): + compiled = RustModelLowering.of(_built_model(), {}).compile_model( + output_variables=_OUTPUTS + ) + + lengths = [output.output_len for output in compiled.outputs] + assert lengths[0] == 1 + assert lengths[1] > 1, "a spatial variable gives every value" + assert lengths[2] == 1 + + def test_tensor_field_output_is_rejected(self): + model = _built_model() + lowering = RustModelLowering.of(model, {}) + component = model.get_processed_variable_or_event(_VECTOR_VAR) + model.variables_and_events["field"] = pybamm.VectorField(component, component) + + with pytest.raises(pybamm.SolverError, match=r"'field' is a tensor field"): + lowering.compile_model(output_variables=["field"]) + + +class TestInputRegistration: + def test_graph_input_order_follows_the_inputs_dict(self): + model = _built_model(with_input=True) + inputs = {"Current function [A]": 0.5} + + lowering = RustModelLowering.of(model, inputs) + + assert lowering.input_name_order == list(inputs) + assert lowering.graph.input_index("Current function [A]") == 0 + + def test_sensitivities_are_compiled_for_the_named_inputs(self): + model = _built_model(with_input=True) + lowering = RustModelLowering.of(model, {"Current function [A]": 0.5}) + + compiled = lowering.compile_model(sensitivities=["Current function [A]"]) + + assert compiled.n_sens_params == 1 + + def test_sensitivity_names_not_supplied_as_inputs_are_rejected(self): + model = _built_model(with_input=True) + lowering = RustModelLowering.of(model, {"Current function [A]": 0.5}) + + with pytest.raises( + pybamm.SolverError, + match=r"Sensitivities were requested for \['Not an input'\]", + ): + lowering.compile_model( + sensitivities=["Current function [A]", "Not an input"] + ) + + def test_an_input_the_graph_does_not_register_is_refused(self): + model = _built_model() + lowering = RustModelLowering.of(model, {}) + + with pytest.raises(pybamm.SolverError, match=r"'other' is not one of"): + lowering.lower(pybamm.InputParameter("other") * pybamm.t) + + assert lowering.graph.input_index("other") is None + assert lowering.graph.n_inputs() == 0 + + +class TestCompileModel: + def test_dae_residual_spans_every_state(self): + model = _built_model(options={"surface form": "algebraic"}) + + compiled = RustModelLowering.of(model, {}).compile_model() + + assert compiled.n_states == model.len_rhs_and_alg + assert compiled.n_algebraic == model.len_alg + + def test_a_model_without_states_compiles(self): + model = pybamm.BaseModel() + model.variables = {"v": pybamm.Scalar(1)} + model.events = [pybamm.Event("t > 5", 5 - pybamm.t)] + model.convert_to_format = "rust" + pybamm.Discretisation().process_model(model) + + compiled = RustModelLowering.of(model, {}).compile_model() + + assert compiled.n_states == 0 + np.testing.assert_allclose( + compiled.events[0](3.0, np.array([]), np.array([])), [2.0] + ) + + def test_a_failed_compile_keeps_the_previous_one(self): + model = _built_model() + lowering = RustModelLowering.of(model, {}) + compiled = lowering.compile_model(output_variables=["Voltage [V]"]) + component = model.get_processed_variable_or_event(_VECTOR_VAR) + model.variables_and_events["field"] = pybamm.VectorField(component, component) + + with pytest.raises(pybamm.SolverError, match=r"tensor field"): + lowering.compile_model(output_variables=["field"]) + + assert lowering.compiled is compiled + + +class TestTerminationEvents: + def test_a_vector_valued_event_is_rejected(self): + model = _built_model() + surface = model.get_processed_variable_or_event(_VECTOR_VAR) + model.events = [*model.events, pybamm.Event("Vector event", surface - 1.0)] + + with pytest.raises(pybamm.SolverError, match=r"'Vector event' has shape"): + RustModelLowering.of(model, {}).compile_model() + + def test_scalar_events_are_all_lowered(self): + model = _built_model() + + compiled = RustModelLowering.of(model, {}).compile_model() + + assert compiled.n_events == len(_termination_events(model)) + + def test_an_event_reading_y_dot_is_refused_unless_allowed(self): + model = _built_model() + rate = pybamm.StateVector(slice(0, 1)).diff(pybamm.t) + model.events = [pybamm.Event("rate", rate + 1)] + lowering = RustModelLowering.of(model, {}) + + with pytest.raises(pybamm.ModelError, match=r"Must provide a 'y_dot'"): + lowering.compile_model(allow_y_dot_events=False) + + assert lowering.compile_model().events_read_y_dot == [True] + + +def _set_up(model, solver=None): + """Set ``model`` up, by an IDAKLUSolver unless ``solver`` is given.""" + (solver or pybamm.IDAKLUSolver()).set_up(model, inputs={}) + return RustModelLowering.current(model).compiled + + +class TestModelViews: + def test_the_rhs_is_the_residual_s_differential_rows(self): + model = _built_model(options={"surface form": "algebraic"}) + assert model.len_alg > 0, "expected a DAE" + compiled = _set_up(model) + + y0 = np.asarray(model.concatenated_initial_conditions.evaluate()).reshape(-1) + residual = np.asarray(compiled.rhs(0.0, y0, np.array([]))).reshape(-1) + rhs = model.rhs_eval(0.0, y0, np.array([])) + + assert rhs.shape == (model.len_rhs, 1) + np.testing.assert_array_equal(rhs.ravel(), residual[: model.len_rhs]) + + def test_every_evaluator_views_the_compiled_model(self): + model = _built_model(options={"surface form": "algebraic"}) + compiled = _set_up(model) + + assert model.rhs_eval._cf is compiled.rhs + assert model.rhs_algebraic_eval._cf is compiled.rhs + assert model.jac_rhs_algebraic_eval._jac is compiled.jacobian + assert model.algebraic_eval._cf is compiled.algebraic_residual + assert [event._cf for event in model.terminate_events_eval] == compiled.events + + def test_the_algebraic_jacobian_spans_every_state(self): + model = _built_model(options={"surface form": "algebraic"}) + _set_up(model) + + y0 = np.asarray(model.concatenated_initial_conditions.evaluate()).reshape(-1) + jacobian = model.jac_algebraic_eval(0.0, y0, np.array([])) + + assert jacobian.shape == (model.len_alg, model.len_rhs_and_alg) + + def test_bound_events_follow_model_events_order(self): + model = _built_model() + _set_up(model) + + events = _termination_events(model) + assert len(model.terminate_events_eval) == len(events) + y0 = np.asarray(model.concatenated_initial_conditions.evaluate()).reshape(-1) + for event, evaluator in zip(events, model.terminate_events_eval, strict=True): + np.testing.assert_allclose( + float(np.asarray(evaluator(0.0, y0, np.array([]))).ravel()[0]), + float(np.asarray(event.expression.evaluate(0.0, y0, inputs={})).item()), + rtol=1e-12, + ) + + @pytest.mark.parametrize( + "solver_class", + [pybamm.IDAKLUSolver, pybamm.ScipySolver], + ) + def test_every_solver_views_the_compiled_model(self, solver_class): + """An unbound events slot would silently skip the event-violation check.""" + model = _built_model() + events = _termination_events(model) + assert events, "expected events the check could silently skip" + + compiled = _set_up(model, solver_class()) + + assert model.rhs_eval._cf is compiled.rhs + assert len(model.terminate_events_eval) == len(events) + + +class TestSetUpFailures: + def test_a_failed_set_up_keeps_the_model_s_evaluators(self): + model = _built_model() + solver = pybamm.IDAKLUSolver() + solver.solve(model, [0, 100]) + rhs_eval = model.rhs_eval + component = model.get_processed_variable_or_event(_VECTOR_VAR) + model.variables_and_events["field"] = pybamm.VectorField(component, component) + + with pytest.raises(pybamm.SolverError, match=r"tensor field"): + pybamm.IDAKLUSolver(output_variables=["field"]).set_up(model, inputs={}) + + assert model.rhs_eval is rhs_eval + solution = solver.solve(model, [0, 100]) + assert solution.termination == "final time" + + def test_a_refused_tolerance_compiles_nothing(self): + model = _built_model() + solver = pybamm.IDAKLUSolver() + solver.solve(model, [0, 100]) + lowering = RustModelLowering.current(model) + compiled, rhs_eval = lowering.compiled, model.rhs_eval + + with pytest.raises(pybamm.SolverError, match=r"Absolute tolerances have shape"): + pybamm.IDAKLUSolver(atol=np.ones(3)).set_up(model, inputs={}) + + assert lowering.compiled is compiled + assert model.rhs_eval is rhs_eval + solution = solver.solve(model, [0, 100]) + assert solution.termination == "final time" + + def test_set_up_without_the_model_s_inputs_is_a_solver_error(self): + model = _built_model(with_input=True) + + with pytest.raises( + pybamm.SolverError, match=r"'Current function \[A\]' is not one of" + ): + pybamm.IDAKLUSolver().set_up(model, inputs={}) + + +class TestOneGraphPerModel: + def test_setting_up_again_reuses_the_graph(self): + model = _built_model() + _set_up(model) + lowering = RustModelLowering.current(model) + nodes = lowering.graph.n_nodes + + _set_up(model) + + assert RustModelLowering.current(model) is lowering + assert lowering.graph.n_nodes == nodes + + def test_new_initial_conditions_leave_the_graph_alone(self): + # They compile on a graph of their own, so a sweep cannot grow the model's + model = pybamm.lithium_ion.SPM() + model.convert_to_format = "rust" + sim = pybamm.Simulation(model) + sim.solve([0, 60], initial_soc=0.5) + lowering = RustModelLowering.current(sim.built_model) + nodes = lowering.graph.n_nodes + + for initial_soc in (0.6, 0.7, 0.8): + sim.solve([0, 60], initial_soc=initial_soc) + + assert RustModelLowering.current(sim.built_model) is lowering + assert lowering.graph.n_nodes == nodes + + def test_other_input_names_get_a_graph_of_their_own(self): + model = _built_model(with_input=True) + lowering = RustModelLowering.of(model, {"Current function [A]": 1.0}) + + assert RustModelLowering.of(model, ["Current function [A]"]) is lowering + assert RustModelLowering.of(model, []) is not lowering + + def test_a_copy_or_pickle_of_the_model_lowers_afresh(self): + import pickle + + model = _built_model() + _set_up(model) + + assert RustModelLowering.current(model.new_copy()) is None + assert RustModelLowering.current(pickle.loads(pickle.dumps(model))) is None + + @pytest.mark.parametrize( + "make_solver", + [ + lambda: pybamm.IDAKLUSolver(options={"calc_ic": False}), + ], + ids=["IDAKLUSolver"], + ) + def test_the_newton_root_solver_reuses_the_compiled_model( + self, monkeypatch, make_solver + ): + # Without the integrator's own initialisation, the Newton solver finds y0 + model = _built_model(options={"surface form": "algebraic"}) + compiles = [] + compile_model = RustModelLowering.compile_model + + def counting(lowering, **kwargs): + compiles.append(None) + return compile_model(lowering, **kwargs) + + monkeypatch.setattr(RustModelLowering, "compile_model", counting) + make_solver().solve(model, np.linspace(0, 10, 3)) + + assert len(compiles) == 1 + assert model.algebraic_root_solver + + def test_casadi_path_lowers_nothing(self): + model = pybamm.lithium_ion.SPM() + model.convert_to_format = "casadi" + sim = pybamm.Simulation(model) + sim.build() + built = sim.built_model + built.convert_to_format = "casadi" + + pybamm.IDAKLUSolver().set_up(built, inputs={}) + + assert RustModelLowering.current(built) is None + assert built.rhs_eval is not None + assert len(built.terminate_events_eval) == len(_termination_events(built)) diff --git a/packages/pybamm/tests/unit/test_solvers/test_solution.py b/packages/pybamm/tests/unit/test_solvers/test_solution.py index 5988b5a525..97f6f31ee7 100644 --- a/packages/pybamm/tests/unit/test_solvers/test_solution.py +++ b/packages/pybamm/tests/unit/test_solvers/test_solution.py @@ -1475,6 +1475,17 @@ def test_update_rebuilds_every_listed_variable(self): np.testing.assert_allclose(solution["c"].entries, built.entries) assert "2c" in solution._variables + def test_solution_save_load_rust_backend(self, tmp_path): + model = pybamm.lithium_ion.SPM() + model.convert_to_format = "rust" + sim = pybamm.Simulation(model, solver=pybamm.IDAKLUSolver()) + sol = sim.solve([0, 3600]) + expected = sol["Voltage [V]"].data + path = tmp_path / "sol.pkl" + sol.save(str(path)) + loaded = pybamm.load(str(path)) + np.testing.assert_allclose(loaded["Voltage [V]"].data, expected) + def test_solution_evals_with_inputs(self): model = pybamm.lithium_ion.SPM() geometry = model.default_geometry diff --git a/packages/pybammsolvers/src/pybammsolvers/idaklu.cpp b/packages/pybammsolvers/src/pybammsolvers/idaklu.cpp index 323a5fe3f5..9d7e56bba0 100644 --- a/packages/pybammsolvers/src/pybammsolvers/idaklu.cpp +++ b/packages/pybammsolvers/src/pybammsolvers/idaklu.cpp @@ -201,29 +201,14 @@ IDAKLUSolverGroup *create_casadi_solver_group( std::move(solvers), number_of_states, number_of_parameters, inputs_length); } -// One IDAKLU solver per Rust evaluator, each over the Rust model's own tapes and Jacobian. -// An int leads: without pybind11 headers, CodeQL parses a leading `py::object` as a variable initialiser +// One IDAKLU solver per Rust evaluator, each sized from its evaluator's own function table. +// A scalar leads: without pybind11 headers, CodeQL parses a leading `py::object` as a variable initialiser IDAKLUSolverGroup *create_rust_solver_group( - int number_of_states, + double rel_tol, const py::sequence &rust_evaluators, - int number_of_inputs, - int number_of_sens_params, - int number_of_events, - int number_of_algebraic_states, - const std::vector &output_lens, - const np_array_int &jac_colptrs, - const np_array_int &jac_rowvals, - int jac_nnz, - int jac_bandwidth_lower, - int jac_bandwidth_upper, - const np_array_int &alg_jac_rowvals, - const np_array_int &alg_jac_colvals, - int alg_jac_nnz, - const np_array &rhs_alg_id, const np_array &atol_np, - double rel_tol, py::dict py_opts, - const std::vector &events_read_yp + bool algebraic_subblock ) { auto setup_opts = SetupOptions(py_opts); auto solver_opts = SolverOptions(py_opts); @@ -236,69 +221,61 @@ IDAKLUSolverGroup *create_rust_solver_group( " evaluator(s) but num_solvers is " + std::to_string(num_solvers) + "; each solver needs its own evaluator."); } - // IDA sizes its vectors from atol and reads rhs_alg_id per state, while Rust writes - // number_of_states into them, so a shorter array would be overrun. - auto check_per_state = [number_of_states](const char *name, py::ssize_t size) { - if (size != number_of_states) { - throw std::invalid_argument( - std::string(name) + " has length " + std::to_string(size) + - " but number_of_states is " + std::to_string(number_of_states) + "."); - } - }; - check_per_state("atol", atol_np.size()); - check_per_state("rhs_alg_id", rhs_alg_id.size()); - // The sub-block IC hands Rust a residual buffer sized from the algebraic ids. - if (number_of_algebraic_states != 0) { - auto ids = rhs_alg_id.unchecked<1>(); - int n_alg_ids = 0; - for (py::ssize_t i = 0; i < ids.shape(0); ++i) { - n_alg_ids += is_algebraic(ids(i)) ? 1 : 0; - } - if (n_alg_ids != number_of_algebraic_states) { - throw std::invalid_argument( - "n_alg is " + std::to_string(number_of_algebraic_states) + - " but rhs_alg_id marks " + std::to_string(n_alg_ids) + " states algebraic."); - } - } - - auto colptrs_ptr = jac_colptrs.unchecked<1>(); - auto rowvals_ptr = jac_rowvals.unchecked<1>(); - std::vector colptrs(colptrs_ptr.data(0), - colptrs_ptr.data(0) + colptrs_ptr.size()); - std::vector rowvals(rowvals_ptr.data(0), - rowvals_ptr.data(0) + rowvals_ptr.size()); - auto alg_rowvals_ptr = alg_jac_rowvals.unchecked<1>(); - auto alg_colvals_ptr = alg_jac_colvals.unchecked<1>(); - std::vector alg_rowvals( - alg_rowvals_ptr.data(0), - alg_rowvals_ptr.data(0) + alg_rowvals_ptr.size() - ); - std::vector alg_colvals( - alg_colvals_ptr.data(0), - alg_colvals_ptr.data(0) + alg_colvals_ptr.size() - ); std::vector> solvers; solvers.reserve(num_solvers); + int number_of_states = 0; + int number_of_sens_params = 0; + int number_of_inputs = 0; for (int i = 0; i < num_solvers; i++) { // One evaluator per solver: they share the compiled tape but not their scratch. auto functions = std::make_unique( - pybamm_rust_detail::claim_evaluator(rust_evaluators[i]), number_of_states, - number_of_inputs, number_of_sens_params, number_of_algebraic_states, - number_of_events, jac_nnz, colptrs, rowvals, alg_jac_nnz, alg_rowvals, - alg_colvals, output_lens, setup_opts, events_read_yp - ); + pybamm_rust_detail::claim_evaluator(rust_evaluators[i]), setup_opts, + algebraic_subblock); + const int n_states = functions->number_of_states; + const int n_sens_params = functions->number_of_parameters; + const int n_inputs = static_cast(functions->inputs.size()); + if (i == 0) { + number_of_states = n_states; + number_of_sens_params = n_sens_params; + number_of_inputs = n_inputs; + // IDA reads one tolerance per state. + if (atol_np.size() != n_states) { + throw std::invalid_argument( + "atol has length " + std::to_string(atol_np.size()) + + " but the Rust model has " + std::to_string(n_states) + " states."); + } + } else if (n_states != number_of_states || n_sens_params != number_of_sens_params || + n_inputs != number_of_inputs) { + // The group sizes every solver's results from the first evaluator's counts. + throw std::invalid_argument( + "rust_evaluators must share one model's state, input and sensitivity counts, " + "but evaluator " + std::to_string(i) + " differs from evaluator 0."); + } + + // Read before `functions` moves into the solver. + const np_array_int colptrs( + static_cast(functions->jac_times_cjmass_colptrs.size()), + functions->jac_times_cjmass_colptrs.data()); + const np_array_int rowvals( + static_cast(functions->jac_times_cjmass_rowvals.size()), + functions->jac_times_cjmass_rowvals.data()); + const np_array ids(static_cast(n_states), functions->state_ids().data()); + const int nnz = functions->number_of_nnz; + const int bandwidth_lower = functions->jac_bandwidth_lower; + const int bandwidth_upper = functions->jac_bandwidth_upper; + const int n_events = functions->number_of_events; solvers.emplace_back( std::unique_ptr( create_idaklu_solver( std::move(functions), - number_of_sens_params, - jac_colptrs, jac_rowvals, jac_nnz, - jac_bandwidth_lower, jac_bandwidth_upper, - number_of_events, - rhs_alg_id, atol_np, rel_tol, - number_of_inputs, + n_sens_params, + colptrs, rowvals, nnz, + bandwidth_lower, bandwidth_upper, + n_events, + ids, atol_np, rel_tol, + n_inputs, solver_opts, setup_opts ) ) @@ -366,26 +343,11 @@ PYBIND11_MODULE(idaklu, m) m.def("create_rust_solver_group", &create_rust_solver_group, "Create a Rust-backed IDAKLU solver group", - py::arg("number_of_states"), + py::arg("rtol"), py::arg("rust_evaluators"), - py::arg("number_of_inputs"), - py::arg("number_of_sens_params"), - py::arg("number_of_events"), - py::arg("n_alg"), - py::arg("output_lens"), - py::arg("jac_colptrs"), - py::arg("jac_rowvals"), - py::arg("jac_nnz"), - py::arg("jac_bandwidth_lower"), - py::arg("jac_bandwidth_upper"), - py::arg("alg_jac_rowvals"), - py::arg("alg_jac_colvals"), - py::arg("alg_jac_nnz"), - py::arg("rhs_alg_id"), py::arg("atol"), - py::arg("rtol"), py::arg("options"), - py::arg("events_read_yp") = std::vector{}, + py::arg("algebraic_subblock"), py::return_value_policy::take_ownership); m.def("observe", &observe, @@ -498,12 +460,9 @@ PYBIND11_MODULE(idaklu, m) py::arg("max_iter"), py::arg("max_backtracks"), py::arg("eps_newt"), py::arg("use_sparse"), py::arg("klu_pivot_tolerance") = 0.1) - .def(py::init, std::vector, - std::vector, sunrealtype, sunrealtype, + .def(py::init, sunrealtype, sunrealtype, int, int, sunrealtype, bool, sunrealtype>(), - py::arg("rust_evaluator"), py::arg("n_rhs"), py::arg("n_alg"), - py::arg("jac_rows"), py::arg("jac_cols"), + py::arg("rust_evaluator"), py::arg("atol"), py::arg("rtol"), py::arg("step_tol"), py::arg("max_iter"), py::arg("max_backtracks"), py::arg("eps_newt"), py::arg("use_sparse"), diff --git a/packages/pybammsolvers/src/pybammsolvers/idaklu_source/Expressions/Rust/RustFunctions.hpp b/packages/pybammsolvers/src/pybammsolvers/idaklu_source/Expressions/Rust/RustFunctions.hpp index d23d985918..88b8f2c8b0 100644 --- a/packages/pybammsolvers/src/pybammsolvers/idaklu_source/Expressions/Rust/RustFunctions.hpp +++ b/packages/pybammsolvers/src/pybammsolvers/idaklu_source/Expressions/Rust/RustFunctions.hpp @@ -9,6 +9,8 @@ #include #include #include +#include +#include #include #include @@ -40,57 +42,22 @@ inline RustEvaluatorPtr claim_evaluator(py::handle capsule) { return RustEvaluatorPtr(static_cast(handle)); } -/* Throw unless `given`, a count C++ sizes buffers from, equals the Rust model's `rust`. */ -inline void check_dim(const char* name, int64_t given, int64_t rust) { - if (given != rust) { - throw std::invalid_argument( - std::string("pybammsolvers: ") + name + " is " + std::to_string(given) + - " but the Rust model has " + std::to_string(rust) + "."); - } -} - -/* Throw unless CSC `(colptrs, rowvals)` holds `nnz` entries of an `n` x `n` matrix. */ -inline void check_csc_pattern(const std::vector& colptrs, - const std::vector& rowvals, int nnz, int n) { - if (colptrs.size() != static_cast(n) + 1 || colptrs.front() != 0 || - colptrs.back() != nnz || rowvals.size() != static_cast(nnz)) { - throw std::invalid_argument( - "pybammsolvers: the Jacobian pattern's " + std::to_string(colptrs.size()) + - " column pointers and " + std::to_string(rowvals.size()) + - " row indices do not fit a " + std::to_string(n) + " x " + std::to_string(n) + - " matrix with nnz = " + std::to_string(nnz) + "."); - } - if (!std::is_sorted(colptrs.begin(), colptrs.end())) { - throw std::invalid_argument( - "pybammsolvers: the Jacobian pattern's column pointers must be non-decreasing."); - } - for (size_t k = 0; k < rowvals.size(); ++k) { - if (rowvals[k] < 0 || rowvals[k] >= n) { - throw std::invalid_argument( - "pybammsolvers: Jacobian entry " + std::to_string(k) + " has row " + - std::to_string(rowvals[k]) + ", outside its " + std::to_string(n) + " rows."); - } - } +/* `indices` as the Expression index type, which is not int64_t on every platform. */ +inline std::vector to_expr_int(const std::vector& indices) { + return std::vector(indices.begin(), indices.end()); } -/* Throw unless COO `(rows, cols)` holds `nnz` entries inside an `n_rows` x `n_cols` matrix. */ -inline void check_coo_pattern(const std::vector& rows, - const std::vector& cols, - int nnz, int n_rows, int n_cols) { - if (rows.size() != static_cast(nnz) || cols.size() != static_cast(nnz)) { - throw std::invalid_argument( - "pybammsolvers: the algebraic Jacobian pattern's rows and cols have lengths " + - std::to_string(rows.size()) + " and " + std::to_string(cols.size()) + - ", but nnz is " + std::to_string(nnz) + "."); - } - for (size_t k = 0; k < rows.size(); ++k) { - if (rows[k] < 0 || rows[k] >= n_rows || cols[k] < 0 || cols[k] >= n_cols) { - throw std::invalid_argument( - "pybammsolvers: algebraic Jacobian entry " + std::to_string(k) + " at (" + - std::to_string(rows[k]) + ", " + std::to_string(cols[k]) + ") lies outside its " + - std::to_string(n_rows) + " x " + std::to_string(n_cols) + " matrix."); - } - } +/* The COO pattern `alg_jac_assemble` fills: rows index the algebraic block, columns the state. */ +inline std::pair, std::vector> read_alg_jac_pattern( + RustModelRef rust) { + const int nnz = PYBAMM_RUST_VALUE(rust, alg_jac_nnz, rust.model); + std::vector rows(nnz); + std::vector cols(nnz); + // Rust refuses a null buffer, which an empty vector may hand it. + if (nnz > 0) { + PYBAMM_RUST_CALL(rust, alg_jac_pattern, rust.model, rows.data(), cols.data()); + } + return {to_expr_int(rows), to_expr_int(cols)}; } } // namespace pybamm_rust_detail @@ -302,13 +269,7 @@ class RustOutputExpression : public RustExpression { class RustAlgResExpression : public RustExpression { public: RustAlgResExpression(RustModelRef rust, int n_alg) - : RustExpression(rust, n_alg) { - // Rust writes its own residual length into the IC solver's `n_alg` buffer. - if (n_alg != 0) { - pybamm_rust_detail::check_dim("n_alg", n_alg, PYBAMM_RUST_VALUE(rust, n_algebraic, - rust.model)); - } - } + : RustExpression(rust, n_alg) {} void operator()() override { if (m_out_len > 0) { @@ -326,24 +287,14 @@ class RustAlgResExpression : public RustExpression { } }; -/** Algebraic Jacobian, in the COO order of the `(row, col)` passed at construction. */ +/** Algebraic Jacobian, in the COO order of `(rows, cols)`: rows in the block, columns in y. */ class RustAlgJacExpression : public RustExpression { public: - RustAlgJacExpression(RustModelRef rust, int nnz, - std::vector rows, + RustAlgJacExpression(RustModelRef rust, std::vector rows, std::vector cols) - : RustExpression(rust, nnz) { + : RustExpression(rust, static_cast(rows.size())) { m_rows = std::move(rows); m_cols = std::move(cols); - // Rust writes its own non-zero count, and the IC solver reads the pattern at `nnz`; rows - // index the algebraic block and columns the full state. - pybamm_rust_detail::check_coo_pattern( - m_rows, m_cols, nnz, PYBAMM_RUST_VALUE(rust, n_algebraic, rust.model), - PYBAMM_RUST_VALUE(rust, n_states, rust.model)); - if (nnz != 0) { - pybamm_rust_detail::check_dim( - "alg_jac_nnz", nnz, PYBAMM_RUST_VALUE(rust, alg_jac_nnz, rust.model)); - } } void operator()() override { @@ -365,13 +316,24 @@ class RustAlgJacExpression : public RustExpression { /** * Base for the Newton adapters: the solver passes `F(t, y_alg, [y_diff; inputs])` but the Rust * FFI expects `g(t, y_full, inputs)`, so `[y_diff; y_alg]` is gathered into a full-state buffer. + * The algebraic states are the model's trailing `n_algebraic`. */ class RustNewtonExpression : public RustExpression { public: - RustNewtonExpression(RustModelRef rust, int out_len, int n_rhs, int n_alg) - : RustExpression(rust, out_len), m_n_rhs(n_rhs), - m_n_alg(checked_split(rust, n_rhs, n_alg)), - m_y_full(static_cast(n_rhs) + n_alg, 0.0) {} + RustNewtonExpression(RustModelRef rust, int out_len) + : RustExpression(rust, out_len), m_n_alg(block_size(rust)), + m_n_rhs(PYBAMM_RUST_VALUE(rust, n_states, rust.model) - m_n_alg), + m_y_full(static_cast(m_n_rhs) + m_n_alg, 0.0) {} + + /// The number of algebraic states the Newton system solves for. + static int block_size(RustModelRef rust) { + const int n_alg = PYBAMM_RUST_VALUE(rust, n_algebraic, rust.model); + if (n_alg == 0) { + throw std::invalid_argument( + "pybammsolvers: the Rust model has no algebraic block for the Newton solver."); + } + return n_alg; + } // Unhide the zero-argument overload the subclasses define and this one delegates to. using Expression::operator(); @@ -391,26 +353,15 @@ class RustNewtonExpression : public RustExpression { return m_arg[2] + m_n_rhs; } - int m_n_rhs; int m_n_alg; + int m_n_rhs; std::vector m_y_full; - -private: - // Rust reads `m_y_full` at its state count and writes its residual length, so both are - // checked before `m_y_full` is sized. - static int checked_split(RustModelRef rust, int n_rhs, int n_alg) { - pybamm_rust_detail::check_dim("n_alg", n_alg, PYBAMM_RUST_VALUE(rust, n_algebraic, - rust.model)); - pybamm_rust_detail::check_dim("n_rhs + n_alg", static_cast(n_rhs) + n_alg, - PYBAMM_RUST_VALUE(rust, n_states, rust.model)); - return n_alg; - } }; class RustNewtonResExpression : public RustNewtonExpression { public: - RustNewtonResExpression(RustModelRef rust, int n_rhs, int n_alg) - : RustNewtonExpression(rust, n_alg, n_rhs, n_alg) {} + explicit RustNewtonResExpression(RustModelRef rust) + : RustNewtonExpression(rust, block_size(rust)) {} void operator()() override { const double* inputs = gather_full_state(); @@ -419,20 +370,24 @@ class RustNewtonResExpression : public RustNewtonExpression { } }; -/** Fills the COO order of `(rows, cols)`, which BuildSparseResources consumes unchanged. */ +/** Fills the algebraic Jacobian's COO order, which BuildSparseResources consumes unchanged. */ class RustNewtonJacExpression : public RustNewtonExpression { public: - RustNewtonJacExpression(RustModelRef rust, int n_rhs, int n_alg, int nnz, - std::vector rows, - std::vector cols) - : RustNewtonExpression(rust, nnz, n_rhs, n_alg) { + explicit RustNewtonJacExpression(RustModelRef rust) + : RustNewtonExpression(rust, PYBAMM_RUST_VALUE(rust, alg_jac_nnz, rust.model)) { + auto [rows, cols] = pybamm_rust_detail::read_alg_jac_pattern(rust); + // The Newton matrix indexes the block, so each state column moves to the block's own. + for (expr_int& col : cols) { + col -= m_n_rhs; + if (col < 0 || col >= m_n_alg) { + throw std::invalid_argument( + "pybammsolvers: the Rust algebraic Jacobian reads state " + + std::to_string(col + m_n_rhs) + ", outside the trailing " + + std::to_string(m_n_alg) + " algebraic states the Newton solver gathers."); + } + } m_rows = std::move(rows); m_cols = std::move(cols); - // The Newton system indexes rows and columns within the algebraic block, and Rust - // writes its own non-zero count. - pybamm_rust_detail::check_coo_pattern(m_rows, m_cols, nnz, n_alg, n_alg); - pybamm_rust_detail::check_dim("alg_jac_nnz", nnz, PYBAMM_RUST_VALUE(rust, alg_jac_nnz, - rust.model)); } void operator()() override { @@ -442,102 +397,105 @@ class RustNewtonJacExpression : public RustNewtonExpression { } }; -/** - * ExpressionSet for Rust-backed models. Expressions are direct members, not unique_ptr: their - * addresses are valid for the base constructor even though members initialise after it. - */ -class RustFunctions : public ExpressionSet { -public: - /** - * `colptrs`/`rowvals` are the Jacobian's CSC pattern; `alg_rowvals`/`alg_colvals` are COO. - * `events_read_yp` says which events read yp, one entry each, or is empty if none does. - */ - RustFunctions( - RustEvaluatorPtr evaluator, - int n_states, - int n_inputs, - int n_sens_params, - int n_alg, - int n_events, - int nnz, - const std::vector& colptrs, - const std::vector& rowvals, - int alg_jac_nnz, - const std::vector& alg_rowvals, - const std::vector& alg_colvals, - const std::vector& output_lens, - const SetupOptions& options, - const std::vector& events_read_yp_arg = {} - ) : - ExpressionSet( - static_cast(&m_rhs), - static_cast(&m_jac), - nnz, - 0, // jac_bandwidth_lower (not used for sparse) - 0, // jac_bandwidth_upper (not used for sparse) - np_array_int(), // empty, we store directly - np_array_int(), // empty, we store directly - n_inputs, // inputs_length - static_cast(&m_jac_action), - static_cast(&m_mass_action), - static_cast(&m_sens), - static_cast(&m_events), - // Checked as the base initialises, before any member is sized from these counts. - checked_dims(borrow(evaluator), n_states, n_inputs, nnz, n_sens_params), - checked_event_count(borrow(evaluator), n_events), - n_sens_params, // n_parameters (forward sensitivities) - options, - static_cast(&m_alg_res), - static_cast(&m_alg_jac) - ), - m_evaluator(std::move(evaluator)), - m_rust(borrow(m_evaluator)), - m_n_sens_params(n_sens_params), - tmp_state_vector(n_states), - tmp_sparse_jacobian_data(nnz), - m_sens_directions(static_cast(n_states) * n_sens_params), - m_sens_jac_actions(m_sens_directions.size()), - m_rhs(m_rust, n_states), - m_jac(m_rust, nnz, - convert_to_expr_int(rowvals), - csc_rowvals_to_coo_cols(colptrs, rowvals, nnz, n_states)), - m_jac_action(m_rust, n_states), - m_mass_action(m_rust, n_states), - m_events(m_rust, n_events), - m_sens(m_rust, n_states, n_sens_params), - m_alg_res(m_rust, n_alg), - m_alg_jac(m_rust, alg_jac_nnz, - convert_to_expr_int(alg_rowvals), - convert_to_expr_int(alg_colvals)) - { - jac_times_cjmass_colptrs = colptrs; - jac_times_cjmass_rowvals = rowvals; - // The base ctor takes inputs_length but does not size `inputs` itself. - inputs.resize(n_inputs); +/** What IDAKLU sizes itself from, read once through a Rust model's own table. */ +struct RustLayout { + int n_states = 0; + int n_inputs = 0; + int n_sens_params = 0; + // IDA's root count: every component of every event + int n_events = 0; + int nnz = 0; + int bandwidth_lower = 0; + int bandwidth_upper = 0; + // The CSC pattern of J - cj*M + std::vector colptrs; + std::vector rowvals; + // IDA's `id`: 1 differential, 0 algebraic + std::vector ids; + // Empty unless an event component reads yp + std::vector events_read_yp; + std::vector output_lens; + // The algebraic sub-block the IC solves, or 0 and empty to solve the full system + int n_alg = 0; + std::vector alg_rows; + std::vector alg_cols; + + /** `algebraic_subblock` asks for the sub-block, which only a model with one can give. */ + static RustLayout read(RustModelRef rust, bool algebraic_subblock) { + RustLayout layout; + layout.n_states = PYBAMM_RUST_VALUE(rust, n_states, rust.model); + layout.n_inputs = PYBAMM_RUST_VALUE(rust, n_inputs, rust.model); + layout.n_sens_params = PYBAMM_RUST_VALUE(rust, n_sens_params, rust.model); + layout.n_events = PYBAMM_RUST_VALUE(rust, total_event_len, rust.model); + layout.nnz = PYBAMM_RUST_VALUE(rust, jac_nnz, rust.model); + + // Rust refuses the null buffer an empty vector may hand it, so empty reads are skipped: + // zeroed column pointers already describe a pattern without entries. + layout.colptrs.assign(static_cast(layout.n_states) + 1, 0); + layout.rowvals.assign(layout.nnz, 0); + if (layout.nnz > 0) { + PYBAMM_RUST_CALL(rust, jac_pattern, rust.model, layout.colptrs.data(), + layout.rowvals.data()); + } + for (int col = 0; col < layout.n_states; ++col) { + for (int64_t k = layout.colptrs[col]; k < layout.colptrs[col + 1]; ++k) { + const int offset = static_cast(layout.rowvals[k]) - col; + layout.bandwidth_lower = std::max(layout.bandwidth_lower, offset); + layout.bandwidth_upper = std::max(layout.bandwidth_upper, -offset); + } + } - check_output_lens(m_rust, output_lens); - m_output_fcns.reserve(output_lens.size()); - for (int i = 0; i < static_cast(output_lens.size()); ++i) { - m_output_fcns.emplace_back(std::make_unique(output_lens[i])); - var_fcns.push_back(static_cast(m_output_fcns.back().get())); + layout.ids.assign(layout.n_states, 1.0); + if (layout.n_states > 0) { + PYBAMM_RUST_CALL(rust, state_ids, rust.model, layout.ids.data()); } - // Left null without one, which turns IDAKLU's upsampling off. - if (checked_upsampling_len(m_rust) > 0) { - m_upsampling = std::make_unique(m_rust); - upsampling_fcn = static_cast(m_upsampling.get()); + if (layout.n_events > 0) { + std::vector reads(layout.n_events); + PYBAMM_RUST_CALL(rust, events_read_y_dot, rust.model, reads.data()); + // Kept only if one reads yp, which picks IDAKLU's derivative-aware root function + if (std::any_of(reads.begin(), reads.end(), [](int read) { return read != 0; })) { + layout.events_read_yp.assign(reads.begin(), reads.end()); + } } - if (!events_read_yp_arg.empty() && - events_read_yp_arg.size() != static_cast(n_events)) { - throw std::invalid_argument("events_read_yp must have one entry per event"); + const int n_outputs = PYBAMM_RUST_VALUE(rust, n_outputs, rust.model); + for (int i = 0; i < n_outputs; ++i) { + layout.output_lens.push_back(PYBAMM_RUST_VALUE(rust, output_len, rust.model, i)); } - // Kept only if an event reads yp, which picks IDAKLU's derivative-aware root function - if (std::find(events_read_yp_arg.begin(), events_read_yp_arg.end(), true) != - events_read_yp_arg.end()) { - events_read_yp = events_read_yp_arg; + + const int n_alg = PYBAMM_RUST_VALUE(rust, n_algebraic, rust.model); + if (algebraic_subblock && n_alg > 0) { + // IDAKLU sizes the sub-block from the ids, but Rust may compile a block over only + // some of those states, which would leave residual entries unwritten. + const auto n_alg_ids = std::count_if( + layout.ids.begin(), layout.ids.end(), [](sunrealtype id) { return is_algebraic(id); }); + if (n_alg != n_alg_ids) { + throw std::invalid_argument( + "pybammsolvers: the Rust model's algebraic block covers " + + std::to_string(n_alg) + " of the " + std::to_string(n_alg_ids) + + " states its mass matrix marks algebraic; the IC sub-block needs all of them."); + } + layout.n_alg = n_alg; + std::tie(layout.alg_rows, layout.alg_cols) = + pybamm_rust_detail::read_alg_jac_pattern(rust); } + return layout; } +}; + +/** + * ExpressionSet for Rust-backed models, sized from the evaluator's own table. Expressions are + * direct members, not unique_ptr: their addresses are valid for the base constructor even though + * members initialise after it. + */ +class RustFunctions : public ExpressionSet { +public: + /** `algebraic_subblock` lets the IC solve the algebraic sub-block of a model with one. */ + RustFunctions(RustEvaluatorPtr evaluator, const SetupOptions& options, + bool algebraic_subblock) + : RustFunctions(std::move(evaluator), options, + RustLayout::read(borrow(evaluator), algebraic_subblock)) {} sunrealtype* get_tmp_state_vector() override { return tmp_state_vector.data(); @@ -547,6 +505,9 @@ class RustFunctions : public ExpressionSet { return tmp_sparse_jacobian_data.data(); } + /** IDA's `id` for each state: 1 differential, 0 algebraic. */ + const std::vector& state_ids() const { return m_state_ids; } + static constexpr bool kNativeKernels = true; // J·yS_i for every sensitivity parameter in one call, which shares a single primal pass. @@ -576,10 +537,69 @@ class RustFunctions : public ExpressionSet { } private: + // `evaluator` is only bound here, so the public constructor reads it before it moves. + RustFunctions(RustEvaluatorPtr&& evaluator, const SetupOptions& options, RustLayout layout) + : ExpressionSet( + static_cast(&m_rhs), + static_cast(&m_jac), + layout.nnz, + layout.bandwidth_lower, + layout.bandwidth_upper, + np_array_int(), // empty, we store directly + np_array_int(), // empty, we store directly + layout.n_inputs, // inputs_length + static_cast(&m_jac_action), + static_cast(&m_mass_action), + static_cast(&m_sens), + static_cast(&m_events), + layout.n_states, + layout.n_events, + layout.n_sens_params, // n_parameters (forward sensitivities) + options, + static_cast(&m_alg_res), + static_cast(&m_alg_jac)), + m_evaluator(std::move(evaluator)), + m_rust(borrow(m_evaluator)), + m_n_sens_params(layout.n_sens_params), + m_state_ids(layout.ids), + tmp_state_vector(layout.n_states), + tmp_sparse_jacobian_data(layout.nnz), + m_sens_directions(static_cast(layout.n_states) * layout.n_sens_params), + m_sens_jac_actions(m_sens_directions.size()), + m_rhs(m_rust, layout.n_states), + m_jac(m_rust, layout.nnz, pybamm_rust_detail::to_expr_int(layout.rowvals), + coo_columns(layout.colptrs, layout.nnz)), + m_jac_action(m_rust, layout.n_states), + m_mass_action(m_rust, layout.n_states), + m_events(m_rust, layout.n_events), + m_sens(m_rust, layout.n_states, layout.n_sens_params), + m_alg_res(m_rust, layout.n_alg), + m_alg_jac(m_rust, layout.alg_rows, layout.alg_cols) + { + jac_times_cjmass_colptrs = std::move(layout.colptrs); + jac_times_cjmass_rowvals = std::move(layout.rowvals); + // The base ctor takes inputs_length but does not size `inputs` itself. + inputs.resize(layout.n_inputs); + events_read_yp = std::move(layout.events_read_yp); + + m_output_fcns.reserve(layout.output_lens.size()); + for (int len : layout.output_lens) { + m_output_fcns.emplace_back(std::make_unique(len)); + var_fcns.push_back(static_cast(m_output_fcns.back().get())); + } + + // Left null without one, which turns IDAKLU's upsampling off. + if (checked_upsampling_len(m_rust) > 0) { + m_upsampling = std::make_unique(m_rust); + upsampling_fcn = static_cast(m_upsampling.get()); + } + } + // Declared first, so the expressions borrowing it are destroyed before it is released. RustEvaluatorPtr m_evaluator; RustModelRef m_rust; int m_n_sens_params; + std::vector m_state_ids; std::vector tmp_state_vector; std::vector tmp_sparse_jacobian_data; @@ -599,30 +619,6 @@ class RustFunctions : public ExpressionSet { std::vector> m_output_fcns; std::unique_ptr m_upsampling; - // Rust borrows every buffer sized from these at its own counts, so a mismatch would overrun. - static int checked_dims(RustModelRef rust, int n_states, int n_inputs, int nnz, - int n_sens_params) { - using pybamm_rust_detail::check_dim; - check_dim("number_of_states", n_states, PYBAMM_RUST_VALUE(rust, n_states, rust.model)); - check_dim("number_of_inputs", n_inputs, PYBAMM_RUST_VALUE(rust, n_inputs, rust.model)); - check_dim("jac_nnz", nnz, PYBAMM_RUST_VALUE(rust, jac_nnz, rust.model)); - check_dim("number_of_sens_params", n_sens_params, - PYBAMM_RUST_VALUE(rust, n_sens_params, rust.model)); - return n_states; - } - - // IDA sizes its root buffer by `n_events`, so each Rust event must be one scalar. - static int checked_event_count(RustModelRef rust, int n_events) { - const int total_event_len = PYBAMM_RUST_VALUE(rust, total_event_len, rust.model); - if (total_event_len != n_events) { - throw std::invalid_argument( - "pybammsolvers: number_of_events is " + std::to_string(n_events) + - " but the Rust model's events have " + std::to_string(total_event_len) + - " components; every termination event must be scalar."); - } - return n_events; - } - // IDAKLU evaluates the upsampling output into one scalar, so Rust must write at most one. static int checked_upsampling_len(RustModelRef rust) { const int len = PYBAMM_RUST_VALUE(rust, upsampling_len, rust.model); @@ -634,40 +630,10 @@ class RustFunctions : public ExpressionSet { return len; } - // Output buffers are sized from `output_lens`, so each must match what Rust writes. - static void check_output_lens(RustModelRef rust, const std::vector& output_lens) { - const int n_outputs = PYBAMM_RUST_VALUE(rust, n_outputs, rust.model); - if (static_cast(output_lens.size()) != n_outputs) { - throw std::invalid_argument( - "pybammsolvers: " + std::to_string(output_lens.size()) + - " output lengths were given for a Rust model with " + - std::to_string(n_outputs) + " output variables."); - } - for (int i = 0; i < n_outputs; ++i) { - const int len = PYBAMM_RUST_VALUE(rust, output_len, rust.model, i); - if (output_lens[i] != len) { - throw std::invalid_argument( - "pybammsolvers: output_lens[" + std::to_string(i) + "] is " + - std::to_string(output_lens[i]) + " but Rust output variable " + - std::to_string(i) + " has " + std::to_string(len) + " elements."); - } - } - } - - static std::vector convert_to_expr_int(const std::vector& v) { - return std::vector(v.begin(), v.end()); - } - - // The column of each CSC entry, after refusing a pattern that would index past `nnz`. - static std::vector csc_rowvals_to_coo_cols( - const std::vector& colptrs, - const std::vector& rowvals, - int nnz, - int n_states - ) { - pybamm_rust_detail::check_csc_pattern(colptrs, rowvals, nnz, n_states); + // The column of each CSC entry. + static std::vector coo_columns(const std::vector& colptrs, int nnz) { std::vector cols(nnz); - int n_cols = static_cast(colptrs.size()) - 1; + const int n_cols = static_cast(colptrs.size()) - 1; for (int col = 0; col < n_cols; ++col) { for (int64_t k = colptrs[col]; k < colptrs[col + 1]; ++k) { cols[k] = static_cast(col); diff --git a/packages/pybammsolvers/src/pybammsolvers/idaklu_source/Expressions/Rust/pybamm_rust_ffi.h b/packages/pybammsolvers/src/pybammsolvers/idaklu_source/Expressions/Rust/pybamm_rust_ffi.h index d28ce5b1c3..837faf1566 100644 --- a/packages/pybammsolvers/src/pybammsolvers/idaklu_source/Expressions/Rust/pybamm_rust_ffi.h +++ b/packages/pybammsolvers/src/pybammsolvers/idaklu_source/Expressions/Rust/pybamm_rust_ffi.h @@ -60,6 +60,10 @@ typedef struct PybammRustFfi { int (*events_eval)(double, const double*, const double*, const double*, double*, void*); int (*upsampling_len)(const void*); int (*upsampling_eval)(double, const double*, const double*, double*, void*); + int (*jac_pattern)(const void*, int64_t*, int64_t*); + int (*state_ids)(const void*, double*); + int (*alg_jac_pattern)(const void*, int64_t*, int64_t*); + int (*events_read_y_dot)(const void*, int*); } PybammRustFfi; /* Mirrors `EvaluatorHandle` in ffi.rs; `ffi` leads in every version. */ diff --git a/packages/pybammsolvers/src/pybammsolvers/idaklu_source/StandaloneNewtonSolver.cpp b/packages/pybammsolvers/src/pybammsolvers/idaklu_source/StandaloneNewtonSolver.cpp index 5cbefc6a43..12d0819d08 100644 --- a/packages/pybammsolvers/src/pybammsolvers/idaklu_source/StandaloneNewtonSolver.cpp +++ b/packages/pybammsolvers/src/pybammsolvers/idaklu_source/StandaloneNewtonSolver.cpp @@ -221,7 +221,7 @@ int checked_atol_width(const std::vector& atol, int n_alg) { if (atol.size() != static_cast(n_alg)) { throw std::invalid_argument( "pybammsolvers: atol has length " + std::to_string(atol.size()) + - " but n_alg is " + std::to_string(n_alg) + "."); + " but the Rust model has " + std::to_string(n_alg) + " algebraic states."); } return n_alg; } @@ -230,10 +230,6 @@ int checked_atol_width(const std::vector& atol, int n_alg) { StandaloneNewtonSolver::StandaloneNewtonSolver( const py::object& rust_evaluator, - int n_rhs, - int n_alg, - const std::vector& jac_rows, - const std::vector& jac_cols, const std::vector& atol, sunrealtype rtol, sunrealtype step_tol, @@ -244,11 +240,9 @@ StandaloneNewtonSolver::StandaloneNewtonSolver( sunrealtype klu_pivot_tolerance) : rust_evaluator_(pybamm_rust_detail::claim_evaluator(rust_evaluator)), system_( - std::make_unique(borrow(rust_evaluator_), n_rhs, n_alg), - std::make_unique( - borrow(rust_evaluator_), n_rhs, n_alg, - static_cast(jac_rows.size()), jac_rows, jac_cols), - checked_atol_width(atol, n_alg), + std::make_unique(borrow(rust_evaluator_)), + std::make_unique(borrow(rust_evaluator_)), + checked_atol_width(atol, RustNewtonExpression::block_size(borrow(rust_evaluator_))), use_sparse, klu_pivot_tolerance), solver_(system_, system_.n_vars(), atol.data(), rtol, step_tol, diff --git a/packages/pybammsolvers/src/pybammsolvers/idaklu_source/StandaloneNewtonSolver.hpp b/packages/pybammsolvers/src/pybammsolvers/idaklu_source/StandaloneNewtonSolver.hpp index de45c02e24..4ee2e12b60 100644 --- a/packages/pybammsolvers/src/pybammsolvers/idaklu_source/StandaloneNewtonSolver.hpp +++ b/packages/pybammsolvers/src/pybammsolvers/idaklu_source/StandaloneNewtonSolver.hpp @@ -100,13 +100,12 @@ class StandaloneNewtonSolver { bool use_sparse, sunrealtype klu_pivot_tolerance); - /** @brief Rust-backed constructor, owning the evaluator `rust_evaluator` holds. */ + /** + * @brief Rust-backed constructor, owning the evaluator `rust_evaluator` holds and solving + * for its model's trailing algebraic states. + */ StandaloneNewtonSolver( const py::object& rust_evaluator, - int n_rhs, - int n_alg, - const std::vector& jac_rows, - const std::vector& jac_cols, const std::vector& atol, sunrealtype rtol, sunrealtype step_tol, diff --git a/packages/pybammsolvers/tests/test_rust_evaluator_capsule.py b/packages/pybammsolvers/tests/test_rust_evaluator_capsule.py index b8408c7451..e04efeded2 100644 --- a/packages/pybammsolvers/tests/test_rust_evaluator_capsule.py +++ b/packages/pybammsolvers/tests/test_rust_evaluator_capsule.py @@ -1,5 +1,5 @@ """pybammsolvers claims a Rust evaluator only from a capsule whose ABI it can read, -for a solver group whose sizes fit.""" +for a solver group with one evaluator per solver.""" from __future__ import annotations @@ -33,10 +33,6 @@ def _capsule(handle): def _newton_solver(rust_evaluator): return idaklu.StandaloneNewtonSolver( rust_evaluator=rust_evaluator, - n_rhs=0, - n_alg=1, - jac_rows=[0], - jac_cols=[0], atol=[1e-8], rtol=1e-8, step_tol=1e-12, @@ -80,41 +76,21 @@ def test_refuses_anything_but_an_evaluator_capsule(self): _newton_solver(0xDEAD0) -def _rust_solver_group(rust_evaluators, options, *, atol, rhs_alg_id): - return idaklu.create_rust_solver_group( - number_of_states=2, - rust_evaluators=rust_evaluators, - number_of_inputs=0, - number_of_sens_params=0, - number_of_events=0, - n_alg=0, - output_lens=[], - jac_colptrs=np.array([0, 1, 2]), - jac_rowvals=np.array([0, 1]), - jac_nnz=2, - jac_bandwidth_lower=0, - jac_bandwidth_upper=0, - alg_jac_rowvals=np.array([], dtype=np.int64), - alg_jac_colvals=np.array([], dtype=np.int64), - alg_jac_nnz=0, - rhs_alg_id=rhs_alg_id, - atol=atol, - rtol=1e-6, - options=options, - ) - - class TestRustSolverGroup: - @pytest.mark.parametrize("short", ["atol", "rhs_alg_id"]) - def test_refuses_a_per_state_array_of_another_length(self, short, solver_options): - per_state = {"atol": np.full(2, 1e-8), "rhs_alg_id": np.ones(2)} - per_state[short] = per_state[short][:1] + def test_refuses_an_evaluator_count_other_than_num_solvers(self, solver_options): # Another ABI version, so a claim would raise RuntimeError instead table = _TableHead(abi_version=0, size=ctypes.sizeof(_TableHead)) handle = _Handle(ctypes.pointer(table), None) capsule = _capsule(handle) with pytest.raises( - ValueError, match=rf"{short} has length 1 but number_of_states is 2\." + ValueError, match=r"holds 2 evaluator\(s\) but num_solvers is 1" ): - _rust_solver_group([capsule], solver_options, **per_state) + idaklu.create_rust_solver_group( + rtol=1e-6, + rust_evaluators=[capsule, capsule], + atol=np.full(2, 1e-8), + options=solver_options, + algebraic_subblock=False, + ) + # Refused before any claim, so the capsule still owns what it holds assert repr(capsule).startswith('