Skip to content

Commit

Permalink
remove default summary variables
Browse files Browse the repository at this point in the history
  • Loading branch information
rtimms committed Apr 17, 2024
1 parent 6a3d93c commit 64ade63
Show file tree
Hide file tree
Showing 15 changed files with 19 additions and 155 deletions.
56 changes: 1 addition & 55 deletions examples/scripts/experimental_protocols/cccv.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
# Constant-current constant-voltage charge
#
import pybamm
import matplotlib.pyplot as plt

pybamm.set_logging_level("NOTICE")
experiment = pybamm.Experiment(
Expand All @@ -17,66 +16,13 @@
]
* 3
)
model = pybamm.lithium_ion.DFN({"SEI": "ec reaction limited"})
model = pybamm.lithium_ion.BasicDFN()
parameter_values = pybamm.ParameterValues("Chen2020")

sim = pybamm.Simulation(
model,
experiment=experiment,
parameter_values=parameter_values,
solver=pybamm.CasadiSolver("fast with events"),
)
sim.solve()

# Plot voltages from the discharge segments only
fig, ax = plt.subplots()
for i in range(3):
# Extract sub solutions
sol = sim.solution.cycles[i]
# Extract variables
t = sol["Time [h]"].entries
V = sol["Voltage [V]"].entries
# Plot
ax.plot(t - t[0], V, label=f"Discharge {i + 1}")
ax.set_xlabel("Time [h]")
ax.set_ylabel("Voltage [V]")
ax.set_xlim([0, t[-1] - t[0]])
ax.legend(loc="lower left")

# Save time, voltage, current, discharge capacity, temperature, and electrolyte
# concentration to csv and matlab formats
sim.solution.save_data(
"output.mat",
[
"Time [h]",
"Current [A]",
"Voltage [V]",
"Discharge capacity [A.h]",
"X-averaged cell temperature [K]",
"Electrolyte concentration [mol.m-3]",
],
to_format="matlab",
short_names={
"Time [h]": "t",
"Current [A]": "I",
"Voltage [V]": "V",
"Discharge capacity [A.h]": "Q",
"X-averaged cell temperature [K]": "T",
"Electrolyte concentration [mol.m-3]": "c_e",
},
)
# We can only save 0D variables to csv
sim.solution.save_data(
"output.csv",
[
"Time [h]",
"Current [A]",
"Voltage [V]",
"Discharge capacity [A.h]",
"X-averaged cell temperature [K]",
],
to_format="csv",
)

# Show all plots
sim.plot()
14 changes: 0 additions & 14 deletions pybamm/callbacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,20 +201,6 @@ def on_cycle_end(self, logs):
f"is below stopping capacity ({cap_stop:.3f} Ah)."
)

voltage_stop = logs["stopping conditions"]["voltage"]
if voltage_stop is not None:
min_voltage = logs["summary variables"]["Minimum voltage [V]"]
if min_voltage > voltage_stop[0]:
self.logger.notice(
f"Minimum voltage is now {min_voltage:.3f} V "
f"(will stop at {voltage_stop[0]:.3f} V)"
)
else:
self.logger.notice(
f"Stopping experiment since minimum voltage ({min_voltage:.3f} V) "
f"is below stopping voltage ({voltage_stop[0]:.3f} V)."
)

def on_experiment_end(self, logs):
elapsed_time = logs["elapsed time"]
self.logger.notice(f"Finish experiment simulation, took {elapsed_time}")
Expand Down
10 changes: 6 additions & 4 deletions pybamm/experiment/experiment.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,12 +168,14 @@ def read_termination(termination):
"'80%', '4Ah', or '4A.h'"
)
elif term.endswith("V"):
end_discharge_V = term.split("V")[0]
termination_dict["voltage"] = (float(end_discharge_V), "V")
raise ValueError(
"Voltage termination at the experiment-level is no longer supported. "
"Please set voltage termination conditions at the step level."
)
else:
raise ValueError(
"Only capacity or voltage can be provided as a termination reason, "
"e.g. '80% capacity', '4 Ah capacity', or '2.5 V'"
"Only capacity can be provided as an experiment-level termination reason, "
"e.g. '80% capacity' or '4 Ah capacity'"
)
return termination_dict

