Skip to content

Introduction of Space Renderer #2803

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

Conversation

Sahil-Chhoker
Copy link
Collaborator

@Sahil-Chhoker Sahil-Chhoker commented Jun 5, 2025

Summary

Introduces SpaceRenderer into the Mesa visualization system, aiming to simplify and decouple the logic of drawing agents, grids, and property layers.

Motive

Part of my GSOC commitment.

Implementation

This PR introduces 2 new files, named space_renderer.py and space_drawers.py.

  • space_renderer.py:

    • Contains the SpaceRenderer class, the main backend for Solara to render the space, agents, and property layers.
    • Key methods include:
      • draw_structure(): Draws the grid structure of the space.
      • draw_propertylayer(): Draws property layers onto the space.
      • draw_agents(): Draws agents onto the space.
      • render(): A comprehensive method to draw all components at once.
    • Manages different rendering backends (Matplotlib, Altair).
    • Handles data collection for agents for both matplotlib and altair and maps agent coordinates.
  • space_drawers.py:

    • Provides specialized drawer classes for different Mesa space types:
      • OrthogonalSpaceDrawer: For standard grid spaces.
      • HexSpaceDrawer: For hexagonal grid spaces.
      • NetworkSpaceDrawer: For network-based spaces.
      • ContinuousSpaceDrawer: For continuous spaces.
      • VoronoiSpaceDrawer: For Voronoi diagram spaces.
    • These classes are used internally by SpaceRenderer to handle the specific drawing logic for each space structure as they contain the specific grid/space drawing logic.

Usage Examples

# for matplolib
renderer = SpaceRenderer(model, ax=ax, backend='matplotlib')
renderer.draw_structure()
renderer.draw_agents(agent_portrayal)
renderer.draw_propertylayer(propertylayer_portrayal)

# if want agents on different ax:
fig, ax = plt.subplot()
renderer.draw_agnets(agent_portrayal, ax=ax)

# for altair, no need to pass ax, if passed will be ignored with a warning
renderer.SpaceRenderer(model, backend="altair")

# if want to apply different modifications to the matplotlib axes
renderer.canvas.set_title("This is a Title")
renderer.canvas.set_xlabel("X-axis")
renderer.canvas.set_ylabel("Y-axis")
renderer.canvas.set_aspect("equal")

renderer.canvas.figure.set_size_inches(10, 10)

page = SolaraViz(
    model,
    renderer,
    components=[...],
    ...
)
page

Additional Context

Checkout the discussion in #2772.
Currently only contains the full coverage for matplotlib spaces, only Orthogonal spaces are available for altair (with property layers).

Summary by CodeRabbit

  • New Features
    • Introduced advanced visualization capabilities for agent-based model spaces, supporting orthogonal grids, hex grids, continuous spaces, Voronoi grids, and network grids.
    • Added a unified renderer that enables layered rendering of space structures, agents, and property layers using both matplotlib and Altair backends.
    • Enhanced the interactive visualization experience in the Solara interface with new components and rendering options.

Copy link

github-actions bot commented Jun 5, 2025

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🔵 +0.9% [-0.2%, +2.2%] 🔵 +0.3% [+0.0%, +0.5%]
BoltzmannWealth large 🔵 +0.1% [-0.7%, +0.8%] 🔵 +2.0% [+0.5%, +3.5%]
Schelling small 🔵 +0.4% [+0.2%, +0.6%] 🔵 -0.5% [-0.7%, -0.3%]
Schelling large 🔵 +0.3% [-1.5%, +3.2%] 🔵 -4.1% [-6.7%, -1.2%]
WolfSheep small 🔵 +0.3% [-0.1%, +0.6%] 🔵 -0.7% [-0.8%, -0.5%]
WolfSheep large 🔵 +1.0% [+0.6%, +1.3%] 🔵 -0.7% [-1.0%, -0.3%]
BoidFlockers small 🔵 +1.6% [+0.6%, +2.6%] 🔵 +0.3% [+0.1%, +0.5%]
BoidFlockers large 🔵 +1.6% [+1.0%, +2.1%] 🔵 -0.6% [-1.0%, -0.2%]

@Sahil-Chhoker
Copy link
Collaborator Author

@coderabbitai full review

Copy link

coderabbitai bot commented Jun 5, 2025

Walkthrough

A new SpaceRenderer class and supporting drawer modules are introduced for advanced visualization of Mesa model spaces, supporting multiple space types and rendering backends. The visualization API is updated to require and expose SpaceRenderer, with new Solara components and controllers integrated to utilize this renderer for flexible, layered agent-based model visualizations.

Changes

File(s) Change Summary
mesa/visualization/init.py Imported SpaceRenderer and added it to the __all__ list, making it a public API component.
mesa/visualization/solara_viz.py Updated Solara visualization to require a renderer argument, integrate space visualization via SpaceRenderer, and add new components.
mesa/visualization/space_drawers.py Introduced new module with drawer classes for orthogonal, hex, network, continuous, and Voronoi spaces, supporting matplotlib/Altair.
mesa/visualization/space_renderer.py Added new SpaceRenderer class for rendering model spaces, agents, and property layers with support for multiple backends and formats.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant SolaraViz
    participant SpaceRenderer
    participant Model

    User->>SolaraViz: Initialize with Model and SpaceRenderer
    SolaraViz->>Model: Access model's space/grid
    SolaraViz->>SpaceRenderer: Set space to model's space
    User->>SolaraViz: Interact (step, reset, etc.)
    SolaraViz->>SpaceRenderer: render(agent_portrayal, propertylayer_portrayal)
    SpaceRenderer->>Model: Collect agent/property data
    SpaceRenderer->>SpaceRenderer: Draw structure, agents, property layers
    SpaceRenderer-->>SolaraViz: Return visualization component
    SolaraViz-->>User: Display updated visualization
Loading

Possibly related PRs

Suggested labels

visualisation

Suggested reviewers

  • tpike3
  • quaquel

Poem

A rabbit with a painter's flair,
Now draws your grids with utmost care.
Hex, network, or orthogonal lines,
Spaces rendered—how it shines!
With Solara's help, the models gleam,
Agents dance in a vivid dream.
🐇✨

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

🧹 Nitpick comments (4)
mesa/visualization/space_renderer.py (1)

108-125: Consider simplifying the conditional logic.

The method works correctly, but the conditional structure could be simplified by removing elif after return statements.

 def _get_space_drawer(self):
     """Get appropriate space drawer based on space type."""
     if isinstance(self.space, OrthogonalGrid):
         return OrthogonalSpaceDrawer(self.space)
-    elif isinstance(self.space, HexGrid):
+    if isinstance(self.space, HexGrid):
         return HexSpaceDrawer(self.space)
-    elif isinstance(self.space, ContinuousSpace):
+    if isinstance(self.space, ContinuousSpace):
         return ContinuousSpaceDrawer(self.space)
-    elif isinstance(self.space, VoronoiGrid):
+    if isinstance(self.space, VoronoiGrid):
         return VoronoiSpaceDrawer(self.space)
-    elif isinstance(self.space, Network):
+    if isinstance(self.space, Network):
         return NetworkSpaceDrawer(self.space)
-    else:
-        raise ValueError(
-            f"Unsupported space type: {type(self.space).__name__}. "
-            "Supported types are OrthogonalGrid, HexGrid, ContinuousSpace, VoronoiGrid, and Network."
-        )
+    raise ValueError(
+        f"Unsupported space type: {type(self.space).__name__}. "
+        "Supported types are OrthogonalGrid, HexGrid, ContinuousSpace, VoronoiGrid, and Network."
+    )
🧰 Tools
🪛 Pylint (3.3.7)

[refactor] 110-124: Unnecessary "elif" after "return", remove the leading "el" from "elif"

(R1705)

mesa/visualization/solara_viz.py (3)

228-228: Fix type annotation.

Use the proper Any type from the typing module instead of lowercase any.

-    dependencies: list[any] | None = None,
+    dependencies: list[Any] | None = None,

You'll also need to import Any from typing:

from typing import TYPE_CHECKING, Literal
+from typing import TYPE_CHECKING, Literal, Any

240-240: Simplify space assignment logic.

The current logic can be simplified using a more direct approach.

-    renderer.space = getattr(model, "grid", None) or getattr(model, "space", None)
+    renderer.space = getattr(model, "grid", getattr(model, "space", None))

276-317: Consider refactoring complex Altair rendering logic.

The Altair backend logic is quite complex and could benefit from being broken down into smaller helper methods for better maintainability and testing.

Consider extracting helper methods like:

  • _build_spatial_charts_list()
  • _combine_charts_with_colorbar()
  • _create_final_chart()

This would improve readability and make the component easier to test and maintain.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 759673a and 2efaf2f.

📒 Files selected for processing (4)
  • mesa/visualization/__init__.py (1 hunks)
  • mesa/visualization/solara_viz.py (14 hunks)
  • mesa/visualization/space_drawers.py (1 hunks)
  • mesa/visualization/space_renderer.py (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
mesa/visualization/space_drawers.py (5)
mesa/discrete_space/voronoi.py (1)
  • VoronoiGrid (175-266)
mesa/space.py (1)
  • SingleGrid (962-1005)
mesa/discrete_space/network.py (1)
  • Network (22-77)
mesa/discrete_space/cell_collection.py (1)
  • cells (92-93)
mesa/discrete_space/discrete_space.py (1)
  • all_cells (151-155)
🪛 Pylint (3.3.7)
mesa/visualization/space_renderer.py

[refactor] 72-72: Too many instance attributes (10/7)

(R0902)


[refactor] 110-124: Unnecessary "elif" after "return", remove the leading "el" from "elif"

(R1705)


[refactor] 161-167: Unnecessary "else" after "return", remove the "else" and de-indent the code inside it

(R1705)


[refactor] 172-179: Unnecessary "elif" after "return", remove the leading "el" from "elif"

(R1705)


[refactor] 181-181: Too many local variables (18/15)

(R0914)


[refactor] 288-288: Too many local variables (24/15)

(R0914)


[refactor] 476-476: Too many local variables (16/15)

(R0914)


[refactor] 572-589: Unnecessary "else" after "return", remove the "else" and de-indent the code inside it

(R1705)


[refactor] 592-592: Too many local variables (28/15)

(R0914)


[refactor] 592-592: Too many branches (20/12)

(R0912)


[refactor] 592-592: Too many statements (69/50)

(R0915)


[refactor] 732-732: Too many local variables (42/15)

(R0914)


[refactor] 732-732: Too many statements (69/50)

(R0915)


[refactor] 1006-1016: Unnecessary "else" after "return", remove the "else" and de-indent the code inside it

(R1705)


[refactor] 1027-1041: Unnecessary "else" after "return", remove the "else" and de-indent the code inside it

(R1705)


[refactor] 1046-1050: Unnecessary "else" after "return", remove the "else" and de-indent the code inside it

(R1705)

mesa/visualization/space_drawers.py

[refactor] 93-93: Too many instance attributes (10/7)

(R0902)


[refactor] 321-321: Too many instance attributes (8/7)

(R0902)

mesa/visualization/solara_viz.py

[refactor] 224-224: Either all return statements in a function should return an expression, or none of them should.

(R1710)

🔇 Additional comments (9)
mesa/visualization/__init__.py (1)

16-16: LGTM!

The changes properly expose the new SpaceRenderer class as part of the public API.

Also applies to: 24-24

mesa/visualization/space_renderer.py (1)

813-819: Verify the data indexing consistency between matplotlib and altair implementations.

The data preparation for Altair uses different indexing compared to the matplotlib version. In matplotlib (line 688), the data is transposed with data.T, while here the DataFrame is created with x as the first dimension.

Ensure this difference is intentional and that both backends produce the same visual output for property layers.

mesa/visualization/solara_viz.py (7)

34-34: Import added correctly.

The altair import is appropriately added to support the new Altair backend functionality in SpaceRendererComponent.


43-43: SpaceRenderer integration looks good.

The import and parameter addition are correctly implemented. The documentation is appropriately updated to reflect the new required renderer parameter.

Also applies to: 57-57, 80-80


137-140: Good defensive programming with component list copying.

Creating a copy of the components list before modification prevents unintended side effects on the original list. The space component integration is cleanly implemented.


179-179: Renderer parameter correctly passed to controllers.

Both ModelController and SimulatorController properly receive the renderer parameter for consistent state management.

Also applies to: 189-189


202-204: CommandConsole handling updated consistently.

The logic correctly checks and removes CommandConsole from display_components instead of the original components list, maintaining consistency with the new component handling approach.


213-221: Clean component factory function.

The create_space_component function provides a clean way to create space visualization components using closures. The implementation is simple and effective.


456-458: Model reset renderer updates implemented correctly.

Both ModelController and SimulatorController properly update the renderer's space attribute when models are reset. The fallback logic using getattr handles both grid and space attributes appropriately.

Also applies to: 583-585

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.

1 participant