Mesa - Datacollection Mesa - Batchrunner: 4.1.1.2 Analysis Modules
Mesa - Datacollection Mesa - Batchrunner: 4.1.1.2 Analysis Modules
If you’re using modeling for research, you’ll want a way to collect the data each model run generates. You’ll probably
also want to run the model multiple times, to see how some output changes with different parameters. Data collection
and batch running are implemented in the appropriately-named analysis modules:
• mesa.datacollection
• mesa.batchrunner
You’d add a data collector to the model like this:
import mesa
# ...
class MyModel(mesa.Model):
def __init__(self, n_agents):
# ...
self.dc = mesa.DataCollector(model_reporters={"agent_count":
lambda m: m.schedule.get_agent_count()},
agent_reporters={"name": lambda a: a.name})
def step(self):
self.schedule.step()
self.dc.collect(self)
The data collector will collect the specified model- and agent-level data at each step of the model. After you’re done
running it, you can extract the data as a pandas DataFrame:
model = MyModel(5)
for t in range(10):
model.step()
model_df = model.dc.get_model_vars_dataframe()
agent_df = model.dc.get_agent_vars_dataframe()
To batch-run the model while varying, for example, the n_agents parameter, you’d use the batch_run function:
import mesa
As with the data collector, once the runs are all over, you can extract the data as a data frame.
batch_df = batch_run.get_model_vars_dataframe()
Important:
• If you are just exploring Mesa and want the fastest way to execute the code we recommend executing this tutorial
online in a Colab notebook.
• If you have installed mesa and are running locally, please ensure that your Mesa version is up-to-date in order to
run this tutorial.
Mesa is a Python framework for agent-based modeling. This tutorial will assist you in getting started. Working through
the tutorial will help you discover the core features of Mesa. Through the tutorial, you are walked through creating a
starter-level model. Functionality is added progressively as the process unfolds. Should anyone find any errors, bugs,
have a suggestion, or just are looking for clarification, let us know!
The premise of this tutorial is to create a starter-level model representing agents exchanging money. This exchange of
money affects wealth.
Next, space is added to allow agents to move based on the change in wealth as time progresses.
Two of Mesa’s analytic tools: the data collector and batch runner are then used to examine the dynamics of this simple
model.
Visualization: There is a separate visualization tutorial that will take users through building a visualization for this
model (aka Boltzmann Wealth Model).
This is a starter-level simulated agent-based economy. In an agent-based economy, the behavior of an individual eco-
nomic agent, such as a consumer or producer, is studied in a market environment. This model is drawn from the field
econophysics, specifically a paper prepared by Drăgulescu et al. for additional information on the modeling assump-
tions used in this model. [Drăgulescu, 2002].
The assumption that govern this model are:
1. There are some number of agents.
2. All agents begin with 1 unit of money.
3. At every step of the model, an agent gives 1 unit of money (if they have it) to some other agent.
Even as a starter-level model the yielded results are both interesting and unexpected to individuals unfamiliar with it
the specific topic. As such, this model is a good starting point to examine Mesa’s core features.
Create and activate a virtual environment. Python version 3.10 or higher is required.
Install Mesa:
If you want to use our newest features, you can also opt to install our latest pre-release version:
If running in Google Colab run the below cell to install Mesa. (This will also work in a locally installed version of
Jupyter.)
Note: you may need to restart the kernel to use updated packages.
After Mesa is installed a model can be built. A jupyter notebook is recommended for this tutorial, this allows for small
segments of codes to be examined one at a time. As an option this can be created using python script files.
Good Practice: Place a model in its own folder/directory. This is not specifically required for the starter_model, but as
other models become more complicated and expand multiple python scripts, documentation, discussions and notebooks
may be added.
jupyter notebook
Create a new Notebook named money_model.ipynb (or whatever you want to call it).
4.2.4.3 Creating Model With Script File (IDE, Text Editor, Colab, etc.)
Create a new file called money_model.py (or whatever you want to call it)
Code will be added as the tutorial progresses.
import mesa
First create the agent. As the tutorial progresses, more functionality will be added to the agent.
Background: Agents are the individual entities that act in the model. It is a good modeling practice to make certain
each Agent can be uniquely identified.
Model-specific information: Agents are the individuals that exchange money, in this case the amount of money an
individual agent has is represented as wealth. Additionally, agents each have a unique identifier.
Code implementation: This is done by creating a new class (or object) that extends mesa.Agent creating a subclass
of the Agent class from mesa. The new class is named MoneyAgent. The technical details about the agent object can
be found in the mesa repo.
The MoneyAgent class is created with the following code:
class MoneyAgent(mesa.Agent):
"""An agent with fixed initial wealth."""
Next, create the model. Again, as the tutorial progresses, more functionality will be added to the model.
Background: The model can be visualized as a grid containing all the agents. The model creates, holds and manages
all the agents on the grid. The model evolves in discrete time steps.
Model-specific information: When a model is created the number of agents within the model is specified. The model
then creates the agents and places them on the grid. The model also contains a scheduler which controls the order in
which agents are activated. The scheduler is also responsible for advancing the model by one step. The model also
contains a data collector which collects data from the model. These topics will be covered in more detail later in the
tutorial.
Code implementation: This is done by creating a new class (or object) that extends mesa.Model and calls super().
__init__(), creating a subclass of the Model class from mesa. The new class is named MoneyModel. The technical
details about the agent object can be found in the mesa repo.
The MoneyModel class is created with the following code:
class MoneyModel(mesa.Model):
"""A model with some number of agents."""
given model uses, and see whether it changes the model behavior. The details pertaining to the scheduler interface can
be located in the same mesa repo.
With that in mind, the MoneyAgent code is modified below to visually show when a new agent is created. The Mon-
eyModel code is modified by adding the RandomActivation method to the model. with the scheduler added looks like
this:
class MoneyAgent(mesa.Agent):
"""An agent with fixed initial wealth."""
def step(self):
# The agent's step will go here.
# For demonstration purposes we will print the agent's unique_id
print(f"Hi, I am an agent, you can call me {str(self.unique_id)}.")
class MoneyModel(mesa.Model):
"""A model with some number of agents."""
# Create agents
for i in range(self.num_agents):
a = MoneyAgent(i, self)
# Add the agent to the scheduler
self.schedule.add(a)
def step(self):
"""Advance the model by one step."""
# The model's step will go here for now this will call the step method of each␣
˓→agent and print the agent's unique_id
self.schedule.step()