Skip to content

feat(agentset): add select_random with uniform and weighted sampling … - #3799

Merged
quaquel merged 5 commits into
mesa:mainfrom
Dilraj07:feature/agentset-select-random
Aug 25, 2026
Merged

quaquel merged 5 commits into
mesa:mainfrom
Dilraj07:feature/agentset-select-random

Conversation

@Dilraj07

Copy link
Copy Markdown
Contributor

Summary

Closes #3746.

Adds a first-class select_random() method to AbstractAgentSet (and all inheriting AgentSet subclasses), enabling:

  1. $\mathcal{O}(k)$ Uniform Random Sampling: Directly samples $k$ agents without the $O(N)$ overhead of full population shuffles (shuffle().select()).
  2. Weighted Selection: Supports fitness-proportionate / roulette-wheel selection, softmax exploration, and weighted agent sampling.

Changes Made

  • mesa/agentset.py (AbstractAgentSet.select_random):
    • Uniform without replacement: $\mathcal{O}(k)$ via self.random.sample.
    • Uniform & Weighted with replacement via self.random.choices.
    • Weighted without replacement via Efraimidis & Spirakis (A-Res) algorithm (k_i = u_i^{1/w_i} where $u_i \sim U(0, 1)$), preserving 100% reproducibility using self.random.
    • Flexible weights support: agent attribute name (str), callable/lambda (Callable), or numerical sequence (Sequence).
    • Supports discrete integer counts ($n \ge 1$) and fractional percentages ($n \in (0, 1]$).
    • Supports inplace=True and inplace=False.
  • tests/test_agentset.py:
    • Added 10 unit tests covering uniform, fractional, with/without replacement, attribute/callable/sequence weights, inplace mutation, error edge cases, and a multi-generation Evolutionary ABM scenario.

Benchmark & Verification

1. Complexity Comparison ($k=5$ sampled)

Population ($N$) Sample Size ($k$) shuffle().select() select_random() Speedup
100 5 0.022 ms 0.003 ms 7.7x
1,000 5 0.302 ms 0.005 ms 64.8x
10,000 5 2.883 ms 0.007 ms 431.3x
100,000 5 38.884 ms 0.007 ms 5,537.4x

2. Verification Visuals

sampling_benchmark_and_distribution image

GSoC Contributor Checklist

Context & motivation

In Agent-Based Modeling and evolutionary/probabilistic simulations, selecting agents proportional to fitness, traits, or connection weights is a fundamental operation. Previously, Mesa lacked weighted selection and required chaining shuffle().select(at_most=k) for uniform subsets, which forces an O(N) full shuffle and intermediate set allocation. This PR adds direct uniform and weighted sampling to AbstractAgentSet.

What I learned

I deepened my understanding of Mesa's AbstractAgentSet design, weak reference handling in collections, and the Efraimidis-Spirakis algorithm for reproducible weighted reservoir sampling without replacement.

Readiness checks

  • This PR addresses an agreed-upon problem (linked issue Add random / weighted sampling to AgentSet #3746)
  • I have read the contributing guide and deprecation policy
  • I have performed a self-review of my code
  • Tests pass locally (pytest tests/test_agentset.py)
  • Code is formatted (ruff check . --fix)

@github-actions

Copy link
Copy Markdown

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🔵 -2.1% [-2.8%, -1.5%] 🔵 -1.5% [-1.7%, -1.3%]
BoltzmannWealth large 🔵 +0.6% [+0.2%, +1.1%] 🔵 +4.7% [+2.9%, +6.5%]
Schelling small 🔵 -2.8% [-3.5%, -2.1%] 🔵 -2.0% [-2.8%, -1.1%]
Schelling large 🔵 +0.5% [-0.2%, +1.3%] 🔵 +5.0% [+3.0%, +6.8%]
WolfSheep small 🔵 -1.4% [-2.1%, -0.8%] 🔵 +3.4% [-0.4%, +6.8%]
WolfSheep large 🔵 -0.9% [-2.0%, +0.2%] 🔵 +0.7% [-1.0%, +2.0%]
SugarscapeG1mt small 🔵 -0.1% [-0.7%, +0.5%] 🔵 +0.7% [-0.9%, +2.3%]
SugarscapeG1mt large 🟢 -4.9% [-6.0%, -3.8%] 🔵 -1.8% [-3.4%, -0.1%]
BoidFlockers small 🔵 -0.9% [-1.4%, -0.4%] 🔵 +0.4% [+0.0%, +0.8%]
BoidFlockers large 🔵 -0.7% [-1.6%, +0.3%] 🔵 +0.6% [+0.4%, +0.7%]

@quaquel quaquel added the enhancement Release notes label label Aug 18, 2026
Comment thread mesa/agentset.py Resolved
Comment thread mesa/agentset.py Resolved

@quaquel quaquel left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I added some comments. Also, what explains the clear performance difference?

@Dilraj07

Copy link
Copy Markdown
Contributor Author

I added some comments. Also, what explains the clear performance difference?

Thanks for the review!

Regarding the performance difference:

1. Microbenchmark (select_random(k) vs shuffle().select(at_most=k)):

  • shuffle().select() shuffles the entire population (O(N)) and allocates an intermediate AgentSet of size N before slicing k agents.
  • select_random(k) uses Python's random.sample() under the hood, sampling only k agents directly in O(k) time without shuffling the rest or creating intermediate sets.
  • Because of this, sampling k=5 takes almost constant time (~0.007 ms) regardless of population size (100 vs 100,000 agents).

2. CI Benchmark Bot:

  • The CI bot benchmarks standard example models (Schelling, Sugarscape, etc.), which don't call select_random yet. The small ±1–4% variations are just standard GitHub Actions runner noise.

Dilraj07 and others added 2 commits August 18, 2026 21:21
- Move weight resolution and validation to private _resolve_weights helper
- Raise ValueError for n <= 0, empty AgentSet, and n > len(agentset) when replace=False
- Update unit tests to verify new validation rules
@quaquel

quaquel commented Aug 19, 2026

Copy link
Copy Markdown
Member

Are there places in the examples were we could already use this code?

@Dilraj07

Copy link
Copy Markdown
Contributor Author

Are there places in the examples were we could already use this code?

Most mesa-examples currently cache .to_list() outside their step() loops (e.g., deffuant_weisbuch). Since select_random() still uses .to_list() internally, replacing those with select_random() inside the loop would actually be slower by reallocating lists $N$ times.

However, select_random() immediately improves two key areas:

1. Fixing Deprecation Warnings (e.g., bank_reserves)
Currently, bank_reserves uses random.choice(self.cell.agents). Since self.cell.agents is an AgentSet, this triggers a sequence __getitem__ deprecation warning. select_random() provides a clean, warning-free native alternative:

neighbors = self.cell.agents.select(lambda a: a != self)
if len(neighbors) > 0:
    customer, = neighbors.select_random(1)

2. Weighted Agent Sampling
We lack evolutionary models in mesa-examples mostly because extracting agents and fitnesses to use random.choices was annoying. Now we can easily support these models directly via self.agents.select_random(k, weights="fitness").

@quaquel

quaquel commented Aug 25, 2026

Copy link
Copy Markdown
Member

I meant the examples that ship with Mesa itself, but we can leave that for a future PR as well.

@quaquel
quaquel merged commit 1dc02d2 into mesa:main Aug 25, 2026
11 checks passed
@EwoutH EwoutH mentioned this pull request Nov 15, 2026
53 of 65 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement Release notes label

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add random / weighted sampling to AgentSet

2 participants