Skip to content

Allowing color mapping to integers in AgentPortrayalStyle #2818

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 2 commits into
base: main
Choose a base branch
from

Conversation

Sahil-Chhoker
Copy link
Collaborator

@Sahil-Chhoker Sahil-Chhoker commented Jul 22, 2025

Summary

Allowing color mapping to integers in AgentPortrayalStyle

Motive

This could only be achieved in the dict version of agent_portrayal, but also now possible in AgentPortrayalStyle.

Implementation

Main problem was the collect_agent_data function in matplotlib used to assume the color of edgecolors as the defined color if edgecolors are not defined, this removes this assumption and allows the mapping of color with a proper colormap.

Usage Examples

Boltzman wealth model works with this:

def agent_portrayal(agent):
    color = agent.wealth  # we are using a colormap to translate wealth to color
    return AgentPortrayalStyle(color=color)

def post_process(ax):
    ax.get_figure().colorbar(ax.collections[0], label="wealth", ax=ax)

# Create initial model instance
model = BoltzmannWealth(50, 10, 10)
renderer = SpaceRenderer(model, backend="matplotlib")

renderer.draw_structure()
renderer.draw_agents(agent_portrayal=agent_portrayal, cmap="viridis", vmin=0, vmax=10)
renderer.post_process = post_process

page = SolaraViz(
    model,
    renderer,
    components=[GiniPlot],
    model_params=model_params,
    name="Boltzmann Wealth Model",
)
page

Summary by CodeRabbit

  • Bug Fixes

    • Improved handling of agent edge colors in visualizations to prevent unintended color assignments.
  • New Features

    • Expanded support for agent color definitions to include numeric values, allowing greater flexibility in specifying colors.

@Sahil-Chhoker Sahil-Chhoker requested a review from tpike3 July 22, 2025 05:19
@Sahil-Chhoker
Copy link
Collaborator Author

@coderabbitai full review

Copy link

coderabbitai bot commented Jul 22, 2025

✅ Actions performed

Full review triggered.

Copy link

coderabbitai bot commented Jul 22, 2025

Walkthrough

The changes expand the accepted types for the color attribute in the AgentPortrayalStyle dataclass to include numeric values and remove code that previously set the edgecolors attribute to the agent's color when unset in the collect_agent_data method of the MatplotlibBackend class.

Changes

File(s) Change Summary
mesa/visualization/components/portrayal_components.py Expanded the color attribute type in AgentPortrayalStyle to include int and float.
mesa/visualization/backends/matplotlib_backend.py Removed logic that set edgecolors to the agent's color when edgecolors was None in collect_agent_data.

Estimated code review effort

1 (~5 minutes)

Possibly related PRs

Suggested labels

visualisation

Suggested reviewers

  • quaquel

Poem

A bunny with a painter’s touch,
Now colors can be numbers—such!
Edgecolors left alone,
While agents brightly shone.
With palettes wide, the models hop,
Matplotlib’s art won’t ever stop!
🐇🎨

✨ Finishing Touches
  • 📝 Generate Docstrings

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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.

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.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
mesa/visualization/components/portrayal_components.py (3)

49-49: Expose a reusable alias & inline comment for new numeric color support

The literal union is getting long and is repeated elsewhere in the codebase. Introduce a ColorLike alias (close to Matplotlib’s semantics) and add a short in-line comment so downstream maintainers immediately understand the intent.

-    color: str | tuple | int | float | None = "tab:blue"
+    # Accepts any Matplotlib-compatible color: name, RGB(A) tuple,
+    # or scalar (int/float) consumed by a colormap.
+    ColorLike = str | tuple | int | float
+    color: ColorLike | None = "tab:blue"

18-45: Sync the docstring with the new scalar-color capability

The descriptive block and example still mention only strings/tuples. Add one sentence and a tiny code snippet showing color=agent.wealth (scalar mapped through cmap). Prevents confusion for users scanning the docs.


49-55: Fail-fast validation for scalar colors

Now that bare numbers are accepted, negative values (or very large ones) will raise cryptic errors deep in Matplotlib. A quick __post_init__ guard such as:

if isinstance(self.color, (int, float)) and self.color < 0:
    raise ValueError("Scalar color values must be non-negative")

would surface problems earlier without noticeable overhead.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 47eff74 and e05956c.

📒 Files selected for processing (2)
  • mesa/visualization/backends/matplotlib_backend.py (0 hunks)
  • mesa/visualization/components/portrayal_components.py (1 hunks)
💤 Files with no reviewable changes (1)
  • mesa/visualization/backends/matplotlib_backend.py
⏰ Context from checks skipped due to timeout of 180000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: run-benchmarks

Copy link

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🔵 -0.8% [-1.3%, -0.4%] 🔵 +1.2% [+1.0%, +1.4%]
BoltzmannWealth large 🔵 -3.5% [-5.5%, -2.0%] 🟢 -9.0% [-11.1%, -6.7%]
Schelling small 🔵 -2.8% [-3.2%, -2.4%] 🔵 -2.8% [-3.9%, -1.9%]
Schelling large 🔵 -2.6% [-3.3%, -1.8%] 🟢 -9.2% [-12.4%, -6.3%]
WolfSheep small 🔵 -1.8% [-2.2%, -1.4%] 🔵 -0.6% [-1.2%, -0.0%]
WolfSheep large 🔵 -1.3% [-2.8%, +0.4%] 🔵 -1.5% [-3.5%, +0.5%]
BoidFlockers small 🔵 -1.9% [-2.6%, -1.3%] 🔵 -1.8% [-2.0%, -1.5%]
BoidFlockers large 🔵 -2.4% [-3.0%, -2.0%] 🔵 -2.3% [-2.8%, -1.7%]

@tpike3
Copy link
Member

tpike3 commented Jul 25, 2025

@Sahil-Chhoker looks good for the code rabbit review any concerns integrating its feedback on

  • Expose a reusable alias & inline comment for new numeric color support (comment 1)
  • Fail-fast validation for scalar colors (comment 3)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants