diff --git a/pybamm/simulation.py b/pybamm/simulation.py index c8403b1c80..d0797faa98 100644 --- a/pybamm/simulation.py +++ b/pybamm/simulation.py @@ -8,6 +8,7 @@ import warnings import sys from functools import lru_cache +from datetime import timedelta def is_notebook(): @@ -718,7 +719,23 @@ def solve( # Use 1-indexing for printing cycle number as it is more # human-intuitive op_conds = self.experiment.operating_conditions[idx] - dt = op_conds["time"] + + start_time = current_solution.t[-1] + + # If next step has a timestamp, dt must take that into account + if op_conds["next timestamp"]: + dt = min( + op_conds["time"], + ( + op_conds["next timestamp"] + - ( + self.experiment.initial_timestamp + + timedelta(seconds=float(start_time)) + ) + ).total_seconds(), + ) + else: + dt = op_conds["time"] op_conds_str = op_conds["string"] model = self.op_conds_to_built_models[op_conds_str] solver = self.op_conds_to_built_solvers[op_conds_str] @@ -727,7 +744,6 @@ def solve( logs["step operating conditions"] = op_conds_str callbacks.on_step_start(logs) - start_time = current_solution.t[-1] kwargs["inputs"] = { **user_inputs, **op_conds, @@ -762,6 +778,8 @@ def solve( # Otherwise, just stop this cycle break + # TODO: add rest step if needed! + steps.append(step_solution) cycle_solution = cycle_solution + step_solution diff --git a/tests/unit/test_experiments/test_simulation_with_experiment.py b/tests/unit/test_experiments/test_simulation_with_experiment.py index 2d4b201d45..7f19d62d39 100644 --- a/tests/unit/test_experiments/test_simulation_with_experiment.py +++ b/tests/unit/test_experiments/test_simulation_with_experiment.py @@ -569,6 +569,29 @@ def test_run_experiment_lead_acid(self): sim = pybamm.Simulation(model, experiment=experiment) sim.solve() + def test_run_time_stamped_experiment(self): + # experiment = pybamm.Experiment( + # [ + # "[2023-01-01 08:00:00] Rest for 1 minute", + # "[2023-01-01 12:00:00] Discharge at 0.5C for 1 hour", + # "[2023-01-01 12:30:00] Charge at 0.1C for 1 hour", + # ] + # ) + experiment = pybamm.Experiment( + [ + "[2023-01-01 08:00:00] Rest for 10 hours", + "[2023-01-01 12:00:00] Discharge at 0.5C for 1 hour", + "[2023-01-01 12:30:00] Charge at 0.1C for 1 hour", + ] + ) + model = pybamm.lithium_ion.SPM() + sim = pybamm.Simulation(model, experiment=experiment) + sol = sim.solve() + sol.plot() + + # TODO: what if a later (beyond next) timestamp should kill current step? + + if __name__ == "__main__": print("Add -v for more debug output")