Simulation-in-Python-with-SimPy
Simulation-in-Python-with-SimPy
WITH SIMPY
A GENTLE INTRODUCTION TO THE WORLD OF
SIMPY AND ANALYSING SIMULATIONS WITH
REAL-WORLD EXAMPLES
HARRY MUNRO
Copyright © 2025 by Harry Munro
No part of this book may be reproduced in any form or by any electronic or mechanical
means, including information storage and retrieval systems, without written permission
from the author, except for the use of brief quotations in a book review.
TESTIMONIALS
Preface vi
Introduction viii
Dear Reader,
Downloadable Code
Most of the code examples are available for download. You can access
the code by downloading and unzipping the file at this link.
Yours sincerely,
Harry Munro
With such capabilities, it’s no surprise that DES is an essential tool for
engineers, scientists, and analysts working in today’s complex, data-
driven world. But as we’ll explore, not all simulation approaches are
created equal - and that’s where Python, and its powerhouse library
SimPy, enter the stage.
Vendor Lock-In
Proprietary tools rarely integrate seamlessly with external systems.
They are designed to keep users within their ecosystem, creating
dependency on a single vendor. This lock-in reduces flexibility and
increases long-term costs, particularly if you need features not
included in the software’s package or decide to move to a different
solution.
With Python, iteration is fast. You can tweak parameters, test new
ideas, and improve your models at a pace that proprietary tools simply
can’t match. This speed is invaluable in dynamic industries where
agility is key.
No two projects are ever the same in simulation engineering. One day,
I might be modelling transport systems; the next, I’m working on opti-
mising mining operations or designing renewable energy systems. The
variety keeps the work endlessly interesting, and the value I bring is
always recognised. When you solve a problem that saves time, money,
or resources, people notice.
Maybe you’ve reached a point where your current job feels stagnant,
or you’re considering a career that offers more flexibility, creativity, and
financial freedom. Simulation engineering could be the fresh start
you’re looking for, and this book will guide you through the possi-
bilities.
If you’ve worked with proprietary tools and felt the pain of high costs,
limited flexibility, or opaque black-box models, this book will help you
INTRODUCTION xv
The transition was not without its hurdles. I was learning Python as I
went, figuring out version control for the first time, and navigating the
complexities of creating detailed simulations from scratch. Yet, the
more I worked with SimPy, the more its advantages became apparent.
It allowed me to model complex sites on the Underground network –
from depots to intricate junctions – with a level of detail and customi-
sation that the proprietary tool couldn’t match.
This experience taught me more than just how to use Python for
simulation. It showed me the power of challenging the status quo,
embracing new tools, and trusting in my ability to learn and adapt.
These lessons have stayed with me, and I hope they’ll inspire you as
you embark on your own journey into simulation with Python.
Downloadable Code
Most of the code examples in this book are available for download.
You can access the code by downloading and unzipping the file at this
link.
CHAPTER 1
WHAT IS DISCRETE-EVENT
SIMULATION (DES)?
A
t its core, Discrete-Event Simulation is a method of modelling
a system as a series of discrete events occurring at specific
points in time. Each event triggers a change in the state of
the system—like a machine starting or stopping, a customer arriving or
leaving, or a signal being sent or received. By focusing on these critical
junctures, DES provides a granular view of system dynamics without
getting lost in the continuous flow of time.
2 HARRY MUNRO
APPLICATIONS OF DES
DES finds its strength in industries where timing and resource alloca-
tion are critical. Its applications are as diverse as the systems it models:
ADVANTAGES OF DES
LIMITATIONS OF DES
E
nter SimPy - a powerful, process-based discrete-event
simulation framework for Python. SimPy provides a clean and
straightforward way to model DES systems, leveraging
Python's simplicity and versatility. With SimPy, you can define events,
manage resources, and simulate processes in a way that's both intuitive
and efficient, making it an excellent tool for academia and industry
alike.
WHY SIMPY
In the world of simulation, simplicity and flexibility are often at odds.
Traditional simulation tools can be robust but intimidating, while
simpler ones may lack the depth needed for complex systems. SimPy
strikes a perfect balance by offering:
• • •
6 HARRY MUNRO
SimPy isn’t just a tool; it’s a bridge between theory and practice. By
combining Python’s accessibility with DES’s precision, it empowers
users to model, test, and improve systems with confidence. As you
progress through this guide, you’ll see how SimPy transforms abstract
concepts into practical solutions, ready to tackle the challenges of
designing, evaluating and optimising modern systems.
CHAPTER 3
SIMPY BASICS
INSTALLATION
I
magine possessing the power to predict the behaviour of a
bustling shop or the seamless operation of a factory—all from the
comfort of your desk. SimPy, a lightweight and intuitive Python
library for discrete-event simulations, allows you to do just that. To
begin your journey into the world of simulation, you need only a
simple command:
CORE CONCEPTS
SimPy revolves around a few key concepts that help model the
behaviour of real-world systems.
Environment
SIMULATION IN PYTHON WITH SIMPY 9
Example:
import simpy
env = simpy.Environment()
Processes
Example:
def process_example(env):
print(f"Process starts at time {env.now}")
yield env.timeout(5)
print(f"Process resumes at time {env.now}")
10 HARRY MUNRO
Events
Example:
def machine(env):
print(f"Machine starts at {env.now}")
yield env.timeout(3) # Machine works for 3
units of time
print(f"Machine stops at {env.now}")
Resources
Resources in SimPy model shared assets that processes compete
for, such as servers, machines, or workers. Resources are essential
when modelling systems with limited availability.
Example:
def process_with_explicit_request(env,
resource):
# Request the resource
req = resource.request()
yield req # Wait until the resource is
available
print(f"Resource acquired at {env.now}")
resource.release(req)
print(f"Resource released at {env.now}")
# Simulation setup
env = simpy.Environment()
resource = simpy.Resource(env, capacity=1)
env.process(process_with_explicit_re‐
quest(env, resource))
env.run(until=10)
Explanation
• • •
Summary
SIMULATION FLOW
Process Creation: Processes are added to the environment using
env.process() like so:
env.process(process_example(env))
env.run(until=10)
T
his section walks through the creation of a basic SimPy
simulation, introducing key concepts like processes, timeouts,
and events. Here’s how to write a simple simulation using
SimPy.
import simpy
env = simpy.Environment()
def car(env):
while True:
print(f'Car parks at {env.now}')
yield env.timeout(5) # Car is parked for 5
units of time
print(f'Car drives at {env.now}')
yield env.timeout(2) # Car drives for 2
units of time
Here:
env.process(car(env))
env.run(until=15)
SIMULATION IN PYTHON WITH SIMPY 17
import simpy
def car(env):
while True:
print(f'Car parks at {env.now}')
yield env.timeout(5) # Car is parked for 5
units of time
print(f'Car drives at {env.now}')
yield env.timeout(2) # Car drives for 2
units of time
env = simpy.Environment()
env.process(car(env))
env.run(until=15)
EXPLANATION OF OUTPUT
The simulation will produce output like:
Car parks at 0
Car drives at 5
Car parks at 7
Car drives at 12
Car parks at 14
1. The car parks at time 0 and stays parked for 5 time units.
2. It then drives from time 5 to time 7.
3. This alternation between parking and driving continues
until the simulation reaches time 15.
18 HARRY MUNRO
S
imPy makes it simple to model real-world processes and
systems by providing several fundamental components.
Understanding these core elements will help you build more
complex simulations.
Example:
def machine(env):
20 HARRY MUNRO
Here, the machine operates for 3 time units, simulated by the env.-
timeout() function, which represents the passage of time.
def worker(env):
print(f'Worker starts at {env.now}')
yield env.timeout(2) # Worker works for 2
time units
print(f'Worker finishes at {env.now}')
In this example, the worker stops working after 2 units of time. The
simulation time advances by 2 time units as the timeout is yielded.
RESOURCES
Resources in SimPy model limited assets like machines, workers, or
servers that processes compete for. When a process needs access to a
resource, it issues a request, and when it’s done, it releases the
resource.
import simpy
env = simpy.Environment()
worker = simpy.Resource(env, capacity=1) #
Only one worker available
env.process(task(env, worker))
env.run(until=10)
In this example:
SCHEDULING EVENTS
SimPy allows you to schedule future events and control how they’re
processed by the environment.
Example:
def event_scheduler(env):
print(f'Starting at {env.now}')
yield env.timeout(5) # Schedule an event 5
units from now
print(f'Event occurred at {env.now}')
env = simpy.Environment()
env.process(event_scheduler(env))
env.run(until=10)
env = simpy.Environment()
SIMULATION IN PYTHON WITH SIMPY 23
env.run(until=10)
Here:
Three tasks are created, but since there’s only one worker,
the tasks must wait for the worker to be available.
Each task takes 2 time units, and the simulation runs for 10
units of time.
CHAPTER 6
SIMULATING A QUEUE
SYSTEM
I
n many real-world systems, entities (like customers, jobs, or
products) need to wait in line for a resource to become available
(e.g., a service desk, a machine, or a server). SimPy makes it easy
to simulate these kinds of queue systems using resources and
processes.
import simpy
In this example:
Here:
Example:
env = simpy.Environment()
counter = simpy.Resource(env, capacity=1)
import simpy
import numpy as np
env = simpy.Environment()
counter = simpy.Resource(env, capacity=1)
28 HARRY MUNRO
env.run(until=20)
Key Differences
Key Observations:
Code Implementation:
import simpy
import matplotlib.pyplot as plt
Example:
import numpy as np
# Plot the number of customers in the queue
over time
plt.plot(times, queue_sizes, marker='o',
label='Queue Size')
Example:
Example:
avg_queue_size = sum(queue_sizes) /
len(queue_sizes)
36 HARRY MUNRO
plt.axhline(avg_queue_size, color='green',
linestyle='--', label=f'Avg Queue Size:
{avg_queue_size:.2f}')
Practical Applications
import simpy
import matplotlib.pyplot as plt
Practical Insights
By increasing the resource capacity and adding traceability, you can
gain deeper insights into how multiple entities compete for resources
in real-world systems. This is particularly useful for:
W
hen working with simulations, especially for complex
systems with multiple entities and events, it’s essential to
write efficient and manageable code. Here are some best
practices to ensure your simulations run smoothly and remain easy to
understand.
Bad Example:
Good Example:
Example:
Example:
Example:
wait_times = []
At the end of the simulation, you can analyse this data to find
bottlenecks or optimise resource usage.
Example:
SIMULATION IN PYTHON WITH SIMPY 47
Example:
A
s we come to the end of this guide, it’s clear that discrete-event
simulation (DES) offers immense power in understanding
complex systems. Whether you’re modelling customer
queues, manufacturing processes, or network traffic, the ability to
simulate and optimise your systems opens up new opportunities for
efficiency, cost savings, and innovation.
By learning SimPy, you’ve not only equipped yourself with the
technical know-how but also gained insights into how real-world
systems behave under various conditions. This knowledge is incred-
ibly valuable, whether you’re in academia, industry, or simply curious
about the inner workings of dynamic systems.
But this is only the beginning of your journey. There’s so much more to
explore in the world of simulation:
Thank you for taking this journey with me. I hope this guide has been
an insightful companion, offering both a practical understanding of
SimPy and a broader appreciation for the power of simulations. Keep
experimenting, keep questioning, and most importantly, keep learning.
If you’re ready to take your simulation skills further, don’t hesitate
to dive into more advanced topics, connect with the community, or
explore other resources. You can sign up to my free masterclass too
here: https://simulation.teachem.digital/webinar-signup
Until then, I wish you the best of luck in your simulation adventures!
ABOUT THE AUTHOR
I've been working with simulation for over 13 years across all sorts of
industries, from transport to mining to defence to energy.
linkedin.com/in/harryjmunro
ALSO BY HARRY MUNRO
Supercharged SimPy
Learn how to make simulations in Python with SimPy, interlaced with relevant
real world examples.
Including advanced topics such as animating SimPy simulations, how to
analyse and visualise simulation results and how to do Monte-Carlo
simulations.
Containing multiple downloadable code examples with the book to keep
forever and evergreen access to the latest version.