mesa icon indicating copy to clipboard operation
mesa copied to clipboard

`VoronoiGrid.find_nearest_cell()` raises `KeyError` after `remove_cell()` due to unsynchronized KD-Tree

Open Dilraj07 opened this issue 1 month ago • 0 comments

Bug Description

In mesa.discrete_space.VoronoiGrid, self._kdtree is constructed once during __init__ from the initial centroids. When a cell is dynamically removed using remove_cell(cell) (inherited from DiscreteSpace), the cell is removed from self._cells, but self._kdtree is not updated or marked dirty.

As a result, subsequent calls to grid.find_nearest_cell(position) near the coordinates of the removed cell return the index of the deleted cell, causing an unhandled KeyError when querying self._cells[index]. Similarly, newly added cells via add_cell() are never indexed in self._kdtree.

Reproduction Steps

import random
from mesa.discrete_space import VoronoiGrid

points = [
    [0.0, 0.0],
    [1.0, 0.0],
    [0.0, 1.0],
    [1.0, 1.0],
]
grid = VoronoiGrid(points, random=random.Random(42))

# Remove a cell
cell_to_remove = grid._cells[0]
grid.remove_cell(cell_to_remove)

# Query nearest cell
nearest = grid.find_nearest_cell([0.05, 0.05])

Expected Behavior

find_nearest_cell() should return the nearest remaining cell in the Voronoi grid without raising KeyError, matching the lazy KD-Tree synchronization pattern already implemented in Network.

Actual Behavior

  File "mesa/discrete_space/voronoi.py", line 257, in find_nearest_cell
    return self._cells[index]
           ~~~~~~~~~~~^^^^^^^
KeyError: np.int64(0)

Proposed Fix

Follow the established pattern in mesa.discrete_space.network.Network:

  1. Track self._kdtree_cells and a self._kdtree_dirty flag in VoronoiGrid.
  2. Override add_cell() and remove_cell() to update self._kdtree_cells and set self._kdtree_dirty = True.
  3. Lazily rebuild self._kdtree in find_nearest_cell() when self._kdtree_dirty is True.
  4. Raise a clear ValueError("No cells found in VoronoiGrid") if all cells have been removed.

Dilraj07 avatar Oct 25 '26 08:10 Dilraj07