
Module 2 ‘I want to fix my delays, and see what works before I try it’
Session 2G: Creating a DES interface with Streamlit - Part 1
Sammi Rosser - Presenter
Amy Heather - Session content creator
We are DEStined for app development



Now it’s time to share results of the model.

You could send everyone your Python code.
But they might not…
Run a few scenarios.
Make some lovely charts.
Send everyone a report.
Job done. Surely.

“Can you rerun it with another three beds?”
“What if we have fewer staff on Tuesdays?”
“Can we change the arrival rate?”
“Can you try all three of those things together?”
Somewhere, a file called final_report_v7_ACTUAL_FINAL.pdf is being created.
But what if they could try it themselves?


Streamlit lets us build a data-focused web application in Python.
We can give our DES model an interface so people can:

There are several other tools for creating interactive apps in Python.
We’re using Streamlit because it runs top-to-bottom in a script-based approach, similar to the Python code we’re already writing.
It is widely used and in very active development.

https://amumodelling-hsma.streamlit.app/


https://stroke-model-des.streamlit.app/



https://non-elective-flow-simulation-model-club.streamlit.app/


https://stars-simpy-example.streamlit.app/


https://playground.hsma.co.uk/

Install Streamlit.
app.py).Import Streamlit at the top of your script:
Run your app from the terminal:
Let’s start with text: a title, a header and a subheader.
Dedicated commands for different text styles, or st.write() for general-purpose output.
st.radioWidgets are interactive controls that let users provide input.
For example, st.radio lets users choose one option from a list.
Set the prompt with label, the choices with options, and the starting position with index (0 selects the first option).
st.pills and st.segmented_controlThese display the choices as buttons rather than a radio list.
Use label and options as before, but set the starting choice with default (e.g., "A") rather than its position.
st.slider and st.numeric_inputDrag a slider or type a number to set a numeric value.
Set the prompt with label, the limits with min_value and max_value, the starting value with value, and the increment with step.
Access the chosen value through a variable or st.session_state.
Alternatively, give the widget a key to access its value through st.session_state:
We can move the slider and see how st.session_state.chosen_value changes.
We recommend this approach as it provides a simple, consistent way to access widget values throughout your app (including from different pages of an app!)
Session state keeps track of values between script re-runs, like a dictionary for the current user’s session.
For our slider with a key:
The user chooses a new inter-arrival time.
Streamlit updates the value in st.session_state.
The script reruns, reading and using the updated value.

We’ll use the DES model from session 2C. As a reminder:
Param, Patient, Model, and Trial classes.
This app will help decision-makers explore staffing options, considering both patient waiting times and staffing costs.
Let’s add an hourly cost per nurse.
class Param:
def __init__(
self,
mean_patient_inter=5,
mean_nurse_consult_time=6,
sd_nurse_consult_time=1,
num_nurses=1,
sim_duration=120,
num_replications=5,
nurse_cost_per_hour=30,
):
self.mean_patient_inter = mean_patient_inter
self.mean_nurse_consult_time = mean_nurse_consult_time
self.sd_nurse_consult_time = sd_nurse_consult_time
self.num_nurses = num_nurses
self.sim_duration = sim_duration
self.num_replications = num_replications
self.nurse_cost_per_hour = nurse_cost_per_hourCalculate the total staffing cost from the number of nurses, the simulation duration and the hourly rate.
This lets us compare the cost of each staffing option alongside its effect on waiting times.
import math
import numpy as np
import pandas as pd
import simpy
from scipy import stats
# stlite requires imports without dotted names
from sim_tools import distributions
Exponential = distributions.Exponential
Lognormal = distributions.Lognormal
class Patient:
def __init__(self, p_id):
self.id = p_id
self.q_time_nurse = pd.NA
class Param:
def __init__(
self,
mean_patient_inter=5,
mean_nurse_consult_time=6,
sd_nurse_consult_time=1,
num_nurses=1,
sim_duration=120,
num_replications=5,
nurse_cost_per_hour=30, # NEW
):
self.mean_patient_inter = mean_patient_inter
self.mean_nurse_consult_time = mean_nurse_consult_time
self.sd_nurse_consult_time = sd_nurse_consult_time
self.num_nurses = num_nurses
self.sim_duration = sim_duration
self.num_replications = num_replications
self.nurse_cost_per_hour = nurse_cost_per_hour # NEW
class Model:
def __init__(self, param, replication_id):
self.param = param
self.replication_id = replication_id
self.env = simpy.Environment()
self.patient_counter = 0
self.nurse = simpy.Resource(self.env, capacity=self.param.num_nurses)
ss = np.random.SeedSequence(self.replication_id)
seeds = ss.spawn(2)
self.patient_inter_dist = Exponential(
mean=self.param.mean_patient_inter, random_seed=seeds[0]
)
self.nurse_consult_time_dist = Lognormal(
mean=self.param.mean_nurse_consult_time,
stdev=self.param.sd_nurse_consult_time,
random_seed=seeds[1],
)
self.list_of_patients = []
self.mean_q_time_nurse = pd.NA
self.sd_q_time_nurse = pd.NA
self.perc_90_q_time_nurse = pd.NA
def generator_patient_arrivals(self):
while True:
self.patient_counter += 1
p = Patient(self.patient_counter)
self.list_of_patients.append(p)
self.env.process(self.attend_clinic(p))
sampled_inter = self.patient_inter_dist.sample()
yield self.env.timeout(sampled_inter)
def attend_clinic(self, patient):
start_q_nurse = self.env.now
with self.nurse.request() as req:
yield req
end_q_nurse = self.env.now
patient.q_time_nurse = end_q_nurse - start_q_nurse
sampled_nurse_act_time = self.nurse_consult_time_dist.sample()
yield self.env.timeout(sampled_nurse_act_time)
def run_model(self):
self.env.process(self.generator_patient_arrivals())
self.env.run(until=self.param.sim_duration)
def convert_entity_list_to_dataframe(self, entity_list):
entity_dateframe = pd.DataFrame(entity.__dict__ for entity in entity_list)
return entity_dateframe
def calculate_run_results(self, entity_dataframe):
self.mean_q_time_nurse = entity_dataframe["q_time_nurse"].mean()
self.sd_q_time_nurse = entity_dataframe["q_time_nurse"].std()
self.perc_90_q_time_nurse = entity_dataframe["q_time_nurse"].quantile(0.9)
class Trial:
def __init__(self, param):
self.param = param
self.list_of_simulation_replications = []
self.trial_mean_q_time_nurse = pd.NA
self.trial_sd_q_time_nurse = pd.NA
self.trial_perc_90_q_time_nurse = pd.NA
self.ci_lower_q_time_nurse = pd.NA
self.ci_upper_q_time_nurse = pd.NA
self.se_q_time_nurse = pd.NA
def run_trial(self):
for replication_id in range(self.param.num_replications):
model_replication = Model(self.param, replication_id)
model_replication.run_model()
patient_df = model_replication.convert_entity_list_to_dataframe(
model_replication.list_of_patients
)
model_replication.calculate_run_results(patient_df)
self.list_of_simulation_replications.append(model_replication)
def calculate_trial_results(self):
self.replication_df = pd.DataFrame(
replication.__dict__ for replication in self.list_of_simulation_replications
)
self.trial_mean_q_time_nurse = self.replication_df["mean_q_time_nurse"].mean()
self.trial_sd_q_time_nurse = self.replication_df["mean_q_time_nurse"].std()
self.trial_perc_90_q_time_nurse = self.replication_df[
"mean_q_time_nurse"
].quantile(0.9)
self.se_q_time_nurse = self.trial_sd_q_time_nurse / math.sqrt(
self.param.num_replications
)
t = stats.t.ppf(0.975, df=self.param.num_replications - 1)
self.ci_lower_q_time_nurse = self.trial_mean_q_time_nurse - (
t * self.se_q_time_nurse
)
self.ci_upper_q_time_nurse = self.trial_mean_q_time_nurse + (
t * self.se_q_time_nurse
)
# NEW
self.total_nurse_cost = (
self.param.num_nurses
* self.param.sim_duration
/ 60
* self.param.nurse_cost_per_hour
)
base_case_params = Param()
base_case_trial = Trial(base_case_params)
base_case_trial.run_trial()
base_case_trial.calculate_trial_results()
print("BASE CASE TRIAL RESULTS")
print("-----------------------")
print("Queuing Time for the Nurse")
print(f"Mean : {base_case_trial.trial_mean_q_time_nurse:.2f} minutes")
print(f"SD : {base_case_trial.trial_sd_q_time_nurse:.2f} minutes")
print(f"90th Perc : {base_case_trial.trial_perc_90_q_time_nurse:.2f} minutes")
print(f"Standard Error : {base_case_trial.se_q_time_nurse:.2f}")
print(
f"95% CI : ({base_case_trial.ci_lower_q_time_nurse:.2f}, ",
f"{base_case_trial.ci_upper_q_time_nurse:.2f}) minutes",
)
print()
what_if_params = Param(num_nurses=2)
what_if_trial = Trial(what_if_params)
what_if_trial.run_trial()
what_if_trial.calculate_trial_results()
print("2 NURSES TRIAL RESULTS")
print("----------------------")
print("Queuing Time for the Nurse")
print(f"Mean : {what_if_trial.trial_mean_q_time_nurse:.2f} minutes")
print(f"SD : {what_if_trial.trial_sd_q_time_nurse:.2f} minutes")
print(f"90th Perc : {what_if_trial.trial_perc_90_q_time_nurse:.2f} minutes")
print(f"Standard Error : {what_if_trial.se_q_time_nurse:.2f}")
print(
f"95% CI : ({what_if_trial.ci_lower_q_time_nurse:.2f}, ",
f"{what_if_trial.ci_upper_q_time_nurse:.2f}) minutes",
)
print()We’ll build a simple app in four steps:
Create the app script.
Get inputs from the user.
Run the model using those inputs.
Display the results.
Create app.py in the same folder as model.py.
It should contain these imports:
plotly.express: chart the results.streamlit: build the interface.Param and Trial: configure and run the model. Here, model refers to model.py in the same folder. The import makes Param and Trial available in our app.Why two Python files?
- Run and test the model independently of the app.
- Avoid redefining model classes each time Streamlit reruns.
Which model parameters should users be able to change?
For this app, we’ll include all everything in Param.
class Param:
def __init__(
self,
mean_patient_inter=5,
mean_nurse_consult_time=6,
sd_nurse_consult_time=1,
num_nurses=1,
sim_duration=120,
num_replications=5,
nurse_cost_per_hour=30,
):
self.mean_patient_inter = mean_patient_inter
self.mean_nurse_consult_time = mean_nurse_consult_time
self.sd_nurse_consult_time = sd_nurse_consult_time
self.num_nurses = num_nurses
self.sim_duration = sim_duration
self.num_replications = num_replications
self.nurse_cost_per_hour = nurse_cost_per_hourWe’ll use our original default (5), then choose some suitable limits and a step size.
All widgets have a help parameter.
We can use it here to explain what the hourly cost should include.
Now we want to run the model in our app, using the selected values instead of relying on the model’s defaults.
params = Param(
mean_patient_inter=st.session_state.mean_patient_inter,
mean_nurse_consult_time=st.session_state.mean_nurse_consult_time,
sd_nurse_consult_time=st.session_state.sd_nurse_consult_time,
num_nurses=st.session_state.num_nurses,
sim_duration=st.session_state.sim_duration,
num_replications=st.session_state.num_replications,
nurse_cost_per_hour=st.session_state.nurse_cost_per_hour,
)
trial = Trial(param=params)
trial.run_trial()
trial.calculate_trial_results()Changing an input reruns the script, but we only want to run the simulation when the user is ready.
st.button() adds a button. Clicking it re-runs the script and returns True for that run, so the indented simulation code executes.
if st.button("Run simulation", type="primary"):
params = Param(
mean_patient_inter=st.session_state.mean_patient_inter,
mean_nurse_consult_time=st.session_state.mean_nurse_consult_time,
sd_nurse_consult_time=st.session_state.sd_nurse_consult_time,
num_nurses=st.session_state.num_nurses,
sim_duration=st.session_state.sim_duration,
num_replications=st.session_state.num_replications,
nurse_cost_per_hour=st.session_state.nurse_cost_per_hour,
)
trial = Trial(param=params)
trial.run_trial()
trial.calculate_trial_results()Previously we printed results to the terminal. We can display similar text in our app.
if st.button("Run simulation", type="primary"):
params = Param(
mean_patient_inter=st.session_state.mean_patient_inter,
mean_nurse_consult_time=st.session_state.mean_nurse_consult_time,
sd_nurse_consult_time=st.session_state.sd_nurse_consult_time,
num_nurses=st.session_state.num_nurses,
sim_duration=st.session_state.sim_duration,
num_replications=st.session_state.num_replications,
nurse_cost_per_hour=st.session_state.nurse_cost_per_hour,
)
trial = Trial(param=params)
trial.run_trial()
trial.calculate_trial_results()
st.subheader("Scenario summary")
st.write(f"""
Summary of nurse queue times across **all** replications.
* Mean: {trial.trial_mean_q_time_nurse:.2f} minutes.
* SD: {trial.trial_sd_q_time_nurse:.2f} minutes.
* 90th Perc: {trial.trial_perc_90_q_time_nurse:.2f} minutes.
* Standard error: {trial.se_q_time_nurse:.2f}
* 95% CI: ({trial.ci_lower_q_time_nurse:.2f},
{trial.ci_upper_q_time_nurse:.2f}) minutes.
Total nurse staffing cost: £{trial.total_nurse_cost:,.2f}
""")Various plotting libraries are supported. For example, using plotly, you create a figure then use st.plotly_chart() to display it in the app.
if st.button("Run simulation", type="primary"):
params = Param(
mean_patient_inter=st.session_state.mean_patient_inter,
mean_nurse_consult_time=st.session_state.mean_nurse_consult_time,
sd_nurse_consult_time=st.session_state.sd_nurse_consult_time,
num_nurses=st.session_state.num_nurses,
sim_duration=st.session_state.sim_duration,
num_replications=st.session_state.num_replications,
nurse_cost_per_hour=st.session_state.nurse_cost_per_hour,
)
trial = Trial(param=params)
trial.run_trial()
trial.calculate_trial_results()
st.subheader("Scenario summary")
st.write(f"""
Summary of nurse queue times across **all** replications.
* Mean: {trial.trial_mean_q_time_nurse:.2f} minutes.
* SD: {trial.trial_sd_q_time_nurse:.2f} minutes.
* 90th Perc: {trial.trial_perc_90_q_time_nurse:.2f} minutes.
* Standard error: {trial.se_q_time_nurse:.2f}
* 95% CI: ({trial.ci_lower_q_time_nurse:.2f},
{trial.ci_upper_q_time_nurse:.2f}) minutes.
Total nurse staffing cost: £{trial.total_nurse_cost:,.2f}
""")
st.subheader("Results from individual replications")
st.write(
"The chart shows how the mean nurse queue time varies between **individual** replications."
)
fig = px.histogram(
data_frame=trial.replication_df,
x="mean_q_time_nurse",
)
fig.update_layout(
xaxis_title="Mean nurse queue time",
yaxis_title="Number of replications"
)
st.plotly_chart(fig)We can create interactive tables with st.dataframe() or static tables with st.table().
if st.button("Run simulation", type="primary"):
params = Param(
mean_patient_inter=st.session_state.mean_patient_inter,
mean_nurse_consult_time=st.session_state.mean_nurse_consult_time,
sd_nurse_consult_time=st.session_state.sd_nurse_consult_time,
num_nurses=st.session_state.num_nurses,
sim_duration=st.session_state.sim_duration,
num_replications=st.session_state.num_replications,
nurse_cost_per_hour=st.session_state.nurse_cost_per_hour,
)
trial = Trial(param=params)
trial.run_trial()
trial.calculate_trial_results()
st.subheader("Scenario summary")
st.write(f"""
Summary of nurse queue times across **all** replications.
* Mean: {trial.trial_mean_q_time_nurse:.2f} minutes.
* SD: {trial.trial_sd_q_time_nurse:.2f} minutes.
* 90th Perc: {trial.trial_perc_90_q_time_nurse:.2f} minutes.
* Standard error: {trial.se_q_time_nurse:.2f}
* 95% CI: ({trial.ci_lower_q_time_nurse:.2f},
{trial.ci_upper_q_time_nurse:.2f}) minutes.
Total nurse staffing cost: £{trial.total_nurse_cost:,.2f}
""")
st.subheader("Results from individual replications")
st.write(
"The chart shows how the mean nurse queue time varies between **individual** replications."
)
fig = px.histogram(
data_frame=trial.replication_df,
x="mean_q_time_nurse",
)
fig.update_layout(
xaxis_title="Mean nurse queue time",
yaxis_title="Number of replications"
)
st.plotly_chart(fig)
underlying = trial.replication_df[
[
"replication_id",
"patient_counter",
"mean_q_time_nurse",
"sd_q_time_nurse",
"perc_90_q_time_nurse",
]
]
st.dataframe(underlying)Use st.download_button() to let users download objects. The object has to be converted to an accepted format - for a dataframe, this means using to_csv().
Note: st.dataframe already shows a download-to-CSV icon when you hover over it. However, you may still want a separate button if:
st.containerWe can group elements using st.container().
Let’s add a border around our model parameters using with st.container(border=True):.
Indent the code for the elements you want inside the container.
with st.container(border=True):
st.subheader("Patients")
st.slider(
label="Mean patient inter-arrival time (minutes)",
min_value=3.0,
max_value=7.0,
value=5.0,
step=0.25,
key="mean_patient_inter",
)
st.subheader("Nurses")
st.number_input(
label="Mean nurse consultation length (minutes)",
min_value=3.0,
max_value=9.0,
value=6.0,
key="mean_nurse_consult_time",
)
st.number_input(
label="Standard deviation of nurse consultation length (minutes)",
min_value=0.0,
value=1.0,
key="sd_nurse_consult_time",
)
st.pills(label="Number of nurses", options=range(1, 5), default=1, key="num_nurses")
st.number_input(
label="Cost per nurse per hour (£)",
min_value=0.0,
value=30.0,
step=1.0,
key="nurse_cost_per_hour",
help="Nurses are costed for the full simulation duration, including time when they are not seeing patients",
)
st.space(size="xxsmall")
st.subheader("Simulation")
st.slider(
label="Simulation duration (minutes)",
min_value=50,
max_value=200,
value=120,
key="sim_duration",
)
st.slider(
label="Number of replications",
min_value=10,
max_value=50,
value=30,
key="num_replications",
)st.containerWe’ve used border=True, but st.container() has other settings you can explore to adjust your layout. For example:
horizonal=True arranges elements side-by-side instead of vertically.gap="medium" sets spacing between elements.height=300 gives a fixed height in pixels, with scrolling if the content doesn’t fit.width="content" makes container match the width of content (instead of width of app or parent container).horizonal_alignment="center" or vertical_alignment="center" to centre items in the container.Many of the Streamlit elements we introduce today also shave additional settings - see the Streamlit documentation to find out what else you can customise.
st.columnsWe can use st.columns() to create containers that are side-by-side.
We specify the number of columns we want, and it returns a list of container objects which we can add elements to using the with notation.
Let’s place our consultation length inputs in columns.
with st.container(border=True):
st.subheader("Patients")
st.slider(
label="Mean patient inter-arrival time (minutes)",
min_value=3.0,
max_value=7.0,
value=5.0,
step=0.25,
key="mean_patient_inter",
)
st.subheader("Nurses")
mean_col, sd_col = st.columns(2)
with mean_col:
st.number_input(
label="Mean consultation length (minutes)",
min_value=3.0,
max_value=9.0,
value=6.0,
key="mean_nurse_consult_time",
)
with sd_col:
st.number_input(
label="Standard deviation of consultation length (minutes)",
min_value=0.0,
value=1.0,
key="sd_nurse_consult_time",
)
st.pills(label="Number of nurses", options=range(1, 5), default=1, key="num_nurses")
st.number_input(
label="Cost per nurse per hour (£)",
min_value=0.0,
value=30.0,
step=1.0,
key="nurse_cost_per_hour",
help="Nurses are costed for the full simulation duration, including time when they are not seeing patients",
)
st.space(size="xxsmall")
st.subheader("Simulation")
st.slider(
label="Simulation duration (minutes)",
min_value=50,
max_value=200,
value=120,
key="sim_duration",
)
st.slider(
label="Number of replications",
min_value=10,
max_value=50,
value=30,
key="num_replications",
)st.expanderst.expander() can be used to hide optional data.
Let’s hide the dataframe with results from individual replications.
if st.button("Run simulation", type="primary"):
params = Param(
mean_patient_inter=st.session_state.mean_patient_inter,
mean_nurse_consult_time=st.session_state.mean_nurse_consult_time,
sd_nurse_consult_time=st.session_state.sd_nurse_consult_time,
num_nurses=st.session_state.num_nurses,
sim_duration=st.session_state.sim_duration,
num_replications=st.session_state.num_replications,
nurse_cost_per_hour=st.session_state.nurse_cost_per_hour,
)
trial = Trial(param=params)
trial.run_trial()
trial.calculate_trial_results()
st.subheader("Scenario summary")
st.write(f"""
Summary of nurse queue times across **all** replications.
* Mean: {trial.trial_mean_q_time_nurse:.2f} minutes.
* SD: {trial.trial_sd_q_time_nurse:.2f} minutes.
* 90th Perc: {trial.trial_perc_90_q_time_nurse:.2f} minutes.
* Standard error: {trial.se_q_time_nurse:.2f}
* 95% CI: ({trial.ci_lower_q_time_nurse:.2f},
{trial.ci_upper_q_time_nurse:.2f}) minutes.
Total nurse staffing cost: £{trial.total_nurse_cost:,.2f}
""")
st.subheader("Results from individual replications")
st.write(
"The chart shows how the mean nurse queue time varies between **individual** replications."
)
fig = px.histogram(
data_frame=trial.replication_df,
x="mean_q_time_nurse",
)
fig.update_layout(
xaxis_title="Mean nurse queue time",
yaxis_title="Number of replications"
)
st.plotly_chart(fig)
with st.expander("View underlying data from each replication"):
underlying = trial.replication_df[
[
"replication_id",
"patient_counter",
"mean_q_time_nurse",
"sd_q_time_nurse",
"perc_90_q_time_nurse",
]
]
st.dataframe(underlying)
st.download_button(
label="Download table as CSV",
data=underlying.to_csv().encode("utf-8"),
)st.spaceUse st.space() to add space between sections of the app.
Set size to adjust the spacing. The default is "small".
"""Simple single-page app."""
import plotly.express as px
import streamlit as st
from model import Param, Trial
with st.container(border=True):
st.subheader("Patients")
st.slider(
label="Mean patient inter-arrival time (minutes)",
min_value=3.0,
max_value=7.0,
value=5.0,
step=0.25,
key="mean_patient_inter",
)
st.subheader("Nurses")
mean_col, sd_col = st.columns(2)
with mean_col:
st.number_input(
label="Mean consultation length (minutes)",
min_value=3.0,
max_value=9.0,
value=6.0,
key="mean_nurse_consult_time",
)
with sd_col:
st.number_input(
label="Standard deviation of consultation length (minutes)",
min_value=0.0,
value=1.0,
key="sd_nurse_consult_time",
)
st.pills(label="Number of nurses", options=range(1, 5), default=1, key="num_nurses")
st.number_input(
label="Cost per nurse per hour (£)",
min_value=0.0,
value=30.0,
step=1.0,
key="nurse_cost_per_hour",
help="Nurses are costed for the full simulation duration, including time when they are not seeing patients",
)
st.space(size="xxsmall")
st.subheader("Simulation")
st.slider(
label="Simulation duration (minutes)",
min_value=50,
max_value=200,
value=120,
key="sim_duration",
)
st.slider(
label="Number of replications",
min_value=10,
max_value=50,
value=30,
key="num_replications",
)
if st.button("Run simulation", type="primary"):
params = Param(
mean_patient_inter=st.session_state.mean_patient_inter,
mean_nurse_consult_time=st.session_state.mean_nurse_consult_time,
sd_nurse_consult_time=st.session_state.sd_nurse_consult_time,
num_nurses=st.session_state.num_nurses,
sim_duration=st.session_state.sim_duration,
num_replications=st.session_state.num_replications,
nurse_cost_per_hour=st.session_state.nurse_cost_per_hour,
)
trial = Trial(param=params)
trial.run_trial()
trial.calculate_trial_results()
st.space()
st.subheader("Scenario summary")
st.write(f"""
Summary of nurse queue times across **all** replications.
* Mean: {trial.trial_mean_q_time_nurse:.2f} minutes.
* SD: {trial.trial_sd_q_time_nurse:.2f} minutes.
* 90th Perc: {trial.trial_perc_90_q_time_nurse:.2f} minutes.
* Standard error: {trial.se_q_time_nurse:.2f}
* 95% CI: ({trial.ci_lower_q_time_nurse:.2f},
{trial.ci_upper_q_time_nurse:.2f}) minutes.
Total nurse staffing cost: £{trial.total_nurse_cost:,.2f}
""")
st.space()
st.subheader("Results from individual replications")
st.write(
"The chart shows how the mean nurse queue time varies between **individual** replications."
)
fig = px.histogram(
data_frame=trial.replication_df,
x="mean_q_time_nurse",
)
fig.update_layout(
xaxis_title="Mean nurse queue time", yaxis_title="Number of replications"
)
st.plotly_chart(fig)
with st.expander("View underlying data from each replication"):
underlying = trial.replication_df[
[
"replication_id",
"patient_counter",
"mean_q_time_nurse",
"sd_q_time_nurse",
"perc_90_q_time_nurse",
]
]
st.dataframe(underlying)
st.download_button(
label="Download table as CSV",
data=underlying.to_csv().encode("utf-8"),
)If we refresh the browser page, it will reset our app. However, users may not realise this, and may be unsure how to reset it.
We can make it easy for them by adding a reset button.
The updated code is on the right - lets work through it…
"""Simple single-page app."""
import plotly.express as px
import streamlit as st
from model import Param, Trial
DEFAULTS = {
"mean_patient_inter": 5.0,
"mean_nurse_consult_time": 6.0,
"sd_nurse_consult_time": 1.0,
"num_nurses": 1,
"nurse_cost_per_hour": 30.0,
"sim_duration": 120,
"num_replications": 30,
}
def reset_widgets():
for key, value in DEFAULTS.items():
st.session_state[key] = value
with st.container(border=True):
st.subheader("Patients")
st.slider(
label="Mean patient inter-arrival time (minutes)",
min_value=3.0,
max_value=7.0,
value=DEFAULTS["mean_patient_inter"],
step=0.25,
key="mean_patient_inter",
)
st.subheader("Nurses")
mean_col, sd_col = st.columns(2)
with mean_col:
st.number_input(
label="Mean consultation length (minutes)",
min_value=3.0,
max_value=9.0,
value=DEFAULTS["mean_nurse_consult_time"],
key="mean_nurse_consult_time",
)
with sd_col:
st.number_input(
label="Standard deviation of consultation length (minutes)",
min_value=0.0,
value=DEFAULTS["sd_nurse_consult_time"],
key="sd_nurse_consult_time",
)
st.pills(
label="Number of nurses",
options=range(1, 5),
default=DEFAULTS["num_nurses"],
key="num_nurses"
)
st.number_input(
label="Cost per nurse per hour (£)",
min_value=0.0,
value=DEFAULTS["nurse_cost_per_hour"],
step=1.0,
key="nurse_cost_per_hour",
help="Nurses are costed for the full simulation duration, including time when they are not seeing patients",
)
st.space(size="xxsmall")
st.subheader("Simulation")
st.slider(
label="Simulation duration (minutes)",
min_value=50,
max_value=200,
value=DEFAULTS["sim_duration"],
key="sim_duration",
)
st.slider(
label="Number of replications",
min_value=10,
max_value=50,
value=DEFAULTS["num_replications"],
key="num_replications",
)
with st.container(horizontal=True):
run = st.button("Run simulation", type="primary")
st.button("Reset to defaults", on_click=reset_widgets)
if run:
params = Param(
mean_patient_inter=st.session_state.mean_patient_inter,
mean_nurse_consult_time=st.session_state.mean_nurse_consult_time,
sd_nurse_consult_time=st.session_state.sd_nurse_consult_time,
num_nurses=st.session_state.num_nurses,
sim_duration=st.session_state.sim_duration,
num_replications=st.session_state.num_replications,
nurse_cost_per_hour=st.session_state.nurse_cost_per_hour,
)
trial = Trial(param=params)
trial.run_trial()
trial.calculate_trial_results()
st.space()
st.subheader("Scenario summary")
st.write(f"""
Summary of nurse queue times across **all** replications.
* Mean: {trial.trial_mean_q_time_nurse:.2f} minutes.
* SD: {trial.trial_sd_q_time_nurse:.2f} minutes.
* 90th Perc: {trial.trial_perc_90_q_time_nurse:.2f} minutes.
* Standard error: {trial.se_q_time_nurse:.2f}
* 95% CI: ({trial.ci_lower_q_time_nurse:.2f},
{trial.ci_upper_q_time_nurse:.2f}) minutes.
Total nurse staffing cost: £{trial.total_nurse_cost:,.2f}
""")
st.space()
st.subheader("Results from individual replications")
st.write(
"The chart shows how the mean nurse queue time varies between **individual** replications."
)
fig = px.histogram(
data_frame=trial.replication_df,
x="mean_q_time_nurse",
)
fig.update_layout(
xaxis_title="Mean nurse queue time", yaxis_title="Number of replications"
)
st.plotly_chart(fig)
with st.expander("View underlying data from each replication"):
underlying = trial.replication_df[
[
"replication_id",
"patient_counter",
"mean_q_time_nurse",
"sd_q_time_nurse",
"perc_90_q_time_nurse",
]
]
st.dataframe(underlying)
st.download_button(
label="Download table as CSV",
data=underlying.to_csv().encode("utf-8"),
)1. Reset widgets function
The new reset_widgets() function replaces the value of each input in the session state using DEAFULTS.
DEFAULTS is a new dictionary at the start of the script. It holds the default value for every input widget.
"""Simple single-page app."""
import plotly.express as px
import streamlit as st
from model import Param, Trial
DEFAULTS = {
"mean_patient_inter": 5.0,
"mean_nurse_consult_time": 6.0,
"sd_nurse_consult_time": 1.0,
"num_nurses": 1,
"nurse_cost_per_hour": 30.0,
"sim_duration": 120,
"num_replications": 30,
}
def reset_widgets():
for key, value in DEFAULTS.items():
st.session_state[key] = value
with st.container(border=True):
st.subheader("Patients")
st.slider(
label="Mean patient inter-arrival time (minutes)",
min_value=3.0,
max_value=7.0,
value=DEFAULTS["mean_patient_inter"],
step=0.25,
key="mean_patient_inter",
)
st.subheader("Nurses")
mean_col, sd_col = st.columns(2)
with mean_col:
st.number_input(
label="Mean consultation length (minutes)",
min_value=3.0,
max_value=9.0,
value=DEFAULTS["mean_nurse_consult_time"],
key="mean_nurse_consult_time",
)
with sd_col:
st.number_input(
label="Standard deviation of consultation length (minutes)",
min_value=0.0,
value=DEFAULTS["sd_nurse_consult_time"],
key="sd_nurse_consult_time",
)
st.pills(
label="Number of nurses",
options=range(1, 5),
default=DEFAULTS["num_nurses"],
key="num_nurses"
)
st.number_input(
label="Cost per nurse per hour (£)",
min_value=0.0,
value=DEFAULTS["nurse_cost_per_hour"],
step=1.0,
key="nurse_cost_per_hour",
help="Nurses are costed for the full simulation duration, including time when they are not seeing patients",
)
st.space(size="xxsmall")
st.subheader("Simulation")
st.slider(
label="Simulation duration (minutes)",
min_value=50,
max_value=200,
value=DEFAULTS["sim_duration"],
key="sim_duration",
)
st.slider(
label="Number of replications",
min_value=10,
max_value=50,
value=DEFAULTS["num_replications"],
key="num_replications",
)
with st.container(horizontal=True):
run = st.button("Run simulation", type="primary")
st.button("Reset to defaults", on_click=reset_widgets)
if run:
params = Param(
mean_patient_inter=st.session_state.mean_patient_inter,
mean_nurse_consult_time=st.session_state.mean_nurse_consult_time,
sd_nurse_consult_time=st.session_state.sd_nurse_consult_time,
num_nurses=st.session_state.num_nurses,
sim_duration=st.session_state.sim_duration,
num_replications=st.session_state.num_replications,
nurse_cost_per_hour=st.session_state.nurse_cost_per_hour,
)
trial = Trial(param=params)
trial.run_trial()
trial.calculate_trial_results()
st.space()
st.subheader("Scenario summary")
st.write(f"""
Summary of nurse queue times across **all** replications.
* Mean: {trial.trial_mean_q_time_nurse:.2f} minutes.
* SD: {trial.trial_sd_q_time_nurse:.2f} minutes.
* 90th Perc: {trial.trial_perc_90_q_time_nurse:.2f} minutes.
* Standard error: {trial.se_q_time_nurse:.2f}
* 95% CI: ({trial.ci_lower_q_time_nurse:.2f},
{trial.ci_upper_q_time_nurse:.2f}) minutes.
Total nurse staffing cost: £{trial.total_nurse_cost:,.2f}
""")
st.space()
st.subheader("Results from individual replications")
st.write(
"The chart shows how the mean nurse queue time varies between **individual** replications."
)
fig = px.histogram(
data_frame=trial.replication_df,
x="mean_q_time_nurse",
)
fig.update_layout(
xaxis_title="Mean nurse queue time", yaxis_title="Number of replications"
)
st.plotly_chart(fig)
with st.expander("View underlying data from each replication"):
underlying = trial.replication_df[
[
"replication_id",
"patient_counter",
"mean_q_time_nurse",
"sd_q_time_nurse",
"perc_90_q_time_nurse",
]
]
st.dataframe(underlying)
st.download_button(
label="Download table as CSV",
data=underlying.to_csv().encode("utf-8"),
)2. Use DEFAULTS
Since we’ve add DEFAULTS, it makes sense to use this when creating each input widget, rather than repeat the default for each item twice.
"""Simple single-page app."""
import plotly.express as px
import streamlit as st
from model import Param, Trial
DEFAULTS = {
"mean_patient_inter": 5.0,
"mean_nurse_consult_time": 6.0,
"sd_nurse_consult_time": 1.0,
"num_nurses": 1,
"nurse_cost_per_hour": 30.0,
"sim_duration": 120,
"num_replications": 30,
}
def reset_widgets():
for key, value in DEFAULTS.items():
st.session_state[key] = value
with st.container(border=True):
st.subheader("Patients")
st.slider(
label="Mean patient inter-arrival time (minutes)",
min_value=3.0,
max_value=7.0,
value=DEFAULTS["mean_patient_inter"],
step=0.25,
key="mean_patient_inter",
)
st.subheader("Nurses")
mean_col, sd_col = st.columns(2)
with mean_col:
st.number_input(
label="Mean consultation length (minutes)",
min_value=3.0,
max_value=9.0,
value=DEFAULTS["mean_nurse_consult_time"],
key="mean_nurse_consult_time",
)
with sd_col:
st.number_input(
label="Standard deviation of consultation length (minutes)",
min_value=0.0,
value=DEFAULTS["sd_nurse_consult_time"],
key="sd_nurse_consult_time",
)
st.pills(
label="Number of nurses",
options=range(1, 5),
default=DEFAULTS["num_nurses"],
key="num_nurses"
)
st.number_input(
label="Cost per nurse per hour (£)",
min_value=0.0,
value=DEFAULTS["nurse_cost_per_hour"],
step=1.0,
key="nurse_cost_per_hour",
help="Nurses are costed for the full simulation duration, including time when they are not seeing patients",
)
st.space(size="xxsmall")
st.subheader("Simulation")
st.slider(
label="Simulation duration (minutes)",
min_value=50,
max_value=200,
value=DEFAULTS["sim_duration"],
key="sim_duration",
)
st.slider(
label="Number of replications",
min_value=10,
max_value=50,
value=DEFAULTS["num_replications"],
key="num_replications",
)
with st.container(horizontal=True):
run = st.button("Run simulation", type="primary")
st.button("Reset to defaults", on_click=reset_widgets)
if run:
params = Param(
mean_patient_inter=st.session_state.mean_patient_inter,
mean_nurse_consult_time=st.session_state.mean_nurse_consult_time,
sd_nurse_consult_time=st.session_state.sd_nurse_consult_time,
num_nurses=st.session_state.num_nurses,
sim_duration=st.session_state.sim_duration,
num_replications=st.session_state.num_replications,
nurse_cost_per_hour=st.session_state.nurse_cost_per_hour,
)
trial = Trial(param=params)
trial.run_trial()
trial.calculate_trial_results()
st.space()
st.subheader("Scenario summary")
st.write(f"""
Summary of nurse queue times across **all** replications.
* Mean: {trial.trial_mean_q_time_nurse:.2f} minutes.
* SD: {trial.trial_sd_q_time_nurse:.2f} minutes.
* 90th Perc: {trial.trial_perc_90_q_time_nurse:.2f} minutes.
* Standard error: {trial.se_q_time_nurse:.2f}
* 95% CI: ({trial.ci_lower_q_time_nurse:.2f},
{trial.ci_upper_q_time_nurse:.2f}) minutes.
Total nurse staffing cost: £{trial.total_nurse_cost:,.2f}
""")
st.space()
st.subheader("Results from individual replications")
st.write(
"The chart shows how the mean nurse queue time varies between **individual** replications."
)
fig = px.histogram(
data_frame=trial.replication_df,
x="mean_q_time_nurse",
)
fig.update_layout(
xaxis_title="Mean nurse queue time", yaxis_title="Number of replications"
)
st.plotly_chart(fig)
with st.expander("View underlying data from each replication"):
underlying = trial.replication_df[
[
"replication_id",
"patient_counter",
"mean_q_time_nurse",
"sd_q_time_nurse",
"perc_90_q_time_nurse",
]
]
st.dataframe(underlying)
st.download_button(
label="Download table as CSV",
data=underlying.to_csv().encode("utf-8"),
)3. Add button
To place a reset button next to “Run simulation”, wrap both in a container with horizontal=True.
Assign the run button to run so you can use it later. For the reset button, set on_click=reset_widgets, so clicking it calls the reset function.
"""Simple single-page app."""
import plotly.express as px
import streamlit as st
from model import Param, Trial
DEFAULTS = {
"mean_patient_inter": 5.0,
"mean_nurse_consult_time": 6.0,
"sd_nurse_consult_time": 1.0,
"num_nurses": 1,
"nurse_cost_per_hour": 30.0,
"sim_duration": 120,
"num_replications": 30,
}
def reset_widgets():
for key, value in DEFAULTS.items():
st.session_state[key] = value
with st.container(border=True):
st.subheader("Patients")
st.slider(
label="Mean patient inter-arrival time (minutes)",
min_value=3.0,
max_value=7.0,
value=DEFAULTS["mean_patient_inter"],
step=0.25,
key="mean_patient_inter",
)
st.subheader("Nurses")
mean_col, sd_col = st.columns(2)
with mean_col:
st.number_input(
label="Mean consultation length (minutes)",
min_value=3.0,
max_value=9.0,
value=DEFAULTS["mean_nurse_consult_time"],
key="mean_nurse_consult_time",
)
with sd_col:
st.number_input(
label="Standard deviation of consultation length (minutes)",
min_value=0.0,
value=DEFAULTS["sd_nurse_consult_time"],
key="sd_nurse_consult_time",
)
st.pills(
label="Number of nurses",
options=range(1, 5),
default=DEFAULTS["num_nurses"],
key="num_nurses"
)
st.number_input(
label="Cost per nurse per hour (£)",
min_value=0.0,
value=DEFAULTS["nurse_cost_per_hour"],
step=1.0,
key="nurse_cost_per_hour",
help="Nurses are costed for the full simulation duration, including time when they are not seeing patients",
)
st.space(size="xxsmall")
st.subheader("Simulation")
st.slider(
label="Simulation duration (minutes)",
min_value=50,
max_value=200,
value=DEFAULTS["sim_duration"],
key="sim_duration",
)
st.slider(
label="Number of replications",
min_value=10,
max_value=50,
value=DEFAULTS["num_replications"],
key="num_replications",
)
with st.container(horizontal=True):
run = st.button("Run simulation", type="primary")
st.button("Reset to defaults", on_click=reset_widgets)
if run:
params = Param(
mean_patient_inter=st.session_state.mean_patient_inter,
mean_nurse_consult_time=st.session_state.mean_nurse_consult_time,
sd_nurse_consult_time=st.session_state.sd_nurse_consult_time,
num_nurses=st.session_state.num_nurses,
sim_duration=st.session_state.sim_duration,
num_replications=st.session_state.num_replications,
nurse_cost_per_hour=st.session_state.nurse_cost_per_hour,
)
trial = Trial(param=params)
trial.run_trial()
trial.calculate_trial_results()
st.space()
st.subheader("Scenario summary")
st.write(f"""
Summary of nurse queue times across **all** replications.
* Mean: {trial.trial_mean_q_time_nurse:.2f} minutes.
* SD: {trial.trial_sd_q_time_nurse:.2f} minutes.
* 90th Perc: {trial.trial_perc_90_q_time_nurse:.2f} minutes.
* Standard error: {trial.se_q_time_nurse:.2f}
* 95% CI: ({trial.ci_lower_q_time_nurse:.2f},
{trial.ci_upper_q_time_nurse:.2f}) minutes.
Total nurse staffing cost: £{trial.total_nurse_cost:,.2f}
""")
st.space()
st.subheader("Results from individual replications")
st.write(
"The chart shows how the mean nurse queue time varies between **individual** replications."
)
fig = px.histogram(
data_frame=trial.replication_df,
x="mean_q_time_nurse",
)
fig.update_layout(
xaxis_title="Mean nurse queue time", yaxis_title="Number of replications"
)
st.plotly_chart(fig)
with st.expander("View underlying data from each replication"):
underlying = trial.replication_df[
[
"replication_id",
"patient_counter",
"mean_q_time_nurse",
"sd_q_time_nurse",
"perc_90_q_time_nurse",
]
]
st.dataframe(underlying)
st.download_button(
label="Download table as CSV",
data=underlying.to_csv().encode("utf-8"),
)on_click=reset_widgets is known as a callback in Streamlit.
A callback is a function that Streamlit runs when the user interacts with a widget. Here that means clicking the button.
Callbacks are not unique to buttons. Most input widgets accept an on_change argument that works the same way. The callback runs when the user changes the widget’s value.
Now it’s your turn to build a Streamlit app!
You have been provided model.py. This is a simple multi-step branching model with a Trial class - the same model from module 2F (vidigi module) (exercise 2).
You shouldn’t need to make any changes to this file.

