Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## Features

- [#1040](https://github.com/pybop-team/PyBOP/pull/1040) - Adds example scripts for validation and parameter statistics.
- [#1038](https://github.com/pybop-team/PyBOP/pull/1038) - Stores the `reason` for a `FailedSolution` and updates the `pybamm.RecommendedSolver` to return the error on failure.
- [#975](https://github.com/pybop-team/PyBOP/pull/975) - Adds coupled GITT-EIS parameterisation: `pybop.pybamm.EISSimulator` accepts a `protocol` and computes an impedance spectrum about the state reached at each acquisition time. Adds the example script `gitt_eis.py`, updates `pybop.plot.nyquist` for subplots, and adds `equal_aspect` to the plotting backends.
- [#1007](https://github.com/pybop-team/PyBOP/pull/1007) - Adds example script for discharge rate parameterisation.
Expand Down
Binary file modified examples/data/LG M50 Synthetic/Full cell/C02/GITT.parquet
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
12 changes: 6 additions & 6 deletions examples/data/LG M50 Synthetic/Full cell/C02/metadata.json
Original file line number Diff line number Diff line change
Expand Up @@ -411,8 +411,8 @@
},
"cycle_info": []
},
"Validation different SOC": {
"lf": "Validation different SOC.parquet",
"Validation pulses discharge": {
"lf": "Validation pulses discharge.parquet",
"info": {
"Name": "LG M50 Synthetic C02",
"Cell type": "LG M50 Synthetic",
Expand Down Expand Up @@ -517,7 +517,7 @@
],
"Cycles": []
},
"Validation different SOC": {
"Validation pulses discharge": {
"Steps": [
5,
6,
Expand Down Expand Up @@ -577,8 +577,8 @@
},
"cycle_info": []
},
"Validation pulses": {
"lf": "Validation pulses.parquet",
"Validation pulses charge": {
"lf": "Validation pulses charge.parquet",
"info": {
"Name": "LG M50 Synthetic C02",
"Cell type": "LG M50 Synthetic",
Expand Down Expand Up @@ -668,7 +668,7 @@
],
"Cycles": []
},
"Validation pulses": {
"Validation pulses charge": {
"Steps": [
2,
3,
Expand Down
Binary file modified examples/data/LG M50 Synthetic/Full cell/C02/pOCV.parquet
Binary file not shown.
Binary file modified examples/data/LG M50 Synthetic/Full cell/EIS/EIS charge.parquet
Binary file not shown.
Binary file not shown.
Binary file not shown.
27 changes: 11 additions & 16 deletions examples/scripts/dfn_parameterisation/2_electrode_ocps.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,10 @@

# Prepare a plot
fig, ax = plt.subplots(1, 2, figsize=(5, 3), dpi=300)
fig.suptitle(cell_type)
ax[0].set_ylabel("Voltage [V]")
for i in range(2):
ax[i].set_xlabel("State of lithiation")
ax[i].set_xlabel("Stoichiometry")
ax[0].xaxis.set_inverted(True)

# Prepare a plot for validation
Expand Down Expand Up @@ -90,7 +91,7 @@
label=f"{electrode}",
)

# Define initial state of lithiation and direction
# Define initial stoichiometry and direction
if "Positive" in electrode:
# Starts fully lithiated and then delithiates
direction_order = ["charge", "discharge"]
Expand Down Expand Up @@ -147,26 +148,20 @@
Q_th = Q_meas / (1.0 - 2 * margin)
Q_scale = Q_th * DE

# Define state of lithiation
dataset["State of lithiation"] = x0 + charge_throughput / Q_scale
# Define stoichiometry (between [margin, 1-margin] state of lithiation)
dataset["Stoichiometry"] = x0 + charge_throughput / Q_scale

if direction == "charge":
assert (
dataset["State of lithiation"][0]
>= dataset["State of lithiation"][-1]
)
assert dataset["Stoichiometry"][0] >= dataset["Stoichiometry"][-1]
ocp_branch = pybop.Interpolant(
np.flipud(dataset["State of lithiation"]),
np.flipud(dataset["Stoichiometry"]),
np.flipud(dataset["Voltage [V]"]),
name="pOCP charge branch",
)
else:
assert (
dataset["State of lithiation"][0]
<= dataset["State of lithiation"][-1]
)
assert dataset["Stoichiometry"][0] <= dataset["Stoichiometry"][-1]
ocp_branch = pybop.Interpolant(
dataset["State of lithiation"],
dataset["Stoichiometry"],
dataset["Voltage [V]"],
name="pOCP discharge branch",
)
Expand All @@ -175,7 +170,7 @@
sol = np.linspace(margin, 1.0 - margin, 501)
colour = "tab:red" if direction == "charge" else "tab:blue"
ax[i].scatter(
dataset["State of lithiation"],
dataset["Stoichiometry"],
dataset["Voltage [V]"],
marker=".",
s=4,
Expand Down Expand Up @@ -210,7 +205,7 @@
with open(cell_path / f"params_{full_cell_direction}.pickle", "wb") as file:
pickle.dump(param, file)

ax[i].title.set_text(electrode)
ax[i].set_title(electrode, y=1.01, va="top", fontsize="small")
ax[i].legend()

fig.savefig(cell_path / f"{cell_label}_electrode_pOCPs.png")
Expand Down
6 changes: 3 additions & 3 deletions examples/scripts/dfn_parameterisation/3_cell_balancing.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def solve_batch(self, inputs, calculate_sensitivities: bool = False):
voltage_offset = Rc * self.input_data
voltage = positive_voltage - negative_voltage - voltage_offset

sol = pybop.Solution()
sol = pybop.Solution(inputs)
sol.set_solution_variable(
"Positive electrode voltage [V]", data=positive_voltage
)
Expand All @@ -111,8 +111,8 @@ def solve_batch(self, inputs, calculate_sensitivities: bool = False):

"""
Perform balancing by fitting electrode pOCP interpolants to the full-cell pOCV function.
Allow different shift values since pOCV is really a function of surface, not average
state of lithiation.
Allow different shift values since pOCV is really a function of the surface, not average,
electrode stoichiometry.
"""

# Define parameters that are shared between charge and discharge branches
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@

# Plot the given OCV
fig_v, ax_v = plt.subplots(1, 1, figsize=(5, 3), dpi=300)
ax_v.set_title(cell_type)
ax_v.set_xlabel("State of charge")
ax_v.set_ylabel("Voltage [V]")
soc = np.linspace(0, 1, 501)
Expand Down
3 changes: 2 additions & 1 deletion examples/scripts/dfn_parameterisation/5_fit_resistances.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def solve_batch(self, inputs, calculate_sensitivities: bool = False):
1 + R1 * Q1 * np.asarray(1j * 2 * np.pi * f_eval, np.complex128) ** a1
)

sol = pybop.Solution()
sol = pybop.Solution(inputs)
sol.set_solution_variable(
"Impedance [Ohm]", data=np.asarray(Z, dtype=np.complex128)
)
Expand Down Expand Up @@ -140,6 +140,7 @@ def solve_batch(self, inputs, calculate_sensitivities: bool = False):
ax.set_title(f"{cell_type}, Nyquist plot")
ax.set_xlabel(r"Re(Z) [m$\Omega$]")
ax.set_ylabel(r"-Im(Z) [m$\Omega$]")
ax.yaxis.set_label_coords(-0.1, 0.5)
colourmap = colormaps["viridis"].resampled(N_SOC)

# Define shared parameters
Expand Down
5 changes: 2 additions & 3 deletions examples/scripts/dfn_parameterisation/5b_charge_transfer.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def solve_batch(self, inputs, calculate_sensitivities: bool = False):
Rct_typ, 2 * j0, out=np.full_like(j0, np.inf), where=j0 != 0
)

sol = pybop.Solution()
sol = pybop.Solution(inputs)
sol.set_solution_variable("Dimensionless exchange rate", data=j0)
sol.set_solution_variable("Charge transfer resistance [Ohm]", data=Rct)
solutions.append(sol)
Expand Down Expand Up @@ -184,7 +184,6 @@ def solve_batch(self, inputs, calculate_sensitivities: bool = False):

# Update and save parameters
other_electrode = "Positive" if dominant_electrode == "Negative" else "Negative"
zero = np.finfo(np.float64).eps # almost zero
param.update(
{
"Typical charge transfer resistance [Ohm]": Rct_typ,
Expand All @@ -201,7 +200,7 @@ def solve_batch(self, inputs, calculate_sensitivities: bool = False):
other_electrode + " electrode dimensionless exchange rate": (
BaseGroupedModel.symmetric_butler_volmer
),
other_electrode + " electrode capacitance [F]": zero,
other_electrode + " electrode capacitance [F]": 0,
"Charge transfer resistance RMSE [mOhm]": result.best_cost,
"Charge transfer resistance max. error [mOhm]": np.max(
np.abs(Rct_fit - Rct_values) * 1e3
Expand Down
18 changes: 7 additions & 11 deletions examples/scripts/dfn_parameterisation/6_discharge_diffusion.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,11 @@
maxiter = 500

# Set up model
model = pybop.lithium_ion.GroupedSPM() # no electrolyte effects
model_options = {"surface form": "negative differential"}
model = pybop.lithium_ion.GroupedSPM(options=model_options) # no electrolyte effects
x_variable = "Time [h]" # "Discharge capacity [A.h]"
output_variables = ["Time [s]", "Voltage [V]", "Discharge capacity [A.h]"]
model.events = [e for e in model.events if e.name != "Maximum voltage [V]"]
solver = pybop.pybamm.RecommendedSolver(options={"silence_sundials_errors": True})


for cell in get_cells():
Expand Down Expand Up @@ -141,7 +141,6 @@
parameter_values=model_param,
protocol=(input_data["Time [s]"], dataset["Time [s]"]),
remove_voltage_events=False,
solver=solver,
)
cost = pybop.RootMeanSquaredError(
dataset, target="Voltage [V]", weighting="domain"
Expand All @@ -157,6 +156,7 @@
print(result)
inputs = result.best_inputs

sum_squared_error_mV2, domain_length = 0, 0
for i, (rate, problem) in enumerate(zip(rates, problems, strict=False)):
problem.simulator.set_output_variables(output_variables)
solution = problem.simulate(inputs=inputs)
Expand All @@ -168,20 +168,16 @@
ax.plot(x, y, linewidth=1, color="black", label=label)

# Evaluate the error
squared_error_mV2.append(
((solution["Voltage [V]"].data - problem.target_data["Voltage [V]"]) * 1e3)
** 2
)
rmse_mV = np.sqrt(np.mean(squared_error_mV2[-1]))
rmse_mV = problem.cost.evaluate(solution).values.item() * 1e3
sum_squared_error_mV2 += rmse_mV**2 * len(problem.domain_data)
domain_length += len(problem.domain_data)
print(rate, "discharge RMSE [mV]:", rmse_mV)

ax.set_title(cell_type)
ax.legend(loc="best", bbox_to_anchor=(0.5, 0.0, 0.5, 1.0))

# Average error over all discharges
squared_error_mV2 = np.concatenate(squared_error_mV2)
rmse_mV = np.sqrt(np.mean(squared_error_mV2))

rmse_mV = np.sqrt(sum_squared_error_mV2 / domain_length)
print("Mean discharge RMSE [mV]:", rmse_mV)

# Update and save parameters
Expand Down
151 changes: 151 additions & 0 deletions examples/scripts/dfn_parameterisation/8_validation_pulses.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
import argparse
import pickle
from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np
import pybamm
import scienceplots # noqa: F401

import pybop
from pybop.applications.utils import (
downsample,
filter_with_preceding_row,
get_cells,
)

"""
Our data is stored in this folder structure:
examples/data
- {Battery type}
- {Cell type}
- {Cell_number}
- {Procedure}.parquet
- metadata.json

We ran pulse experiments for validation (not used for fitting) in the charge
and discharge directions.

For each full-cell, simulate the experiment and compare to the data.
"""

parser = argparse.ArgumentParser()
parser.add_argument("--draft", action="store_true", help="Draft mode")
parser.add_argument("--show-plots", action="store_true", help="Show plots")
args = parser.parse_args()

plt.style.use("science")

if args.draft:
plt.rcParams.update({"text.usetex": False})

# Set up model
model_options = {"surface form": "negative differential"}
model = pybop.lithium_ion.GroupedSPM(options=model_options)
x_variable = "Discharge capacity [A.h]" # "Time [h]"
output_variables = ["Time [s]", "Voltage [V]", "Discharge capacity [A.h]"]

for cell in get_cells():
cell_label = cell.info["Cell label"]
cell_type = cell.info["Cell type"]
cell_path = Path(__file__).parent / "results" / cell_type / cell_label
print("\n", cell_type, cell_label)

""" Plot every validation experiment versus simulation. """
for direction, init_dod in zip(["discharge", "charge"], [0.1, 1.0], strict=False):
procedure = cell.procedure["Validation pulses " + direction]
experiment_name = procedure.experiment_names[-1]
cycle_info = procedure.experiment(experiment_name).cycle_info
N_cycles = 1 if cycle_info == [] else cycle_info[0][-1]

# Get the data
dataset = pybop.import_pyprobe_result(
filter_with_preceding_row(
procedure, experiment=experiment_name, cycle=range(N_cycles)
)
)
initial_capacity = dataset["Discharge capacity [A.h]"][0]
dataset["Discharge capacity [A.h]"] = (
dataset["Discharge capacity [A.h]"] - initial_capacity
)
dataset["Time [s]"] -= dataset["Time [s]"][0]
if direction == "charge" and x_variable == "Discharge capacity [A.h]":
x_variable = "Charge capacity [A.h]"
dataset[x_variable] = -dataset["Discharge capacity [A.h]"]

# Plot the data
fig, ax = plt.subplots(1, 1, figsize=(5, 3), dpi=300)
ax.set_xlabel(x_variable.replace("capacity [A.h]", "throughput [A.h]"))
ax.set_ylabel("Voltage [V]")
x_data = dataset[x_variable]
x, y = downsample(x_data, dataset["Voltage [V]"], tol_x=np.max(x_data) / 500)
ax.plot(x, y, ls=":", linewidth=1.4, color="tab:green", label="Data")

""" Validate per direction for now. Later decide how to deal with hysteresis """
other_direction = "discharge" if direction == "charge" else "charge"

# Load the extra parameters and then update with the desired direction
with open(cell_path / f"params_{other_direction}.pickle", "rb") as file:
other_param = pickle.load(file)
model_param = pybamm.ParameterValues(other_param.copy())
with open(cell_path / f"params_{direction}.pickle", "rb") as file:
param = pickle.load(file)
model_param.update(pybamm.ParameterValues(param))

# Without electrolyte parameters, use series resistance directly
if isinstance(model, pybop.lithium_ion.GroupedSPM):
model_param["Series resistance [Ohm]"] = model_param[
"Series resistance (ECM) [Ohm]"
]

# Define protocol for each cycle
model_param["Initial SoC"] = (
1.0
- init_dod
* model_param["Nominal cell capacity [A.h]"]
/ model_param["Measured cell capacity [A.h]"]
)
input_data = pybop.generate_consistent_current(dataset, tolerance=1e-3)
input_data = pybop.downsample_constant_current(
input_data, tolerance=model_param["Nominal cell capacity [A.h]"] / 100
)
print(f"Downsampled {len(dataset)} to {len(input_data)} points")
model_param["Current function [A]"] = pybop.Interpolant(
input_data["Time [s]"], input_data["Current [A]"], name="Current function"
)

# Run a simulation
simulator = pybop.pybamm.Simulator(
model,
parameter_values=model_param,
protocol=(input_data["Time [s]"], dataset["Time [s]"]),
output_variables=output_variables,
)
solution = simulator.solve()
if x_variable == "Charge capacity [A.h]":
x_data = -solution["Discharge capacity [A.h]"].data
else:
x_data = solution[x_variable].data
x, y = downsample(
x_data, solution["Voltage [V]"].data, tol_x=np.max(x_data) / 500
)
ax.plot(x, y, linewidth=0.7, color="black", alpha=0.8, label="Simulation")

# Evaluate the error
cost = pybop.RootMeanSquaredError(dataset, weighting="domain")
rmse_mV = cost.evaluate(solution).values.item() * 1e3

ax.set_title(cell_type)
ax.legend()
print(experiment_name, "RMSE [mV]:", rmse_mV)

# Update and save parameters
param.update({"Validation RMSE [mV]": rmse_mV})
with open(cell_path / f"params_{direction}.pickle", "wb") as file:
pickle.dump(param, file)

fig.savefig(cell_path / f"{cell_label}_validation_{direction}.png")

if args.show_plots:
plt.show()
plt.close()
Loading
Loading