Reading PyBaMM Fast: Architecture for Battery Modeling and AI Data
Reading PyBaMM Fast: Architecture for Battery Modeling and AI Data
Search
Ask the AI

Reading PyBaMM Fast: Architecture for Battery Modeling and AI Data

This article explains how PyBaMM compiles electrochemical PDEs into a solvable system. When the solver fails at cycle 300, its layered architecture provides a way to locate the failure.

One spelling note for searchers: the formal name is PyBaMM (Python Battery Mathematical Modelling), not PyBAMM. EIS used to live in a separate package, pybammeis, and has since merged into core — use pybamm.EISSimulation, which linearises the underlying DAE system in the frequency domain.

PyBaMM pipeline from physical model to AI dataset
The most valuable atomic unit of battery AI data is not a voltage curve but an auditable computation graph: model structure, parameterisation, protocol, solver state and explicit label extraction together.

PyBaMM battery modelling series · Data pipeline (part 1 of 5): Next: PyBaMM EIS Data Generation: Impedance Features and AI Labels · Series hub: Data pipeline (5) + Silent failures, measured (8) · RSS feed.

1. PyBaMM as a DAE compilation pipeline

PyBaMM represents equations as a symbolic expression tree, then processes parameters, mesh, spatial discretisation and numerical solution. Simulation organises these steps. Model classes and submodels define the continuous equations; spatial methods turn operators such as gradients and divergences into discrete operations.

Use the following stages to inspect a configuration. Parameter values, the experiment and the solver are usually inputs to Simulation; model construction then processes parameters and discretisation:

  1. Model: SPM, SPMe, or DFN built on P2D porous-electrode theory.
  2. Submodel options: SEI growth, plating overpotential, particle fracture mechanics, LAM, surface-area formulation. This must happen at model construction — pushing values into parameters afterwards enables nothing.
  3. Parameterisation: inject nonlinear functions such as OCP curves plus scalar properties, mapping symbols to physical quantities.
  4. Experiment: current or C-rate, cutoffs, CCCV cycling and rest periods. Boundary conditions come from model equations and discretisation settings.
  5. Discretisation and solver: typical one-dimensional battery models use finite volumes to produce an ODE or DAE system. Choose a solver compatible with that system.

The failing stage is a useful diagnostic clue: missing parameters commonly surface during parameter processing or construction, and mesh errors during discretisation. If a model shows little degradation, inspect enabled submodels, their parameters, protocol duration and output definitions together; it is not uniquely a stage-two failure.

2. Formalising DFN, and where stiffness comes from

DFN solves coupled conservation laws in the solid and electrolyte phases. Solid lithium concentration \(c_s(r,x,t)\) inside a particle obeys Fick’s second law in spherical coordinates:

$$ \frac{\partial c_s}{\partial t} = \frac{1}{r^2} \frac{\partial}{\partial r} \left( r^2 D_s(c_s) \frac{\partial c_s}{\partial r} \right) $$

This couples to the particle-electrolyte interface through Butler-Volmer kinetics, which sets the volumetric transfer current density \(j(x,t)\):

$$ j = a_s i_0 \left[ \exp\left(\frac{\alpha_a F \eta}{R T}\right)-\exp\left(-\frac{\alpha_c F \eta}{R T}\right) \right] $$

In common Butler-Volmer parameterisations, exchange current density \(i_0\) depends on particle-surface concentration, electrolyte concentration and temperature; overpotential enters the exponential terms. The factor \(a_s\) makes \(j\) above a volumetric reaction-current density. The simplified expression \(\eta = \phi_s-\phi_e-U_{OCP}(c_s)\) needs the corresponding additional terms when film resistance or other mechanisms are enabled.

The discretised DFN combines diffusion timescales, reaction kinetics and algebraic constraints. Its stiffness depends on parameters, mesh and enabled submodels; the default model need not explicitly include double-layer dynamics. Implicit methods suit these systems. An explicit method’s stability step must be assessed for the actual discretised problem, not inferred from a universal microseconds-to-hours ratio.

3. Symbolic trees and automatic differentiation

PyBaMM constructs model equations from symbolic nodes (pybamm.Variable, pybamm.grad, pybamm.div). The snippet below shows the expression tree and symbolic differentiation:

import pybamm

x = pybamm.Variable("x")
expr = 3 * x**2 + 2 * x

print(expr)             # the expression tree itself
print(expr.diff(x))     # symbolic derivative - a new tree, not a number

A real diffusion operator looks like this. Note that grad and div require a variable with a domain — spatial operators need to know which geometry they discretise over, and omitting it raises immediately:

c_s = pybamm.Variable("Solid concentration", domain="negative particle")
D_s = pybamm.Parameter("Solid diffusion coefficient")

N_s = -D_s * pybamm.grad(c_s)   # diffusive flux
dcdt = -pybamm.div(N_s)         # rate of change of concentration

The symbolic graph supports parameter substitution, compatible meshes and symbolic or CasADi differentiation. Jacobian derivatives support the Newton iterations in implicit solvers. Convergence also depends on consistent initial conditions, tolerances, linear solves and model state; an exact Jacobian alone does not guarantee it.

4. Choosing a solver

The spatially discretised DFN is typically a stiff system with differential variables and algebraic constraints. PyBaMM converts expressions according to the selected format and solver; CasADi is one route, not a mandatory compiler for every backend. IDA/IDAS use variable-order, variable-step BDF for DAEs. ODE routes such as ScipySolver have their own methods and scope.

