Skip to content

Commit

Permalink
fixes weakref bug in shuffe_do (#2399)
Browse files Browse the repository at this point in the history
* fixes weakref bug in shuffe_do

if one agent removes another agent, it could still be activated by shuffle_do. This adds a unit test to spot the bug and contains the fix.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
quaquel and pre-commit-ci[bot] authored Oct 22, 2024
1 parent 470ab0a commit 3c0cd62
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 6 deletions.
14 changes: 8 additions & 6 deletions mesa/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,15 +294,17 @@ def shuffle_do(self, method: str | Callable, *args, **kwargs) -> AgentSet:
It's a fast, optimized version of calling shuffle() followed by do().
"""
agents = list(self._agents.keys())
self.random.shuffle(agents)
weakrefs = list(self._agents.keyrefs())
self.random.shuffle(weakrefs)

if isinstance(method, str):
for agent in agents:
getattr(agent, method)(*args, **kwargs)
for ref in weakrefs:
if (agent := ref()) is not None:
getattr(agent, method)(*args, **kwargs)
else:
for agent in agents:
method(agent, *args, **kwargs)
for ref in weakrefs:
if (agent := ref()) is not None:
method(agent, *args, **kwargs)

return self

Expand Down
23 changes: 23 additions & 0 deletions tests/test_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -472,6 +472,29 @@ def test_method(self):
original_order != shuffled_order
), "The order should be different after shuffle_do"

class AgentWithRemove(Agent):
def __init__(self, model):
super().__init__(model)
self.is_alive = True

def remove(self):
super().remove()
self.is_alive = False

def step(self):
if not self.is_alive:
raise Exception

agent_to_remove = self.random.choice(self.model.agents)

if agent_to_remove is not self:
agent_to_remove.remove()

model = Model(seed=32)
for _ in range(100):
AgentWithRemove(model)
model.agents.shuffle_do("step")


def test_agentset_get_attribute():
"""Test AgentSet.get for attributes."""
Expand Down

0 comments on commit 3c0cd62

Please sign in to comment.