Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 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
14 changes: 12 additions & 2 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,18 @@ jobs:
test:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python-version: ["3.10", "3.11", "3.12", "3.13"]
include:
# All Python versions against the latest PyBaMM
- {python-version: "3.10", pybamm-version: "26.4"}
- {python-version: "3.11", pybamm-version: "26.4"}
- {python-version: "3.12", pybamm-version: "26.4"}
- {python-version: "3.13", pybamm-version: "26.4"}
- {python-version: "3.14", pybamm-version: "26.4"}
# Older PyBaMM versions against the latest Python they support
- {python-version: "3.13", pybamm-version: "25.12"}
- {python-version: "3.14", pybamm-version: "26.3"}

steps:
- uses: actions/checkout@v4
Expand All @@ -38,7 +48,7 @@ jobs:
python-version: ${{ matrix.python-version }}

- name: Install
run: pip install -e ".[test]" mypy
run: pip install -e ".[test]" mypy "pybamm==${{ matrix.pybamm-version }}"

- name: mypy
run: mypy src/pathsim_batt
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ classifiers = [
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Programming Language :: Python :: 3.14",
"Topic :: Scientific/Engineering",
]
dependencies = [
Expand Down
254 changes: 213 additions & 41 deletions src/pathsim_batt/cells/pybamm_cell.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,35 @@
"Ambient temperature [K]": 298.15,
}

# The PyBaMM variable name used for voltage cut-off detection.
# Both base classes locate it by name in ``_pybamm_output_vars`` at construction
# time, so subclasses may place it at any position in the list.
# Canonical PyBaMM variable name for terminal voltage (lithium-ion / lead-acid).
# Equivalent-circuit and sodium-ion BasicDFN models export it under a different
# name; ``_VOLTAGE_VAR_CANDIDATES`` lists all known aliases in priority order.
_TERMINAL_VOLTAGE_VAR = "Terminal voltage [V]"

_VOLTAGE_VAR_CANDIDATES: list[str] = [
"Terminal voltage [V]",
"Voltage [V]",
"Battery voltage [V]",
]
_HEATING_VAR_CANDIDATES: list[str] = [
"Total heating [W]",
"Total heat generation [W]",
]
_TEMP_VAR_CANDIDATES: list[str] = [
"X-averaged cell temperature [K]",
"Cell temperature [K]",
]
_SOC_CAPACITY_VAR = "Discharge capacity [A.h]"
_SOC_DIRECT_CANDIDATES: list[str] = ["State of charge", "State of Charge", "SoC"]

# Map from the canonical names used in ``_pybamm_output_vars`` to their
# per-model-family fallback lists.
_VAR_ALIAS_MAP: dict[str, list[str]] = {
"Terminal voltage [V]": _VOLTAGE_VAR_CANDIDATES,
"Total heating [W]": _HEATING_VAR_CANDIDATES,
"X-averaged cell temperature [K]": _TEMP_VAR_CANDIDATES,
}


def _prepare_parameter_values(
parameter_values: pybamm.ParameterValues | None,
Expand All @@ -42,6 +66,113 @@ def _prepare_parameter_values(
return parameter_values


def _pick_var(variables: dict, candidates: list[str], description: str) -> str:
"""Return the first name in *candidates* present in *variables*.

Raises ``ValueError`` listing all tried names if none match.
"""
for name in candidates:
if name in variables:
return name
raise ValueError(
f"No {description} variable found in PyBaMM model. Tried: {candidates}"
)


def _resolve_output_vars(
requested: list[str],
available: dict,
) -> tuple[list[str], str | None, str | None]:
"""Map *requested* variable names to names actually present in *available*.

Returns ``(resolved, soc_cap_var, soc_direct_var)``:

* ``resolved`` — same length as *requested*; each entry is the actual
PyBaMM variable name to use (canonical or alias).
* ``soc_cap_var`` — ``"Discharge capacity [A.h]"`` when available (standard
electrochemical models), otherwise ``None``.
* ``soc_direct_var`` — a direct SoC variable name used when *soc_cap_var*
is ``None`` (ECM, some basic models).
"""
resolved = [
_pick_var(available, _VAR_ALIAS_MAP[name], name)
if (name not in available and name in _VAR_ALIAS_MAP)
else name
for name in requested
]

if _SOC_CAPACITY_VAR in available:
return resolved, _SOC_CAPACITY_VAR, None
return (
resolved,
None,
_pick_var(available, _SOC_DIRECT_CANDIDATES, "state of charge"),
)


def _detect_soc_direct_scale(
sim: pybamm.Simulation,
soc_direct_var: str | None,
) -> float:
"""Return 1/100 if *soc_direct_var* is in percentage form, else 1.0.

Some models (e.g. lead-acid) export ``"State of Charge"`` in the range
0–100 rather than 0–1. Evaluating the variable at the initial state with
zero current lets us detect this once at construction time.
"""
if soc_direct_var is None:
return 1.0
objs = sim.built_model.export_casadi_objects(
[soc_direct_var],
input_parameter_order=list(_DEFAULT_INPUTS.keys()),
)
p0 = casadi.DM(list(_DEFAULT_INPUTS.values()))
x0 = casadi.Function("x0", [objs["inputs"]], [objs["x0"]])(p0)
z0 = casadi.Function("z0", [objs["inputs"]], [objs["z0"]])(p0)
soc_fn = casadi.Function(
"soc",
[objs["t"], objs["x"], objs["z"], objs["inputs"]],
[objs["variables"][soc_direct_var]],
)
raw = float(soc_fn(0.0, x0, z0, p0))
return 1.0 / 100.0 if raw > 1.0 else 1.0


def _build_simulation(
sim: pybamm.Simulation,
model: pybamm.BaseBatteryModel,
initial_soc: float,
) -> None:
"""Build *sim*, handling model-family-specific initialisation quirks.

* **ECM** (``Thevenin``): initial SoC is set via ``set_initial_state`` on
the parameter values before build; ``initial_soc`` cannot be passed to
``sim.build()`` directly.
* **Lead-acid** models: the eSOH solver used by the standard build path is
lithium-ion–specific and fails for lead-acid parameter sets; build
without ``initial_soc``.
* **All other models**: standard ``sim.build(initial_soc=...)``.
"""
if isinstance(model, pybamm.equivalent_circuit.Thevenin):
from pybamm.models.full_battery_models.equivalent_circuit import (
set_initial_state,
)

set_initial_state(initial_soc, sim.parameter_values)
sim.build(inputs=_DEFAULT_INPUTS)
elif isinstance(model, pybamm.lead_acid.BaseModel):
if initial_soc != 1.0:
raise ValueError(
"initial_soc is not supported for lead-acid models: PyBaMM's "
"lead-acid parameter sets do not include the electrode OCP data "
"required to map a target SoC to initial stoichiometries. "
"The initial state is always determined by the parameter values."
)
sim.build(inputs=_DEFAULT_INPUTS)
else:
sim.build(initial_soc=initial_soc, inputs=_DEFAULT_INPUTS)
Comment thread
DavidMStraub marked this conversation as resolved.
Resolved


# BLOCKS ===============================================================================


Expand Down Expand Up @@ -82,13 +213,11 @@ def __init__(
) -> None:
self._initial_soc = float(initial_soc)

try:
self._v_idx = self._pybamm_output_vars.index(_TERMINAL_VOLTAGE_VAR)
except ValueError:
if not any(v in self._pybamm_output_vars for v in _VOLTAGE_VAR_CANDIDATES):
raise TypeError(
f"{type(self).__name__}._pybamm_output_vars must contain "
f"'{_TERMINAL_VOLTAGE_VAR}'."
) from None
f"{type(self).__name__}._pybamm_output_vars must contain one of "
f"{_VOLTAGE_VAR_CANDIDATES}."
)
Comment thread
DavidMStraub marked this conversation as resolved.
Resolved

if model is None:
model = pybamm.lithium_ion.SPMe(
Expand All @@ -113,27 +242,44 @@ def __init__(
parameter_values=self._parameter_values,
solver=pybamm_solver,
)
sim.build(initial_soc=self._initial_soc, inputs=_DEFAULT_INPUTS)
_build_simulation(sim, model, self._initial_soc)

available = sim.built_model.variables

# Early DAE check: probe with just the voltage variable so that the
# NotImplementedError is raised before variable-resolution, giving a
# cleaner error message for models that are DAE *and* also lack other
# required output variables (e.g. sodium_ion.BasicDFN).
_vol_var = _pick_var(available, _VOLTAGE_VAR_CANDIDATES, "terminal voltage")
_probe = sim.built_model.export_casadi_objects(
[_vol_var], input_parameter_order=list(_DEFAULT_INPUTS.keys())
)
if _probe["z"].numel() > 0:
raise NotImplementedError(
f"{type(self).__name__}: the supplied PyBaMM model has "
f"{_probe['z'].numel()} algebraic variable(s) after discretisation "
"(DAE system). Only pure ODE models are supported by this block. "
"Use a CellCoSim* block for DAE models."
)

all_out_vars = self._pybamm_output_vars + ["Discharge capacity [A.h]"]
resolved_output_vars, soc_cap_var, soc_direct_var = _resolve_output_vars(
self._pybamm_output_vars, available
)
self._v_idx = resolved_output_vars.index(
next(v for v in _VOLTAGE_VAR_CANDIDATES if v in resolved_output_vars)
)

extra_soc_var = soc_cap_var if soc_cap_var is not None else soc_direct_var
all_out_vars = resolved_output_vars + [extra_soc_var]
casadi_objs = sim.built_model.export_casadi_objects(
all_out_vars,
input_parameter_order=list(_DEFAULT_INPUTS.keys()),
)

t_sym = casadi_objs["t"]
x_sym = casadi_objs["x"]
z_sym = casadi_objs["z"]
p_sym = casadi_objs["inputs"]

if z_sym.numel() > 0:
raise NotImplementedError(
f"{type(self).__name__}: the supplied PyBaMM model has "
f"{z_sym.numel()} algebraic variable(s) after discretisation "
"(DAE system). Only pure ODE models are supported. "
"Use SPMe or SPM instead of DFN."
)

rhs_fn = casadi.Function("rhs", [t_sym, x_sym, p_sym], [casadi_objs["rhs"]])
jac_fn = casadi.Function(
"jac_rhs", [t_sym, x_sym, p_sym], [casadi_objs["jac_rhs"]]
Expand All @@ -153,7 +299,7 @@ def __init__(

q_nominal = self._q_nominal
initial_soc_val = float(initial_soc)
pybamm_output_vars = list(self._pybamm_output_vars)
soc_direct_scale = _detect_soc_direct_scale(sim, soc_direct_var)

def _pack(u):
return casadi.DM([float(u[0]), float(u[1])])
Expand All @@ -175,9 +321,13 @@ def jac_dyn(x, u, t):
def func_alg(x, u, t):
xv = casadi.DM(x.reshape(-1, 1))
p = _pack(u)
outputs = [float(out_var_fns[n](t, xv, p)) for n in pybamm_output_vars]
q_dis = float(out_var_fns["Discharge capacity [A.h]"](t, xv, p))
soc = max(0.0, min(1.0, initial_soc_val - q_dis / q_nominal))
outputs = [float(out_var_fns[n](t, xv, p)) for n in resolved_output_vars]
if soc_cap_var is not None:
q_dis = float(out_var_fns[soc_cap_var](t, xv, p))
soc = max(0.0, min(1.0, initial_soc_val - q_dis / q_nominal))
else:
raw = float(out_var_fns[soc_direct_var](t, xv, p))
soc = max(0.0, min(1.0, raw * soc_direct_scale))
outputs.append(soc)
V = outputs[v_idx]
if V <= v_lower:
Expand Down Expand Up @@ -232,13 +382,12 @@ def __init__(
) -> None:
self._initial_soc = float(initial_soc)

try:
self._v_idx = self._pybamm_output_vars.index(_TERMINAL_VOLTAGE_VAR)
except ValueError:
if not any(v in self._pybamm_output_vars for v in _VOLTAGE_VAR_CANDIDATES):
raise TypeError(
f"{type(self).__name__}._pybamm_output_vars must contain "
f"'{_TERMINAL_VOLTAGE_VAR}'."
) from None
f"{type(self).__name__}._pybamm_output_vars must contain one of "
f"{_VOLTAGE_VAR_CANDIDATES}."
)

self._dt = float(dt)
if self._dt <= 0.0:
raise ValueError("dt must be positive")
Expand All @@ -264,6 +413,19 @@ def __init__(

self._sim = self._build_sim()

available = self._sim.built_model.variables
self._resolved_output_vars, self._soc_cap_var, self._soc_direct_var = (
_resolve_output_vars(self._pybamm_output_vars, available)
)
self._v_idx = self._resolved_output_vars.index(
next(v for v in _VOLTAGE_VAR_CANDIDATES if v in self._resolved_output_vars)
)
# Scale factor: 1.0 if SOC direct variable is in [0,1] fraction form,
# 1/100 if it is in percentage form (e.g. lead_acid "State of Charge").
self._soc_direct_scale = _detect_soc_direct_scale(
self._sim, self._soc_direct_var
)

self._last_outputs: npt.NDArray[np.float64] = self._initial_outputs()

super().__init__(func=self._discrete_step, T=self._dt, tau=self._dt)
Expand All @@ -278,7 +440,7 @@ def _build_sim(self) -> pybamm.Simulation:
parameter_values=self._parameter_values,
solver=self._pybamm_solver,
)
sim.build(initial_soc=self._initial_soc, inputs=_DEFAULT_INPUTS)
_build_simulation(sim, self._model, self._initial_soc)
return sim

def _initial_outputs(self) -> npt.NDArray[np.float64]:
Expand All @@ -292,7 +454,10 @@ def _initial_outputs(self) -> npt.NDArray[np.float64]:
not account for a non-default initial temperature or a non-zero current at
t=0.
"""
all_out_vars = self._pybamm_output_vars + ["Discharge capacity [A.h]"]
extra_soc_var = (
self._soc_cap_var if self._soc_cap_var is not None else self._soc_direct_var
)
all_out_vars = self._resolved_output_vars + [extra_soc_var]
casadi_objs = self._sim.built_model.export_casadi_objects(
all_out_vars,
input_parameter_order=list(_DEFAULT_INPUTS.keys()),
Expand All @@ -308,19 +473,22 @@ def _initial_outputs(self) -> npt.NDArray[np.float64]:
z0 = casadi.Function("z0", [p_sym], [casadi_objs["z0"]])(p0)

outputs: list[float] = []
for name in self._pybamm_output_vars:
for name in self._resolved_output_vars:
fn = casadi.Function(
"v", [t_sym, x_sym, z_sym, p_sym], [casadi_objs["variables"][name]]
)
outputs.append(float(fn(0.0, x0, z0, p0)))

q_dis_fn = casadi.Function(
"q",
extra_fn = casadi.Function(
"e",
[t_sym, x_sym, z_sym, p_sym],
[casadi_objs["variables"]["Discharge capacity [A.h]"]],
[casadi_objs["variables"][extra_soc_var]],
)
q_dis = float(q_dis_fn(0.0, x0, z0, p0))
soc = max(0.0, min(1.0, self._initial_soc - q_dis / self._q_nominal))
extra_val = float(extra_fn(0.0, x0, z0, p0))
if self._soc_cap_var is not None:
soc = max(0.0, min(1.0, self._initial_soc - extra_val / self._q_nominal))
else:
soc = max(0.0, min(1.0, extra_val * self._soc_direct_scale))
outputs.append(soc)

return np.array(outputs, dtype=np.float64)
Expand All @@ -333,9 +501,13 @@ def _discrete_step(self, current: float, t_amb: float) -> npt.NDArray[np.float64
self._sim.step(dt=self._dt, inputs=inputs, save=False)

sol = self._sim.solution
outputs = [float(sol[n].entries[-1]) for n in self._pybamm_output_vars]
q_dis = float(sol["Discharge capacity [A.h]"].entries[-1])
soc = max(0.0, min(1.0, self._initial_soc - q_dis / self._q_nominal))
outputs = [float(sol[n].entries[-1]) for n in self._resolved_output_vars]
if self._soc_cap_var is not None:
q_dis = float(sol[self._soc_cap_var].entries[-1])
soc = max(0.0, min(1.0, self._initial_soc - q_dis / self._q_nominal))
else:
raw = float(sol[self._soc_direct_var].entries[-1])
soc = max(0.0, min(1.0, raw * self._soc_direct_scale))
outputs.append(soc)

self._last_outputs = np.array(outputs, dtype=np.float64)
Expand Down
Loading
Loading