Basics of Discrete Event Simulation using SimPy
Last Updated :
19 Nov, 2020
SimPy is a powerful process-based discrete event simulation framework written in Python.
Installation :
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 -
Python
def func():
return 1
return 2
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
Python
def func():
while True:
yield 1
yield 2
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 -
Python3
# Python 3 code to demonstrate basics of SimPy package
# Simulation of a Traffic Light
# import the SimPy package
import simpy
# Generator function that defines the working of the traffic light
# "timeout()" function makes next yield statement wait for a
# given time passed as the argument
def Traffic_Light(env):
while True:
print ("Light turns GRN at " + str(env.now))
# Light is green for 25 seconds
yield env.timeout(25)
print ("Light turns YEL at " + str(env.now))
# Light is yellow for 5 seconds
yield env.timeout(5)
print ("Light turns RED at " + str(env.now))
# Light is red for 60 seconds
yield env.timeout(60)
# env is the environment variable
env = simpy.Environment()
# The process defined by the function Traffic_Light(env)
# is added to the environment
env.process(Traffic_Light(env))
# The process is run for the first 180 seconds (180 is not included)
env.run(until = 180)
Output :
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.
Similar Reads
GUI Dice Roll Simulation using Python
In this article, we are going to create Rolling The Dices Game using Tkinter and a random module in Python. A random module in Python is a built-in module used to generate random numbers for various distributions. Here, we will use this module to create random outcomes for our dice. Python offers va
4 min read
Generating Basic Discrete Time Signals
Generating basic discrete-time signals for Discrete-Time Signal ProcessingUnit Step, Unit Impulse, Unit Ramp, exponential signals are very commonly used signals in signal processing to perform various operations. Unit step signal is given byUnit impulse signal is given byUnit ramp signal is given by
2 min read
Monty Hall Problem's Simulation Using Pygame
In this article, we are going to see how to create Monty Hall games using Pygame in Python. Monty Hall was a game show of the American television game show Let's Make a Deal. Suppose you're on a game show, and you're given the choice of three doors, Behind one door is a car; behind the others, goat
13 min read
Dice Rolling Simulator using Python-random
In this article, we will create a classic rolling dice simulator with the help of basic Python knowledge. Here we will be using the random module since we randomize the dice simulator for random outputs. Function used: 1) random.randint(): This function generates a random number in the given range.
2 min read
Turing Machine Simulator Using Python
Turing machines and deterministic finite automata (DFAs) are two fundamental concepts in computer science and automata theory. Both these concepts are used to model and analyze computational systems and are essential tools in understanding the limits of computation. A Turing machine is a theoretical
11 min read
How to choose elements from the list with different probability using NumPy?
We will see How to use numpy.random.choice() method to choose elements from the list with different probability. Syntax: numpy.random.choice(a, size=None, replace=True, p=None) Output: Return the numpy array of random samples. Note: parameter p is probabilities associated with each entry in a(1d-arr
2 min read
Introduction to Simulation Modeling in Python
Simulation is imitating the operations which take place within a system to study its behavior. Analyzing and creating the model of a system to predict its performance is called simulation modeling. Simulation mimics a real-life process to determine or predict the response of the entire system. This
4 min read
Maximize Optimization using Scipy
In this post, we'll talk about the Python Scipy module and the idea of linear programming problems, including how to maximize the objective function and obtain the best solution. Linear Programming Linear Programming consists of an objective function (Z) and some constraints. According to the situat
5 min read
Blackjack console game using Python
Blackjack is a popular two-player card game that is played with a deck of standard playing cards around the world in casinos. The main criteria for winning this game are chance and strategy. The challenge of this game is to get as close to 21 points as possible without exceeding them. That is why it
6 min read
Python program for biased coin flipping simulation
Flipping a biased coin is an interesting exercise that combines probability theory with programming. There is a fixed probability of getting Head and Tails on a Biased coin, though it is not a 50/50 chance. In this article, we will show you the Python program to simulate flipping a biased coin. Pyth
2 min read