The PyBaMM Battery Modelling Framework: From Expression Trees to Experiment Protocols
NewOverview
A recurring pattern in battery research is a model that must be physically faithful enough to support design decisions while remaining fast enough to survive parameter sweeps and duty-cycle simulation. PyBaMM is a widely adopted open-source option in that space, and the earlier entry in this collection was written from exactly that angle.
Its landing point needs correction. The entry positioned PyBaMM as a battery electrochemical digital twin, listed digital twins for storage farms and electric vehicles and SOH prediction as its use cases, and glossed the framework as automatically assembled from a configuration file. A star count was appended in parentheses as well. Each of these needs adjusting.
First, PyBaMM is a modelling and simulation framework, not a digital twin system. A digital twin is a continuously running model that maintains a data loop with a physical asset; PyBaMM supplies offline solving capability, and only gains digital-twin behaviour once data assimilation, live data ingestion and state estimation are attached. It collects nothing and updates nothing on its own.
Second, the "assembled from a configuration file" description points at a mechanism that no longer exists in this form. Current PyBaMM builds models through an expression tree: every mathematical expression in a model is an instance of a Symbol subclass, and users compose them explicitly in Python code. The model structure is therefore programmable data that can be generated, transformed and inspected programmatically.
Third, the star count is a volatile number that would expire quickly inside a permanent entry, so it is removed here.
Fourth, the year needs adjusting. The entry recorded 2019, while the PyBaMM citation paper appeared in 2021 in the Journal of Open Research Software, and the licence file carries a 2018 copyright year. This entry uses 2021, following the citation paper.
What this guide therefore explains is how a battery simulation framework is assembled, what its public interfaces look like, how version policy affects engineering practice, and which part of a physics AI workflow it can actually carry. See tools/physicsnemos for a GPU-accelerated numerical alternative, collections/surrogate-modeling-rom for the general surrogate and reduced-order taxonomy, and cases/battery-thermal-piml for a physics-informed network predicting battery pack temperature fields. This entry covers the physical model layer itself.
How It Works
PyBaMM stands for Python Battery Mathematical Modelling. Its README defines it as an open-source battery simulation package written in Python, comprising (i) a framework for writing and solving systems of differential equations, (ii) a library of battery models and parameters, and (iii) specialised tools for simulating battery-specific experiments and visualising results.
The first piece is the expression tree. Every model is written as a set of mathematical expressions, each an instance of a Symbol subclass such as Parameter, FunctionParameter or Variable. Users assemble equations by combining these symbols in Python code, so the model is a composable, differentiable, automatically differentiable expression tree. This is the structural difference from template-driven simulation tools: model structure is itself data, and can be generated, transformed and tested programmatically.
The second piece is the discretisation pipeline. Each model contains continuous operators that must be discretised before solving, and this is handled by a Discretisation object receiving a Mesh and a dictionary of SpatialMethod objects. Meshes split into several submesh types, each domain such as negative electrode, positive electrode, separator and electrolyte may carry its own number of points, and spatial discretisation options span finite volume and finite element. Behaviour is switched through BatteryModelOptions, whose documented option keys include particle diffusion form (Fickian diffusion, uniform profile, quadratic profile, quartic profile, MSMR), particle mechanics (none, swelling only, swelling and cracking), particle phases, particle shape, particle size, the SEI submodel, SEI film resistance, SEI on cracks, SEI porosity change, stress-induced diffusion, surface form, surface temperature form, thermal model (isothermal, lumped, x-lumped, x-full), whether total interfacial current density is a state variable, and a family of transport efficiency models including Bruggeman, ordered packing, hyperbola of revolution, overlapping spheres, tortuosity factor and random overlapping cylinders.
The third piece is solving and experimenting. The recommended and default solver is IDAKLUSolver, a PyBaMM wrapper around the SUNDIALS suite, whose C/C++ implementation moved into a standalone pybammsolvers package at version 25.1, leaving the main PyBaMM package pure Python. Results are returned as a Solution object; plotting runs through QuickPlot, with plot_voltage_components() and plot_summary_variables() handling voltage decomposition and summary quantities.
Experiments are described by an Experiment object, given either as Python strings or as a sequence of step.BaseStep objects. A typical protocol discharges at C/10 for ten hours or until 3.3 V, rests an hour, charges at 1 A until 4.1 V, holds at 4.1 V until 50 mA, and rests again; such protocols pass directly to Simulation.
The model family documented in the public API lists three main models: lithium_ion.SPM (single particle model), lithium_ion.SPMe (single particle model with electrolyte) and lithium_ion.DFN (Doyle-Fuller-Newman). SPM neglects electrolyte concentration distribution, SPMe retains electrolyte but eliminates its diffusion equation algebraically, and DFN keeps the full set of solid diffusion, electrolyte diffusion and potential equations. Fidelity and cost rise together, and the choice is a physical assumption rather than a performance knob.
On degradation, SEI growth options include none, constant, reaction limited, reaction limited asymmetric, solvent-diffusion limited, electron-migration limited, interstitial-diffusion limited, ec reaction limited, ec reaction limited asymmetric, VonKolzenberg2020 and tunnelling limited. Plating offers no_plating, plating and total_lithium_plating, the last two distinguishing local from whole-cell treatment. The OCP side adds single-state, MSMR, single-state hysteresis, single-state differential capacity hysteresis and current sigmoid forms.
Parameter sets are named author plus year. Bundled lithium-ion sets include Ai2020, Bonkile2024, Chen2020, Chen2020_composite, Ecker2015, Ecker2015_graphite_halfcell, Marquis2019, Mohtat2020, NCA_Kim2011, OKane2022, ORegan2022, Prada2013, Ramadass2004, Xu2019 and MSMR_example_set. Third-party sets register through the pybamm_parameter_sets entry point, and community or partner models ship separately in the model zoo package.
Scope and Assumptions
The first assumption is that model fidelity matches the intended use. Choosing between DFN and SPM is a physical trade-off, not a performance setting: SPM omits electrolyte diffusion and yields optimistic results in fast-charging, high-rate or electrolyte-limited regimes, while DFN keeps full physics at higher solve cost and convergence difficulty. Drawing DFN-level engineering conclusions from SPM output is a mismatch of premises.
The second assumption concerns what a parameter set represents. Every bundled set corresponds to a specific cell described in a specific paper, Chen2020 being NMC811 and Marquis2019 the LG M50 among others. Treating them as generic defaults is risky, since material parameters, OCP curves and solid diffusivities are all bound to a particular chemistry.
The third assumption is geometric consistency. PyBaMM ships default geometries with a pouch option among the cell geometry choices, and inferring production dimensions requires custom geometry plus a consistency re-check of mesh and parameters afterwards.
The fourth assumption is the depth of thermal and mechanical coupling. Four thermal tiers run from isothermal to the full heat equation, particle mechanics spans swelling and cracking, and these options stack, each additional tier raising both cost and parameter demand. Real projects rarely enable everything.
The fifth assumption is the timescale of degradation. SEI growth and plating are tractable over hundreds to thousands of cycles, but projecting to full life requires assumptions PyBaMM itself does not supply.
The sixth assumption concerns the compiled solver layer. IDAKLUSolver relies on prebuilt binaries shipped by pybammsolvers, and each platform and Python version needs its own wheel. Where no wheel exists, users fall back to pure Python solvers at a noticeable performance cost.
Getting Started
The shortest path in the README is four lines of Python: instantiate pybamm.lithium_ion.DFN(), wrap it in a Simulation, solve over [0, 3600] for one hour of 1C constant-current discharge, and plot.
The version with an experiment protocol builds an Experiment from a repeated sequence of discharge at C/10 for ten hours or until 3.3 V, a one-hour rest, charge at 1 A until 4.1 V, hold at 4.1 V until 50 mA and another rest, then solves it against the same DFN model.
For installation the project strongly recommends a virtual environment. The pip route is pip install pybamm; the conda route uses the conda-forge channel, where conda install -c conda-forge pybamm-base installs only required dependencies and conda install -c conda-forge pybamm installs everything except jax. The optional JAX solver has its own install path with jax >=0.7.0, <0.9.0.
Platforms supported are GNU/Linux, macOS and Windows. One caveat: the README notes that versions between 24.11.2 and 25.6, excluding those boundaries, are not available on conda-forge, so those versions require the pip channel.
For real onboarding the project recommends the Getting Started notebooks rather than the API reference. Nine tutorials cover running a model, comparing models, basic plotting, setting parameter values, running experiments, managing simulation outputs, model options, solver options and changing the mesh. Six further notebooks build models from a simple ODE model through a simple PDE model, the negative particle problem, comparing full and reduced-order models, a half-cell model and a simple SEI growth model. A separate performance group covers the Simulation pipeline and its performance profile, re-running with different parameters through input parameters, the solvers, interpolation and evaluation points, solver tolerances, reducing memory use by defining output variables, and parallel execution of many simulations through OpenMP.
Community and partner models install separately with pip install pybamm-model-zoo.
For citations, appending pybamm.print_citations() prints the relevant BibTeX to the terminal, or writes it to a file when given a filename; the full list sits in packages/pybamm/src/pybamm/CITATIONS.bib. The base citation is Sulzer V., Marquis S. G., Timms R., Robinson M. and Chapman S. J. (2021), *Python Battery Mathematical Modelling (PyBaMM)*, Journal of Open Research Software, 9(1), DOI 10.5334/jors.309. The README also notes that PyBaMM relies heavily on CasADi, so CasADi's publications belong in the reference list too.
Comparison with Alternatives
Four families of alternatives frame PyBaMM's position.
The first is commercial electrochemical design tooling, widely used inside cell manufacturers and usually deeply coupled to proprietary experimental calibration flows. The difference is programmability and auditability: the model is expression-tree source code that can be read line by line, modified, generated and tested programmatically. What PyBaMM lacks by comparison is the accumulated calibration workflow and enterprise engineering management of commercial suites.
The second is other open-source battery modelling projects, where the real difference lies in the modelling language chosen, whether equations written directly for a general solver or the emphasis placed on data. PyBaMM takes the programmable-assembly route with physics at its core, and accepts the modelling abstractions that implies.
The third is the machine-learned surrogate route. cases/battery-thermal-piml offers a concrete contrast: a physics-informed network predicts liquid-cooled pack temperature fields directly, bypassing electrochemical modelling, whereas PyBaMM's SPMe and DFN are the physical model itself. The two can be alternatives or layers, with SPMe providing a physical baseline that a surrogate accelerates or corrects.
The fourth is reduced-order and real-time modelling. collections/surrogate-modeling-rom surveys reduced-order methods in general. Within the PyBaMM ecosystem, SPM and SPMe are already a physical-level reduction relative to DFN, and applying POD or ROM on top of DFN is a numerical-level reduction: the former keeps the equation structure, the latter keeps the solution manifold.
One horizontal axis worth naming is the solver ecosystem. The default IDAKLU runs on SUNDIALS, while the optional JAX solver uses forward-mode automatic differentiation. tools/jax and tools/jax-cfd describe JAX in computational fluid dynamics, the same idea as PyBaMM's JAX solver: keeping equations differentiable so optimisation, parameter estimation and uncertainty propagation can descend gradients on the model itself rather than perturbing it with finite differences.
Benchmarks and Evidence
One fact belongs in front: PyBaMM publishes no model accuracy leaderboard and no official validation dataset acting as an accuracy yardstick. Its correctness argument rests on three pillars.
The first is literature correspondence. Each bundled parameter set maps to an experimental paper, and each equation form maps to specific work, from the original Doyle-Fuller-Newman treatment through Newman electrolyte models to individual SEI growth mechanisms. Accuracy arguments take the form of agreement with a given paper under given conditions, and these are distributed across the literature rather than collected in one table.
The second is cross-model consistency. One tutorial covers model comparison, and the differences between SPM, SPMe and DFN under identical conditions constitute a test in themselves: if the reduced model deviates beyond expectation, the reduction assumption fails. This is the most common validation instrument in the PyBaMM ecosystem.
The third is regression testing and coverage. The repository runs a periodic test pipeline with coverage badges, so models and solvers face regression checks on every commit.
Evidence on the machine-learning side is best found at the methodological level. The official documentation offers no tutorial on accelerating PyBaMM with ML, but the ecosystem contains substantial work along three routes: using PyBaMM as a data generator for parameter sweeps that produce training pairs; writing physical constraints into surrogate losses so the surrogate inherits part of the conservation structure; and embedding PyBaMM inside optimisation loops, using a differentiable solver or finite-difference gradients to optimise charging protocols or cell designs directly. The third route is feasible precisely because of the expression tree's differentiability and the InputParameter mechanism, and the performance documentation covers both that mechanism and the trimming of output variables, which are the two capabilities that make large-scale parameter studies over PyBaMM practical.
The boundary worth stating: acceleration ratios and accuracy gains reported by such third-party work depend on the specific cell, operating conditions and surrogate architecture, and they do not measure PyBaMM itself. Cite the individual paper and state its scope.
On data, PyBaMM ships no experimental dataset. Users needing cell test data for parameter estimation or validation must obtain it separately.
Role in Physics-AI Workflows
Inside a physics AI workflow, PyBaMM serves as the physical kernel, reachable along five paths.
The first is as a data generator, currently the most common use: sweep parameters in PyBaMM to produce samples pairing parameters with voltage curves, capacity and temperature, then train a model on them. This requires batch simulation capability, and the OpenMP parallel notebook, the input parameter mechanism and output variable trimming exist for exactly this purpose.
The second is as the kernel of parameter estimation. Given a voltage curve and a duty cycle, the unknown material parameters form a standard inverse problem, and PyBaMM supplies the value representation, scalars, Python functions and Symbol expressions, along with residual computation, so an optimiser can close the loop.
The third is as a differentiable kernel inside an optimisation loop, the most valuable path for physics AI. Charging protocols, cell geometry and tab placement become design variables attached to model parameters, and gradients optimise them directly. The JAX solver route exists for this purpose, and its output is an optimisable expression over design variables and performance metrics rather than a trained network.
The fourth is hybrid models. Physics supplies the baseline and ML absorbs systematic bias, most commonly from ageing, where SEI and plating mechanism parameters are hard to calibrate. In such structures PyBaMM provides trustworthy physics for early and mid life while ML carries the long-horizon extrapolation.
The fifth is as a real-time BMS kernel. SPM is cheap enough to run embedded or at the edge, supporting online state estimation and safety envelope checks. The performance engineering considerations in collections/performance-engineering apply at this level too.
All five paths share one premise: the physical quantities PyBaMM returns must be trustworthy, which requires the right model form, the right parameter set, and degradation choices backed by experiment.
Limitations and Failure Modes
The first is full-life extrapolation. SEI growth and plating models give sensible trends over hundreds to thousands of cycles, but full-life capacity fade involves many unmodelled mechanisms, positive particle cracking, transition metal dissolution, gassing, and repeated SEI rupture and reformation, none of which the parameterised degradation models cover. The earlier entry's claim about SOH prediction holds only within a bounded cycle window.
The second is quantitative conclusions for uncalibrated cells. Bundled parameter sets correspond to particular chemistries. A quantitative prediction for a cell that was never experimentally calibrated may have the right curve shape and wrong numbers, which matters most outside cell manufacturers.
The third is the limits of plating and fast-charging boundaries. Quantitative capability for plating depends on SEI film electron permeability, a parameter that varies widely across the literature, so fast-charge window predictions are highly sensitive to the chosen values.
The fourth is simplification of spatial non-uniformity. The x-averaged reduction is valid when current density is approximately uniform through thickness and collector potential variation is negligible, and both premises weaken at very low or very high rates.
The fifth is the simplification of geometry and multiphysics coupling. Default geometries are specific; full three-dimensional thermal-electrochemical coupling, contact thermal resistance and module-level cooling networks are not on the core path and must be built separately.
The sixth is behaviour change across versions. PyBaMM uses CalVer with breaking changes targeting the first feature release of a month, so an upstream change to a default model, default solver or default option changes numerical results. Any decision process depending on PyBaMM must pin its version.
The seventh is build dependencies and platform differences. Prebuilt binaries from pybammsolvers do not cover every platform and Python version, and where no wheel exists users must fall back to a pure Python solver at a clear performance gap, which bulk simulation plans should budget for.
The eighth is conceptual misuse. Wiring PyBaMM into a production pipeline in the expectation that it handles live data streams and state updates yields an incomplete system. The framework provides the kernel; a digital twin additionally needs data assimilation, online state estimation, alarming logic and operational monitoring.
Version and Source Notes
This section records each correction to the earlier entry together with the boundaries established by primary sources.
- Framework positioning. The README defines PyBaMM as an open-source battery simulation package with three parts: a framework for writing and solving ODE systems, a library of battery models and parameters, and specialised experiment and visualisation tools. Calling it a digital twin overstates it, since a digital twin needs additional online and assimilation layers.
- Model assembly. Models are composed in Python code through
Symbolexpression trees, making model structure programmable data. The earlier claim of automatic assembly from configuration files does not match the current public API.
- Model family. The public API documentation lists SPM, SPMe and DFN. The earlier entry is consistent here.
- Solvers. The recommended and default solver is
IDAKLUSolver, a SUNDIALS wrapper whose C/C++ implementation moved to the standalonepybammsolverspackage at 25.1, making the main package pure Python. An optional jax solver exists, requiringjax >=0.7.0, <0.9.0.
- Modelling options. Behaviour is switched through
BatteryModelOptions, covering particle diffusion form, particle mechanics, particle phases, shape and size distribution, SEI with film resistance, cracks and porosity change, stress-induced diffusion, surface form, ambient temperature form, four thermal tiers, whether total interfacial current density is a state variable, and a transport efficiency family.
- Degradation submodels. SEI options run from none and constant through the reaction-limited, diffusion-limited and migration-limited families to VonKolzenberg2020 and tunnelling limited; plating offers no_plating, plating and total_lithium_plating; OCP adds single-state, MSMR, hysteresis, differential capacity hysteresis and current sigmoid forms.
- Parameter sets. Bundled lithium-ion sets include Ai2020, Bonkile2024, Chen2020, Chen2020_composite, Ecker2015, Ecker2015_graphite_halfcell, Marquis2019, Mohtat2020, NCA_Kim2011, OKane2022, ORegan2022, Prada2013, Ramadass2004, Xu2019 and MSMR_example_set, with third-party sets registered through the
pybamm_parameter_setsentry point.
- Model zoo. Community and partner models ship separately via
pip install pybamm-model-zoo, which means version compatibility with core models must be checked by the user.
- Version policy. PyBaMM uses CalVer with the form
YY.MM.N.P, whereYY.MMis year and month,Ncounts feature releases within the month starting at zero, andPis the patch level. There is no fixed release schedule. Public API removals and renames ship aDeprecationWarningfor at least two prior feature releases. Breaking changes target the first feature release of a month and appear under a## Breaking changesheading at the top ofCHANGELOG.md; later feature releases in the same month should not contain them, and where genuinely necessary the rationale and a standard deprecation note must appear in both the pull request and the changelog. Patch releases contain only fixes. The README's simplified statement that any release may contain breaking changes is expanded inRELEASE.md.
- Definition of public API. The release policy defines public API as anything documented on docs.pybamm.org. Internal modules, underscore-prefixed names and undocumented helpers are private and may change between any two versions, so the practical test for interface stability is whether a symbol appears in the rendered API reference index.
- Version availability. The README notes that versions between 24.11.2 and 25.6, excluding those boundaries, are not available on conda-forge.
- Platforms and installation. GNU/Linux, macOS and Windows are supported, through pip and conda-forge, where conda splits into
pybamm-basefor required dependencies andpybammfor everything except jax.
- Citation. The base citation is Sulzer V., Marquis S. G., Timms R., Robinson M. and Chapman S. J. (2021), Journal of Open Research Software, 9(1), DOI 10.5334/jors.309;
pybamm.print_citations()prints BibTeX; the full list sits inpackages/pybamm/src/pybamm/CITATIONS.bib; the README notes heavy reliance on CasADi.
- Governance and funding. PyBaMM uses an open governance model and is fiscally sponsored by NumFOCUS.
- Licence. The repository LICENSE.txt is the three-clause BSD licence, with the copyright line reading Copyright (c) 2018, the PyBaMM team; the README describes the project as fully open source.
- Year. The earlier entry recorded 2019; this entry uses 2021 following the citation paper, while the licence copyright year is 2018.
- Volatile numbers. The star count in parentheses is a snapshot of repository popularity and would expire, so it is removed. Such indicators do not belong in permanent entry text.
- Telemetry. PyBaMM collects anonymous usage data by default, covering version, Python version and which functions run, and can be disabled through
PYBAMM_DISABLE_TELEMETRYorpybamm.telemetry.disable().
- Absence of an official benchmark. No official accuracy leaderboard or validation dataset exists; correctness arguments are distributed across parameter-set literature, cross-model comparison and regression testing. The earlier phrase about published papers validated against commercial cell data refers to work across the ecosystem rather than an official validation suite.
For related reading see cases/physicsnemo-tcad-chip-thermal for another vertical under the same longform verification, tools/physicsnemos for the GPU-accelerated route, guides/classical-solver-cost-boundary-2026 for solver cost boundaries, and collections/numerics-and-solvers.
References
- PyBaMM project repository and README, covering framework definition, CalVer policy, installation and citation instructions, https://github.com/pybamm-team/PyBaMM
- Sulzer V., Marquis S. G., Timms R., Robinson M. and Chapman S. J., "Python Battery Mathematical Modelling (PyBaMM)", Journal of Open Research Software, 9(1), 14, 2021, DOI 10.5334/jors.309
- PyBaMM licence file LICENSE.txt, three-clause BSD with the line Copyright (c) 2018, the PyBaMM team, https://github.com/pybamm-team/PyBaMM/blob/main/LICENSE.txt
- PyBaMM user guide public API overview, covering SPM / SPMe / DFN, Simulation, ParameterValues, Experiment, IDAKLUSolver and Discretisation, https://docs.pybamm.org/en/latest/source/user_guide/fundamentals/public_api.html
- PyBaMM release policy documentation RELEASE.md, covering CalVer, breaking changes, deprecation policy and the definition of public API, https://docs.pybamm.org/en/latest/source/user_guide/release.html
- PyBaMM battery model option definitions in
base_battery_model.py, enumerating SEI, plating, particle mechanics, thermal and transport efficiency options, https://github.com/pybamm-team/PyBaMM/blob/main/packages/pybamm/src/pybamm/models/full_battery_models/base_battery_model.py - PyBaMM lithium-ion parameter set directory listing Ai2020, Bonkile2024, Chen2020, Marquis2019, Mohtat2020, OKane2022, ORegan2022, Prada2013 and Ramadass2004 among others, https://github.com/pybamm-team/PyBaMM/tree/main/packages/pybamm/src/pybamm/input/parameters/lithium_ion
- PyBaMM parameter set registration documentation describing the
pybamm_parameter_setsentry point for third-party sets, https://docs.pybamm.org/en/latest/source/api/parameters/parameter_sets.html - PyBaMM performance documentation covering the Simulation pipeline, InputParameter, solvers, output variable trimming and OpenMP parallelism, https://docs.pybamm.org/en/latest/source/examples/notebooks/performance/index.html
- PyBaMM release history on GitHub Releases, illustrating the CalVer version scheme, https://github.com/pybamm-team/PyBaMM/releases
- PyBaMM telemetry documentation describing anonymous usage data and how to disable it, https://docs.pybamm.org/en/latest/source/user_guide/index.html
- Marquis S. G., et al., "A Solver for the Doyle-Fuller-Newman Model", Journal of The Electrochemical Society, 167(1), 2020
- Murray Y., et al., "PyBaMM: Python Battery Mathematical Modelling", Journal of Open Source Software, 6(62), 2021