SimPy is a powerful process-based discrete event simulation framework written in Python.
To install SimPy, use the following command –
pip install simpy
Basic Concepts :
The core idea behind SimPy is the generator function in Python. The difference between a normal function and a generator is that a normal function uses the “return” statement, while a generator uses “yield” statement.
If the function has a return statement, then even on multiple function calls, it returns the same value. For eg –
When the func() is called during the runtime, it will always return at the first instance of the return statement, that is, the function func() always returns 1, and the next return statement is never executed.
However, in discrete event simulation, we may need to find the state of the system at a given time T. For that, it is required to remember the state of the interval just before T, and then perform the given simulation and return to state at time T.
This is where generator functions are quite useful. For example, consider the following function
Now, when the first time this function is called, it ‘yields’ 1. However, on the very next call, it will yield 2. In some sense, it remembers what it returned upon the last call, and moves on to the next yield statement.
Events in SimPy are called processes, which are defined by generator functions of their own. These processes take place inside an Environment. (Imagine the environment to be a large box, inside of which the processes are kept.)
Consider a simple example, involving the simulation of a traffic light –
Light turns GRN at 0 Light turns YEL at 25 Light turns RED at 30 Light turns GRN at 90 Light turns YEL at 115 Light turns RED at 120
In this code, the generator function Traffic_Light(env) takes the environment variable as the argument and simulates the operation of the traffic light for the time period passed as argument in the env.run() function. (Actually, time in SimPy is unitless. Though it can be converted to hours, minutes or seconds as per convenience). env.now returns the current value of the time elapsed.
env.timeout() function is the base of this simulation, as it waits for the time passed as the argument to be elapsed on the computer’s simulation clock (it is not a real time clock), and then initiate the next yield statement, till the time passed as argument in env.run() has finished.
env.run() starts all the processes linked to the environment at the same time = 0.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.