Skip to content

fix: accept numpy arrays and pandas Series as select_random weights - #3989

Merged
quaquel merged 2 commits into
mesa:mainfrom
SahilKumar75:fix/select-random-array-weights
Nov 10, 2026
Merged

quaquel merged 2 commits into
mesa:mainfrom
SahilKumar75:fix/select-random-array-weights

Conversation

@SahilKumar75

Copy link
Copy Markdown
Contributor

Pre-PR checklist

  • This pull request is a bug fix, not a new feature.
  • New tests were added for the fixed behaviour.
  • ruff and the pre-commit hooks pass locally.

Summary

AgentSet.select_random advertises weights as a sequence of floats, but it rejects two of the most natural containers in a numpy based library: numpy.ndarray and pandas.Series. Passing either raises an opaque TypeError, so weighted (roulette wheel / fitness proportional) selection fails for anyone who computes weights with numpy or pandas.

Bug description

_resolve_weights in mesa/agentset.py dispatches on the weights type and only treats a value as numeric weights when it is a collections.abc.Sequence:

elif isinstance(weights, Sequence):
    ...
else:
    raise TypeError(f"Unsupported weights type: {type(weights).__name__}. ...")

AgentSet.select_random rejected numpy arrays and pandas Series passed as
weights, because _resolve_weights only accepted collections.abc.Sequence.
This was inconsistent with AgentSet.set, which already accepts list, tuple,
numpy.ndarray and pandas.Series, so a get -> compute weights with numpy ->
select_random round trip failed with an opaque TypeError.

Accept ndarray and Series in _resolve_weights alongside Sequence. The
existing length, finiteness, non-negativity and positive-sum checks are
unchanged. Added regression tests for array-like weights and the length
mismatch case.
@github-actions github-actions Bot added the testing Release notes label label Oct 26, 2026
@mesa-triage-bot

Copy link
Copy Markdown

The current weights helper rejects both containers, as described. Could you share a small example from the model or workflow where you encountered this, showing how the weights are computed and passed to select_random? That would connect the regression tests to the modelling use case.


Automated triage note, written by an AI model for the Mesa maintainers. It can be wrong, and it doesn't make decisions: maintainers do. If it missed the point, say so here.

@quaquel quaquel added the enhancement Release notes label label Nov 10, 2026
@quaquel
quaquel merged commit 25239c4 into mesa:main Nov 10, 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

enhancement Release notes label testing Release notes label

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants