0
# Mesa: Agent-Based Modeling Framework
1
2
Mesa is a Python framework for agent-based modeling (ABM) that enables researchers and developers to build, analyze, and visualize complex adaptive systems. It provides a modular architecture for creating models where autonomous agents interact with each other and their environment according to defined rules.
3
4
## Package Information
5
6
**PyPI Package:** `mesa`
7
**Python Version:** 3.11+
8
**Installation:** `pip install mesa`
9
**Version:** 3.2.0
10
**License:** Apache 2.0
11
12
## Core Imports
13
14
```python { .api }
15
# Core agent-based modeling classes
16
from mesa import Agent, Model
17
# Note: AgentSet is available via Agent.create_agents() or model.agents
18
19
# Data collection utilities
20
from mesa import DataCollector
21
22
# Traditional spatial modeling (legacy)
23
from mesa import space
24
25
# Modern discrete spatial modeling
26
from mesa import discrete_space
27
28
# Batch running for parameter sweeps
29
from mesa import batch_run
30
31
# Experimental features
32
from mesa import experimental
33
34
# Logging utilities
35
import mesa.mesa_logging
36
```
37
38
## Basic Usage
39
40
### Simple Model Creation
41
42
```python { .api }
43
from mesa import Agent, Model
44
from mesa.discrete_space import Grid
45
46
class MyAgent(Agent):
47
"""Example agent with basic behavior."""
48
49
def __init__(self, model):
50
super().__init__(model)
51
self.energy = 100
52
53
def step(self):
54
"""Agent behavior executed each simulation step."""
55
self.energy -= 1
56
if self.energy <= 0:
57
self.remove()
58
59
class MyModel(Model):
60
"""Example model with agents on a grid."""
61
62
def __init__(self, n_agents: int, width: int, height: int):
63
super().__init__()
64
self.space = Grid(width, height)
65
66
# Create agents
67
for i in range(n_agents):
68
agent = MyAgent(self)
69
# Place agent randomly
70
self.space.place_agent(agent, self.space.select_random_empty_cell())
71
72
def step(self):
73
"""Execute one step of the model."""
74
self.agents.shuffle_do("step")
75
76
# Run the model
77
model = MyModel(n_agents=50, width=20, height=20)
78
for i in range(100):
79
model.step()
80
if len(model.agents) == 0:
81
break
82
```
83
84
## Architecture
85
86
Mesa follows a modular agent-based modeling architecture with several key components:
87
88
### Agents
89
Individual entities that act autonomously according to defined rules. Agents have:
90
- **Unique Identity**: Each agent has a unique ID within the model
91
- **State**: Internal variables that define the agent's current condition
92
- **Behavior**: Methods that define how the agent acts each simulation step
93
- **Interactions**: Ability to interact with other agents and the environment
94
95
### Model
96
The container that manages the simulation, including:
97
- **Agent Management**: Registration, creation, and removal of agents
98
- **Scheduling**: Coordination of agent actions each simulation step
99
- **Environment**: Spatial structures and global variables
100
- **Data Collection**: Tracking of model and agent variables over time
101
102
### Space
103
Spatial structures where agents can be positioned:
104
- **Discrete Spaces**: Grid-based environments with distinct cells
105
- **Continuous Spaces**: Spaces with real-valued coordinates
106
- **Network Spaces**: Graph-based environments with nodes and edges
107
108
### Data Collection
109
Systematic recording of model dynamics:
110
- **Model Reporters**: Functions that collect model-level statistics
111
- **Agent Reporters**: Functions that collect agent-level data
112
- **Time Series**: Longitudinal data across simulation steps
113
114
## Capabilities
115
116
### Core Agent-Based Modeling
117
118
Mesa provides fundamental classes for building agent-based models with powerful agent management capabilities.
119
120
```python { .api }
121
from mesa import Agent, Model
122
# AgentSet is accessible through agent creation or model.agents property
123
124
class Agent:
125
"""Base class for model agents with lifecycle management."""
126
127
def __init__(self, model: Model, *args, **kwargs) -> None: ...
128
def step(self) -> None: ...
129
def advance(self) -> None: ...
130
def remove(self) -> None: ...
131
132
@classmethod
133
def create_agents(cls, model: Model, n: int, *args, **kwargs) -> AgentSet[Agent]: ...
134
135
@property
136
def random(self) -> Random: ...
137
138
@property
139
def rng(self) -> np.random.Generator: ...
140
141
class AgentSet(MutableSet, Sequence):
142
"""Collection class for managing ordered sets of agents with advanced operations."""
143
144
def __init__(self, agents: Iterable[Agent], random: Random | None = None): ...
145
146
def select(self, filter_func: Callable[[Agent], bool] | None = None,
147
at_most: int | float = float("inf"),
148
inplace: bool = False,
149
agent_type: type[Agent] | None = None) -> AgentSet: ...
150
151
def shuffle(self, inplace: bool = False) -> AgentSet: ...
152
def sort(self, key: Callable[[Agent], Any] | str,
153
ascending: bool = False, inplace: bool = False) -> AgentSet: ...
154
155
def do(self, method: str | Callable, *args, **kwargs) -> AgentSet: ...
156
def shuffle_do(self, method: str | Callable, *args, **kwargs) -> AgentSet: ...
157
def map(self, method: str | Callable, *args, **kwargs) -> list[Any]: ...
158
159
class Model:
160
"""Base class for agent-based models with simulation management."""
161
162
def __init__(self, *args: Any, seed: float | None = None,
163
rng: RNGLike | SeedLike | None = None, **kwargs: Any) -> None: ...
164
165
def step(self) -> None: ...
166
def run_model(self) -> None: ...
167
def register_agent(self, agent): ...
168
def deregister_agent(self, agent): ...
169
170
@property
171
def agents(self) -> AgentSet: ...
172
173
@property
174
def agents_by_type(self) -> dict[type[Agent], AgentSet]: ...
175
```
176
177
**Learn More:** [Core Agent-Based Modeling →](core.md)
178
179
### Data Collection
180
181
Comprehensive data collection system for tracking model dynamics and generating datasets for analysis.
182
183
```python { .api }
184
from mesa import DataCollector
185
186
class DataCollector:
187
"""Data collection system for Mesa models with multiple reporter types."""
188
189
def __init__(self,
190
model_reporters=None,
191
agent_reporters=None,
192
agenttype_reporters=None,
193
tables=None): ...
194
195
def collect(self, model): ...
196
def add_table_row(self, table_name, row, ignore_missing=False): ...
197
def get_model_vars_dataframe(self): ...
198
def get_agent_vars_dataframe(self): ...
199
def get_agenttype_vars_dataframe(self, agent_type): ...
200
def get_table_dataframe(self, table_name): ...
201
```
202
203
**Learn More:** [Data Collection →](data-collection.md)
204
205
### Spatial Systems
206
207
Mesa provides two spatial modeling approaches: the traditional mesa.space module and the modern mesa.discrete_space module.
208
209
```python { .api }
210
# Legacy spatial system (maintenance mode)
211
from mesa.space import MultiGrid, SingleGrid, ContinuousSpace, NetworkGrid
212
213
# Modern discrete spatial system (active development)
214
from mesa.discrete_space import Grid, HexGrid, Network, Cell, CellAgent
215
216
# Property layers for spatial data
217
from mesa.discrete_space import PropertyLayer
218
from mesa.space import PropertyLayer as LegacyPropertyLayer
219
220
class Grid:
221
"""Modern grid-based discrete space with cell-centric approach."""
222
223
def __init__(self, width: int, height: int, torus: bool = False): ...
224
def place_agent(self, agent, cell): ...
225
def move_agent(self, agent, cell): ...
226
def select_random_empty_cell(self): ...
227
228
class CellAgent(Agent):
229
"""Agent class that understands cell-based spatial interactions."""
230
231
def __init__(self, model, cell=None): ...
232
def move_to(self, cell): ...
233
def get_neighbors(self, include_center=False): ...
234
```
235
236
**Learn More:** [Spatial Systems →](spatial.md)
237
238
### Batch Running
239
240
Parameter sweep functionality for systematic exploration of model behavior across different parameter combinations.
241
242
```python { .api }
243
from mesa import batch_run
244
245
def batch_run(model_cls: type[Model],
246
parameters: Mapping[str, Any | Iterable[Any]],
247
number_processes: int | None = 1,
248
iterations: int = 1,
249
data_collection_period: int = -1,
250
max_steps: int = 1000,
251
display_progress: bool = True) -> list[dict[str, Any]]:
252
"""
253
Batch run a Mesa model with parameter sweeps.
254
255
Parameters:
256
model_cls: The model class to run
257
parameters: Dictionary of parameter names to values or ranges
258
number_processes: Number of parallel processes (None for all cores)
259
iterations: Number of iterations per parameter combination
260
data_collection_period: How often to collect data (-1 for end only)
261
max_steps: Maximum number of steps per model run
262
display_progress: Whether to show progress bar
263
264
Returns:
265
List of dictionaries containing collected data
266
"""
267
...
268
```
269
270
**Learn More:** [Batch Running →](batch-running.md)
271
272
### Experimental Features
273
274
Cutting-edge features under active development including DEVS simulation, reactive programming, and advanced visualization.
275
276
```python { .api }
277
from mesa import experimental
278
279
# Submodules available
280
experimental.devs # Discrete Event Simulation framework
281
experimental.mesa_signals # Reactive programming with observables
282
experimental.meta_agents # Meta-agent functionality
283
experimental.continuous_space # Enhanced continuous space modeling
284
```
285
286
**Learn More:** [Experimental Features →](experimental.md)
287
288
## Type Definitions
289
290
```python { .api }
291
# Core type aliases used throughout Mesa
292
from typing import Any, Callable, Iterable, Sequence
293
import numpy as np
294
from random import Random
295
296
# Model-related types
297
SeedLike = int | np.integer | Sequence[int] | np.random.SeedSequence
298
RNGLike = np.random.Generator | np.random.BitGenerator
299
300
# Spatial types
301
Coordinate = tuple[int, int]
302
FloatCoordinate = tuple[float, float] | np.ndarray
303
NetworkCoordinate = int
304
Position = Coordinate | FloatCoordinate | NetworkCoordinate
305
306
# Grid content types
307
GridContent = Agent | None
308
MultiGridContent = list[Agent]
309
```
310
311
## Related Documentation
312
313
- **[Core Agent-Based Modeling](core.md)** - Agent, AgentSet, and Model classes
314
- **[Data Collection](data-collection.md)** - DataCollector system
315
- **[Spatial Systems](spatial.md)** - Both legacy and modern spatial approaches
316
- **[Batch Running](batch-running.md)** - Parameter sweeps and batch execution
317
- **[Experimental Features](experimental.md)** - Cutting-edge experimental modules