Optimise _remove_agent in Continuous Space#3491
Conversation
|
Performance benchmarks:
|
|
|
||
| # Pop the last elements | ||
| self.active_agents.pop() | ||
| self._index_to_agent.pop(last_index, None) |
There was a problem hiding this comment.
I am fine with this change, but I wonder whether a further improvement might not be possible.
At the moment, on every access of agent.position, the agent has to look up its index. This seems wasteful. In principle, an agent can be assigned an index when added to a space and just keep this index for its lifetime. This does mean that on the space side, the indexing becomes a bit more difficult because we need to maintain a numpy array with the currently active indices. But it might offer speedups. Thoughts are welcome.
There was a problem hiding this comment.
we need to maintain a numpy array with the currently active indices
How about using _mesa_index? I noticed we haven't using it actively. Any specific reason? Also see my latest commit.
There was a problem hiding this comment.
My hunch is that this index was added at some point while developing the code, but was not used in the final merged PR.
156cc27 to
3b82e0f
Compare
|
Performance benchmarks:
|
Summary
This PR optimizes the internal agent removal process in$O(N)$ array shifting logic with an $O(1)$ "swap-with-last" algorithm. This eliminates costly
ContinuousSpaceby replacing theforloops and NumPy array slice shifting, drastically improving performance for models with high agent churn.Motive
See #3490
Implementation
This PR aligns
ContinuousSpacewith the performance standards recently established in Mesa's data collection modules. It implements the exact same "swap-with-last" logic used byNumpyAgentDataSet.Additional Notes
As Mesa 4.0 moves toward the "Stacked Spaces" architecture (where Continuous Agents may have primary role), optimizing base operations can be seen as prerequisites effort before we start introducing major changes
Closes #3490