Skip to content

Commit

Permalink
Merge pull request pybamm-team#3494 from agriyakhetarpal/random-seed-…
Browse files Browse the repository at this point in the history
…for-simulations

Improve reliability of simulations when using `CasadiSolver`
  • Loading branch information
Saransh-cpp authored Nov 25, 2023
2 parents a463246 + dfde5d0 commit d7d6262
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## Bug fixes

- Fixed a bug where simulations using the CasADi-based solvers would fail randomly with the half-cell model ([#3494](https://github.com/pybamm-team/PyBaMM/pull/3494))
- Fixed bug that made identical Experiment steps with different end times crash ([#3516](https://github.com/pybamm-team/PyBaMM/pull/3516))
- Fixed bug in calculation of theoretical energy that made it very slow ([#3506](https://github.com/pybamm-team/PyBaMM/pull/3506))
- The irreversible plating model now increments `f"{Domain} dead lithium concentration [mol.m-3]"`, not `f"{Domain} lithium plating concentration [mol.m-3]"` as it did previously. ([#3485](https://github.com/pybamm-team/PyBaMM/pull/3485))
Expand Down
16 changes: 16 additions & 0 deletions pybamm/simulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import pickle
import pybamm
import numpy as np
import hashlib
import warnings
import sys
from functools import lru_cache
Expand Down Expand Up @@ -133,6 +134,9 @@ def __init__(
self._solution = None
self.quick_plot = None

# Initialise instances of Simulation class with the same random seed
self._set_random_seed()

# ignore runtime warnings in notebooks
if is_notebook(): # pragma: no cover
import warnings
Expand All @@ -156,6 +160,18 @@ def __setstate__(self, state):
self.__dict__ = state
self.get_esoh_solver = lru_cache()(self._get_esoh_solver)

# If the solver being used is CasadiSolver or its variants, set a fixed
# random seed during class initialization to the SHA-256 hash of the class
# name for purposes of reproducibility.
def _set_random_seed(self):
if isinstance(self._solver, pybamm.CasadiSolver) or isinstance(
self._solver, pybamm.CasadiAlgebraicSolver
):
np.random.seed(
int(hashlib.sha256(self.__class__.__name__.encode()).hexdigest(), 16)
% (2**32)
)

def set_up_and_parameterise_experiment(self):
"""
Set up a simulation to run with an experiment. This creates a dictionary of
Expand Down

0 comments on commit d7d6262

Please sign in to comment.