Generate Battery Aging and EIS AI Datasets with PyBaMM
Generate Battery Aging and EIS AI Datasets with PyBaMM
Search
Ask the AI

Generate Battery Aging and EIS AI Datasets with PyBaMM

Start a PyBaMM dataset with the model, parameter ranges, loading and temperature conditions. Record states, observables, numerical settings and solver outcomes, then check sensitivity to those choices. This separates model response, numerical error and sampling-distribution effects.

This article gives a tested PyBaMM degradation example and examines four errors in data generation. The full degradation example solves the electrochemical model; the downloadable lab tests the data schema and includes surrogate labels. Using simulated data for real cells requires parameter identification and calibration against experimental data.

Example SOH and local ECM resistance labels over cycle count
Example SOH and resistance labels from the lab’s surrogate formula, which tests the pipeline schema. Degradation curves only mean something once they are calibrated against real cycling data.

PyBaMM battery modelling series · Data pipeline (part 3 of 5): Previous: PyBaMM EIS Data Generation: Impedance Features and AI Labels · Next: Training a Battery AI Model with PyBaMM: Predicting SOH and RUL · Series hub: Data pipeline (5) + Silent failures, measured (8) · RSS feed.

1. Stating the dataset objective formally

A well-posed battery AI dataset is this set:

$$ \mathcal{D} = \{(\mathbf{x}_i, \mathbf{y}_i, \mathbf{m}_i)\}_{i=1}^N $$

The real vector \(\mathbf{x}_i \in \mathbb{R}^p\) holds voltage and protocol features; complex impedance \(Z(\omega)\) can be encoded by real and imaginary components. Labels \(\mathbf{y}_i \in \mathbb{R}^q\) are model states or quantities such as SOH, LLI and LAM derived under a stated protocol. SOH can also be estimated by capacity tests; these are not all unobservable internal states.

Metadata \(\mathbf{m}_i\) records model assumptions, parameter provenance, protocol and solver settings for traceability and comparison. It does not itself establish causality in \(f: \mathbf{x} \rightarrow \mathbf{y}\). Store it as nested records or as a separate table with reliable linking identifiers.

2. Pick the model first — it caps how much data you can generate

Model complexity and numerical settings jointly determine cost. SPM, SPMe and DFN approximate electrolyte and electrode spatial behaviour differently. Identify the mechanisms needed for the labels, then benchmark their cost under matched conditions.

Scope of the preserved model table: roughly >1C is not a universal SPM failure boundary, and error direction requires validation. DFN also has geometry, kinetics and parameter assumptions; it is not “rarely wrong” by definition. Benchmark relative cost under matched settings.

Model Physics included Relative cost When it is wrong
SPM Single particle, no electrolyte concentration gradient Lowest Above roughly 1C, electrolyte polarisation matters and voltage curves are systematically optimistic
SPMe Single particle plus electrolyte dynamics Moderate Not enough when you need reaction distribution through the electrode thickness
DFN Full Doyle-Fuller-Newman, spatially resolved electrodes Highest Rarely “wrong”, but solver failure rates climb noticeably under degradation

One option is a broad SPMe sweep followed by DFN recomputation of a selected subset. Record the model and numerical settings for each sample, compare target outputs and cost, then choose the allocation of runs.

Cost depends on mesh, cycle count, solver and hardware. The recorded timings below belong to their stated environment; the script prints elapsed time for comparison on the target machine.

3. Degradation dynamics and where the labels come from

Labels come from selected submodel states or derived quantities. For a uniform planar SEI film of fixed composition and density with no film removal, define \(j_{SEI,cons}\ge0\) as the magnitude of lithium-consuming reaction current per interface area, and \(z\) as electron equivalents per mole of SEI. Faradaic balance gives:

$$ \frac{\partial L_{SEI}}{\partial t} = \frac{M_{SEI}}{\rho_{SEI} z F} j_{SEI,cons}. $$

Here \(M_{SEI}\) is molar mass, \(\rho_{SEI}\) is density and \(F\) is Faraday’s constant. This balance explains film growth under the stated conditions. Check PyBaMM’s specific reaction location, volume inventory, changing area and crack surface separately; the selected reaction-current model supplies temperature and other kinetic dependence.

  • SOH: capacity of the current cycle over a reference capacity, \(Q_k / Q_0\). The script below uses PyBaMM’s eSOH Capacity [A.h] with cycle 1 as the reference.
  • RUL-to-80: cycles remaining to \(SOH = 0.8\) under specified future loads, temperature and capacity-test conditions. Retain censoring when a trajectory does not reach the threshold. The 50-cycle example below does not observe a true threshold lifetime.
  • LLI: loss relative to the model’s defined lithium inventory and initial reference. Interpret SEI, plating and other contributions separately; an arbitrary parasitic-current integral is not automatically the whole LLI or coulombic efficiency.
  • LAM: depends on the selected active-material-loss submodel and may be stress-, reaction- or otherwise driven. This stress-driven implementation uses stress scales and a power law, not a universal yield-strength switch. Record the electrodes separately.
  • EIS feature vector: obtained by linearising a compatible model with the relevant dynamics at the selected operating point. SPM, SPMe and DFN can all be used with suitable EIS settings.

4. A pipeline that actually runs

The preserved degradation example below was run on the listed versions. It assembles the model, cycles and labels. Its ok=True means this exception branch was not entered; compare completed cycles, termination reason and requested cycles before treating the trajectory as complete. Errors during parameter processing or other stages can also occur outside this try block.

The code comments about parameter sets and exceptions apply to the listed configuration and versions. check_already_exists=False permits new keys; confirm that sampled keys are actually read by the model. Metadata can also live in a reliably linked separate table. Temperature, overpotential and thickness dependence belongs in the selected SEI reaction-current model rather than being multiplied in unconditionally again.

import time
import pybamm

# Degradation mechanisms must be declared when the model is constructed.
# Pushing SEI parameters into ParameterValues afterwards does NOT enable
# them - this is the most common "it ran but nothing degraded" mistake.
OPTIONS = {
    "SEI": "solvent-diffusion limited",
    "SEI porosity change": "true",
    "lithium plating": "partially reversible",
    "lithium plating porosity change": "true",
    "particle mechanics": ("swelling and cracking", "swelling only"),
    "SEI on cracks": "true",
    "loss of active material": "stress-driven",
    "calculate discharge energy": "true",
}

def run_one(cycles=100, model_cls=pybamm.lithium_ion.SPMe, seed_params=None):
    model = model_cls(options=OPTIONS)

    # OKane2022 ships parameters for every degradation submodel used here.
    # With a set like Chen2020, which has no plating parameters, building
    # the model raises a KeyError. (SEI rate constants are generic examples
    # in every shipped set, OKane2022 included.)
    param = pybamm.ParameterValues("OKane2022")
    if seed_params:
        param.update(seed_params, check_already_exists=False)

    exp = pybamm.Experiment(
        [("Discharge at 1C until 2.5V", "Charge at 0.3C until 4.2V", "Hold at 4.2V until C/100")]
        * cycles
    )

    sim = pybamm.Simulation(
        model, parameter_values=param, experiment=exp,
        solver=pybamm.IDAKLUSolver(),   # already the default; named for the record
    )

    t0 = time.perf_counter()
    try:
        # calc_esoh=True (the default) computes "Capacity [A.h]". With
        # calc_esoh=False that summary variable does not exist.
        sol = sim.solve(calc_esoh=True)
    except pybamm.SolverError as exc:
        # PyBaMM raises only when the very first step fails. A later failure
        # ends the run and returns the cycles finished so far, so also compare
        # cycles_completed with cycles_requested.
        # Failed samples must be kept, not silently skipped. The boundary of
        # the usable parameter space is drawn precisely by these failures.
        return {"ok": False, "reason": str(exc)[:200], "seconds": time.perf_counter() - t0}

    elapsed = time.perf_counter() - t0
    sv = sol.summary_variables

    # SummaryVariables has no keys() and no __contains__: "name in sv" falls
    # back to integer indexing and raises KeyError. all_variables lists the names.
    def pick(*names):
        available = sv.all_variables
        for n in names:
            if n in available:
                return sv[n]
        raise KeyError(f"none of {names} present; available: {available[:12]}")

    cap = pick("Capacity [A.h]")
    return {
        "ok": True,
        "seconds": elapsed,
        "cycles_requested": cycles,
        "cycles_completed": len(cap),
        "capacity": cap,
        "soh": [c / cap[0] for c in cap],
        "lli": pick("Loss of lithium inventory [%]"),
        "lam_neg": pick("Loss of active material in negative electrode [%]"),
        "lam_pos": pick("Loss of active material in positive electrode [%]"),
        # Metadata travels with the labels. Do not put it in a separate file.
        "meta": {
            "model": model_cls.__name__,
            "param_set": "OKane2022",
            "pybamm_version": pybamm.__version__,
            "options": OPTIONS,
        },
    }

if __name__ == "__main__":
    r = run_one(cycles=50)
    if r["ok"]:
        print(f"{r['cycles_completed']} of {r['cycles_requested']} cycles in {r['seconds']:.1f}s")
        print(f"final SOH={r['soh'][-1]:.4f}  LLI={r['lli'][-1]:.2f}%  "
              f"LAM(neg)={r['lam_neg'][-1]:.2f}%  LAM(pos)={r['lam_pos'][-1]:.2f}%")
    else:
        print(f"solver failed (this is also data): {r['reason']}")

On PyBaMM 26.10.1.1, Python 3.13 and an Apple M3 this prints the lines below. PyBaMM 26.5.0 prints the same labels.

50 of 50 cycles in 15.9s
final SOH=0.9981  LLI=0.33%  LAM(neg)=0.07%  LAM(pos)=0.01%

The eSOH Capacity [A.h] here needs calc_esoh enabled. The original run delivered 4.937 A·h at 1C in cycle 1 and 4.963 A·h in cycle 2, against an eSOH capacity of 5.096 A·h. In this example the first cycle starts differently, so cycle 2 is the reference for matched delivered-charge comparisons. Other protocols need their own reference and start/end conditions; see the capacity article.

Correction, 2026-11-07: the script published here before this date crashed on PyBaMM 26.5.0 and 26.10.0.0 with KeyError: "Variable '0' is not a summary variable." at if n in sv, and its calc_esoh=False left Capacity [A.h] undefined. The script above fixes both and reports cycles_requested. An old comment called IDAKLU faster than a CasADi default; IDAKLU is the default on these versions. This section also said the repository script wraps this code in multiprocessing, and section 5 gave a wrong example of early termination. Both are corrected below.

The downloadable lab supplies a design manifest, labels, spectra, a quality report and a group-split baseline. Use the command below to inspect that workflow; its label provenance and limitations are described immediately afterwards.

cd pybamm-ai-data-lab
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

python src/run_all.py --samples 200 --workers 4 --seed 7 \
  --backend pybamm --output /tmp/pybamm-ai-dataset

This script is lighter than the code above. With --backend pybamm it solves SPM on Mohtat2020 for at most 3 cycles per sample, divides the solved capacity by the manifest’s nominal capacity, and takes LLI, LAM and RUL from a built-in surrogate formula. On 26.10.1.1 the command above finished with all 200 samples marked backend_used=pybamm, and 79 of them had SOH above 1. Use it to test the schema and the split logic. --workers is accepted, but the run is sequential. For degradation labels at scale, call run_one from your own process pool, starting at 4 workers and watching memory.

5. Four data-generation checks

