Skip to content

Commit f8408cd

Browse files
authored
Implement Streamlit UI for Boltzmann wealth model (#36)
* Implement Streamlit UI for Boltzmann wealth model * change slider text * change slider text * update readme --------- Co-authored-by: Ankit Kumar <[email protected]>
1 parent 5818cf1 commit f8408cd

File tree

3 files changed

+203
-0
lines changed

3 files changed

+203
-0
lines changed

examples/boltzmann_wealth_model/Readme.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,12 @@ If your browser doesn't open automatically, point it to [http://127.0.0.1:8521/]
3333
* ``boltzmann_wealth_model/server.py``: Code for the interactive visualization.
3434
* ``run.py``: Launches the server.
3535

36+
## Optional
37+
38+
* ``boltzmann_wealth_model/app.py``: can be used to run the simulation via the streamlit interface.
39+
* For this some additional packages like ``streamlit`` and ``altair`` needs to be installed.
40+
* Once installed, the app can be opened in the browser using : ``streamlit run app.py``
41+
3642
## Further Reading
3743

3844
The full tutorial describing how the model is built can be found at:
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
from boltzmann_wealth_model.model import BoltzmannWealthModel
2+
3+
import streamlit as st
4+
5+
import time
6+
7+
import pandas as pd
8+
9+
import altair as alt
10+
11+
12+
model = st.title("Boltzman Wealth Model")
13+
num_agents = st.slider(
14+
"Choose how many agents to include in the model",
15+
min_value=1,
16+
max_value=100,
17+
value=50,
18+
)
19+
num_ticks = st.slider(
20+
"Select number of Simulation Runs", min_value=1, max_value=100, value=50
21+
)
22+
height = st.slider("Select Grid Height", min_value=10, max_value=100, step=10, value=15)
23+
width = st.slider("Select Grid Width", min_value=10, max_value=100, step=10, value=20)
24+
model = BoltzmannWealthModel(num_agents, height, width)
25+
26+
27+
status_text = st.empty()
28+
run = st.button("Run Simulation")
29+
30+
31+
if run:
32+
tick = time.time()
33+
step = 0
34+
# init grid
35+
df_grid = pd.DataFrame()
36+
df_gini = pd.DataFrame({"step": [0], "gini": [-1]})
37+
for x in range(width):
38+
for y in range(height):
39+
df_grid = pd.concat(
40+
[df_grid, pd.DataFrame({"x": [x], "y": [y], "agent_count": 0})],
41+
ignore_index=True,
42+
)
43+
44+
heatmap = (
45+
alt.Chart(df_grid)
46+
.mark_point(size=100)
47+
.encode(x="x", y="y", color=alt.Color("agent_count"))
48+
.interactive()
49+
.properties(width=800, height=600)
50+
)
51+
52+
line = (
53+
alt.Chart(df_gini)
54+
.mark_line(point=True)
55+
.encode(x="step", y="gini")
56+
.properties(width=800, height=600)
57+
)
58+
59+
# init progress bar
60+
my_bar = st.progress(0, text="Simulation Progress") # progress
61+
placeholder = st.empty()
62+
st.subheader("Agent Grid")
63+
chart = st.altair_chart(heatmap)
64+
st.subheader("Gini Values")
65+
line_chart = st.altair_chart(line)
66+
67+
color_scale = alt.Scale(
68+
domain=[0, 1, 2, 3, 4], range=["red", "cyan", "white", "white", "blue"]
69+
)
70+
for i in range(num_ticks):
71+
model.step()
72+
my_bar.progress((i / num_ticks), text="Simulation progress")
73+
placeholder.text("Step = %d" % i)
74+
for cell in model.grid.coord_iter():
75+
cell_content, x, y = cell
76+
agent_count = len(cell_content)
77+
selected_row = df_grid[(df_grid["x"] == x) & (df_grid["y"] == y)]
78+
df_grid.loc[
79+
selected_row.index, "agent_count"
80+
] = agent_count # random.choice([1,2])
81+
82+
df_gini = pd.concat(
83+
[
84+
df_gini,
85+
pd.DataFrame(
86+
{"step": [i], "gini": [model.datacollector.model_vars["Gini"][i]]}
87+
),
88+
]
89+
)
90+
# st.table(df_grid)
91+
heatmap = (
92+
alt.Chart(df_grid)
93+
.mark_circle(size=100)
94+
.encode(x="x", y="y", color=alt.Color("agent_count", scale=color_scale))
95+
.interactive()
96+
.properties(width=800, height=600)
97+
)
98+
chart.altair_chart(heatmap)
99+
100+
line = (
101+
alt.Chart(df_gini)
102+
.mark_line(point=True)
103+
.encode(x="step", y="gini")
104+
.properties(width=800, height=600)
105+
)
106+
line_chart.altair_chart(line)
107+
108+
time.sleep(0.01)
109+
110+
tock = time.time()
111+
st.success(f"Simulation completed in {tock - tick:.2f} secs")
112+
113+
# st.subheader('Agent Grid')
114+
# fig = px.imshow(agent_counts,labels={'color':'Agent Count'})
115+
# st.plotly_chart(fig)
116+
# st.subheader('Gini value over sim ticks (Plotly)')
117+
# chart = st.line_chart(model.datacollector.model_vars['Gini'])
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
import mesa
2+
3+
import streamlit as st
4+
5+
import time
6+
7+
import pandas as pd
8+
9+
import altair as alt
10+
11+
12+
import numpy as np
13+
from conways_game_of_life.model import ConwaysGameOfLife
14+
15+
import pandas as pd
16+
17+
18+
model = st.title("Boltzman Wealth Model")
19+
num_ticks = st.slider("Select number of Steps", min_value=1, max_value=100, value=50)
20+
height = st.slider("Select Grid Height", min_value=10, max_value=100, step=10, value=15)
21+
width = st.slider("Select Grid Width", min_value=10, max_value=100, step=10, value=20)
22+
model = ConwaysGameOfLife(height, width)
23+
24+
col1, col2, col3 = st.columns(3)
25+
status_text = st.empty()
26+
# step_mode = st.checkbox('Run Step-by-Step')
27+
run = st.button("Run Simulation")
28+
29+
30+
if run:
31+
tick = time.time()
32+
step = 0
33+
# init grid
34+
df_grid = pd.DataFrame()
35+
agent_counts = np.zeros((model.grid.width, model.grid.height))
36+
for x in range(width):
37+
for y in range(height):
38+
df_grid = pd.concat(
39+
[df_grid, pd.DataFrame({"x": [x], "y": [y], "state": [0]})],
40+
ignore_index=True,
41+
)
42+
43+
heatmap = (
44+
alt.Chart(df_grid)
45+
.mark_point(size=100)
46+
.encode(x="x", y="y", color=alt.Color("state"))
47+
.interactive()
48+
.properties(width=800, height=600)
49+
)
50+
51+
# init progress bar
52+
my_bar = st.progress(0, text="Simulation Progress") # progress
53+
placeholder = st.empty()
54+
st.subheader("Agent Grid")
55+
chart = st.altair_chart(heatmap, use_container_width=True)
56+
color_scale = alt.Scale(domain=[0, 1], range=["red", "yellow"])
57+
for i in range(num_ticks):
58+
model.step()
59+
my_bar.progress((i / num_ticks), text="Simulation progress")
60+
placeholder.text("Step = %d" % i)
61+
for contents, x, y in model.grid.coord_iter():
62+
# print('x:',x,'y:',y, 'state:',contents)
63+
selected_row = df_grid[(df_grid["x"] == x) & (df_grid["y"] == y)]
64+
df_grid.loc[
65+
selected_row.index, "state"
66+
] = contents.state # random.choice([1,2])
67+
68+
heatmap = (
69+
alt.Chart(df_grid)
70+
.mark_circle(size=100)
71+
.encode(x="x", y="y", color=alt.Color("state", scale=color_scale))
72+
.interactive()
73+
.properties(width=800, height=600)
74+
)
75+
chart.altair_chart(heatmap)
76+
77+
time.sleep(0.1)
78+
79+
tock = time.time()
80+
st.success(f"Simulation completed in {tock - tick:.2f} secs")

0 commit comments

Comments
 (0)