-
Notifications
You must be signed in to change notification settings - Fork 1k
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
base: main
Are you sure you want to change the base?
Conversation
Performance benchmarks:
|
@coderabbitai full review |
WalkthroughA new Changes
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
Poem
✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
Documentation and Community
|
There was a problem hiding this 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
afterreturn
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 lowercaseany
.- 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
📒 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 originalcomponents
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
for more information, see https://pre-commit.ci
for more information, see https://pre-commit.ci
@tpike3, thanks for checking. Missing out these little things is what I was afraid of.
|
@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? |
@Sahil-Chhoker running through some more variants -
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
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 |
@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 As you are ahead of schedule, take a look and let us know what you think. |
The solara resizing feature was never in our control, can't fix it.
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.
Not all the functionalities of matplotlib can be added to altair, but this one seemed important so I added it.
Thanks. |
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 However if I am understanding the code correctly, currently it is
This would be more like
Let me know if this makes sense, as well as your thoughts and concerns. |
You are asking me to break the
|
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? |
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. |
There was a problem hiding this 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)
I have an additional thought I want to note, but not blocking for this PR.
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: 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. |
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. |
(I will leave the final call for review and merge to @tpike3) |
I think there is a little more clean up to do --- Running
Running sugerscape_g1mt from examples:
Let me know if you need any more info or want to to correct anything on my end. |
for more information, see https://pre-commit.ci
@tpike3, I've made all the necessary changes, please give them a check. If everything comes out fine then this PR can be merged. |
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
andspace_drawers.py
.space_renderer.py
:SpaceRenderer
class, the main backend for Solara to render the space, agents, and property layers.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.space_drawers.py
:OrthogonalSpaceDrawer
: For standard grid spaces.HexSpaceDrawer
: For hexagonal grid spaces.NetworkSpaceDrawer
: For network-based spaces.ContinuousSpaceDrawer
: For continuous spaces.VoronoiSpaceDrawer
: For Voronoi diagram spaces.SpaceRenderer
to handle the specific drawing logic for each space structure as they contain the specific grid/space drawing logic.Usage Examples
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