Monday, November 26, 2012

Queue simulation in Scilab

This post is an answer for Agnes, who commented the last post:

Engineering and Scientific Computing with Scilab - Book

This script is a simple simulation of a queue of packs (or anything else) which there are a source, the queue and a destiny.

I coded this script for simulating and problem where there is a source that sends packs with a specific probability, a queue that receives the source packs and stores them, with a maximum number of stored packs, and a destiny that receives the packs from the queue with another specific probability.

All interested ones can run the code and comment it.

N_packs = 15; //total number of packs

P_send = 0.5; //probability of a pack to be sent

P_process = 0.5; //probability of a pack to be processed

N_queue = 10; //maximum number of elements in the queue

N_sent = 0; //number of packs sent to queue

N_line = 0; //number of packs in the queue

N_processed = 0; //number of packs processed

src = rand(N_packs, 2); //source packs

dst = []; //destiny packs

line = []; //queue

processed = []; //processed packs

while N_processed < N_packs,
    try
        plot(src(:,1) + N_queue + 2, src(:,2), '.g'); 
//plots source packs as green dots
    end;
    
    try
        plot(processed(:,1) + N_queue + 2, processed(:,2), '*k'); 
//plots the queue as line of blue dots
    end;
    
    plot(1:N_queue, zeros(1, N_queue), '.w'); //clears queue dots
    
    try
        plot(line(:,1), line(:,2), '.b'); 
//plots the queue as line of blue dots
    end;
    
    try
        plot(dst(:,1), dst(:,2), '.r'); 
//plots destiny packs as red dots
    end;
    
    if rand() < P_send then 
//sends a pack with P_send probability
        if and([N_line < N_queue N_sent < N_packs]) then 
//verifies the queue is full or all packs have been sent
            N_sent = N_sent + 1;
            
            N_line = N_line + 1;
            
            line(N_line,:) = [N_line 0];
            
            processed(N_sent,:) = src(1,:);
            
            src = src(2:$,:);
        end
    end
    
    if rand() < P_process then 
//processes a pack with P_process probability
        if N_line > 0 then 
//verifies the line has at least one pack
            N_processed = N_processed + 1;
            
            N_line = N_line - 1;
            
            line = line(1:N_line,:);
            
            dst(N_processed,:) = -rand(1, 2);
        end
    end
end

No comments: