Introduction to the SimPy package

Discrete Event Simulation in Python

Dr Diogo Costa

Adjunct Professor, University of Saskatchewan, Canada & CEO of ImpactBLUE-Scientific

What is SimPy?

SimPy package logo: Discrete event simulations for Python

  • Process-based discrete-event simulation framework based on standard Python

  • Uses generator functions to define processes and events (explored in Toolbox prerequisite course)

  • Scalable:

    • Models can contain multiple generators
    • Each generator can include multiple processes
    • Processes can run in sequence or in parallel
Discrete Event Simulation in Python

Normal functions vs. generator functions

Normal Function

def mygenerator():
    return 10
  • return returns a value and terminates the execution of the function

Executing the function:

10

Generator Function

def mygenerator():
    yield 20
    yield 12
  • yield returns a value and pauses the execution while maintaining internal states.

Executing the generator:

20
12
Discrete Event Simulation in Python

Summarizing key SimPy methods

1) Create a SimPy Environment

env = simpy.Environment()

2) Adding Generator Function to a SimPy Environment

env.process()

3) Run the model

env.run()

4) Let time pass in a simulation

env.timeout()

5) Get current simulation time

env.now
Discrete Event Simulation in Python

Traffic lights: Building a SimPy model

1) Import the SimPy Package

import simpy

2) Creating a generator function containing processes

def traffic_light(env, name, timestep):
     while True:
        yield env.timeout(timestep)
        print(f"Time {env.now:02d} sec | Traffic light at {name} | Red light!")
        yield env.timeout(timestep)
        print(f"Time {env.now:02d} sec | Traffic light at {name} | Yellow Light!")
        yield env.timeout(timestep)
        print(f"Time {env.now:02d} sec | Traffic light at {name} | Green Light!")
Discrete Event Simulation in Python

Traffic lights: Building a SimPy model

3) Creating a SimPy building environment

env = simpy.Environment()

4) Add the generator to SimPy environment

env.process(traffic_light(env, "Leslie St.", 15))
env.process(traffic_light(env, "Arlington Av.", 30))

5) Run the model

env.run(until=90)
Discrete Event Simulation in Python

Traffic lights: Model outputs

Console model output:

Time 15 sec  |  Traffic light at Leslie St.     |  Red light!
Time 30 sec  |  Traffic light at Arlington Av.  |  Red light!
Time 30 sec  |  Traffic light at Leslie St.     |  Yellow Light!
Time 45 sec  |  Traffic light at Leslie St.     |  Green Light!
Time 60 sec  |  Traffic light at Arlington Av.  |  Yellow Light!
Time 60 sec  |  Traffic light at Leslie St.     |  Red light!
Time 75 sec  |  Traffic light at Leslie St.     |  Yellow Light!
Discrete Event Simulation in Python

Let's practice!

Discrete Event Simulation in Python

Preparing Video For Download...