Infinite loop in Grid.select_random_empty_cell() when no empty cells exist
Describe the bug
When a grid is completely full and you call select_random_empty_cell(), the program hangs forever in an infinite loop. No exception is raised, making it very hard to debug.
This happens in real models when populations grow and fill up all available space, which is pretty common in agent-based simulations.
Expected behavior
Should raise a clear error message instead of hanging:
ValueError: Cannot select random empty cell: grid is full.
To Reproduce
from mesa import Model
from mesa.discrete_space.cell_agent import CellAgent
from mesa.discrete_space.grid import OrthogonalMooreGrid
class SimpleAgent(CellAgent):
def __init__(self, model, cell):
super().__init__(model)
self.cell = cell
model = Model()
grid = OrthogonalMooreGrid(dimensions=(3, 3), capacity=1, random=model.random)
for cell in grid.all_cells:
SimpleAgent(model, cell)
empty_cell = grid.select_random_empty_cell()
Run this and the program will hang forever at the last line.
Why this happens
The code uses while True which never exits when there are no empty cells:
if self._try_random:
while True:
cell = self.all_cells.select_random_cell()
if cell.is_empty:
return cell
๐ CodeRabbit Plan Mode
Generate an implementation plan and prompts that you can use with your favorite coding agent.
- [ ] Create Plan
๐ Similar Issues
Possible Duplicates
- ISSUE-2968
Related Issues
- https://github.com/mesa/mesa/issues/2968
- https://github.com/mesa/mesa/issues/2982
- https://github.com/mesa/mesa/issues/2962
- https://github.com/mesa/mesa/issues/2980
๐ค Suggested Assignees
๐งช Issue enrichment is currently in open beta.
You can configure auto-planning by selecting labels in the issue_enrichment configuration.
To disable automatic issue enrichment, add the following to your .coderabbit.yaml:
issue_enrichment:
auto_enrich:
enabled: false
๐ฌ Have feedback or questions? Drop into our discord or schedule a call!