VoronoiGrid passes raw callable capacity to Cell.__init__ instead of numeric_capacity
Describe the bug
In mesa/discrete_space/voronoi.py, VoronoiGrid.__init__ explicitly separates a callable capacity into capacity_function and numeric_capacity (setting numeric_capacity = None when capacity is callable) before passing capacity=numeric_capacity to super().__init__().
However, immediately afterward when constructing self._cells, it passes the raw capacity argument instead of numeric_capacity to cell_klass(...):
self._cells = {
i: cell_klass(
coordinate=i, # Integer index
capacity=capacity,
random=self.random,
position=self.centroids_coordinates[i], # Physical centroid position
)
for i in range(len(self.centroids_coordinates))
}
This violates Cell.__init__'s capacity: int | None = None contract by passing a Callable during cell construction, and leaves cell.capacity as a function for any cell not overwritten in _build_cell_polygons() (causing Cell.add_agent() to raise TypeError: '>=' not supported between instances of 'int' and 'function').
Expected behavior
VoronoiGrid.__init__ should pass capacity=numeric_capacity when instantiating cell_klass so every Cell is initialized with int | None before _build_cell_polygons() assigns area-derived capacities.
To Reproduce
from mesa.discrete_space import Cell, VoronoiGrid
class StrictCell(Cell):
def __init__(self, coordinate, position=None, capacity=None, random=None):
if capacity is not None and not isinstance(capacity, int):
raise TypeError(
f"Expected int | None for capacity, got {type(capacity).__name__}"
)
super().__init__(
coordinate, position=position, capacity=capacity, random=random
)
grid = VoronoiGrid(
[(0, 0), (1, 0), (0, 1), (1, 1)],
capacity=lambda area: max(1, int(area)),
cell_klass=StrictCell,
)
Actual Output
TypeError: Expected int | None for capacity, got function
Additional Context
- Affected file:
mesa/discrete_space/voronoi.py(VoronoiGrid.__init__) - Origin & practical impact: Discovered while auditing
VoronoiGrid.__init__againstCell.__init__'s type contract (capacity: int | None = None) rather than from a specific built-in example model. In user models that pairVoronoiGridwith a callablecapacity(such as an area-based capacity function) and a customcell_klass, any subclass validatingcapacity(e.g.,if capacity is not None and capacity < 0:) or initializing capacity-dependent attributes inside__init__immediately crashes with aTypeError. Additionally, any cell whose capacity is not overwritten in_build_cell_polygons()retains afunctionobject and raisesTypeErrorlater duringCell.add_agent(). - Fix: Passing
capacity=numeric_capacityalignscell_klass(...)initialization withsuper().__init__(capacity=numeric_capacity, ...)directly above it (addressed in #4103).
- The space itself does not seem to use capacity at all.
- I would favor resolving the capacity when instantiating the cells.
@quaquel Thanks for closing the PRs to force discussion — that's the right process.
The bug: VoronoiGrid.__init__ passes the raw capacity argument (which may be a Callable) to cell_klass, violating Cell.__init__'s capacity: int | None contract. This causes TypeError for any custom cell that validates capacity in __init__, and leaves cell.capacity as a function for cells not overwritten in _build_cell_polygons().
Minimal fix (my PR #4103, also #4135): Pass self.capacity (the already-separated numeric capacity) to cell_klass. This:
- Matches what
super().__init__(capacity=self.capacity, ...)receives two lines above - Restores the type contract
- Cells temporarily see None for callable capacity → final int set in
_build_cell_polygons()(same two-phase pattern as fixed numeric capacity) - 1-line change, low risk
Eager computation (PR #4155): Compute Voronoi polygons before creating cells so they receive final int capacity immediately. This is a stronger guarantee but requires reordering initialization (~80 lines changed), forces eager geometry computation, and complicates dynamic add_cell/remove_cell.
My take: The minimal fix resolves the actual bug (type contract violation). Eager computation is a valid enhancement for custom cells that need final capacity in __init__, but it's separable — such cells can defer capacity-dependent setup to a post-init method (pattern used elsewhere in Mesa).
Question for the team: Is the temporary None during cell __init__ acceptable for callable capacity (consistent with current fixed-capacity behavior), or do we want to adopt eager computation as the new contract 😊? Happy to implement either once agreed.
Thanks for the summary, @priyanshux-dev. I wrote #4155 (the eager version), so I wanted to correct a few details of the comparison, since they bear on the trade-off:
- Size: the change is about 34 added and 14 removed lines in
voronoi.py, not ~80. - Eagerness: nothing new is computed eagerly. On
main,__init__already calls_connect_cells()(which builds the triangulation) and_build_cell_polygons()(which exports the regions and computes areas) before it returns. The change only moves the triangulation and the area-based capacity before the cells are created. add_cell/remove_cell: these only update the KD-tree and aren't touched.
Behaviour for existing code is unchanged: for 60 random point sets (2,055 cells) a callable capacity still equals fn(cell.properties["area"]), and a fixed or missing capacity is unchanged. The one difference is a cell with no Voronoi region, which previously could keep the callable and now gets None.
So the trade-off is that cells receive their final capacity in __init__ versus a temporary None for callable capacities. @quaquel, you mentioned favoring resolving the capacity when the cells are created, which is what the eager version does. If that's the direction, I'm happy to rebase #4155's branch (fix-voronoi-final-capacity in my fork) or leave it to whoever the maintainers prefer. I won't open anything until you say.