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

AgentSet: Add set method #2254

Merged
merged 4 commits into from
Aug 28, 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
15 changes: 15 additions & 0 deletions mesa/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,21 @@ def get(self, attr_names: str | list[str]) -> list[Any]:
for agent in self._agents
]

def set(self, attr_name: str, value: Any) -> AgentSet:
"""
Set a specified attribute to a given value for all agents in the AgentSet.

Args:
attr_name (str): The name of the attribute to set.
value (Any): The value to set the attribute to.

Returns:
AgentSet: The AgentSet instance itself, after setting the attribute.
"""
for agent in self:
setattr(agent, attr_name, value)
return self

def __getitem__(self, item: int | slice) -> Agent:
"""
Retrieve an agent or a slice of agents from the AgentSet.
Expand Down
24 changes: 24 additions & 0 deletions tests/test_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,30 @@ def remove_function(agent):
assert len(agentset) == 0


def test_agentset_set_method():
# Initialize the model and agents with and without existing attributes
class TestAgentWithAttribute(Agent):
def __init__(self, unique_id, model, age=None):
super().__init__(unique_id, model)
self.age = age

model = Model()
agents = [TestAgentWithAttribute(model.next_id(), model, age=i) for i in range(5)]
agentset = AgentSet(agents, model)

# Set a new attribute "health" and an existing attribute "age" for all agents
agentset.set("health", 100).set("age", 50).set("status", "active")

# Check if all agents have the "health", "age", and "status" attributes correctly set
for agent in agentset:
assert hasattr(agent, "health")
assert agent.health == 100
assert hasattr(agent, "age")
assert agent.age == 50
assert hasattr(agent, "status")
assert agent.status == "active"


def test_agentset_map_str():
model = Model()
agents = [TestAgent(model.next_id(), model) for _ in range(10)]
Expand Down
Loading