Skip to content

Commit

Permalink
cell_space: Allow CellCollection to be empty (projectmesa#2502)
Browse files Browse the repository at this point in the history
Sometimes it's useful to have any empty cell collection in the cell space, which can happen after selection with no cells that meet the selection requirements.

However, self._capacity would give an error, because there were no cell to derive the capacity from. This PR resolves that error.
  • Loading branch information
EwoutH authored Nov 13, 2024
1 parent 66d2fee commit e8b64cc
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
6 changes: 4 additions & 2 deletions mesa/experimental/cell_space/cell_collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,10 @@ def __init__(
else:
self._cells = {cell: cell.agents for cell in cells}

#
self._capacity: int = next(iter(self._cells.keys())).capacity
# Get capacity from first cell if collection is not empty
self._capacity: int | None = (
next(iter(self._cells.keys())).capacity if self._cells else None
)

if random is None:
warnings.warn(
Expand Down
34 changes: 34 additions & 0 deletions tests/test_cell_space.py
Original file line number Diff line number Diff line change
Expand Up @@ -583,6 +583,40 @@ def test_cell_collection():
assert len(cells) == len(collection)


def test_empty_cell_collection():
"""Test that CellCollection properly handles empty collections."""
rng = random.Random(42)

# Test initializing with empty collection
collection = CellCollection([], random=rng)
assert len(collection) == 0
assert collection._capacity is None
assert list(collection.cells) == []
assert list(collection.agents) == []

# Test selecting from empty collection
selected = collection.select(lambda cell: True)
assert len(selected) == 0
assert selected._capacity is None

# Test filtering to empty collection
n = 10
full_collection = CellCollection(
[Cell((i,), random=rng) for i in range(n)], random=rng
)
assert len(full_collection) == n

# Filter to empty collection
empty_result = full_collection.select(lambda cell: False)
assert len(empty_result) == 0
assert empty_result._capacity is None

# Test at_most with empty collection
at_most_result = full_collection.select(lambda cell: False, at_most=5)
assert len(at_most_result) == 0
assert at_most_result._capacity is None


### PropertyLayer tests
def test_property_layer_integration():
"""Test integration of PropertyLayer with DiscrateSpace and Cell."""
Expand Down

0 comments on commit e8b64cc

Please sign in to comment.