Check the following signals against outputs, parameters and logs. Some cases return quietly; others raise a missing-parameter or solver error.

1. Degradation was never actually enabled

Illustrative signal: after 500 cycles, SOH remains near 0.999. This is not the preceding 50-cycle result and does not alone prove degradation is disabled. Check the change expected from that model, parameter set and protocol.

Cause: degradation submodels must be declared through options when the model is constructed. Building pybamm.lithium_ion.DFN() and then updating SEI parameters in ParameterValues does not switch SEI growth on — those parameters are silently ignored. Check it directly: print(model.options["SEI"]).

2. Parameter set does not match the mechanisms

Symptom: SOH collapses absurdly fast, or LLI climbs to physically impossible values.

Check that the parameter set covers and calibrates the selected mechanisms. Example SEI values in sets such as Chen2020 do not automatically represent the target cell; missing plating or cracking parameters can instead raise KeyError. OKane2022 is a starting point for this example, with each parameter’s source, cell and calibration still requiring inspection.

3. The experiment terminated early

Symptom: cycles_completed is far below what you requested, with no exception raised.

Besides explicit capacity, voltage or time termination, default step-duration exhaustion, unspecified model events and failures in later steps can end an experiment. Inspect logs and termination reasons and compare completed with requested cycles. Mark truncated trajectories rather than treating every endpoint as observed end of life.

4. Diagnose an EIS anomaly

Investigation signals include negative real impedance or an unusual high-frequency hook. Check sign, expected passivity, operating point, frequency resolution and numerical settings before assigning a cause.

Check stationarity, signal amplitude, model dynamics, linear-system conditioning and numerical error, and apply an appropriate KK consistency method. Finite frequency coverage and basis mismatch also affect residuals. Preserve anomalies with a diagnostic status; unverified responses should not be labelled successful physics solves.

6. Parameter identification: aligning synthetic data to real cells

For interpreting or predicting real cells, one calibration option minimises weighted residuals between measured voltage \(V_{exp}\) and simulated voltage \(V_{sim}(\mathbf{p})\), with validation on unused conditions. An example objective is:

$$ J(\mathbf{p}) = \sum_{k} w_k \left( V_{exp}(t_k)-V_{sim}(t_k; \mathbf{p}) \right)^2 $$

import numpy as np
import pybamm
import scipy.optimize as opt

model = pybamm.lithium_ion.SPMe()
base_param = pybamm.ParameterValues("Chen2020")

# V_exp / t_eval come from your cycler export, already aligned to one time grid
# t_eval: np.ndarray  shape (T,)
# V_exp:  np.ndarray  shape (T,)

KEYS = [
    "Negative electrode active material volume fraction",
    "Positive electrode active material volume fraction",
]
BOUNDS = [(0.4, 0.8), (0.4, 0.8)]

def objective(x):
    param = base_param.copy()          # copy, or iterations contaminate each other
    param.update(dict(zip(KEYS, x)))
    try:
        sim = pybamm.Simulation(model, parameter_values=param)
        sol = sim.solve(t_eval)
    except pybamm.SolverError:
        return 1e6                     # large penalty for non-convergent points;
                                       # raising here kills the whole optimisation
    V_sim = sol["Terminal voltage [V]"](t_eval)
    if np.isnan(V_sim).any():          # run hit a voltage event before t_eval[-1]
        return 1e6
    return float(np.sum((V_exp - V_sim) ** 2))

res = opt.minimize(
    objective,
    x0=[base_param[k] for k in KEYS],
    method="L-BFGS-B",
    bounds=BOUNDS,
)
print(res.x, res.fun)

This example uses copy() to isolate trial parameters and returns a penalty for solver failure or NaN after a cut-off. Supply finite, aligned t_eval and V_exp and choose a penalty against the objective scale. In the original 26.10.1.1 test, early termination produced NaN and L-BFGS-B returned its start with a NaN objective. The guard was added on 2026-11-07.

