Skip to content

Prevent zero weight agents from filling weighted samples - #3845

Merged
quaquel merged 2 commits into
mesa:mainfrom
SahilKumar75:fix-zero-weight-sampling
Sep 15, 2026
Merged

quaquel merged 2 commits into
mesa:mainfrom
SahilKumar75:fix-zero-weight-sampling

Conversation

@SahilKumar75

Copy link
Copy Markdown
Contributor

Note

Use this template for bug fixes only. For enhancements and new features, use the feature template and get maintainer approval in an issue or discussion before opening a PR.

Pre PR Checklist

  • This PR is a bug fix, not a new feature or enhancement.

Summary

Prevents weighted sampling without replacement from selecting agents whose weight is zero when too few agents have positive weights.

Bug / Issue

Closes #3844.

When the requested sample size exceeded the number of positive weights, the sampling algorithm used zero weight entries to fill the result. Those agents should have no chance of selection.

Implementation

Counts positive weights before weighted sampling without replacement. The method now raises a clear ValueError when the requested sample cannot be formed from agents with positive weights.

Testing

Added a regression test using one positive weight and two zero weights. The test verifies that requesting two agents raises the expected error.

Validation completed:

  • python3 -m pytest tests/test_agentset.py -q: 40 passed
  • ruff check mesa/agentset.py tests/test_agentset.py: passed
  • ruff format --check mesa/agentset.py tests/test_agentset.py: passed

Additional Notes

Sampling with replacement is unchanged.

@github-actions github-actions Bot added the testing Release notes label label Sep 8, 2026
@github-actions

github-actions Bot commented Sep 8, 2026

Copy link
Copy Markdown

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🔵 -1.0% [-2.1%, +0.1%] 🔴 +3.6% [+3.4%, +3.8%]
BoltzmannWealth large 🔵 -0.9% [-2.0%, +0.1%] 🟢 -8.0% [-11.0%, -5.1%]
Schelling small 🟢 -5.3% [-6.0%, -4.6%] 🔵 +1.0% [+0.2%, +1.9%]
Schelling large 🔵 -0.9% [-1.4%, -0.1%] 🟢 -8.5% [-9.7%, -7.4%]
WolfSheep small 🟢 -5.7% [-6.4%, -5.1%] 🔵 +1.7% [-2.0%, +5.7%]
WolfSheep large 🟢 -5.2% [-6.2%, -4.1%] 🟢 -11.8% [-14.7%, -9.0%]
SugarscapeG1mt small 🟢 -6.4% [-7.4%, -5.4%] 🔵 -2.6% [-4.1%, -1.1%]
SugarscapeG1mt large 🟢 -7.0% [-9.3%, -4.9%] 🔵 -2.5% [-3.8%, -0.9%]
BoidFlockers small 🔵 -0.2% [-1.0%, +0.8%] 🔵 +2.1% [+1.5%, +2.5%]
BoidFlockers large 🔵 +1.6% [+0.9%, +2.3%] 🔵 +1.6% [+1.3%, +1.9%]
MultiLevelAllianceModel small 🔵 +1.0% [-0.3%, +2.3%] 🔴 +5.9% [+5.2%, +6.5%]
MultiLevelAllianceModel large 🔵 -3.5% [-5.1%, -1.9%] 🔵 +2.1% [-2.1%, +6.9%]

@dietcoke-17 dietcoke-17 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for tracking this down and fixing it, @SahilKumar75 — nice work. Confirmed this is a real bug: zero-weight agents were getting a sort key of zero instead of being excluded, so they'd fill in when there weren't enough positive-weight agents to satisfy the sample size. Great Work and

A few things I'd like addressed before merging:
1.Naming: positive_weights holds a count, not the weights themselves. Suggest positive_weight_count to avoid confusion.
2.A mixed case with some zero and some positive weights, where positive count is sufficient — confirms the zero-weight agent is still never selected and no false-positive error fires. Right now we only test the failure path.

@shipitdev shipitdev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

thank you @SahilKumar75 for reporting and raising a PR

looking at the current implementation, using sum() adds the overhead of iterating through weights list twice, and then still keeping zero-weight agents in keys which forces the keys.sort() to sort thru all the zero weight entries which i think are unnecessary. a more efficient and cleaner way would be to just remove the else block entirely since the zero-weight agents have a 0% chance of being selected anyway, we dont even need to store them in keys in the first place. i believe this was implemented in #3799 (cc @quaquel) i just want to get your thoughts on this.

Comment thread mesa/agentset.py Outdated
if replace:
chosen = self.random.choices(items, weights=w, k=sample_size)
else:
positive_weights = sum(weight > 0 for weight in w)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

we could just do it all in a single pass like this:

# Efraimidis & Spirakis (A-Res) algorithm for weighted sampling without replacement
keys = []
for agent, wi in zip(items, w):
    if wi > 0:
        u = self.random.random()
        key = u ** (1.0 / wi)
        keys.append((key, agent))

if sample_size > len(keys):
    raise ValueError(
        f"Sample size ({sample_size}) cannot exceed the number of "
        f"agents with positive weights ({len(keys)}) when "
        "replace=False."
    )

keys.sort(key=lambda x: x[0], reverse=True)
chosen = [agent for _, agent in keys[:sample_size]]

that way we wouldn't need sum(), and keys.sort() only has to sort the agents that actually have a chance of being picked.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@dietcoke-17 please let me know your verdict after reading this as well :) Thank you

@SahilKumar75

Copy link
Copy Markdown
Contributor Author

Thanks for the reviews. I updated the implementation to build sampling keys only for agents with positive weights, so validation and sorting now use the filtered list in one pass. The count is named positive_weight_count, and I added a mixed case regression test confirming that sampling succeeds when enough positive weights exist while the zero weight agent remains excluded. All 41 focused AgentSet tests pass, and the modified files pass Ruff lint and format checks.

@quaquel quaquel added the bug Release notes label label Sep 15, 2026
@quaquel
quaquel merged commit 2a2a2b9 into mesa:main Sep 15, 2026
16 of 17 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Release notes label testing Release notes label

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Weighted sampling without replacement can select agents with zero weight

4 participants