PyBaMM Solver Convergence Failures: Numerics or Physics
PyBaMM Solver Convergence Failures: Numerics or Physics
Search
Ask the AI

PyBaMM Solver Convergence Failures: Numerics or Physics

For example, a long PyBaMM degradation run may fail at cycle 300 with SUNDIALS output ending in Corrector convergence failed repeatedly or with |h| = hmin. Record the last successful state, then examine numerical convergence and the model’s physical domain together.

The error reports a failure of the numerical iteration, not a diagnosis of its cause. Poor scaling, initial conditions, discontinuous inputs, an ill-conditioned Jacobian, or a state approaching the model’s domain boundary can contribute. Compare states and convergence under controlled changes before changing tolerances or the protocol.

PyBaMM battery modelling series · Silent failures, measured (part 6 of 8): Previous: PyBaMM SEI and Lithium Plating: Reaction Laws, Temperature and Pore Clogging · Next: Fitting PyBaMM Parameters: PyBOP Versions, Identifiability and Validation · Series hub: Data pipeline (5) + Silent failures, measured (8) · RSS feed.

1. What the error actually says

IDAKLU is a BDF solver: at each step it forms an implicit algebraic system and solves it with Newton iterations. The “corrector” is that Newton loop. Two things can end a step:

  • The corrector does not converge. Newton iterated up to its limit without the residual falling far enough. The solver responds by shrinking the timestep and retrying.
  • The timestep hits hmin. After repeated shrinking there is nothing left to shrink. This is what |h| = hmin means.

The solver retries a failed nonlinear solve with smaller internal timesteps. This error means that the allowed convergence-failure count or minimum-step condition was reached. A smaller maximum or initial step can still change the path into the failing state; a denser output grid is a separate setting and need not change internal integration steps.

Read the message as a failure to satisfy the nonlinear convergence test under the current settings. It does not establish that no solution exists or that every possible timestep has been tried.

2. The decision that matters: numerics or physics

Use a simpler model as a comparison. Keep parameter values, experiment, initial state, relevant degradation options and diagnostic outputs aligned, then investigate where the solutions begin to differ.

import pybamm

# params and experiment are the ones from the failing run, for example:
params = pybamm.ParameterValues("OKane2022")
experiment = pybamm.Experiment(
    [("Discharge at 1C until 2.5V", "Charge at 0.3C until 4.2V", "Hold at 4.2V until C/100")] * 100
)

# Re-run the same experiment on a simpler model. SPMe drops the spatial
# resolution of DFN but keeps electrolyte gradients, so it survives states
# that DFN cannot represent.
for cls in (pybamm.lithium_ion.SPMe, pybamm.lithium_ion.DFN):
    sim = pybamm.Simulation(cls(), parameter_values=params, experiment=experiment)
    try:
        sol = sim.solve()
    except pybamm.SolverError as exc:
        print(f"{cls.__name__}: failed at the first step - {exc}")
        continue
    print(f"{cls.__name__}: {len(sol.cycles)} of {len(experiment.cycles)} cycles, "
          f"ended on {sol.termination}")

Check completed cycles, steps, termination and logs against the requested experiment. In the recorded tests on 26.5.0 and 26.10.1.1, injecting a SolverError into step 5 of a three-cycle experiment returned 2 of 3 cycles without raising. Some failures at the start of an experiment raise; other errors, callbacks or version-specific handling may also raise. A returned solution can include an incomplete final cycle.

Read the result like this:

SPMe DFN What it means
fails too fails Physics. The parameter set drives the cell into a state neither model can represent. Solver options will not fix it.
completes fails Probably still physics, localised in what DFN resolves and SPMe averages away – most often a concentration going out of bounds somewhere in the electrode.
completes completes with different options Numerics. This is the only case where tuning the solver is the right move.

Interpretation of the comparison: the table records proposed diagnoses, but completion alone does not establish them. Both models can share a numerical difficulty; SPMe can complete because its approximation changes the equations; and a successful option change needs a convergence and state-domain check. The example above uses cls(), so it omits degradation options from a failing degradation model unless they are explicitly supplied. Its code comments about SPMe “surviving” a state describe a possible outcome, not a physical-validity test.

3. Finding the physically impossible state

Inspect quantities whose constitutive laws or geometry have restricted domains. Record both the final values and their evolution before failure:

  • Particle surface concentration approaching 0 or its maximum. For common Butler–Volmer parameterizations, the exchange current tends to zero there; a finite imposed reaction current can require a large overpotential.
  • Electrolyte concentration approaching zero or leaving the fitted range of the transport functions. Conductivity may vanish and some expressions become singular; diffusivity is not universally undefined at zero.
  • Porosity approaching zero when SEI/plating porosity-change coupling is enabled. This is one possible failure mechanism; the cycle index alone does not identify it.

Inspect the last successful segment together with solver logs. Compare spatial minima and maxima, units, parameter-function domains and event thresholds:

import numpy as np

# Solve a shorter run that succeeds, then look at how close the bounded
# variables came to their limits. A run that "worked" but approached a
# boundary is the same failure a few dozen cycles earlier.
sol = sim.solve()

for name in ("Negative particle surface concentration",
             "Positive particle surface concentration",
             "Electrolyte concentration [mol.m-3]",
             "Negative electrode porosity"):
    try:
        v = sol[name].entries
    except KeyError:
        continue          # names vary with model options; skip rather than crash the diagnostic
    print(f"{name:<44} min={np.min(v):.4g}  max={np.max(v):.4g}")

In the tested versions, the two particle-concentration names without units are dimensionless aliases. Use explicit Negative particle surface stoichiometry and Positive particle surface stoichiometry, or concentration names with [mol.m-3], and compare against the matching limits. A missing variable is unavailable, not a passing check. A trajectory near a boundary warrants investigation; it does not prove that a later failure has the same cause.

A stoichiometry of 0.999 or 0.001, a tenfold concentration decrease, or declining porosity is a diagnostic signal. Whether it invalidates the model depends on the parameter functions, event thresholds and imposed current. Check those conditions before attributing the failure to the protocol or changing it.

4. When it really is numerics: the options that exist

The following table preserves the defaults recorded on 26.5.0 and 26.10.1.1. Treat the usage column as a starting point and check the installed version’s options.

Option Default When to change it
rtol 1e-4 Constructor argument, not an option. Tightening costs time; loosening hides error.
atol 1e-6 Worth revisiting when a state variable's natural magnitude is far from 1.
max_num_steps 100000 Raise for very long experiments that end without an error but short of the requested cycles.
max_nonlinear_iterations 40 Raising it lets Newton work harder per step; helps stiff-but-solvable states, does nothing for singular ones.
max_convergence_failures 100 Raising it only postpones the same failure. Useful mainly to confirm it is not transient.
nonlinear_convergence_coefficient 0.33 Loosening the Newton acceptance threshold. Try last, and re-verify results afterwards.
max_order_bdf 5 Lowering to 2-3 can stabilise runs with sharp transitions at the cost of speed.
jacobian "sparse" Leave alone. Sparse is right for discretised battery models.
linear_solver "SUNLinSol_KLU" Leave alone unless profiling says otherwise.
num_threads 1 Raise only when solving many parameter sets; it does not speed up one solve.

Option scope: max_num_steps limits internal steps between requested output times; it is not a cycle-count limit. Inspect the actual failure flag before raising it. max_convergence_failures can help a difficult but solvable step, and its effect is not necessarily just postponement. Sparse KLU is a useful default, while supported alternatives depend on the matrix and build. num_threads controls available threads and num_solvers controls parallel solves; speed depends on the backend and workload.

The trap: option keys that silently do nothing

Before PyBaMM 26.10.0.0, a misspelt key in the IDAKLU options dictionary was accepted and ignored. {"max_nonlinear_iteration": 100}, with the final s missing, passes without a word on 26.5.0 and 26.9.0.0. You will conclude the option "did not help" when it was never applied. From 26.10.0.0 the same dictionary raises a SolverError that lists the known options.

options = {"max_nonlinear_iterations": 100, "max_order_bdf": 3}

# 26.10.0.0 and later raise on an unknown key. On older versions, check it yourself.
unknown = set(options) - set(pybamm.IDAKLUSolver().options)
assert not unknown, f"unknown IDAKLU options: {unknown}"

solver = pybamm.IDAKLUSolver(rtol=1e-6, atol=1e-8, options=options)
model = pybamm.lithium_ion.DFN()

sim = pybamm.Simulation(model, parameter_values=params,
                        experiment=experiment, solver=solver)

The model format is a smaller concern. The docstring says these options only apply when model.convert_to_format == "casadi", and IDAKLUSolver enforces that itself: it converts any other format to CasADi and logs a WARNING. On an SPM set to convert_to_format = "python", max_order_bdf=1 raised the solution from 50 to 72 time points in a 3000 s discharge, the same change as on a CasADi model, on both 26.5.0 and 26.10.1.1.

Correction, 2026-11-07: this section used to say that options on a non-CasADi model are silently ignored. That does not reproduce on 26.5.0 or 26.10.1.1: the model is converted with a WARNING and the options apply. Up to 26.9.0.0 the silent failure is the misspelt key described above.

5. Why long runs fail and short ones do not

