0% found this document useful (0 votes)
43 views31 pages

Mslab All 2982

The document is a student's practical file that contains 10 experiments conducted for the course "Modelling & Simulation Lab". It includes the aim, software, description, pseudocode, implementation, and output for each experiment focusing on random number generation, linear congruential generator, chi-square testing of random numbers, Monte Carlo simulation, LAG model simulation, and single/multiple queue server system simulation.

Uploaded by

Anubhav Khurana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views31 pages

Mslab All 2982

The document is a student's practical file that contains 10 experiments conducted for the course "Modelling & Simulation Lab". It includes the aim, software, description, pseudocode, implementation, and output for each experiment focusing on random number generation, linear congruential generator, chi-square testing of random numbers, Monte Carlo simulation, LAG model simulation, and single/multiple queue server system simulation.

Uploaded by

Anubhav Khurana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

PRACTICAL FILE

Student Name Anubhav Khurana


UID 19BCS2982
Section & 19BCS-11 Group-A
Group
Department Computer Science & Engineering
Session Aug-Dec 2022
Course Name Modelling & Simulation Lab
Course Code CSP-443
Semester 7TH
INDEX

S. Experiment Date of Conduct Viva Record Total Teacher’s


N. Experiment (12 (10 (08 (30 Signature
marks) marks) marks) marks)

1. Write a program to
implement a random number
generator.
2. Write a program to
implement linear
congruential generator
3. Write a program to
implement testing of
Random numbers (Chi
Square)
4. Write a program to
implement Monte Carlo
Simulation
5. Write a program to
implement simulation of
LAG model
6. Write a program to
implement simulation of
Single Queue Server System
7. Write a program to
implement simulation of
Multiple Queue Server
System
8. Write a program to
implement simulation of a
conveyor belt system
9. Write a program to
implement simulation of
inventory system
10. Write a program to
implement COBWEB model
CourseName:Modelling & Simulation Lab Course code: CSP-443

Experiment:1

Aim: To implement the basic components like random number generator.

Tools/Software Required: MATLAB R2013A, Personal computer

Description:
Rand:- Uniformly distributed random numbers
Randn:- Normally distributed random numbers
Randi:- Uniformly distributed pseudorandom integers

Pseudo code/Algorithms/Flowchart/Steps:
Rand:

X = rand returns a random scalar drawn from the uniform distribution in the interval (0,1). X = rand(n) returns
an n-by-n matrix of uniformly distributed random numbers.
X =rand(sz1,...,szN) returns an sz1-by-...-by-szN array of random numbers
where sz1,...,szN indicate the size of each dimension. For example, rand(3,4) returns a 3-by-4 matrix.
X = rand(sz) returns an array of random numbers where size vector sz defines size(X). For example, rand([3
4]) returns a 3-by-4 matrix.
X=rand( ,typename) returns an array of random numbers of data type
typename. The typename input can be either "single" or "double".

Randn:
X = randn returns a random scalar drawn from the standard normal distribution. X = randn(n) returns an n-by-
n matrix of normally distributed random numbers.
X = randn( ,typename) returns an array of random numbers of data type typename.
The typename input can be either "single" or "double". You can use any of the input arguments in the previous
syntaxes.

Name : Anubhav UID: 19BCS2982


CourseName:Modelling & Simulation Lab Course code: CSP-443
Randi:
X = randi(imax) returns a pseudorandom scalar integer between 1 and imax.
X = randi(imax,n) returns an n-by-n matrix of pseudorandom integers drawn from the discrete uniform
distribution on the interval [1,imax].
X = randi(imax,sz1,...,szN) returns an sz1-by-...-by-szN array where sz1,...,szN indicate the size of each
dimension. For example, randi(10,3,4) returns a 3-by-4 array of pseudorandom integers between 1 and 10.
X = randi(imax,sz) returns an array where size vector sz defines size(X). For example, randi(10,[3 4]) returns a
3-by-4 array of pseudorandom integers between 1 and 10.

Implementation & Output:


Rand:

Name : Anubhav UID: 19BCS2982


CourseName:Modelling & Simulation Lab Course code: CSP-443

Name : Anubhav UID: 19BCS2982


CourseName:Modelling & Simulation Lab Course code: CSP-443
Randn:

Name : Anubhav UID: 19BCS2982


CourseName:Modelling & Simulation Lab Course code: CSP-443
Randi:

Name : Anubhav UID: 19BCS2982


CourseName:Modelling & Simulation Lab Course code: CSP-443

Experiment:2

Aim: Write a program to implement linear congruential generator.

Tools/Software Required: MATLAB R2013A, Personal computer

Description:
Formula for the linear congruential generator is
X(i+1)= mod(a*(x(i)+c),m)
Where,
X(i+i) is the random numbers generated a is the multiplier
x(i) is Seed (previous random number generated)
c is incremental value m is the modulus conditions: m>0 a< m x

Pseudo code/Algorithms/Flowchart/Steps:
a = 25; c = 37;
m = 200;
x = zeros(1,200);
x(1) = 7;
for i=2:numel(x)
x(i) = mod(a*x(i-1)+c,m)
end

Name : Anubhav UID: 19BCS2982


CourseName:Modelling & Simulation Lab Course code: CSP-443
Implementation & Output:

Name : Anubhav UID: 19BCS2982


Course Name: Modelling & Simulation Lab Course code: CSP-443

Experiment: 3

Aim: To implement testing of Random numbers (Chi Square).

Tools/Software Required: MATLAB R2013A, Personal computer

Description:
h = chi2gof(x) returns a test decision for the null hypothesis that the data in vector x comes from a normal
distribution with a mean and variance estimated from x, using the chi-square goodness of-fit test. The
alternative hypothesis is that the data does not come from such a distribution. The result h is 1 if the test
rejects the null hypothesis at the 5% significance level, and 0 otherwise. h = chi2gof(x,Name,Value) returns
a test decision for the chi-square goodness-of-fit test with additional options specified by one or more
name-value pair arguments. For example, you can test for a distribution other than normal, or change the
significance level of the test.

Pseudo code/Algorithms/Flowchart/Steps:
PROGRAM:
h = chi2gof(x)
h = chi2gof(x,Name,Value)

Name : Anubhav UID: 19BCS2982


Course Name: Modelling & Simulation Lab Course code: CSP-443

Implementation & Output:

Name : Anubhav UID: 19BCS2982


Course Name: Modelling & Simulation Lab Course code: CSP-443

Name : Anubhav UID: 19BCS2982


Course Name: Modelling & Simulation Course code: CSP-443

Experiment: 4

Aim: To implement Monte Carlo Simulation.

Tools/Software Required: MATLAB R2013A, Personal computer

Description:
Monte Carlo simulation is a method for exploring the sensitivity of a complex system by
varying parameterswithin statistical constraints. These systems can include financial,
physical, and mathematical models that are simulated in a loop, with statistical uncertainty
between simulations. The results from the simulation are analysed to determine the
characteristics of the system.

Pseudo code/Algorithms/Flowchart/Steps:
N=10000;
head=0;
tail=0;
for
i=1:N
if rand<=0.5
head=head+1;
plot(head,tail,'
g.'); else
tail=tail+1;
plot(head,tail,'
r.'); end
hold
on; end
hold off;
prob_t=head
/N;
prob_h=tail
/N;

Name: Anubhav UID: 19BCS2982


Course Name: Modelling & Simulation Course code: CSP-443

Implementation & Output:

Name: Anubhav UID: 19BCS2982


CourseName: Modelling and simulation lab Course code: CSP-443

Experiment:5

Aim: To implement the simulation of LAG model.


Tools/Software Required: Using MATLAB R2013A, personal computer
Description:
A “lag” is a fixed amount of passing time; One set of observations in a time series is plotted (lagged) against
a second, later set of data. The kth lag is the time period that happened “k” time points before time i..
Example : 𝑦𝑡 = 𝛼 − 𝛽0𝑡𝑡 + 𝛽1𝑡𝑡−1 + 𝛽2𝑡𝑡−2 + 𝑈𝑡

Auto regression Model :


Autoregression is a time series model that uses observations from previous time steps as input to a
regression equation to predict the value at the next time step.
Example : 𝑦𝑡 = 𝛼 + 𝛾𝑦𝑡−1 + 𝛾𝑦𝑡−2 + 𝑢𝑡

Function used : lagmatrix (Y , X)


Where , X= Lag to be introduced
Y= Matrix
Lagmatrix is an inbuild function in matlab , that is used to introduce a lag of X into Y matrix.
Lagmatrix(Y,lags) shifts the input regular series Y in time by the lags (positive) or leads (negative) in lags,
and returns the matrix of shifted series YLag.

Pseudo code/Algorithms/Flowchart/Steps:
• Generate matrix Y
• Set Lag X , that you want to introduce
• Use lagmatrix(Y,X) to use
• Print output

Name: Anubhav UID: 19BCS2982


CourseName: Modelling and simulation lab Course code: CSP-443
Implementation :
Y = randi([1,10],[3,2])
X = [1,2]
m = lagmatrix(Y, X)

Output:

Name: Anubhav UID: 19BCS2982


CourseName: Modeling & simulation lab Course code: CSP-443

Experiment:6

Aim:
Write a program to implement simulation of Single Queue Server System.

Software Required:
MATLAB R2013A, Personal computer, Simulink.

Theory:
This example shows how to model a single-queue single-server system with a single traffic source and an
infinite storage capacity. In the notation, the M stands for Markovian; M/M/1 means that the system has a
Poisson arrival process, an exponential service time distribution, and one server. Queuing theory provides
exact theoretical results for some performance measures of an M/M/1 queuing system and this model makes
it easy to compare empirical results with the corresponding theoretical results.

The model includes the components listed below:


• Entity Generator block: Models a Poisson arrival process by generating entities (also known as
"customers" in queuing theory).
• Simulink Function exponentialArrivalTime(): Returns data representing the interarrival times
for the generated entities. The interarrival time of a Poisson arrival process is an exponential
random variable.
• Entity Queue block: Stores entities that have yet to be served in FIFO order
• Entity Server block: Models a server whose service time has an exponential distribution.

Time Based Entity Generator block: It models a Poisson arrival process by generating entities (also known
as "customers" in queuing theory).
Exponential Interarrival Time Distribution subsystem: It creates a signal representing the interarrival
times for the generated entities. The interarrival time of a Poisson arrival process is an exponential random
variable.
FIFO Queue block: It stores entities that have yet to be served.
Single Server block: It models a server whose service time has an exponential distribution.

Code:

Name: Anubhav UID: 19BCS2982


CourseName: Modeling & simulation lab Course code: CSP-443

% Exponential service time with rate 1


Mean = 1;
Dt = -mean * log(1- rand() );

Output:

Name: Anubhav UID: 19BCS2982


CourseName: Modeling & simulation Course code:

Experiment:7

Aim:
Write a program to implement simulation of Multiple Queue Server System.

Software Required:
MATLAB R2013A, Personal computer, Simulink.

Theory:
The purpose of this LiveScript is to simulate M/M/N queuing system, where N is the number of servers and
queues with unlimited space for customers. There are 4 variables that needs to be defined by user:
N = number of servers and queues ( N of servers = N of queues)
Tk = time duration of simulation in minutes
mi0 = arrival rate in minutes/customer arrival, i.e. mi0 = 0,5 -> customer arrives every 30 sec
mi1 = service rate in minutes/customer served, i.e. mi1 = 2,5 -> customer is served in 2 minutes and 30 sec
The arrival and service rates are not static, but they are distributed by an exponential distribution. The
random seed of rand in exponential distribution is managed by rng(44) at the start of the script.
The script is divided into sections by their purpose. The first section serves to set parameters by user. This is
the only section where user should edit variables. Then there is pre-allocation section, with approximation
pre-allocation of some vectors. Third is simulation section. Fourth is vector edit section. Vectors that have
been approximately pre-allocated are here trimmed. Fifth section contains text outputs. Sixth section
contains graph outputs with gpu parallelization enabled.
Variable names in text outputs:
ppc(i) - average number of customers in queue(i) at any time of simulation
maxf(i) - maximum number of customers in queue(i) at time
vetappz - average number of customers in the whole system at any time
cpz - total number of customers in system
maxpz - maximum number of customers in system at time
pvl(i) - average workload of server(i) in %
pcc(i) - average waiting time in queue(i)
NC - total number of served customers
Here are some examples of ways to combine FIFO Queue and Single Server blocks to model different
situations:
• Serial Queue-Server Pairs

Name: Anubhav UID: 19BCS2982


CourseName: Modeling & simulation Course code:

• Parallel Queue-Server Pairs as Alternatives


• Parallel Queue-Server Pairs in Multicasting
• Serial Connection of Queues
• Parallel Connection of Queues

Output:

Name: Anubhav UID: 19BCS2982


CourseName: Modelling and Simulation Lab Course code: CSP-443

Experiment No: 8

AIM: - Write a program to implement simulation of inventory system.

IDEA USED: - MATLAB R2022a or MATLAB Online Compiler, Simulink

DESCRIPTION: -
This example shows how to build a simple inventory management system for a retail store. This example
includes:
• Random customer arrivals to the store with the number of products requested by each customer also
randomly distributed
• Tracking available inventory at the end of the day
• Tracking and disposal of expired products
• Placing periodic orders for fresh products
• Store profitability analysis

FLOWCHART: -

Fig 3.1.1 Flowchart for Inventory Management

Name: Anubhav UID: 19BCS2982


CourseName: Modelling and Simulation Lab Course code: CSP-443

IMPLEMENTATION: -

Fig 3.1.2 Sample Inventory Management

Name: Anubhav UID: 19BCS2982


CourseName: Modelling and Simulation Lab Course code: CSP-443

Structure of the Model


The model includes these components:
• Warehouse: The warehouse generates and stores products in shelves. The products
have limited shelf life and they are dispatched when a product order is received.

Fig 3.1.3 Warehouse


During the generation process, products are marked with their manufacture day, and they are
periodically checked for disposal if their storage duration exceeds the maximum days they are
allowed to stay on the shelf. Warehouse component allows you to specify the initial quantity of
available products and the maximum number of days they are allowed to remain on the shelf.

• Transportation: The Transportation block represents the delay, which is the duration between a
product's dispatch from the warehouse and its arrival at the store. The default delay is set to two
hours.

Fig 3.1.4 Transportation


• Customer Arrival: The arrival of customers at the store is modeled as a Poisson process and you
can specify the mean time between arrivals. The number of products required by each customer is
also random and it is generated from a discrete uniform distribution. You can specify the upper
bound of this uniform distribution.
• Store Management:

Name: Anubhav UID: 19BCS2982


CourseName: Modelling and Simulation Lab Course code: CSP-443

Fig 3.1.5 Store Management

• Store Tag: This area models the part of the retail store that receives products from the warehouse
and applies the 'Product' and 'Expiry' tags on them. These tags allow us to search for products later
on.
• Customers Entry: Represents customers entering the store to pick up products from the shelves
and their departure from the store. This is modeled using the 'Entity Find' block, which looks for
entities in the system that have the 'Product' tag associated with them.
• Store Shelf: This area contains a Queue where the products are stored. Customers pick up products
from here. An 'Entity Gate' that is perpetually closed ensures that products don't flow out of the
store.
• Expired Products Removal: This area models the periodic removal of expired products from the
store's shelves. This is modeled using the 'Entity Find' block. The find block is triggered periodically
to perform a search for entities that have the 'Product' tag associated with them. It then looks for
products that have exceeded the shelf life and discards them.
• Accounting: This area models the investigation of profitability of the retail store for the duration
between consecutive product ordering points. The profit is calculated as a function of the product
procurement price, product holding cost and the product selling price. The profit also plays a role
in determining the number of products that the retail store orders. If the store is profitable in the
current period, then the new quantity to be ordered is the sum of the previously ordered quantity
plus any unfulfilled orders. This is also adjusted for expired and unsold products.

Name: Anubhav UID: 19BCS2982


CourseName: Modelling and Simulation Lab Course code: CSP-443

• Periodic Order Placement: This area models periodic order placement by the retail store. An order
is placed with the Warehouse for supplying a fresh batch of products to the retail store. You can
specify the period by setting the value of the reorder point.

Fig 3.1.6 Periodic Order Placement

SAMPLE OUTPUT: -
The model is simulated for 60 days. One unit of simulation time represents 1 minute of wall clock time. Based
on the model parameters set, plots are generated showing the number of products sold, the number of
customers who arrived at the store, the product order size, number of expired products in the store and the
store's profitability. Observe that for each period, the optimal store order quantity is around 85 for the given
customer arrival rate.

Name: Anubhav UID: 19BCS2982


CourseName: Modelling and Simulation Lab Course code: CSP-443

Experiment No: 9

AIM: -Write a program to implement simulation of telephonic

SYSTEM IDEA USED: -MATLAB R2022a or MATLAB

Online Compiler

DISCUSSION: -
Lost calls are any inbound calls that do not result in the caller being connected to either an advisor or an
answering service. This happens when the customer hangs up or is disconnected by the centre. The centre
may disconnect a call deliberately, because of timeout – the call was taking too long to reach an agent – or
through error.
Categories of Lost Call
• Abandoned – The customer terminates the call before it is answered. The industry standard suggests
that an abandon rate of 2-5% is commonplace.
• Missed – The call is deliberately disconnected by the centre. This usually occurs when an incoming
call reaches the maximum threshold for waiting time set by the ACD.
• Dropped – The call is accidentally disconnected due to a technical error. The dropped call rate for
landline calls is below 0.01%. The rate for mobile phone calls is slightly higher, but a dropped call
rate of even a few per cent would warrant further investigation.

STEPS: -
1. Scan the potential event.
2. Select the activity that is to cause the event.
3. Test whether the potential event that can be executed.
4. Change records to reflect the event.
5. Gather the statistics of simulation output.

IMPLEMENTATION:
clear all;
Tracking available inventory at the end of the dayhome;
C = 100; %Number of calls made ( 100 taken for ease of comparision) mIAT = input('Enter
mean inter arrival time (mins):');
callInt =exprnd(mIAT,[C-1,1]); %Inter arrival time for 100 calls

arrvInst = zeros(length(callInt)+1 ,1); % Call arrival instances


%Compute call arrival instances arrvInst(1) = 0; %First call arrives at time = 0
for k = 2:C,
arrvInst(k) = arrvInst(k-1) + callInt(k-1);

Name: Anubhav UID: 19BCS2982


CourseName: Modelling and Simulation Lab Course code: CSP-443
end

mHT = input('Enter mean holding time (mins):');


holdTime = exprnd(mHT,[C,1]); %Holding time for 100 calls.
termTime = zeros(C,1); %Termination instances

%Compute call termination time for k = 1:C,


termTime(k) = arrvInst(k) + holdTime(k); %Termination time = arrivalInstance +
holdingTime

N = 10; %Number of trunked channels available


Serviced = 0; Blocked = 0; flagServed = 0; %Flag is 1 if serviced
channels = zeros(N,1); %Channel array chUsage = N*ones(C,1);
%-----Determine : Serviced, Blocked calls-------------
for i = 1:100,
for k = 1:N,
if( channels(k) < arrvInst(i))
Serviced = Serviced + 1;
flagServed = 1;
channels(k) = termTime(i);
break;
end
end
%Check remaining channels
if(k < 5 )
for j = k+1:5,
if(channels(j) < arrvInst(i))
channels(j) = 0; %If calls have been terminated clear the channels
end
end
elseif (flagServed == 0)
Blocked = Blocked + 1;
end
flagServed = 0; %Reset Flag
% channels = sor t(channels); %Sort channels according to termInst values
for x = 1:N,
if (channels(x) == 0)
chUsage(i) = chUsage(i) - 1;
end
end
end

display('Serviced calls :'); disp(Serviced);


display('Blocked calls :');
disp(Blocked); stem(chUsage) title('Channel Usage Graph');

Name: Anubhav UID: 19BCS2982


CourseName: Modelling and Simulation Lab Course code: CSP-443

SAMPLE OUTPUT:-
Simulation of a trunked communication network with N channels. Total of 100 calls are considered for
simulation. The network is a Lost Calls Cleared type system

Fig 3.2.1 Sample Output of Simulation of Telephonic System

Name: Anubhav UID: 19BCS2982


CourseName: Modelling and Simulation Lab Course code: CSP-443

Experiment No: 10

AIM :- Write a program to implement COBWEB model.

SOFTWARE REQUIRED: -MATLAB R2022a or MATLAB Online Compiler

DESCRIPTION: -
The cobweb model or cobweb theory is an economic model that explains why prices might
be subject to periodic fluctuations in certain types of markets . It describes cyclical supply
and demand in a market where the amount produced must be chosen before prices are
observed. The cobweb model is generally based on a time lag between supply and demand
decisions. Agricultural markets are a context where the cobweb model might apply, since
there is a lag between planting and harvesting (gives two agricultural examples: rubber
and corn). Suppose for example that as a result of unexpectedly bad weather, farmers go
to market with an unusually small crop of strawberries. This shortage, equivalent to a
leftward shift in the market's supply curve, results in high prices. If farmers expect these
high price conditions to continue, then in the following year, they will raise their
production of strawberries relative to other crops. Therefore, when they go to market the
supply will be high, resulting in low prices. If they then expect low prices to continue,
they will decrease their production of strawberries for the next year, resulting in high
prices again.
The cobweb model can have two types of outcomes:
• If the supply curve is steeper than the demand curve, then the fluctuations decrease in
magnitude with each cycle, so a plot of the prices and quantities over time would look like an inward
spiral, as shown in the first diagram. This is called the stable or convergent case.
• If the demand curve is steeper than the supply curve, then the fluctuations increase in
magnitude with each cycle, so that prices and quantities spiral outwards. This is called the unstable or
divergent case.

IMPLEMENTATION: -
function cobweb(f,a,b,x0,N)

x=linspace(a,b,N);
y=f(x);
hold on;

plot(x,y,'k');

Name: Anubhav UID: 19BCS2982


CourseName: Modelling and Simulation Lab Course code: CSP-443
plot(x,x,'r');
xlabel('x(t)')
ylabel('y(t)')
x(1)=x0;

line([x(1),x(1)],[0,f(x(1))]);
line([x(1),f(x(1))],[f(x(1)),f(x(1))]); for i=1:N
x(i+1)=f(x(i));
line([x(i+1),x(i+1)],[x(i+1),f(x(i+1))]);
line([x(i+1),f(x(i+1))],[f(x(i+1)),f(x(i+1))])

end

hold off;
function
ret=f(x)
ret=2*x.*(1-x);

Fig 3.3.1 Various COBWEB Fluctuations

Two other possibilities are:


• Fluctuations may also maintain a constant magnitude, so a plot of the outcomes would produce
a simple rectangle. This happens in the linear case if the supply and demand curves have exactly the
same slope (in absolute value).
• If the supply curve is less steep than the demand curve near the point where the two curves
cross, but steeper when we move sufficiently far away, then prices and quantities will spiral away
from the equilibrium price but will not diverge indefinitely; instead, they may converge to a limit
cycle.

Name: Anubhav UID: 19BCS2982


CourseName: Modelling and Simulation Lab Course code: CSP-443
STEPS: -
If we are working on the problem of survival of fittest in the population, then this solution will
involve following steps:
1. Select parents from the population
2. Crossover and generate a new population
3. Mutation on new population
4. Calculate fitness for the new generation
The loop is stopped when no better solutions are coming after several iterations.

SAMPLE OUTPUT: -
The sample output graph will be COBWEB which will depend upon the input function and values
that we chose.

Fig 3.3.2 Sample COBWEB Graph

Name: Anubhav UID: 19BCS2982

You might also like