Skip to content

Updating Examples and Docs inline with the new API. #2819

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

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

Sahil-Chhoker
Copy link
Collaborator

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

Summary

Updating the examples and docs showcasing the usage of the new API.

Motive

Part of my GSoC commitment.

Implementation

Updated the examples to include the basic usage of renderer with comments explaining what the code is actually doing.

Additional Notes

@tpike3, I've updated basic examples showcasing basic functionalities of the renderer, please review them and tell me how can they be improved.
One functionality I've left out is passing the kwargs to draw_structure to customize how the grid is drawn, I couldn't find a good place to fit it in, in the basic examples, maybe you can suggest something.

Summary by CodeRabbit

  • New Features

    • Enhanced visualization in multiple examples by introducing a more flexible renderer for displaying agents and grids.
    • Updated agent portrayal to use a dedicated style object, enabling improved customization of appearance.
  • Bug Fixes

    • Improved color schemes and marker sizing for better visual clarity in agent-based models.
  • Documentation

    • Added and updated comments to clarify visualization setup and rendering steps.
  • Refactor

    • Replaced previous visualization components with a unified renderer approach across several example applications.
    • Updated plotting functions to use more modern libraries and styling options.

Copy link

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🔵 +2.7% [+1.7%, +3.7%] 🔵 +0.0% [-0.2%, +0.3%]
BoltzmannWealth large 🔵 +1.8% [+1.0%, +2.7%] 🔵 +5.1% [+1.1%, +8.7%]
Schelling small 🔵 +2.2% [+2.0%, +2.5%] 🔵 +2.2% [+1.8%, +2.6%]
Schelling large 🔵 +1.4% [+0.9%, +1.9%] 🔴 +7.8% [+5.5%, +10.4%]
WolfSheep small 🔵 +1.9% [+1.6%, +2.2%] 🔵 +2.1% [+1.8%, +2.4%]
WolfSheep large 🔴 +5.3% [+4.5%, +6.0%] 🔴 +10.6% [+8.5%, +12.9%]
BoidFlockers small 🔵 -0.2% [-0.9%, +0.5%] 🔵 -1.4% [-1.5%, -1.2%]
BoidFlockers large 🔵 -0.3% [-0.9%, +0.4%] 🔵 -0.5% [-0.8%, -0.1%]

@Sahil-Chhoker
Copy link
Collaborator Author

@coderabbitai full review

Copy link

coderabbitai bot commented Jul 23, 2025

✅ Actions performed

Full review triggered.

@Sahil-Chhoker Sahil-Chhoker requested a review from tpike3 July 23, 2025 03:50
Copy link

coderabbitai bot commented Jul 23, 2025

Walkthrough

This update refactors several Mesa example applications to use the new SpaceRenderer and AgentPortrayalStyle classes for visualization. It replaces previous usage of make_space_component and plain dictionaries for agent portrayal, updating rendering logic and imports accordingly. Some plotting post-processing functions are also revised.

Changes

File(s) Change Summary
mesa/examples/basic/boid_flockers/app.py Refactored to use SpaceRenderer and AgentPortrayalStyle; updated agent portrayal logic and visualization setup.
mesa/examples/basic/boltzmann_wealth_model/app.py Switched to SpaceRenderer for visualization; agent portrayal now uses AgentPortrayalStyle; updated comments.
mesa/examples/basic/conways_game_of_life/app.py Replaced space component with SpaceRenderer; agent portrayal now uses AgentPortrayalStyle; minor size tweak.
mesa/examples/basic/schelling/app.py Visualization now uses SpaceRenderer; agent portrayal unchanged; added explanatory comments.
mesa/examples/basic/virus_on_network/app.py Migrated to SpaceRenderer and AgentPortrayalStyle; updated colors, size, and post-processing for plots.

Sequence Diagram(s)

sequenceDiagram
    participant Model
    participant SpaceRenderer
    participant AgentPortrayalStyle
    participant SolaraViz

    Model->>SpaceRenderer: Initialize with model and backend
    SpaceRenderer->>AgentPortrayalStyle: Use for agent portrayal
    SpaceRenderer->>SpaceRenderer: Render grid and agents
    SpaceRenderer->>SolaraViz: Pass renderer as component
    SolaraViz->>SpaceRenderer: Display visualization
Loading

Estimated code review effort

3 (~45 minutes)

Possibly related PRs

Suggested labels

visualisation

Suggested reviewers

  • tpike3
  • quaquel

Poem

A rabbit hopped through grids anew,
With colors bright and markers true.
Renderers now take the stage,
As agents dance from cage to cage.
Portrayal styles, so neat and spry—
Mesa’s world, a clearer sky!
🐇✨

✨ 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: 1

🔭 Outside diff range comments (1)
mesa/examples/basic/schelling/app.py (1)

18-44: Fix invalid marker usage causing pipeline failure.

The matplotlib backend doesn't support image file paths as markers. The pipeline failure confirms this: "ValueError caused by unrecognized marker style './resources/orange_happy.png'".

Replace image file paths with valid matplotlib markers:

def agent_portrayal(agent):
    style = AgentPortrayalStyle(
        x=agent.cell.coordinate[0],
        y=agent.cell.coordinate[1],
-        marker="./resources/orange_happy.png",
+        marker="o",  # Use circle marker
        size=75,
    )
    if agent.type == 0:
        if agent.happy:
            style.update(
-                ("marker", "./resources/blue_happy.png"),
+                ("marker", "s"),  # Use square marker
            )
        else:
            style.update(
-                ("marker", "./resources/blue_unhappy.png"),
+                ("marker", "^"),  # Use triangle marker
                ("size", 50),
                ("zorder", 2),
            )
    else:
        if not agent.happy:
            style.update(
-                ("marker", "./resources/orange_unhappy.png"),
+                ("marker", "v"),  # Use inverted triangle marker
                ("size", 50),
                ("zorder", 2),
            )
    return style
🧹 Nitpick comments (2)
mesa/examples/basic/schelling/app.py (1)

60-67: Update comments to reflect actual implementation.

The comments mention "images as markers" but the code uses matplotlib marker symbols, not actual image files.

-# Note: Models with images as markers are very performance intensive.
+# Note: The renderer provides a unified interface for drawing agents and grid structure.
# Here we use renderer.render() to render the agents and grid in one go.
# This function always renders the grid and then renders the agents or
# property layers on top of it if specified. It also supports passing the
# post_process function to fine-tune the plot after rendering in itself.
mesa/examples/basic/boid_flockers/app.py (1)

20-34: Optimize marker application in style update.

The marker caching approach is excellent for performance. However, line 33 redundantly reapplies the same marker that was already set.

    if neighbors >= 2:
-        boid_style.update(("color", "green"), ("marker", MARKER_CACHE[rounded_deg]))
+        boid_style.update(("color", "green"))

The marker is already set during initial style creation, so it doesn't need to be reapplied when only the color changes.

📜 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 377f301.

📒 Files selected for processing (5)
  • mesa/examples/basic/boid_flockers/app.py (3 hunks)
  • mesa/examples/basic/boltzmann_wealth_model/app.py (3 hunks)
  • mesa/examples/basic/conways_game_of_life/app.py (3 hunks)
  • mesa/examples/basic/schelling/app.py (2 hunks)
  • mesa/examples/basic/virus_on_network/app.py (2 hunks)
🧠 Learnings (5)
📓 Common learnings
Learnt from: Sahil-Chhoker
PR: projectmesa/mesa#2803
File: mesa/visualization/backends/altair_backend.py:312-553
Timestamp: 2025-06-20T16:44:20.677Z
Learning: In mesa/visualization/backends/altair_backend.py, the author prefers to keep the draw_propertylayer method intact despite its complexity, as they believe breaking it into smaller functions would divert attention from the main logic flow. The method is well-documented and follows a clear sequence of operations for property layer rendering.
mesa/examples/basic/schelling/app.py (1)

Learnt from: Sahil-Chhoker
PR: #2803
File: mesa/visualization/backends/altair_backend.py:312-553
Timestamp: 2025-06-20T16:44:20.677Z
Learning: In mesa/visualization/backends/altair_backend.py, the author prefers to keep the draw_propertylayer method intact despite its complexity, as they believe breaking it into smaller functions would divert attention from the main logic flow. The method is well-documented and follows a clear sequence of operations for property layer rendering.

mesa/examples/basic/boltzmann_wealth_model/app.py (1)

Learnt from: Sahil-Chhoker
PR: #2803
File: mesa/visualization/backends/altair_backend.py:312-553
Timestamp: 2025-06-20T16:44:20.677Z
Learning: In mesa/visualization/backends/altair_backend.py, the author prefers to keep the draw_propertylayer method intact despite its complexity, as they believe breaking it into smaller functions would divert attention from the main logic flow. The method is well-documented and follows a clear sequence of operations for property layer rendering.

mesa/examples/basic/boid_flockers/app.py (1)

Learnt from: Sahil-Chhoker
PR: #2803
File: mesa/visualization/backends/altair_backend.py:312-553
Timestamp: 2025-06-20T16:44:20.677Z
Learning: In mesa/visualization/backends/altair_backend.py, the author prefers to keep the draw_propertylayer method intact despite its complexity, as they believe breaking it into smaller functions would divert attention from the main logic flow. The method is well-documented and follows a clear sequence of operations for property layer rendering.

mesa/examples/basic/virus_on_network/app.py (1)

Learnt from: Sahil-Chhoker
PR: #2803
File: mesa/visualization/backends/altair_backend.py:312-553
Timestamp: 2025-06-20T16:44:20.677Z
Learning: In mesa/visualization/backends/altair_backend.py, the author prefers to keep the draw_propertylayer method intact despite its complexity, as they believe breaking it into smaller functions would divert attention from the main logic flow. The method is well-documented and follows a clear sequence of operations for property layer rendering.

🧬 Code Graph Analysis (2)
mesa/examples/basic/conways_game_of_life/app.py (2)
mesa/visualization/space_renderer.py (1)
  • SpaceRenderer (44-394)
mesa/visualization/components/portrayal_components.py (1)
  • AgentPortrayalStyle (18-73)
mesa/examples/basic/boltzmann_wealth_model/app.py (2)
mesa/visualization/space_renderer.py (1)
  • SpaceRenderer (44-394)
mesa/visualization/components/portrayal_components.py (1)
  • AgentPortrayalStyle (18-73)
🪛 GitHub Actions: build
mesa/examples/basic/schelling/app.py

[error] 67-67: Test failure in test_schelling_model: ValueError caused by unrecognized marker style './resources/orange_happy.png' in matplotlib scatter plot marker setting.

mesa/examples/basic/boltzmann_wealth_model/app.py

[error] 54-54: Test failure in test_boltzmann_model: ValueError due to invalid RGBA argument np.int64(1) in matplotlib color handling during agent rendering.

🧰 Additional context used
🧠 Learnings (5)
📓 Common learnings
Learnt from: Sahil-Chhoker
PR: projectmesa/mesa#2803
File: mesa/visualization/backends/altair_backend.py:312-553
Timestamp: 2025-06-20T16:44:20.677Z
Learning: In mesa/visualization/backends/altair_backend.py, the author prefers to keep the draw_propertylayer method intact despite its complexity, as they believe breaking it into smaller functions would divert attention from the main logic flow. The method is well-documented and follows a clear sequence of operations for property layer rendering.
mesa/examples/basic/schelling/app.py (1)

Learnt from: Sahil-Chhoker
PR: #2803
File: mesa/visualization/backends/altair_backend.py:312-553
Timestamp: 2025-06-20T16:44:20.677Z
Learning: In mesa/visualization/backends/altair_backend.py, the author prefers to keep the draw_propertylayer method intact despite its complexity, as they believe breaking it into smaller functions would divert attention from the main logic flow. The method is well-documented and follows a clear sequence of operations for property layer rendering.

mesa/examples/basic/boltzmann_wealth_model/app.py (1)

Learnt from: Sahil-Chhoker
PR: #2803
File: mesa/visualization/backends/altair_backend.py:312-553
Timestamp: 2025-06-20T16:44:20.677Z
Learning: In mesa/visualization/backends/altair_backend.py, the author prefers to keep the draw_propertylayer method intact despite its complexity, as they believe breaking it into smaller functions would divert attention from the main logic flow. The method is well-documented and follows a clear sequence of operations for property layer rendering.

mesa/examples/basic/boid_flockers/app.py (1)

Learnt from: Sahil-Chhoker
PR: #2803
File: mesa/visualization/backends/altair_backend.py:312-553
Timestamp: 2025-06-20T16:44:20.677Z
Learning: In mesa/visualization/backends/altair_backend.py, the author prefers to keep the draw_propertylayer method intact despite its complexity, as they believe breaking it into smaller functions would divert attention from the main logic flow. The method is well-documented and follows a clear sequence of operations for property layer rendering.

mesa/examples/basic/virus_on_network/app.py (1)

Learnt from: Sahil-Chhoker
PR: #2803
File: mesa/visualization/backends/altair_backend.py:312-553
Timestamp: 2025-06-20T16:44:20.677Z
Learning: In mesa/visualization/backends/altair_backend.py, the author prefers to keep the draw_propertylayer method intact despite its complexity, as they believe breaking it into smaller functions would divert attention from the main logic flow. The method is well-documented and follows a clear sequence of operations for property layer rendering.

🧬 Code Graph Analysis (2)
mesa/examples/basic/conways_game_of_life/app.py (2)
mesa/visualization/space_renderer.py (1)
  • SpaceRenderer (44-394)
mesa/visualization/components/portrayal_components.py (1)
  • AgentPortrayalStyle (18-73)
mesa/examples/basic/boltzmann_wealth_model/app.py (2)
mesa/visualization/space_renderer.py (1)
  • SpaceRenderer (44-394)
mesa/visualization/components/portrayal_components.py (1)
  • AgentPortrayalStyle (18-73)
🪛 GitHub Actions: build
mesa/examples/basic/schelling/app.py

[error] 67-67: Test failure in test_schelling_model: ValueError caused by unrecognized marker style './resources/orange_happy.png' in matplotlib scatter plot marker setting.

mesa/examples/basic/boltzmann_wealth_model/app.py

[error] 54-54: Test failure in test_boltzmann_model: ValueError due to invalid RGBA argument np.int64(1) in matplotlib color handling during agent rendering.

🔇 Additional comments (15)
mesa/examples/basic/schelling/app.py (2)

7-7: Import change looks good.

The addition of SpaceRenderer import aligns with the new visualization API.


71-79: SolaraViz configuration updated correctly.

The direct usage of the renderer object instead of the old component approach is consistent with the new API.

mesa/examples/basic/conways_game_of_life/app.py (4)

4-6: Import changes align with new API.

The replacement of old components with SpaceRenderer and AgentPortrayalStyle is consistent with the modernization effort.


9-14: Agent portrayal correctly implemented.

The function properly returns AgentPortrayalStyle with valid matplotlib markers and appropriate styling based on agent state.


58-66: Renderer setup is well-implemented.

The explicit use of draw_agents() followed by post_process assignment provides clear control over the rendering pipeline. The detailed comments effectively explain the renderer's capabilities.


73-78: SolaraViz configuration follows new API correctly.

The direct renderer usage aligns with the modernized visualization approach.

mesa/examples/basic/boltzmann_wealth_model/app.py (3)

5-5: Import changes support new visualization API.

The addition of SpaceRenderer and AgentPortrayalStyle aligns with the modernization effort across examples.

Also applies to: 8-8


44-55: Renderer setup is well-documented and structured.

The explicit rendering steps with colormap configuration provide clear control over the visualization pipeline. The comprehensive comments effectively explain the process.


70-76: SolaraViz configuration updated correctly.

The combination of the renderer with additional plot components demonstrates proper usage of the new API.

mesa/examples/basic/virus_on_network/app.py (4)

13-13: Import changes support Altair backend usage.

The imports align with the new visualization API and demonstrate cross-backend compatibility.

Also applies to: 16-16


19-25: Agent portrayal correctly updated for new API.

The color scheme simplification and size increase improve readability while maintaining proper state-based visualization.


96-108: Post-processing function properly adapted for Altair.

The chart styling and legend configuration demonstrate proper Altair usage for visualization enhancement.


111-131: Altair backend implementation is well-integrated.

The consistent use of Altair across the renderer and plot components with matching color schemes demonstrates proper cross-component coordination.

mesa/examples/basic/boid_flockers/app.py (2)

9-10: Import changes align with new visualization API.

The consolidated import and addition of AgentPortrayalStyle support the modernized rendering approach.


75-83: Renderer setup demonstrates concise API usage.

The method chaining approach effectively combines renderer creation and rendering in a single line while maintaining readability.

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

Successfully merging this pull request may close these issues.

1 participant