Skip to content

Support multiple functions in AgentSet agg method#2743

Merged
EwoutH merged 4 commits intomesa:mainfrom
EwoutH:multiple_agg
Apr 25, 2025
Merged

Support multiple functions in AgentSet agg method#2743
EwoutH merged 4 commits intomesa:mainfrom
EwoutH:multiple_agg

Conversation

@EwoutH
Copy link
Copy Markdown
Member

@EwoutH EwoutH commented Mar 30, 2025

Summary

This PR enhances the AgentSet.agg method to accept lists and tuples of aggregation functions, enabling multiple aggregations in a single method call.

Motive

Currently, when analyzing agent attributes, users need to make separate calls to agg for each aggregation function (min, max, sum, etc.). This creates performance overhead since the attribute values must be collected multiple times.

This enhancement improves both performance and code readability by supporting multiple aggregation functions in a single call, allowing the attribute values to be collected just once and reused across all aggregation functions.

Implementation

  • Modified the agg method signature to accept a single callable or an iterable of callables
  • Updated the return type to handle returning either a single value or a list of results
  • Updated docstring with examples to demonstrate the new functionality
  • Added comprehensive tests to verify all use cases

Usage Examples

# Before (multiple calls required)
min_wealth = model.agents.agg("wealth", min)
max_wealth = model.agents.agg("wealth", max)
total_wealth = model.agents.agg("wealth", sum)

# After (single call)
min_wealth, max_wealth, total_wealth = model.agents.agg("wealth", [min, max, sum])

# Also works with custom functions
stats = model.agents.agg("wealth", [min, max, np.mean, custom_aggregation_function])

Additional Notes

This enhancement is completely backward compatible, so existing code will continue to work without changes. The method will now return a tuple when multiple functions are provided, maintaining the same order as the input function list.

It might also reduce future datacollector complexity, because aggregation can be done efficiently outside it.

I also considered allowing multiple attribute values, but I decided against it since it adds complexity, its use case is less clear and the performance improvements are negligible.

EwoutH added 2 commits March 30, 2025 15:37
Enhance the AgentSet.agg method to accept a list or tuple of functions in addition to a single function. This enables performing multiple aggregations in a single call, improving both convenience and efficiency when analyzing agent attributes.
Add test cases to verify that the AgentSet.agg method properly handles lists and tuples of aggregation functions.
@EwoutH EwoutH added the enhancement Release notes label label Mar 30, 2025
@Sahil-Chhoker
Copy link
Copy Markdown
Collaborator

Its amazing that you still trying to improve the AgentSet, I may not have the expertise to review it but I love reading the code for such features.

@github-actions
Copy link
Copy Markdown

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🔵 -0.5% [-1.0%, +0.0%] 🔵 -0.1% [-0.2%, +0.1%]
BoltzmannWealth large 🔵 -0.3% [-1.1%, +1.0%] 🔵 -0.6% [-0.9%, -0.2%]
Schelling small 🔵 -0.9% [-1.1%, -0.7%] 🔵 -0.3% [-0.3%, -0.2%]
Schelling large 🔵 +3.0% [-0.9%, +9.9%] 🔵 -1.6% [-3.0%, +0.0%]
WolfSheep small 🔵 -0.8% [-1.1%, -0.6%] 🔵 -1.3% [-1.4%, -1.1%]
WolfSheep large 🔵 -0.8% [-1.1%, -0.6%] 🔵 -1.2% [-1.6%, -0.9%]
BoidFlockers small 🔵 -1.5% [-2.3%, -0.7%] 🔵 -1.2% [-1.3%, -1.1%]
BoidFlockers large 🔵 -2.5% [-2.9%, -2.0%] 🔵 -1.0% [-1.2%, -0.9%]

@EwoutH
Copy link
Copy Markdown
Member Author

EwoutH commented Mar 30, 2025

Its amazing that you still trying to improve the AgentSet

It's so fun working on it, you can go from idea to complete PR in less than an hour.

I may not have the expertise to review it but I love reading the code for such features.

Give it a try, it's the quickest way to get there ;)

@EwoutH EwoutH requested a review from Copilot March 30, 2025 14:30

This comment was marked as resolved.

@Ben-geo

This comment was marked as resolved.

Copy link
Copy Markdown
Member

@quaquel quaquel left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks good to me!

@EwoutH
Copy link
Copy Markdown
Member Author

EwoutH commented Mar 30, 2025

@quaquel thanks! Before merging, two questions.

I also considered allowing multiple attribute values, but I decided against it since it adds complexity, its use case is less clear and the performance improvements are negligible.

  1. Do you agree with this?

  2. I want to add a return_values boolean in a follow up PR, that allows to also return all values, which internally is already present in values. Do you see any problems or things to consider (API wise or other)?

@quaquel
Copy link
Copy Markdown
Member

quaquel commented Mar 30, 2025

  1. We have discussed this before I think and this was why we kept agg simple. Indeed, having both multiple attributes and multiple methods is too much. However, I might see a use case for multiple attributes, single operation. However, documenting and type hinting all that becomes messy.
  2. We have split various other AgentSet methods to get rid of a return_value boolean, so I am not greatly in favor.

@EwoutH
Copy link
Copy Markdown
Member Author

EwoutH commented Mar 30, 2025

Thanks for your perspective. Agree on both in some extend.

  1. I was thinking of allowing multiple attributes or multiple methods, but not both. However, I think the former case is both less used and less beneficial performance wise. So I think I will leave it at this.
  2. I'm a bit in doubt, but I think if you want all values anyway you could just run a .get() yourself and then run the function directly instead of through .agg. On the other hand, having this a one-liner is quite elegant. But especially the combination with this PR makes it a bit complicated (since you could have 4 different return types if you adopt both).

I will think about this a bit more.

@Sahil-Chhoker
Copy link
Copy Markdown
Collaborator

While I have no problem with this PR, here are some things I would like to know:

  1. What was the need of this feature? (maybe point me there)
  2. Was 'it' possible before this?

Copy link
Copy Markdown
Member

@adamamer20 adamamer20 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice addition!

  1. I was initially considering allowing either multiple attributes or multiple methods, but not both. That said, I feel the case of multiple attributes is less common and provides limited performance benefits. So, for now, I think I’ll keep things as they are.

Personally, I’d still vote in favor of supporting multiple attributes as well—it gives the user more flexibility and freedom in how they want to use the function.
From an implementation perspective, you could use typing.overload to define valid combinations of parameters and return types. This way, the IDE will offer typing suggestions depending on the input.

from typing import overload, Collection, Any, Callable
from collections.abc import Iterable

    @overload
    def agg(
        self,
        attribute: str,
        func: Callable
    ) -> Any:
        ...

    @overload
    def agg(
        self,
        attribute: Collection[str],
        func: Callable
    ) -> dict[str, Any]:
        ...

    @overload
    def agg(
        self,
        attribute: str,
        func: Iterable[Callable]
    ) -> tuple[Any, ...]:
        ...

    @overload
    def agg(
        self,
        attribute: Collection[str],
        func: Iterable[Callable]
    ) -> dict[str, tuple[Any, ...]]:
        ...

    def agg(
        self,
        attribute: str | Collection[str],
        func: Callable | Iterable[Callable]
    ) -> Any | dict[str, Any] | tuple[Any, ...] | dict[str, tuple[Any, ...]]:
        # implementation

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 25, 2025

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@EwoutH EwoutH merged commit 6868f4f into mesa:main Apr 25, 2025
12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement Release notes label

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants