Thanks to visit codestin.com
Credit goes to Github.com

Skip to content

Grid.select_random_empty_cell hangs on full grids #2968

@ShreyasN707

Description

@ShreyasN707

I noticed Grid.select_random_empty_cell appears to be able to enter an infinite loop when the grid has no empty cells available.

When _try_random is enabled (the default), the method keeps sampling random cells inside a while True loop and only returns once an empty cell is found. If the grid is fully occupied, this condition is never met, so the call never returns and the simulation ends up hanging.

From reading the implementation, this looks like an unguarded edge case.

Expected behavior

select_random_empty_cell should always terminate in a predictable way.
If no empty cells exist, I would expect it to either fall back to the deterministic implementation in DiscreteSpace or fail cleanly with a clear error, rather than hanging indefinitely.

To Reproduce

Minimal reproduction:

Create a small grid (for example, 2×2).

Fill all cells with agents so that no empty cells remain.

Call grid.select_random_empty_cell().

Example:

from mesa.discrete_space.grid import OrthogonalMooreGrid

grid = OrthogonalMooreGrid((2, 2))
for cell in grid.all_cells:
    cell.add_agent(object())  # fill all cells

# This call does not return
grid.select_random_empty_cell()

Once the grid is full, the function hangs and never returns.

Additional context

  • This seems to occur specifically in the _try_random branch due to the unbounded while True loop.

  • A possible fix could be to limit the number of random attempts and then fall back to DiscreteSpace.select_random_empty_cell(), keeping the current optimization while guaranteeing termination.

  • Could you please take a look and confirm whether this behavior is expected?

@EwoutH @quaquel I can raise a PR fixing this issue!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions