Repository navigation
feat(agentset): add select_random with uniform and weighted sampling … - #3799
Conversation
|
Performance benchmarks:
|
quaquel
left a comment
There was a problem hiding this comment.
I added some comments. Also, what explains the clear performance difference?
Thanks for the review! Regarding the performance difference: 1. Microbenchmark (
2. CI Benchmark Bot:
|
- 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
|
Are there places in the examples were we could already use this code? |
Most However, 1. Fixing Deprecation Warnings (e.g., neighbors = self.cell.agents.select(lambda a: a != self)
if len(neighbors) > 0:
customer, = neighbors.select_random(1)2. Weighted Agent Sampling |
|
I meant the examples that ship with Mesa itself, but we can leave that for a future PR as well. |
Summary
Closes #3746.
Adds a first-class
select_random()method toAbstractAgentSet(and all inheritingAgentSetsubclasses), enabling:shuffle().select()).Changes Made
mesa/agentset.py(AbstractAgentSet.select_random):self.random.sample.self.random.choices.k_i = u_i^{1/w_i}where $u_i \sim U(0, 1)$), preserving 100% reproducibility usingself.random.str), callable/lambda (Callable), or numerical sequence (Sequence).inplace=Trueandinplace=False.tests/test_agentset.py:Benchmark & Verification
1. Complexity Comparison ($k=5$ sampled)
shuffle().select()select_random()2. Verification Visuals
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 toAbstractAgentSet.What I learned
I deepened my understanding of Mesa's
AbstractAgentSetdesign, weak reference handling in collections, and the Efraimidis-Spirakis algorithm for reproducible weighted reservoir sampling without replacement.Readiness checks
pytest tests/test_agentset.py)ruff check . --fix)