Skip to content

Commit 2154cb1

Browse files
committed
model.agents: Store agents in nested dict keys
This commit introduces dics nested into a single defaultdict for agent storage, using agent instances as inner keys and None as inner values. The decision is based on: 1. Determinism: A dictionary ensures deterministic behavior for reproducible research outcomes. 2. Performance: Benchmarks showed that dictionaries offer a good balance between performance and functionality, especially in models with frequent agent updates. 3. Usability and Explicitness: While the use of None values is unconventional, this approach is practical and avoids the complexity of nested structures or external dependencies. It aligns with clear and explicit coding practices, making the framework more accessible and maintainable. The choice of a defaultdict with None values addresses the need for deterministic behavior, performance efficiency, and clarity in implementation. Additional utility functions like `select_agents()` will be added to enhance usability. Discussion for historical reference: #1894 (comment)
1 parent a8bb15f commit 2154cb1

File tree

2 files changed

+5
-4
lines changed

2 files changed

+5
-4
lines changed

mesa/agent.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,11 +42,11 @@ def __init__(self, unique_id: int, model: Model) -> None:
4242
self.pos: Position | None = None
4343

4444
# Register the agent with the model using defaultdict
45-
self.model.agents[type(self)].append(self)
45+
self.model.agents[type(self)][self] = None
4646

4747
def remove(self) -> None:
4848
"""Remove and delete the agent from the model."""
49-
self.model.agents[type(self)].remove(self)
49+
self.model.agents[type(self)].pop(self)
5050

5151
def step(self) -> None:
5252
"""A single step of the agent."""

mesa/model.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,8 @@ class Model:
2727
running: A boolean indicating if the model should continue running.
2828
schedule: An object to manage the order and execution of agent steps.
2929
current_id: A counter for assigning unique IDs to agents.
30-
agents: A defaultdict mapping each agent type to a list of its instances.
30+
agents: A defaultdict mapping each agent type to a dict of its instances.
31+
Agent instances are saved in the nested dict keys, with the values being None.
3132
"""
3233

3334
def __new__(cls, *args: Any, **kwargs: Any) -> Any:
@@ -50,7 +51,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:
5051
self.running = True
5152
self.schedule = None
5253
self.current_id = 0
53-
self.agents: defaultdict[type, list] = defaultdict(list)
54+
self.agents: defaultdict[type, dict] = defaultdict(dict)
5455

5556
@property
5657
def agent_types(self) -> list:

0 commit comments

Comments
 (0)