mesa icon indicating copy to clipboard operation
mesa copied to clipboard

Optimize `Cell` agent storage and provide vectorized API access

Open falloficaruss opened this issue 9 months ago • 7 comments

Problem

Currently, mesa.discrete_space.Cell uses a standard Python list to store agents (self._agents). This presents two main issues:

  1. Performance Bottleneck: Agent removal (list.remove) is an $O(n)$ operation. In models with high-density cells (e.g., aggregations or "hot-spot" cells), this significantly degrades performance during the agent movement phase.

  2. API Inconsistency: While Mesa emphasizes "AgentSet over Loops", cell.agents currently returns a standard list, forcing users to use manual Python loops instead of vectorized AgentSet methods (like .do(), .select(), or .agg()).

There is an existing TODO in cell.py noting that neither AgentSet nor weakrefs are perceived as performant for this specific use case.

Proposed Solution

I propose a "Hybrid View" approach that optimizes internal storage while exposing the modern Mesa API:

  1. Internal Storage Refactor: Change self._agents from a list to a dict[Agent, None] (or a set). This makes agent registration/deregulation (add/remove) an $O(1)$ operation, regardless of cell density.

  2. Lazy AgentSet Property: Update the agents property to return an AgentSet (or a specialized view) on demand):

@property
def agents(self) -> AgentSet:
    return AgentSet(self._agents.keys(), random=self.model.random)

This provides users with the vectorized API (cell.agents.do("step")) without the memory overhead of maintaining thousands of persistent AgentSet instances.

Benefits

  • Speed: $O(1)$ removals in movement-heavy models.
  • Usability: Consistency with model.agents and AgentSet patterns.

falloficaruss avatar Feb 23 '26 13:02 falloficaruss

@quaquel Could we approach the optimization this way?

By using a dict for internal storage but exposing a "Lazy AgentSet" property, we could solve the $O(n)$ removal bottleneck (making it $O(1)$ without the memory costs of initialized AgentSet objects for every cell in a large grid.

Does this "Hybrid View" align with the performance goals of the modern discrete space architecture, or do you see a risk in creating these transient AgentSet objects on demand?

falloficaruss avatar Feb 23 '26 14:02 falloficaruss

We recently added a _HardRefAgentSet, I would be curious to see the performance implications of using this inside Cell.

Note also that CellCollection.agents relies heavily on Cell.agents being an iterable and this also has direct performance implications throughout the code base and in particular the examples used in benchmarking.

quaquel avatar Feb 23 '26 14:02 quaquel

The addition of _HardKeyAgentSet seems like the perfect fit here. Since the Cell (within the Space) already explicitly manages the registration and deregistration of its agents, using strong references avoids the "scrubbing" overhead of weak-refs while finally addressing that $O(n)$ removal bottleneck in list.remove().

This approach solves both of our goals:

  1. Performance: Moving to $O(1)$ removals for agent movement in high-density cells.
  2. Architecture: It unifies the Cell API with the rest of Mesa by providing native access to vectorized methods without manual loops.

Regarding CellCollection.agents: since _HardKeyAgentSet is a standard iterable, the current itertools.chain implementation remains perfectly compatible. We might even see a secondary performance win there by avoiding some of the list-copying overhead. I'm aligned with this direction.

falloficaruss avatar Feb 23 '26 14:02 falloficaruss

When I was working on _HardKeyAgentSet, I tried replacing list with _HardKeyAgentSet and raw dict but neither performed better due to :

  1. Wrapper overhead in _HardKeyAgentSet (custom __init__, add, remove)
  2. Even when stripping away the AgentSet wrapper to use a raw dict, it still falls short in iteration. A standard list simply iterates faster than a dictionary's keys in Python. The iteration penalty outweighs the removal speedup.
  3. To prevent bugs where users manually clear the cell's internal storage, I had to expose the raw dict via a read-only KeysView. Because a KeysView doesn't support indexing, any user code requiring random access forces an explicit cast via list(cell.agents). This adds back the memory allocation costs we were trying to avoid.

Curious to see your approach :)

codebreaker32 avatar Feb 23 '26 16:02 codebreaker32

Great Points, @codebreaker32!

  1. Even when stripping away the AgentSet wrapper to use a raw dict, it still falls short in iteration. A standard list simply iterates faster than a dictionary's keys in Python. The iteration penalty outweighs the removal speedup.

If iteration and random access are the dominant operations in the simulation hot-path, then staying with a list for core internal storage is absolutely the right call. The $O(n)$ removal is a fair price to pay for fast, contiguous iteration and $O(1)$ indexing.

However, we are still left with the API Inconsistency: users lose all the powerful vectorized methods (.do(), .select(), .agg()) the moment they look inside a cell.

A List-Backed AgentSet View What if we kept the internal storage as a raw list (for maximum speed), but exposed an AgentSet Proxy that operates directly on that list?

Instead of copying the list or wrapping a dict, we could implement a lightweight AgentSet variant (e.g., ListAgentSet) that satisfies the AbstractAgentSet interface but uses an existing list as its backing store. This would:

  1. Maintain Max Speed: Iteration remains list-based.
  2. Enable modern API: Users can call cell.agents.do("eat") or cell.agents.select(...) without manual loops.
  1. To prevent bugs where users manually clear the cell's internal storage, I had to expose the raw dict via a read-only KeysView. Because a KeysView doesn't support indexing, any user code requiring random access forces an explicit cast via list(cell.agents). This adds back the memory allocation costs we were trying to avoid.
  1. Since it's list-backed, we could implement getitem natively, removing the need for users to call list(cell.agents) for random access.

falloficaruss avatar Feb 24 '26 03:02 falloficaruss

When I was working on _HardKeyAgentSet, I tried replacing list with _HardKeyAgentSet and raw dict but neither performed better

Thanks for checking that and sharing it here.

However, we are still left with the API Inconsistency: users lose all the powerful vectorized methods (.do(), .select(), .agg()) the moment they look inside a cell.

I would not call it an API inconsistency as long as it is well documented. Also, the methods are not truly vectorized but just implement the loop over the agents inside the method.

The main question is what the use case is for both cell.agents and CellCollection.agents. Typically, in either case, one is looking for a specific agent or doing some filtering. So AgentSet methods might be useful, but it is also not too difficult to implement these on top of a list yourself.

So, I am open to exploring ways of adding agentset like functionality to both cell.agents and cellcollection.agents but performance in the benchmark models will be quite important.

quaquel avatar Feb 24 '26 12:02 quaquel

My goal is not to claim low-level speedups from these methods, but to improve usability for common cell-level workflows.

The main question is what the use case is for both cell.agents and CellCollection.agents. Typically, in either case, one is looking for a specific agent or doing some filtering. So AgentSet methods might be useful, but it is also not too difficult to implement these on top of a list yourself.

The use cases I had in mind for cell.agents and CellCollection.agents:

  • Filtering agents in a cell or neighborhood without manual loops.
  • Running actions on selected agents directly at cell/neighborhood level.
  • Computing quick local summaries (counts, averages, totals) in a consistent way.

I agree performance on benchmark models is the key requirement. So I suggest this path:

  • Keep list-backed internal storage for cells.
  • Explore AgentSet-like functionality on top of current storage.
  • Run benchmark comparisons on the standard benchmark models before any merge decision.
  • Proceed only if runtime impact is neutral or better.

falloficaruss avatar Feb 24 '26 13:02 falloficaruss