From 7254182e07de810c17f71cb4cfb089fd1f92c639 Mon Sep 17 00:00:00 2001 From: rht Date: Sat, 6 Jan 2024 18:54:14 -0500 Subject: [PATCH] model: Move random seed and random to __init__ Given that `super().__init__()` is now necessary for user's model class `__init__()`, this simplifies the `Model` construct. And `model.random` can be initialized with other RNG objects (`np.random.default_rng(...)`, or any other RNG). Prior discussion https://github.com/projectmesa/mesa/discussions/1938.# Please enter the commit message for your changes. Lines starting --- mesa/model.py | 21 +++++++-------------- 1 file changed, 7 insertions(+), 14 deletions(-) diff --git a/mesa/model.py b/mesa/model.py index d998e112f26..240970812f7 100644 --- a/mesa/model.py +++ b/mesa/model.py @@ -49,20 +49,6 @@ class Model: initialize_data_collector: Sets up the data collector for the model, requiring an initialized scheduler and agents. """ - def __new__(cls, *args: Any, **kwargs: Any) -> Any: - """Create a new model object and instantiate its RNG automatically.""" - obj = object.__new__(cls) - obj._seed = kwargs.get("seed") - if obj._seed is None: - # We explicitly specify the seed here so that we know its value in - # advance. - obj._seed = random.random() - obj.random = random.Random(obj._seed) - # TODO: Remove these 2 lines just before Mesa 3.0 - obj._steps = 0 - obj._time = 0 - return obj - def __init__(self, *args: Any, **kwargs: Any) -> None: """Create a new model. Overload this method with the actual code to start the model. Always start with super().__init__() to initialize the @@ -74,6 +60,13 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.current_id = 0 self.agents_: defaultdict[type, dict] = defaultdict(dict) + self._seed = kwargs.get("seed") + if self._seed is None: + # We explicitly specify the seed here so that we know its value in + # advance. + self._seed = random.random() + self.random = random.Random(self._seed) + self._steps: int = 0 self._time: TimeT = 0 # the model's clock