Skip to content

Commit a361ab1

Browse files
rhttpike3
authored andcommitted
trading Sugarscape: Add solara visualization
1 parent 51dac64 commit a361ab1

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

examples/sugarscape_g1mt/Readme.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ Then open your browser to [http://127.0.0.1:8521/](http://127.0.0.1:8521/) and p
8282
* ``sugarscape_g1mt/sugar_map.txt``: Provides sugar and spice landscape in raster type format.
8383
* ``server.py``: Sets up and launches and interactive visualization server.
8484
* ``run.py``: Runs Server, Single Run or Batch Run with data collection and basic analysis.
85+
* `app.py`: Runs a visualization server via Solara (`solara run app.py`).
8586

8687
## Additional Resources
8788

examples/sugarscape_g1mt/app.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import numpy as np
2+
import solara
3+
from matplotlib.figure import Figure
4+
from mesa_models.experimental import JupyterViz
5+
from sugarscape_g1mt.model import SugarscapeG1mt
6+
from sugarscape_g1mt.resource_agents import Sugar
7+
from sugarscape_g1mt.trader_agents import Trader
8+
9+
10+
def space_drawer(viz):
11+
def portray(g):
12+
layers = {
13+
"sugar": [[np.nan for j in range(g.height)] for i in range(g.width)],
14+
"spice": [[np.nan for j in range(g.height)] for i in range(g.width)],
15+
"trader": {"x": [], "y": [], "c": "tab:red", "marker": "o", "s": 10},
16+
}
17+
18+
for i in range(g.width):
19+
for j in range(g.height):
20+
content = g._grid[i][j]
21+
for agent in content:
22+
if isinstance(agent, Trader):
23+
layers["trader"]["x"].append(i)
24+
layers["trader"]["y"].append(j)
25+
else:
26+
# Don't visualize resource with value <= 1.
27+
value = agent.amount if agent.amount > 1 else np.nan
28+
if isinstance(agent, Sugar):
29+
layers["sugar"][i][j] = value
30+
else:
31+
layers["spice"][i][j] = value
32+
return layers
33+
34+
fig = Figure()
35+
ax = fig.subplots()
36+
out = portray(viz.model.grid)
37+
# Sugar
38+
# Important note: imshow by default draws from upper left. You have to
39+
# always explicitly specify origin="lower".
40+
im = ax.imshow(out["sugar"], cmap="spring", origin="lower")
41+
fig.colorbar(im, orientation="vertical")
42+
# Spice
43+
ax.imshow(out["spice"], cmap="winter", origin="lower")
44+
# Trader
45+
ax.scatter(**out["trader"])
46+
ax.set_axis_off()
47+
solara.FigureMatplotlib(fig, dependencies=[viz.model, viz.df])
48+
49+
50+
model_params = {
51+
"width": 50,
52+
"height": 50,
53+
}
54+
55+
page = JupyterViz(
56+
SugarscapeG1mt,
57+
model_params,
58+
measures=["Trader", "Price"],
59+
name="Sugarscape {G1, M, T}",
60+
space_drawer=space_drawer,
61+
play_interval=1500,
62+
)
63+
page # noqa

0 commit comments

Comments
 (0)