Skip to content

Fix ValueError in get_k_nearest_agents when k >= number of agents - #3671

Merged
quaquel merged 6 commits into
mesa:mainfrom
Vartika222:fix-k-nearest-agents-crash
May 19, 2026
Merged

quaquel merged 6 commits into
mesa:mainfrom
Vartika222:fix-k-nearest-agents-crash

Conversation

@Vartika222

@Vartika222 Vartika222 commented Mar 31, 2026 •

Copy link
Copy Markdown
Contributor

Pre-PR Checklist

  • This PR is a bug fix, not a new feature or enhancement.

Summary

get_k_nearest_agents crashed when k >= n (number of agents) or the space was empty, due to np.argpartition receiving an out-of-range index.

Bug / Issue

Two problems:

  • No guard against k >= n or empty space, causing np.argpartition to raise a ValueError
  • Off-by-one: np.argpartition takes a zero-based index so it should be k-1, not k

Implementation

  • Early return for empty space or k <= 0
  • Clamp k to n when k > n, with a UserWarning so the caller knows
  • Fix np.argpartition(dists, k-1)
  • Update docstring to document the k > n behaviour

Testing

Four new tests: k > n (checks warning too), empty space, k=0, and k exactly equal to population. All existing tests pass.

Additional Notes

Also removed an unrelated line that had crept into test_examples_viz.py, and aligned new tests to use Model(rng=42) / model.random per reviewer feedback.

@github-actions

Copy link
Copy Markdown

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🔵 -2.4% [-2.9%, -1.9%] 🔵 +0.8% [+0.5%, +1.0%]
BoltzmannWealth large 🔵 -1.2% [-2.2%, +0.1%] 🟢 -5.3% [-6.4%, -4.2%]
Schelling small 🔵 -1.9% [-2.9%, -0.9%] 🔵 -0.3% [-1.5%, +0.8%]
Schelling large 🔵 -0.9% [-3.1%, +1.3%] 🔵 +0.3% [-1.3%, +1.8%]
WolfSheep small 🟢 -5.3% [-6.0%, -4.6%] 🔵 -0.5% [-4.9%, +3.6%]
WolfSheep large 🔵 -1.7% [-2.8%, -0.5%] 🔵 +1.7% [-0.2%, +3.9%]
SugarscapeG1mt small 🔵 -2.5% [-3.3%, -1.8%] 🔵 -2.3% [-3.8%, -0.8%]
SugarscapeG1mt large 🔵 +1.8% [-0.4%, +3.8%] 🔵 -0.2% [-1.6%, +1.2%]
BoidFlockers small 🔵 -0.1% [-0.9%, +0.6%] 🔵 +0.6% [-0.1%, +1.1%]
BoidFlockers large 🔵 -1.0% [-2.6%, +0.5%] 🔵 -1.6% [-2.6%, -0.5%]

@codebreaker32

codebreaker32 commented Apr 1, 2026 •

Copy link
Copy Markdown
Collaborator

This description is unclear and looks AI-generated, Please update it

@Vartika222

Copy link
Copy Markdown
Contributor Author

This description is unclear and looks AI-generated, Please update it

fixed

@codebreaker32

Copy link
Copy Markdown
Collaborator

Please write a proper description following our PR template

self.agent_positions: (
np.array
) # a view on _agent_positions containing all active positions
self.agent_positions = self._agent_positions[0:0]

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.

why?

display(space_viz)
page_session.wait_for_selector("img")
changed_space = page_session.locator("img").first.screenshot()
changed_space = page_session.locator("img").last.screenshot()

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.

please remove this change. It is unrelated to the PR.

Comment on lines +498 to +500
model = Model()
space = ContinuousSpace([[0, 10], [0, 10]], random=Random(42))

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.

Suggested change
model = Model()
space = ContinuousSpace([[0, 10], [0, 10]], random=Random(42))
model = Model(rng=42)
space = ContinuousSpace([[0, 10], [0, 10]], random=model.random)

also remove import random from the top.


def test_continuous_space_k_empty_space():
"""Test that empty space returns no agents."""
space = ContinuousSpace([[0, 10], [0, 10]], random=Random(42))

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.

same here

Comment on lines +525 to +527
model = Model()
space = ContinuousSpace([[0, 10], [0, 10]], random=Random(42))

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.

same here

Comment on lines +539 to +541
model = Model()
space = ContinuousSpace([[0, 10], [0, 10]], random=Random(42))

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.

same here

@Vartika222

Copy link
Copy Markdown
Contributor Author

Please write a proper description following our PR template

fixed

@quaquel
quaquel merged commit 9780c9f into mesa:main May 19, 2026
11 checks passed
EwoutH pushed a commit that referenced this pull request Oct 28, 2026
)

* Fix run_model_test capturing initial image instead of updated visualization

* Fix ValueError in get_k_nearest_agents when k >= number of agents

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fix k>=n and empty space handling in ContinuousSpace

* Address review feedback: add warning for k>n, fix test setup, remove unrelated viz change

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Jan Kwakkel <[email protected]>
(cherry picked from commit 9780c9f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Release notes label

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants