Open Sim Tutorial
Open Sim Tutorial
net/publication/390428622
CITATIONS READS
0 30
5 authors, including:
Navonil Mustafee
University of Exeter
199 PUBLICATIONS 3,993 CITATIONS
SEE PROFILE
All content following this page was uploaded by Thomas Monks on 04 April 2025.
Navonil Mustafee
ABSTRACT
This tutorial aims to support modellers working in healthcare research or practice to build Discrete-
Event Simulation models using the Free and Open Source Software SimPy and Python. We provide a
step-by-step guide to building a stylised urgent care telephone call centre model. Open materials that
accompany the tutorial, including models and exercises, are available online and can be run without
installing Python. As the materials are introductory, we also provide a “next steps” section that describes
simple, intermediate and advanced extensions to the work.
1 INTRODUCTION
Computer simulation has long been used as a tool for decision support in healthcare process design
and optimisation, particularly in supporting healthcare decision makers to ask ‘what-if’ we delivered
care differently. Within the academic literature, Discrete-Event Simulation (DES) has become the
predominant approach in healthcare modelling (Salleh et al. 2017). Recent reviews of the field
demonstrate the wide-ranging applications of DES in health service delivery, for example, evaluating
operational performance, improving patient flow, and optimizing service scheduling (Vázquez-Serrano
et al. 2021, Forbus and Berleant 2022, Roy et al. 2021). DES models are valuable for decision making
and are also valuable research artefacts in and of themselves: models are time-consuming to code
and document in natural language; require significant clinical, methods, and informatics expertise; and
depend on specialized software and logic. Given the cost that goes into a developing a coded model
we argue that Free and Open Source Software (FOSS) and its value to Open Science (Monks et al.
2024) has a substantive role to play in increasing the ability for models to be shared and reused across
health services.
This paper provides an introduction to building DES models in FOSS. By the end of the tutorial
readers will have the skills to code and extend a simple queuing model in Python and SimPy. Before
providing a step-by-step coding of a DES model in health, we introduce the concept of FOSS and
what this means for computer simulation studies. We then briefly review the availability of FOSS
Monks, Harper, Heather, Mayne, and Mustafee
DES packages; the barriers associated with using them for research compared to modern Commercial
Off-The-Shelf (COTS) simulation packages; and the other initiatives available that aim to increase
FOSS uptake in research.
0. The freedom to run the program as you wish, for any purpose.
1. The freedom to study how the program works and modify it to suit your needs.
2. The freedom to redistribute copies to help your neighbours.
3. The freedom to distribute copies of your modified versions to others, allowing the whole
community to benefit from your changes.
Importantly, FOSS involves more than just open source code; it grants users the right to freely
adapt and distribute copies of code. FOSS repositories often include a permissive license like MIT or
BSD-2 licenses. These grant users the four freedoms (within commercial or non-commercial work),
waive liability, and require crediting (citation) of the authors and their software in subsequent work.
FOSS is increasingly used for computer simulation, such as DES (Monks and Harper 2023a). This
tutorial will focus on DES in Python, as it is the language we use in our practical health care simulation
studies (e.g. Harper et al. (2023)).
typically developed in NetLogo (and in October 2024, there were 1162 models: 61% NetLogo and 7%
Python, etc). Taking a different approach, the Sharing Tools and Artefacts for Reusable Simulations
(STARS) framework for healthcare aims to support simulation researchers to share a version of their
FOSS computer simulation model that is accessible and reusable by others (Monks et al. 2024). STARS
provides details of both architecture to share models, and also published applied examples of Python
models for others to adapt and reuse. A software-specific initiative to highlight is the extensive and
growing documentation to Ciw2 that now contains over 40 topics of support (as of October 2024).
Another software-specific intiative provides a tutorial to use Streamlit to build a browser based user-
interface to Python models (Monks and Harper 2023b). Lastly, in the UK, the NIHR Applied Research
Collaboration South West Peninsula funds the Health Service Modelling Associates Programme3 that
has developed the “Little Book of DES” ([Link] The book teaches simulation methods
to the NHS using Python and Simpy.
and Cohn 2018), end-of-life care (Chalk et al. 2021), and operating theatre management (Hassanzadeh
et al. 2023, Harper et al. 2023).
• Section 4: Introduces the basic tools to model variability in Python via the NumPy library.
• Section 5: Creates a basic SimPy model to simulate the arrival process.
• Section 6: Adds queuing and service components to the model.
• Section 7: Adds basic result collection logic to the model.
• Section 8: Discusses where a reader should look next in their studies as well as highlighting
some additional resources available in our online supplementary material.
Here we used the uniform method of the PRNG object, but we could have similarly used the
exponential method.
1 import numpy as np
2
3 rng = [Link].default_rng(42) # define arrivals PRNG
4 samples = [Link](low=10, high=40, size=1_000_000)
Listing 1: Efficient sampling using the NumPy package
4 [Link]
Monks, Harper, Heather, Mayne, and Mustafee
5.2 Delays
We can include delays or activities within a SimPy process model. For example, these might be the
duration of a patient’s stay on a ward or the duration of an operation. In this case, we introduce a time
between arrival events (inter-arrival time). In Listing 2, an inter-arrival time is sampled on Line 10.
This is used on Line 11 to create a delay via the timeout method of the environment object env.
Model logic can access the simulation time before and after delays using [Link] (e.g. line 12).
5.3 Processes
In SimPy, the event-process mechanism is implemented using Python generators. A generator is a
Python object that can return a sequence of values; for example, a sequence of times between patient
arrivals. A simple way to visualise the arrival processes in SimPy is as an infinite loop of delays, where
each delay represents the time until the next arrival. Unlike a standard Python loop, a generator can
be paused and resumed at later time, making it ideal for event-scheduling in SimPy.
For each arrival process in our model, we create a new generator process. In Listing 2, we have
created a single arrival process (for callers) modelled by the generator function arrivals_generator
(Lines 5 to 12). The generator function contains an infinite loop (here implemented as a while loop). On
Monks, Harper, Heather, Mayne, and Mustafee
each iteration, a new inter-arrival time is sampled from the Exponential distribution and an environment
timeout (delay) of the same duration is yielded. The keyword yield before the timeout is essential in
Listing 2 Line 11: it is needed to tell the Python interpreter that the function is a Python generator. On
line 11 yield is combined with [Link]() to schedule the end of the event (the next caller
arrival).
1. Add a Python generator called service which contains the queuing and call activity logic
(Listing 3).
2. Create a SimPy resource called operator (Listing 4)
3. Modify arrivals_generator to create and schedule the service process, which uses
operator, as each caller arrives to the model (Listing 4).
1. A caller service process requests a call operator resource. If none are available, the caller
process waits in a queue.
2. Once an operator resource becomes available, the call process is assigned and undergoes a
phone triage (represented as a delay). The duration of this delay is sampled from a triangular
distribution.
3. After the call process is completed, the operator resource is released, and the caller process
exits the model.
6.1.1 Parameters
The service generator accepts four parameters (as in Line 1 of Listing 3):
1 import numpy as np
2 import itertools
3 import simpy
4
5
6 def arrivals_generator(env, operators):
7
8 # create the arrival process rng
9 arrival_rng = [Link].default_rng()
10
Monks, Harper, Heather, Mayne, and Mustafee
11 # create the service rng that we pass to each service process created
12 service_rng = [Link].default_rng()
13
14 # with a counter variable that we can use for unique Ids
15 for caller_count in [Link](start=1):
16 inter_arrival_time = arrival_rng.exponential(60.0 / 100.0)
17 yield [Link](inter_arrival_time)
18 print(f"call arrives at: {[Link]:.3f}")
19
20 # create a new simpy process for serving this caller.
21 [Link](service(caller_count, operators, env, service_rng))
22
23
24 # model parameters
25 RUN_LENGTH = 100
26 N_OPERATORS = 13
27
28 # create simpy environment and operator resources
29 env = [Link]()
30 operators = [Link](env, capacity=N_OPERATORS)
31
32 [Link](arrivals_generator(env, operators))
33 [Link](until=RUN_LENGTH)
34 print(f"end of run. simulation clock time = {[Link]}")
Listing 4: A modified arrival process and run script used to created service processes
1. Code an auditor/observer process. This process will periodically observe the state of the
system. We can use this to collect information on the current state at time t. For example,
how many callers are queuing and how many have a call in progress, at certain timepoints
throughout the day.
2. Store process metrics during a run and perform calculations at the end of a run. For
example, if you want to calculate mean patient waiting time then store each caller waiting time
in a list and calculate the mean at the end of the run.
3. Monitor resources to calculate time weighted statistics. Resource utilisation and mean queue
length can be tracked as resources are requested and released. This is more a advanced approach
to results collection that requires both knowledge of theory and Object Orientated Programming
to implement. The method is beyond the scope of our tutorial, but we provide an example
implementation in our online supplementary material.
In this tutorial, we will calculate the mean waiting time for a single replication of the model using
method 2. To do this we will make the following modifications to the code:
• Replace all calls to Python’s print function with a custom trace function that can be used to
toggle the display of model output on or off.
• Create a Python dictionary called results that will store all waiting times for service. For
simplicity, we will give this global variable scope.
• Modify service to calculate caller waiting times and store these in results.
• Create a function called single_run that will run the model once and return the mean waiting
time as a result.
• Line 17: Computes the waiting time (current simulation time minus the arrival time, which we
already recorded on Line 10).
• Line 18: Stores this time in results (the global dictionary) by appending to a list stored
under the key waiting_times.
Lines 20 and 25 are also modified to call the function trace, defined in Lines 1 to 4. This simple
function prints output messages depending on whether a constant called TRACE is set to true or false.
1 def trace(msg):
2 """Wrap print function to toggle simulation printed output on/off"""
3 if TRACE:
4 print(msg)
5
6
7 def service(identifier, operators, env, service_rng):
8 """Simulates the service process for a call operator"""
9 # record the time that call entered the queue
10 start_wait = [Link]
11
12 # request an operator
13 with [Link]() as req:
14 yield req
15
16 # record the waiting time for call to be answered
17 waiting_time = [Link] - start_wait
18 results["waiting_times"].append(waiting_time)
Monks, Harper, Heather, Mayne, and Mustafee
19
20 trace(f"operator answered call {identifier} at " + f"{[Link]:.3f}")
21
22 call_duration = service_rng.triangular(left=5.0, mode=7.0, right=10.0)
23 yield [Link](call_duration)
24
25 trace(
26 f"call {identifier} ended {[Link]:.3f}; "
27 + f"waiting time was {waiting_time:.3f}"
28 )
Listing 5: Setup of results collection mode
single_run (or multiple replications) function. This class should contain default values and a way
to quickly set all of the parameters. By using a class, the number of parameters passed to each function
within a model is minimal (as low as one: the Experiment object). When using this approach, we
would also recommend eliminating all global variables (which have only been included in our tutorial
for simplicity). Monks and Harper (2023b) provide an advanced tutorial describing this object-oriented
approach using classes, and apply it to both SimPy and Ciw models. We provide an applied example using
an Experiment class in our supplementary online material (see the 07_experiments.ipynb
notebook).
9 SUMMARY
Our aim in this tutorial is to support modellers in their journey to build and share FOSS DES models.
When compared to DES models built using COTS packages, FOSS models are still relatively rare. We
hope this tutorial will be part of the solution to increase the FOSS DES prevalence in the literature. This
is because we feel that - in order for the modelling and simulation community to learn and adopt the
skills needed to build FOSS models - we need to build a critical mass of open models. As discussed, the
tutorial we provide is only introductory, but it is relatively simple to extend our work to health systems
with more detailed processes and patient pathways. We hope that the intermediate and advanced next
steps we outline also open readers to new ideas, such as RAPs, and an understanding of how their DES
models work and could be organised.
Monks, Harper, Heather, Mayne, and Mustafee
ACKNOWLEDGMENTS
TM is supported by the NIHR Applied Research Collaboration South West Peninsula. The views
expressed in this publication are those of the author(s) and not necessarily those of the NIHR or the
Department of Health and Social Care.
FUNDING
This work was supported by the Medical Research Council [MR/Z503915/1].
For the purpose of open access, the author has applied a Creative Commons Attribution (CC BY)
licence to any Author Accepted Manuscript version arising from this submission.
REFERENCES
Allen, M., A. Bhanji, J. Willemsen, S. Dudfield, S. Logan, and T. Monks. 2020. “A simulation modelling
toolkit for organising outpatient dialysis services during the COVID-19 pandemic”. PLoS One 15
(8): e0237628.
Anagnostou, A., D. Groen, S. J. Taylor, D. Suleimenova, N. Abubakar, A. Saha, K. Mintram, M. Ghorbani,
H. Daroge, T. Islam, Y. Xue, E. Okine, and N. Anokye. 2022. “FACS-CHARM: A Hybrid Agent-
Based and Discrete-Event Simulation Approach for Covid-19 Management at Regional Level”. In
2022 Winter Simulation Conference (WSC), 1223–1234.
Bovim, T. R., A. N. Gullhav, H. Andersson, J. Dale, and K. Karlsen. 2021, December. “Simulating
emergency patient flow during the COVID-19 pandemic”. Journal of Simulation 0 (0): 1–15.
Publisher: Taylor & Francis eprint: [Link]
Bovim, T. R., A. N. Gullhav, H. Andersson, J. Dale, and K. Karlsen. 2023. “Simulating emergency
patient flow during the COVID-19 pandemic”. Journal of Simulation 17 (4): 407–421.
Chalk, D., S. Robbins, R. Kandasamy, K. Rush, A. Aggarwal, R. Sullivan, and C. Chamberlain. 2021.
“Modelling palliative and end-of-life resource requirements during COVID-19: implications for
quality care”. BMJ open 11 (5): e043795.
Dagkakis, G., and C. Heavey. 2016. “A review of open source discrete event simulation software for
operations research”. Journal of Simulation 10 (3): 193–206.
Forbus, J. J., and D. Berleant. 2022. “Discrete-Event Simulation in Healthcare Settings: A Review”.
Modelling 3 (4): 417–433.
Goldberg, A. P., and J. R. Karr. 2020. “DE-Sim: an object-oriented, discrete-event simulation tool for
data-intensive modeling of complex systems in Python”. Journal of Open Source Software 5 (55):
2685.
Griffiths, J. D., M. Jones, M. Read, and J. E. Williams. 2010. “A simulation model of bed-occupancy
in a critical care unit”. Journal of Simulation 4 (1): 52–59.
Harper, A., T. Monks, R. Wilson, M. T. Redaniel, E. Eyles, T. Jones, C. Penfold, A. Elliott, T. Keen,
M. Pitt et al. 2023. “Development and application of simulation modelling for orthopaedic elective
resource planning in England”. BMJ open 13 (12): e076221.
Hassanzadeh, H., J. Boyle, S. Khanna, B. Biki, F. Syed, L. Sweeney, and E. Borkwood. 2023. “A
discrete event simulation for improving operating theatre efficiency”. The International Journal of
Health Planning and Management 38 (2): 360–379.
McInnes, A. I., and B. R. Thorne. 2011. “ScipySim: Towards Distributed Heterogeneous System
Simulation for the SciPy Platform”.
Monks, T., and A. Harper. 2023a. “Computer model and code sharing practices in healthcare discrete-
event simulation: a systematic scoping review”. Journal of Simulation 0 (0): 1–16. Publisher:
Taylor & Francis eprint: [Link]
Monks, T., and A. Harper. 2023b. “Improving the usability of open health service delivery simulation
models using Python and web apps”. NIHR Open Research 3:48.
Monks, Thomas and Harper, Alison and Heather, Amy 2025, February. “An introduction to Discrete-
Event Simulation using Free and Open Source Software”.
Monks, T., A. Harper, and N. Mustafee. 2024. “Towards sharing tools and artefacts for reusable
simulations in healthcare”. Journal of Simulation 0 (0): 1–20.
NHS 2024. “NHS 111 Online Service”. [Link] Accessed: 2024-10-10.
Monks, Harper, Heather, Mayne, and Mustafee
Palmer, Geraint and Tian, Yawen 2021a, March. “Source code for Ciw hybrid simulations.”.
Palmer, G. I. et al. 2019. “Ciw: An open-source discrete event simulation library”. Journal of Simula-
tion 13 (1): 68–82.
Palmer, G. I., and Y. Tian. 2021b. “Implementing hybrid simulations that integrate DES+ SD in Python”.
Journal of Simulation:1–17.
Pfeiffer, A. et al. 2012. “PySimulator–A simulation and analysis environment in Python with plugin
infrastructure”.
Ren, Y., M. Phan, P. Luong, J. Wu, D. Shell, C. D. Barras, S. Chryssidis, H. K. Kok, M. Burney,
B. Tahayori, J. Maingard, A. Jhamb, V. Thijs, D. M. Brooks, and H. Asadi. 2021. “Application of
a computational model in simulating an endovascular clot retrieval service system within regional
Australia”. Journal of Medical Imaging and Radiation Oncology 65 (7): 850–857.
Ren, Y., M. Phan, P. Luong, J. Wu, D. Shell, C. D. Barras, H. K. Kok, M. Burney, B. Tahayori, H. M.
Seah, J. Maingard, K. Zhou, A. Lamanna, A. Jhamb, V. Thijs, D. M. Brooks, and H. Asadi. 2020.
“Geographic Service Delivery for Endovascular Clot Retrieval: Using Discrete Event Simulation
to Optimize Resources”. World Neurosurgery 141:e400–e413.
Richardson, D. B., and A. E. M. Cohn. 2018. “MODELING THE IMPACT OF MAKE-AHEAD
CHEMOTHERAPY DRUG POLICIES THROUGH DISCRETE-EVENT SIMULATION”. In 2018
Winter Simulation Conference (WSC), 2690–2700.
Roy, S., S. P. Venkatesan, and M. Goh. 2021. “Healthcare services: A systematic review of patient-
centric logistics issues using simulation”. Journal of the Operational Research Society 72 (10):
2342–2364.
Salleh, S., P. Thokala, A. Brennan, R. Hughes, and A. Booth. 2017. “Simulation Modelling in Healthcare:
An Umbrella Review of Systematic Literature Reviews”. PharmacoEconomics 35 (9): 937–949.
Team SimPy 2020. “SimPy 3.0.11”. [Link]
van der Ham, R. 2018. “Salabim: open source discrete event simulation and animation in python”. In
Proceedings of the 2018 Winter Simulation Conference, 4186–4187.
Vázquez-Serrano, J. I., R. E. Peimbert-Garcı́a, and L. E. Cárdenas-Barrón. 2021. “Discrete-Event Simu-
lation Modeling in Healthcare: A Comprehensive Review”. International Journal of Environmental
Research and Public Health 18 (22): 12262.
Wise, A. F., L. E. Morgan, A. Heib, C. S. Currie, A. Champneys, R. Nadarajah, C. Gale, and M. Mamas.
2021. “Modeling Of Waiting Lists For Chronic Heart Failure In The Wake Of The COVID-19
Pandemic”. In 2021 Winter Simulation Conference (WSC), 1–11.
AUTHOR BIOGRAPHIES
THOMAS MONKS is an Associate Professor of Health Data Science at University of Exeter Medical
School. His research interests include open science for computer simulation, urgent and emergency
care, and real-time discrete-event simulation. His email address is [Link]@[Link]
ALISON HARPER is a lecturer in operations and analytics at the Centre for Simulation, Analytics
and Modelling, University of Exeter. Her research interests include applied health and social care mod-
elling and simulation, real-time simulation, and reusable modelling in healthcare. Her email address is
[Link]@[Link]
AMY HEATHER is a Postdoctoral Research Associate the Peninsula Collaboration for Health Oper-
ational Research and Data Science (PenCHORD) at the University of Exeter. Her research interests
include health data science and open science. Her email address is a.heather2@[Link]
ANDREW MAYNE is Chief Scientist for Data, Operational Research and Artificial Intelligence at
Somerset NHS Foundation Trust. He is also Chief Technology Officer for the South West Secure Data
Environment. His interests are in admission prediction and simulation modelling of patient pathways
in the NHS. His email address is [Link]@[Link]
hybrid modelling and real-time simulation, and their application in healthcare, supply chain management,
circular economy and climate change adaptation and resilience. He is a Joint Editor-in-Chief of the View publication stats