-
Notifications
You must be signed in to change notification settings - Fork 874
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Introduce AgentSet class #1916
Introduce AgentSet class #1916
Conversation
What's really nice it that you can now do things like if agent in model.agents This commit introduces the `AgentSet` class in the Mesa agent-based modeling framework, along with significant changes to the agent management process. The `AgentSet` class is designed to encapsulate and manage a collection of agents, providing methods for efficient selection, sorting, shuffling, and applying actions to groups of agents. This addition aims to enhance the framework's scalability and flexibility in handling agent operations. Key changes include: - **Agent Class Modifications**: Updated the `Agent` class to directly manage agent registration and removal within the model's `_agents` attribute. This simplification removes the need for separate registration and removal methods, maintaining the encapsulation of agent management logic within the `Agent` class itself. - **Model Class Enhancements**: Refactored the `Model` class to utilize the `AgentSet` class. The `agents` property now returns an `AgentSet` instance, representing all agents in the model. This change streamlines agent access and manipulation, aligning with the object-oriented design of the framework. - **AgentSet Functionality**: The new `AgentSet` class includes methods like `select`, `shuffle`, `sort`, and `do_each` to enable more intuitive and powerful operations on agent collections. These methods support a range of common tasks in agent-based modeling, such as filtering agents based on criteria, randomizing their order, or applying actions to each agent. This implementation significantly refactors agent management in the Mesa framework, aiming to provide a more robust and user-friendly interface for modeling complex systems with diverse agent interactions. The addition of `AgentSet` aligns with the framework's goal of facilitating efficient and effective agent-based modeling.
Codecov ReportAttention:
Additional details and impacted files@@ Coverage Diff @@
## main #1916 +/- ##
==========================================
+ Coverage 77.53% 79.10% +1.56%
==========================================
Files 15 15
Lines 1015 1096 +81
Branches 221 236 +15
==========================================
+ Hits 787 867 +80
- Misses 197 198 +1
Partials 31 31 ☔ View full report in Codecov by Sentry. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
some quick suggestions
…sults _agent is now a WeakKeyDictionary, and for arguments sake, I added the inplace keyword argument
I won’t be working on it between now and out meeting tomorrow, so take it as far as you like. Maybe there is also still some stuff from #1911 that can be ported over. |
I'll see what I can do tomorrow morning. I just addressed my comments on your first submission and added the inplace keyword argument. |
Awesome PR |
Thanks for working on It. I will try to do an initial review tomorrow between 9 and 10 CET, otherwise around noon (feel free to continue regardless). |
I’m leaning towards just documenting properly that you can use |
I disagree with the copy thing. First, it adds another method call into any chain. Second, the API now follows Pandas, so users of Mesa are likely to be familiar with it. Third, in particular in the case of a large number of agents, there are substantial memory advantages to using |
Thanks for your perspective. Sound arguments, let me further think about it. Also curious what others think. I would propose all the "getting data back" things (like |
I concur with keeping inplace in the API, since I think copying should be the default. We will see how that turns out performance wise, but we shouldnt worry about that just yet. I also agree we should keep this PR small at first and add further functions later. This is a very solid basis and can/should be used for lots of things so not overcomplicate things now. |
Keeping the PR focused is the right way to go. However, it should also be feature-complete, and the basic structure should be solid. Otherwise, the code base keeps changing repeatedly to reflect new ideas. My suggestion would be to focus on making sure AgentSet has the following things:
What can be discussed or kept for later, in my view, are:
|
updates Agent and Model to not rely on sets when creating AgentSet. also removes unnecessary check in agent if key exists. Because of defaultdict this is not needed. Likewise, deregistring is done, and error is caught (It is better to ask forgiveness than permission). some comments in indexing
Inheriting from Also remarkably, there is a reference to an |
If either of you has anything to add to the Python discussion on |
We follow 1, but I am not sure we need to worry about 2 (it involves subset and superset comparisons as far as I can tell); 3 is likewise unnecessary. While googling this, I came across some discussions on pickling the set. Is this something we want to support? |
The question is should do_each return the return values the called function or return the AgentSet itself. The latter would allow to keep on chaining, for example: agents.do_each(step).select(n=10).do_each(move) But getting the return values could also be valueable, so maybe we can also add |
Unit tests have been added, and it seems pretty complete. However, there are several outstanding issues:
|
Just two more comments from my side, otherwise I think we are good to go! |
both have been done. |
I approved, but would like to have 2 more eyes on this before I feel comfortable merging. But I think @EwoutH you can start to adapt this in your other prs |
Thanks, I agree on at least another reviewer. No other PRs I have currently open have to be modified based on this PR (we can modify the schedulers, datacollector, and maybe grid in the future). |
@EwoutH , I get this error while running one of the examples which looks related to this change:
|
Thanks for reporting, that's because the example (for some reason) doesn't run It should be fixed in #1928. |
(Still catching up with the influx of exciting constructive developments with the new APIs.) Modifying slightly the example:
As far as I understand, this overlaps with the declarative data collecting specification in #348 (comment)? I find it excessive to have 2 APIs, where one is for agent dynamics description and another for data collection. I am wondering if the 2 APIs are inevitable. The constraint seems to be to make it easy to build complex scheduler and data collection, while to minimize the amount of documentation needed. |
How do I select |
Currently,
|
Just thought of this now, but their might be one edge-case in which we might break user models: If |
This PR is based on the discussion in #1912 (comment) for the initial discussion.
This PR introduces the
AgentSet
class in the Mesa agent-based modeling framework, along with significant changes to the agent management process. TheAgentSet
class is designed to encapsulate and manage a collection of agents, providing methods for efficient selection, sorting, shuffling, and applying actions to groups of agents. This addition aims to enhance the framework's scalability and flexibility in handling agent operations.Key Changes
Agent
class has been updated to manage agent registration and removal within the model's_agents
attribute directly. This approach eliminates the need for separate registration and removal methods.Model
class now utilizes theAgentSet
class. Theagents
property returns anAgentSet
instance, representing all agents in the model, thus streamlining agent access and manipulation.AgentSet
class includes methods likeselect
,shuffle
,sort
, anddo
for more intuitive operations on agent collections. These methods facilitate tasks like filtering agents, randomizing their order, sorting, and applying actions to each agent.AgentSet
maintains weak references to agents, enabling efficient management of agent lifecycles and garbage collection. It uses aWeakKeyDictionary
to store agents.Usage examples
Selecting and Filtering Agents:
Shuffling Agents:
Sorting Agents:
Applying Actions to Agents:
Retrieving Agent Attributes:
Advanced Chaining examples
Filter, Shuffle, and Apply an Action:
Chaining
select
,shuffle
, anddo
allows for filtering, randomizing, and then performing an action on the selected agents.Sort, Select Top N, and Get Attribute:
This chain sorts agents, selects the top N agents based on the sort, and retrieves a specific attribute from these agents.
Complex Filtering and Action Application:
Combining multiple filters and then applying an action. This chain can be particularly useful for complex conditional operations.
Combined Set Operations and Action Application:
If set-like operations (union, intersection, difference) are implemented, they can be combined with action application.
Shuffle, Sort, and Sequential Action Execution:
This chain first randomizes the order of agents, then sorts them based on an attribute, and finally applies a method sequentially.
Nested Chain Operations:
Combining chaining with nested operations for more sophisticated scenarios.
Replacing schedulers
You can use the new AgentSet functionality to replacer the current schedulers and create entirely new ones.
1. BaseScheduler
The
BaseScheduler
activates each agent once per step, in the order they were added.2. RandomActivation
RandomActivation
activates each agent once per step, in random order.3. SimultaneousActivation
In
SimultaneousActivation
, all agents are activated simultaneously. This can be simulated by first collecting all agents' decisions and then applying them.4. StagedActivation
StagedActivation
allows for multiple stages per step. For instance, agents first "move", then "eat", then "sleep".5. RandomActivationByType
RandomActivationByType
activates each type of agent in random order.These examples demonstrate how the
AgentSet
class can be used to replicate the behavior of different schedulers in Mesa. TheAgentSet
class provides a more flexible and concise way to define the activation and interaction patterns among agents within the model.Future work
__reversed__
,index
,count
,clear
,pop
,__ior__
) for enhanced performance and functionality.