Skip to content

Commit 09cfde8

Browse files
authored
docs: Split off the overview page, extend with spaces/activation (#2673)
* docs: Split off the overview to a separate page Based on feedback from the paper, this splits the overview (again) off to a separate page. It does add one more item to the top bar, but I think that's worth it. * docs: Add space and time advancement sections to overview Expand the Mesa overview documentation to fully cover all core features: - Add comprehensive section on spaces including grid-based, network, and Voronoi spaces, with code examples - Add section on property layers and continuous space functionality - Add new section on time advancement covering basic steps, agent activation patterns, and event-based scheduling - Include practical code examples demonstrating each feature - Maintain consistency with existing documentation style and structure This update brings the overview in line with Mesa's paper, ensuring all major features are properly documented in one place.
1 parent e7660ee commit 09cfde8

File tree

3 files changed

+304
-218
lines changed

3 files changed

+304
-218
lines changed

docs/getting_started.md

+2-218
Original file line numberDiff line numberDiff line change
@@ -3,232 +3,16 @@ Mesa is a modular framework for building, analyzing and visualizing agent-based
33

44
**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.
55

6-
76
## Tutorials
8-
If you want to get a quick start on how to build agent based models with MESA, check the tutorials:
7+
If you want to get a quick start on how to build agent based models with MESA, check the overview and tutorials:
98

9+
- [Overview of the MESA library](overview): Learn about the core concepts and components of Mesa.
1010
- [Introductory Tutorial](tutorials/intro_tutorial): Learn how to create your first Mesa model.
1111
- [Visualization Tutorial](tutorials/visualization_tutorial): Learn how to create interactive visualizations for your models.
1212

1313
## Examples
1414
Mesa ships with a collection of example models. These are classic ABMs, so if you are familiar with ABMs and want to get a quick sense of how MESA works, these examples are great place to start. You can find them [here](examples).
1515

16-
17-
## Overview of the MESA library
18-
19-
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:
20-
21-
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.
22-
2. **Analysis:** Tools to collect data generated from your model, or to run it multiple times with different parameter values.
23-
3. **Visualization:** Classes to create and launch an interactive model visualization, using a browser-based interface.
24-
25-
### Modeling modules
26-
27-
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:
28-
29-
- [mesa.model](apis/model)
30-
- [mesa.agent](apis/agent)
31-
- [mesa.space](apis/space)
32-
33-
The skeleton of a model might look like this:
34-
35-
```python
36-
import mesa
37-
38-
class MyAgent(mesa.Agent):
39-
def __init__(self, model, age):
40-
super().__init__(model)
41-
self.age = age
42-
43-
def step(self):
44-
self.age += 1
45-
print(f"Agent {self.unique_id} now is {self.age} years old")
46-
# Whatever else the agent does when activated
47-
48-
class MyModel(mesa.Model):
49-
def __init__(self, n_agents):
50-
super().__init__()
51-
self.grid = mesa.space.MultiGrid(10, 10, torus=True)
52-
for _ in range(n_agents):
53-
initial_age = self.random.randint(0, 80)
54-
a = MyAgent(self, initial_age)
55-
coords = (self.random.randrange(0, 10), self.random.randrange(0, 10))
56-
self.grid.place_agent(a, coords)
57-
58-
def step(self):
59-
self.agents.shuffle_do("step")
60-
```
61-
62-
If you instantiate a model and run it for one step, like so:
63-
64-
```python
65-
model = MyModel(5)
66-
model.step()
67-
```
68-
69-
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.
70-
71-
72-
### AgentSet and model.agents
73-
Mesa 3.0 makes `model.agents` and the AgentSet class central in managing and activating agents.
74-
75-
#### model.agents
76-
`model.agents` is an AgentSet containing all agents in the model. It's automatically updated when agents are added or removed:
77-
78-
```python
79-
# Get total number of agents
80-
num_agents = len(model.agents)
81-
82-
# Iterate over all agents
83-
for agent in model.agents:
84-
print(agent.unique_id)
85-
```
86-
87-
#### AgentSet Functionality
88-
AgentSet offers several methods for efficient agent management:
89-
90-
1. **Selecting**: Filter agents based on criteria.
91-
```python
92-
high_energy_agents = model.agents.select(lambda a: a.energy > 50)
93-
```
94-
2. **Shuffling and Sorting**: Randomize or order agents.
95-
```python
96-
shuffled_agents = model.agents.shuffle()
97-
sorted_agents = model.agents.sort(key="energy", ascending=False)
98-
```
99-
3. **Applying methods**: Execute methods on all agents.
100-
```python
101-
model.agents.do("step")
102-
model.agents.shuffle_do("move") # Shuffle then apply method
103-
```
104-
4. **Aggregating**: Compute aggregate values across agents.
105-
```python
106-
avg_energy = model.agents.agg("energy", func=np.mean)
107-
```
108-
5. **Grouping**: Group agents by attributes.
109-
```python
110-
grouped_agents = model.agents.groupby("species")
111-
112-
for _, agent_group in grouped_agents:
113-
agent_group.shuffle_do()
114-
species_counts = grouped_agents.count()
115-
mean_age_by_group = grouped_agents.agg("age", np.mean)
116-
```
117-
`model.agents` can also be accessed within a model instance using `self.agents`.
118-
119-
These are just some examples of using the AgentSet, there are many more possibilities, see the [AgentSet API docs](apis/agent).
120-
121-
### Analysis modules
122-
123-
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:
124-
125-
- [mesa.datacollection](apis/datacollection)
126-
- [mesa.batchrunner](apis/batchrunner)
127-
128-
You'd add a data collector to the model like this:
129-
130-
```python
131-
import mesa
132-
import numpy as np
133-
134-
# ...
135-
136-
class MyModel(mesa.Model):
137-
def __init__(self, n_agents):
138-
super().__init__()
139-
# ... (model initialization code)
140-
self.datacollector = mesa.DataCollector(
141-
model_reporters={"mean_age": lambda m: m.agents.agg("age", np.mean)},
142-
agent_reporters={"age": "age"}
143-
)
144-
145-
def step(self):
146-
self.agents.shuffle_do("step")
147-
self.datacollector.collect(self)
148-
```
149-
150-
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:
151-
152-
```python
153-
model = MyModel(5)
154-
for t in range(10):
155-
model.step()
156-
model_df = model.datacollector.get_model_vars_dataframe()
157-
agent_df = model.datacollector.get_agent_vars_dataframe()
158-
```
159-
160-
To batch-run the model while varying, for example, the n_agents parameter, you'd use the [`batch_run`](apis/batchrunner) function:
161-
162-
```python
163-
import mesa
164-
165-
parameters = {"n_agents": range(1, 6)}
166-
results = mesa.batch_run(
167-
MyModel,
168-
parameters,
169-
iterations=5,
170-
max_steps=100,
171-
data_collection_period=1,
172-
)
173-
```
174-
175-
The results are returned as a list of dictionaries, which can be easily converted to a pandas DataFrame for further analysis.
176-
177-
### Visualization
178-
Mesa now uses a new browser-based visualization system called SolaraViz. This allows for interactive, customizable visualizations of your models.
179-
180-
Note: SolaraViz is experimental and still in active development in Mesa 3.x. While we attempt to minimize them, there might be API breaking changes in minor releases.
181-
> **Note:** SolaraViz instantiates new models using `**model_parameters.value`, so all model inputs must be keyword arguments.
182-
183-
Ensure your model's `__init__` method accepts keyword arguments matching the `model_params` keys.
184-
185-
```python
186-
class MyModel(Model):
187-
def __init__(self, n_agents=10, seed=None):
188-
super().__init__(seed=seed)
189-
# Initialize the model with N agents
190-
```
191-
The core functionality for building your own visualizations resides in the [`mesa.visualization`](apis/visualization) namespace.
192-
193-
Here's a basic example of how to set up a visualization:
194-
195-
```python
196-
from mesa.visualization import SolaraViz, make_space_component, make_plot_component
197-
198-
199-
def agent_portrayal(agent):
200-
return {"color": "blue", "size": 50}
201-
202-
203-
model_params = {
204-
"N": {
205-
"type": "SliderInt",
206-
"value": 50,
207-
"label": "Number of agents:",
208-
"min": 10,
209-
"max": 100,
210-
"step": 1,
211-
}
212-
}
213-
214-
page = SolaraViz(
215-
MyModel,
216-
[
217-
make_space_component(agent_portrayal),
218-
make_plot_component("mean_age")
219-
],
220-
model_params=model_params
221-
)
222-
page
223-
```
224-
This will create an interactive visualization of your model, including:
225-
226-
- A grid visualization of agents
227-
- A plot of a model metric over time
228-
- A slider to adjust the number of agents
229-
230-
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).
231-
23216
## Further resources
23317
To further explore Mesa and its features, we have the following resources available:
23418

docs/index.md

+1
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ The original Mesa conference paper is [available here](http://conference.scipy.o
7474
:maxdepth: 7
7575
7676
Getting started <getting_started>
77+
Overview <overview>
7778
Examples <examples>
7879
Migration guide <migration_guide>
7980
API Documentation <apis/api_main>

0 commit comments

Comments
 (0)