Open
Description
What's the problem this feature will solve?
Currently, Mesa has multiple collection implementations (AgentSet
, CellCollection
) with overlapping functionality. This leads to:
- Code duplication across different collection types
- Inconsistent interfaces between collections
- Difficulty in maintaining and extending collection functionality
- Challenges when developing new collection types (e.g., for mesa-geo's LayerCollection @wang-boyu )
Describe the solution you'd like
Introduce a new CollectionBase
class that would:
-
Provide a common foundation for all Mesa collections with shared functionality:
- Basic attributes (
__contains__
,__len__
) - Set and get operations
- Sequence operations (indexing, iteration)
- Filtering and selection (select shuffle, sort)
- Method invocation on items (map)
- Aggregation operations
- Basic attributes (
-
Use weak references for proper memory management and garbage collection, crucial for simulation performance
Example usage:
class CollectionBase(Generic[T]):
"""A base collection class that provides set-like and sequence functionality. """
def __init__(self, items: Iterable[T], random: Random | None = None):
self._initialize_storage(items)
def _initialize_storage(self, items: Iterable[T]) -> None:
self._items = weakref.WeakKeyDictionary({item: None for item in items})
class AgentSet(CollectionBase[Agent]):
"""Agent-specific collection implementation"""
pass
class CellCollection(CollectionBase[Cell]):
"""Cell-specific collection implementation"""
pass
class LayerCollection(CollectionBase[Layer]):
"""Geographic layer collection for mesa-geo"""
pass
Benefits:
- Reduced code duplication and consistent interface across all collections
- Easier maintenance and simplified development of new collection types
- Collection based operations like aggregation and mapping
- Improved performance through shared optimisations
Additional context
- Reference implementation: Google Earth Engine API's Collection Implementation
This would be a significant architectural improvement for Mesa, making it more maintainable and extensible while providing a better developer experience.
Activity