Generated banner for Pybamm
Generated logo for Pybamm

Pybamm

K-DenseCommunityCreated by K-Dense Inc.

  • Skill
  • Workflow
  • Science and research
  • MIT
  • Low risk
  • Has scripts

From the author

Simulates lithium-ion battery charge, discharge and rest experiments with PyBaMM, records parameter-set provenance, checks mesh and solver sensitivity, and compares predicted voltage curves with measured cycling data. Use for SPM or DFN electrochemical battery modeling, C-rate protocols, voltage cutoffs, parameter studies and numerical validation of battery simulations.
— the description by K-Dense Inc.

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured workflow for simulating single-cell lithium-ion battery experiments using PyBaMM. It supports SPM and DFN electrochemical models to simulate charge, discharge, and rest protocols. The tool automates the execution of simulations, performs numerical sensitivity analysis by comparing results across different solver tolerances and mesh resolutions, and generates detailed reports including parameter provenance and voltage curve comparisons against measured data.

What it does

  • Simulates battery charge, discharge, and rest experiments using SPM or DFN models.
  • Validates simulation protocols against defined JSON contracts.
  • Performs numerical sensitivity analysis by varying solver tolerances and mesh density.
  • Compares predicted voltage curves against user-supplied cycling data.
  • Records parameter-set provenance and simulation metadata.
  • Exports detailed reports including voltage residuals and event-time differences.

When to use it

  • When you need to model single-cell battery behavior under specific current protocols.
  • When comparing electrochemical model predictions (SPM/DFN) against experimental cycling data.
  • When performing numerical validation to ensure simulation results are independent of mesh and solver settings.
  • When you need to track parameter-set snapshots after SOC initialization.

Advantages

  • Automates the comparison between baseline, high-tolerance, and refined-mesh simulations.
  • Provides clear metrics for voltage RMSE, MAE, and bias.
  • Ensures reproducibility by snapshotting parameters after SOC initialization.
  • Strict protocol validation prevents common configuration errors.

Usage examples

“Run a simulation for a 0.5C discharge protocol using the Chen2020 parameter set.”
The tool executes the simulation, generates a baseline curve, and outputs a report including parameter snapshots and numerical validation results.
“Compare my measured cycling data in measured.csv against an SPM model prediction.”
The tool runs the SPM simulation, calculates voltage residuals against the provided CSV, and generates a measurement-residuals.csv file.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/k-dense-ai/pybamm/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip pybamm.zip -d .agents/skills

Documentation by K-Dense Inc.

PyBaMM battery experiments

When to use

Use this skill to model single-cell constant-current charge/discharge and rest, examine voltage and charge trajectories, or compare SPM/DFN predictions to cycling measurements. The helper runs real PyBaMM experiments and three numerical resolutions; it does not control a battery cycler or establish an operating envelope for hardware.

Runtime and tested case

uv venv --python 3.12 battery-env
uv pip install --python battery-env/bin/python pybamm==26.9.0.0 pybammsolvers==0.10.0

This release requires pybammsolvers>=0.10.0, NumPy 2 or newer, and CasADi 3.8.1. The tested environment used Python 3.12.10, NumPy 2.5.3 and SciPy 1.18.1. IDAKLU is the recommended solver; CasadiSolver and ScipySolver are deprecated in this release. Refer to the 26.9.0.0 manual below, since latest can describe unreleased APIs.

The included assets/chen2020-protocol.json is a synthetic isothermal 298.15-K SPM case: 80% initial SOC, discharge at 0.5C for 600 s, rest for 120 s, charge at 0.5C for 600 s. Chen2020 supplies an LG M50 parameterization with 5-Ah nominal capacity; here 0.5C means 2.5 A. This is an executable reference example, not a claim that an arbitrary user's cell has those parameters. The helper disables PyBaMM usage telemetry unless the caller has already explicitly configured that variable.

Workflow

  1. Establish the cell chemistry, geometry, nominal capacity, initial state, temperature and current-sign convention. Use an appropriate parameter set and explain its source. Distinguish a paper's fitted parameters from measurements of this particular cell. Do not transplant degradation parameters without checking their meaning and applicable conditions.

  2. Convert the requested protocol to the JSON contract in references/protocol-and-comparison.md. Positive simulation current discharges; negative current charges. Every step has a finite duration. A specified voltage cutoff can end it earlier; the report records actual termination times. C-rates use the selected set's nominal capacity. A change in that capacity changes current.

  3. Choose SPM when its reduced transport assumptions are adequate; use DFN when resolving electrolyte/electrode transport matters. The helper's tested models are isothermal and exclude aging, mechanics, plating and pack control. Increasing rate can invalidate SPM predictions even if numerical convergence is excellent.

  4. Run the helper. It validates protocol fields, rejects unknown or overridden-by-protocol parameter inputs, uses IDAKLU, and snapshots the base parameters after SOC initialization. Keep the protocol with that snapshot: experiment steps supply their own currents. Infeasible or skipped steps are errors, rather than silently presenting a partial protocol as complete.

  5. Read the two numerical comparisons separately: baseline versus tighter tolerances isolates solver error; tight tolerances on the original versus doubled mesh isolates discretization. Compare voltage differences and event-time differences against the accuracy the question needs. Refine again when these are too large; one doubling does not prove convergence.

  6. If measurements are available, check current, time origin, temperature, SOC and capacity before interpreting residuals. Supply matching seconds, volts and amps. The helper reports voltage RMSE/MAE/bias and current RMSE, preserving residuals. A small voltage error under a mismatched input current does not validate the model. This workflow compares curves; it does not claim to identify unique kinetic parameters from voltage alone.

Run and inspect

From the skill directory, point battery-env/bin/python at the environment created above:

battery-env/bin/python scripts/simulate_battery.py assets/chen2020-protocol.json \
  --output battery-reference

# measured.csv is user data with time_s,voltage_V,current_A columns.
battery-env/bin/python scripts/simulate_battery.py protocol.json \
  --measured measured.csv --mesh-points 30 --output battery-comparison

The first command was executed as written with an external output location. The second uses illustrative user filenames; the measurement path was exercised against a frozen synthetic reference curve in the tests. Output directories must be new.

ArtifactInterpretation
curve.csvBaseline time, step, voltage, current and net discharge capacity
tight-tolerance.csvSame mesh, tighter solver
refined-mesh.csvDoubled mesh with tighter solver
parameters.jsonBase parameters after SOC initialization; step currents remain in the protocol
report.jsonProtocol/checksum, package versions, parameter source, numerical comparisons and terminations
measurement-residuals.csvPrediction minus measurement and current mismatch, when measurements were supplied

The reference case conserved integrated charge: 600 s at 2.5 A yielded 0.4166667 Ah, then equal charge returned net discharge capacity to zero. Voltage stayed within the Chen2020 limits in this case. Tightening tolerances changed voltage by about 1 microvolt; doubling mesh from 20 to 40 points changed it by about 2.17 mV, so claiming sub-millivolt mesh accuracy would be unjustified. A separate real DFN test stopped at the requested 3.9-V event and verified its charge integral. Native tests also exercise charge cutoff, infeasible discharge, capacity-to-current conversion, and replay of the exported SOC-adjusted parameters without reinitializing SOC. The frozen reference is numerical regression evidence, not measured-cell validation.

Primary references

The linked release manuals, bundled helper, parameter serialization and optional DataLoader recipe in the reference were verified against PyBaMM 26.9.0.0.

Files

references/protocol-and-comparison.md

Protocol and curve contract

The helper accepts model (SPM or DFN), parameter_set (an installed PyBaMM set), initial_soc in (0,1], positive temperature_K, positive sample_period_s, a nonempty steps list, and optional numeric parameter_overrides. Unknown fields are rejected; there is no implicit cycles or repeated-cycle option. Repeat the desired steps explicitly when needed. The example set Chen2020 is tested; other sets require chemistry/geometry compatibility checks.

The root, each step and parameter_overrides must be JSON objects. Each step contains kind and positive duration_s. charge and discharge also require positive c_rate, and may contain until_voltage_V within the set's lower/upper cutoffs. rest has no rate or cutoff. A sample period cannot exceed a step's duration. For example:

{
  "kind": "discharge",
  "c_rate": 0.5,
  "duration_s": 3600,
  "until_voltage_V": 3.0
}

Current is ±C-rate times nominal Ah capacity. All duration and timestamp values are seconds; temperatures are Kelvin, never Celsius. Use temperature_K for the uniform isothermal setting; overrides of initial/ambient temperature are rejected to avoid contradictory settings. The helper is single-cell only: the series-cell count must be one. Upstream voltage step events use Battery voltage [V], while the exported Voltage [V] is cell voltage; these differ in a string of cells. Nominal capacity changes the C-rate-to-current conversion, not the electrode geometry or active material inventory. Reconcile those independently when reparameterizing a cell.

Existing scalar numeric PyBaMM parameters may be overridden; functional OCP and transport laws cannot be replaced through this helper. Current function [A] overrides and initial electrode concentration overrides are rejected because the experiment and initial_soc would replace them. Use the exact installed parameter keys (list(parameters.keys())); current upstream ParameterValues.update() permits new keys, so it is not itself a typo detector. The helper explicitly checks membership. Do not inject functions or executable code through JSON.

initial_soc sets electrode concentrations through PyBaMM's parameterization-dependent initial state solver; it is not a universal concentration multiplier or a guarantee of feasible terminal voltage under load. A discharge cutoff must lie below the loaded starting voltage; a charge cutoff must lie above it. skip_ok=False rejects an already-satisfied step condition. The helper accepts SOC in (0,1] as a deliberately narrower contract than upstream's [0,1].

parameters.json serializes simulation.parameter_values after solve(initial_soc=...), using ParameterValues.to_json(). The original parameter object still has its original concentrations and must not be mistaken for that snapshot. Load the snapshot with pybamm.ParameterValues.from_json(path); retain the protocol because each step overrides the base Current function [A]. It is a parameter snapshot, not a saved solution or a model definition.

Voltage holds (CCCV), power control, thermal dynamics and degradation are available in upstream PyBaMM but are outside this helper's tested protocol. Extend using the upstream step APIs and test against a physically appropriate case rather than translating a voltage hold into constant current.

Numerical comparisons

The baseline uses IDAKLU rtol=1e-6, atol=1e-8; the tightened run uses 1e-8, 1e-10. Both use the same mesh. The third run doubles all x_n,x_s,x_p,r_n,r_p point counts at the tightened tolerances. Only relevant spatial dimensions enter each model (SPM and DFN use different physics).

Voltage is compared at 101 positions over the shared elapsed interval of each corresponding step. This avoids interpolating across a current discontinuity. Event duration differences are reported separately because cutoff shifts change later absolute step times. Always check these alongside the voltage metric, especially near a steep end-of-discharge drop. The output period controls saved samples, not the adaptive solver's internal step size. For a duration not divisible by the period, 26.9.0.0 distributes samples uniformly over the duration using a rounded point count, so the spacing need not equal the requested period exactly. Read the actual time column. The comparisons interpolate saved samples; also reduce the output period when interpolation error could dominate.

net_discharge_capacity_Ah integrates signed current. It decreases during charging and is not cumulative charge throughput, remaining capacity, a cycle count, or measured state of health.

Measured curves

The CSV has exactly:

time_s,voltage_V,current_A
0,3.98,2.5
120,3.93,2.5
300,3.90,2.5

Require finite values and strictly increasing time. These rows are illustrative, not measured data. Convert raw instrument units and polarity explicitly upstream and retain their provenance. The helper interpolates the baseline at measurement times only inside the simulated interval; it never extrapolates. If only an overlapping segment is intended, select and document that segment upstream.

Align experiment start from acquisition evidence; do not optimize a time shift solely to improve fit unless that is an explicit fitting parameter with uncertainty. Samples right at a current switch can represent either side of an instantaneous ohmic change; align acquisition semantics and inspect the current-difference column before comparing those voltages. RMSE gives each supplied sample equal weight, so oversampling a long rest changes its contribution. Resample deliberately if a time-weighted or phase-balanced score is desired, and retain the original curve.

Report residual structure across charge, rest and discharge, not just a single score. Temperature, SOC, capacity calibration and hysteresis can dominate mismatches. Parameter fitting should compare identifiability and uncertainty against independent experiments rather than treating a lower error on the same curve as sufficient validation.

Optional upstream datasets

For a public reference dataset, PyBaMM 26.9.0.0 exposes DataLoader() with no version argument, show_registry() returning a filename list, and get_data(filename) returning a local Path. There is no fetch_data() method. The shipped loader pins the separate data release v1.0.2 and uses Pooch to cache and verify each file against its registered SHA-256 hash.

import hashlib
import pybamm

loader = pybamm.DataLoader()
filename = "Ecker_1C.csv"
assert filename in loader.show_registry()
path = loader.get_data(filename)
print(loader.version, path.name, hashlib.sha256(path.read_bytes()).hexdigest())

This recipe fetched the 1,049-byte public file and verified hash 428dc5113a6430492f430fb9e895f67d3e20f5643dc49a1cc0a922b92a5a8e01 on the review date. The network operation is an unauthenticated HTTPS GET of the release asset at https://github.com/pybamm-team/pybamm-data/releases/download/v1.0.2/Ecker_1C.csv, which may redirect to GitHub's asset storage. It returns file bytes, not a paginated JSON API. An unknown filename raises ValueError before fetching; network or checksum failures are not missing data. Do not edit loader internals to invent a dataset-version constructor option.

Ecker data concerns a Kokam cell, not the Chen2020 LG M50 example. This file has two headerless columns and lacks the helper's required current column. Check the source experiment and units before constructing a comparison CSV; downloading and hashing it does not validate a model. The bundled helper does not fetch datasets automatically.

Release contracts

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs Python

The author says: Requires Python 3.12 with PyBaMM 26.9.0.0 and pybammsolvers 0.10.0 (IDAKLU). NumPy and CasADi are supplied by PyBaMM. Network is needed for installation and optional upstream dataset retrieval; bundled simulations and CSV comparisons run locally without credentials.

Security

What our scanner noticed· Low risk

  • Instructions that use the network
  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
K-Dense Inc.
Publisher
K-Dense (Community)
Source
K-Dense-AI/scientific-agent-skills · skills/pybamm · commit a25cf9e
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE.md)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by K-Dense Inc. or K-Dense.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download pybamm.zip