Discrete Event Simulation in Python
Dr Diogo Costa
Adjunct Professor, University of Saskatchewan, Canada & CEO of ImpactBLUE-Scientific
Process-based discrete-event simulation framework based on standard Python
Uses generator functions to define processes and events (explored in Toolbox prerequisite course)
Scalable:
Normal Function
def mygenerator():
return 10
return
returns a value and terminates the execution of the functionExecuting 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
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
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!")
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)
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