Calibration and independent validation determine whether synthetic distributions serve a real-cell task. PyBOP organises costs and optimisation; the official pybamm-param README directs new users to PyBOP. Check APIs for the installed version.

7. Split by trajectory and design

For generalisation to new cells or designs, group trajectories and designs during splitting. Randomly scattering cycles 10, 50 and 100 from one trajectory across train and test can reward local interpolation. Forecasting later states of the same trajectory is a different task that needs a time-based evaluation.

  • Choose grouping keys for the evaluation target, such as cell_design_id or explicitly separated parameter regions, and check whether closely related designs still cross the split.
  • For whole-spectrum features or new-cell generalisation, group frequencies from the same spectrum together. Frequency interpolation is a separate valid task; report it as such instead of treating its accuracy as new-cell generalisation.
  • Assert it after splitting: no cell_design_id in the test set may appear in training. Putting that assertion in the pipeline is far cheaper than discovering suspiciously good metrics later.

8. Quality gates for dataset generation

At scale, sample count matters far less than whether each batch clears the physical, numerical and machine-learning gates.

Interpret the quality table against the protocol and study target. A valid short-term or control sample need not show measurable SOH fade. Retain provenance for failures, anomalous spectra and censored trajectories; their use in a training task needs an explicit design rather than a blanket nonphysical label.

Gate What is checked Pass condition On failure
Parameter sampling Ranges, correlations, LHS coverage, share of pathological combinations Covers the main physical dimensions without producing non-physical states Narrow the bounds, or label the pathological region as OOD
Degradation active Whether final SOH, LLI and LAM moved from their initial values Measurable SOH fade, of a magnitude consistent with the protocol Check model.options against the parameter set
Solver convergence SUNDIALS/CasADi status, step count, tolerance, failure exceptions Retained samples carry a success flag and stable step statistics Drop failed samples but keep the failing parameters to map the boundary
Trajectory completeness Ratio of cycles_completed to requested cycles Early-terminated samples are explicitly flagged Group them separately; do not mix with complete trajectories
EIS sanity Nyquist shape, high-frequency intercept, Warburg tail, KK consistency Spectrum is consistent with model assumptions and frequency grid Flag as numerical artefact, exclude from supervised training
Split strategy Whether cell_design_id, protocol_id or parameter clusters leak across splits Test set comes from physically isolated designs or protocols Rebuild the split; never scatter one trajectory randomly

9. Closing the gap to real cells

Synthetic data can support pre-training, active-learning studies and architecture ablations. Applying their conclusions to real cells also calls for:

  • Continuous calibration against differential voltage analysis (DVA) and incremental capacity analysis (ICA) from real cyclers. Both are unusually sensitive to electrode-level degradation, which makes them good probes for whether the model captured the right mechanism. To look at a curve before writing any code, the site’s dQ/dV incremental capacity analyser plots it in the browser.
  • Use global sensitivity analysis, such as Sobol indices, to inspect parameter effects, stating ranges, distributions and correlations. Unexpected results call for checking units, equations, distributions and output definitions, not changing bounds from intuition alone.
  • Record numerical failures: for example, retain failure status, parameters and diagnostics when a \(10^{-6}\) absolute tolerance is not met. Solver failure does not establish that a state is nonphysical. Do not label an unverified value as a successful simulation.

Synthetic self-consistency can conceal differences from measurements. Assess manufacturing variability, temperature fields and sensor noise for the task; introduce disturbances supported by measurements when needed, then test on independent real data. Noise injection alone does not guarantee transfer.

References

Batch generation runs into solver non-convergence more than anything else. For telling apart “tune the solver” from “fix the protocol”, see PyBaMM solver convergence failures.

Related: PyBaMM experiments that finish and are wrong — check every experiment actually completed before it becomes a training sample: slow steps in amps are cut off silently at 24 hours. Before using PyBaMM’s capacity and loss variables as labels, see what PyBaMM’s capacity numbers actually measure.

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