diff --git a/docs/best-practices.rst b/docs/best-practices.rst index 34ade0cdb3b..205f375b010 100644 --- a/docs/best-practices.rst +++ b/docs/best-practices.rst @@ -32,3 +32,29 @@ an ``images`` directory. The `Schelling `_ model is a good example of a small well-packaged model. + +Randomization +------------- + +If your model involves some random choice, you can use either ``random`` +(Python's built-in random number generator) or ``numpy.random`` (the generator +included with Numpy). + +The constructor for the ``Model`` class automatically "seeds" these random +number generators using the current time, so each run will produce different +random numbers. For testing purposes, it can be helpful to use the same +random-number seed for multiple runs. To accomplish this, pass a value to the +Model constructor: + +.. code:: python + + class AwesomeModel(Model): + def __init__(self, seed=None): + super().__init__(seed) + # ... + + model = AwesomeModel(seed=1234) + # ... + +This approach will cause ``RandomActivation`` to activate agents in a +repeatable fashion. diff --git a/mesa/model.py b/mesa/model.py index 6e4d4241157..849caeaf45d 100644 --- a/mesa/model.py +++ b/mesa/model.py @@ -7,6 +7,7 @@ """ import datetime as dt import random +import numpy class Model: @@ -23,11 +24,14 @@ def __init__(self, seed=None): running: a bool indicating if the model should continue running """ + # seed both the numpy and Python random number generators if seed is None: self.seed = dt.datetime.now() else: self.seed = seed random.seed(seed) + numpy.random.seed(seed) + self.running = True self.schedule = None