mesa icon indicating copy to clipboard operation
mesa copied to clipboard

Weighted sampling without replacement can select agents with zero weight

Open SahilKumar75 opened this issue 2 months ago • 0 comments

Describe the bug

AgentSet.select_random() can select agents whose weight is zero when replace=False and the requested sample size exceeds the number of agents with positive weights. The weighted sampling algorithm assigns zero weight entries a key of zero, then includes those entries to fill the requested sample.

Expected behavior

An agent with zero weight should not be selected by weighted sampling. If the requested sample cannot be formed from agents with positive weights without replacement, the method should raise a clear ValueError.

To Reproduce

from random import Random

from mesa import Agent, Model
from mesa.agentset import AgentSet

model = Model()
agents = [Agent(model) for _ in range(3)]
agentset = AgentSet(agents, random=Random(7))

sampled = agentset.select_random(
    2,
    weights=[1.0, 0.0, 0.0],
    replace=False,
)

print([agents.index(agent) for agent in sampled])

This prints [0, 1], so an agent with zero weight is included.

Additional context

The issue affects weighted sampling without replacement. Sampling with replacement already excludes zero weight entries because it uses random.choices().

SahilKumar75 avatar Sep 08 '26 14:09 SahilKumar75