Optimize `Cell` agent storage and provide vectorized API access
Problem
Currently, mesa.discrete_space.Cell uses a standard Python list to store agents (self._agents). This presents two main issues:
-
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. -
API Inconsistency: While Mesa emphasizes "AgentSet over Loops",
cell.agentscurrently returns a standard list, forcing users to use manual Python loops instead of vectorizedAgentSetmethods (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:
-
Internal Storage Refactor: Change
self._agentsfrom a list to adict[Agent, None](or aset). This makes agent registration/deregulation (add/remove) an $O(1)$ operation, regardless of cell density. -
Lazy
AgentSetProperty: Update the agents property to return anAgentSet(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.agentsandAgentSetpatterns.
@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?
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.
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:
- Performance: Moving to $O(1)$ removals for agent movement in high-density cells.
- Architecture: It unifies the
CellAPI 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.
When I was working on _HardKeyAgentSet, I tried replacing list with _HardKeyAgentSet and raw dict but neither performed better due to :
- Wrapper overhead in
_HardKeyAgentSet(custom__init__,add,remove) - Even when stripping away the
AgentSetwrapper to use a rawdict, it still falls short in iteration. A standardlistsimply iterates faster than a dictionary's keys in Python. The iteration penalty outweighs the removal speedup. - To prevent bugs where users manually clear the cell's internal storage, I had to expose the raw
dictvia a read-onlyKeysView. Because aKeysViewdoesn't support indexing, any user code requiring random access forces an explicit cast vialist(cell.agents). This adds back the memory allocation costs we were trying to avoid.
Curious to see your approach :)
Great Points, @codebreaker32!
- Even when stripping away the
AgentSetwrapper to use a rawdict, it still falls short in iteration. A standardlistsimply 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:
- Maintain Max Speed: Iteration remains list-based.
- Enable modern API: Users can call
cell.agents.do("eat")orcell.agents.select(...)without manual loops.
- To prevent bugs where users manually clear the cell's internal storage, I had to expose the raw
dictvia a read-onlyKeysView. Because aKeysViewdoesn't support indexing, any user code requiring random access forces an explicit cast vialist(cell.agents). This adds back the memory allocation costs we were trying to avoid.
- Since it's list-backed, we could implement
getitemnatively, removing the need for users to calllist(cell.agents)for random access.
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.
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.agentsandCellCollection.agents. Typically, in either case, one is looking for a specific agent or doing some filtering. SoAgentSetmethods 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.