Skip to content

A unified interface for different collection types #2671

Open
@AdamZh0u

Description

@AdamZh0u

What's the problem this feature will solve?
Currently, Mesa has multiple collection implementations (AgentSet, CellCollection) with overlapping functionality. This leads to:

  1. Code duplication across different collection types
  2. Inconsistent interfaces between collections
  3. Difficulty in maintaining and extending collection functionality
  4. 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:

  1. 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
  2. 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:

  1. Reduced code duplication and consistent interface across all collections
  2. Easier maintenance and simplified development of new collection types
  3. Collection based operations like aggregation and mapping
  4. Improved performance through shared optimisations

Additional context

This would be a significant architectural improvement for Mesa, making it more maintainable and extensible while providing a better developer experience.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions