`VoronoiGrid.find_nearest_cell()` raises `KeyError` after `remove_cell()` due to unsynchronized KD-Tree
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:
- Track
self._kdtree_cellsand aself._kdtree_dirtyflag inVoronoiGrid. - Override
add_cell()andremove_cell()to updateself._kdtree_cellsand setself._kdtree_dirty = True. - Lazily rebuild
self._kdtreeinfind_nearest_cell()whenself._kdtree_dirtyis True. - Raise a clear
ValueError("No cells found in VoronoiGrid")if all cells have been removed.