EIS probes timescales associated with ohmic paths, interfacial reactions and transport. Their responses can overlap in frequency. Assign physical meaning to an intercept, arc or diffusion region against the model, operating point and measured frequency range.
Turning a Nyquist plot into usable machine learning labels requires addressing its underdetermination: very different parameter combinations produce nearly identical curves. This article covers how to break that degeneracy, and what to record so the curves still mean something six months later.
PyBaMM battery modelling series · Data pipeline (part 2 of 5): Previous: Reading PyBaMM Fast: Architecture for Battery Modeling and AI Data · Next: Generate Battery Aging and EIS AI Datasets with PyBaMM · Series hub: Data pipeline (5) + Silent failures, measured (8) · RSS feed.
1. The complex-analysis foundation
Small-signal EIS defines a linear response near a steady or sufficiently stationary operating point. Complex impedance is the ratio of voltage and current perturbations at the same frequency:
$$ Z(\omega) = \frac{\tilde{V}(\omega)}{\tilde{I}(\omega)} = Z_{re}(\omega) + j Z_{im}(\omega) $$
In an equivalent circuit model, an \(n\)-th order RC network coupled to a Warburg element \(Z_W\):
$$ Z_{ECM}(s) = R_\Omega + \sum_{k=1}^{n} \frac{R_k}{1 + s R_k C_k} + Z_W(s), \quad s = j\omega $$
Physics-driven AI needs far more than curve fitting. The features must be physically bounded quantities derived from continuum equations (concentrated solution theory, Butler-Volmer kinetics):
- High-frequency ohmic intercept \(R_\Omega\): a resistive high-frequency limit estimates series resistance in a simplified model without additional high-frequency inductance. Electrolyte, electronic paths and contacts can contribute; check the frequency range and model.
- Charge-transfer arc: its negative-imaginary peak is \(\max(-Z_{im})\), not \(-\max(Z_{im})\). An isolated ideal parallel-RC arc has peak height \(R_{ct}/2\). Overlapping processes prevent one peak from uniquely determining \(R_{ct}\) and \(C_{dl}\).
- Warburg coefficient \(\sigma_W\): in a semi-infinite diffusion approximation, this scales the frequency-dependent impedance; it is not a phase angle. Finite length and boundary conditions change the lower-frequency shape. State the Warburg form and its applicable band.
Control perturbation amplitude and check whether the response changes when amplitude changes. Larger signals can generate harmonics and amplitude dependence; the linear small-signal transfer function then does not describe the entire response.
2. Generating the frequency response in PyBaMM
First, a versioning problem that stops a lot of people: EIS used to live in a separate package, pybammeis, and has since been merged into PyBaMM core. Older tutorials write import pybammeis; PyBaMM has exposed pybamm.EISSimulation since v26.4.0. Install the wrong package or copy the wrong import and the resulting error has nothing to do with impedance, which sends you debugging in the wrong direction. The code in this article was tested on PyBaMM 26.10.1.1, 26.9.0.0 and 26.5.0.
import numpy as np
import pybamm
model = pybamm.lithium_ion.DFN(options={
"surface form": "differential", # required - see below
"particle shape": "spherical",
"SEI": "solvent-diffusion limited",
})
params = pybamm.ParameterValues("Chen2020")
eis = pybamm.EISSimulation(model, parameter_values=params)
# Log-spaced frequency vector: 1 mHz to 10 kHz
frequencies = np.logspace(-3, 4, 60)
sol = eis.solve(frequencies)
Use "surface form": "differential" to include double-layer dynamics in this model. In the original tests, omission raised ValueError on 26.5.0, 26.9.0.0 and 26.10.1.1. The "surface form": "algebraic" option ran but lacked the same dynamic arc. At 10 kHz, the original Chen2020 test on 26.10.1.1 recorded 2.75 mΩ for differential form and 45.98 mΩ for algebraic form; changing double-layer capacitance did not change the latter. The skip_surface_form_check=True option, available since 26.7.0.0, skips a check rather than adding missing dynamics.
Getting the raw impedance array out
eis.solve() returns an EISSolution. Its impedance attribute is a complex128 array with one value per frequency, and sol["Impedance [Ohm]"] returns the same array:
z = sol.impedance
nyquist_tensor = np.column_stack((frequencies, z.real, z.imag))
The original record for this model is 74.4 − 31.0j mΩ at 1 mHz and 2.75 − 0.49j mΩ at 10 kHz. These values use the stated model, parameters and default initial state. For a SOC sweep, pass initial_soc to solve. For temperature changes, update the relevant temperature parameters and functions that actually depend on temperature.
Correction, 2026-11-07: this section used to give a helper, extract_impedance(eis), that searched the simulation object for the array and raised AttributeError on PyBaMM 26.5.0 and 26.10.0.0. The array is on the object that solve() returns. The section also said a missing surface form raises nothing, and PyBaMM raises ValueError; the silent failure is the algebraic form described above. I removed a line that set SEI kinetic rate constant [m.s-1], because a solvent-diffusion limited model does not read it. Section 8 is corrected too: run_all.py has no --precision flag.
3. Identifiability: why one Nyquist plot is not enough
With several coupled physical parameters, one impedance spectrum need not identify them all uniquely. Define the variable parameters and observation conditions, then assess identifiability for that model.
For example, exchange-current density and specific surface area enter a simplified reaction-impedance scale through their product. Halving area and doubling exchange-current density can preserve that scale. Area may also change total double-layer capacitance and other processes, so the full spectrum need not remain unchanged. When using the EIS equivalent-circuit fitter, treat boundary hits as diagnostic signals alongside residuals, sensitivity and parameter correlation.
Under that parameter degeneracy, one spectrum does not uniquely identify the target mechanism. Joint spectra at several operating points can add information; inspect sensitivity and identifiability to determine which degeneracies those conditions resolve.
The sweep table’s physical interpretations depend on the selected parameter functions. Ohmic contributions can vary with concentration, SOC or temperature; a thermal sweep adds distinguishing information only when the relevant processes have effective temperature dependence. A protocol_id affects EIS only if its resulting history state reaches the linearisation.
| Sweep dimension | What it separates | Physical basis |
|---|---|---|
soc |
Thermodynamic state vs kinetic degradation | Open-circuit potential varies with intercalation fraction \(\theta\), while ohmic resistance barely moves with SOC |
temperature_c |
Processes with different activation energies | Each rate constant follows its own Arrhenius dependence, and a thermal sweep pulls them apart |
protocol_id |
Path-dependent hysteresis | DST, WLTP and similar load profiles leave different concentration-gradient histories |
Retain a grouping key for each cell’s sweep. Joint fitting or set-valued input can use information across operating points. When training on individual spectra to assess generalisation to new cells, split by cell or design so adjacent SOC points from one group do not cross training and test.
4. Validity checking with Kramers-Kronig
KK checks assess consistency with a linear, causal, stable, time-invariant response. Practical tests also depend on the frequency band, asymptotic terms and noise. A large residual calls for separating drift, nonlinearity, finite-band effects, model mismatch and numerical error; it does not directly identify a degraded operating point or an ill-conditioned Jacobian.
The preserved demonstration below uses a fixed bank of 40 RC basis functions. It returns that finite RC model’s fitting residual. Interpret its original “KK violation” comment within that limitation. The time-constant range, number of elements and missing series inductance or capacitance can change the residual. A formal Lin-KK analysis also checks underfitting, overfitting and residual structure.
import numpy as np
def linear_kk_residual(freq, z, n_rc=40):
"""Fit the spectrum with n_rc RC elements at log-spaced time constants.
An RC network always satisfies KK, so whatever cannot be fitted is the
KK violation. Returns relative residual; empirically, more than a few
percent means the spectrum is suspect."""
w = 2 * np.pi * np.asarray(freq)
taus = np.logspace(np.log10(1 / w.max()), np.log10(1 / w.min()), n_rc)
# Basis: 1/(1+jw*tau) per RC, plus a constant term for R_ohm
A = np.column_stack([1.0 / (1.0 + 1j * w[:, None] * taus), np.ones((len(w), 1))])
# Complex least squares: stack real and imaginary parts into one real system.
# Fitting them separately discards the constraint that both must come from
# the same parameter set - which is exactly what KK expresses.
A_ri = np.vstack([A.real, A.imag])
z_ri = np.concatenate([z.real, z.imag])
coef, *_ = np.linalg.lstsq(A_ri, z_ri, rcond=None)
z_fit = A @ coef
return float(np.linalg.norm(z - z_fit) / np.linalg.norm(z))
resid = linear_kk_residual(frequencies, z)
if resid > 0.02:
print(f"KK residual {resid:.3f} is high; flag this spectrum, exclude from training")
The original spectrum’s RC fitting residual was 0.0078, below the example’s 0.02 threshold. That is a screening setting for this example, not a universal acceptance limit for every model and frequency range.
This demonstration stacks real and imaginary components with shared coefficients. Lin-KK can also fit one component and check predictions of the other. Independent, unrelated coefficient sets do not establish a shared response model; shared coefficients in this construction are not the entirety of the KK relations.
5. Label schema: fields you cannot omit
For traceable training data interpreted across operating conditions, record the frequency axis, operating point, model and parameter provenance alongside Z_re and Z_im. Those fields help distinguish SOC, temperature and degradation changes.
| Field | Meaning | Why it cannot be dropped |
|---|---|---|
frequency_hz |
Frequency sample points | The impedance tensor must align strictly with the frequency axis; samples on different grids cannot be mixed directly |
z_re, z_im |
Real and imaginary impedance | Forms the Nyquist and Bode features |
soc, temperature_c |
Operating point | Separates degradation effects from thermodynamic state effects — see section 3 |
model_name, parameter_set |
DFN/SPMe/SPM and parameter provenance | Spectra from different physical models must never be conflated |
lli, lam_neg, lam_pos, soh |
Degradation labels | Supervision targets; the two electrodes’ LAM must stay separate |
solver_status |
Whether the solver converged | Stops failed samples from being read as real physical responses |
kk_residual |
Linear KK test residual | Quantifies validity so downstream can filter by threshold instead of all-or-nothing |
sweep_id |
Grouping key for one cell’s sweep set | The basis for group splitting, and the unit that breaks parameter degeneracy |
6. Three anomalies to check every time
Scan for these after every generation run. None of them raises an exception:
- Negative real part: check the sign convention, operating point, expected passivity, convergence and numerical settings. A passive model has non-negative real impedance, but a negative value alone does not establish a numerical artefact. Preserve and flag it for investigation rather than taking its absolute value.
- Low-frequency anomalies: inspect solver status, neighbouring frequencies and repeat computations. Refine the frequency grid or numerical settings. A spike is a diagnostic signal, not proof of solver failure or evidence that a physical model response can be excluded.
- Repeat runs disagreeing: fix versions, parameters, initial state, solver settings and backend, then compare with specified absolute and relative tolerances. Cross-platform or parallel floating-point results need not be bit-identical. Investigate differences beyond tolerance and record their extent.
7. Splitting and leakage
When the target is generalisation to new cells or designs, keep adjacent operating points from one degradation trajectory out of opposing train/test partitions. Local interpolation can otherwise make the assessment optimistic. The example splits by sweep_id or cell_design_id:
from sklearn.model_selection import GroupShuffleSplit
splitter = GroupShuffleSplit(test_size=0.2, random_state=42)
train_idx, test_idx = next(splitter.split(X, y, groups=sweep_id))
# Assert it in the pipeline
assert not (set(sweep_id[train_idx]) & set(sweep_id[test_idx])), "group leak"
8. Generation pipeline
cd pybamm-ai-data-lab
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
python src/run_all.py --backend pybamm
This command runs on 26.10.1.1 and produces 24 samples by default. PyBaMM returns impedance as complex128, so the script has no precision setting. Its EIS step calls EISSimulation(model) with the model’s default parameters for every row, so parameter_set, soc and temperature_c in the manifest do not reach the solve. Use its spectra to test the schema; for training data, pass your own parameter_values and initial_soc to the code in section 2.
Keep separate provenance and status for failed solves, surrogates and imputed values. A solver failure can arise from the model, parameters, initial state or numerical settings; it does not automatically identify a physical state. If a study uses multi-fidelity or imputed data, record its method and validation rather than labelling it as a successful physics solve.
References
- PyBaMM EIS Simulation DAE Solvers
- pybamm-eis (archived; merged into PyBaMM core)
- Physics-based battery model parametrisation from impedance data
- PyBOP: battery model optimisation and parameterisation
- impedance.py: Lin-KK validation, model order and optional series capacitance
- impedance.py validation source
The underdetermined single spectrum from section 3 is the same problem in the time domain: fitting PyBaMM parameters and identifiability covers how to tell whether an optimiser’s numbers were measured or merely fitted.
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