Simulation-in-Python-with-SimPy-Print
Simulation-in-Python-with-SimPy-Print
WITH SIMPY
A GENTLE INTRODUCTION TO THE WORLD OF
SIMPY AND ANALYSING SIMULATIONS WITH
REAL-WORLD EXAMPLES
HARRY MUNRO
Copyright © 2024 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,
Yours sincerely,
Harry Munro
INTRODUCTION
But what does this look like in practice? Let me share a story from my
career that illustrates how simulation can transform decision-making
and drive meaningful outcomes.
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:
resource = simpy.Resource(env, capacity=1)
with resource.request() as req:
yield req # Wait until the resource is available
yield env.timeout(5) # Use the resource for 5 units of time
# Simulation setup
env = simpy.Environment()
resource = simpy.Resource(env, capacity=1)
env.process(process_with_explicit_request(env, resource))
env.run(until=10)
12 HARRY MUNRO
• • •
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)
import simpy
16 HARRY MUNRO
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
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.
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):
SIMULATION IN PYTHON WITH SIMPY 19
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):
SIMULATION IN PYTHON WITH SIMPY 21
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()
worker = simpy.Resource(env, capacity=1) # Only one worker
available
env.run(until=10)
22 HARRY MUNRO
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:
SIMULATION IN PYTHON WITH SIMPY 25
Example:
env = simpy.Environment()
counter = simpy.Resource(env, capacity=1)
import simpy
import numpy as np
26 HARRY MUNRO
env = simpy.Environment()
counter = simpy.Resource(env, capacity=1)
env.run(until=20)
Key Differences
Key Observations:
• • •
28 HARRY MUNRO
• • •
SIMULATION IN PYTHON WITH SIMPY 29
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')
# Adjust the x-axis times to align the moving average with the correct
starting point
32 HARRY MUNRO
Example:
Example:
Practical Applications
import simpy
import matplotlib.pyplot as plt
36 HARRY MUNRO
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 45
Example:
env.step() # Executes one event at a time
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.
Until then, I wish you the best of luck in your simulation adventures!
ABOUT THE AUTHOR