0% found this document useful (0 votes)
20 views

Mesa - Datacollection Mesa - Batchrunner: 4.1.1.2 Analysis Modules

Uploaded by

ADITYA KULKARNI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Mesa - Datacollection Mesa - Batchrunner: 4.1.1.2 Analysis Modules

Uploaded by

ADITYA KULKARNI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Mesa Documentation, Release .

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

parameters = {"n_agents": range(1, 20)}


mesa.batch_run(
MyModel,
parameters,
max_steps=10,
)

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()

4.1. Mesa Overview 11


Mesa Documentation, Release .1

4.2 Introductory Tutorial

4.2.1 The Boltzmann Wealth Model

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.

4.2.2 Tutorial Description

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.

4.2.2.1 More Tutorials:

Visualization: There is a separate visualization tutorial that will take users through building a visualization for this
model (aka Boltzmann Wealth Model).

4.2.3 Model Description

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.

12 Chapter 4. Mesa Packages


Mesa Documentation, Release .1

4.2.3.1 Tutorial Setup

Create and activate a virtual environment. Python version 3.10 or higher is required.
Install Mesa:

pip install --upgrade mesa

If you want to use our newest features, you can also opt to install our latest pre-release version:

pip install --upgrade --pre mesa

Install Jupyter Notebook (optional):

pip install jupyter

Install Seaborn (which is used for data visualization):

pip install seaborn

If running in Google Colab run the below cell to install Mesa. (This will also work in a locally installed version of
Jupyter.)

# SKIP THIS CELL unless running in colab

%pip install --quiet mesa


# The exclamation points tell jupyter to do the command via the command line

Note: you may need to restart the kernel to use updated packages.

4.2.4 Building the Sample Model

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.

4.2.4.1 Create New Folder/Directory

• Using operating system commands create a new folder/directory named ‘starter_model’.


• Change into the new folder/directory.

4.2. Introductory Tutorial 13


Mesa Documentation, Release .1

4.2.4.2 Creating Model With Jupyter Notebook

Write the model interactively in Jupyter Notebook cells.


Start Jupyter Notebook:

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.

4.2.4.4 Import Dependencies

This includes importing of dependencies needed for the tutorial.

import mesa

# Data visualization tools.


import seaborn as sns

# Has multi-dimensional arrays and matrices. Has a large collection of


# mathematical functions to operate on these arrays.
import numpy as np

# Data manipulation and analysis.


import pandas as pd

4.2.4.5 Create Agent

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."""

def __init__(self, unique_id, model):


# Pass the parameters to the parent class.
super().__init__(unique_id, model)
(continues on next page)

14 Chapter 4. Mesa Packages


Mesa Documentation, Release .1

(continued from previous page)

# Create the agent's variable and set the initial values.


self.wealth = 1

4.2.4.6 Create Model

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."""

def __init__(self, N):


super().__init__()
self.num_agents = N
# Create agents
for i in range(self.num_agents):
a = MoneyAgent(i, self)

4.2.4.7 Adding the Scheduler

Now the model will be modified to add a scheduler.


Background: The scheduler controls the order in which agents are activated, causing the agent to take their defined
action. The scheduler is also responsible for advancing the model by one step. A step is the smallest unit of time in the
model, and is often referred to as a tick. The scheduler can be configured to activate agents in different orders. This
can be important as the order in which agents are activated can impact the results of the model [Comer2014]. At each
step of the model, one or more of the agents – usually all of them – are activated and take their own step, changing
internally and/or interacting with one another or the environment.
Model-specific information: A new class is named RandomActivationByAgent is created which extends mesa.
time.RandomActivation creating a subclass of the RandomActivation class from Mesa. This class activates all
the agents once per step, in random order. Every agent is expected to have a step method. The step method is the action
the agent takes when it is activated by the model schedule. We add an agent to the schedule using the add method;
when we call the schedule’s step method, the model shuffles the order of the agents, then activates and executes each
agent’s step method. The scheduler is then added to the model.
Code implementation: The technical details about the timer object can be found in the mesa repo. Mesa offers a few
different built-in scheduler classes, with a common interface. That makes it easy to change the activation regime a

4.2. Introductory Tutorial 15


Mesa Documentation, Release .1

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 __init__(self, unique_id, model):


# Pass the parameters to the parent class.
super().__init__(unique_id, model)

# Create the agent's attribute and set the initial values.


self.wealth = 1

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."""

def __init__(self, N):


super().__init__()
self.num_agents = N
# Create scheduler and assign it to the model
self.schedule = mesa.time.RandomActivation(self)

# 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()

16 Chapter 4. Mesa Packages

You might also like