Skip to content

Fix find_nearest_cell on a toroidal HexGrid near the edges - #3979

Merged
quaquel merged 2 commits into
mesa:mainfrom
ARYAMANN7279:fix/hexgrid-torus-nearest-cell
Nov 30, 2026
Merged

quaquel merged 2 commits into
mesa:mainfrom
ARYAMANN7279:fix/hexgrid-torus-nearest-cell

Conversation

@ARYAMANN7279

Copy link
Copy Markdown
Contributor

Pre-PR Checklist

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

Summary

HexGrid.find_nearest_cell returns the wrong cell for points close to an edge of a toroidal grid, because the KD-tree does not know about the wrap-around.

Bug / Issue

The tree is built from the cell positions only. For torus=True the query point is wrapped into the grid, but the nearest cell can be on the other side of an edge, and the tree cannot see it. For example on a 4x4 torus, the point (0.0, 5.9) returns the cell at y=4.5, 1.4 away, while the cell across the top/bottom edge is 0.87 away. I did not find an existing issue for this. (#3958 and #3959 are about the odd-r/even-r layout, which is a separate thing. This is independent of that choice.)

I compared find_nearest_cell with a brute force search over wrapped distances for 2000 random points per grid. On 4x4, 6x4, 6x6, 8x2 and 4x8 torus grids, between 11% and 28% of the answers were wrong. The non-torus grids had none.

Implementation

KDTree supports periodic boundaries through boxsize. When torus=True the tree is now built with boxsize=(width * sqrt(3), height * 1.5), the same period that find_nearest_cell already uses to wrap the query. All cell positions lie inside that box, as the periodic tree requires.

Testing

New test test_hex_grid_torus_nearest_cell: 200 random points on a 4x6 torus, checking that the returned cell is at the minimum wrapped distance. It does not depend on the layout, so it still holds if #3959 changes the positions. It fails on main and passes with this change. tests/discrete_space passes (124 tests), and ruff check and ruff format are clean.

Additional Notes

I used an LLM assistant (Claude Code) to help find and fix this. I reproduced the bug myself and I can explain the change.

🤖 Generated with Claude Code

@github-actions github-actions Bot added the testing Release notes label label Oct 23, 2026

@dietcoke-17 dietcoke-17 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the clear write-up and for including the brute-force comparison. The diagnosis is right: a non-periodic KDTree can't see across the wrap, and passing boxsize when torus=True is the idiomatic fix. Non-torus behaviour is unchanged, and the test checks distance rather than cell identity, so it handles ties and doesn't depend on the layout (so it should survive #3959).

LGTM.

@github-actions

Copy link
Copy Markdown

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🔵 -1.5% [-2.3%, -0.8%] 🔵 +0.1% [-0.1%, +0.3%]
BoltzmannWealth large 🔵 +2.9% [+2.0%, +3.9%] 🔵 +4.7% [+1.4%, +8.0%]
Schelling small 🔵 +0.1% [-0.6%, +0.8%] 🔵 -0.9% [-1.8%, -0.1%]
Schelling large 🔵 +1.4% [+0.5%, +2.2%] 🔵 +4.2% [+0.9%, +7.6%]
WolfSheep small 🔵 +0.5% [+0.0%, +1.1%] 🔵 -1.3% [-5.3%, +2.9%]
WolfSheep large 🔵 +0.1% [-0.7%, +0.9%] 🔵 +0.1% [-2.3%, +2.4%]
SugarscapeG1mt small 🔵 -1.2% [-1.8%, -0.5%] 🔵 -1.5% [-3.3%, +0.0%]
SugarscapeG1mt large 🔵 -2.3% [-4.1%, -0.3%] 🔵 +1.4% [-0.6%, +3.4%]
BoidFlockers small 🔵 -0.2% [-0.7%, +0.4%] 🔵 +1.5% [+1.0%, +2.0%]
BoidFlockers large 🔵 +0.5% [-0.1%, +1.2%] 🔵 +1.2% [+0.8%, +1.6%]
MultiLevelAllianceModel small 🔵 +0.1% [-1.7%, +1.9%] 🔵 -0.0% [-0.8%, +0.7%]
MultiLevelAllianceModel large 🔵 +0.5% [-0.9%, +1.9%] 🔴 +8.0% [+6.0%, +10.1%]

@mesa-triage-bot

Copy link
Copy Markdown

Thanks @ARYAMANN7279 for the brute-force comparison and regression test. The numerical example explains the lookup error, but the real-model impact is still missing.

Before maintainer review, please address these two blockers:

  1. Rebase onto current main, as requested in maintainer feedback, to validate against the current base.
  2. Open and link an issue explaining a real-model use case and how the incorrect nearest-cell lookup affects it, as described in the developer guide.

Automated note by an AI model; it can be wrong, and maintainers make the decisions. About this bot.

The KD-tree only held the primary cell positions, so for a point close to
an edge of a torus it could return a cell on the near side even if a
cell across the edge was closer. Build the tree with the periodic box
size when torus=True.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@ARYAMANN7279

Copy link
Copy Markdown
Contributor Author

I rebased the branch onto the current main (one conflict in the test file with #3959, I kept both tests). The new test fails on main without the fix and passes with it.

I opened #4097 with the impact: on a toroidal HexGrid 7.6% of random points on a 10x10 grid (0.8% on 100x100) get a cell that is not the nearest, all of them near an edge. This PR fixes #4097. I don't have a published model that hits this, so the issue says that the numbers come from random points.

@lahari936

Copy link
Copy Markdown
Contributor

Reproduced #4097 on current main and checked this fix against it.

I used the script from the issue, 2000 random points per grid size, compared with a brute-force search that uses the wrapped distance. Share of points that get a cell that isn't the nearest:

  • main: 7.5% (10x10), 2.5% (30x30), 1.7% (50x50)
  • this branch: 0.0% at all three sizes

Other things I tried on this branch:

  • query points well outside the box (from -2x to 3x the period) on 4x4 and 2x2 grids: 0 wrong out of 3000, so the periodic tree wraps the query points as well
  • a non-torus HexGrid still gives the same cell as before
  • tests/discrete_space/test_spatial_lookups.py: 16 passed

One small note, not blocking: boxsize = (width * sqrt(3), height * 1.5) is exactly the period of the even-r layout only because a torus HexGrid already requires an even width and height (the constructor raises otherwise). If that restriction is ever lifted, this box would need another look.

I'm not a maintainer, so no approval from me, but this looks right to me.

@ARYAMANN7279

Copy link
Copy Markdown
Contributor Author

Thanks @lahari936 for reproducing it and for checking points outside the box too.

About the box size: yes, I rely on the constructor, which raises for a torus with an odd width or height (HexGrid with torus=True requires both width and height to be even). With even sizes (width * sqrt(3), height * 1.5) is the period of the even-r layout. I did not add a separate check for it here, but I can add a comment next to boxsize that says so, if the maintainers like that.

@quaquel
quaquel merged commit 2d35e24 into mesa:main Nov 30, 2026
14 of 15 checks passed
@EwoutH EwoutH added the bug Release notes label label Nov 30, 2026
EwoutH added a commit to EwoutH/mesa that referenced this pull request Nov 30, 2026
Seven PRs were merged after the notes were drafted: mesa#4284, mesa#3960,
mesa#4261, mesa#3979, mesa#4286, mesa#4216 and mesa#4301. Also moves the release date to
2026-11-30.

Assisted-by: Claude Code
EwoutH added a commit that referenced this pull request Nov 30, 2026
* Update release notes and version for 4.0.0a1

Add the 4.0.0a1 release notes to HISTORY.md, leaving out changes
already released in Mesa 3.5.1 to 3.5.4, and bump the version to
4.0.0a1. Move the #4182 replication id fix, which was added under
4.0.0a0, into the 4.0.0a1 notes where it was released.

Assisted-by: Claude Opus 5.5

* Leave dependabot and pre-commit.ci bumps out of the 4.0.0a1 notes

Assisted-by: Claude Opus 5.5

* Add PRs merged on 2026-11-30 to the 4.0.0a1 notes

Seven PRs were merged after the notes were drafted: #4284, #3960,
#4261, #3979, #4286, #4216 and #4301. Also moves the release date to
2026-11-30.

Assisted-by: Claude Code
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Release notes label testing Release notes label

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants