Skip to content

Commit e8b64cc

Browse files
authored
cell_space: Allow CellCollection to be empty (#2502)
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.
1 parent 66d2fee commit e8b64cc

File tree

2 files changed

+38
-2
lines changed

2 files changed

+38
-2
lines changed

mesa/experimental/cell_space/cell_collection.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,10 @@ def __init__(
4848
else:
4949
self._cells = {cell: cell.agents for cell in cells}
5050

51-
#
52-
self._capacity: int = next(iter(self._cells.keys())).capacity
51+
# Get capacity from first cell if collection is not empty
52+
self._capacity: int | None = (
53+
next(iter(self._cells.keys())).capacity if self._cells else None
54+
)
5355

5456
if random is None:
5557
warnings.warn(

tests/test_cell_space.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -583,6 +583,40 @@ def test_cell_collection():
583583
assert len(cells) == len(collection)
584584

585585

586+
def test_empty_cell_collection():
587+
"""Test that CellCollection properly handles empty collections."""
588+
rng = random.Random(42)
589+
590+
# Test initializing with empty collection
591+
collection = CellCollection([], random=rng)
592+
assert len(collection) == 0
593+
assert collection._capacity is None
594+
assert list(collection.cells) == []
595+
assert list(collection.agents) == []
596+
597+
# Test selecting from empty collection
598+
selected = collection.select(lambda cell: True)
599+
assert len(selected) == 0
600+
assert selected._capacity is None
601+
602+
# Test filtering to empty collection
603+
n = 10
604+
full_collection = CellCollection(
605+
[Cell((i,), random=rng) for i in range(n)], random=rng
606+
)
607+
assert len(full_collection) == n
608+
609+
# Filter to empty collection
610+
empty_result = full_collection.select(lambda cell: False)
611+
assert len(empty_result) == 0
612+
assert empty_result._capacity is None
613+
614+
# Test at_most with empty collection
615+
at_most_result = full_collection.select(lambda cell: False, at_most=5)
616+
assert len(at_most_result) == 0
617+
assert at_most_result._capacity is None
618+
619+
586620
### PropertyLayer tests
587621
def test_property_layer_integration():
588622
"""Test integration of PropertyLayer with DiscrateSpace and Cell."""

0 commit comments

Comments
 (0)