Using callbacks in objectives

This notebook explains how to use a callback in an objective function. For details on the Callback class, see the API reference. Potential use cases for this are:

  • Plotting some outputs at each iteration of the optimization

  • Saving internal variables to plot once the optimization is complete

Some objectives have “internal callbacks” which are not intended to be user facing. These are standard callbacks that can be used to plot the results of an optimization by using DataFit.plot_fit_results(). For user-facing callbacks, users should create their own callback objects and call them directly for plotting, as demonstrated in this notebook.

Creating a custom callback

To implement a custom callback, create a class that inherits from iwp.callbacks.Callback and calls some specific functions. See the documentation for iwp.callbacks.Callback for more information on the available functions and their expected inputs.

import ionworkspipeline as iwp
import matplotlib.pyplot as plt
import pybamm
import numpy as np
import pandas as pd

class MyCallback(iwp.callbacks.Callback):
    def __init__(self):
        super().__init__()
        # Implement our own iteration counter
        self.iter = 0

    def on_objective_build(self, logs):
        self.data_ = logs["data"]

    def on_run_iteration(self, logs):
        # Print some information at each iteration
        inputs = logs["inputs"]
        V_model = logs["outputs"]["Voltage [V]"]
        V_data = self.data_["Voltage [V]"]

        # calculate RMSE, note this is not necessarily the cost function used in the optimization
        rmse = np.sqrt(np.nanmean((V_model - V_data) ** 2))

        print(f"Iteration: {self.iter}, Inputs: {inputs}, RMSE: {rmse}")
        self.iter += 1

    def on_datafit_finish(self, logs):
        self.fit_results_ = logs

    def plot_fit_results(self):
        """
        Plot the fit results.
        """
        data = self.data_
        fit = self.fit_results_["outputs"]

        fit_results = {
            "data": (data["Time [s]"], data["Voltage [V]"]),
            "fit": (fit["Time [s]"], fit["Voltage [V]"]),
        }

        markers = {"data": "o", "fit": "--"}
        colors = {"data": "k", "fit": "tab:red"}
        fig, ax = plt.subplots()
        for name, (t, V) in fit_results.items():
            ax.plot(
                t,
                V,
                markers[name],
                label=name,
                color=colors[name],
                mfc="none",
                linewidth=2,
            )
        ax.grid(alpha=0.5)
        ax.set_xlabel("Time [s]")
        ax.set_ylabel("Voltage [V]")
        ax.legend()

        return fig, ax

To use this callback, we generate synthetic data for a current-driven experiment and fit a SPM using the CurrentDriven objective.

model = pybamm.lithium_ion.SPM()
parameter_values = iwp.ParameterValues("Chen2020")
t = np.linspace(0, 3600, 1000)
sim = iwp.Simulation(model, parameter_values=parameter_values, t_eval=t, t_interp=t)
sim.solve()
data = pd.DataFrame(
    {x: sim.solution[x].entries for x in ["Time [s]", "Current [A]", "Voltage [V]"]}
)

# In this example we just fit the diffusivity in the positive electrode
parameters = {
    "Positive particle diffusivity [m2.s-1]": iwp.Parameter("D_s", initial_value=1e-15),
}

# Create the callback
callback = MyCallback()
objective = iwp.objectives.CurrentDriven(
    data, options={"model": model}, callbacks=callback
)
current_driven = iwp.DataFit(objective, parameters=parameters)

# make sure we're not accidentally initializing with the correct values by passing
# them in
params_for_pipeline = {k: v for k, v in parameter_values.items() if k not in parameters}

results = current_driven.run(params_for_pipeline)
Iteration: 0, Inputs: {'D_s': 1.0}, RMSE: 0.1590962387090109
Iteration: 1, Inputs: {'D_s': 1.0}, RMSE: 0.1590962387090109
Iteration: 2, Inputs: {'D_s': 2.0}, RMSE: 0.06447715147449944
Iteration: 3, Inputs: {'D_s': 0.0}, RMSE: 9999999996.444777
Iteration: 4, Inputs: {'D_s': 1.5000000000000013}, RMSE: 0.10181491874615002
Iteration: 5, Inputs: {'D_s': 2.25}, RMSE: 0.05119216091393636
Iteration: 6, Inputs: {'D_s': 2.5}, RMSE: 0.04021364194061269
Iteration: 7, Inputs: {'D_s': 2.6}, RMSE: 0.036324441831389415
Iteration: 8, Inputs: {'D_s': 2.5}, RMSE: 0.04021364194061269
Iteration: 9, Inputs: {'D_s': 2.7}, RMSE: 0.03267971456004004
Iteration: 10, Inputs: {'D_s': 2.8000000000000003}, RMSE: 0.029260996684282503
Iteration: 11, Inputs: {'D_s': 2.9000000000000004}, RMSE: 0.026033577239970206
Iteration: 12, Inputs: {'D_s': 3.0000000000000004}, RMSE: 0.022993913200351237
Iteration: 13, Inputs: {'D_s': 3.14142135623731}, RMSE: 0.018977865334583066
Iteration: 14, Inputs: {'D_s': 3.3414213562373103}, RMSE: 0.013801829369493753
Iteration: 15, Inputs: {'D_s': 3.4414213562373104}, RMSE: 0.011410032929099088
Iteration: 16, Inputs: {'D_s': 3.5414213562373105}, RMSE: 0.009135918891271754
Iteration: 17, Inputs: {'D_s': 3.68284271247462}, RMSE: 0.0061053596395327595
Iteration: 18, Inputs: {'D_s': 3.8255560283267496}, RMSE: 0.0032477587088833213
[IDAS ERROR]  IDASolve
  At t = 0 and h = 1e-09, the corrector convergence failed repeatedly or with |h| = hmin.
Iteration: 19, Inputs: {'D_s': 3.9255560283267497}, RMSE: 0.0013551503632840568
Iteration: 20, Inputs: {'D_s': 4.02555602832675}, RMSE: 0.00045352566294328797
Iteration: 21, Inputs: {'D_s': 4.125556028326749}, RMSE: 0.002181173029511941
Iteration: 22, Inputs: {'D_s': 4.075152555084683}, RMSE: 0.001318622201740196
Iteration: 23, Inputs: {'D_s': 4.000556028326749}, RMSE: 1.1678128258064302e-05
Iteration: 24, Inputs: {'D_s': 3.9905560283267496}, RMSE: 0.00017050656578591355
Iteration: 25, Inputs: {'D_s': 4.010556028326749}, RMSE: 0.00018746623855982566
Iteration: 26, Inputs: {'D_s': 4.005555717001819}, RMSE: 9.84879065632482e-05
Iteration: 27, Inputs: {'D_s': 3.9980560283267494}, RMSE: 3.663097469613664e-05
Iteration: 28, Inputs: {'D_s': 4.003055856720214}, RMSE: 5.410125273950375e-05
Iteration: 29, Inputs: {'D_s': 3.9995560283267495}, RMSE: 1.1757845354718266e-05
Iteration: 30, Inputs: {'D_s': 4.00155602832675}, RMSE: 2.7819954002754624e-05
Iteration: 31, Inputs: {'D_s': 4.00105602775989}, RMSE: 1.9372530825179473e-05
Iteration: 32, Inputs: {'D_s': 4.000306028326749}, RMSE: 8.76672372483199e-06
Iteration: 33, Inputs: {'D_s': 4.000058442501101}, RMSE: 7.5737564114094004e-06
Iteration: 34, Inputs: {'D_s': 4.000406028326749}, RMSE: 9.791248322393369e-06
Iteration: 35, Inputs: {'D_s': 4.000206028326749}, RMSE: 8.01487807170079e-06
Iteration: 36, Inputs: {'D_s': 4.0001060283267496}, RMSE: 7.6169465772662484e-06
Iteration: 37, Inputs: {'D_s': 4.00005878212573}, RMSE: 7.5737541880938e-06
Iteration: 38, Inputs: {'D_s': 4.0001310283267495}, RMSE: 7.679402918836147e-06
Iteration: 39, Inputs: {'D_s': 4.000118528326695}, RMSE: 7.64497033996774e-06
Iteration: 40, Inputs: {'D_s': 4.00009602832675}, RMSE: 7.599190181612186e-06
Iteration: 41, Inputs: {'D_s': 4.00008602832675}, RMSE: 7.589435239930965e-06
Iteration: 42, Inputs: {'D_s': 4.000101028326747}, RMSE: 7.607547974853362e-06
Iteration: 43, Inputs: {'D_s': 4.00009352832675}, RMSE: 7.5992338679556236e-06
Iteration: 44, Inputs: {'D_s': 4.000098528326748}, RMSE: 7.603238751789723e-06
Iteration: 45, Inputs: {'D_s': 4.00009502832675}, RMSE: 7.5976438298725375e-06
Iteration: 46, Inputs: {'D_s': 4.00009402832675}, RMSE: 7.599970856441544e-06
Iteration: 47, Inputs: {'D_s': 4.00009502832675}, RMSE: 7.5976438298725375e-06

Now we use the results to plot the fit at the end of the optimization.

_ = results.plot_fit_results()
../../../_images/1e0ebe97b03f84b2546bad2a11ac9d6c2b62307c483dc3fff8940a58ab629545.png

Cost logger

The DataFit class has an internal “cost-logger” attribute that can be used to log and visualize the cost function during optimization. This is useful for monitoring the progress of the optimization. The cost logger is a dictionary that stores the cost function value at each iteration. The cost logger can be accessed using the cost_logger attribute of the DataFit object.

By default, the cost logger tracks the cost function value. DataFit.plot_trace can be used the plot the progress at the end of the optimization.

objective = iwp.objectives.CurrentDriven(data, options={"model": model})
current_driven = iwp.DataFit(objective, parameters=parameters)
_ = current_driven.run(params_for_pipeline)
_ = current_driven.plot_trace()
[IDAS ERROR]  IDASolve
  At t = 0 and h = 1e-09, the corrector convergence failed repeatedly or with |h| = hmin.
../../../_images/760b88d0eb6f97d6ab82c48ca9885dde58c820337355e95d6145ff10a654351e.png

The cost logger can be changed by passing the cost_logger argument to the DataFit object. For example, the following example shows how to pass a cost logger that plots the cost function and parameter values every 10 seconds.

current_driven = iwp.DataFit(
    objective,
    parameters=parameters,
    cost_logger=iwp.data_fits.CostLogger(plot_every=10),
)