Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions docs/best-practices.rst
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,29 @@ an ``images`` directory.
The `Schelling
<https://github.com/projectmesa/mesa/tree/master/examples/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.
4 changes: 4 additions & 0 deletions mesa/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"""
import datetime as dt
import random
import numpy


class Model:
Expand All @@ -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

Expand Down