A failure after hundreds of cycles can arise as degradation changes concentrations, geometry and conditioning. Solver scaling, events and step transitions can also become harder along that trajectory; late failure alone does not prove monotonic physical deterioration.

With the corresponding coupling enabled, SEI growth and plating can reduce porosity, while lithium-inventory and active-material loss change accessible stoichiometry and capacity. Check the enabled submodels and the actual state trajectory to identify the mechanism.

Two consequences for how you debug:

  • Use accelerated degradation as a diagnostic comparison. Change the parameter actually read by the selected law and compare the resulting failure state. In the tested "solvent-diffusion limited" law this is solvent diffusivity; SEI kinetic rate constant [m.s-1] enters the "ec reaction limited" family. An earlier failure is useful when its mechanism matches the original.
  • Record the cycle index in your failure reports. "Fails at cycle 300 of 500 with parameter set X" is diagnosable; "the simulation crashes" is not.
import pybamm

# Accelerate degradation so a cycle-300 failure reproduces inside 20 cycles.
# The goal is not a physically meaningful result - it is turning a multi-hour
# iteration loop into a multi-minute one.
params = pybamm.ParameterValues("OKane2022")
fast = params.copy()
fast["SEI solvent diffusivity [m2.s-1]"] *= 50

n_cycles = 30
sim = pybamm.Simulation(
    pybamm.lithium_ion.DFN(options={"SEI": "solvent-diffusion limited"}),
    parameter_values=fast,
    experiment=pybamm.Experiment(
        [("Discharge at 1C until 3.0V", "Charge at 1C until 4.2V", "Hold at 4.2V until C/50")] * n_cycles
    ),
)
sol = sim.solve()
if len(sol.cycles) < n_cycles:
    print(f"reproduced: stopped in cycle {len(sol.cycles)}, {sol.termination}")
else:
    print(f"completed {n_cycles} cycles - raise the multiplier further")

In the recorded 26.10.1.1 test, this run completed all 30 cycles. Multiplying the diffusivity by 50 raised lithium inventory loss from 0.036% to 0.479%; multiplying SEI kinetic rate constant [m.s-1] by 50 instead left it at 0.036%. This tests which parameter the selected SEI law reads. Further acceleration changes the model trajectory, so verify that it reproduces the original failure mechanism before using it for diagnosis.

6. A checklist, in the order worth trying

  1. Record where it failed. Cycle index, step within the cycle, and the last successful time.
  2. Re-run on SPMe. Align the relevant options and inspect the states. Shared failure narrows the comparison but still requires numerical and physical checks.
  3. Inspect bounded variables on the longest run that succeeds. Look for stoichiometry near 0 or 1, electrolyte concentration collapsing, porosity approaching zero.
  4. Check the experiment against the cell. Compare current, cutoff limits and event behavior with the degraded state and the parameter functions’ valid ranges.
  5. Test options according to the error. Examine scaling, initial consistency and timestep transitions, then test nonlinear iterations or BDF order. Before 26.10.0.0, check keys against pybamm.IDAKLUSolver().options.
  6. Re-verify the results after loosening anything. A run that completes because the acceptance threshold was relaxed is not automatically a run you can trust; compare a shorter segment against the tighter settings.

7. What to record when it works

Record the failing state and the comparison that supports the diagnosis. These details make a later failure under another parameter set easier to investigate.

The following fictional record illustrates the fields and diagnostic evidence to preserve.

Model:        DFN, options {SEI: solvent-diffusion limited, ...}
Parameters:   OKane2022, modified: SEI solvent diffusivity x 50
Experiment:   1C/1C CCCV, 500 cycles requested
Failure:      cycle 312, discharge step, t = ...
Diagnosis:    negative particle surface stoichiometry -> 0.9993
Root cause:   cutoff voltage unreachable after ~30% capacity fade
Fix:          cutoff moved to 2.8V; NOT a solver change
Solver:       IDAKLU, rtol 1e-4, atol 1e-6, defaults otherwise

The record above is a fictional format example. A stoichiometry of 0.9993 alone does not establish the stated root cause. Moving the cutoff to 2.8V changes the requested experiment; justify that change from the intended protocol and cell limits, and preserve the original failed result.

References

If the diagnosis lands on the parameters rather than the solver, continue with fitting PyBaMM parameters and identifiability.

See also: PyBaMM architecture and solver choice, on the SPM/SPMe/DFN trade-off and why IDAKLU suits long degradation runs.

Related: PyBaMM’s built-in parameter sets, measured. In the reported tests, Marquis2019’s nominal “1C” was about 0.78C relative to measured low-rate capacity, and Chen2020’s discharge capacity changed little in the tested temperature comparison.

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