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




You’ve built a DES model!

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

Let’s share the model

You could send everyone your Python code.
But they might not…

  • Know Python.
  • Have it installed.
  • Have the right environment or packages.
  • Know which bits to run or which numbers to change.
  • Have time to figure all that out.

Actually, let’s send a report

Run a few scenarios.

Make some lovely charts.

Send everyone a report.

Job done. Surely.

You get a few questions back…

“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?

Enter Streamlit

Streamlit lets us build a data-focused web application in Python.

We can give our DES model an interface so people can:

  • Choose model inputs
  • Run scenarios
  • Explore charts and results

Other web app tools

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.

DES app showcase: acute medical unit

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

DES app showcase: stroke ward

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

DES app showcase: non-elective flow

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

DES app showcase: urgent treatment centre

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

DES app showcase: DES playground

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

Getting started with streamlit

How to create and run a Streamlit app

  1. Install Streamlit.

    pip install streamlit
  1. Create a Python script (e.g., app.py).
  1. Import Streamlit at the top of your script:

    import streamlit as st
  1. Run your app from the terminal:

    streamlit run app.py

What can we put in a Streamlit app?

Let’s start with text: a title, a header and a subheader.

app.py:

import streamlit as st

st.title("This is a title")

st.header("This is a header")

st.subheader("This is a subheader")

App:

Other Streamlit text

Dedicated commands for different text styles, or st.write() for general-purpose output.

import streamlit as st

st.write("Text")

st.markdown("Text with **markdown**")

st.text("Text **without markdown**")

st.badge("Badge")

st.caption("Caption")

st.code("Code")

Widgets: st.radio

Widgets 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).

import streamlit as st

st.radio(
    label="Choose an option",
    options=["A", "B", "C"],
    index=0,
)

Widgets: st.pills and st.segmented_control

These 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.

import streamlit as st

st.pills(
    label="Choose an option",
    options=["A", "B", "C"],
    default="A",
)

st.segmented_control(
    label="Choose an option",
    options=["A", "B", "C"],
    default="A",
)

Widgets: st.slider and st.numeric_input

Drag 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.

import streamlit as st

st.slider(
    label="Pick a number",
    min_value=0,
    max_value=10,
    value=2,
    step=1,
)

st.number_input(
    label="Pick a number",
    min_value=0,
    max_value=10,
    value=2,
    step=1,
)

Accessing the chosen value

Access the chosen value through a variable or st.session_state.

To assign the widget’s return value to a variable:

import streamlit as st

chosen_value = st.slider(
    label="Pick a number", 
    min_value=0,
    max_value=10,
    value=2,
    step=1
)

st.write(f"Chosen value: {chosen_value}")

We can move the slider and see how chosen_value changes.

Accessing the chosen value

Alternatively, give the widget a key to access its value through st.session_state:

import streamlit as st

st.slider(
    label="Pick a number",
    min_value=0,
    max_value=10,
    value=2,
    step=1,
    key="chosen_value",
)

st.write(f"Chosen value: {st.session_state.chosen_value}")

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

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:

  1. The user chooses a new inter-arrival time.

  2. Streamlit updates the value in st.session_state.

  3. The script reruns, reading and using the updated value.

Let’s build a streamlit app for our DES model

Let’s build a streamlit app!

We’ll use the DES model from session 2C. As a reminder:

  • It has Param, Patient, Model, and Trial classes.
  • It simulates a simple nurse clinic.

Before we build the app…

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_hour

Before we build the app…

Calculate 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.

        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
        )

        self.total_nurse_cost = (
            self.param.num_nurses
            * self.param.sim_duration
            / 60
            * self.param.nurse_cost_per_hour
        )

Updated model with nurse costs

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()

Streamlit app

We’ll build a simple app in four steps:

  1. Create the app script.

  2. Get inputs from the user.

  3. Run the model using those inputs.

  4. Display the results.

Create the app script

Create app.py in the same folder as model.py.

It should contain these imports:

