Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/5963.bugfix.1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Reading a vector field whose components hold a time integral raises `NotImplementedError`; it used to return the integrand in place of the integral.
1 change: 1 addition & 0 deletions changelog.d/5963.bugfix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`Solution.update([...])` builds every listed variable before storing any, so a name that fails stores none of them; it used to keep those built before it.
6 changes: 6 additions & 0 deletions packages/pybamm-rust/pybamm-python/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -503,6 +503,12 @@ impl CompiledModel {
.map(|f| f.clone_ref(py))
}

/// The retained derivation graph; roots lowered into it share the solve's indices.
#[getter]
fn graph(&self, py: Python<'_>) -> Py<ExprGraph> {
self.graph.clone_ref(py)
}

/// Pure df/dy (cj = 0, no mass): the bundle's composed `JacobianData`.
#[getter]
fn jacobian(&self, py: Python<'_>) -> PyResult<Py<CompiledJacobian>> {
Expand Down
5 changes: 5 additions & 0 deletions packages/pybamm/src/pybamm/plotting/quick_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,11 @@ def set_output_variables(self, output_variables, solutions):
# Calculate subplot positions based on number of variables supplied
self.subplot_positions = {}

# Every name below is read from every solution, so build them as one set
names = [var for variable_tuple in output_variables for var in variable_tuple]
for solution in solutions:
solution._build_missing(names)

for k, variable_tuple in enumerate(output_variables):
# Prepare list of variables
variables = [None] * len(solutions)
Expand Down
4 changes: 4 additions & 0 deletions packages/pybamm/src/pybamm/rust/_core.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,10 @@ class CompiledModel:
def rhs(self) -> CompiledFunction:
"""Primal ``f(t, y, p)`` as a shareable view."""

@property
def graph(self) -> ExprGraph:
"""The retained derivation arena (observation lowers new roots into it)."""

@property
def jacobian(self) -> CompiledJacobian:
"""Pure ``df/dy`` (``cj = 0``, no mass), composed over the bundle's tapes."""
Expand Down
271 changes: 259 additions & 12 deletions packages/pybamm/src/pybamm/solvers/observation.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,44 @@
"""How a :class:`pybamm.Solution` reads its variables.

:func:`build_variable` turns a variable name into a processed variable over a
Solution's sub-solutions, its *segments*, reading each segment through its own
model. A *leaf* is one segment's compiled form of one variable; each model keeps
its leaves in an :class:`ObserverCache`, so every solution of it reuses them.

:class:`OutputAssembly` is the ``output_variables`` counterpart: the solver has
already computed those variables, so it owns the payload's row layout and
populates the Solution eagerly.
:func:`build_variable` reads each of a Solution's segments through its own model. A
*leaf*, one segment's compiled form of one variable, is cached for every solution of
the model: on a Rust model's lowering, or else in an :class:`ObserverCache`.

:class:`OutputAssembly` lays out the ``output_variables`` the solver computed itself.
"""

from __future__ import annotations

from collections.abc import Mapping, Sequence
from itertools import accumulate, pairwise
from typing import Self
from typing import TYPE_CHECKING, Self

import casadi
import numpy as np
import numpy.typing as npt

import pybamm
from pybamm.solvers.base_processed_variable import BaseProcessedVariable
from pybamm.solvers.rust_lowering import RustModelLowering
from pybamm.solvers.variable_observer import (
CasadiObserver,
NativeObserver,
SharedOutputLeaf,
SharedOutputs,
check_variable_in_solve,
pack_sensitivity_dict,
)

if TYPE_CHECKING:
from pybamm.rust import CompiledFunction
from pybamm.solvers.variable_observer import NativeLeaf


class ObserverCache:
"""The compiled leaves of one model's variables, keyed by variable name.
"""The CasADi leaves of one model's variables, keyed by variable name.

A name is assumed to keep one expression for the model's lifetime. Each leaf
is built for the input layout and solution options (such as ``compile`` and
A name is assumed to keep one expression for the model's lifetime. Each leaf is
built for the input layout and solution options (such as ``compile`` and
``cse``) of the first solve that reads it, and later solves reuse it as is.
"""

Expand Down Expand Up @@ -112,6 +117,9 @@ def build_variable(solution: pybamm.Solution, name: str) -> BaseProcessedVariabl
vars_pybamm = [
model.get_processed_variable_or_event(name) for model in solution.all_models
]
segments = _native_segments(solution)
if segments is not None:
return _build_native_variable(solution, name, vars_pybamm, segments)
vars_casadi = [None] * len(solution.all_models)
for i, (model, ys, inputs) in enumerate(
zip(solution.all_models, solution.all_ys, solution.all_inputs, strict=True)
Expand All @@ -120,6 +128,7 @@ def build_variable(solution: pybamm.Solution, name: str) -> BaseProcessedVariabl
check_variable_in_solve(solution, name, var_pybamm)
cache = ObserverCache.of(model)
if isinstance(var_pybamm, pybamm.VectorField):
_check_vector_field(name, var_pybamm)
vars_casadi[i] = [
cache.casadi_leaf(
solution, f"{name}[{k}]", component, inputs, ys.shape
Expand All @@ -139,6 +148,244 @@ def build_variable(solution: pybamm.Solution, name: str) -> BaseProcessedVariabl
)


def _check_vector_field(name: str, var_pybamm: pybamm.VectorField) -> None:
"""Reject a vector field that reads a time integral.

Parameters
----------
name : str
The variable's name.
var_pybamm : :class:`pybamm.VectorField`
The variable's discretised expression.

Raises
------
NotImplementedError
If a component of ``var_pybamm`` holds an ``ExplicitTimeIntegral`` or a
``DiscreteTimeSum``.
"""
if var_pybamm.has_symbol_of_classes(
(pybamm.ExplicitTimeIntegral, pybamm.DiscreteTimeSum)
):
raise NotImplementedError(
f"Cannot process variable '{name}': a vector field's components "
"cannot hold a time integral."
)


def build_variables(
solution: pybamm.Solution, names: Sequence[str]
) -> dict[str, BaseProcessedVariable]:
"""The processed variables ``names`` of ``solution``, built as one set.

On a natively read solution, non-time-integral variables share one tape per
segment, so their common subexpressions are evaluated once.
"""
segments = _native_segments(solution)
if segments is None:
return {name: build_variable(solution, name) for name in names}
vars_pybamm = {
name: [
model.get_processed_variable_or_event(name) for model in solution.all_models
]
for name in names
}
shared = [
name
for name in names
if not any(
isinstance(var, pybamm.VectorField)
or segment.time_integral(name, var) is not None
for var, segment in zip(vars_pybamm[name], segments, strict=True)
)
]
if len(shared) < 2:
return {name: build_variable(solution, name) for name in names}
variables = {
name: build_variable(solution, name) for name in names if name not in shared
}
variables.update(_build_native_set(solution, shared, vars_pybamm, segments))
return {name: variables[name] for name in names}


class _NativeSegment:
"""One segment's native leaves, compiled on its model's Rust graph.

Each is cached by the expression it compiles as well as its name, as a name
may come to mean another expression.

Parameters
----------
lowering : :class:`pybamm.solvers.rust_lowering.RustModelLowering`
The lowering of the segment's model.
n_states : int
The number of states the segment's leaves read.
"""

def __init__(self, lowering: RustModelLowering, n_states: int):
self.lowering = lowering
self.n_states = n_states

def time_integral(
self, name: str, var_pybamm: pybamm.Symbol
) -> pybamm.ProcessedVariableTimeIntegral | None:
"""The time integral ``var_pybamm`` reads, or None, found on first use."""
return self.lowering.cached(
("time integral", name, var_pybamm.id, self.n_states),
lambda: pybamm.ProcessedVariableTimeIntegral.from_pybamm_var(
var_pybamm, self.n_states
),
)

def leaf(
self, name: str, var_pybamm: pybamm.Symbol
) -> tuple[
CompiledFunction, pybamm.Symbol, pybamm.ProcessedVariableTimeIntegral | None
]:
"""The leaf of ``var_pybamm``, its integrand and time integral, or None."""

def build():
time_integral = self.time_integral(name, var_pybamm)
integrand = (
var_pybamm if time_integral is None else time_integral.sum_node.child
)
leaf = self.lowering.function(integrand, name, n_states=self.n_states)
return leaf, integrand, time_integral

return self.lowering.cached(("leaf", name, var_pybamm.id, self.n_states), build)

def shared_leaf(self, vars_pybamm: dict[str, pybamm.Symbol]) -> CompiledFunction:
"""One tape over a set of variables, compiled on first use."""
return self.lowering.cached(
(
"set",
tuple((name, var.id) for name, var in vars_pybamm.items()),
self.n_states,
),
lambda: self.lowering.outputs_function(vars_pybamm, n_states=self.n_states),
)

def post_sum_leaf(
self, name: str, time_integral: pybamm.ProcessedVariableTimeIntegral | None
) -> CompiledFunction | None:
"""The post-sum tape a time integral's sensitivities need, or None."""
if time_integral is None or time_integral.post_sum_node is None:
return None
post_sum_node = time_integral.post_sum_node
# Its states are the integral's values
n_integral = time_integral.sum_node.evaluate_for_shape().shape[0]
return self.lowering.cached(
("post sum", name, post_sum_node.id),
lambda: self.lowering.function(
post_sum_node, "post_sum", n_states=n_integral
),
)


def _native_segments(solution: pybamm.Solution) -> list[_NativeSegment] | None:
"""Each segment's native reader, when every segment's model is a Rust model."""
models = solution.all_models
if any(model.convert_to_format != "rust" for model in models):
return None
placeholder_states = _placeholder_states(solution)
return [
_NativeSegment(
_lowering_for(model, inputs),
ys.shape[0] if placeholder_states is None else placeholder_states[i],
)
for i, (model, ys, inputs) in enumerate(
zip(models, solution.all_ys, solution.all_inputs, strict=True)
)
]


def _lowering_for(model: pybamm.BaseModel, inputs: dict) -> RustModelLowering:
"""The lowering to read ``model`` through with ``inputs``.

It is the model's own when it takes these inputs in any order, as leaves take
their inputs by name, and one made for the model if it has none. Other inputs
read through a lowering of their own, cached on the model's, which stays in
place.
"""
lowering = RustModelLowering.current(model)
if lowering is None:
return RustModelLowering.of(model, inputs)
names = frozenset(inputs)
if set(lowering.input_name_order) == names:
return lowering
return lowering.cached(
("lowering", names), lambda: RustModelLowering(model, inputs)
)


def _placeholder_states(solution: pybamm.Solution) -> list[int] | None:
"""Each segment's state count when the solve stored no states, else None."""
if not solution.variables_returned:
return None
return [model.len_rhs_and_alg for model in solution.all_models]


def _build_native_variable(
solution: pybamm.Solution,
name: str,
vars_pybamm: list[pybamm.Symbol],
segments: Sequence[_NativeSegment],
) -> BaseProcessedVariable:
"""A lazily evaluated variable whose leaves are native tapes."""
time_integral = None
leaves: list[NativeLeaf | list[CompiledFunction]] = []
for i, segment in enumerate(segments):
var_pybamm = vars_pybamm[i]
check_variable_in_solve(solution, name, var_pybamm)
if isinstance(var_pybamm, pybamm.VectorField):
_check_vector_field(name, var_pybamm)
leaves.append(
[
segment.leaf(f"{name}[{k}]", component)[0]
for k, component in enumerate(var_pybamm.components)
]
)
else:
leaf, vars_pybamm[i], time_integral = segment.leaf(name, var_pybamm)
leaves.append(leaf)
observer = NativeObserver(
leaves,
_placeholder_states(solution),
segments[0].post_sum_leaf(name, time_integral),
)
return pybamm.process_variable(
name, vars_pybamm, observer, solution, time_integral=time_integral
)


def _build_native_set(
solution: pybamm.Solution,
names: Sequence[str],
vars_pybamm: Mapping[str, list[pybamm.Symbol]],
segments: Sequence[_NativeSegment],
) -> dict[str, BaseProcessedVariable]:
"""Lazily evaluated variables reading one shared native tape per segment."""
shared_outputs = []
for i, segment in enumerate(segments):
for name in names:
check_variable_in_solve(solution, name, vars_pybamm[name][i])
function = segment.shared_leaf({name: vars_pybamm[name][i] for name in names})
shared_outputs.append(SharedOutputs(function))
placeholder_states = _placeholder_states(solution)
return {
name: pybamm.process_variable(
name,
vars_pybamm[name],
NativeObserver(
[SharedOutputLeaf(shared, name) for shared in shared_outputs],
placeholder_states,
),
solution,
)
for name in names
}


class OutputAssembly:
"""The row layout of an ``output_variables`` payload, and its attachment.

Expand Down
Loading
Loading