Module 2 ‘I want to fix my delays, and see what works before I try it’

Session 2H: Creating a DES interface with Streamlit - Part 2

Sammi Rosser - Presenter

Amy Heather - Session content creator

And they all lived APPily every after




Reminder: App from the last session

Reminder: App from the last session

View stlite app in new tab

Scenarios

Adding scenarios to our app


A common use for a DES app is to compare scenarios with different inputs.

Our current app shows results for one run at a time. Changing the inputs and running again replaces the previous results.

To compare scenarios, we need to:

  1. Save each run’s inputs and results.
  2. Allow users to view and compare saved scenarios.

Preview: the app we will create

Preview: the app we will create

View stlite app in new tab

Two pages: run scenarios and explore results

As shown, our app now splits the original simulation page into two:

  • Run simulation: set inputs and run the model.
  • View results: view results from a saved scenario or compare several.


Why?

These pages support two different tasks: setting up simulations and making sense of their results. Users can move between them without having to do both in the same place.

This keeps the interface manageable if we add more inputs, results and comparison features.

New dictionary in session state

We first create an empty dictionary in session state, ready to store scenario results.

st.session_state.scenarios = {}


We need to make sure it is only created it if it doesn’t already exist.

This is because Streamlit reruns the script when users interact with the app. Without this check, each rerun would replace the dictionary with an empty one, clearing any saved results.

if "scenarios" not in st.session_state:
    st.session_state.scenarios = {}

New dictionary in session state

We’ll initialise the dictionary in app.py, which runs before whichever page the user opens.


Why not in simulation.py?

Users might open the results page before running a simulation. If we created the dictionary only in simulation.py, it wouldn’t exist yet, causing an error.

Putting this code in app.py ensures the dictionary exists before either page needs it.

"""Entrypoint for app. Defines navigation."""

import streamlit as st

# Initialise session state before running any page
if "scenarios" not in st.session_state:
    st.session_state.scenarios = {}

pg = st.navigation(
    [
        st.Page("home.py", title="Home"),
        st.Page("simulation.py", title="Run simulation"),
    ]
)

pg.run()

Run and save the results

In simulation.py, we’ll keep the code that sets the inputs and runs the simulation.

We’ll remove the analysis code for now and move it to the results page later. We can also remove import plotly.express as px as this page no longer uses it.


We’ll add new code to:

  1. Name the scenario

  2. Save its settings and results in st.session_state.scenarios.

"""Simple single-page app."""

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 and save scenario", 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()

    # Save results to session state to allow comparison between scenarios
    scenario_name = f"Scenario {len(st.session_state.scenarios) + 1}"
    st.session_state.scenarios[scenario_name] = {
        "settings": {
            "Scenario": scenario_name,
            "Inter-arrival": st.session_state.mean_patient_inter,
            "Consultation mean": st.session_state.mean_nurse_consult_time,
            "Consultation SD": st.session_state.sd_nurse_consult_time,
            "Nurses": st.session_state.num_nurses,
            "Cost per hour": st.session_state.nurse_cost_per_hour,
            "Duration": st.session_state.sim_duration,
            "Replications": st.session_state.num_replications,
        },
        "mean": trial.trial_mean_q_time_nurse,
        "sd": trial.trial_sd_q_time_nurse,
        "p90": trial.trial_perc_90_q_time_nurse,
        "se": trial.se_q_time_nurse,
        "ci_lower": trial.ci_lower_q_time_nurse,
        "ci_upper": trial.ci_upper_q_time_nurse,
        "cost": trial.total_nurse_cost,
        "df": trial.replication_df,
    }

Run and save the results

Scenario names are based on how many scenarios are already stored (e.g., “Scenario 1”, “Scenario 2”).


Settings record the inputs used for each scenario, so we can interpret and compare its results.

Results are the summary statistics, saved using shorter keys like mean and sd so they are easier to access later.

    # Save results to session state to allow comparison between scenarios
    scenario_name = f"Scenario {len(st.session_state.scenarios) + 1}"
    st.session_state.scenarios[scenario_name] = {
        "settings": {
            "Scenario": scenario_name,
            "Inter-arrival": st.session_state.mean_patient_inter,
            "Consultation mean": st.session_state.mean_nurse_consult_time,
            "Consultation SD": st.session_state.sd_nurse_consult_time,
            "Nurses": st.session_state.num_nurses,
            "Cost per hour": st.session_state.nurse_cost_per_hour,
            "Duration": st.session_state.sim_duration,
            "Replications": st.session_state.num_replications,
        },
        "mean": trial.trial_mean_q_time_nurse,
        "sd": trial.trial_sd_q_time_nurse,
        "p90": trial.trial_perc_90_q_time_nurse,
        "se": trial.se_q_time_nurse,
        "ci_lower": trial.ci_lower_q_time_nurse,
        "ci_upper": trial.ci_upper_q_time_nurse,
        "cost": trial.total_nurse_cost,
        "df": trial.replication_df,
    }

Run and save the results

We then set chosen_scenario to this scenario, making it the default selection when the user opens the results page.

We also show a success message to confirm that the scenario has run and its results have been saved.



    # Select the newly saved scenario and show confirmation
    st.session_state.chosen_scenario = scenario_name
    st.success(f"""
    {scenario_name} ran successfully and was saved for this sesssion.
    """)

Keeping track of scenarios

We can also show a table of saved scenarios, so users can keep track of their runs.

This checks if scenarios is empty - and will only appear after the first scenario has been run.

We take the settings from each saved scenario and display them as a row in the table.

A caption reminds users that these scenarios are saved for the current session only.


if st.session_state.scenarios:
    st.divider()
    st.header("Saved scenarios")

    st.dataframe(
        [scenario["settings"] for scenario in st.session_state.scenarios.values()],
        hide_index=True,
    )
    st.caption("Scenarios are saved for the current session only.")

st.divider()

You may’ve noticed we used a new Streamlit element here - st.divider().

This displays a horizontal line on the app.


if st.session_state.scenarios:
    st.divider()
    st.header("Saved scenarios")

    st.dataframe(
        [scenario["settings"] for scenario in st.session_state.scenarios.values()],
        hide_index=True,
    )
    st.caption("Scenarios are saved for the current session only.")

Linking to results page

At the end of simulation.py, we’ll add a button linking to results.py, which we’ll create next.

Clicking the button calls st.switch_page to take the user to the results page.


    st.divider()
    st.header("Results")
    if st.button(label="Go to results page", type="primary"):
        st.switch_page("results.py")

Results from one scenario


Now let’s make the results page!


We’ll start by moving the analysis code we removed earlier into a new file, results.py.

You can that code on the right.


However, we’ll need to make some changes so it can work…

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

Required changes



1. Import the packages

Import pandas, plotly.express and streamlit for this page.

import pandas as pd
import plotly.express as px
import streamlit as st

# Get results of chosen scenario
results = st.session_state.scenarios[st.session_state.chosen_scenario]

st.space()
st.subheader("Scenario summary")
st.write(f"""
Summary of nurse queue times across **all** replications.

* Mean: {results["mean"]:.2f} minutes.
* SD: {results["sd"]:.2f} minutes.
* 90th Perc: {results["p90"]:.2f} minutes.
* Standard error: {results["se"]:.2f}
* 95% CI: ({results["ci_lower"]:.2f}, {results["ci_upper"]:.2f}) minutes

Total nurse staffing cost: £{results["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=results["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 = results["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"),
    )

Required changes



2. Retrieve the chosen scenario

Use chosen_scenario to look up the saved scenario in scenarios and store it as results.


For now, this is the most recently run scenario. We’ll add a way for users to choose a different scenario in a moment.

import pandas as pd
import plotly.express as px
import streamlit as st

# Get results of chosen scenario
results = st.session_state.scenarios[st.session_state.chosen_scenario]

st.space()
st.subheader("Scenario summary")
st.write(f"""
Summary of nurse queue times across **all** replications.

* Mean: {results["mean"]:.2f} minutes.
* SD: {results["sd"]:.2f} minutes.
* 90th Perc: {results["p90"]:.2f} minutes.
* Standard error: {results["se"]:.2f}
* 95% CI: ({results["ci_lower"]:.2f}, {results["ci_upper"]:.2f}) minutes

Total nurse staffing cost: £{results["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=results["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 = results["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"),
    )

Required changes



3. Display the saved results

Read the summary statistics and cost from results, rather than directly from the simulation trial object.

import pandas as pd
import plotly.express as px
import streamlit as st

# Get results of chosen scenario
results = st.session_state.scenarios[st.session_state.chosen_scenario]

st.space()
st.subheader("Scenario summary")
st.write(f"""
Summary of nurse queue times across **all** replications.

* Mean: {results["mean"]:.2f} minutes.
* SD: {results["sd"]:.2f} minutes.
* 90th Perc: {results["p90"]:.2f} minutes.
* Standard error: {results["se"]:.2f}
* 95% CI: ({results["ci_lower"]:.2f}, {results["ci_upper"]:.2f}) minutes

Total nurse staffing cost: £{results["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=results["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 = results["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"),
    )

Required changes



4. Use saved data in histogram and table

Use results["df"] as the data source for both the histogram and the table of individual replications.

import pandas as pd
import plotly.express as px
import streamlit as st

# Get results of chosen scenario
results = st.session_state.scenarios[st.session_state.chosen_scenario]

st.space()
st.subheader("Scenario summary")
st.write(f"""
Summary of nurse queue times across **all** replications.

* Mean: {results["mean"]:.2f} minutes.
* SD: {results["sd"]:.2f} minutes.
* 90th Perc: {results["p90"]:.2f} minutes.
* Standard error: {results["se"]:.2f}
* 95% CI: ({results["ci_lower"]:.2f}, {results["ci_upper"]:.2f}) minutes

Total nurse staffing cost: £{results["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=results["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 = results["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"),
    )

Choose a scenario

Now we can let users choosen their chosen_scenario to view.

We’ll add:

  • A dropdown to select a saved scenario.
  • A table of scenario settings, so users can see what they’re choosing between.
  • A highlighted row showing the selected scenario.

Choose a scenario

Let’s work through the code to do that…

with st.container(border=True):
    st.selectbox(
        label="**Choose a scenario to view:**",
        options=list(st.session_state.scenarios),
        key="chosen_scenario",
    )

    # Convert the settings dictionary into a dataframe
    settings = pd.DataFrame(
        [
            scenario["settings"]
            for scenario in st.session_state.scenarios.values()
        ]
    )

    # Show dataframe of saved scenarios, with chosen scenario highlighted
    st.caption("The selected scenario is highlighted below.")
    st.dataframe(
        style_settings(
            settings=settings,
            chosen_scenarios=[st.session_state.chosen_scenario],
        ),
        hide_index=True,
    )

Choose a scenario



1. Use st.container(border=True)

This keeps the scenario selection area visually separate from the results.

with st.container(border=True):
    st.selectbox(
        label="**Choose a scenario to view:**",
        options=list(st.session_state.scenarios),
        key="chosen_scenario",
    )

    # Convert the settings dictionary into a dataframe
    settings = pd.DataFrame(
        [
            scenario["settings"]
            for scenario in st.session_state.scenarios.values()
        ]
    )

    # Show dataframe of saved scenarios, with chosen scenario highlighted
    st.caption("The selected scenario is highlighted below.")
    st.dataframe(
        style_settings(
            settings=settings,
            chosen_scenarios=[st.session_state.chosen_scenario],
        ),
        hide_index=True,
    )

Choose a scenario



2. Select a scenario

Use st.selectbox() to create a dropdown with the names of save scenarios.

Using key="chosen_scenario" means the selection is saved as and overwrites the last chosen_scenario in session state.

with st.container(border=True):
    st.selectbox(
        label="**Choose a scenario to view:**",
        options=list(st.session_state.scenarios),
        key="chosen_scenario",
    )

    # Convert the settings dictionary into a dataframe
    settings = pd.DataFrame(
        [
            scenario["settings"]
            for scenario in st.session_state.scenarios.values()
        ]
    )

    # Show dataframe of saved scenarios, with chosen scenario highlighted
    st.caption("The selected scenario is highlighted below.")
    st.dataframe(
        style_settings(
            settings=settings,
            chosen_scenarios=[st.session_state.chosen_scenario],
        ),
        hide_index=True,
    )

Choose a scenario



3. Create a settings dataframe

Extract the settings dictionary for each saved scenario and combined them into a dataframe, with one row per scenario.

with st.container(border=True):
    st.selectbox(
        label="**Choose a scenario to view:**",
        options=list(st.session_state.scenarios),
        key="chosen_scenario",
    )

    # Convert the settings dictionary into a dataframe
    settings = pd.DataFrame(
        [
            scenario["settings"]
            for scenario in st.session_state.scenarios.values()
        ]
    )

    # Show dataframe of saved scenarios, with chosen scenario highlighted
    st.caption("The selected scenario is highlighted below.")
    st.dataframe(
        style_settings(
            settings=settings,
            chosen_scenarios=[st.session_state.chosen_scenario],
        ),
        hide_index=True,
    )

Choose a scenario



4. Display the settings dataframe

Use st.dataframe() to display settings.

We’ll write a function style_settings() which we can apply to the dataframe to highlight the chosen scenario row…

with st.container(border=True):
    st.selectbox(
        label="**Choose a scenario to view:**",
        options=list(st.session_state.scenarios),
        key="chosen_scenario",
    )

    # Convert the settings dictionary into a dataframe
    settings = pd.DataFrame(
        [
            scenario["settings"]
            for scenario in st.session_state.scenarios.values()
        ]
    )

    # Show dataframe of saved scenarios, with chosen scenario highlighted
    st.caption("The selected scenario is highlighted below.")
    st.dataframe(
        style_settings(
            settings=settings,
            chosen_scenarios=[st.session_state.chosen_scenario],
        ),
        hide_index=True,
    )

style_settings()

We’ll write this function near the start of our results.py script.

It checks each row’s scenario name against chosen_scenarios. Matching rows get a pale blue background. We use .style.apply() to apply this formatting row by row, then .format(precision=2) to display decimal values to two decimal places.

# Function for highlighting the row/s with the chosen scenario/s
def style_settings(settings, chosen_scenarios):
    def highlight(row):
        style = (
            "background-color: #dbeafe; color: #111827"
            if row["Scenario"] in chosen_scenarios
            else ""
        )
        return [style] * len(row)

    return settings.style.apply(highlight, axis=1).format(precision=2)

No scenarios to view

Users might open the results page before running a scenario.

We’ll show a message explaining that there are no saved results yet and directing them to run a scenario first.

No scenarios to view

We first check whether scenarios is empty.

If it is, we show a message using st.info().

Otherwise, we display the results page as before.

if not st.session_state.scenarios:
    st.info("Run and save scenarios to view results here.", icon="ℹ️")

else:
    st.space()
    with st.container(border=True):
        st.selectbox(
            label="**Choose a scenario to view:**",
            options=list(st.session_state.scenarios),
            key="chosen_scenario",
        )
    
    ...


This avoids trying to display results when none are available.

Creating tabs



We have now finished the code for displaying results from one chosen scenario. Next, we’ll add a way to compare several scenarios.


We’ll use st.tabs to organise these two tasks within the results page:

  • View single scenario
  • Compare scenarios

Creating tabs

We pass st.tabs() a list with titles for each tab.


It returns a container for each tab, which we assign to variables (here, tab_single and tab_compare).


We then use a with block to add content to each tab.

st.title("View results")

if not st.session_state.scenarios:
    st.info("Run and save scenarios to view results here.", icon="ℹ️")

else:
    st.write(
        "You can either view results from a **single scenario**, or **compare across scenarios**."
    )

    tab_single, tab_compare = st.tabs(
        ["View single scenario", "Compare scenarios"]
    )

    with tab_single:
        st.space()
        with st.container(border=True):
            st.selectbox(
                label="**Choose a scenario to view:**",
                options=list(st.session_state.scenarios),
                key="chosen_scenario",
            )
            ...

Choosing scenarios to compare




On the “Compare scenarios” tab, we’ll add a selection box where users can choose multiple saved scenarios.

If fewer than two scenario are run or selected, we’ll show a messages asking them to run or select at least two.

Choosing scenarios to compare

Let’s work through the code to do that…

with tab_compare:
    if len(st.session_state.scenarios) < 2:
        st.info("Run at least two scenarios to enable comparison", icon="ℹ️")

    else:
        st.space()
        with st.container(border=True):
            chosen_compare = st.multiselect(
                label="**Choose scenarios to compare**",
                options=list(st.session_state.scenarios),
            )

            st.caption("The selected scenarios are highlighted below.")

            st.dataframe(
                style_settings(settings=settings, chosen_scenarios=chosen_compare),
                hide_index=True,
            )

        if len(chosen_compare) < 2:
            st.info("Choose at least two scenario to compare", icon="ℹ️")

        else:
            # Results - will write next

Choosing scenarios to compare



1. Use tab_compare and warn for insufficient scenarios

If scenarios in session state only has zero or one saved scenarios, a message is displayed using st.info().

with tab_compare:
    if len(st.session_state.scenarios) < 2:
        st.info("Run at least two scenarios to enable comparison", icon="ℹ️")

    else:
        st.space()
        with st.container(border=True):
            chosen_compare = st.multiselect(
                label="**Choose scenarios to compare**",
                options=list(st.session_state.scenarios),
            )

            st.caption("The selected scenarios are highlighted below.")

            st.dataframe(
                style_settings(settings=settings, chosen_scenarios=chosen_compare),
                hide_index=True,
            )

        if len(chosen_compare) < 2:
            st.info("Choose at least two scenario to compare", icon="ℹ️")

        else:
            # Results - will write next

Choosing scenarios to compare



2. Multiselect

Once there are at least two scenarios, we set up a container and create st.multiselect().

This is similar to selectbox, but allows users to choose multiple options at once.

with tab_compare:
    if len(st.session_state.scenarios) < 2:
        st.info("Run at least two scenarios to enable comparison", icon="ℹ️")

    else:
        st.space()
        with st.container(border=True):
            chosen_compare = st.multiselect(
                label="**Choose scenarios to compare**",
                options=list(st.session_state.scenarios),
            )

            st.caption("The selected scenarios are highlighted below.")

            st.dataframe(
                style_settings(settings=settings, chosen_scenarios=chosen_compare),
                hide_index=True,
            )

        if len(chosen_compare) < 2:
            st.info("Choose at least two scenario to compare", icon="ℹ️")

        else:
            # Results - will write next

Choosing scenarios to compare



3. Show saved scenarios

Like before, we can show the saved scenarios and highlighted those selected using style_settings().

with tab_compare:
    if len(st.session_state.scenarios) < 2:
        st.info("Run at least two scenarios to enable comparison", icon="ℹ️")

    else:
        st.space()
        with st.container(border=True):
            chosen_compare = st.multiselect(
                label="**Choose scenarios to compare**",
                options=list(st.session_state.scenarios),
            )

            st.caption("The selected scenarios are highlighted below.")

            st.dataframe(
                style_settings(settings=settings, chosen_scenarios=chosen_compare),
                hide_index=True,
            )

        if len(chosen_compare) < 2:
            st.info("Choose at least two scenario to compare", icon="ℹ️")

        else:
            # Results - will write next

Choosing scenarios to compare



4. Check chosen scenarios

Show a message until at least two scenarios have been chosen. Then, results can be shown.

with tab_compare:
    if len(st.session_state.scenarios) < 2:
        st.info("Run at least two scenarios to enable comparison", icon="ℹ️")

    else:
        st.space()
        with st.container(border=True):
            chosen_compare = st.multiselect(
                label="**Choose scenarios to compare**",
                options=list(st.session_state.scenarios),
            )

            st.caption("The selected scenarios are highlighted below.")

            st.dataframe(
                style_settings(settings=settings, chosen_scenarios=chosen_compare),
                hide_index=True,
            )

        if len(chosen_compare) < 2:
            st.info("Choose at least two scenario to compare", icon="ℹ️")

        else:
            # Results - will write next

Boxplot





Boxplots are a great option for comparing results across scenarios side by side.

They make it easy to see both the average results and the spread of results across replications.

Boxplot



1. Introduce figure

We’ll start by using st.subheader() and st.write() to introduce the figure and explain what it is showing.

st.subheader("Mean nurse queue time")
st.write(
    "Compare the mean nurse queue times across replications. "
    "Each point represents one replication."
)

# Combine replication results, adding a scenario label.
replications = pd.concat(
    [
        st.session_state.scenarios[name]["df"].assign(Scenario=name)
        for name in chosen_compare
    ],
    ignore_index=True,
)

fig = px.box(
    replications,
    x="Scenario",
    y="mean_q_time_nurse",
    color="Scenario",
    points="all",
    category_orders={
        "Scenario": [
            name
            for name in st.session_state.scenarios
            if name in chosen_compare
        ]
    },
    hover_data=["replication_id"],
)
fig.update_layout(
    yaxis_title="Mean nurse queue time",
    showlegend=False,
)
st.plotly_chart(fig)

Boxplot



2. Create single results dataframe

Next, we use pd.concat() to stack the replication-level results from each scenario into a single dataframe called replications.

We also add a Scenario column to identify which scenario each row belongs to.

st.subheader("Mean nurse queue time")
st.write(
    "Compare the mean nurse queue times across replications. "
    "Each point represents one replication."
)

# Combine replication results, adding a scenario label.
replications = pd.concat(
    [
        st.session_state.scenarios[name]["df"].assign(Scenario=name)
        for name in chosen_compare
    ],
    ignore_index=True,
)

fig = px.box(
    replications,
    x="Scenario",
    y="mean_q_time_nurse",
    color="Scenario",
    points="all",
    category_orders={
        "Scenario": [
            name
            for name in st.session_state.scenarios
            if name in chosen_compare
        ]
    },
    hover_data=["replication_id"],
)
fig.update_layout(
    yaxis_title="Mean nurse queue time",
    showlegend=False,
)
st.plotly_chart(fig)

Boxplot

3. Create boxplot

We create the figure using plotly.express.box():

  • color: group and color by scenario.
  • points: show each replication as a dot.
  • category_orders: keeps scenarios in the order they were saved.
  • hover_data: include replication IDs.

It’s displayed with st.plotly_chart().

st.subheader("Mean nurse queue time")
st.write(
    "Compare the mean nurse queue times across replications. "
    "Each point represents one replication."
)

# Combine replication results, adding a scenario label.
replications = pd.concat(
    [
        st.session_state.scenarios[name]["df"].assign(Scenario=name)
        for name in chosen_compare
    ],
    ignore_index=True,
)

fig = px.box(
    replications,
    x="Scenario",
    y="mean_q_time_nurse",
    color="Scenario",
    points="all",
    category_orders={
        "Scenario": [
            name
            for name in st.session_state.scenarios
            if name in chosen_compare
        ]
    },
    hover_data=["replication_id"],
)
fig.update_layout(
    yaxis_title="Mean nurse queue time",
    showlegend=False,
)
st.plotly_chart(fig)

Comparison table

We could also use tables to compare results.

Comparison table



1. Construct summary table for nurse queue time

Here, we are creating a table with the descriptive statistics from each scenario.

st.space()
st.subheader("Summary statistics")

summary = pd.DataFrame(
    [
        {
            "Scenario": name,
            "Mean": st.session_state.scenarios[name]["mean"],
            "SD": st.session_state.scenarios[name]["sd"],
            "90th percentile": st.session_state.scenarios[name]["p90"],
            "Standard error": st.session_state.scenarios[name]["se"],
            "95% CI lower": st.session_state.scenarios[name][
                "ci_lower"
            ],
            "95% CI upper": st.session_state.scenarios[name][
                "ci_upper"
            ],
        }
        for name in chosen_compare
    ]
)

st.caption("Nurse queue time summary statistics, in minutes:")

st.dataframe(
    summary.style.format(precision=2),
    hide_index=True,
)

costs = pd.DataFrame(
    [
        {
            "Scenario": name,
            "Total cost (£)": st.session_state.scenarios[name]["cost"],
        }
        for name in chosen_compare
    ]
)

st.caption("Total nurse staffing costs:")

st.dataframe(costs, hide_index=True)

Comparison table



2. Display summary table

We then display it using st.dataframe(), with style.format() to round the numbers.

st.caption() provides some helpful context.

st.space()
st.subheader("Summary statistics")

summary = pd.DataFrame(
    [
        {
            "Scenario": name,
            "Mean": st.session_state.scenarios[name]["mean"],
            "SD": st.session_state.scenarios[name]["sd"],
            "90th percentile": st.session_state.scenarios[name]["p90"],
            "Standard error": st.session_state.scenarios[name]["se"],
            "95% CI lower": st.session_state.scenarios[name][
                "ci_lower"
            ],
            "95% CI upper": st.session_state.scenarios[name][
                "ci_upper"
            ],
        }
        for name in chosen_compare
    ]
)

st.caption("Nurse queue time summary statistics, in minutes:")

st.dataframe(
    summary.style.format(precision=2),
    hide_index=True,
)

costs = pd.DataFrame(
    [
        {
            "Scenario": name,
            "Total cost (£)": st.session_state.scenarios[name]["cost"],
        }
        for name in chosen_compare
    ]
)

st.caption("Total nurse staffing costs:")

st.dataframe(costs, hide_index=True)

Comparison table



3. Repeat for costs

We can repeat this to show the nurse costs for each scenario. These are deterministic, just based on the number of resources in the simulation, so a single number is presented for each scenario.

st.space()
st.subheader("Summary statistics")

summary = pd.DataFrame(
    [
        {
            "Scenario": name,
            "Mean": st.session_state.scenarios[name]["mean"],
            "SD": st.session_state.scenarios[name]["sd"],
            "90th percentile": st.session_state.scenarios[name]["p90"],
            "Standard error": st.session_state.scenarios[name]["se"],
            "95% CI lower": st.session_state.scenarios[name][
                "ci_lower"
            ],
            "95% CI upper": st.session_state.scenarios[name][
                "ci_upper"
            ],
        }
        for name in chosen_compare
    ]
)

st.caption("Nurse queue time summary statistics, in minutes:")

st.dataframe(
    summary.style.format(precision=2),
    hide_index=True,
)

costs = pd.DataFrame(
    [
        {
            "Scenario": name,
            "Total cost (£)": st.session_state.scenarios[name]["cost"],
        }
        for name in chosen_compare
    ]
)

st.caption("Total nurse staffing costs:")

st.dataframe(costs, hide_index=True)

Exercise 1

Exercise 1

Adapt the app you created in the last session so users can save and compare scenarios.

Create two separate pages:

  • simulation.py: run the simulation and save each scenario’s settings and results.
  • results.py: view results for one saved scenario or compare results across multiple scenarios.

Use session state to make saved scenarios available on both pages.

?? minutes + ?? minute break

Extensions

  • Add a selector to choose which outcome to compare in the boxplot.
  • Let users delete saved scenarios.
  • Highlight which settings differ between selected scenarios.
  • Let users add a short optional note describing each scenario.

stlite

Reminder: Streamlit Community Cloud

In the last session, we introduced Streamlit Community Cloud.

It was an easy way to deploy from GitHub, with automatic updates when you push changes.

However, apps share limited server resources and go to sleep after 12 hours without visitors.

stlite

An alternative is stlite, which runs Python directly in the user’s browser. Instead of sending requests to a server to run your code, the user’s own device does the work.

How does stlite work?

A browser can display your app, but can’t normally run its Python code. Browsers usually use JavaScript, a programming language designed for web pages.

In 2017, WebAssembly (Wasm) was released. It allows browsers to run compiled code alongside JavaScript, including software they wouldn’t normally support.

Pyodide uses WebAssembly to provide a Python environment. It includes an interpreter (which reads and runs Python code) and support for packages.

stlite uses this environment to run your Streamlit app on the user’s device.

stlite: pros and cons

Pros:

  • No server to wake up.
  • No external resource limits, can cope with concurrent users.
  • Data doesn’t leave the user’s browser.
  • Host for free with GitHub Pages.

Cons:

  • Initial loading can take longer while Python and packages download.
  • Slower to run (as depends on the user’s device).
  • Not all Python packages and Streamlit features are supported.
  • Set-up is not as easy as Streamlit Community Cloud.
  • Browser caching can leave users seeing an older version of the app.

Running a Streamlit app with stlite

To use stlite, we add an index.html file to our app folder. HTML defines the structure and content of a web page. This file loads stlite and tells it how to launch our app.


We can reuse a standard template, changing a few details for our app.

Let’s work through the index.html used to deploy the scenario app.

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <title>Scenario app</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@stlite/browser@1.12.2/build/stlite.css" />
    <script type="module" src="https://cdn.jsdelivr.net/npm/@stlite/browser@1.12.2/build/stlite.js"></script>
  </head>
  <body>
    <streamlit-app src="./app.py">
        <app-file name="home.py" url="./home.py"></app-file>
        <app-file name="model.py" url="./model.py"></app-file>
        <app-file name="results.py" url="./results.py"></app-file>
        <app-file name="simulation.py" url="./simulation.py"></app-file>
        <app-file
            name="images/model_diagram.drawio.png"
            url="./images/model_diagram.drawio.png"
        ></app-file>
        <app-requirements>
            simpy==4.1.2
            numpy
            pandas
            sim-tools==1.3.0
        </app-requirements>
    </streamlit-app>
  </body>
</html>

Running a Streamlit app with stlite


The highlighted lines provide the standard page structure and can stay the same between apps.

  • <head> contains page settings and loads stlite’s stylesheet and JavaScript.
  • <body> contains the page content, including our app.

The closing tags at the end mark where the app, page body and HTML document finish.

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <title>Scenario app</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@stlite/browser@1.12.2/build/stlite.css" />
    <script type="module" src="https://cdn.jsdelivr.net/npm/@stlite/browser@1.12.2/build/stlite.js"></script>
  </head>
  <body>
    <streamlit-app src="./app.py">
        <app-file name="home.py" url="./home.py"></app-file>
        <app-file name="model.py" url="./model.py"></app-file>
        <app-file name="results.py" url="./results.py"></app-file>
        <app-file name="simulation.py" url="./simulation.py"></app-file>
        <app-file
            name="images/model_diagram.drawio.png"
            url="./images/model_diagram.drawio.png"
        ></app-file>
        <app-requirements>
            simpy==4.1.2
            numpy
            pandas
            sim-tools==1.3.0
        </app-requirements>
    </streamlit-app>
  </body>
</html>

Running a Streamlit app with stlite

Having said that, you’ll notice these are pinned to a particular version of stlite: @stlite/browser@1.12.2.

If a new version is released since the development of these slides, you may wish to upgrade to that - you can see the latest version in the stlite GitHub releases: https://github.com/whitphx/stlite/releases.

stlite recommend pinning to a version as they say their API may change without backwards compatability in future releases.

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <title>Scenario app</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@stlite/browser@1.12.2/build/stlite.css" />
    <script type="module" src="https://cdn.jsdelivr.net/npm/@stlite/browser@1.12.2/build/stlite.js"></script>
  </head>
  <body>
    <streamlit-app src="./app.py">
        <app-file name="home.py" url="./home.py"></app-file>
        <app-file name="model.py" url="./model.py"></app-file>
        <app-file name="results.py" url="./results.py"></app-file>
        <app-file name="simulation.py" url="./simulation.py"></app-file>
        <app-file
            name="images/model_diagram.drawio.png"
            url="./images/model_diagram.drawio.png"
        ></app-file>
        <app-requirements>
            simpy==4.1.2
            numpy
            pandas
            sim-tools==1.3.0
        </app-requirements>
    </streamlit-app>
  </body>
</html>

Running a Streamlit app with stlite


Moving on, these are things you’ll want to amend for your own app…


<title> sets the browser tab’s initial title.

The app replaces this once it loads, so it only appears briefly.

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <title>Scenario app</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@stlite/browser@1.12.2/build/stlite.css" />
    <script type="module" src="https://cdn.jsdelivr.net/npm/@stlite/browser@1.12.2/build/stlite.js"></script>
  </head>
  <body>
    <streamlit-app src="./app.py">
        <app-file name="home.py" url="./home.py"></app-file>
        <app-file name="model.py" url="./model.py"></app-file>
        <app-file name="results.py" url="./results.py"></app-file>
        <app-file name="simulation.py" url="./simulation.py"></app-file>
        <app-file
            name="images/model_diagram.drawio.png"
            url="./images/model_diagram.drawio.png"
        ></app-file>
        <app-requirements>
            simpy==4.1.2
            numpy
            pandas
            sim-tools==1.3.0
        </app-requirements>
    </streamlit-app>
  </body>
</html>

Running a Streamlit app with stlite



<streamlit-app> specifies the entrypoint file.

<app-file> identifies all other files required by the app - including Python files, images, and other file types.=

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <title>Scenario app</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@stlite/browser@1.12.2/build/stlite.css" />
    <script type="module" src="https://cdn.jsdelivr.net/npm/@stlite/browser@1.12.2/build/stlite.js"></script>
  </head>
  <body>
    <streamlit-app src="./app.py">
        <app-file name="home.py" url="./home.py"></app-file>
        <app-file name="model.py" url="./model.py"></app-file>
        <app-file name="results.py" url="./results.py"></app-file>
        <app-file name="simulation.py" url="./simulation.py"></app-file>
        <app-file
            name="images/model_diagram.drawio.png"
            url="./images/model_diagram.drawio.png"
        ></app-file>
        <app-requirements>
            simpy==4.1.2
            numpy
            pandas
            sim-tools==1.3.0
        </app-requirements>
    </streamlit-app>
  </body>
</html>

Running a Streamlit app with stlite


<app-requirements> lists the Python packages to install.

We pin simpy and sim-tools to the versions used to develop the app. We leave numpy and pandas unpinned so Pyodide can use its compatible versions.


We don’t include streamlit as stlite provides it.

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <title>Scenario app</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@stlite/browser@1.12.2/build/stlite.css" />
    <script type="module" src="https://cdn.jsdelivr.net/npm/@stlite/browser@1.12.2/build/stlite.js"></script>
  </head>
  <body>
    <streamlit-app src="./app.py">
        <app-file name="home.py" url="./home.py"></app-file>
        <app-file name="model.py" url="./model.py"></app-file>
        <app-file name="results.py" url="./results.py"></app-file>
        <app-file name="simulation.py" url="./simulation.py"></app-file>
        <app-file
            name="images/model_diagram.drawio.png"
            url="./images/model_diagram.drawio.png"
        ></app-file>
        <app-requirements>
            simpy==4.1.2
            numpy
            pandas
            sim-tools==1.3.0
        </app-requirements>
    </streamlit-app>
  </body>
</html>

Streamlit versions in stlite

stlite includes a modified version of Streamlit, adapted to run in the browser. This is why we do not add streamlit to <app-requirements>.

The stlite developers periodically update this version to the latest version of Streamlit, but may not always be up-to-date. New Streamlit features may therefore not be available immediately in stlite. Check the stlite release notes, and test your app before upgrading.

Each stlite release is pinned to a particular version of streamlit. For example, stlite 1.12.2 includes a build based on Streamlit 1.65.0.

Finding which streamlit version is in use

Via GitHub:

  1. Open the stlite release you are using on GitHub.
  2. Click the streamlit submodule link (e.g., streamlit @ 9c524f4). This opens the exact Streamlit source code included in that release.
  3. Open lib/pyproject.toml and find version under [project].

Alternatively, run your app using your chosen stlite version and include this command to see which Streamlit build it uses:

st.write("Streamlit version:", st.__version__)

Try out the stlite app locally

index.html serves as the website’s starting page. To view the app locally, open a terminal in the folder containing index.html and run:

python -m http.server 8000

Then open http://localhost:8000 in your browser. This lets us test the app on our own computer.

To share it with others through a web address, we need to host its files online. GitHub Pages can host index.html and the other files our app needs. When someone visits the website, their browser downloads these files and runs the app using stlite.

Hosting an stlite app on GitHub Pages

GitHub Pages



GitHub Pages is a website hosting service. It takes HTML, CSS, and JavaScript files from your GitHub repository and publishes them as a website.


It is free to use with public repositories.

It is easy to set up because it integrates directly with your GitHub repository.

Enabling GitHub Pages



The first step for setting up our stlite app website is to enable GitHub Pages.

From your GitHub repository, click on “Settings” and then in the sidebar click on “Pages”.

Enabling GitHub Pages

Under Source, select Deploy from a branch (if not already selected).

Then select main and / (root) and click Save.

It should now say your site is “currently being built from the main branch”.

Deployed site

Your app should now be live on GitHub Pages. Click the github-pages deployment in your repository’s right sidebar to view the deployment details and website link.

File locations

These instructions assume your app files are in the repository root (the top-level folder).

This is why we selected / (root) when setting up GitHub Pages.

For example:

your-repository/
├── index.html
├── app.py
├── home.py
├── model.py
├── simulation.py
├── results.py
└── images/
    └── logo.png

File locations

You can also organise your app files into subfolders.

If index.html stays in the root, the GitHub Pages settings stay the same. Just update the paths in index.html to match your file locations.

For example:

your-repository/
├── index.html
└── app/
    ├── app.py
    ├── home.py
    ├── model.py
    ├── simulation.py
    ├── results.py
    └── images/
        └── logo.png

File locations

If you move index.html into a subfolder too, you have a few options:

Location What to do
docs/index.html Select main → /docs as the publishing source.
app/index.html Publish the repository root and access the app at https://USERNAME.github.io/REPOSITORY/app/.
app/index.html Use a GitHub Actions workflow to publisht the contents of app/

For simplicity, we recommend keeping index.html in the repository root. The other files can be in subfolders - just make sure the paths in index.html match their locations.

Other hosting options

All aboard the Enterprise


If you’re lucky enough to be working in a progressive organisation, you may have access to a service like Posit Connect, Plotly Dash Enterprise or Snowflake.

These services massively simplify the deployment and hosting of Streamlit apps, along with a series of bells and whistles like permission management/user authentication support.

It usually means someone else has already dealt with (most of) the messy stuff around secure sharing of data.

All aboard the Enterprise

For example, from Posit Connect, you can deploy Streamlit apps with just a few lines - as well as Shiny apps (in R or Python), Quarto documents (with scheduled refresh), Dash apps…

Name your price

Price - and/or the way pricing is calculated - can often be a barrier for organisations.

E.g., the “enhanced” tier of Posit Connect

However, the efficiency savings by working with a tool like this have the potential to be huge.

Posit in particular have some history of working with NHS organisations to make pricing available that will work.

Anyone using these? Shout out or pop it in the chat!

Customising app appearance

Customising app appearance

There’s lots of fun ways to change the appearance of your app!

We’re going to touch on a few of the options available…

st.set_page_config

This function configures the page’s appearance. Set defaults in app.py, then override them on individual pages if needed. Key parameters include…

page_title: The title shown in the browser tab.

page_icon: The favicon, which is a small icon beside the browser tab’s title. Use an image, emoji or Material Symbols icon.

import streamlit as st

st.set_page_config(
    page_title="Nurse simulation",
    page_icon="🏥",
)

st.set_page_config

layout decides whether the app constrains content to a centered column (default) or if it uses the available page width.

This is what an app looks like with layout="centered".

import streamlit as st

st.set_page_config(
    layout="centered"
)

with st.sidebar:
    st.title("Layout demo")

st.image("backtothefuture.png")

st.set_page_config

layout decides whether the app constrains content to a centered column (default) or if it uses the available page width.

This is what an app looks like with layout="wide".

import streamlit as st

st.set_page_config(
    layout="wide"
)

with st.sidebar:
    st.title("Layout demo")

st.image("backtothefuture.png")

st.navigation

When we set-up our multi-page app using st.navigation, it provided a navigation menu in a sidebar by default.

We can move the navigation menu to the top of the screen using position="top". For example:


import streamlit as st

pg = st.navigation(
    pages=[
        st.Page("page1.py"),
        st.Page("page2.py"),
    ],
    position="top",
)
pg.run()

config.toml

Create a .streamlit folder in your project folder, then add a config.toml file:

your-app/
├── app.py
└── .streamlit/
    └── config.toml

This is a configuration file. It can control things like logging, error messages, and caching.

We’ll focus now on using it to customise the app’s theme.

config.toml theme

[theme]

# Theme that your custom theme inherits from
# Can be Streamlit's default light or dark theme
# Or a local file path or URL to a custom theme.toml file
base = "light"

# Primary accent colour for interactive elements
primaryColor = "#2563EB"

#  Background colour for the main content area
backgroundColor = "#FFFCF5"

# Secondary background colour, used for widgets and the sidebar
secondaryBackgroundColor = "#DEEAF6"

# Default text colour
textColor = "#172B4D"

# Default font, excluding code
font = "sans-serif"

Define your theme settings under [theme]. There are lots of options - we have included a few of the main ones here.

Use [theme.sidebar] to override settings specifically for the sidebar.

You can also define separate light and dark themes using [theme.light] and [theme.dark].

config.toml theme: light

This is what the default light theme looks like.

[theme]

# Theme that your custom theme inherits from
# Can be Streamlit's default light or dark theme
# Or a local file path or URL to a custom theme.toml file
base = "light"

config.toml theme: dark

This is what the default dark theme looks like.

[theme]

# Theme that your custom theme inherits from
# Can be Streamlit's default light or dark theme
# Or a local file path or URL to a custom theme.toml file
base = "dark"

config.toml theme: custom

This is an example of a custom theme.

[theme]

# Theme that your custom theme inherits from
# Can be Streamlit's default light or dark theme
# Or a local file path or URL to a custom theme.toml file
base = "light"

# Primary accent colour for interactive elements
primaryColor = "#2563EB"

#  Background colour for the main content area
backgroundColor = "#FFFCF5"

# Secondary background colour, used for widgets and the sidebar
secondaryBackgroundColor = "#DEEAF6"

# Default text colour
textColor = "#172B4D"

# Default font, excluding code
font = "sans-serif"

CSS

For additional customisation, we can use CSS (Cascading Style Sheets). CSS is a language that controls how web content look.

Use config.toml for the overall theme, and Streamlit’s built-in options wherever possible. CSS is useful for more specific styling that these options don’t support.

We can write these styles in a .css file and load them into our app using st.html().

import streamlit as st

with open("style.css") as css:
    st.html(f"<style>{css.read()}</style>")

Streamlit has introduced lots of new features over the last few years. You may find older tutorial using CSS, but those features are now supported directly by Streamlit, so it’s always worth checking the current documentaiton.

Exercise 2

Exercise 2


(1) Deploy your app using stlite and GitHub pages.

(2) Customise your app. You could try:

  • Setting st.set_page_config.
  • Adding st.logo().
  • Moving navigation menu to top of screen.
  • Adding config.toml with a custom theme.

Remember: If you add new files, they will also need to be added to index.html.

?? minutes + ?? minute break

Extensions

  • Use CSS to customise an element beyond the options available in the theme settings.
  • Create both a light and a dark theme for your app.
  • Test your deployed app on a phone or narrow browser window - could you improve the layout?

Other streamlit features

Other streamlit features

We’ve focused on the key features for building and sharing a DES app.

Streamlit has plenty more to offer, but we can’t cover everything in these sessions.

We’ll briefly highlight a few other features you might find useful.

See the Streamlit documentation for more examples and guidance.

st.metric()

Display a key value (value) with an optional indicator of change (delta).

By default, positive changes are green and negative changes are red, but this can be inverted or set manually.

import streamlit as st

st.metric(
    label="Average daily referrals",
    value=120,
    delta="10 vs last year",
    delta_color="red"
)

st.metric(
    label="Staffed beds",
    value=32,
    delta="4 vs last year",
    delta_color="green",
)

st.grid()

st.grid() is a responsive container that works well for displaying metrics side by side. Elements reflow into fewer columns when less width is available, so the layout can adapt to different screen sizes.

import streamlit as st

grid = st.grid()

grid.metric(
    label="Average daily referrals",
    value=120,
    delta="10 vs last year",
    delta_color="red"
)

grid.metric(
    label="Staffed beds",
    value=32,
    delta="4 vs last year",
    delta_color="green",
)

Input widgets

There are several other input widgets beyond those we’ve used, including:

Status elements

If your simulation takes a while to run, status elements can be helpful for reassuring users that they app is working and that they should wait.


Supported chart libraries

We used st.plotly_chart, but there are several others…

Built-in streamlit charts

Streamlit also has some built-in plotting functions.


st.toast

This displays a short message in the app’s top-right corner which disappears after 4 seconds.

import streamlit as st

if st.button("Show notification"):
    st.toast("Your simulation has finished!")

st.popover

Popover creates a container that opens when clicked.

import streamlit as st

with st.popover("Open popover"):
    st.write("Hello!")

st.write("""
This is our demo app.

We are demonstrating `st.popover`.

It will appear over the top of this text when clicked.
""")

Fragments

By default, interacting with a widget reruns the app script.

Use @st.fragment to define a function that can rerun independently when users interact with widgets inside it.

For example, users could change which results appear in a chart without rerunning unrelated parts of the page.

Caching

Use @st.cache_data to save the output of a function and reuse it when its code and inputs haven’t changed.

This can avoid repeatedly loading data or performing expensive calculations.

Be careful when caching a simulation: running it again with the same inputs may return the cached results rather than generate a new random sample.

User authentication

Streamlit supports signing users in with st.login().

  • st.user provides information about the signed-in user.
  • st.logout() signs them out.

Connections and databases

Streamlit has built-in support for connections to Snowflake and SQL using SQLAlchemy.

Custom components



If Streamlit doesn’t have the feature you need, you may find a custom component developed by the community.

These extend your app with additional functionality.

You can also build your own components.

Check compatibility with your deployment approach, particularly if you are using stlite.

App testing

Streamlit’s AppTest lets you test an app programmatically.

You can simulate interactions, such as changing an input or clicking a button, and check the resulting output.

For example, check that opening the results page before running a scenario displays your information message rather than an error.