Version correction for the solver table: the original comparison is retained below. “CasadiSolver: Default” does not apply to PyBaMM 26.5.0: BaseModel.default_solver returns IDAKLUSolver for ordinary ODE/DAE models and NonlinearSolver for purely algebraic models. Speed rankings need matched benchmarks. ScipySolver is an ODE route and does not directly solve algebraic-constraint DAEs.

Solver Use for Caveat
CasadiSolver Default, most general Noticeably slower than IDAKLU on long cycling experiments
IDAKLUSolver First choice for long degradation runs Sparse linear algebra; the advantage grows with problem size
ScipySolver Quick experiments on pure-ODE models Cannot handle DAEs with algebraic constraints

Record tolerances, mesh and solver version, and recompute important outputs with tighter tolerances or a finer mesh. If features change materially, assess discretisation and solver errors before interpreting them as degradation. Whether defaults are adequate depends on the output being measured.

5. The three models are different state spaces, not accuracy tiers

SPM, SPMe and DFN make different approximations to electrolyte and electrode spatial distributions. For generated labels, first check that the model represents the target mechanism, then compare output error and computational cost in the intended conditions.

  • SPM: uses a representative particle per electrode for solid diffusion. The default PyBaMM implementation uses constant electrolyte concentration and a leading-order potential approximation. It can be useful when electrolyte gradients are small. At high rates or other strong-gradient conditions, compare errors with a more complete model or data; their direction is not fixed by the model name.
  • SPMe: adds electrolyte concentration and potential corrections to the single-particle framework. It can support sweeps that need those effects; compare cost and accuracy with the same mesh, solver settings and operating conditions.
  • DFN: resolves spatial distributions across the negative electrode, separator and positive electrode. Local plating also requires its submodel; EIS requires the dynamics relevant to the target response. Published impedance-parameterisation work uses SPMe too, so EIS arcs are not exclusive to DFN.

One option is to sweep with SPMe and recompute a selected subset with DFN. Record models, options and numerical settings, then compare their effects on the target output.

6. Schema design for AI samples

Design the dataset for falsifiability. An auditable sample carries:

  • Boundary and initial conditions: initial \(c_s\) distribution (SOC), thermal field, rate limits, frequency excitation grid.
  • Observable features: terminal voltage statistics, \(Z_{re}\) and \(Z_{im}\), high-frequency intercept, Warburg tail coefficient.
  • Physical labels: record moles of lithium consumed by SEI, LLI normalised to a stated reference, and LAM defined separately for each electrode. ECM labels also require their fitted model, units, constraints and residuals; they are not unique direct outputs of every electrochemical model.
  • Solver fingerprint: solver type, tolerance, version, failure flags, step statistics.

7. Sample audit table

Use this to judge whether a sample has research value, rather than merely producing a curve.

Audit dimension Must record Research value Unacceptable signal
Model structure SPM/SPMe/DFN, enabled degradation submodels, parameter set version Determines which mechanisms the sample can express Only a voltage curve, with no record of model or parameter set
Experimental protocol C-rate, temperature, cutoffs, rest time, EIS frequency grid Determines identifiability between observables and internal state Train and test share adjacent cycles of one trajectory
Solver state Solver type and version, tolerance, failure flags, step statistics Separates real physical change from numerical error Non-convergent, deeply degraded samples written into training
Trajectory completeness Cycles completed vs cycles requested Identifies truncated, early-terminated trajectories Trajectories of different lengths treated as equivalent samples
Label extraction Formulas and units for SOH, LLI, LAM, ECM parameters Ensures the model learns interpretable physical quantities A bare health_score with no unit, formula or provenance

8. Three methodological traps

  • Interpret synthetic truth within the model. Known parameters can provide ground truth for a synthetic control. Transfer to real cells requires experimental validation of the model and parameters; nonlinear least squares is one calibration option.
  • Check coverage as well as count. Even 10,000 samples can occupy a narrow parameter region. Choose physically supported ranges and correlations before considering a coverage method such as Latin hypercube sampling. The sampler alone guarantees neither identifiability nor physical diversity.
  • Check numerical sensitivity. When extracting impedance or other features from degraded states, retain failures and compare the features after tightening tolerance and refining the mesh.

Transfer to real cells also requires assessing manufacturing differences, temperature variation and sensor noise. A model can include some of these mechanisms or disturbances, but generated data reflects only what was included and validated. Test transfer on real measurements.

References

The “solver fails at cycle 300” scenario from the opening has its own troubleshooting guide: PyBaMM solver convergence failures – numerics or physics, including every IDAKLU option default and one trap that fails silently.

Related: PyBaMM’s built-in parameter sets, measured records the versions and protocols for a capacity and temperature comparison. Marquis2019’s “1C” is about 0.78C relative to the measured capacity defined there; Chen2020 showed a small cold-capacity change in that test.

A tool I built

Validate your cell model on independent data

VoltSift is an online workspace I built. Upload three CSV files (a fitting record, an independent validation record and an open-circuit voltage curve), and it fits a cell model, checks voltage error and coverage on the held-out record, and produces a report. The standard workflow supports single NMC cells at 25°C and SOC 20%–100%. Register and verify your email to get one free analysis, available for seven days.

Visit VoltSift · Prepare the three CSV files · How to read the validation results

Leave a Reply

Scroll down