mesa icon indicating copy to clipboard operation
mesa copied to clipboard

HexGrid.find_nearest_cell returns a cell that is not the nearest near the edges of a torus

Open ARYAMANN7279 opened this issue 2 weeks ago • 0 comments

Describe the bug

find_nearest_cell is how a continuous position gets mapped to a cell of a HexGrid, for example a position from a continuous-space movement rule, a click in a visualization, or coordinates from an external dataset. On a torus the nearest cell can lie across an edge. The KD-tree in HexGrid is built without the periodic box, so for a point close to an edge it can return a cell on the near side even if a cell across the edge is closer.

I measured how often this happens on current main. For each grid size I took 4000 uniform random points and compared the returned cell with a brute-force search that uses the wrapped distance:

grid size points that get a cell that is not the nearest
10 x 10 7.6%
30 x 30 2.9%
50 x 50 1.1%
100 x 100 0.8%

All of the wrong points were within 1.5 units of an edge. With a periodic KD-tree (#3979) there are none. Non-torus grids are not affected.

So a model that places or looks up agents by coordinates on a toroidal HexGrid would put a few percent of them into a cell on the wrong side of the seam, and the error depends on the grid size. I do not have a published model that hits this, the numbers above come from random points.

Expected behavior

find_nearest_cell returns the cell with the smallest distance to the point, taking the wrap-around of the torus into account.

To Reproduce

import math, random
import numpy as np
from mesa.discrete_space import HexGrid

w, h = 10, 10
grid = HexGrid((w, h), torus=True, random=random.Random(1))
cells = list(grid.all_cells)
pos = np.array([c.position for c in cells])
period = np.array([w * math.sqrt(3), h * 1.5])

rng = np.random.default_rng(0)
wrong = 0
for p in rng.uniform(0, period, size=(4000, 2)):
    d = np.abs(pos - p)
    d = np.minimum(d, period - d)
    dist = np.hypot(d[:, 0], d[:, 1])
    if dist[cells.index(grid.find_nearest_cell(p))] > dist.min() + 1e-9:
        wrong += 1
print(wrong / 4000)   # 0.0755 on main, 0.0 with the fix

Additional context

The fix is in #3979: it passes boxsize to the KD-tree when torus=True and adds a regression test.

ARYAMANN7279 avatar Nov 15 '26 03:11 ARYAMANN7279