Expand Down
1 change: 1 addition & 0 deletions pybamm/models/base_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ def __init__(self, name="Unnamed model"):
self._boundary_conditions = {}
self._variables_by_submodel = {}
self._variables = pybamm.FuzzyDict({})
self._summary_variables = []
self._events = []
self._concatenated_rhs = None
self._concatenated_algebraic = None
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ def set_degradation_variables(self):
}
)

def set_summary_variables(self):
def set_default_summary_variables(self):
"""
Sets the default summary variables.
"""
Expand Down
4 changes: 0 additions & 4 deletions pybamm/models/full_battery_models/lithium_ion/basic_dfn.py
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,3 @@ def __init__(self, name="Doyle-Fuller-Newman model"):
pybamm.Event("Minimum voltage [V]", voltage - param.voltage_low_cut),
pybamm.Event("Maximum voltage [V]", param.voltage_high_cut - voltage),
]
# Summary variables is a list of variables that can be accessed and plotted
# per-cycle when running experiments. Typically used to track degradation
# variables (e.g LAM, LLI, capacity fade, etc.)
self.summary_variables = ["Time [s]", "Voltage [V]"]
Original file line number Diff line number Diff line change
Expand Up @@ -403,10 +403,6 @@ def __init__(self, name="Composite graphite/silicon Doyle-Fuller-Newman model"):
pybamm.Event("Minimum voltage [V]", voltage - param.voltage_low_cut),
pybamm.Event("Maximum voltage [V]", param.voltage_high_cut - voltage),
]
# Summary variables is a list of variables that can be accessed and plotted
# per-cycle when running experiments. Typically used to track degradation
# variables (e.g LAM, LLI, capacity fade, etc.)
self.summary_variables = ["Time [s]", "Voltage [V]"]

@property
def default_parameter_values(self):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,3 @@ def __init__(self, options=None, name="Doyle-Fuller-Newman half cell model"):
"Battery voltage [V]": voltage * num_cells,
"Instantaneous power [W.m-2]": i_cell * voltage,
}
# Summary variables is a list of variables that can be accessed and plotted
# per-cycle when running experiments. Typically used to track degradation
# variables (e.g LAM, LLI, capacity fade, etc.)
self.summary_variables = ["Time [s]", "Voltage [V]"]
4 changes: 0 additions & 4 deletions pybamm/models/full_battery_models/lithium_ion/basic_spm.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,3 @@ def __init__(self, name="Single Particle Model"):
pybamm.Event("Minimum voltage [V]", V - param.voltage_low_cut),
pybamm.Event("Maximum voltage [V]", param.voltage_high_cut - V),
]
# Summary variables is a list of variables that can be accessed and plotted
# per-cycle when running experiments. Typically used to track degradation
# variables (e.g LAM, LLI, capacity fade, etc.)
self.summary_variables = ["Time [s]", "Voltage [V]"]
3 changes: 3 additions & 0 deletions pybamm/models/full_battery_models/lithium_ion/dfn.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,3 +121,6 @@ def set_electrolyte_potential_submodel(self):
self.submodels[f"{domain} surface potential difference"] = surf_model(
self.param, domain, self.options
)

def set_summary_variables(self):
self.set_default_summary_variables()
3 changes: 3 additions & 0 deletions pybamm/models/full_battery_models/lithium_ion/spm.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,3 +160,6 @@ def set_electrolyte_potential_submodel(self):
self.submodels[f"{domain} surface potential difference"] = surf_model(
self.param, domain, options=self.options
)

def set_summary_variables(self):
self.set_default_summary_variables()
10 changes: 1 addition & 9 deletions pybamm/simulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -552,9 +552,6 @@ def solve(
all_first_states = starting_solution_first_states
current_solution = starting_solution or pybamm.EmptySolution()

voltage_stop = self.experiment.termination.get("voltage")
logs["stopping conditions"] = {"voltage": voltage_stop}

idx = 0
num_cycles = len(self.experiment.cycle_lengths)
feasible = True # simulation will stop if experiment is infeasible
Expand Down Expand Up @@ -823,7 +820,7 @@ def solve(
capacity_stop = value / 100 * capacity_start
else:
capacity_stop = None
logs["stopping conditions"]["capacity"] = capacity_stop
logs["stopping conditions"] = {"capacity": capacity_stop}

logs["elapsed time"] = timer.time()
callbacks.on_cycle_end(logs)
Expand All @@ -835,11 +832,6 @@ def solve(
if not np.isnan(capacity_now) and capacity_now <= capacity_stop:
break

if voltage_stop is not None:
min_voltage = cycle_sum_vars["Minimum voltage [V]"]
if min_voltage <= voltage_stop[0]:
break

# Break if the experiment is infeasible (or errored)
if feasible is False:
break
Expand Down
28 changes: 3 additions & 25 deletions pybamm/solvers/solution.py
Original file line number Diff line number Diff line change
Expand Up @@ -934,33 +934,11 @@ def _get_cycle_summary_variables(cycle_solution, esoh_solver, user_inputs=None):
model = cycle_solution.all_models[0]
cycle_summary_variables = pybamm.FuzzyDict({})

# Measured capacity variables
if "Discharge capacity [A.h]" in model.variables:
Q = cycle_solution["Discharge capacity [A.h]"].data
min_Q, max_Q = np.min(Q), np.max(Q)

cycle_summary_variables.update(
{
"Minimum measured discharge capacity [A.h]": min_Q,
"Maximum measured discharge capacity [A.h]": max_Q,
"Measured capacity [A.h]": max_Q - min_Q,
}
)

# Voltage variables
if "Battery voltage [V]" in model.variables:
V = cycle_solution["Battery voltage [V]"].data
min_V, max_V = np.min(V), np.max(V)

cycle_summary_variables.update(
{"Minimum voltage [V]": min_V, "Maximum voltage [V]": max_V}
)

# Degradation variables
degradation_variables = model.summary_variables
# Summary variables
summary_variables = model.summary_variables
first_state = cycle_solution.first_state
last_state = cycle_solution.last_state
for var in degradation_variables:
for var in summary_variables:
data_first = first_state[var].data
data_last = last_state[var].data
cycle_summary_variables[var] = data_last[0]
Expand Down
12 changes: 0 additions & 12 deletions tests/unit/test_experiments/test_experiment.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,18 +124,6 @@ def test_termination(self):
)
self.assertEqual(experiment.termination, {"capacity": (4.1, "Ah")})

experiment = pybamm.Experiment(
["Discharge at 1 C for 20 seconds"], termination=["3V"]
)
self.assertEqual(experiment.termination, {"voltage": (3, "V")})

experiment = pybamm.Experiment(
["Discharge at 1 C for 20 seconds"], termination=["3V", "4.1Ah capacity"]
)
self.assertEqual(
experiment.termination, {"voltage": (3, "V"), "capacity": (4.1, "Ah")}
)

with self.assertRaisesRegex(ValueError, "Only capacity"):
experiment = pybamm.Experiment(
["Discharge at 1 C for 20 seconds"], termination="bla bla capacity bla"
Expand Down
19 changes: 0 additions & 19 deletions tests/unit/test_experiments/test_simulation_with_experiment.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,25 +330,6 @@ def test_run_experiment_with_pbar(self):
sim = pybamm.Simulation(model, experiment=experiment)
sim.solve(showprogress=True)

def test_run_experiment_termination_voltage(self):
# with percent
experiment = pybamm.Experiment(
[
("Discharge at 0.5C for 10 minutes", "Rest for 10 minutes"),
]
* 5,
termination="4V",
)
model = pybamm.lithium_ion.SPM()
param = pybamm.ParameterValues("Chen2020")
sim = pybamm.Simulation(model, experiment=experiment, parameter_values=param)
# Test with calc_esoh=False here
sol = sim.solve(calc_esoh=False)
# Only two cycles should be completed, only 2nd cycle should go below 4V
np.testing.assert_array_less(4, np.min(sol.cycles[0]["Voltage [V]"].data))
np.testing.assert_array_less(np.min(sol.cycles[1]["Voltage [V]"].data), 4)
self.assertEqual(len(sol.cycles), 2)

def test_save_at_cycles(self):
experiment = pybamm.Experiment(
[
Expand Down

0 comments on commit 64ade63

Please sign in to comment.