Create an app.py script and work through these steps:
?? minutes + ?? minute break
Extensions
- Add
st.spinner()to show when the simulation is running. If your simulation is too quick to show it, you can addfrom time import time; time.sleep(1).- This model is the same as the one from Module 2F Exercise 2. Use your animation code from that exercise to generate and display an animation within the app
- Instead of printing the mean / SD / 90th percentile / etc. with
st.write(), try instead usingst.grid()andgrid.metric()to display the results as metric cards.
So far, we have created a single page app.
Now let’s turn it into a multipage app by adding a homepage. This should:

app.py to simulation.py.home.py for our homepage.app.py as the main entry point. In app.py, we define each page using st.Page() and provide these as a list to st.navigation() which we then run().app.py:
home.pyimport streamlit as st
st.title("Nurse clinic simulation")
st.write("""
This app allows you to run a simple discrete-event simulation (DES) of a nurse
clinic.
This is a synthetic model created for the HSMA course. It is from
[session 2C: Replications, Reproducibility and Multiple Activities]
(https://docs.google.com/presentation/d/1ZCgLD82pcPGyNPMvpki724URyNudy_CNpLn8
82V9B1w/edit?usp=sharing).
""")
st.image("images/model_diagram.drawio.png")
st.caption("""
Model diagram: patient arrives, waits for an available nurse, has a
consultation, then leaves.
""")It is a free platform that allows you to share a Streamlit web app from a GitHub repository.
Pros:
Cons:
In practice: best suited to lightweight demonstrations and dashboards, and not for computationally intensive models or very high numbers of visitors.
1. Add a requirements.txt file.
List the packages your app needs, including any specific versions. Save it in the repository root or alongside the app’s Python file.
Example requirements.txt:
simpy==4.1.2
numpy==2.5.3
pandas==3.0.6
sim-tools==1.3.0
streamlit==1.67.0
Community cloud also supports uv.lock, Pipfile, environment.yml and pyproject.toml. Just choose one to use. requirements.txt is the default choice.
We will set the Python version separately in Community Cloud’s settings later.




Your new app will now be live! You can manage apps at https://share.streamlit.io/ under “My apps”. Click “⋮” next to app to view options (e.g., reboot, settings).

Under “Settings”, you can choose the Python version.
By default, it will use the latest supported by Community Cloud.

Using the app you created in Exercise 1:
Turn it into a multipage app with a homepage and a simulation page. On the homepage, explain what the model represents, how to use the app, and who created it.
Deploy the app on Streamlit Community Cloud.
?? minutes + ?? minute break
Extensions
- Add help text to inputs, including their units and what changing them represents.
- Display a message explaining the results in plain English, using values from the simulation.
- Add a results download using
st.download_buttonso users can save their simulation outputs.
