Skip to content

Commit

Permalink
feat: Implement Altair version of grid visualization
Browse files Browse the repository at this point in the history
  • Loading branch information
rht and rlskoeser committed Jan 24, 2024
1 parent c1fae84 commit d5f0cb9
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
52 changes: 52 additions & 0 deletions mesa/experimental/components/altair.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import contextlib
from typing import Optional

import pandas as pd
import solara

with contextlib.suppress(ImportError):
import altair as alt

@solara.component
def SpaceAltair(model, agent_portrayal, dependencies: Optional[list[any]] = None):
space = getattr(model, "grid", None)
if space is None:
# Sometimes the space is defined as model.space instead of model.grid
space = model.space
chart = _draw_grid(space, agent_portrayal)
solara.FigureAltair(chart)


def _draw_grid(space, agent_portrayal):
def portray(g):
all_agent_data = []
for content, (x, y) in space.coord_iter():
if not content:
continue
if not hasattr(content, "__iter__"):
# Is a single grid
content = [content]
for agent in content:
# use all data from agent portrayal, and add x,y coordinates
agent_data = agent_portrayal(agent)
agent_data["x"] = x
agent_data["y"] = y
all_agent_data.append(agent_data)
return all_agent_data

all_agent_data = portray(space)
df = pd.DataFrame(all_agent_data)
chart = (
alt.Chart(df)
.mark_point(filled=True)
.encode(
# no x-axis label
x=alt.X("x", axis=None),
# no y-axis label
y=alt.Y("y", axis=None),
size=alt.Size("size"),
color=alt.Color("color"),
)
# .configure_view(strokeOpacity=0) # hide grid/chart lines
)
return chart
5 changes: 5 additions & 0 deletions mesa/experimental/jupyter_viz.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from solara.alias import rv

import mesa.experimental.components.matplotlib as components_matplotlib
import mesa.experimental.components.altair as components_altair

# Avoid interactive backend
plt.switch_backend("agg")
Expand Down Expand Up @@ -74,6 +75,10 @@ def ColorCard(color, layout_type):
components_matplotlib.SpaceMatplotlib(
model, agent_portrayal, dependencies=[current_step.value]
)
elif space_drawer == "altair":
components_altair.SpaceAltair(
model, agent_portrayal, dependencies=[current_step.value]
)
elif space_drawer:
# if specified, draw agent space with an alternate renderer
space_drawer(model, agent_portrayal)
Expand Down

0 comments on commit d5f0cb9

Please sign in to comment.