Skip to content

Refactor Agent Portrayal to Use AgentPortrayalStyle Instead of Dictionary(#2436) #2728

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

Open
wants to merge 11 commits into
base: main
Choose a base branch
from

Conversation

aarav-shukla07
Copy link
Contributor

Summary

This PR refactors Mesa’s visualization system by replacing the dictionary-based agent_portrayal system with a new AgentPortrayalStyle class. This improves code clarity, ensures validation, and enhances backend compatibility across different visualization methods

Bug / Issue

Closes #2436

Previously, agent_portrayal functions returned a dictionary with properties like "color", "marker", "size", and "zorder". However, this approach:

  • Lacked validation, allowing invalid properties.
  • Made it harder to maintain and extend the portrayal system.
  • Was inconsistent across Matplotlib and Altair visualizations.

This PR introduces AgentPortrayalStyle, making agent portrayal more structured and type-safe while maintaining backward compatibility.

Implementation

  • Created AgentPortrayalStyle class to encapsulate agent portrayal properties.
  • Modified make_mpl_space_component to handle both AgentPortrayalStyle and dictionary-based portrayals for backward compatibility.
  • Updated app.py examples to use AgentPortrayalStyle.
  • Refactored test_call_space_drawer in test_solara_viz.py to ensure compatibility with the new portrayal system.
  • Fixed space initialization issues in tests by correctly initializing ContinuousSpace.
  • Added a seeded random generator to improve test reproducibility and remove warnings.

Testing

Run all Mesa tests to ensure no regressions:

pytest

Verified that test_call_space_drawer correctly handles AgentPortrayalStyle

pytest tests/test_solara_viz.py::test_call_space_drawer -s

Result: All tests passed with no new failures.

Additional Notes

  • This PR maintains backward compatibility by allowing both dictionary-based portrayals and the new AgentPortrayalStyle class.
  • Future improvements can involve updating all Mesa examples to exclusively use AgentPortrayalStyle.
  • Fixing the test warnings about random number generation ensures consistent test results across runs.

Copy link

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🔴 +7.8% [+6.7%, +8.8%] 🔵 +1.5% [+1.4%, +1.6%]
BoltzmannWealth large 🔴 +23.0% [+3.9%, +61.9%] 🔴 +13.4% [+11.9%, +15.0%]
Schelling small 🔵 +2.3% [+2.0%, +2.6%] 🔵 +2.7% [+2.5%, +3.0%]
Schelling large 🔵 +2.5% [+1.4%, +3.5%] 🔵 +3.4% [+0.6%, +6.0%]
WolfSheep small 🔵 +2.1% [+1.7%, +2.5%] 🔵 +0.8% [+0.5%, +1.1%]
WolfSheep large 🔵 +2.8% [+1.5%, +4.7%] 🔵 +2.9% [+1.2%, +4.3%]
BoidFlockers small 🔵 +0.1% [-0.4%, +0.7%] 🔵 +0.7% [+0.4%, +0.9%]
BoidFlockers large 🔵 -0.9% [-1.5%, -0.4%] 🔵 +0.1% [-0.3%, +0.5%]

@EwoutH
Copy link
Member

EwoutH commented Mar 22, 2025

@aarav-shukla07 thanks for your PR! An AgentPortrayalStyle as a proper class would be great to have, I requested our visualization experts to review.

@EwoutH EwoutH added breaking Release notes label enhancement Release notes label labels Mar 22, 2025
@quaquel
Copy link
Member

quaquel commented Mar 23, 2025

I like the basic idea and resulting API. However, I have some concerns about the implementation and the performance overhead that would require some custom benchmarking.

  1. Can we make AgentPortrayalStyle a dataclass or something similar?
  2. The new code in mpl_space_drawing iterates over the agents twice, which is wasteful. The new code is also largely not located in collect_agent_data, so I am struggling to understand what is going on here.
  3. I am inclined to add the loc to AgentPortrayalStyle. This would nicely encapsulate all visual encoding in a single data object.

@Sahil-Chhoker
Copy link
Collaborator

@aarav-shukla07, The code in mpl_space_drawing.py is same as in #2693 which is already closed. Please clean it up.

@aarav-shukla07
Copy link
Contributor Author

I like the basic idea and resulting API. However, I have some concerns about the implementation and the performance overhead that would require some custom benchmarking.

  1. Can we make AgentPortrayalStyle a dataclass or something similar?
  2. The new code in mpl_space_drawing iterates over the agents twice, which is wasteful. The new code is also largely not located in collect_agent_data, so I am struggling to understand what is going on here.
  3. I am inclined to add the loc to AgentPortrayalStyle. This would nicely encapsulate all visual encoding in a single data object.

Hi @quaquel ,

Thank you for your detailed feedback! Here’s how I’ve addressed your concerns:

(1) Converted AgentPortrayalStyle into a dataclass

This encapsulates all visual encoding in a single object, improving readability and structure.

(2) Optimized collect_agent_data

Previously, it iterated over agents twice. Now, it processes them in a single loop, reducing unnecessary overhead.

(3) Added loc directly to AgentPortrayalStyle

This ensures that all relevant visual properties, including position, are encapsulated within a single structured object.

I’ve also verified that all tests pass , and I’ve resolved the merge conflicts to ensure smooth integration. Please let me know if there are any further improvements or clarifications needed!

Thanks again for your guidance. Looking forward to your feedback.

@aarav-shukla07
Copy link
Contributor Author

Hi @Sahil-Chhoker ,

Thank you for your feedback. I acknowledge that the code in mpl_space_drawing.py was similar to the one in #2693, which has already been closed. I had cleaned up the redundant changes and ensure that only the necessary modifications remain in this PR.

I have updated the PR and verified that the changes align with the latest codebase. Please let me know if there are any further improvements or clarification needed!

Thanks again for your guidance. Looking forward to your feedback.

edgecolors: str = "black" # edge color for markers
loc: tuple[float, float] | None = None # stores agent position

def to_dict(self):
Copy link
Member

Choose a reason for hiding this comment

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

I would suggest doing it the other way arround. In get_agent_data if the return is a dict cast it to a AgentPortrayalStyle and issue a warning


def MakeSpaceMatplotlib(model):
def wrapped_agent_portrayal(agent):
Copy link
Member

Choose a reason for hiding this comment

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

can't this be handled inside get_agent_data?

warnings.warn(
f"the following fields are not used in agent portrayal and thus ignored: {msg}.",
stacklevel=2,
portrayal_dict = agent_portrayal(agent) or {}
Copy link
Member

Choose a reason for hiding this comment

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

why the or?

portrayal_dict = agent_portrayal(agent) or {}

agent_data_list.append(
AgentPortrayalStyle(
Copy link
Member

Choose a reason for hiding this comment

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

This is wasteful because in the current code you already allways get an AgentPortrayalStyle instance.

alpha=portrayal_dict.get("alpha", 1.0),
linewidths=portrayal_dict.get("linewidths", 1.0),
edgecolors=portrayal_dict.get("edgecolors", "black"),
loc=agent.pos if agent.pos is not None else (0, 0), # Store location
Copy link
Member

Choose a reason for hiding this comment

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

this is not correct.

loc is either agent.pos or agent.cell.coordinate

@@ -346,7 +308,9 @@ def draw_orthogonal_grid(

# gather agent data
s_default = (180 / max(space.width, space.height)) ** 2
arguments = collect_agent_data(space, agent_portrayal, size=s_default)
arguments = collect_agent_data(
space, agent_portrayal, default_color="tab:red", default_size=30
Copy link
Member

Choose a reason for hiding this comment

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

these defaults can be moved into AgentPortrayalStyle

# Calculate hexagon centers for agents if agents are present and plot them.
if loc.size > 0:
loc[:, 0] = loc[:, 0] * x_spacing + ((loc[:, 1] - 1) % 2) * (x_spacing / 2)
loc[:, 1] = loc[:, 1] * y_spacing
arguments["loc"] = loc
for i, agent_data in enumerate(arguments):
Copy link
Member

Choose a reason for hiding this comment

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

What happens here?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Previously, arguments was structured as a dictionary holding arrays for all agents — so we could assign the entire loc array at once using arguments["loc"] = loc.

With the updated structure, arguments is now a list of dictionaries, each representing an individual agent’s data. To assign each agent its own specific location, we iterate through arguments and update each ```agent_data entry:

for i, agent_data in enumerate(arguments):
    agent_data["loc"] = loc[i]

This change ensures that each agent dictionary gets its corresponding location from the loc array, maintaining alignment between spatial data and individual agent portrayal.

arr[:] = arguments["marker"]
data["marker"] = arr
return data
return agent_data_list
Copy link
Member

Choose a reason for hiding this comment

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

not sure but it might be better to turn all agent data into numpy arrays already here so we avoid needless iterations later.

Comment on lines +450 to +459
scatter_data = {
"s": [a.size for a in agent_data_list],
"c": [a.color for a in agent_data_list],
"marker": [a.marker for a in agent_data_list],
"zorder": [a.zorder for a in agent_data_list],
"loc": np.array([a.loc for a in agent_data_list], dtype=np.float64),
"alpha": [a.alpha for a in agent_data_list],
"edgecolors": [a.edgecolors for a in agent_data_list],
"linewidths": [a.linewidths for a in agent_data_list],
}
Copy link
Member

Choose a reason for hiding this comment

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

this is wasteful iteration. You iterate over the same data 8 times.

Comment on lines 609 to 613
marker = [agent_data.marker for agent_data in arguments]
zorder = [agent_data.zorder for agent_data in arguments]
edgecolors = [agent_data.edgecolors for agent_data in arguments]
linewidths = [agent_data.linewidths for agent_data in arguments]
alpha = [agent_data.alpha for agent_data in arguments]
Copy link
Member

Choose a reason for hiding this comment

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

same here, 5 repeated iterations

Copy link
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.

There are various things that can be done to improve this PR further. Let me know if you have questions.

@EwoutH EwoutH requested a review from sanika-n April 5, 2025 14:46
@EwoutH
Copy link
Member

EwoutH commented Apr 5, 2025

@Sahil-Chhoker / @sanika-n, could (one of) you review this PR?

Copy link

coderabbitai bot commented Apr 5, 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.


🪧 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

@aarav-shukla07
Copy link
Contributor Author

Hi @quaquel ,

Thank you for your valuable feedback!
Based on your suggestions, I’ve made the following changes:

  • Consolidated multiple iterations over agent_data_list into a single pass while constructing scatter_data.

  • Refactored collect_agent_data to return NumPy arrays directly, avoiding unnecessary intermediate structures.

  • Ensured compatibility across all grids and resolved the attribute issues that appeared during testing.

All tests are now passing locally after resolving the merge conflict. Please let me know if you’d prefer further optimizations (e.g., using structured arrays or different handling of defaults).

Looking forward to your thoughts!

@Sahil-Chhoker
Copy link
Collaborator

@Sahil-Chhoker / @sanika-n, could (one of) you review this PR?

Really sorry again, I am travelling most of the next week (until 10th) so I won't be able to find time to review this PR, @sanika-n is it alright if I leave the review to you?

@sanika-n
Copy link
Collaborator

sanika-n commented Apr 5, 2025

I am currently tied up with my proposal, but I can take this up after 8th

Copy link
Collaborator

@Sahil-Chhoker Sahil-Chhoker left a comment

Choose a reason for hiding this comment

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

Hey @aarav-shukla07, I took a little look at this PR, so to just start the review can you please start by incorporating quaquel's review? Also I see that the previous docstrings are all missing, I don't see any need to remove them, so fix that as well. And at last, can you fix the tests so that they actually pass?

@sanika-n
Copy link
Collaborator

Also, could you pls update the tests/test_components_matplotlib.py file as well? That still uses a dictionary for agent-portrayal, you can find the code here

@aarav-shukla07
Copy link
Contributor Author

Hello @Sahil-Chhoker @sanika-n
Since I was travelling for the last few days, so I wasn't able to changes the code, so sorry for that.
I will try my best to update the changes as fast as possible.
Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
breaking Release notes label enhancement Release notes label
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Shift from dict for agent_potrayal to an AgentPortrayalStyle class
5 participants