Skip to content

Commit

Permalink
Add NumPy random seed to notebook instead (#4847)
Browse files Browse the repository at this point in the history
Co-authored-by: Eric G. Kratz <[email protected]>
  • Loading branch information
agriyakhetarpal and kratman authored Feb 14, 2025
1 parent b5863e9 commit b0b0fb6
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 16 deletions.
20 changes: 20 additions & 0 deletions docs/source/examples/notebooks/models/half-cell.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,26 @@
"import matplotlib.pyplot as plt"
]
},
{
"cell_type": "markdown",
"id": "2b2e62ad",
"metadata": {},
"source": [
"First, we introduce a random seed to ensure reproducibility of the results before running the simulation:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7f30409c",
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"\n",
"np.random.seed(42)"
]
},
{
"cell_type": "markdown",
"id": "f372aa29",
Expand Down
16 changes: 0 additions & 16 deletions src/pybamm/simulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import pickle
import pybamm
import numpy as np
import hashlib
import warnings
from functools import lru_cache
from datetime import timedelta
Expand Down Expand Up @@ -133,9 +132,6 @@ 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 @@ -159,18 +155,6 @@ 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, solve_kwargs=None):
msg = "pybamm.simulation.set_up_and_parameterise_experiment is deprecated and not meant to be accessed by users."
warnings.warn(msg, DeprecationWarning, stacklevel=2)
Expand Down

0 comments on commit b0b0fb6

Please sign in to comment.