Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
time: Use weak references to agents in schedulers
This commit modifies the schedulers to use weak references for agent management. The update aims to improve memory efficiency and garbage collection, especially in scenarios where agents are dynamically added and removed during model execution. It also ensures that the Agent remove() method also removes the Agent from a schedule. Key Changes: - Agents within schedulers are now stored as weak references (`weakref.ref[Agent]`), reducing the memory footprint and allowing for more efficient garbage collection. - The `add` method in `BaseScheduler` and derived classes has been updated to store agents as weak references. - The `remove` method has been modified to handle both direct agent objects and weak references, improving flexibility and robustness. - Updated `do_each` method to iterate over a copy of agent keys and check the existence of agents before calling methods, ensuring stability during dynamic agent removal. - Added a `agents` property to return a list of live agent instances, maintaining backward compatibility for user code that iterates over agents. - Ensured all existing tests pass, confirming the stability and correctness of the changes. The changes result in a more memory-efficient scheduler implementation in Mesa, while preserving existing functionality and ensuring backward compatibility. All 27 current tests pass without any modifications, so there shouldn't be changes breaking compatibility.
- Loading branch information