Skip to content

Commit 221084d

Browse files
authored
Model: Replace get_agents_of_type method with agents_by_type property (#2267)
This PR replaces the Model method `get_agents_of_type()` with an `agents_by_type` property, which directly returns the dict. Instead of using: ```Python model.get_agents_of_type(Sheep) ``` You should now use: ```Python model.agents_of_type[Sheep] ``` Since we also use `agents` and not `get_agents`, it's more intuitive to directly have access to the object itself (in this case the `agents_by_type` dict). It's also is more concise and since you have full dict access, more flexible. Examples and tests are updated and an deprecation warning is added for `get_agents_of_type()`.
1 parent 002d3f4 commit 221084d

File tree

5 files changed

+38
-18
lines changed

5 files changed

+38
-18
lines changed

benchmarks/WolfSheep/wolf_sheep.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -227,8 +227,8 @@ def __init__(
227227
patch.move_to(cell)
228228

229229
def step(self):
230-
self.get_agents_of_type(Sheep).shuffle(inplace=True).do("step")
231-
self.get_agents_of_type(Wolf).shuffle(inplace=True).do("step")
230+
self.agents_by_type[Sheep].shuffle(inplace=True).do("step")
231+
self.agents_by_type[Wolf].shuffle(inplace=True).do("step")
232232

233233

234234
if __name__ == "__main__":

mesa/experimental/devs/examples/wolf_sheep.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -231,8 +231,8 @@ def __init__(
231231
self.grid.place_agent(patch, pos)
232232

233233
def step(self):
234-
self.get_agents_of_type(Sheep).shuffle(inplace=True).do("step")
235-
self.get_agents_of_type(Wolf).shuffle(inplace=True).do("step")
234+
self.agents_by_type[Sheep].shuffle(inplace=True).do("step")
235+
self.agents_by_type[Wolf].shuffle(inplace=True).do("step")
236236

237237

238238
if __name__ == "__main__":

mesa/model.py

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -33,11 +33,13 @@ class Model:
3333
Properties:
3434
agents: An AgentSet containing all agents in the model
3535
agent_types: A list of different agent types present in the model.
36+
agents_by_type: A dictionary where the keys are agent types and the values are the corresponding AgentSets.
3637
steps: An integer representing the number of steps the model has taken.
3738
It increases automatically at the start of each step() call.
3839
3940
Methods:
4041
get_agents_of_type: Returns an AgentSet of agents of the specified type.
42+
Deprecated: Use agents_by_type[agenttype] instead.
4143
run_model: Runs the model's simulation until a defined end condition is reached.
4244
step: Executes a single step of the model's simulation process.
4345
next_id: Generates and returns the next unique identifier for an agent.
@@ -106,24 +108,26 @@ def agent_types(self) -> list[type]:
106108
"""Return a list of all unique agent types registered with the model."""
107109
return list(self._agents_by_type.keys())
108110

109-
def get_agents_of_type(self, agenttype: type[Agent]) -> AgentSet:
110-
"""Retrieves an AgentSet containing all agents of the specified type.
111-
112-
Args:
113-
agenttype: The type of agent to retrieve.
114-
115-
Raises:
116-
KeyError: If agenttype does not exist
117-
111+
@property
112+
def agents_by_type(self) -> dict[type[Agent], AgentSet]:
113+
"""A dictionary where the keys are agent types and the values are the corresponding AgentSets."""
114+
return self._agents_by_type
118115

119-
"""
120-
return self._agents_by_type[agenttype]
116+
def get_agents_of_type(self, agenttype: type[Agent]) -> AgentSet:
117+
"""Deprecated: Retrieves an AgentSet containing all agents of the specified type."""
118+
warnings.warn(
119+
f"Model.get_agents_of_type() is deprecated, please replace get_agents_of_type({agenttype})"
120+
f"with the property agents_by_type[{agenttype}].",
121+
DeprecationWarning,
122+
stacklevel=2,
123+
)
124+
return self.agents_by_type[agenttype]
121125

122126
def _setup_agent_registration(self):
123127
"""helper method to initialize the agent registration datastructures"""
124128
self._agents = {} # the hard references to all agents in the model
125129
self._agents_by_type: dict[
126-
type, AgentSet
130+
type[Agent], AgentSet
127131
] = {} # a dict with an agentset for each class of agents
128132
self._all_agents = AgentSet([], self) # an agenset with all agents
129133

tests/test_model.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from mesa.agent import Agent
1+
from mesa.agent import Agent, AgentSet
22
from mesa.model import Model
33

44

@@ -53,3 +53,19 @@ class TestAgent(Agent):
5353
test_agent = TestAgent(model.next_id(), model)
5454
assert test_agent in model.agents
5555
assert type(test_agent) in model.agent_types
56+
57+
58+
def test_agents_by_type():
59+
class Wolf(Agent):
60+
pass
61+
62+
class Sheep(Agent):
63+
pass
64+
65+
model = Model()
66+
wolf = Wolf(1, model)
67+
sheep = Sheep(2, model)
68+
69+
assert model.agents_by_type[Wolf] == AgentSet([wolf], model)
70+
assert model.agents_by_type[Sheep] == AgentSet([sheep], model)
71+
assert len(model.agents_by_type) == 2

tests/test_time.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -320,7 +320,7 @@ def test_random_activation_counts(self):
320320
agent_types = model.agent_types
321321
for agent_type in agent_types:
322322
assert model.schedule.get_type_count(agent_type) == len(
323-
model.get_agents_of_type(agent_type)
323+
model.agents_by_type[agent_type]
324324
)
325325

326326
# def test_add_non_unique_ids(self):

0 commit comments

Comments
 (0)