import plotly.express as px
import streamlit as st

from model import Param, Trial
  • 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.

Get inputs from the user

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_hour
  • Mean time between arrivals
  • Mean and SD of consultation time
  • Number of nurses
  • Simulation duration
  • Number of replications
  • Hourly cost per nurse

Inputs: inter-arrival time

We’ll use our original default (5), then choose some suitable limits and a step size.

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",
)

Inputs: Consultation time

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",
)

Inputs: Number of nurses

st.pills(
    label="Number of nurses",
    options=range(1, 5),
    default=1,
    key="num_nurses",
)

Inputs: Hourly cost

All widgets have a help parameter.

We can use it here to explain what the hourly cost should include.


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",
)

Inputs: 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",
)

Run model using the inputs

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()

When should the model run?

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()

Displaying simulation 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}
    """)

Charts

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)

Dataframes

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)

Download button

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().

st.download_button(
    label="Download table as CSV",
    data=underlying.to_csv().encode("utf-8"),
)


Note: st.dataframe already shows a download-to-CSV icon when you hover over it. However, you may still want a separate button if:

  • It makes the option obvious, as users may not find the hover icon.
  • You don’t display the data, just download it.
  • You want to control the filename and which columns are included.

Improving layout: st.container


We 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",
    )

Improving layout: st.container

We’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.

Improving layout: st.columns


We 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",
    )

Improving layout: st.expander



st.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"),
        )

Improving layout: st.space



Use 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"),
        )

Reset button


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"),
        )

Reset button



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"),
        )

Reset button



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"),
        )

Reset button


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"),
        )

Callbacks

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.

Our app (via Streamlit Community Cloud)

Our app (via stlite)

View app in new tab

Exercise 1

Exercise 1

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.

Exercise 1


Create an app.py script and work through these steps:

  1. Create input widgets so users can choose the model parameters.
  2. Create a button to run the model with their chosen inputs.
  3. Display results of the simulation (e.g., via text, figures and tables).

?? 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 add from 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 using st.grid() and grid.metric() to display the results as metric cards.

Multipage apps

Multipage apps


So far, we have created a single page app.


Now let’s turn it into a multipage app by adding a homepage. This should:

  • Introduce the model and its uses.
  • Explain how to use the app.
  • Credit the authors.

Organising our multipage app

  1. Rename our existing app.py to simulation.py.
  2. Create home.py for our homepage.
  3. Create 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:

import streamlit as st

# Define pages and their order
pg = st.navigation(
    [
        st.Page("home.py", title="Home"),
        st.Page("simulation.py", title="Run simulation"),
    ]
)
pg.run()

home.py

import 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.
""")

Our app (via Streamlit Community Cloud)

Our app (via stlite)

View app in new tab

Deploying your app on Streamlit Community Cloud

Streamlit Community Cloud

It is a free platform that allows you to share a Streamlit web app from a GitHub repository.

Pros:

  • Easy to use - just provide GitHub URL.
  • Automatically updates with changes pushed to GitHub.
  • Can have unlimited number of public apps (limits on private apps).

Cons:

  • Limited computing resources so apps with high usage may slow down or stop working.
  • After 12 hours without visitors, the app will “fall asleep”, and users have to “wake it up” again.

In practice: best suited to lightweight demonstrations and dashboards, and not for computationally intensive models or very high numbers of visitors.

Deploying on Community Cloud

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.

Deploying on Community Cloud

  1. Sign in with GitHub at https://streamlit.io/cloud.

Deploying on Community Cloud

  1. In top right corner, click “Create app” then choose “Deploy a public app from GitHub”.

Deploying on Community Cloud

  1. Enter details for the app you want to deploy and click “Deploy”.

Deploying on Community Cloud

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).

Deploying on Community Cloud

Under “Settings”, you can choose the Python version.

By default, it will use the latest supported by Community Cloud.

Exercise 2

Exercise 2

Using the app you created in Exercise 1:

  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.

  2. 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_button so users can save their simulation outputs.