Skip to content

Commit 4c82989

Browse files
authored
docs: Update overview for Mesa 3.0 (#2317)
* docs: Update overview for Mesa 3.0 * Overview: Add further resources section * overview: Add section on AgentSet and model.agents * overview: Smaller headings * Apply suggestions from code review
1 parent ee550a8 commit 4c82989

File tree

1 file changed

+141
-29
lines changed

1 file changed

+141
-29
lines changed

docs/overview.md

+141-29
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
# Mesa Overview
2-
32
Mesa is a modular framework for building, analyzing and visualizing agent-based models.
43

54
**Agent-based models** are computer simulations involving multiple entities (the agents) acting and interacting with one another based on their programmed behavior. Agents can be used to represent living cells, animals, individual humans, even entire organizations or abstract entities. Sometimes, we may have an understanding of how the individual components of a system behave, and want to see what system-level behaviors and effects emerge from their interaction. Other times, we may have a good idea of how the system overall behaves, and want to figure out what individual behaviors explain it. Or we may want to see how to get agents to cooperate or compete most effectively. Or we may just want to build a cool toy with colorful little dots moving around.
@@ -8,16 +7,15 @@ Mesa is a modular framework for building, analyzing and visualizing agent-based
87

98
Mesa is modular, meaning that its modeling, analysis and visualization components are kept separate but intended to work together. The modules are grouped into three categories:
109

11-
1. **Modeling:** Modules used to build the models themselves: a model and agent classes, a scheduler to determine the sequence in which the agents act, and space for them to move around on.
10+
1. **Modeling:** Classes used to build the models themselves: a model and agent classes, space for them to move around in, and built-in functionality for managing agents.
1211
2. **Analysis:** Tools to collect data generated from your model, or to run it multiple times with different parameter values.
13-
3. **Visualization:** Classes to create and launch an interactive model visualization, using a server with a JavaScript interface.
12+
3. **Visualization:** Classes to create and launch an interactive model visualization, using a browser-based interface.
1413

1514
### Modeling modules
1615

17-
Most models consist of one class to represent the model itself; one class (or more) for agents; a scheduler to handle time (what order the agents act in), and possibly a space for the agents to inhabit and move through. These are implemented in Mesa's modeling modules:
16+
Most models consist of one class to represent the model itself and one or more classes for agents. Mesa provides built-in functionality for managing agents and their interactions. These are implemented in Mesa's modeling modules:
1817

1918
- `mesa.Model`, `mesa.Agent`
20-
- [mesa.time](apis/time)
2119
- [mesa.space](apis/space)
2220

2321
The skeleton of a model might look like this:
@@ -26,27 +24,27 @@ The skeleton of a model might look like this:
2624
import mesa
2725

2826
class MyAgent(mesa.Agent):
29-
def __init__(self, name, model):
30-
super().__init__(name, model)
31-
self.name = name
27+
def __init__(self, model, age):
28+
super().__init__(model)
29+
self.age = age
3230

3331
def step(self):
34-
print("{} activated".format(self.name))
32+
self.age += 1
33+
print(f"Agent {self.unique_id} now is {self.age} years old")
3534
# Whatever else the agent does when activated
3635

3736
class MyModel(mesa.Model):
3837
def __init__(self, n_agents):
3938
super().__init__()
40-
self.schedule = mesa.time.RandomActivation(self)
4139
self.grid = mesa.space.MultiGrid(10, 10, torus=True)
42-
for i in range(n_agents):
43-
a = MyAgent(i, self)
44-
self.schedule.add(a)
40+
for _ in range(n_agents):
41+
initial_age = self.random.randint(0, 80)
42+
a = MyAgent(self, initial_age)
4543
coords = (self.random.randrange(0, 10), self.random.randrange(0, 10))
4644
self.grid.place_agent(a, coords)
4745

4846
def step(self):
49-
self.schedule.step()
47+
self.agents.shuffle_do("step")
5048
```
5149

5250
If you instantiate a model and run it for one step, like so:
@@ -56,10 +54,59 @@ model = MyModel(5)
5654
model.step()
5755
```
5856

59-
You should see agents 0-4, activated in random order. See the [tutorial](tutorials/intro_tutorial) or API documentation for more detail on how to add model functionality.
57+
You should see agents 1-5, activated in random order. See the [tutorial](tutorials/intro_tutorial) or API documentation for more detail on how to add model functionality.
6058

6159
To bootstrap a new model install mesa and run `mesa startproject`
6260

61+
### AgentSet and model.agents
62+
Mesa 3.0 makes `model.agents` and the AgentSet class central in managing and activating agents.
63+
64+
#### model.agents
65+
`model.agents` is an AgentSet containing all agents in the model. It's automatically updated when agents are added or removed:
66+
67+
```python
68+
# Get total number of agents
69+
num_agents = len(model.agents)
70+
71+
# Iterate over all agents
72+
for agent in model.agents:
73+
print(agent.unique_id)
74+
```
75+
76+
#### AgentSet Functionality
77+
AgentSet offers several methods for efficient agent management:
78+
79+
1. **Selecting**: Filter agents based on criteria.
80+
```python
81+
high_energy_agents = model.agents.select(lambda a: a.energy > 50)
82+
```
83+
2. **Shuffling and Sorting**: Randomize or order agents.
84+
```python
85+
shuffled_agents = model.agents.shuffle()
86+
sorted_agents = model.agents.sort(key="energy", ascending=False)
87+
```
88+
3. **Applying methods**: Execute methods on all agents.
89+
```python
90+
model.agents.do("step")
91+
model.agents.shuffle_do("move") # Shuffle then apply method
92+
```
93+
4. **Aggregating**: Compute aggregate values across agents.
94+
```python
95+
avg_energy = model.agents.agg("energy", func=np.mean)
96+
```
97+
5. **Grouping**: Group agents by attributes.
98+
```python
99+
grouped_agents = model.agents.groupby("species")
100+
101+
for _, agent_group in grouped_agents:
102+
agent_group.shuffle_do()
103+
species_counts = grouped_agents.count()
104+
mean_age_by_group = grouped_agents.agg("age", np.mean)
105+
```
106+
`model.agents` can also be accessed within a model instance using `self.agents`.
107+
108+
These are just some examples of using the AgentSet, there are many more possibilities, see the [AgentSet API docs](apis/agent).
109+
63110
### Analysis modules
64111

65112
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:
@@ -71,19 +118,22 @@ You'd add a data collector to the model like this:
71118

72119
```python
73120
import mesa
121+
import numpy as np
74122

75123
# ...
76124

77125
class MyModel(mesa.Model):
78126
def __init__(self, n_agents):
79-
# ...
80-
self.dc = mesa.DataCollector(model_reporters={"agent_count":
81-
lambda m: m.schedule.get_agent_count()},
82-
agent_reporters={"name": lambda a: a.name})
127+
super().__init__()
128+
# ... (model initialization code)
129+
self.datacollector = mesa.DataCollector(
130+
model_reporters={"mean_age": lambda m: m.agents.agg("age", np.mean)},
131+
agent_reporters={"age": "age"}
132+
)
83133

84134
def step(self):
85-
self.schedule.step()
86-
self.dc.collect(self)
135+
self.agents.shuffle_do("step")
136+
self.datacollector.collect(self)
87137
```
88138

89139
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](http://pandas.pydata.org/) DataFrame:
@@ -92,25 +142,87 @@ The data collector will collect the specified model- and agent-level data at eac
92142
model = MyModel(5)
93143
for t in range(10):
94144
model.step()
95-
model_df = model.dc.get_model_vars_dataframe()
96-
agent_df = model.dc.get_agent_vars_dataframe()
145+
model_df = model.datacollector.get_model_vars_dataframe()
146+
agent_df = model.datacollector.get_agent_vars_dataframe()
97147
```
98148

99-
To batch-run the model while varying, for example, the n_agents parameter, you'd use the `batch_run` function:
149+
To batch-run the model while varying, for example, the n_agents parameter, you'd use the [`batch_run`](apis/batchrunner) function:
100150

101151
```python
102152
import mesa
103153

104-
parameters = {"n_agents": range(1, 20)}
105-
mesa.batch_run(
154+
parameters = {"n_agents": range(1, 6)}
155+
results = mesa.batch_run(
106156
MyModel,
107157
parameters,
108-
max_steps=10,
158+
iterations=5,
159+
max_steps=100,
160+
data_collection_period=1,
109161
)
110162
```
111163

112-
As with the data collector, once the runs are all over, you can extract the data as a data frame.
164+
The results are returned as a list of dictionaries, which can be easily converted to a pandas DataFrame for further analysis.
165+
166+
### Visualization
167+
Mesa now uses a new browser-based visualization system called SolaraViz. This allows for interactive, customizable visualizations of your models. Here's a basic example of how to set up a visualization:
113168

114169
```python
115-
batch_df = batch_run.get_model_vars_dataframe()
170+
from mesa.visualization import SolaraViz, make_space_matplotlib, make_plot_measure
171+
172+
def agent_portrayal(agent):
173+
return {"color": "blue", "size": 50}
174+
175+
model_params = {
176+
"N": {
177+
"type": "SliderInt",
178+
"value": 50,
179+
"label": "Number of agents:",
180+
"min": 10,
181+
"max": 100,
182+
"step": 1,
183+
}
184+
}
185+
186+
page = SolaraViz(
187+
MyModel,
188+
[
189+
make_space_matplotlib(agent_portrayal),
190+
make_plot_measure("mean_age")
191+
],
192+
model_params=model_params
193+
)
194+
page
116195
```
196+
This will create an interactive visualization of your model, including:
197+
198+
- A grid visualization of agents
199+
- A plot of a model metric over time
200+
- A slider to adjust the number of agents
201+
202+
You can also create custom visualization components using Matplotlib. For more advanced usage and customization options, please refer to the [visualization tutorial](tutorials/visualization_tutorial).
203+
204+
### Further resources
205+
To further explore Mesa and its features, we have the following resources available:
206+
207+
#### Tutorials
208+
- [Introductory Tutorial](tutorials/intro_tutorial): Learn how to create your first Mesa model.
209+
- [Visualization Tutorial](tutorials/visualization_tutorial.html): Learn how to create interactive visualizations for your models.
210+
211+
#### API documentation
212+
- [Mesa API reference](apis): Detailed documentation of Mesa's classes and functions.
213+
214+
#### Example models
215+
- [Mesa Examples repository](https://github.com/projectmesa/mesa-examples): A collection of example models demonstrating various Mesa features and modeling techniques.
216+
217+
#### Migration guide
218+
- [Mesa 3.0 Migration guide](migration_guide): If you're upgrading from an earlier version of Mesa, this guide will help you navigate the changes in Mesa 3.0.
219+
220+
#### Source Ccode and development
221+
- [Mesa GitHub repository](https://github.com/projectmesa/mesa): Access the full source code of Mesa, contribute to its development, or report issues.
222+
- [Mesa release notes](https://github.com/projectmesa/mesa/releases): View the detailed changelog of Mesa, including all past releases and their features.
223+
224+
#### Community and support
225+
- [Mesa GitHub Discussions](https://github.com/projectmesa/mesa/discussions): Join discussions, ask questions, and connect with other Mesa users.
226+
- [Matrix Chat](https://matrix.to/#/#project-mesa:matrix.org): Real-time chat for quick questions and community interaction.
227+
228+
Enjoy modelling with Mesa, and feel free to reach out!

0 commit comments

Comments
 (0)