Skip to content

Bugfix in agentset to handle addition and removal correctly #1960

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Merged
merged 3 commits into from
Jan 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion mesa/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,12 @@ def do(
Returns:
AgentSet | list[Any]: The results of the method calls if return_results is True, otherwise the AgentSet itself.
"""
res = [getattr(agent, method_name)(*args, **kwargs) for agent in self._agents]
# we iterate over the actual weakref keys and check if weakref is alive before calling the method
res = [
getattr(agentref(), method_name)(*args, **kwargs)
for agentref in self._agents.keyrefs()
if agentref()
]

return res if return_results else self

Expand Down
45 changes: 45 additions & 0 deletions tests/test_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,26 @@ def get_unique_identifier(self):
return self.unique_id


class TestAgentDo(Agent):
def __init__(
self,
unique_id,
model,
):
super().__init__(unique_id, model)
self.agent_set = None

def get_unique_identifier(self):
return self.unique_id

def do_add(self):
agent = TestAgentDo(self.model.next_id(), self.model)
self.agent_set.add(agent)

def do_remove(self):
self.agent_set.remove(self)


def test_agent_removal():
model = Model()
agent = TestAgent(model.next_id(), model)
Expand Down Expand Up @@ -164,6 +184,31 @@ def test_agentset_do_method():
with pytest.raises(AttributeError):
agentset.do("non_existing_method")

# tests for addition and removal in do
# do iterates, so no error should be raised to change size while iterating
# related to issue #1595

# setup
n = 10
model = Model()
agents = [TestAgentDo(model.next_id(), model) for _ in range(n)]
agentset = AgentSet(agents, model)
for agent in agents:
agent.agent_set = agentset

agentset.do("do_add")
assert len(agentset) == 2 * n

# setup
model = Model()
agents = [TestAgentDo(model.next_id(), model) for _ in range(10)]
agentset = AgentSet(agents, model)
for agent in agents:
agent.agent_set = agentset

agentset.do("do_remove")
assert len(agentset) == 0


def test_agentset_get_attribute():
model = Model()
Expand Down