Skip to main content
Callbacks let you run custom code at defined points during an experiment simulation without modifying the solver or model. They are attached to sim.solve() and invoked automatically as the solver progresses through cycles and steps.
The Callback API is experimental — the interface may change in future releases.

Built-in callbacks

LoggingCallback

Added automatically if no LoggingCallback is present in the list passed to sim.solve(). It logs progress to pybamm.logger or an optional log file:
LoggingCallback emits:
  • NOTICE on experiment start, each cycle start, each step start, and experiment end
  • WARNING when an experiment step is infeasible
  • ERROR on solver errors

CallbackList

CallbackList wraps multiple callbacks so they can be dispatched as one:
You normally do not need to construct CallbackList manually — setup_callbacks() does this for you and ensures a LoggingCallback is always present.

Callback interface

Every callback method receives a single logs dict. The table below lists each hook and the keys available in logs at that point:

Creating a custom callback

Subclass pybamm.callbacks.Callback and override whichever hooks you need. Methods that are not overridden default to pass.
save_callback.py

Using callbacks with Simulation

Pass a list of callback instances to the callbacks keyword of sim.solve():
use_callbacks.py
A LoggingCallback is inserted automatically if you do not include one, so you only need to list callbacks you actually want in addition to the default logging.

Example: early-stopping callback

The following callback raises an exception to stop the simulation if the voltage drops below a threshold mid-experiment:
early_stop_callback.py
CallbackList delegates every on_* call to each registered callback using a callback_loop_decorator. The decorator is applied automatically at class definition time by inspecting all methods that start with on_ via inspect.getmembers. This means adding a new on_custom_event method to Callback automatically becomes dispatchable through CallbackList without any changes to CallbackList itself.