Add random / weighted sampling to AgentSet
What's the problem this feature will solve?
AgentSet has no built-in way to draw a random sample of agents, and no way at all to do a weighted selection.
- Uniform random subset: you currently have to chain
agents.shuffle().select(at_most=n), which is non-obvious (it works becauseselecttakes the firstnafter a shuffle). - Weighted selection (pick agents with probability proportional to some attribute, e.g. fitness-proportional / roulette-wheel selection): there is no path through the AgentSet API at all. You have to drop down to raw primitives:
agents = model.agents.to_list()
weights = [a.fitness for a in agents]
chosen = model.random.choices(agents, weights=weights, k=2)
Weighted and random selection are very common ABM operations (selection by fitness, preferential attachment, random matching, sampling a subset to act each step), so it would be useful to have a first-class, reproducible method for them.
Describe the solution you'd like
A sampling method on AgentSet, for example:
# uniform, without replacement (returns an AgentSet)
model.agents.select_random(3)
# weighted by an attribute
model.agents.select_random(3, weights="fitness")
# weighted by a callable
model.agents.select_random(3, weights=lambda a: a.fitness ** 2)
# with replacement
model.agents.select_random(3, replace=True)
It would use the model's seeded RNG (self.random) so results stay reproducible, and return an AgentSet (consistent with select/shuffle). weights could accept a sequence, an attribute name, or a callable.
Open design questions for maintainers:
- Method name:
select_randomvssample(noteCellCollectionalready hasselect_random_agent). - Return type for
n == 1: anAgentSetof one, or the agent itself. weightsinput format (sequence / attribute name / callable , or a subset of these).
Are you planning to open a PR for this?
Yes, happy to open a PR once the API (name, signature, return type) is agreed.
Additional context
Self-contained and additive (no change to existing behavior). It would build on self.random (random.sample for uniform without replacement, random.choices for weighted/with replacement), so it stays reproducible. Mesa 4.0.0a0 / current main.
I disagree that the current approach, agents.shuffle().select(at_most=n), is not obvious. We carefully designed the AgentSet api to encourage this style of chaining.
However, I can see performance and API simplification arguments for still adding a direct select_random method which also would support weights in some way. So, if you are interested, why don't you show an example implementation and assess its performance relative to chaining?
Fair point on the chaining, you're right that shuffle().select(at_most=n) is idiomatic, and I'll drop the "non-obvious" framing.
That said, there are two concrete arguments for a direct method, and I prototyped it to check.
Performance. shuffle() does a full O(N) shuffle of all agents and builds an intermediate AgentSet, even when you only want a few; a direct random.sample / random.choices avoids that. The difference only really matters at scale. Median timings (stdlib random, seeded), taking the median across several runs since the small cases are noisy:
- N = 100,000, sample 5 (the common "pick a few agents from many" case): chaining ~190 ms vs
select_random~6 ms, i.e. consistently 20-35x faster across runs. - N = 100,000, sample 50,000: ~2.4x faster (stable).
- N = 1,000: both are in the tens-to-hundreds of microseconds and the gap is within measurement noise, so there's no meaningful perf argument at small sizes; the case is really about large populations.
Weights. This is the part chaining can't express at all. The weighted path works as expected (over 1000 single draws from agents with fitness [1, 1, 1, 1, 100], the fit=100 agent was selected 960 times), and it's reproducible (same seed gives the same draw).
Example implementation (would live on AbstractAgentSet):
def select_random(self, n=1, *, weights=None, replace=False):
items = self.to_list()
if weights is not None:
w = (
[getattr(a, weights) for a in items] if isinstance(weights, str)
else [weights(a) for a in items] if callable(weights)
else list(weights)
)
if replace:
chosen = self.random.choices(items, weights=w, k=n)
else:
# weighted sampling without replacement (Efraimidis-Spirakis)
keyed = sorted(
(
(self.random.random() ** (1 / wi) if wi > 0 else 0.0, i)
for i, wi in enumerate(w)
),
reverse=True,
)
chosen = [items[i] for _, i in keyed[:n]]
elif replace:
chosen = self.random.choices(items, k=n)
else:
chosen = self.random.sample(items, k=min(n, len(items)))
return AgentSet(chosen, self.random)
It uses the model's seeded self.random, so it stays reproducible. (Verified the edge cases too: n larger than the set clamps to all agents, an empty set returns an empty AgentSet.)
Open questions before I turn this into a PR:
- Name:
select_random? (CellCollectionhasselect_random_agent.) n == 1return: an AgentSet of one (consistent withselect), or the agent itself?weightsinput: support attribute-name + callable + sequence, or a subset?- For weighted-without-replacement I used Efraimidis-Spirakis; is that fine, or would you prefer with-replacement only, or a numpy-based approach via
self.rng?
If the approach looks good, I'll open a PR with tests.
Hi @quaquel,
Following up on your request to assess the performance relative to chaining and formalize the implementation, I have completed the design, implementation on AbstractAgentSet, and empirical testing.
Proposed Method Signature
def select_random(
self,
n: int | float = 1,
*,
weights: str | Callable[[A], float] | Sequence[float] | None = None,
replace: bool = False,
inplace: bool = False,
) -> AbstractAgentSet[A]:
Key Design Choices & Addressing Open Questions:
- Method Name (
select_random): Naturally complementsselect()and aligns withCellCollection.select_random_agent(). - Return Type: Always returns an
AbstractAgentSet(even for n=1) to maintain fluent method chaining (e.g.,model.agents.select_random(5, weights="fitness").do("step")). - Weights Support: Supports attribute names (
weights="fitness"), callables (weights=lambda a: a.fitness**2), and numerical sequences. - Fractional Sampling: Supports float n in (0, 1] (e.g.,
n=0.2selects 20% of the population), consistent withAgentSet.select(). - Reproducibility & Algorithms:
- Uniform without replacement:
self.random.sample(items, k=n)(O(k) selection). - Uniform / Weighted with replacement:
self.random.choices(items, weights=w, k=n). - Weighted without replacement: Efraimidis-Spirakis (A-Res) algorithm using
self.random.random(), ensuring exact probability weighting and 100% seeded reproducibility withself.random.
- Uniform without replacement:
- Inplace Support: Supports
inplace=Trueandinplace=False.
Empirical Verification & Benchmark
We ran benchmarks across population sizes N in [10^2, 10^5] comparing shuffle().select(at_most=5) (O(N)) vs select_random(n=5) (O(k)):
| 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 |
I have the implementation on AbstractAgentSet and full unit tests ready. If this design looks good to you, I'll open the PR!