Simulating Sugar Rush with Python: An Agent-Based Model with Mesa
Last Updated on July 17, 2023 by Editorial Team
Author(s): Ulrik Thyge Pedersen
Originally published on Towards AI.
Building and Analyzing an Agent-Based Model of Sugar Trading Behavior using Mesa Library in Python
Introduction
Agent-based modeling (ABM) is a powerful simulation technique that allows researchers and practitioners to study complex systems by modeling the interactions and behaviors of individual agents within the system. ABM has been widely used in various fields, such as social sciences, economics, ecology, and public health, to better understand the emergent properties and dynamics of complex systems.
In recent years, Python has become a popular programming language for ABM due to its ease of use, flexibility, and extensive ecosystem of libraries. One such library is Mesa, which provides a framework for building agent-based models in Python.
Mesa offers a rich set of tools and features for creating, simulating, and analyzing ABMs, making it a valuable resource for researchers and practitioners interested in modeling complex systems.
In this article, we will focus on the implementation of an ABM using the Mesa library in Python, specifically the sugar trading model from the Mesa-ABM-Tutorial GitHub repository. We will provide a step-by-step guide to building the model, including creating agents, defining their behaviors, and scheduling their interactions. We will also demonstrate how to use the Mesa libraryβs visualization modules to analyze the modelβs behavior and interpret the results.
By exploring the sugar trading model as an example, we aim to showcase the capabilities of the Mesa library for building and analyzing ABMs in Python. We will provide code examples and explanations to help readers understand the implementation process and get started with their own ABM projects using Mesa. So, letβs dive into the world of agent-based modeling with Python and Mesa!
Mesa Library and its Features
Mesa is an open-source Python library for building agent-based models, developed by the Santa Fe Instituteβs Complex Systems Summer School. It provides a flexible framework for creating and simulating ABMs, with various features that make it a powerful tool for modeling complex systems.
Key Components of Mesa
Mesa has several key components that are central to building ABMs:
- Model: The Model class in Mesa represents the overarching structure of the ABM. It defines the environment, agents, and the rules that govern their interactions. It also manages the scheduling of agent behaviors and updates to the model state.
- Agent: The Agent class in Mesa represents the individual agents in the ABM. Agents can have their own states, behaviors, and interactions with other agents and the environment. They can be customized to represent different types of entities in the system being modeled, such as individuals, organizations, or biological entities.
- Scheduler: The Scheduler class in Mesa manages the scheduling of agent behaviors in the ABM. It allows you to specify the order in which agents should act, and it can handle different types of scheduling, such as random or sequential, depending on the requirements of the model.
Grid-based and Network-based Modeling
Mesa supports two main types of spatial modeling: grid-based and network-based.
- Grid-based Modeling: In grid-based modeling, the environment is represented as a grid, where agents occupy discrete cells. This is suitable for modeling systems with regular spatial structures, such as cellular automata or spatially explicit models. Mesa provides a Grid class that can be used to create and manipulate grid-based environments.
- Network-based Modeling: In network-based modeling, the environment is represented as a network or graph, where agents are nodes and edges represent their interactions. This is suitable for modeling systems with complex connectivity patterns, such as social networks or transportation networks. Mesa provides a Network class that can be used to create and manipulate network-based environments.
Scheduling Agent Behaviors
The Scheduler class in Mesa allows you to schedule agent behaviors in different ways, such as:
- Random Order: Agents behave in random order, which can be useful for modeling stochastic processes or interactions.
- Sequential Order: Agents behave in a fixed order, which can be useful for modeling processes that occur sequentially or in a predefined order.
- Priority Queue: Agents behave based on their priority, which can be useful for modeling processes that have different levels of importance or urgency.
- Time-based Scheduling: Agents behave at specific time steps, which can be useful for modeling processes that occur at discrete time intervals.
Hereβs an example code snippet that demonstrates how to create a simple Model, Agent, and Scheduler in Mesa:
In this example, MyModel
is a simple model with agents that are instances of MyAgent
. The RandomActivation
scheduler is used to schedule agent behaviors in random order. The step()
method in both the MyAgent
and MyModel
classes define the behaviors of the agents and the model at each time step, respectively.
Mesa provides many other features for agent-based modeling, such as data collection, visualization, and parameter tuning. These features can be used to analyze and interpret the results of the ABM, as well as to validate and calibrate the model.
In the next chapter, we will focus on implementing a sugar trading ABM using the Mesa library, and explore how the key components of Mesa, including the Model, Agent, and Scheduler, can be utilized to create a realistic and dynamic simulation of sugar trading behavior among agents.
We will also discuss the challenges and considerations in building ABMs, such as model validation, parameter sensitivity, and result interpretation. Stay tuned for the implementation details and code examples in the next chapter!
Sugar Trading Model Description
In this chapter, we will provide a detailed description of the sugar trading model that we will be implementing using the Mesa library. The model simulates the interactions between sugar producers and consumers in a market, where producers produce sugar and consumers consume sugar based on certain rules and behaviors.
The sugar trading model consists of the following key components:
- Agents: The model includes two types of agents β sugar producers and sugar consumers. Sugar producers are responsible for producing sugar based on their production rates, while sugar consumers are responsible for consuming sugar based on their consumption rates.
- Market: The market serves as the environment where sugar producers and consumers interact. It keeps track of the current sugar stock, sugar prices, and the trading activities between agents.
- Behaviors: Agents in the model follow certain behaviors. Sugar producers adjust their production rates based on the current sugar stock and market prices, while sugar consumers adjust their consumption rates based on the current sugar stock and their desired consumption levels.
- Trading: Sugar producers and consumers engage in trading activities in the market. Producers sell sugar at a certain price, and consumers buy sugar at the current market price. The trading activities are influenced by the behaviors of the agents and the dynamics of the market.
- Time-stepping: The model operates in discrete time steps, where agents update their behaviors and interact in the market at each time step. The model can be run for a specified number of time steps to observe the dynamics of the sugar market over time.
Now letβs take a closer look at the key components of the sugar trading model and their implementation using the Mesa library in Python.
Agent Implementation
We define two agent classes in our sugar trading model: SugarProducer
and SugarConsumer
. The SugarProducer
class represents the sugar producers in the market, and the SugarConsumer
class represents the sugar consumers. Both classes inherit from the mesa.Agent
class provided by the Mesa library, which allows us to define their behaviors and interactions in the model.
The SugarProducer
class has the following attributes:
unique_id
: A unique identifier for each sugar producer.model
: A reference to the sugar trading model instance that the producer belongs to.production_rate
: The rate at which the producer produces sugar.sugar_stock
: The current stock of sugar that the producer has.
The SugarConsumer
class has the following attributes:
unique_id
: A unique identifier for each sugar consumer.model
: A reference to the sugar trading model instance that the consumer belongs to.consumption_rate
: The rate at which the consumer consumes sugar.desired_consumption
: The desired level of sugar consumption for the consumer.
Market Implementation
We define a SugarMarket
class to represent the market in the sugar trading model. The SugarMarket
class keeps track of the current sugar stock, sugar prices, and the trading activities between sugar producers and consumers.
The SugarMarket
class has the following attributes:
model
: A reference to the sugar trading model instance that the market belongs to.sugar_stock
: The current stock of sugar in the market.sugar_price
: The current price of sugar in the market.trades
: A list to store the trading activities between sugar producers and consumers.
The SugarMarket
class has the following methods:
get_sugar_price()
: Calculates the current price of sugar based on the supply and demand in the market.register_trade(producer, consumer, quantity, price)
: Registers a trade between a sugar producer and a consumer in the market.clear_trades()
: Clears the list of trades after each time step
Behaviors Implementation
The behaviors of the sugar producers and consumers are implemented as methods within the SugarProducer
and SugarConsumer
classes, respectively. These behaviors determine how agents adjust their production and consumption rates based on the current state of the market.
For example, the SugarProducer
class has the following behaviors:
adjust_production_rate()
: Calculates the new production rate for the sugar producer based on the current sugar stock and market prices. The producer adjusts its production rate to match the desired sugar stock level and the market prices.
Similarly, the SugarConsumer
class has the following behaviors:
adjust_consumption_rate()
: Calculates the new consumption rate for the sugar consumer based on the current sugar stock, desired consumption level, and market prices. The consumer adjusts its consumption rate to match its desired consumption level and the market prices.
Trading Implementation
The trading activities between sugar producers and consumers are implemented in the SugarMarket
class. The market determines the current price of sugar based on the supply and demand in the market, and registers trades between producers and consumers.
For example, the SugarMarket
class has the following methods related to trading:
get_sugar_price()
: Calculates the current price of sugar based on the supply and demand in the market. The price is determined based on the available sugar stock and the total desired consumption level of all consumers.register_trade(producer, consumer, quantity, price)
: Registers a trade between a sugar producer and a consumer in the market. The trade includes the quantity of sugar traded and the price at which it was traded.
Time-Stepping Implementation
The sugar trading model operates in discrete time steps, where agents update their behaviors and interact in the market at each time step. This time-stepping mechanism is implemented in the main SugarModel
class using the mesa.TimeModel
provided by the Mesa Library.
The SugarModel
class has the following methods related to time-stepping:
step()
: Executes one-time step of the model. In each time step, agents update their behaviors, the market determines the current price of sugar, and trading activities are registered. The model can be run for a specified number of time steps using this method.
That concludes the description of the sugar trading model and its implementation using the Mesa library in Python. In the next chapter, we will focus on how to set up and run the model, as well as analyze the results.
Implementation of Sugar Trading Model Using Mesa
In this chapter, we will dive into the implementation details of the sugar trading model using the Mesa library in Python. We will cover the steps to set up the model, create agents, define their behaviors, and simulate the model using the time-stepping mechanism provided by Mesa.
Model Setup
To set up the sugar trading model using Mesa, we first need to import the necessary modules and define the classes for the agents and the market. Hereβs an example of how the model setup can be done:
Agent Behaviors
Next, we need to define the behaviors of the sugar producers and consumers as methods within their respective agent classes. These behaviors determine how agents adjust their production and consumption rates based on the current state of the market. Hereβs an example of how the adjust_production_rate()
and adjust_consumption_rate()
behaviors can be implemented:
Market Trading Activities
The trading activities between sugar producers and consumers are implemented in the SugarMarket
class. The market determines the current price of sugar based on the supply and demand in the market, and registers trades between producers and consumers. Here's an example of how the get_sugar_price()
and register_trade()
methods can be implemented:
Model Simulation
Once the model setup, agent behaviors, and market trading activities are defined, we can simulate the sugar trading model using the time-stepping mechanism provided by Mesa. Hereβs an example of how the step()
method in the SugarModel
class can be implemented:
In this chapter, we have implemented the sugar trading model using the Mesa library in Python. We covered the steps to set up the model, create agents with their behaviors, define the market trading activities, and simulate the model using the time-stepping mechanism provided by Mesa. We also discussed how to visualize the model using the built-in visualization functionality provided by Mesa.
In the next chapter, we will focus on the analysis and interpretation of the model results.
Model Visualization
Visualizing the sugar trading model can help us understand the dynamics of the model and gain insights into its behavior. Mesa provides built-in functionality for visualizing the model, including visualizing the grid space, agent positions, and agent attributes. In this chapter, we will explore various visualization techniques using the Mesa library in Python.
Grid Visualization
One common way to visualize agent-based models is through a grid visualization, where each cell in the grid represents a location in the model space, and agents are depicted as symbols or colors on the grid. In our sugar trading model, we can use a grid visualization to show the positions of sugar producers and consumers in the market.
Hereβs an example of how to create a grid visualization using the CanvasGrid
class provided by Mesa:
The agent_portrayal_function
is a user-defined function that specifies how each agent should be portrayed in the grid visualization. In this example, we depict sugar producers as green circles and sugar consumers as blue circles.
Time Series Visualization
Another way to analyze the dynamics of the sugar trading model is through time series visualization, which shows how the model variables change over time. We can use the matplotlib
library in Python to create time series plots for various model variables, such as the sugar prices, sugar stock levels, and consumption levels.
Hereβs an example of how to create a time series plot for sugar prices using matplotlib
:
This code snippet retrieves the sugar prices from the market
object in the SugarModel
and creates a time series plot using matplotlib
. The x-axis represents the time steps, and the y-axis represents the sugar prices.
Agent Attribute Visualization
We can also visualize the attributes of individual agents in the sugar trading model to gain insights into their behaviors. For example, we can create scatter plots to visualize the relationship between the sugar stock levels and consumption levels of sugar consumers.
Hereβs an example of how to create a scatter plot for sugar consumer attributes using matplotlib
:
In this example, we retrieve the sugar stock levels and consumption levels of sugar consumers from the SugarModel
and create a scatter plot using matplotlib
. The x-axis represents the sugar stock levels, and the y-axis represents the consumption levels.
Visualization of Model Dynamics
In addition to visualizing agent attributes and model variables, we can also create dynamic visualizations that show how the model changes over time. For example, we can create animations to visualize the movement of agents, changes in agent attributes, and the evolution of the market in the sugar trading model. Mesa provides a CanvasGrid
class that allows us to create dynamic visualizations with animations. Hereβs an example of how to create an animated grid visualization using CanvasGrid
:
This code snippet creates an animated grid visualization using CanvasGrid
with a 10×10 grid size and 500×500 pixels in size. The agent_portrayal_function
is a user-defined function that specifies how each agent should be portrayed in the animation. The x
and y
attributes in the portrayal dictionary specify the positions of the agents in the grid.
Visualizing the sugar trading model using the Mesa library in Python can greatly enhance our understanding of the modelβs dynamics and behaviors. Grid visualizations, time series plots, scatter plots, and dynamic animations are powerful tools for analyzing and interpreting the results of an agent-based model. By visualizing the model, we can gain insights into its behavior, validate its outcomes, and communicate the findings effectively to others.
Conclusion
In this article, we have explored the implementation of an agent-based model for sugar trading using the Mesa library in Python. We started with an introduction to agent-based modeling and its potential applications, followed by an overview of the Mesa library and its features. We then delved into the sugar trading model description, discussing the modelβs components, behaviors, and interactions among agents.
Next, we provided a step-by-step guide on how to implement the sugar trading model using the Mesa library in Python. We covered the creation of agents, scheduling of model steps, and implementation of agent behaviors. We also discussed how to set up the model parameters and run the model simulation.
We then focused on model visualization, which is a crucial step in analyzing and interpreting the results of an agent-based model. We showed examples of visualizing the model using Mesaβs built-in visualization modules, such as the CanvasGrid
for grid-based visualizations and ChartModule
for time series plots. We also demonstrated how to create custom visualizations, such as scatter plots, using external libraries like matplotlib
. Additionally, we highlighted the use of animations to visualize dynamic changes in the model over time.
In conclusion, the Mesa library in Python provides a powerful toolset for implementing, visualizing, and analyzing agent-based models. The sugar trading model example presented in this article serves as a practical demonstration of how to use Mesa to develop and analyze an agent-based model. By leveraging the capabilities of Mesa, researchers and practitioners can create sophisticated agent-based models to study complex systems and gain valuable insights into their behaviors and dynamics!
Thank you for reading my story!
Subscribe for free to get notified when I publish a new story!
Find me on LinkedIn and Kaggle!
β¦and I would love your feedback!
Join thousands of data leaders on the AI newsletter. Join over 80,000 subscribers and keep up to date with the latest developments in AI. From research to projects and ideas. If you are building an AI startup, an AI-related product, or a service, we invite you to consider becoming aΒ sponsor.
Published via Towards AI