Skip to content

Fix get_nearest_neighbors returning k+1 agents for co-located agents - #3899

Closed
Shivansh1205 wants to merge 4 commits into
mesa:mainfrom
Shivansh1205:fix/continuous-nearest-neighbors-colocated
Closed

Shivansh1205 wants to merge 4 commits into
mesa:mainfrom
Shivansh1205:fix/continuous-nearest-neighbors-colocated

Conversation

@Shivansh1205

@Shivansh1205 Shivansh1205 commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Pre-PR Checklist

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

Summary

ContinuousSpaceAgent.get_nearest_neighbors(k) could return k + 1 neighbors when more than k other agents share the querying agent's position.

Bug / Issue

Fixes #3898

The method requests the k + 1 nearest agents and drops self, assuming self is always among them. With co-located agents, more than k + 1 agents are at distance 0. np.argpartition may then pick k + 1 of them without self, so nothing is dropped and the caller gets k + 1 neighbors.

Implementation

Two parts:

  1. ContinuousSpaceAgent.get_nearest_neighbors: after filtering out self, truncate both the agents list and the distances array to k. self (distance 0) can only be missing from the k + 1 nearest when every returned agent is also at distance 0. Dropping the last one therefore still gives a correct k-nearest result. When self is present, the slice is a no-op.
  2. ContinuousSpace.get_k_nearest_agents: np.argpartition does not resolve ties deterministically, so which co-located agents came back could vary. The method now finds the k-th smallest distance, takes every agent strictly closer, and fills the remainder from the agents tied at that distance by internal index. It then sorts the result by distance with a stable sort. Results are now deterministic and sorted by distance. Ties break on the agent's internal index, which follows insertion order unless agents have been removed: removal moves the last agent into the freed slot. The docstring documents this.

Testing

  • test_get_nearest_neighbors_colocated_agents: places 5 agents at the same point and checks, for every agent and k in 1-3, that exactly k neighbors and k distances are returned, that self is excluded, that all distances are 0, and that the result is deterministic.
    • Fails before the change: assert 2 == 1 for agents whose self was crowded out.
  • test_get_k_nearest_agents_ties_deterministic: 30 agents, mostly co-located, checks that ties resolve on internal index and that results are sorted by distance.
  • ruff check / ruff format --check clean.

Additional Notes

get_k_nearest_agents now returns agents sorted by distance. Previously the order was unspecified. The set of agents returned is unchanged except for which tied agents are chosen.

get_nearest_neighbors asks the space for the k+1 nearest agents and then
drops the querying agent, assuming it is always among them. When more
than k other agents share the querying agent's position, all of them are
at distance 0 and argpartition may return k+1 of them without self, so
nothing is dropped and k+1 neighbors are returned.

Truncate the filtered result to k. This is correct because self is only
excluded when all k+1 returned agents are at distance 0.

Fixes mesa#3898
@github-actions github-actions Bot added experimental Release notes label testing Release notes label labels Sep 30, 2026
@github-actions

Copy link
Copy Markdown

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🔵 +0.4% [-0.0%, +0.8%] 🔵 +0.7% [+0.5%, +1.0%]
BoltzmannWealth large 🔵 +1.0% [+0.6%, +1.4%] 🔵 +0.3% [-0.4%, +1.1%]
Schelling small 🔵 +1.7% [+1.2%, +2.2%] 🔵 +0.7% [-0.2%, +1.6%]
Schelling large 🔵 +0.6% [+0.1%, +1.2%] 🔵 -0.4% [-2.5%, +1.2%]
WolfSheep small 🔵 +1.4% [+0.9%, +2.0%] 🔵 -2.4% [-6.5%, +1.8%]
WolfSheep large 🔵 +1.1% [+0.5%, +1.7%] 🔵 +0.3% [-1.3%, +1.6%]
SugarscapeG1mt small 🔴 +3.6% [+3.2%, +4.1%] 🔵 -0.2% [-2.0%, +1.5%]
SugarscapeG1mt large 🔵 +1.5% [+0.4%, +2.5%] 🔵 +2.2% [+0.3%, +4.2%]
BoidFlockers small 🔵 -2.0% [-2.4%, -1.5%] 🔵 -1.5% [-2.0%, -1.0%]
BoidFlockers large 🔵 -2.0% [-2.3%, -1.7%] 🔵 -0.7% [-1.0%, -0.4%]
MultiLevelAllianceModel small 🔵 -1.0% [-2.2%, +0.3%] 🔵 -0.2% [-0.7%, +0.4%]
MultiLevelAllianceModel large 🔵 -0.9% [-2.1%, +0.3%] 🔵 -0.9% [-1.9%, +0.2%]

Shivansh1205 and others added 2 commits October 6, 2026 12:35
np.argpartition does not resolve ties deterministically, so truncating
the k+1 nearest to k depended on argpartition internals. Select the k
nearest by (distance, insertion index) and return them sorted, which
matches the documented tie rule of get_k_nearest_agents and makes the
truncation in get_nearest_neighbors well defined.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Removing an agent moves the last agent into the freed slot, so the
internal index only matches insertion order until an agent is removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@quaquel quaquel added the bug Release notes label label Oct 20, 2026
indices = np.concatenate([closer, tied])
# sort by distance, with internal index as tie-breaker
indices = indices[np.argsort(dists[indices], kind="stable")]
agents = [agents[i] for i in indices]

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.

I think I understand what is going on, but what are the performance implications of this? Partition and argsort both involve a sort operation.


# np.argpartition expects zero-based index (k-1) and returns the indices of the k smallest distances
indices = np.argpartition(dists, k - 1)[:k]
# np.argpartition does not resolve ties deterministically, so we find the k-th

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.

where is your evidence for this claim. All I can find is that the default selection algorithm is unstable, not that it is not deterministic.

@quaquel

quaquel commented Oct 24, 2026

Copy link
Copy Markdown
Member

closing this as stale

@quaquel quaquel closed this Oct 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Release notes label experimental Release notes label testing Release notes label

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ContinuousSpaceAgent.get_nearest_neighbors returns k+1 neighbors when agents share a position

2 participants