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 group_by method to AgentSet for attribute-based grouping #2092

Closed
Closed
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
16 changes: 16 additions & 0 deletions mesa/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,22 @@ def __setstate__(self, state):
self.model = state["model"]
self._update(state["agents"])

def group_by(self, attr_name: str) -> dict:
"""
Group agents in the AgentSet based on the specified attribute.

Args:
attr_name (str): The name of the attribute to group agents by.

Returns:
dict: A dictionary where keys are attribute values and values are lists of agents with those attribute values.
"""
grouped_agents = defaultdict(list)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this not be a defaultdict(AgentSet)? Similar to the binning discussion, this would mimic pandas in that groupby returns a group identifier and an AgentSet with the agents in that group.

Copy link
Author

@ai-naymul ai-naymul Apr 19, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You raise a valid point regarding the return type of the group_by method. Changing the return type to defaultdict(AgentSet) would indeed align more closely with pandas' groupby functionality.

grouped_agents = defaultdict(AgentSet)

when adding agents to the groups:

for agent in self: attr_value = getattr(agent, attr_name, None) if attr_value not in grouped_agents: grouped_agents[attr_value] = AgentSet(model=self.model) grouped_agents[attr_value].add(agent)

Let me know whats your thought on these changes. Looking forward :)

for agent in self:
attr_value = getattr(agent, attr_name, None)
grouped_agents[attr_value].append(agent)
return grouped_agents

@property
def random(self) -> Random:
"""
Expand Down
14 changes: 14 additions & 0 deletions tests/test_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,3 +282,17 @@ def test_agentset_shuffle():
agentset = AgentSet(test_agents, model=model)
agentset.shuffle(inplace=True)
assert not all(a1 == a2 for a1, a2 in zip(test_agents, agentset))


def test_agentset_group_by():
model = Model()
agents = [TestAgent(model.next_id(), model) for _ in range(10)]
for i, agent in enumerate(agents):
agent.category = i % 2 # Assign categories 0 or 1
agentset = AgentSet(agents, model)

grouped = agentset.group_by("category")
assert len(grouped[0]) == 5
assert len(grouped[1]) == 5
assert all(agent.category == 0 for agent in grouped[0])
assert all(agent.category == 1 for agent in grouped[1])
Loading