Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Add optimized shuffle_do() method to AgentSet #2283

Merged
merged 5 commits into from
Sep 21, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
2 changes: 1 addition & 1 deletion benchmarks/BoltzmannWealth/boltzmann_wealth.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def __init__(self, seed=None, n=100, width=10, height=10):

def step(self):
"""Run the model for a single step."""
self.agents.shuffle().do("step")
self.agents.shuffle_do("step")
# collect data
self.datacollector.collect(self)

Expand Down
4 changes: 2 additions & 2 deletions benchmarks/WolfSheep/wolf_sheep.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,8 +227,8 @@ def __init__(

def step(self):
"""Run one step of the model."""
self.agents_by_type[Sheep].shuffle(inplace=True).do("step")
self.agents_by_type[Wolf].shuffle(inplace=True).do("step")
self.agents_by_type[Sheep].shuffle_do("step")
self.agents_by_type[Wolf].shuffle_do("step")


if __name__ == "__main__":
Expand Down
13 changes: 13 additions & 0 deletions mesa/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,19 @@ def do(self, method: str | Callable, *args, **kwargs) -> AgentSet:

return self

def shuffle_do(self, method: str | Callable, *args, **kwargs) -> AgentSet:
agents = list(self._agents.keys())
self.random.shuffle(agents)

if isinstance(method, str):
for agent in agents:
getattr(agent, method)(*args, **kwargs)
else:
for agent in agents:
method(agent, *args, **kwargs)

return self

def map(self, method: str | Callable, *args, **kwargs) -> list[Any]:
"""Invoke a method or function on each agent in the AgentSet and return the results.

Expand Down
2 changes: 1 addition & 1 deletion mesa/experimental/devs/examples/epstein_civil_violence.py
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ def __init__(

def step(self):
"""Run one step of the model."""
self.active_agents.shuffle(inplace=True).do("step")
self.active_agents.shuffle_do("step")


if __name__ == "__main__":
Expand Down
4 changes: 2 additions & 2 deletions mesa/experimental/devs/examples/wolf_sheep.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,8 +230,8 @@ def __init__(

def step(self):
"""Perform one step of the model."""
self.agents_by_type[Sheep].shuffle(inplace=True).do("step")
self.agents_by_type[Wolf].shuffle(inplace=True).do("step")
self.agents_by_type[Sheep].shuffle_do("step")
self.agents_by_type[Wolf].shuffle_do("step")


if __name__ == "__main__":
Expand Down
36 changes: 36 additions & 0 deletions tests/test_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,42 @@ def test_agentset_map_callable():
assert all(i == entry for i, entry in zip(results, range(1, 11)))


def test_agentset_shuffle_do():
"""Test AgentSet.shuffle_do method."""
model = Model()

class TestAgentShuffleDo(Agent):
def __init__(self, model):
super().__init__(model)
self.called = False

def test_method(self):
self.called = True

agents = [TestAgentShuffleDo(model) for _ in range(100)]
agentset = AgentSet(agents, model)

# Test shuffle_do with a string method name
agentset.shuffle_do("test_method")
assert all(agent.called for agent in agents)

# Reset the called flag
for agent in agents:
agent.called = False

# Test shuffle_do with a callable
agentset.shuffle_do(lambda agent: setattr(agent, "called", True))
assert all(agent.called for agent in agents)

# Verify that the order is indeed shuffled
original_order = list(agentset)
shuffled_order = []
agentset.shuffle_do(lambda agent: shuffled_order.append(agent))
assert (
original_order != shuffled_order
), "The order should be different after shuffle_do"


def test_agentset_get_attribute():
"""Test AgentSet.get for attributes."""
model = Model()
Expand Down
Loading