Skip to content

Ensure Unique unique_id Values When Adding Agents to AgentSetPolars #142

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
8 changes: 7 additions & 1 deletion mesa_frames/concrete/polars/agentset.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,13 @@ def add(
if isinstance(obj._mask, pl.Series):
original_active_indices = obj._agents.filter(obj._mask)["unique_id"]

obj._agents = pl.concat([obj._agents, new_agents], how="diagonal_relaxed")
combined_agents = pl.concat([obj._agents, new_agents], how="diagonal_relaxed")
if combined_agents["unique_id"].is_duplicated().any():
raise ValueError(
"Some ids are duplicated in the AgentSet that are trying to be added together."
)

obj._agents = combined_agents

if isinstance(obj._mask, pl.Series):
obj._update_mask(original_active_indices, new_agents["unique_id"])
Expand Down
19 changes: 19 additions & 0 deletions tests/polars/test_agentset_polars.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,17 @@ def fix1_AgentSetPolars() -> ExampleAgentSetPolars:
return agents


@pytest.fixture
def fix4_AgentSetPolars() -> ExampleAgentSetPolars:
model = ModelDF()
agents = ExampleAgentSetPolars(model)
agents.add({"unique_id": [0, 1, 2, 3]})
agents["wealth"] = agents.starting_wealth
agents["age"] = [10, 20, 30, 40]
model.agents.add(agents)
return agents


@pytest.fixture
def fix2_AgentSetPolars() -> ExampleAgentSetPolars:
model = ModelDF()
Expand Down Expand Up @@ -73,9 +84,17 @@ def test_add(
self,
fix1_AgentSetPolars: ExampleAgentSetPolars,
fix2_AgentSetPolars: ExampleAgentSetPolars,
fix4_AgentSetPolars: ExampleAgentSetPolars,
):
agents = fix1_AgentSetPolars
agents2 = fix2_AgentSetPolars
agents4 = fix4_AgentSetPolars

with pytest.raises(
ValueError,
match="Some ids are duplicated in the AgentSet that are trying to be added together.",
):
result = agents.add(agents4.agents, inplace=False)

# Test with a DataFrame
result = agents.add(agents2.agents, inplace=False)
Expand Down