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

Open
wants to merge 62 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 comprehensive spatial visualization support for various grid types including orthogonal, hexagonal, continuous, Voronoi, and network grids.
    • Added a unified SpaceRenderer enabling layered rendering of model spaces, agents, and property layers with both Matplotlib and Altair backends.
    • Enhanced Solara interface with new components for reactive space rendering and improved model control integration.
    • Provided new visualization backends for interactive and static rendering, supporting detailed customization of agent and property layer appearances.

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.
mesa/visualization/backends/init.py Added new module exporting AltairBackend and MatplotlibBackend as visualization backends.
mesa/visualization/backends/abstract_renderer.py Added abstract base class AbstractRenderer defining interface for visualization backends with methods for drawing structure, agents, and property layers.
mesa/visualization/backends/altair_backend.py Added AltairBackend class implementing visualization backend using Altair for interactive spatial visualizations.
mesa/visualization/backends/matplotlib_backend.py Added MatplotlibBackend class implementing visualization backend using Matplotlib for static spatial visualizations.

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

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

@Sahil-Chhoker
Copy link
Collaborator Author

@tpike3, thanks for checking. Missing out these little things is what I was afraid of.

  1. I made space renderer optional but never added the null check so that's covered now.
  2. It's default solara viz behavior (existed before this PR) that if there is no components list passed, it automatically draws a altair space, it will not happen if you pass a component's list even if it's empty. Should I remove this functionality?

@tpike3
Copy link
Member

tpike3 commented Jun 29, 2025

@tpike3, thanks for checking. Missing out these little things is what I was afraid of.

  1. I made space renderer optional but never added the null check so that's covered now.
  2. It's default solara viz behavior (existed before this PR) that if there is no components list passed, it automatically draws a altair space, it will not happen if you pass a component's list even if it's empty. Should I remove this functionality?

@Sahil-Chhoker Thanks --- for #2 we need to keep it backwards compatible. There may be a couple ways to do this, but off the top of my head, can you use renderer to override the lack of components?

@tpike3
Copy link
Member

tpike3 commented Jun 29, 2025

@Sahil-Chhoker running through some more variants -

  • The Solara resizing feature of the plots is better, but still clunky, could you take a look at the again

I pretty sure you have said this, but you need to update the Altair plot. Both backends should produce the same look and feel

Right now

Plot Matplotlib Altair
position in center of x,y grid on intersection of x,y
labels no x y labels has x,y labels
legend no legend has legend

Also for the boltzmann wealth model altair is just showing circles and has a legend for opacity but the circles are not filling in.

Still some very good work

@tpike3
Copy link
Member

tpike3 commented Jun 29, 2025

Great work on the SpaceRenderer system! The backend abstraction and separation of concerns look really solid. I also really like the API, it's quite elegant overall.

I wanted to discuss one architectural question: should we consider backend-specific subclasses instead of the current string-based backend selection?

Current approach:

renderer = SpaceRenderer(model, backend="matplotlib")
renderer.draw_structure(figsize=(10, 8))  # Works with matplotlib, ignored by altair

Potential subclass approach:

renderer = MatplotlibSpaceRenderer(model)  
renderer.draw_structure(figsize=(10, 8))   # Type-safe, IDE knows this parameter
renderer.save_figure("output.png")        # Backend-specific methods possible

The main advantage would be type safety - IDEs could provide proper autocomplete and catch invalid parameters at development time rather than runtime. Each backend could also expose specific methods without cluttering the base API.

We could maintain the current simple API with a factory function:

# Simple usage (returns appropriate subclass)
renderer = SpaceRenderer(model, backend="matplotlib")

# Advanced usage (direct class access)
from mesa.visualization.backends import MatplotlibSpaceRenderer
renderer = MatplotlibSpaceRenderer(model)

The common functionality would stay in the base SpaceRenderer class, so code duplication would be minimal. The current architecture already has the backend abstraction that would make this transition straightforward.

The trade-off is slightly more complexity for advanced users who want full type safety, though the factory function would keep the simple cases unchanged.

@EwoutH, @Sahil-Chhoker and I talked about this on Thursday and I was pretty reluctant as I thought it was an impossible tradeoff, but having some time to think on this an look through the code some more in this context I can see the appeal and a possible way forward.

Goal being get to ----

# Simple usage (returns appropriate subclass)
renderer = SpaceRenderer(model, backend="matplotlib")

# Advanced usage (direct class access)
from mesa.visualization.backends import MatplotlibSpaceRenderer
renderer = MatplotlibSpaceRenderer(model)

@Sahil-Chhoker Looking through the code to do this my impression is that this could be accomplished by
breaking apart space_drawerer and space_renderer so all the backend specific stuff is in their respective files and then the space_drawer and space_renderer functions support the backend classes. However, I didn't code it out and there is always unexpected challenges.

As you are ahead of schedule, take a look and let us know what you think.

@Sahil-Chhoker
Copy link
Collaborator Author

  • The Solara resizing feature of the plots is better, but still clunky, could you take a look at the again

The solara resizing feature was never in our control, can't fix it.

I pretty sure you have said this, but you need to update the Altair plot. Both backends should produce the same look and feel

Both backends have their own quirks, and adding code to align the visual look for both makes them less flexible, therefore I think they are better left natural.

Also for the boltzmann wealth model altair is just showing circles and has a legend for opacity but the circles are not filling in.

Not all the functionalities of matplotlib can be added to altair, but this one seemed important so I added it.

Still some very good work

Thanks.

@Sahil-Chhoker
Copy link
Collaborator Author

@Sahil-Chhoker Looking through the code to do this my impression is that this could be accomplished by breaking apart space_drawerer and space_renderer so all the backend specific stuff is in their respective files and then the space_drawer and space_renderer functions support the backend classes. However, I didn't code it out and there is always unexpected challenges.

I'm sorry but this doesn't clear the picture to me, can you explain your approach to me more thoroughly.

@tpike3
Copy link
Member

tpike3 commented Jun 30, 2025

@Sahil-Chhoker Looking through the code to do this my impression is that this could be accomplished by breaking apart space_drawerer and space_renderer so all the backend specific stuff is in their respective files and then the space_drawer and space_renderer functions support the backend classes. However, I didn't code it out and there is always unexpected challenges.

I'm sorry but this doesn't clear the picture to me, can you explain your approach to me more thoroughly.

Just to emphasize, this is very approximate as I have not tried refactoring your code to truly assess the feasibility.

Goal is that the current approach works and each backend can function if accessed directly.

My thought is what if you take the draw_matplolib, draw_altair from each of the space_drawer classes and put them in the MatplotlibBackend and AltairBackend . space_drawer could then call them and they could be called directly. This would obviously take more much refactoring then I am indicating.

However if I am understanding the code correctly, currently it is

space_render calls space_drawer calls respective backend

This would be more like

space_render calls space_drawer

space_render calls respective backend

space_drawer and respective backend call each other to produce space_render.

Let me know if this makes sense, as well as your thoughts and concerns.

@Sahil-Chhoker
Copy link
Collaborator Author

Sahil-Chhoker commented Jun 30, 2025

You are asking me to break the space_drawer classes into their Matplotlib and Altair parts, but that's not possible. The reason I made them together was that all the space drawing related logic is unified and we don't have to keep passing arguments here and there, what I mean is that all the logic need to draw the space in both matplotlib and altair is in the drawer classes like size, padding, viz limits, etc. so we can easily keep track of them, and breaking them apart just messes with my design entirely.

space_render calls space_drawer calls respective backend

SpaceRenderer calls the respective backend, and backend calls the respective space drawer.

@tpike3
Copy link
Member

tpike3 commented Jul 1, 2025

You are asking me to break the space_drawer classes into their Matplotlib and Altair parts, but that's not possible. The reason I made them together was that all the space drawing related logic is unified and we don't have to keep passing arguments here and there, what I mean is that all the logic need to draw the space in both matplotlib and altair is in the drawer classes like size, padding, viz limits, etc. so we can easily keep track of them, and breaking them apart just messes with my design entirely.

space_render calls space_drawer calls respective backend

SpaceRenderer calls the respective backend, and backend calls the respective space drawer.

Hmmm ok.. well keep cleaning up its performance, and let me chew on this for a bit, longer. @EwoutH and @quaquel would you be able to make Thursday at 1830 CEST to discuss?

@Sahil-Chhoker
Copy link
Collaborator Author

I've also cleared up all the known irregularities, so this PR is good to go from my side, let me know if you find something concerning.

Copy link
Member

@EwoutH EwoutH left a comment

Choose a reason for hiding this comment

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

I'm going to trust both your calls on it. Let's move forward.

Thanks for the extensive effort, and especially the constructive discussions!

(when merging, please Squash and merge)

@EwoutH
Copy link
Member

EwoutH commented Jul 1, 2025

I have an additional thought I want to note, but not blocking for this PR.

The whole idea behind SpaceRenderer is to keep things backend-agnostic. If we start adding subclass-specific methods like matplotlib_renderer.set_grid_lines() or altair_renderer.set_interactive_tooltip(), it kind of defeats the purpose — switching backends would suddenly become messy instead of seamless.

I don't think the switching backends should need to be seemless. You purposely pick one that fits your model and features. Not every backend will be optimal for everything - or even have to be able to do or render anything (for example, I'm perfectly fine with only having one backend that supports NetworkSpaces).

If it looks like this it would be fine:

image

Everything that's common goes into a general SpaceRenderer, in the back-end specific subclasses we can support specific features of specific backends.

But, I think this also could be done after this PR is merged, we can always create additional subclasses and support those.

@Sahil-Chhoker
Copy link
Collaborator Author

The whole idea behind SpaceRenderer is to keep things backend-agnostic. If we start adding subclass-specific methods like matplotlib_renderer.set_grid_lines() or altair_renderer.set_interactive_tooltip(), it kind of defeats the purpose — switching backends would suddenly become messy instead of seamless.

I don't think the switching backends should need to be seemless. You purposely pick one that fits your model and features. Not every backend will be optimal for everything - or even have to be able to do or render anything (for example, I'm perfectly fine with only having one backend that supports NetworkSpaces).

I like this way of thinking and I now think this is more practical. Thanks for the suggestion, I'll be sure to explore in this direction and see what I can come up with in the future.

@EwoutH
Copy link
Member

EwoutH commented Jul 3, 2025

(I will leave the final call for review and merge to @tpike3)

@tpike3
Copy link
Member

tpike3 commented Jul 3, 2025

@Sahil-Chhoker

I think there is a little more clean up to do ---

Running boltzmann_wealth_model from examples:

  • altair : looks great! runs really well
  • matplotlib: I get this error
 File "C:\Users\thoma\Documents\GitHub\dev\mesa\mesa\visualization\solara_viz.py", line 248, in SpaceRendererComponent
    renderer.canvas.lines[:],
    ^^^^^^^^^^^^^^^
  File "C:\Users\thoma\Documents\GitHub\dev\mesa\mesa\visualization\space_renderer.py", line 315, in canvas
    ax = self.backend_renderer.canvas
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'MatplotlibBackend' object has no attribute 'canvas'. Did you mean: '_canvas'?

Running sugerscape_g1mt from examples:

  • altair:

    • works with just draw_agents
    • when I try and add in the property layer which may need to be updated but defined using--
    def propertylayer_portrayal(layer):
    if layer.name == "sugar":
      return PropertyLayerStyle(
          color="blue", alpha=0.8, colorbar=True, vmin=0, vmax=10
      )
    return PropertyLayerStyle(color="red", alpha=0.8, colorbar=True, vmin=0, vmax=10
    

    I get :

    TypeError: Objects with 'config' attribute cannot be used within VConcatChart. Consider defining the config attribute in the   
    VConcatChart object instead.
    
  • matplolib : same error as above

Let me know if you need any more info or want to to correct anything on my end.

@Sahil-Chhoker
Copy link
Collaborator Author

@tpike3, I've made all the necessary changes, please give them a check. If everything comes out fine then this PR can be merged.

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

Successfully merging this pull request may close these issues.

4 participants