Skip to content

Commit 327f293

Browse files
rhtrlskoeser
andcommitted
feat: Implement Altair version of grid visualization
_draw_grid is derived from https://github.com/Princeton-CDH/simulating-risk/blob/907c290e12c97b28aa9ce9c80ea7fc52a4f280ae/simulatingrisk/hawkdove/server.py#L114-L171 Co-authored-by: rlskoeser <rebecca.s.koeser@princeton.edu>
1 parent c1fae84 commit 327f293

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import contextlib
2+
from typing import Optional
3+
4+
import pandas as pd
5+
import solara
6+
7+
with contextlib.suppress(ImportError):
8+
import altair as alt
9+
10+
@solara.component
11+
def SpaceAltair(model, agent_portrayal, dependencies: Optional[list[any]] = None):
12+
space = getattr(model, "grid", None)
13+
if space is None:
14+
# Sometimes the space is defined as model.space instead of model.grid
15+
space = model.space
16+
chart = _draw_grid(space, agent_portrayal)
17+
solara.FigureAltair(chart)
18+
19+
20+
def _draw_grid(space, agent_portrayal):
21+
def portray(g):
22+
all_agent_data = []
23+
for content, (x, y) in space.coord_iter():
24+
if not content:
25+
continue
26+
if not hasattr(content, "__iter__"):
27+
# Is a single grid
28+
content = [content] # noqa: PLW2901
29+
for agent in content:
30+
# use all data from agent portrayal, and add x,y coordinates
31+
agent_data = agent_portrayal(agent)
32+
agent_data["x"] = x
33+
agent_data["y"] = y
34+
all_agent_data.append(agent_data)
35+
return all_agent_data
36+
37+
all_agent_data = portray(space)
38+
df = pd.DataFrame(all_agent_data)
39+
chart = (
40+
alt.Chart(df)
41+
.mark_point(filled=True)
42+
.encode(
43+
# no x-axis label
44+
x=alt.X("x", axis=None),
45+
# no y-axis label
46+
y=alt.Y("y", axis=None),
47+
size=alt.Size("size"),
48+
color=alt.Color("color"),
49+
)
50+
# .configure_view(strokeOpacity=0) # hide grid/chart lines
51+
)
52+
return chart

mesa/experimental/jupyter_viz.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import solara
77
from solara.alias import rv
88

9+
import mesa.experimental.components.altair as components_altair
910
import mesa.experimental.components.matplotlib as components_matplotlib
1011

1112
# Avoid interactive backend
@@ -74,6 +75,10 @@ def ColorCard(color, layout_type):
7475
components_matplotlib.SpaceMatplotlib(
7576
model, agent_portrayal, dependencies=[current_step.value]
7677
)
78+
elif space_drawer == "altair":
79+
components_altair.SpaceAltair(
80+
model, agent_portrayal, dependencies=[current_step.value]
81+
)
7782
elif space_drawer:
7883
# if specified, draw agent space with an alternate renderer
7984
space_drawer(model, agent_portrayal)

0 commit comments

Comments
 (0)