SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library...

72

Transcript of SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library...

Page 1: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

SIM : a C++ library for Discrete Event SimulationDirk Bolier - Anton Eli�ensVrije Universiteit, Department of Mathematics and Computer ScienceDe Boelelaan 1081, 1081 HV Amsterdam, The Netherlandsemail: [email protected] - [email protected] 9, 1994AbstractIn this report we give a full description of sim, a C++ library for discrete event simulation. Thesim library supports both an event and process-oriented approach to developing simulations. Eventsas well as entities (which may be considered as events with states signifying episodes in its life-time)are provided as abstract classes that must be re�ned by the application programmer to de�ne theactual events and entities participating in the simulation.The sim library is integrated with the hush library, thus o�ering powerful graphic and animationfacilities. However, the sim library may also be used independently, on both Unix and MS-Dosplatforms.This report presents an overview of the classes constituting the sim library (including the classesevent, entity, generator, resource, queue, histogram and analysis) as well as two standard examplesillustrating the deployment of the classes in writing simulation programs. Also, an example is givenof how to create a graphical animation of a particular simulation. The appendix contains, moreover,a more extensive example of a jobshop simulation illustrating how the analysis class may be used toobtain measurements of complex queing behavior.Keywords: discrete event simulation, events, entities, modeling, simulation experiments, simula-tion animation, simulation analysis

Page 2: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.
Page 3: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

Contents1 Introduction 12 The library SIM. 13 Program structure 23.1 The event scheduling strategy : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 23.2 Primitives and event states : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 33.3 The event-based approach : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 53.3.1 The Dining Philosophers : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 53.3.2 The event class : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 103.4 The process-oriented approach : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 113.4.1 The process philosopher : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 113.4.2 The entity class : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 133.5 The simulation class : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 143.6 The generator class : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 154 Queuing events 174.1 Queues and resources : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 174.2 A M/M/1 Queue : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 174.3 Queue behavior : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 204.4 The resource class : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 234.5 The queue class : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 245 Gathering and analyzing results 255.1 Gathering results with histograms : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 255.1.1 Histogram types, samples and reports : : : : : : : : : : : : : : : : : : : : : : : : : 265.1.2 Mean and variance : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 265.1.3 Printing a histogram : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 265.1.4 The histogram class : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 285.2 Realizing accuracy goals : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 295.2.1 Batch means and repetition : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 295.2.2 Antithetic variates : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 305.3 Analyzing the results : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 315.3.1 Con�dence intervals : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 315.3.2 Covariance and correlation : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 325.3.3 Fitting curves and distributions : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 335.3.4 The behavior of the simulation : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 345.3.5 The design of experiments : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 365.3.6 The analysis class : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 376 Creating a graphical interface 396.1 A graphical interface for the Dining Philosophers : : : : : : : : : : : : : : : : : : : : : : : 396.2 The screen class : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 427 Conclusions 43A Probability distributions 44

Page 4: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

B The generator and some tests 48B.1 The linear congruential generator : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 48B.2 Tests on the random number stream : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 48B.3 A test on the distributions : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 50B.4 A test on the event scheduling strategy : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 50C The analysis class 50D A case study of a job shop 52D.1 The problem : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 52D.2 The program : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 53D.3 The results : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 63

Page 5: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

1 IntroductionDiscrete Event Simulation A simulation is the execution of a model, represented by a computerprogram, that gives information about the system being investigated. The simulation approach of an-alyzing a model is opposed to the analytical approach, where the method of analyzing the system ispurely theoretical. As this approach is more reliable, the simulation approach gives more exibility andconvenience. The library sim adopts the method of the Discrete Event Simulation. With this approach,the components of the model consist of events, which are activated at certain points in time and in thisway a�ect the overall state of the system. The points in time that an event is activated are randomized,so no input from outside the system is required. Events exist autonomously and they are discrete sobetween the execution of two events nothing happens. The library sim provides an event-based, as wellas a process-oriented approach of writing a simulation program. With the process-oriented approach, thecomponents of the program consist of entities, which combine several related events into one process.Object Oriented Sim is written in the C++ programming language, which is presented in [Stroustrup91]. The library provides classes, that can be used by writing a C++ simulation program. We providedthe library with such a functionality, that the resulting language is similar to simula and simscript, whichare described in [Birtwhistle 73] and [Kiviat 69] respectively. The library certainly o�ers additionaladvantages. If you are interested in these before reading further, check the Conclusions section. Thelibrary is a C++ extension of the C simulation library, presented in [Watkins 93], in this way allowing foran Object Oriented approach towards Discrete Event Simulation. The extension consists of the classesanalysis and screen, the report methods, the reset methods, scheduling priorities, graphical features andadditional functionality for the other classes (more probability distributions for the class generator forexample).Hush The library can be compiled to both a pure ASCII version as well as a hush version (see [Eliens94] for a description of the hush library). Both ASCII and hush simulation programs run in the ASCIIas well as the hush version of the library. If you run the library in hush mode, you can use the built-ingraphical features as the printing of histogram and analysis objects. The implemented process can thenbe tested on correctness in no time by building a simple but powerful graphical screen. For a morecomplex interface (a graphical animation for example) the features explicit for the hush library can beused.2 The library SIM.The library consists of the following C++ classes :� simulation - the class simulation keeps the scheduler, that controls, which event should be activated.It employs a calendar of events and repeatedly extracts the event, that should execute. The functionoperator() of the event, that we will refer to as the application operator, is called when the event isactivated. A clock is kept, so it can be determined which event becomes the current. Furthermore,it maintains a conditional list where events can be put that could not execute but may execute inthe future.� event - events represent the dynamic objects in the system. They have a temporary existence andunique characteristics. An event in the simulation should be derived from the abstract class eventand be given functionality by overriding its application operator.� entity - an entity represents a process in the system, it combines several related events into oneprocess. As with the event class, the entity class is abstract. A process should be derived from itand be given functionality by overriding its application operator.1

Page 6: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

� generator - a collection functions that permits a variety of random number streams and probabilitydistributions for generating random numbers.� resource - a resource represents a passive object in the model, that is used by an event.� queue - a queue maintains the queued events, for example waiting for a resource to become free.� histogram - the class histogram makes it possible to gather and print samples in a exible andconvenient way. Histograms are printed both to standard output and on a window.� analysis - the class analysis makes it possible to analyze a histogram. Members for con�denceintervals, covariance and correlation, �tting curves and probability distributions and for analyzingthe behavior of the simulation are provided. The results of the analysis are printed both to standardoutput and on a window.� screen - the screen has built-in features as the clock, a start-stop button and a manner to adjustthe speed of the simulation. Furthermore it o�ers methods to ask for input variables and to addand move �gures on the screen.3 Program structureA typical simulation program, employing the sim library, creates a simulation object in main or appli-cation::main, together with the required resources and queues, that represent the static objects in thesystem and the required histogram and analysis objects for gathering and analyzing results. The dynamicobjects should be derived from the classes event or entity, and be given functionality by overriding theapplication operator of these classes. You should use application::main and create the simulation objectwith a pointer to the hush toolkit, if you want to run the library in hush mode. The application shouldthen be created and invoked in the main function. Before running the simulation, it should be set up byscheduling some events or entities depending on the type of simulation.3.1 The event scheduling strategyWhen a simulation is set up it runs after invoking the simulation::runmethod. The simulation then runsuntil the simulation::quit method is invoked, until there are no events left or for a speci�ed number oftime units or events. When using the latter approach the events should receive a kill ag when createdand be terminated when not used any more. As a remark the termination of a not used event is goodprogramming practice and should in each case be done to prevent the system from over ow.At the time an event is due to be activated, it is extracted from the scheduler and the main simulationroutine executes the code from the application operator of that event. The library adopts the algorithmthat is outlined in the next �gure as its event scheduling strategy.2

Page 7: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

add initial events?-any events ?? noyesselect next events?advance clock?execute events?can any conditional events run ?? noyesexecute conditional events?�running ??�yes noprint results�g 3.1. The event scheduling strategy of sim.Notice, that the algorithm extracts all events with the same activation time. The main simulation routineactivates them in priority order with the highest scheduling priority �rst. Before executing the events,the simulation clock is updated to the activation time of the current events. Furthermore, the conditionallist is traversed in priority order with highest scheduling priority �rst. Events, that can run now, areexecuted.After the running of the simulation some statistics of the starting and end time, of the number ofcreated, activated and terminated events and of the actual time taken are given.3.2 Primitives and event statesWhen an event is activated it can be manipulated in various ways. The event can be appended to aqueue, it can be put back in the scheduler and so on. On its way it changes state. We identify thefollowing states an event can be in :� passive - indicating that the event is currently not available for any processing.3

Page 8: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

� active - indicating that this is the event currently being processed.� queued - the event is in a queue.� pending - the event is in the scheduler.� conditional - indicating the event is on the conditional list.� closed - the event is on the conditional list but unavailable.�g 3.2. States of an event.The diverse primitives that manipulate the event and cause the change of state are then :� passivate - which takes an event out of the simulation but doesn't destroy the event.� hold - which takes a passive event and adds it to the conditional list. This event then executes aftereach activated event.� schedule - which takes a passive event and adds it to the scheduler. This event then executes aftera speci�ed period.� wait - which puts the event currently executing on the scheduler.� activate - which takes a passive, pending or conditional event and schedules it to become active atthe current simulation time. A typical use is to bring forward the activation of an event at presenttime.� terminate - which terminates an active or passive event.� append, prepend - which add passive and active events to a queue.� extract, removefront, removeback - these functions obtain events from the queue.� withdraw, reinstate - which respectively prevent a conditional event from executing by changing itsstate to closed and put a closed event back in its conditional state.�g 3.3. Primitives.As you may have noticed the invoking of a primitive has not always e�ect. The event should be inthe correct state �rst. The invoking of the hold primitive for example assumes a passive event. This statecan be obtained by �rst passivating the event.Consider the following transition diagram that shows the di�erent states an event can be in, inrelationship with the di�erent functions, that manipulate them. The central state of an event is thepassive state. Most events should �rst be passivated before they continue. Notice that an event alsochanges state if it is pending and is due to execute. This event (the �rst event in the scheduler) is extractedfrom the scheduler and becomes active. An event that is on the conditional list stays conditional whileexecuting until it is explicitly passivated.4

Page 9: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

&%'$pending&%'$passive &%'$queued&%'$active&%'$condi-tional&%'$closed@@@R��� XXXXXXXXXXXXzXXXXXXXXXXy -���������������������:���������������������9�����������*������������ ��������� ���������

����AAAAAAUXXXXXXXz-�eventterminate schedulepassivate remove/extractappend/prependwaitactivateactivatepassivatepassivatehold activatereinstatewithdraw terminate

append/prepend�g 3.4. The event state-transition diagramEntities An entity (that combines several related events) has the same states and primitives as anevent. The di�erence is in the use of an additional phase, as is explained in section 3.4.3.3 The event-based approachWith the event-based approach of writing a simulation program we �rst identify the events in the model.The behavior of an event is implemented by deriving it from the class event and overriding the applicationoperator of this class. Consider the next problem3.3.1 The Dining PhilosophersThe problem is as follows. Five philosophers sit around a table with �ve chopsticks in between. Theythink and if they're hungry and if two chopsticks are available, they eat. If a philosopher gets hungry ands/he can't acquire a chopstick, the philosopher waits until s/he can. The philosopher doesn't think, ifs/he is waiting or eating. We're interested in the fraction of the time, that a philosopher actually thinks.To model this problem, three events can be identi�ed, eat, think and await. The corresponding classesare derived from the class event. Furthermore we need a chopstick for every philosopher. These arerepresented as a resource. The thinking times are gathered in an instance of the class histogram and thegenerator takes care of the variations in the time needed to think and eat.We develop this program in the following steps. First, the library is included as sim.h. The declarationsof the global variables and constants follow after that. The time unit in this simulation is an hour, so aphilosopher has a mean eating time of two hours and a mean thinking time of �ve hours. The durationof the simulation is a year. Finally, we de�ne the various events.#include <sim.h>enum {NUMBER=5,EAT_TIME=2,THINK_TIME=5};5

Page 10: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

simulation* sim;resource* chopstick[NUMBER];histogram* thinking;generator* g;const double duration = 52*7*24.0; // a yearclass eat : public event{private :int id; // identity of the philosopherpublic :eat(int i); // constructor, taking identityvirtual int operator()(); // application operator};class think : public event{private :int id; // identity of the philosopherpublic :think(int i); // constructor, taking identityvirtual int operator()(); // application operator};class await : public event{private :int id; // identity of the philosopherpublic :await(int i); // constructor, taking identityvirtual int operator()(); // application operator}; �g 3.5. The de�nitions of the philosopher programNext, we implement the various events. An event is given its functionality by deriving it from the classevent and overriding its application operator.The logic of the eat event is that the philosopher eats for a random time, exponentially distributedwith the eating time as mean. So, we �rst determine the actual eating time and schedule a think eventto be activated after this eating time. The eat event can be terminated.eat::eat(int i) : event(){ id = i; } // set identityint eat::operator()(){ double t;think* th; 6

Page 11: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

t = g -> exponential(EAT_TIME); // determine eating timeth = new think(id); // create a thinking eventsim -> schedule(th,t); // schedule thinkingsim -> terminate(this); // terminate this eat eventreturn OK;} �g 3.6. The eat eventIf a philosopher starts to think, the philosopher �rst releases both chopsticks. The thinking time isdetermined and a sample is made of this thinking time. An await event is scheduled and the think eventis terminated.think::think(int i) : event(){ id = i; } // set identityint think::operator()(){ double t;await* aw;chopstick[id] -> release(); // release left chopstickchopstick[(id+1)%NUMBER] -> release(); // release rightt = g -> exponential(THINK_TIME); // determine thinking timethinking -> sample(id,t/duration*100); // add a sample (%)aw = new await(id); // create await eventsim -> schedule(aw,t); // schedule waitingsim -> terminate(this); // terminate thinkingreturn OK;} �g 3.7. The think eventThe await event acquires the left and right chopstick and schedules an eat event immediately, if bothchopsticks are available. The await event is passivated as it could be on the conditional list. If nochopsticks are available, the await event stays on the conditional list or, if it was not conditional as is thecase the �rst time it is activated, it is added to the conditional list.await::await(int i) : event(){ id = i; } // set identityint await::operator()(){ eat* e;if ( (chopstick[id] -> available()) && // available ?chopstick[(id+1)%NUMBER] -> available()) )7

Page 12: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

{ chopstick[id] -> acquire(); // acquire leftchopstick[(id+1)%NUMBER] -> acquire(); // acquire righte = new eat(id);sim -> passivate(this); // extract from conditional listsim -> schedule(e,0); // schedule eat event immediatelysim -> terminate(this); // terminate await event}else if (!conditional()) // not on conditional list{ sim -> passivate(this); // make passivesim -> hold(this); // add to conditional list}return OK;} �g 3.8. The await eventIf the library runs in ASCII mode all that needs to be done is to de�ne the main function. This functiontakes care of setting up and running the simulation.main(){ int i;await* aw;sim = new simulation(); // create simulation objectg = new generator(1); // create generatorthinking = new histogram(1,1,NUMBER,FREQUENCY,GRAPH,"THINKING TIME (%)"); // frequency graphfor (i=0;i<NUMBER;i++){ chopstick[i] = new resource(1); // create chopsticksaw = new await(i); // schedule eachsim -> schedule(aw,0); // philosopher to be waiting}sim -> run(duration); // run for duration time unitscout << (*thinking) << endl; // print resulting histogramdelete thinking;delete sim;} �g 3.9. The main functionThe main function �rst creates the simulation object. Furthermore, a generator, a frequency histogramand �ve resources that represent the chopsticks are created. The simulation starts with all philosophers8

Page 13: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

waiting and runs for a year (52*7*24 hours). After running the simulation, the resulting histogram isprinted to standard output.If the library sim runs in hush mode the application::main routine takes care of setting up andrunning the simulation. It overrides the abstract session::main function from the hush library that iscalled before starting the hush-event loop. Consider the following de�nition and implementation of theapplication class, that is derived from session.class application : public session{public :application(int argc,char** argv);virtual void main(kit* tk,int argc,char** argv);};application::application(int argc,char** argv) : session(argc,argv,"philosophers"){}void application::main(kit* tk,int argc,char** argv){ int i;await* aw;sim = new simulation(tk); // create simulation object with the toolkitg = new generator(1); // create generatorthinking = new histogram(1,1,NUMBER,FREQUENCY,GRAPH,"THINKING TIME (%)"); // frequency graphfor (i=0;i<NUMBER;i++){ chopstick[i] = new resource(1); // create chopsticksaw = new await(i); // schedule eachsim -> schedule(aw,0); // philosopher waiting}sim -> run(duration); // run for duration time unitscout << (*thinking) << endl; // print resulting histogramdelete thinking;delete sim;} �g 3.10. The applicationThe only di�erence between the main of �gure 3.9. and the application::main of �gure 3.10. is theparameter of the constructor. If this method receives the pointer to the hush toolkit the library runs inhush mode. If these method does not receive anything (or the default NULL pointer) the library runsin ASCII mode, as is the case in the �rst implementation of of the main function. Additionally, for therunning in hush mode, the creation and invocation of the session object in the main function is required.main(int argc,char** argv) 9

Page 14: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

{ session* s;s = new application(argc,argv); // create the sessions -> run(); // start the sessionexit(0);} �g 3.11. The main functionSession is used to start up the hush toolkit. Its use is illustrated in the philosopher program. You shouldderive an application from the session, give it a name and override its session::main function. In mainall you do is create and start the session. For a more detailed description of the session class, which isnecessary if you are not satis�ed with the graphical features of the sim library, see [Eliens 94]. The sessionclass is also de�ned in the ASCII version of the library. Its functionality is zero, but hush programs canbe linked to the ASCII library in this way.3.3.2 The event classThe interface of the event class :interface event{protected :event(int qp=0,int sp=0,int kf = FALSE); // queuing and scheduling// priority and kill flag as argumentspublic :virtual ~event(); // destructor.virtual int operator()() = 0; // emptyvirtual int verify(); // returns OKint report(histogram* h,double interval = 0); // create reportvoid stamp(); // add time stampdouble timespent(); // time since the stampint queuingpriority(); // return queuing priorityint schedulingpriority(); // return scheduling priorityvoid queuingpriority(int p); // adjust queuing priorityvoid schedulingpriority(int p); // adjust scheduling priorityint active(); // is active ?int pending(); // is pending ?int conditional(); // is conditional ?int closed(); // is closed ?10

Page 15: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

int passive(); // is passive ?int queued(); // is queued ?}; �g 3.12. The interface of the class eventThe constructor gets the priorities (default 0) and the kill ag of the event. The kill ag should beset when the simulation is ran for count terminated events. The application operator is invoked when theevent is activated. This function is purely virtual. It must be implemented in a subtype, that is derivedfrom event. The method verify is also virtual, it returns OK and should be overwritten (and returnFALSE) if this event should be terminated when the simulation::cancel or the queue::cancel methodsare invoked. The method report �lls a FREQUENCY histogram with samples of the lifetime of everyinstance of the event. The histogram is printed to standard output and on a window (if the library runsin hush mode) each interval time units and at the end of the simulation. If interval is equal to 0, as inthe default case, the histogram is only printed, at the end of the simulation. Successive prints are onthe same window. When it is used, the method should be invoked for every instance of the reportedtype, when �rst activated and the instance of the reported type should be explicitly terminated, whennot used anymore. The function stamp adds a time stamp of the current simulation time to the event.The function timespent returns the time since the event received a time stamp with the stamp method.These two methods can be used to create samples of, for example, service times of an event. The priorityfunctions return or adjust the scheduling or queuing priority of the event. The scheduling priority isused to order the activation of events with a same activation time. The event with the highest priorityis activated �rst. The queuing priority is used to model priority queues. The event with the highestqueuing priority goes to the front of the queue. The other functions return a boolean, according to thestate of the event.As a remark, the notion of a simulation event and the notion of a hush-event (for example the clickingon a button) are integrated, if the library runs in hush mode. You can use the event class both as a simevent and as a hush event. The hush event is described in [Eliens 94].3.4 The process-oriented approachWith the process-oriented approach the components of the model consist of entities, which represent theexistence of some object in the system such as a philosopher. An entity receives a phase that determinesthe behavior of the entity.We �rst identify the processes (or the types) in the model. The events are represented as methods ofa process. The application operator calls these events at the hand of the phase the process is in.3.4.1 The process philosopherConsider the following de�nition and implementation of the process philosopherenum {EATING,THINKING,WAITING} // phases of a philosopherclass philosopher : public entity{private :int id;public : 11

Page 16: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

philosopher(int ph,int i); // constructor, taking phase and idvirtual int operator()(); // application operatorint eat(); // eat eventint think(); // think eventint await(); // await event};philosopher::philosopher(int ph,int i) : entity(ph){ id = i; // set phase and identity}int philosopher::operator()(){ switch (phase()) // what phase is the philosopher in ?{case EATING :return eat(); // the philosopher eatscase THINKING :return think(); // the philosopher thinkscase WAITING :return await(); // the philosopher waits}return FALSE;}int philosopher::eat(){ double t;t = g -> exponential(EAT_TIME); // determine thinking timephase(THINKING); // set phase to thinkingsim -> wait(t); // schedule this philosopher thinkingreturn OK;}int philosopher::think(){ double t;chopstick[id] -> release(); // release left chopstickchopstick[(id+1)%NUMBER] -> release(); // release rightt = g -> exponential(THINK_TIME); // determine thinking timethinking -> sample(id,t/duration*100); // sample (%)phase(WAITING); // set phase on waitingsim -> wait(t); // schedule this philosopher waitingreturn OK;} 12

Page 17: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

int philosopher::await(){ if ( (chopstick[id] -> available()) && // available ?chopstick[(id+1)%NUMBER] -> available()) ){ chopstick[id] -> acquire(); // acquire left chopstickchopstick[(id+1)%NUMBER] -> acquire(); // acquire rightsim -> passivate(this); // make passivephase(EATING); // set phase on eatingsim -> activate(this); // activate as eating}else if (!conditional()){ sim -> passivate(this); // make passivesim -> hold(this); // add to conditional}return OK;} �g 3.13. The implementation of the philosopher processDependent on the phase the philosopher is in, the appropriate action on the simulation environment istaken. These actions closely resemble the events, described in the event-based approach of this problem.The main di�erence is in the use of phase. If, for example, a philosopher �nishes eating, his/her phaseis set to THINKING and s/he is scheduled after t time units, whereas in the event-based approach athink event is scheduled and the eat event is explicitly terminated. So, in the process-oriented solution aphilosopher exists for the entire simulation. In the main or session::main function the simulation is setup by scheduling the �ve philosophers, initially waiting, instead of scheduling �ve await events.3.4.2 The entity classThe interface of the entity class. It is derived from event and adds the phase of the process to event.interface entity : public event{protected :entity(int ph=0,int qp=0,int sp=0,int kf = FALSE); // constructorpublic :virtual ~entity(); // destructorint phase(); // return phasevoid phase(int p); // adjust phase}; �g 3.14. The interface of the entity class13

Page 18: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

The constructor takes the phase, queuing priority and scheduling priority and the kill ag of the entity(default 0), The function phase adjust or returns this phase. Furthermore, the class entity inherits everyfunction of the class event, so these functions can also be invoked for an entity.3.5 The simulation classThe primitives and methods for running and ending the simulation are provided by the simulation class.If the simulation object receives a pointer to the Tcl/Tk toolkit the sim library runs in hush mode,otherwise it runs in ASCII mode. The class simulation has the following interface :interface simulation{ simulation(kit* tk = NULL); // constructor, taking the toolkitvirtual ~simulation(); // destructorvoid run(); // run until no events leftvoid run(double t); // run for t time unitsvoid run(int count); // run for count terminated eventsvoid quit(); // quit simulationvoid terminate(event* e); // terminate evoid scan(); // scan conditional always ?int schedule(event* e,double t); // schedule e at tint wait(double t); // schedule currentint passivate(event* e); // passivate eint activate(event* e); // activate eint hold(event* e); // add e to conditionalint withdraw(event* e); // put e on closedint reinstate(event* e); // put e on conditionalint cancel(); // cancel eventsvoid reset(); // reset the simulationdouble clock(); // return clockvoid postscript(char* fn); // generate postscriptfriend ostream& operator<<(ostream& os,simulation& s);}; �g 3.15. The interface of the class simulationIf the constructor receives the pointer to the hush toolkit the library runs in hush mode. The method runis used to run the simulation for t time units, for count terminated events or until no scheduled events14

Page 19: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

are left. In the Dining Philosopher Problem, we used the method taking a double, as the simulationshould run for 52*7*24 time units. A simulation can also be run for count events, the simulation thenstops, if count events are terminated, that had set their kill- ag set to OK when created. If run is done,it prints statistics of how the simulation stopped, of the number of events that were created, activatedand terminated and of the actual time (in seconds) that the simulation ran. These results are printed tostandard output and, if hush is enabled on a window (the same window for each run). The simulation canalso be stopped by calling quit. With the function terminate, an event is terminated and removed fromthe simulation. It calls the virtual destructor of the class event, that can be overwritten by the derivedevent. If the kill- ag of the terminated event is set to OK, the simulation stops if this is the countth eventthat is terminated in this way. The count should have been set in the run method. If the function scan isused, the list with the conditional events is traversed, even between events with the same activation time.If schedule is used, the event e is put on the pending list and is executed after t time units. In the caseof the dining philosophers for example, if an eat event is the current, a think event is scheduled after thephilosopher �nishes eating. If wait is used, the event that currently executes is put on the pending list andis executed after t time units. The method passivate extracts an event from the pending or conditionallist and makes it passive. For example, an await event is passivated, if both chopsticks become available.The function activate removes an event from the pending and conditional list and schedules it to becomeactive at the current time. The method hold adds an event to the conditional list. For example, an awaitevent is made conditional, if no chopsticks are available. The method withdraw prevents a conditionalevent from being scanned by changing its state to closed. The method reinstate allows a conditionalevent to be scanned again. The method cancel removes and deletes every event from the scheduler andconditional list that receives FALSE from its event::verify method. These methods can be used to modelthe breakdown of a server for example, departure events should be canceled then. The simulation can bereset as nothing had happened to it by using the method reset. Reset clears the scheduler and conditionallist, resets the clock to 0 and resets the reports and screen (if set) to their original state. If you want torun the simulation without reports this time, you can delete the simulation object and create a new one.As with the terminate method, the cancel and reset functions stop the simulation if count is speci�edand the countth event has been terminated. The function clock returns the current simulation time. Thefunction postscript writes the window of the simulation object (if created) in postscript format to thespeci�ed �le. The operator<< function writes the pending tree and conditional list to standard output.This function can be used for the debugging of a simulation program.3.6 The generator classThe class generator represents the random number generator. The generator is used to get the randomizedactivation times of the various events. It gets a seed and creates a random number stream, according tothe method described in appendix B.Each time a member of the generator is invoked to get a random number, the next number fromthe stream is calculated and is transformed, according to the probability distribution belonging to thatmember. This number is returned and can be used in the simulation. If, for example, a normal distributionwith 10 as mean and 1 as standard deviation is speci�ed to transform the random number stream, thegenerated numbers have 10 as mean and show little variation because of the low standard deviation.Refer to appendix A for a description of the various probability distributions that the library uses.The class generator has the following interface :interface generator{public :generator(unsigned int seed); // constructor15

Page 20: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

void antithetic(); // use 1-random()void reset(); // reset random number streamint probability(double p = 0.5); // OK with prob. pdouble uniform(double a,double b);double exponential(double a);double hyperexponential(double p,double a,double b);double laplace(double a);double normal(double a,double b);double chisquare(unsigned int n);double student(unsigned int n);double lognormal(double a,double b);double erlang(unsigned int n,double a);double gamma(double a,double b);double beta(double a,double b);double fdistribution(unsigned int n,unsigned int m);double poisson(double a);double geometric(double p);double hypergeometric(unsigned int m,unsigned int n,double p);double weibull(double a,double b);double binomial(double p,unsigned int n);double negativebinomial(double p,unsigned int n);double triangular(double a);protected :double random(); // produces a random number between 0 and 1}; �g 3.16. The interface of the generator class.A generator, with given seed, produces the same random number stream every time, it is created withthat seed. One should uctuate seeds to get reliable random numbers.If the method antithetic is invoked, the inverse of the current stream is used, i.e. instead of thegenerated random number, say x, 1-x is used. This method can be used when the variance of the samplesmade is too high (see section 5.2).The function reset resets the random number stream, as if no random number was generated from thisstream. The member probability returns OK with probability p and FALSE with probability 1-p. Thedistribution functions all return a random number from the stream, following the belonging probabilitydistribution. The method random produces a new variate (between 0 and 1) from the random numberstream. It is made protected so a derived generator can use this stream and add new distributions to theexisting ones.16

Page 21: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

4 Queuing eventsThe notion of a queue as a waiting line of a service facility is familiar to most of us. Queues occurwherever an imbalance occurs between requests for a limited resource and the ability of a service facilityto provide that resource. The size of the queue depends on the amount of the resource available andthe demand for it by customers. You can think of queuing applications, that make a trade-o� betweenthe cost of providing more of a resource and the cost of allowing larger queues to form. In the followingsections we look at some typical queue types and queue behavior. Furthermore we describe the interfacesof the classes resource and queue at the hand of a standard queuing example.4.1 Queues and resourcesTo model the above we �rst need a resource and a queue. As customers arrive and depart, after beingserved we need at least three events (or an entity for both the customer and server). These types arein fact general for every queuing application. The di�erence then comes from the arrival and servicepattern, from the service policy, from the resource amount and from the queuing priority of every event.These can be modeled as follows :� arrival and service pattern - In the arrival event a next arrival is scheduled after the appropriatetime. The service event schedules a departure event after the service time.� service policy - When an arrival occurs it is served according to the service policy. The mostcommon ones are the LIFO (last in �rst out) and FIFO (�rst in �rst out) queues. The �rst one canbe modeled by adding an arrival to the front of the queue with the queue::prepend method, the lastone is modeled by adding the arrival event to the back with the queue::append method. In bothcases we then take the front of the queue with the queue::removefront method. Additional servicepolicies can easily be modeled as variations of the ones above.� resource amount - The number of arrivals that can be served depends on the resource amount. Whena resource is created it receives its initial amount. This amount is then increased and decreasedevery time a certain amount is released or acquired, with the resource::release and resource::acquiremethods. A resource can be released in the departure event (after being served) and can be acquiredin the service event if the asked amount is available, which can be checked with the resource::availablemethod.� queuing priority - A priority queue can be modeled by giving a queuing priority to an event, whencreated. When appended or prepended an event that has a higher priority goes in front of an eventwith a lower priority.4.2 A M/M/1 QueueA M/M/1 queue has an exponential interarrival and service time and a single server. We are interestedin the statistics of the size of the queue and the waiting times of a customer, with varying means for theinterarrival times and service times. Consider the following process-oriented simulation program.We �rst include the library and de�ne the phases for a customer. The simulation object, the resource,the generators, the queue and the means for the arrival and service times, as well as the customer andserver entities are declared.#include <sim.h>enum {ARRIVAL,DEPARTURE}; 17

Page 22: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

simulation* sim;resource* r;queue* q;generator* g1, *g2; // for inter-arrival and service timesdouble meanarrival,meanservice; // mean arrival and service timeclass customer : public entity{public :customer(int ph);virtual int operator()();int arrival();int departure();};class server : public entity{public :server();virtual int operator()();}; �g 4.1. The de�nitions of the M/M/1 queueA customer arrives or departs, so it receives a phase, when created. The behavior of the processcustomer is implemented in its application operator. When a customer arrives, �rst a new customeris scheduled to arrive. We take the inter-arrival time to be exponential, with meanarrival as the meanarrival time. Then the customer is appended to the queue. When the customer is served the resource isacquired by the server, a departing customer then releases the resource and is terminated. The defaultamount of 1 is released and acquired each time.customer::customer(int ph) : entity(ph){}int customer::operator()(){ switch (phase()){ case ARRIVAL :return arrival();case DEPARTURE :return departure();return FALSE;}int customer::arrival() 18

Page 23: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

{ customer* c;c = new customer(ARRIVAL); // schedule new customersim -> schedule(c,(g1 -> exponential(meanarrival)));q -> append(this); // append to the queuereturn OK;}int customer::departure(){ r -> release(); // release the resourcesim -> terminate(this); // terminate this customerreturn OK;} �g 4.2. The customer entityThe behavior of the process server does not depend on a phase. Every time it is activated, it takesa customer from the queue if possible, i.e. if the queue is not empty and if the required amount of theresource (in this case the default amount of 1) is available. If it takes a customer, it acquires the resource,adjusts the phase of the customer to DEPARTURE and schedules the customer to depart, after it hasbeen served.server::server() : entity(){}int server::operator()(){ customer* c;// can we serve a customer ?if ( (!(q -> empty())) && (r -> available()) ){ c = (customer *)q -> removefront(); // take firstr -> acquire(); // acquire the resourcec -> phase(DEPARTURE); // adjust phase and schedule departingsim -> schedule(c,g2 -> exponential(meanservice));}return OK;} �g 4.3. The server entityThe function main creates the simulation object and two di�erent generators, that are used forcalculating the inter arrival time of the customers and the service time. Furthermore, it creates the queueand two histograms, that are used for generating reports on the size of the queue and the waiting times19

Page 24: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

of a customer. A resource with an initial amount of 1 is created. The simulation is set up by schedulinga customer to arrive immediately and making the server conditional. The server is never passivated, soit stays on the conditional list for the entire simulation and is activated, whenever a customer is.main(int argc,char** argv){ customer* c;server* s;histogram* h1,*h2;// create objects and reportsif (argc == 3){ meanarrival = atof(argv[1]);meanservice = atof(argv[2]);}elseexit(0);sim = new simulation();g1 = new generator(8120);g2 = new generator(434);h1 = new histogram(0,1,10,WEIGHTED,GRAPH,"QUEUE SIZE");h2 = new histogram(0,1,10,FREQUENCY,GRAPH,"WAITING TIMES");q = new queue();q -> reportsize(h1); // generate a report on the size of the queueq -> reportwaiting(h2); // generate a report on waiting timesr = new resource(1);// set up and run the simulationc = new customer(ARRIVAL);sim -> schedule(c,0.0); // initially a customer arrivess = new server();sim -> hold(s); // the server is conditionalsim -> run(10000.0);delete h1;delete h2;delete q;delete sim;} �g 4.4. The main function4.3 Queue behaviorIn this section we look at some examples of how more complex scenarios involving queues can be modeled.20

Page 25: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

Queue swapping This behavior occurs when a member of the queue leaves in preference for an al-ternative queue. We can model the swapping of an event e between the queues q1 and q2 as follows: if (condition){ q1 -> extract(e); // from every positionq2 -> append(e); // append to second queue} �g 4.5. Swappingwhere condition could be something as the checking of the sizes of the two queues.Balking If a queue is too long it usually deters further additions. This phenomenon is called balkingand its implementation is straightforward :if (q -> size() < MAX)q -> append(e); // append if possible�g 4.6. BalkingThe event is appended when there is room for it.Reneging Reneging is the premature departure of a customer from a queue before it has had anyservice. This is typically the case when its waiting time exceeded some upper limit. We could model thisby checking the entire queue with the queue::cancel method, but more e�cient is the following additionto the arrival event :e -> stamp(); // add a time stampq -> append(e); // appendand the checking of the waiting time in the service event.if (q -> front() -> timespent() > MAX) // if waited too longq -> terminatefront(); // destroy the front�g 4.7. RenegingThe queue::front method only returns the front of the queue and does not remove it. If the waiting timeof the front exceeded the limit, the event is removed and terminated. The queue::terminatefront thenmakes no sample of the waiting time, even if the event had a report on waiting times.21

Page 26: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

Service pre-emption Pre-emption occurs when a customer being served is interrupted by the server infavour of a new customer that has a higher priority. The interrupted customer can then wait to completeits service, wait to be served again or simply leave the system. The interrupting arrival then takes theplace of the interrupted event. Consider the following behavior of the server entity of the M/M/1 queue.Events should then receive a queuing priority when created and the event currently being served shouldbe set to NULL when terminated.int server::operator()(){ if (!(q -> empty())) // if an event waitingif (!current) // if nothing being servedreturn serve() // just serveelse if (q -> front -> queuingpriority() > current -> queuingpriority())return preempt(); // front has a higher priority}int server::serve(){ c = (customer* )q -> removefront();r -> acquire();c -> phase(DEPARTURE);current = c; // record as currentsim -> schedule(c,g2 -> exponential(meanservice));return OK;}int server::preempt(){ sim -> terminate(current); // terminate the currentc = (customer* )q -> removefront();r -> acquire();c -> phase(DEPARTURE);current = c; // record as currentsim -> schedule(c,g2 -> exponential(meanservice));return OK;} �g 4.8. Pre-emptionIf the front can be served we look if there is currently a customer being served (the current variable isset to NULL in the departure event). If so the front is served only if its queuing priority is higher. Thefront is then recorded as the current. A more complex scenario where we record the service time left andappend the interrupted entity once again is given in the case study of appendix D.Time dependencies The arrival and service rates have been considered constant so far. This is notalways realistic. The arrival rate at a supermarket shows a noticeable peak around evening for example.We can easily model this by constructing an arrivaltime function as follows :22

Page 27: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

double arrivaltime(){ if (sim -> clock() < TIME1) // use the appropriate meanreturn (g -> exponential(MEAN1)); // at the hand of the currentelse if (sim -> clock() < TIME2) // simulation timereturn (g -> exponential(MEAN2));else if (sim -> clock() < TIME3)return (g -> exponential(MEAN3));..} �g 4.9. Time dependenciesand we have di�erent arrival rates at di�erent times, if this function is used when a new arrival isscheduled.4.4 The resource classA resource represents the static objects in the simulation, that events or entities can use. The classresource has the following interface :interface resource{ resource(double a); // constructorint report(histogram* h,double interval = 0); // generate reportvoid reset(); // reset amount left to initialvoid release(double a = 1); // release amount left by avoid acquire(double a = 1); // acquire a from amount leftint available(double a = 1); // is an amount a available ?int full(); // is full ?int empty(); // is empty ?double left(); // how much left ?double used(); // how much used ?double occupied(); // returns occupation (%).friend ostream& operator<<(ostream& os,resource& r);}; �g 4.10. The interface of the class resourceA resource maintains the initial and current amount. These amounts are set to a, when created. Whenreport is used, the given histogram is �lled with samples of the occupation of the resource. Samples are23

Page 28: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

taken each time release or acquire is invoked. The histogram should be of type WEIGHTED and isprinted to standard output and on its window (if the library runs in hush mode) each interval time unitsor if interval is equal to 0 (default), it is printed only when the simulation stops. Successive prints are onthe same window. The function reset can be used to reset the current amount to the initial. With themethod release an amount a of the resource is set free. For example, a departing customer releases theresource for the default amount 1. With acquire an amount a is claimed. Before acquiring this amount,available should be used to check if this is legal. The server does accordingly, if it is trying to serve acustomer. The method full returns OK if the resource is full and FALSE otherwise. The function emptyreturns OK if the resource is empty. The method left returns the amount left that can be acquired.The method used returns the amount that already has been acquired. The function occupied returnsthe occupation of the resource in percents. The resource can be printed to standard output with theoverloaded operator<< function. The initial and current amount and the occupation are printed then.This function can be used for the debugging of a simulation program.4.5 The queue classThe class queue has the following interface :interface queue{ queue(); // constructorvirtual ~queue(); // destructorvoid reset(); // reset queueint reportsize(histogram* h,double interval = 0);int reportwaiting(histogram* h,double interval = 0,int qp = 0);int prepend(event* e); // add to frontint append(event* e); // add to backevent* removefront(); // remove frontevent* front(); // return frontevent* removeback(); // remove backevent* back(); // return backint extract(event* e); // extract eint terminatefront(); // terminate frontint terminateback(); // terminate backint cancel(); // cancel specified eventsint size(); // return sizeint empty(); // is empty ?friend ostream& operator<<(ostream& os,queue& q);}; 24

Page 29: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

�g 4.11. The interface of the class queueThe class queue maintains the queued events in priority order with highest queuing priority at thefront of the queue. Furthermore, it maintains the size of the queue. The function reset resets the queueas if no events were queued. The function reportsize �lls the given histogram with samples of the size ofthe queue. The samples are taken, each time an event or entity is appended to, prepended to, removedfrom or extracted from the queue. The histogram is printed at the end of the simulation or, if interval isnot equal to 0, each interval time units. It should be of type WEIGHTED. The method reportwaiting �llsthe histogram with samples of the waiting times of the events that have as queuing priority qp. Each timean event is appended or prepended, it gets a time-stamp. When it is removed or extracted, a sample ismade of the time it has been in the queue. The histogram should be of type FREQUENCY. The methodprepend adds an event to the front of the queue, append adds it to the back of the queue. If the eventsor entities received a queuing priority, they are added in priority order, with higher priority �rst. Themethod removefront removes the front of the queue and returns this event, removeback removes the backand returns this event. The methods back and front only return the back and the front of the queue. Theextract function extracts an event from the queue, if that event is in the queue. The terminate functionsterminate the front or back of the queue. The cancel method removes and terminates every event fromthe queue that returns FALSE from its event::verify method. Even if the queue has a report no sample ismade of the waiting time of the terminated event or of the size of the queue if these functions are invoked.If the kill- ag of the terminated events is set to OK, the simulation stops if this is the countth event thatis terminated in this way. Count should have been set in the simulation::run method then. The cancelmethod can be used to model, for example, the canceling of events that waited too long. The functionsize returns the size of the queue and empty returns OK, if the queue is empty, FALSE otherwise. Theoperator<< function is overloaded for queue, so when used the tree-structure and size of the queue areprinted to standard output. This function can be used for the debugging of a simulation program.5 Gathering and analyzing resultsIn this section we present the histogram and analysis class from the sim library. These classes can be usedto gather and analyze the results of a simulation. Results can be gathered by taking explicit sampleswith the method sample, as is the case in the example of the dining philosophers, or by using the reportmembers, as is the case in the example of the M/M/1 queue.Accuracy can be realized by having long runs. The increase in the number of samples made obviouslygives more accurate results. We can then reduce the variance of the results by splitting a long run in shortsubruns or by having several independent runs and take the means of the means of each run. Anothermethod of reducing the variance is by introducing antithetic variates.The class analysismakes it possible to analyze a histogram. It provides members for taking con�denceintervals, for determining the covariance and correlation of two variables, for analyzing the behavior ofthe simulation and for �tting curves and probability distributions.5.1 Gathering results with histogramsThe library sim uses the histogram as a means to gather data. When a sample is made the value of thesample is added to the sum of values and the frequency to the sum of frequencies to calculate the meanand variance of the data. The frequency of the sample is then recorded in the column the value of thesample falls in. The histogram and its statistics can be printed both in ASCII format and on a window(if the library runs in hush mode). Successive prints are on the same window then.25

Page 30: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

5.1.1 Histogram types, samples and reportsA histogram takes six parameters, when created, so it can be used in a very exible way. It takes thestart value, the width of a column, the number of columns, the type of the histogram, the type of theoutput and the title.Three di�erent types are speci�ed for a histogram. The type FREQUENCY is used for the distributionof the frequency data of a variable. The type WEIGHTED also takes the length of the simulated time,that the variable persisted, in account. Finally, the type SERIES is used to create time series histograms,that are used to show the uctuation of a variable over time.Data are recorded in a histogram, when using the method sample. This method takes the value ofthe sample and its frequency, say x and y and adjusts the internal histogram data. If the type of thehistogram is equal to FREQUENCY, the y value is added to the sum of frequencies of the column, thatx falls in. If the type of the histogram is equal to WEIGHTED, the y value is multiplied by the timesince the last sample was taken. In a time series histogram, the x-axis represents time, so the x valueis ignored and the y value is added to the columns between the last column in which a sample was putand the column that represents the current simulation time. In the case of the dining philosophers, forexample, a histogram of type FREQUENCY su�ces. If we were interested in weighted averages, as isthe case in analyzing queue sizes, the histogram should be of type WEIGHTED.The report methods use the sample function. If you use these methods the library adds the samplesfor you. The method �le writes every sample made in the histogram to the speci�ed �le (the x value onthe �rst new line and the y value on the second one).5.1.2 Mean and varianceThe histogram class also provides methods for calculating three important statistical measures that areused extensively, the mean, variance and standard deviation. The mean gives a measure of the averagevalue of a set of samples. It is de�ned as : x = Pni=1 xipiPni=1 piwhere n is the number of observations made, xi is the value of the ith observation and pi is the numberof occurrences of the ith observation (the y value as described in the preceding section).The variance gives a measure of the spread of a set of samples, it is de�ned as :s2 = Pni=1(xi�x)2piPni=1 piThe standard deviation is the square root of the variance. It is useful because it transforms the varianceto a dimension which is comparable to the original set of samples.5.1.3 Printing a histogramThe mean, variance and standard deviation are also given, if the histogram is printed. Furthermore thesum of frequencies and the maximal and minimal values are given. The set of samples can be printed asa frequency graph, a cumulative frequency graph or a table. Furthermore only the statistics or the barsof the histogram can be speci�ed. The histogram is printed to standard output as well as on a window(if the library runs in hush mode). Successive prints are on the same window then.The following histograms were obtained by running the example of the M/M/1 queue, with a meanarrival time of 13 and a mean service time of 14 .-------------------------------------------------------------------26

Page 31: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

QUEUE SIZEmean = 2.296, variance = 11.034, std dev = 3.322sum of frequencies = 10000min val = 0.000, max val = 27.0000.00 4367.71#############################################################1.00 1375.03###################2.00 1063.30###############3.00 774.50##########4.00 594.07########5.00 453.16######6.00 334.99####7.00 246.18###8.00 183.12##9.00 141.73##over 466.16######-------------------------------------------------------------------WAITING TIMESmean = 0.764, variance = 0.966, std dev = 0.983sum of frequencies = 30069min val = 0.000, max val = 8.3520.00 21699.00#############################################################1.00 5220.00##############2.00 1901.00#####3.00 748.00##4.00 364.00#5.00 100.006.00 25.007.00 9.008.00 3.009.00 0.00 �g 5.1. The results as two ASCII graphs.The last column represents the frequency of the samples, that fell outside the scope of the histogram.The maximal queue size is 27, so adjusting the width of a column to 3 or the number of columns to 30would prevent this from happening. If the library runs in hush mode the method also generates a windowas depicted in the following �gure :27

Page 32: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

�g 5.2. The histogram of the queue size as two windows.5.1.4 The histogram classThe class histogram has the following interface :typedef enum {WEIGHTED,FREQUENCY,SERIES} histogramtype;typedef enum {GRAPH,CUMULATIVE,TABLE,STATISTICS,BARSGRAPH,BARSCUMULATIVE,BARSTABLE} outputtype;interface histogram{ histogram(double st,double wd,int nc,histogramtype kd,outputtype op,char* tl); // constructorvirtual ~histogram(); // destructorvoid sample(double x,double y = 1); // adds a sampleFILE* file(char* fn); // write samples to fnvoid reset(); // resets histogramdouble mean(); // return mean28

Page 33: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

double variance(); // return variancedouble standarddeviation(); // return standard deviationvoid postscript(char* fn1,char* fn2); // generate postscriptfriend ostream& operator<<(ostream& os,histogram& h);}; �g 5.3. The interface of the class histogram.Three di�erent types and seven di�erent output possibilities are speci�ed for histogram. The outputtypes specify a frequency graph, a cumulative frequency graph or a table. The last four types onlyprint the statistics or the bars of the histogram. The constructor takes the start value, the width ofa column, the number of columns, type of histogram, output type and the title. The function sampletakes two doubles and adjusts the internal data accordingly, as described in section 5.1. The method�le writes every sample made in the histogram to the speci�ed �le (the x value on the �rst new line andthe y value on the second new line). It returns the �le pointer of the created �le. The function resetresets the histogram (and its window), as if no samples were recorded. The methods mean, variance andstandarddeviation return the belonging values of the recorded samples. The function postscript writes thewindows of the histogram object (if created) in postscript format to the speci�ed �les. The operator<<function is used to print the histogram to standard output and on a window (if the library is in hushmode).5.2 Realizing accuracy goalsAn increase in the number of samples made obviously gives more accurate results. Reducing the variancecan then be obtained by splitting a long run in several subruns or by repeating a single run. Methodsto do these are the methods of batch means and of repetition. If a run is repeated the use of antitheticvariates can also be of (some) help.5.2.1 Batch means and repetitionThe method of batch means splits a run into several subruns. It records the means of each subrun. Thefollowing addition to the main function of the M/M/1 queue uses this method to obtain the means ofthe queue size and waiting times for the M/M/1 queue.h3 = new histogram(0,1,10,WEIGHTED,STATISTICS,"MEANS QUEUE SIZE");h4 = new histogram(0,1,10,WEIGHTED,STATISTICS,"MEANS WAITING TIMES");for (i=0;i<100;i++){ sim -> run(10000.0);h3 -> sample(h1 -> mean()); // sample the meanh4 -> sample(h2 -> mean());h1 -> reset(); // reset for the next subrunh2 -> reset();}cout << (*h3); 29

Page 34: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

cout << (*h4); �g 5.4. Batch meansAfter sampling the mean of each subrun, the histograms are reset, so the results only cover a singlesubrun. The means of means are in both cases weighted, as runs di�er some in their length.The method of repeating a single run has the disadvantage that on each run we have an initial transientphase. It can be implemented as follows :h3 = new histogram(0,1,10,WEIGHTED,STATISTICS,"MEANS QUEUE SIZE");h4 = new histogram(0,1,10,WEIGHTED,STATISTICS,"MEANS WAITING TIMES");for (i=0;i<100;i++){ sim -> run(10000.0);h3 -> sample(h1 -> mean()); // sample the meanh4 -> sample(h2 -> mean());h1 -> reset(); // reset objectsh2 -> reset();r -> reset();q -> reset();sim -> reset();c = new customer(ARRIVAL); // set up againsim -> schedule(c,0.0);s = new server();sim -> hold(s);}cout << (*h3);cout << (*h4); �g 5.5. RepetitionIn this case we also reset the resource, queue and simulation object so we have several independent runs.The simulation is set up at the beginning of each run by scheduling an arrival and making the serverconditional.5.2.2 Antithetic variatesIf a run produces estimates that are too high, the reverse of the random number stream can be used (by�rst invoking the generator::antithetic method) when repeating the run. The second run then producesestimates that are too low. When combining the results the overall error tends to cancel out and thevariance reduces.Notice that the generator should be reset at the beginning of the second run. Furthermore this methodwill only have e�ect when the random number stream indeed produces numbers that are too high (or toolow). 30

Page 35: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

5.3 Analyzing the resultsThe class analysis makes it possible to analyze a histogram. It provides members for taking con�denceintervals, for covariance and correlation, for analyzing the behavior of the simulation, for �tting curvesand probability distributions and for comparing the mean of the histogram with theoretical queue values.5.3.1 Con�dence intervalsSuppose we are not only interested in the sample mean, but also in some probability judgement of theaccuracy of this mean. The usual way to do this is to construct a con�dence interval for the value of thetrue mean. If we denote the estimated mean as �, the estimated standard deviation as s and the sum offrequencies as n, then, for n large enough, the 100(1 � �)% con�dence interval for the true value of themean is given by �� z�=2 spnwhere z� denotes the �th percentile of the standard normal distribution. The library sim calculates thisinterval for � = 0:01, � = 0:05 and � = 0:10. If n is not large enough, the central limit theory doesn'tapply here. In this case sim takes the percentile from the student distribution. The library adopts avalue of 30 for determining whether the student or the normal distribution should be used. This is alsothe value that is used in [Watkins 93].You should be careful how to interpret this 100(1� �)% con�dence level. The correct interpretation,according to [Kalvelagen 90] is as follows. If you construct a large number of 100(1 � �)% con�denceintervals each based on a sample of n observations with n large enough, the proportion of intervals whichcover the true value of the mean is approximately equal to 1� �.The class analysis also provides a method that returns the con�dence interval for the di�erence ofmeans of the histogram to be analyzed, say a, and the histogram given as parameter in the method, sayb. If we have common variances, the interval is equal to(�a � �b)� z�=2sq 1na + 1nbwhere s is the standard deviation of the samples.In the more typical case in which the variances are not equal, the percentile comes from the studentdistribution and the standard deviation s is estimated ass =q (na�1)s2a+(nb�1)s2bna+nb�2In the example of the M/M/1 queue, we can take a 95% con�dence interval of the histogram of thequeue size as follows :analysis* a;a = new analysis(h1); // h1 is the histogram to be analyzeda -> confidence(PERCENT95); // take 95% conf. int. of the meancout << (*a); // print results�g 5.6. Taking a con�dence interval with simThe resulting output of the analysis object is outlined in the next �gure :31

Page 36: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

-------------------------------------------------------------------CONFIDENCE : QUEUE SIZElevel : 95estimated mean : 2.30interval : +/-0.07 �g 5.7. The ASCII output of an analysis objectIf the library runs in hush mode these results are also shown on a window (with successive prints onthe same window).5.3.2 Covariance and correlationIf the variables that are analyzed are dependent, i.e. their values a�ect each other, we sometimes needinformation about their dependency. A useful measure is the correlationcoe�cient, that is determinedfrom the covariance of two variables.The analysis class provides the methods covariance and correlation to determine the belonging values.The covariance is de�ned as Cov(X;Y ) = Pni=1(xi�x)(yi�y)piPni=1 piwhere n is the number of observations made, xi and yi are the values of the ith observation in the twosamples, x and y are the means of sample x and sample y and pi is the number of occurrences of theith observation in both samples. The pi values are adjusted for the two samples. If, for example, thecorrelation of the sizes of two queues over time is determined, we take equal intervals for the pi values.The correlation coe�cient is then : �(X;Y ) = Cov(X;Y )p�2(X)�2(Y )which divides the covariance with the two variances.The square of the correlation coe�cient tells us what proportion of the variation of the y values canbe attributed to a linear relationship with the x values. If the variables are independent (or uncorrelated)the covariance and correlation coe�cient are equal to 0.The methods of the library assume that the samples of the two histograms are written to a �le. Ifwe have a simulation that exhibits queue swapping we could determine the correlation of the sizes of thequeues as follows :q1 -> reportsize(h1); // add reportsq2 -> reportsize(h2);h1 -> file("sizes1"); // raw samplesh2 -> file("sizes2");sim -> run(10000.0);a = new analysis(h1);a -> covariance(h2); // covariance h1 and h2a -> correlation(h2); // correlation h1 and h2cout << (*a); �g 5.8. Covariance and correlation.32

Page 37: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

5.3.3 Fitting curves and distributionsSuppose you want to investigate if there is some form of linear or quadratic relationship between thesamples you made. The library provides members to �t a linear or quadratic curve on the data. Youcan �t a curve with your own parameters, otherwise the curve that minimizes the sum of the squareddeviations between the recorded and predicted data is taken. Furthermore, the belonging �2 statisticand probability are given. The probability is calculated with the method chisquaretest. This methodcalculates the �2 statistic, taken from [Kalvelagen 90], that is de�ned as :�2 =Prj=1 (Nj�npj)(Nj�npj)npjwhere r is the number of columns (and r-1 the degree of freedom of the test), Nj is the observed value forcolumn j (the column frequency) and npj is the expected value for that column (the calculated value).The �2 test can only be applied if the size of the sample is large enough. Therefore we pool the columnswith an expected value of less then 5 (and the corresponding observed columns) with columns that havea frequency that is high enough. The degree of freedom decreases by 1 for each pooled column then. Thebelonging �2 probability is the chance that the �2 statistic is greater then the calculated �2 statistic,given the degree of freedom. In the case of �tting a curve, a �2 probability that is equal to 0 suggests noreasonable �t. The following code �ts a linear curve.analysis* a;a = new analysis(h); // h is the histogram to be analyzeda -> linear(); // fit linear curvecout << (*a); // print results�g 5.9. Fitting a curveThe library also provides methods to �t a probability distribution on the histogram to be analyzed.The method calculates the relevant parameters of the distribution from the mean and variance of thehistogram data or, if the parameter(s) to the distribution are speci�ed, it just uses these parameters.The method then constructs the distribution and �ts this distribution on the histogram data. Afterperforming the �2 test, the belonging �2 statistic and probability are given.The printing of the analysis object is on standard output and if the library runs in hush mode also ona window. The curve is also shown on the window of the histogram, if this window exists. The followingwindow was obtained by �lling a histogram (with a column width of 0.5) with 10000 samples from thenormal distribution with a mean of 5 and a standard deviation of 1.3. The analysis::normal methodreceived these parameters, when invoked. If not, the method had calculated the a and b values from thehistogram data.33

Page 38: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

�g 5.10. Fitting the normal distribution5.3.4 The behavior of the simulationThe behavior of the simulation should be expected to uctuate because of the stochastic nature of themodel. This behavior can be broadly classi�ed, according to [Watkins 93], into one of the three followingcategories :� steady-state behavior - in which the average uctuation tends to remain essentially constant.� transient behavior - in which the average uctuations do not settle down to a single value.� regenerative behavior - which is cyclic.Transient and steady-state behavior Consider the M/M/1 queue. In the beginning customers areappended to an empty queue. The average of the queue sizes and waiting times increases, so the systemshows transient behavior. After some time the situation is normalized and the average uctuation tendsto remain constant. This period of time is in most cases the period, that is of interest to the user.The library provides a member behavior, that takes a SERIES histogram h and an integer n. Themethod �lls the histogram h with the moving averages of the histogram to be analyzed, i.e. the samplesrecorded averaged over the last n values. The time series histogram is printed to standard output and (ifin hush mode) on a window when the simulation stops. The histogram h should be of type SERIES, soit shows the uctuation of the moving average as a function of time. Indications for the behavior of thesimulation are : 34

Page 39: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

� steady-state behavior - the moving average remains more or less constant.� transient behavior - the moving average increases or decreases for a relevant period.The following code generates a SERIES histogram from the histogram of the queue size of the M/M/1queue.analysis* a;histogram* h3; // create time series histogramh3 = new histogram(0,100,100,SERIES,GRAPH,"moving average queue size");a = new analysis(h1); // h1 is the histogram, to be analyzeda -> behavior(h3,20); // generate a report on behaviorsim -> run(10000.0); // call behavior before running the simulation�g 5.11. Analyzing the behavior of the simulationNotice that the total width of the histogram should cover the entire simulation time. Furthermore,the method behavior should be invoked, before the simulation is run.Suppose we were interested in the queue sizes and waiting times of the M/M/1 queue, when itsbehavior was steady. Furthermore, from inspecting the SERIES histogram of the moving average, weobtained a initial transient period of 500 time units. The following addition to main would do the job :sim -> run(500.0); // run for initial transient periodq -> reportsize(h1); // generate a report on queue sizesq -> reportwaiting(h2); // generate a report on waiting timessim -> run(10000.0); // run for steady period�g 5.12. Running for an initial transient periodThe reports are generated after the initial run, so they only cover the results of the steady period.Regenerative behavior If the simulation shows regenerative behavior the simulation returns to aparticular state where the past history of states has no in uence on the future of the system. Considerthe M/M/1 queue. If no customers are waiting and none being served, the system is in a regenerativestate. At this time the past history has no e�ect on its future behavior.Suppose we want to run the simulation of the M/M/1 queue for n cycles. First we quit the simulationwhen the regenerative state is entered. The following addition to the departure event will do the job :case DEPARTURE :r -> release();sim -> terminate(this);// check for a cycleif (q -> empty() && r -> full()) // system empty ?35

Page 40: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

sim -> quit(); // quit the simulationreturn OK; �g 5.13. Detecting the regenerative stateIn this way when a customer departs we look if s/he was the last being served and if the waiting line isempty or not. The simulation then quits and can easily be started again in the main loop. The additionto the main function is :h3 = new histogram(0,1,10,WEIGHTED,STATISTICS,"MEANS QUEUE SIZE");h4 = new histogram(0,1,10,WEIGHTED,STATISTICS,"MEANS WAITING TIMES");for (i=0;i<n;i++){ sim -> run(); // run until quit (for a cycle)h3 -> sample(h1 -> mean()); // sample means of each cycleh4 -> sample(h2 -> mean());h1 -> reset(); // reset reportsh2 -> reset();}cout << (*h3);cout << (*h4); �g 5.14. Running for n cyclesFurthermore we can discard the statistics of the initial transient period of each cycle, as described in thepreceding section. A cycle should cover a relevant period if we model a simulation like that.5.3.5 The design of experimentsIn this section we look brie y at the design of experiments. Suppose we are not only interested inthe results of a single simulation run, but we'd also like to compare the results of runs under varyingconditions. You can think of a post o�ce with a �xed arrival and service pattern but a varying number ofservice points. The set of input variables and their values is called the treatment of the experiment then.The single execution of an experiment is called a trial and the con�guration of the experiment is calledthe experimental unit. An experiment consists of several trials with several treatments. The results canthen be gathered and analyzed as described in the preceding sections.Consider the M/M/1 queue. If we run several trials and take as treatment the same conditions exceptfor a di�erent resource amount, we can investigate the relationship with the mean queue size and meanwaiting time. After that we can make a trade-o� between the decrease in these values and the costs ofproviding more of the resource and �nd some optimum. The addition to the main function :double amount = 1;r = new resource(amount);h3 = new histogram(1,1,5,FREQUENCY,BARSGRAPH,"AMOUNT - QUEUE SIZE");h4 = new histogram(1,1,5,FREQUENCY,BARSGRAPH,"AMOUNT - WAITING TIMES");while (amount <= 5) 36

Page 41: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

{ sim -> run(10000.0);h3 -> sample(amount,h1 -> mean());h4 -> sample(amount,h2 -> mean());h1 -> reset();h2 -> reset();amount += 1;delete r;r = new resource(amount);q -> reset();g1 -> reset();g2 -> reset();sim -> reset();c = new customer(ARRIVAL);sim -> schedule(c,0.0);s = new server();sim -> hold(s);}cout << (*h3);cout << (*h4); �g 5.15. An experimentNotice that the total experimental unit is reset, except for the resource. The resource is destroyed andcreated with a new initial amount on each trial.5.3.6 The analysis classThe interface of the class analysis is :typedef enum {PERCENT90,PERCENT95,PERCENT99} level;interface analysis{ analysis(histogram* h); // taking histogram to analyzevirtual ~analysis(); // destructorvoid reset(); // reset output structuresdouble confidence(level cl); // confidence interval of meandouble confidence(level cl,histogram* h); // differencedouble covariance(histogram* h2); // covariance h and h2double correlation(histogram* h2); // correlation h and h2double chisquaretest(double* expected); // chi-square testdouble linear(); // linear fit, return chi-squaredouble linear(double a,double b); 37

Page 42: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

double quadratic(); // quadratic fit, return chi-squaredouble quadratic(double a,double b,double c);double uniform(); // uniform fit, return chi-squaredouble uniform(double a,double b);...double laplace(); // laplace fit, return chi-squaredouble laplace(double a);int behavior(histogram* h,int n); // report behaviorint MM1size(double lb,double mu); // M/M/1 queue valuesint MM1waitingtime(double lb,double mu);int MMcsize(double lb,double mu); // M/M/c queue valuesint MMcwaitingtime(double lb,double mu);int MD1size(double lb,double mu); // D/D/1 queue valuesint MD1waitingtime(double lb,double mu);void postscript(char* fn); // generate postscriptfriend ostream& operator<<(ostream& os,analysis& a);}; �g 5.16. The interface of the class analysisThe complete listing of the interface is given in appendix C.The constructor takes the histogram, to be analyzed and creates output structures, which can be setby the di�erent methods and be printed to standard output and on the belonging windows (if in hushmode), using the operator<< function. The method reset can be used to reset the structures as if nothingwas analyzed yet. This method removes every existing window from the screen. The method con�dencereturns the con�dence interval for the mean of the histogram, to be analyzed. If it takes a secondhistogram as parameter, it returns the con�dence interval for the di�erence of means. Each time thefunction con�dence is invoked, it creates an output structure, that is printed when the analysis object is.The methods covariance and correlation determine and return the covariance and correlation coe�cient ofthe two histograms. The function chisquaretest takes an array of doubles and returns the �2 probability,according to the values of the histogram. The probability that the statistic is greater then the calculatedstatistic is returned. The output structure contains also the �2 statistic and degree of freedom. Thefunctions linear and quadratic respectively �t a linear and quadratic curve on the histogram, the outputcontains the (estimated) parameters and the �2 probability. The distribution methods �t the belongingdistributions on the histograms, the output contains the (estimated) parameter(s), the �2 statistic andthe �2 probability. They all return the belonging �2 probability. The method behavior is used to analyzethe behavior of the simulation, as described in section 5.3.4. The queue methods compare the mean ofthe histogram with the mean of the queue size or waiting time and also give the con�dence interval forthe histogram mean. If the theoretical mean lies within the con�dence interval of the histogram meanthe method returns OK, otherwise FALSE. The function postscript writes the windows of the analysisobject (if created) in postscript format to the speci�ed �le. The overloaded operator<< function makes38

Page 43: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

it possible to write an analysis object to standard output and (if in hush mode) on the belonging windows(one for each method). Successive prints take the same window.6 Creating a graphical interfaceThe library also o�ers a class to develop in no time a simple but powerful graphical interface for thesimulation program (for example to check if the implemented process is right). If you want to provide thesimulation with a more complex graphical interface (for a graphical animation for example), you can usethe hush library as described in [Eliens 94]. The screen class of the sim library o�ers built-in tools as thesimulation clock, a start-stop button, means for adjusting the speed of the simulation, queries for inputvariables and methods for creating and moving �gures. The functionality of the screen class is explainedat the hand of a graphical interface for the philosophers program. When using the screen the libraryshould run in hush mode, otherwise only the query method has any e�ect.6.1 A graphical interface for the Dining PhilosophersThe graphical interface of the philosophers program consists of a table, �ve dishes and �ve chopsticks. Thecurrent state of the philosopher is presented as a piece of text. The clock, speed adjuster and the start-stop button are built-in in the screen object. At last the duration is asked before running the simulation.The interface is created in the application::initscreen() method, that is called in application::main() justbefore running the simulation. The code merely consists of adding circles for the dishes and the table,lines for the chopsticks, text for the state of the philosopher and a query for the duration of the simulationprogram. The �gures are added, knowing that the screen defaults are a width of 800 units and a heightof 500 units.void application::initscreen(){ s = new screen(5); // create the screens -> circle("table",400,250,200,"-fill black"); // tables -> circle("b1",275,295,25,"-fill white"); // dishess -> circle("b1",275,295,20,"-fill white");s -> text("b1",275,295,"1");s -> circle("b2",400,395,25,"-fill white");s -> circle("b2",400,395,20,"-fill white");s -> text("b2",400,395,"2");s -> circle("b3",525,295,25,"-fill white");s -> circle("b3",525,295,20,"-fill white");s -> text("b3",525,295,"3");s -> circle("b4",475,145,25,"-fill white");s -> circle("b4",475,145,20,"-fill white");s -> text("b4",475,145,"4");s -> circle("b5",325,145,25,"-fill white");s -> circle("b5",325,145,20,"-fill white");s -> text("b5",325,145,"5");s -> line("c1",270,210,320,240,"-fill white"); // chopsticks39

Page 44: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

s -> line("c2",300,380,340,340,"-fill white");s -> line("c3",460,340,500,380,"-fill white");s -> line("c4",530,210,480,240,"-fill white");s -> line("c5",400,115,400,175,"-fill white");s -> text("t1",150,330,"waiting"); // statess -> text("t2",400,475,"waiting");s -> text("t3",650,330,"waiting");s -> text("t4",570,50,"waiting");s -> text("t5",230,50,"waiting");duration = s -> query("duration"); // query for the duration} �g 6.1. Creating and initializing the screenThe screen is made global as it is used in the events from the philosopher program. If a philosopherstarts to think it releases the chopsticks. We wrote a function releasechopsticks that not only releasesthe chopsticks but also changes the screen. It moves the chopsticks away from the dish to their centralpositions and changes the state of the philosopher on the screen. This function then replaces the releasingof the chopsticks in the philosopher::think function. Consider the implementation.void philosopher::releasechopsticks(){ chopstick[id] -> release(); // release left chopstickchopstick[(id+1)%NUMBER] -> release(); // release right chopstickswitch(id) // which philosopher ?{ case 0 :s -> move("c1",10,-40); // move chopsticks tos -> move("c2",30,30); // their central positionss -> destroy("t1"); // change the state on thes -> text("t1",150,330,"thinking"); // screen to thinkingbreak;case 1 :s -> move("c2",-50,-20); // move chopsticks tos -> move("c3",50,-20); // their central positionss -> destroy("t2"); // change the state on thes -> text("t2",400,475,"thinking"); // screen to thinkingbreak;case 2 :s -> move("c3",-30,30); // move chopsticks tos -> move("c4",-10,-40); // their central positionss -> destroy("t3"); // change the state on thes -> text("t3",650,330,"thinking"); // screen to thinkingbreak;case 3 : 40

Page 45: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

s -> move("c4",20,50); // move chopsticks tos -> move("c5",-40,0); // their central positionss -> destroy("t4"); // change the state on thes -> text("t4",570,50,"thinking"); // screen to thinkingbreak;case 4 :s -> move("c5",40,0); // move chopsticks tos -> move("c1",-20,50); // their central positionss -> destroy("t5"); // change the state on thes -> text("t5",230,50,"thinking"); // screen to thinkingbreak;}} �g 6.2. Releasing the chopsticksThe functions acquirechopsticks and waitonchopsticks are the same and are not included here. The�rst one acquires the chopsticks, moves them in the opposite direction and changes the state on the screento eating. The second one doesn't acquire or move the chopsticks, it only changes the state on the screento waiting. We obtained the following screen :

41

Page 46: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

�g 6.3. The philosophers screen6.2 The screen classThe screen class has the following interface :interface screen{ screen(double fct,int x = 800,int y = 500,char* options = "-background lightskyblue1");virtual ~screen(); // destructorvoid reset(); // reset the screenvoid line(char* fig,int x1,int y1,int x2,int y2,char* options = "");void line(char* fig,char* linespec,char* options = "");void oval(char* fig,int x1,int y1,int x2,int y2,char* options = "");void circle(char* fig,int x,int y,int r,char* options = "");void polygon(char* fig,char* linespec,char* options = "");void rectangle(char* fig,int x1,int y1,int x2,int y2,char* options = "");void square(char* fig,int x,int y,int r,char* options = "");void bitmap(char* fig,int x,int y,char* bitmap,char* options = "");void text(char* fig,int x,int y,char* txt,char* options = "");42

Page 47: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

void move(char* fig,int x,int y); // move figurevoid destroy(char* fig); // destroy figuredouble query(char* txt); // pop-up a queryvoid postscript(char* fn); // generate postscript}; �g 6.4. The interface of the class screenThe constructor creates the components of the screen. As you have seen the screen consists of a start-stopbutton, which starts and stops the simulation, an adjuster for the speed, the simulation clock, a windowon which �gures can be put and moved and a quit button, which ends the session. The constructor takesfour arguments. The �rst one is the factor that we multiply the delay between the execution of two eventswith. If the current speed is 0, the delay is the inter-execution time in seconds (regardless of the timeunit in the simulation) times this factor. As you increase the speed by 1 (up to 100), the delay decreasesby 1 % (down to 0 %). The x and y arguments set the width (default 800) and height (default 500) of thescreen. The options argument comes from the hush library. It can be used to set the background color,for example. If you click on the quit button or invoke the destructor the session is stopped and the screenand the other windows (for the histograms etc.) are removed. The reset function resets the clock to 0and the start-stop button to the stop state but doesn't delete the �gures from the screen. These shouldbe explicitly removed by destroying the �gures. The method line takes two coordinates and puts a linebetween them. The line is added to the speci�ed �gure. The coordinates can also be speci�ed by an arrayof coordinates (that can easily be constructed with the sprintf function). The options parameter (emptyby default) comes from the hush library. You can, for example, specify the �ll color of a �gure as in thephilosopher program. The methods oval, polygon and rectangle create an oval, polygon and rectanglerespectively. These items are added between the speci�ed coordinates and belong to the speci�ed �gure.The methods square and circle add the �gure on the speci�ed coordinate with r as radius. The bitmapfunction takes a bitmap and adds this bitmap on the speci�ed coordinate and to the speci�ed �gure. Themethod text adds a text item on the speci�ed coordinate and adds it to the speci�ed �gure. A �gure canbe moved x to the right and y downwards with the move method. All items belonging to �g are moved inthis direction. The method destroy deletes the speci�ed �gure from the screen. Furthermore you can usethe function query. This function creates a window with the speci�ed text, with room to enter a valueand an OK button. If you click once on the entry you can enter the value. If you click on the OK button,the window disappears and the value is returned as a double and can be used in the simulation program(as is the duration of the philosophers simulation). The postscript method writes the screen in postscriptformat to the speci�ed �le.If the library doesn't run in hush mode only the query method is of any value. It prints the speci�edtext and asks and returns an input value.7 ConclusionsThe library sim extends C++, so that the resulting language exhibits the same functionality as widelyused languages as simscript or simula. Sim provides a convenient, yet exible way to write simulationprograms in C++. It o�ers in addition the advantages of C++ :43

Page 48: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

� e�ciency - C++ compilers typically generate much more e�cient code as is the case with simulaand simscript.� readability - it is our experience that programs written with the sim library tend to be smaller, bemore readable and describe the simulation model more accurate.� features - C++ provides more advanced object-oriented features than simula and simscript. Forexample, class instance variables to be either private or public, instead of only public. Furthermorethe inheritance mechanism provides powerful means for code sharing and structuring programs asa type hierarchy. These features a�ect the structure and problems of debugging of a program.� generality - C++ is known and used in other areas as simulation.� the means to capture complexity - we wrote much larger simulations, then the ones included in thisarticle. As C++ is well suited for developing complex software projects, sim is for writing complexsimulations.Furthermore, the library o�ers more advanced features than simula or simscript. For example the possibil-ity to write both event-based and process-oriented simulations, the classes histogram, analysis and screen,the report members, scheduling priorities and the possibility to create complex graphical interfaces.Acknowledgements We would like to thank Arjan van der Valk, Erik van der Sluis and Aad van derVaart for their comments on the library.References[Birtwhistle 73] G.M. Birtwhistle, O-J Dahl, B. Myhrhaug, K. Nygaard : Simula Begin, Academic Press1973.[Eliens 94] A. Eliens : Hush - a C++ API for Tcl/Tk[Gross 85] D. Gross, C.M. Harris : Fundamentals of queuing theory, John Wiley & Sons 1985.[Kalvelagen 90] E. Kalvelagen, H.C. Tijms : Exploring Operations Research & Statistics in the MicroLab, Prentice Hall 1990.[Kiviat 69] P.J. Kiviat, R. Villanueva, H.M. Markowitz : The Simscript II, Prentice Hall 1969.[Stroustrup 91] B. Stroustrup : The C++ Programming Language, Addison Wesley 1991.[Watkins 93] K. Watkins : Discrete Event Simulation in C, McGraw-Hill 1993.A Probability distributionsThe generator class provides the following probability distributions as described in [Watkins 93] and[Kalvelagen 90] for transforming a random number stream. Some use the � function, which is de�ned as: �(�) = R10 z�e�zdzThe distributions are : 44

Page 49: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

� the uniform distribution, this distribution represents the situation whereby a random number cantake values within a �nite range [�; �] with equal probability. It is characterized by the followingfunction : 1��� ; for � � x � �0; otherwiseThe method in the library takes the upper and lower limit as parameters.� the exponential distribution, takes the non-negative mean � as parameter. Its function :1�e� x� ; for x � 00; otherwiseThis function is used to model purely random events such as the time between arrivals of a customer.� the hyperexponential distribution, takes the non-negative means � and � of two exponential distri-butions as parameters. It then generates a variate from the �rst distribution with chance p and avariate of the second with chance 1-p. Its function :p�e� x� 1�p� e� x� ; for x � 00; otherwise� the normal distribution, the �rst parameter to this distribution is the mean �, the second is thestandard deviation �. It is characterized by the following probability distribution :1p2�� e�(x��)2=2�2; for �1 � x � 1This function is used for the modeling of the additive e�ect of several independent trials.� the lognormal distribution, It is calculated as the logarithm of the normal distribution with � asmean and � as standard deviation. Its probability function :1�xp2� e�(lnx��)2=2�2; for x � 00; otherwise� the erlang distribution. It is used to model service times in a queuing system that has n serverswhere each server has a mean service time of �. The overall service time of this system is given bythe erlang distribution. It is characterized by the following distribution :�(�x)n�1e��x(n�1)! ; for x � 00; otherwise� the gamma distribution, this distribution is parameterized by two values � and �, both greater then0. It has the following probability distribution :45

Page 50: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

��x��1e�x��(�) ; for x � 00; otherwise� the poisson distribution, gets the mean � as parameter. This function is used to model the num-ber of occurrences, such as the number of component failures, over a given period of time. It ischaracterized by the following distribution :�xx! e��; for x = 0; 1; :::;10; otherwise� the geometric distribution, this distribution is characterized by p, the chance on success. It is usedto model the number of occurrences between two signi�cant events as the number of failures toacquire a particular resource until the �rst success. Its distribution :(1� p)x�1p; for x = 0; 1; :::;10; otherwise� the hypergeometric distribution. Suppose that a sample of size n is to be randomly chosen (withoutreplacements) from an urn containing m balls of which mp are white and m(1-p) are black. Thechance of x white balls selected follows the hypergeometric distribution and is equal to :� mpx �� m(1� p)n� x �� mn � ; for x = 0; 1; :::;min(mp; n)0; otherwise� the weibull distribution, it gets � and � as parameters, both greater then 0. It is used for reliabilitymeasures such as the lifetime of components. It is characterized by the following distributionfunction : ��x��1e�x�=�; for x � 00; otherwise� the binomial distribution, gets as parameters p, the chance on a success and n, the number of trials.It is used to model the number of successes in n independent Bernoulli trials. It has the followingprobability distribution : � nx � px(1 � p)n�x; for x = 0; 1; :::; n0; otherwise� the negative binomial distribution, it is parameterized by p, the chance on a success, and n, thenumber of successes. The negative binomial distribution returns the number of failures before thenth success. You can think of the number of retransmissions of a �le. The negative binomialdistribution is characterized by the following function :46

Page 51: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

� n+ x� 1x � pn(1� p)x; for x = 0; 1; :::;10; otherwise� the beta distribution, this probability function is characterized by the two parameters � and �. Itis used to model random proportions as the fraction of customers that could not be served. It hasthe following distribution : �(�+�)�(�)�(�)x��1(1� x)��1; for 0 � x � 10; otherwise� the laplace distribution. The laplace distribution looks like the exponential distribution with amirror image in the y-axis. It has the following probability function :12�e�jxj=�; for �1 � x � 1� the �2 distribution, with n, the degrees of freedom as parameter. It has as probability distributionfunction : xn=2�1e�x=22n=2�(n=2) ; for x � 00; otherwiseThe �2 distribution is a special case of the gamma distribution with � = n=2 and � = 1=2.� the student's t distribution, it also gets the degrees of freedom as parameter. If n is large enough(� 30), it can be approximated by the standard normal distribution. It has as function :�(n=2+1=2)pn��(n=2) 1(1+x2=n)(n+1)=2 ; for �1 � x � 1� the F distribution, returns a value of the F distribution, which is often used for testing variances.The distribution takes two positive integers as arguments, de�ning the degrees of freedom of thevariances being tested. It has a probability distribution function :�((n+m)=2)(n=m)n=2�(n=2)�(m=2) x(n=2)�1(1 + nxm )�(n+m)=2; for x � 00; otherwise� the triangular distribution, it gets the mode of the distribution as parameter. Dependent on themode m the distribution is in the function takes on various triangular shapes. If the mode is equalto 0.5, the triangular distribution is symmetrical. It has the following probability function :2mx; for 0 � x < m < 121�m(1� x); for m � x � 10; otherwise47

Page 52: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

B The generator and some testsIn this section we present the generator and some tests. The generator uses the linear congruentialmethod as described in [Watkins 93] to produce its random numbers (section B.1.). The tests cover therandomness of the random number stream (section B.2.), the quality of the distributions that transformthe stream (section B.3.) and the quality of the event scheduling routine (section B.4.).B.1 The linear congruential generatorThe linear congruential generator consists of the following four numbers :� m, the modulus, m > 0� a, the multiplier, 0 � a < m� c, the increment, 0 � c < m� X0, the seed, 0 � X0 < mfrom which a sequence of random numbers < Xn >; n � 0 can be generated by settingXn = (aXn�1 + c) mod mThese numbers should be chosen in such a way, that the random number stream provides a longcycle time and has good statistical properties. The parameter values, that the library sim uses, area = 663608941; c = 0 and m = 232, yielding the following sequence :Xn = 663608941Xn�1 mod 232This generator has a period of 109, which is plenty for most computer models and has due to computerrepresentation 16.7 million di�erent values equally spaced in the interval [0,1). Furthermore, it has passedseveral statistical tests.B.2 Tests on the random number streamWe wrote the following tests for the random number stream :Empirical tests� the Uniformity Test. The interval is split up into 10 intervals. For randomness we would expectthe counts in each interval to be equal. A �2 test is performed with each member of the expectedarray equal to the number of random fractions divided by 10.We also wrote two variations of this test. The �rst one groups the random numbers into pairs, thesecond one into triples. The expected values of each pair and triple are then the number of randomfractions divided by 2*100 and by 3*1000 respectively.� The Poker Test. In this test we multiply the random fractions with 10 and cast them to integers.Furthermore we group the sequence of integers into sequences of �ve consecutive integers. Thefrequency of the following categories is recorded :{ 1 - All of the same or two di�erent integers in a group.{ 2 - Three di�erent integers in a group.{ 3 - Four di�erent integers in a group. 48

Page 53: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

{ 4 - Five di�erent integers in a group.A �2 test is performed with the following expected values for each category (n is the number offractions):{ 1 - 0.0136 n.{ 2 - 0.1800 n.{ 3 - 0.5040 n.{ 4 - 0.3024 n.� the Gap Test. An interval between a and b is de�ned (0 < a < b < 1). Each random number isreplaced with 0 if outside and with 1 if inside the interval. We are interested in the lengths of thegaps. The expected value of a gap of length k is :(b� a)(1 � (b� a))kn� the Coupon Collector Test. In this test we divide the interval [0,1) into �ve intervals [0,0.2),..,[0.8,1).The number of random fractions to get at least a count of 1 in each interval is counted. We de�ne16 categories as follows :{ 1 - sequence of 5.{ 2 - sequence of 6.{ ..{ 15 - sequence of 19.{ 16 - sequence of 20 or more.The expected values of each category are calculated as :pin; 1 � i � 16with n the number of fractions and pi from the following sequence of probabilities : 0.03840000,0.07680000, 0.09984000, 0.10752000, 0.10450944, 0.09547776, 0.08381645, 0.07163904, 0.06011299,0.04979157, 0.04086200, 0.03331007, 0.02702163, 0.02184196, 0.01760857, 0.07144851In all cases we �ll an array with the expected values for the taken test and perform a �2 test with theobserved values with the method from the analysis class. The hypothesis of randomness is rejected ifthe probability is less then 0.05 (no randomness) or more then 0.95 (fabricated) in 95% or more of theexperiments.The serial correlation test The statistical correlation between two consecutive numbers from a linearcongruential generator is given byCorr(xi; xi+1) = 1a [1� 6cm + 6( cm)2 + �]with j�j � a+6mA generator can be treated as correlated if the correlation is greater than 0.01. In our generator we haveCorr(xi; xi+1) � 1663608941 [1 + 0:16] = 1:7510�9So it exhibits adequately low autocorrelation. 49

Page 54: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

B.3 A test on the distributionsThe distributions that transform the random number stream are tested with the methods from theanalysis class. We �ll a histogram with values taken from the speci�ed probability distribution with thegiven parameters and �t the theoretical values on the histogram with these parameters. The hypothesisof randomness is rejected if the �2 probability is less then 0.05 or more then 0.95 in 95% or more of theexperiments .B.4 A test on the event scheduling strategyThe event scheduling strategy is tested by running a general queuing simulation. The arrival and servicepattern (M or D), the number of service points and the arrival and service rate are the input for thesimulation. The results are compared with the analytical values with the methods of the analysis class.If these values lie within the 95% interval of the simulation results on 95% or more of the experiments theevent scheduling strategy passed the test. For example, if we look at the analytical values of the M/M/1queue, with an arrival rate of 3 and a service rate of 4, the mean of the queue size, according to [Gross85], is equal to �2�2���where � is the number of arriving customers per time unit and � is the service rate per time unit. So thequeue size in our M/M/1 queue is equal to 94 .The mean time spent queuing is ��2���or in our M/M/1 queue 34 . These values do indeed agree with the results of the simulation program ofthe M/M/1 queue, taking the con�dence intervals into account.C The analysis classThe complete interface of the analysis class :typedef enum {PERCENT90,PERCENT95,PERCENT99} level;interface analysis{ analysis(histogram* h); // taking histogram to analyzevirtual ~analysis(); // destructorvoid reset(); // reset output structuresdouble confidence(level cl); // confidence interval of meandouble confidence(level cl,histogram* h); // differencedouble covariance(histogram* h2); // covariance h and h2double correlation(histogram* h2); // correlation h and h2double chisquaretest(double* expected); // chi-square test50

Page 55: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

double linear(); // linear fit, return chi-squaredouble linear(double a,double b);double quadratic(); // quadratic fit, return chi-squaredouble quadratic(double a,double b,double c);double uniform(); // uniform fit, return chi-squaredouble uniform(double a,double b);double exponential(); // exponential fit, return chi-squaredouble exponential(double a);double hyperexponential(double p); // hyperexponential fit, return chi-squaredouble hyperexponential(double p,double a,double b);double gamma(); // gamma fit, return chi-squaredouble gamma(double a,double b);double erlang(); // erlang fit, return chi-squaredouble erlang(unsigned int n,double a);double binomial(); // binomial fit, return chi-squaredouble binomial(double p,unsigned int n);double geometric(); // geometric fit, return chi-squaredouble geometric(double p);double hypergeometric(unsigned int n); // hypergeometric, return chi-squaredouble hypergeometric(unsigned int m,unsigned int n,double p);double negativebinomial(); // neg. binomial fit, return chi-squaredouble negativebinomial(double p,unsigned int n);double poisson(); // poisson fit, return chi-squaredouble poisson(double a);double normal(); // normal fit, return chi-squaredouble normal(double a,double b);double lognormal(); // lognormal fit, return chi-squaredouble lognormal(double a,double b);double chisquare(); // chisquare fit, return chi-squaredouble chisquare(unsigned int n);double student(); // students' t fit, return chi-squaredouble student(unsigned int n);double fdistribution(); // F distribution fit, return chi-squaredouble fdistribution(unsigned int n,unsigned int m);double beta(); // beta fit, return chi-squaredouble beta(double a,double b);double weibull(); // weibull fit, return chi-squaredouble weibull(double a,double b);double triangular(); // triangular fit, return chi-squaredouble triangular(double a);double laplace(); // laplace fit, return chi-squaredouble laplace(double a);int behavior(histogram* h,int n); // report behavior// compare sizes and waiting times for various queuesint MM1size(double lb,double mu);int MM1waitingtime(double lb,double mu);51

Page 56: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

int MMcsize(double lb,double mu,unsigned int c);int MMcwaitingtime(double lb,double mu,unsigned int c);int MD1size(double lb,double mu);int MD1waitingtime(double lb,double mu);void postscript(char* fn); // generate postscriptfriend ostream& operator<<(ostream& os,analysis& a);}; �g C.1. The interface of the class analysisNotice that the hypergeometric �t in both cases requires the n value. This value represents the numberof items drawn from the population and therefore should be known. The hyperexponential �t always takesthe chance of the �rst exponential distribution.D A case study of a job shopThis example illustrates the use of priority queues in a simulation of a jobshop. A jobshop is a systemwhere a central resource is shared by customers that submit complete jobs for processing and receivesome form of output. You can think of a batch computer system with a single cpu. Typically the cost tothe customer in using this service is based on the amount of time required to process the particular job.D.1 The problemIn our example the customers are served in priority order with highest priority �rst. Furthermore a jobwith the highest priority preempts the job that is currently served, if the current job does not have thehighest priority. The job, that is preempted is appended to the queue and is served later for the remainingservice time. If a customer is not served after some maximal period the customer is discarded. In ourexample the jobshop o�ers four grades of service and a premium is paid for a higher grade of servicebecause higher priority jobs always go in front of lower priority jobs when queuing for service time. Eachgrade of service has an associated job priority. They are de�ned as 0,1,2 or 3 with 3 being the highestand 0 the lowest.Based on the existing job load we are interested in the waiting times and the number of interrupts forcustomers taking the priority into account. Furthermore we are interested in the number of customers,that depart without being served.Existing measurements of the tra�c load have indicated that job submissions basically fall into threeclasses of service usage which are independent of the grade of service. Job submissions follow a normaldistribution with the parameters shown in the next table.Type of Standard Percentagejob Mean deviation of totalA 0.76 0.16 21B 2.14 0.22 57C 13.65 1.83 22�g. D.1. Parameters for job submissions52

Page 57: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

A job has a maximal waiting time of 50 time units. For the inter-arrival time of jobs we choose anexponential distribution with parameters shown in the next table.Grade ofService Distribution Mean0 Exponential 19.81 Exponential 13.62 Exponential 11.23 Exponential 27.5�g. D.2. Parameters for inter-arrival timesFurthermore, redundancy has been built-in for the server, because it is subject to stochastic failures.If the server goes down, an identical server is switched on and the broken server is replaced. The systemas a whole goes down when the operating server goes down while the standby is not yet replaced. Inthis kind of problem it is convenient to work with the Weibull distribution, according to [Kalvelagen 90].Closer examination has revealed as parameters for the weibull distribution of the lifetime of the server �= 1 and � = 1.4. Finally, the replacement time is uniformly distributed between 0.1 and 0.12. We areinterested in statistics of the lifetime of the system as a whole.D.2 The programWe wrote the following program. It consists of the entities job, server and breakdown, the priority queueq, the resource shop and the various generator, histogram and analysis objects.#include <sim/sim.h>// phases jobenum {ARRIVAL,DEPARTURE,INTERRUPTED};// phases serverenum {RUNNING,BROKEN};// phases breakdownenum {BOTH_SERVERS_OK,ONE_SERVER_DOWN,BOTH_SERVERS_DOWN};// number of job types,number of grades of service and number of runsenum {JOBTYPES=3,PRIORITIES=4,RUNS=10000};// define highest queuingpriority and maximal waiting timeenum {HIGHEST=3,MAXWAITED=50};class server;simulation* sim;histogram* waited[PRIORITIES];histogram* total[PRIORITIES];histogram* interrupted[PRIORITIES];histogram* lost; 53

Page 58: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

histogram* lifetime;histogram* prob;generator* g1, *g2;resource* shop;queue* q;server* s;double mean[JOBTYPES] = {0.76,2.14,13.65};double stddev[JOBTYPES] = {0.16,0.22,1.83};double probability[JOBTYPES] = {0.21,0.57,0.22};double arrivalrate[PRIORITIES] = {19.8,13.6,11.2,27.5};class job : public entity{ public :job(int ph,int qp,int sp=0);virtual int operator()();int arrival();int departure();double servicetime();double startingtime;double timeleft;int interrupts;};class server : public entity{ public :server(int ph);virtual int operator()();int serve();int preempt();int discard();void breakdown(double t);void fixed();job* current;};class breakdown : public entity{ private :int runs;double last;public :breakdown(int ph,int sp);virtual int operator()(); 54

Page 59: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

int bothok();int onedown();int bothdown();};// constructor, taking phase, scheduling priority and queuing// priority of the jobjob::job(int ph,int qp,int sp) : entity(ph,qp,sp){ startingtime = 0;timeleft = 0;interrupts = 0;}// behavior of a jobint job::operator()(){ switch (phase()){ case ARRIVAL :return arrival();case DEPARTURE :return departure();}return FALSE;}// arrival eventint job::arrival(){ job* j;// add time stamp (for check on waiting time)stamp();// schedule next jobj = new job(ARRIVAL,queuingpriority());sim -> schedule(j,(g1 -> exponential(arrivalrate[queuingpriority()])));// append and report.report(total[queuingpriority()]);q -> append(this);return OK;} 55

Page 60: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

// departure eventint job::departure(){ // add sample, release shop and leave itinterrupted[queuingpriority()] -> sample(interrupts);shop -> release();sim -> terminate(this);s -> current = NULL;return OK;}// if interrupted return time left, else determine service timedouble job::servicetime(){ double p;if (phase() == INTERRUPTED)return timeleft;else{ p = g1 -> uniform(0,1);if (p < probability[0])return (g1 -> normal(mean[0],stddev[0]));else if (p < (probability[0] + probability[1]))return (g1 -> normal(mean[1],stddev[1]));elsereturn (g1 -> normal(mean[2],stddev[2]));}}server::server(int ph) : entity(ph){ current = NULL;}// if possible serve or preemptint server::operator()(){ job* j;// check if brokenif (phase() == BROKEN)return FALSE;// check if empty 56

Page 61: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

if (!(q -> empty())){ j = (job *)q -> front();// if waited too long don't serve itif ((j -> timespent()) > MAXWAITED)return discard();// shop availableelse if (shop -> available())return serve();// current has not highest priority and the front haselse if ( (j -> queuingpriority() == HIGHEST) &&(current -> queuingpriority() != HIGHEST) )return preempt();}return FALSE;}// serve the frontint server::serve(){ double t;job* j;j = (job *)q -> removefront();// determine service time, before adjusting the phaset = j -> servicetime();// acquire shop and schedule departureshop -> acquire();j -> phase(DEPARTURE);// set starting time and time left.j -> startingtime = sim -> clock();j -> timeleft = t;// set currentcurrent = j;sim -> schedule(j,t);return OK;}// preempt current job and serve the frontint server::preempt(){ 57

Page 62: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

double t;job* j;j = (job *)q -> removefront();// update current job, (it always exists)current -> timeleft -= sim -> clock() - current -> startingtime;current -> startingtime = sim -> clock();// remove as departing entity and append as interrupted entitysim -> passivate(current);current -> phase(INTERRUPTED);(current -> interrupts)++;q -> append(current);// update current job, (it always exists)// serve new jobj -> phase(DEPARTURE);t = j -> servicetime();// set starting time and time left.j -> startingtime = sim -> clock();j -> timeleft = t;current = j;sim -> schedule(j,t);return OK;}// discard frontint server::discard(){ job* j;j = (job *)q -> front();// add samplelost -> sample(j -> queuingpriority());interrupted[queuingpriority()] -> sample(j -> interrupts);// terminate without recording the waiting timeq -> terminatefront();return FALSE;}// model a breakdown of the servervoid server::breakdown(double t) 58

Page 63: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

{ if (current){ // extract departuresim -> passivate(current);// update current jobcurrent -> timeleft -= sim -> clock() - current -> startingtime;current -> startingtime = sim -> clock() + t;// schedule departuresim -> schedule(current,(current -> timeleft + t));}phase(BROKEN);}// the server is fixedvoid server::fixed(){ phase(RUNNING);}breakdown::breakdown(int ph,int sp) : entity(ph,0,sp){ last = 0;runs = 0;}// behavior of a breakdownint breakdown::operator()(){ switch (phase()){ case BOTH_SERVERS_OK :return bothok();case ONE_SERVER_DOWN :return onedown();case BOTH_SERVERS_DOWN :return bothdown();}return FALSE;}// both servers OKint breakdown::bothok() 59

Page 64: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

{ double life;// if total number of runs is reached, quitif (runs == RUNS)sim -> quit();elseruns++;// schedule one part downs -> fixed();life = g2 -> weibull(1,1.4);phase(ONE_SERVER_DOWN);sim -> wait(life);return OK;}// one server DOWNint breakdown::onedown(){ double life,replacementtime;// schedule both parts down, if not replaced on timelife = g2 -> weibull(1,1.4);replacementtime = g2 -> uniform(0.1,0.12);if (life < replacementtime)phase(BOTH_SERVERS_DOWN);sim -> wait(life);return OK;}// both servers DOWNint breakdown::bothdown(){ double replacementtime,t;int j=0;// replace both servers and adjust server processreplacementtime = g2 -> uniform(0.1,0.12);phase(BOTH_SERVERS_OK);sim -> wait(replacementtime);s -> breakdown(replacementtime);// sample time server was up, and the probability of the lifetimet = sim -> clock() - last;last = sim -> clock() + replacementtime;lifetime -> sample(t);while (j < t) 60

Page 65: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

{ prob -> sample(j,1.0/RUNS);j += 5;}return OK;}// initialize and run the simulationvoid main(){ analysis* alifetime;analysis* aprob;int i;job* j;breakdown* b;sim = new simulation();sim -> scan();g1 = new generator(821); // inter-arrival and service timesg2 = new generator(18); // life and replacement times of the serverwaited[0]= new histogram(0,1,20,FREQUENCY,STATISTICS,"waiting times for acustomer with queuingpriority 0");waited[1]= new histogram(0,1,20,FREQUENCY,STATISTICS,"waiting times for acustomer with queuingpriority 1");waited[2]= new histogram(0,1,20,FREQUENCY,STATISTICS,"waiting times for acustomer with queuingpriority 2");waited[3]= new histogram(0,1,20,FREQUENCY,STATISTICS,"waiting times for acustomer with queuingpriority 3");total[0]= new histogram(0,1,20,FREQUENCY,STATISTICS,"total time spent for acustomer with queuingpriority 0");total[1]= new histogram(0,1,20,FREQUENCY,STATISTICS,"total time spent for acustomer with queuingpriority 1");total[2]= new histogram(0,1,20,FREQUENCY,STATISTICS,"total time spent for acustomer with queuingpriority 2");total[3]= new histogram(0,1,20,FREQUENCY,STATISTICS,"total time spent for acustomer with queuingpriority 3");interrupted[0]= new histogram(0,1,20,FREQUENCY,STATISTICS,"number ofinterrupts for a customer with queuingpriority 0");interrupted[1]= new histogram(0,1,20,FREQUENCY,STATISTICS,"number ofinterrupts for a customer with queuingpriority 1");interrupted[2]= new histogram(0,1,20,FREQUENCY,STATISTICS,"number ofinterrupts for a customer with queuingpriority 2");interrupted[3]= new histogram(0,1,20,FREQUENCY,STATISTICS,"number ofinterrupts for a customer with queuingpriority 3");61

Page 66: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

lost = new histogram(0,1,4,FREQUENCY,BARSGRAPH,"lost jobs");lifetime = new histogram(0,10,20,FREQUENCY,GRAPH,"life time");prob = new histogram(0,5,20,FREQUENCY,BARSGRAPH,"P(X > t)");q = new queue();shop = new resource(1);// add reports on the waiting timesfor (i=0;i<PRIORITIES;i++)q -> reportwaiting(waited[i],0,i);// initially the jobs are submitted and the server is conditional// the first ones are scheduled in priority order to generate// the reports in queuing priority orderfor (i=0;i<PRIORITIES;i++){ j = new job(ARRIVAL,i,PRIORITIES-i);sim -> schedule(j,0);}s = new server(RUNNING);sim -> hold(s);// schedule a breakdown, it has the lowest scheduling priority so a// customer first departs, if a breakdown occurs at the same timeb = new breakdown(BOTH_SERVERS_OK,-1);sim -> schedule(b,0);// run for RUNS lifetimes of the serversim -> run();// print resultsfor (i=0;i<PRIORITIES;i++){ cout << (*interrupted[i]);delete interrupted[i];delete waited[i];delete total[i];}cout << (*lost);cout << (*lifetime);alifetime = new analysis(lifetime);alifetime -> confidence(PERCENT95);cout << (*alifetime);cout << (*prob);aprob = new analysis(prob);aprob -> exponential();cout << (*aprob); 62

Page 67: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

delete lost;delete lifetime;delete prob;delete alifetime;delete aprob;delete q;delete sim;} �g D.3. The listing of the jobshop programD.3 The resultsThe following ASCII output was obtained :Simulation started at 0.000000Simulation stopped - quit called at 213640.080344Created - 53385 eventsActivated - 681816 eventsTerminated - 53359 eventsActual time taken - 82 seconds-------------------------------------------------------------------waiting times for a customer with queuingpriority 0mean = 17.511, variance = 246.715, std dev = 15.707sum of frequencies = 6183min val = 0.000, max val = 49.995-------------------------------------------------------------------waiting times for a customer with queuingpriority 1mean = 15.372, variance = 204.220, std dev = 14.291sum of frequencies = 14317min val = 0.000, max val = 49.991-------------------------------------------------------------------waiting times for a customer with queuingpriority 2mean = 8.782, variance = 82.108, std dev = 9.061sum of frequencies = 21769min val = 0.000, max val = 49.997-------------------------------------------------------------------63

Page 68: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

waiting times for a customer with queuingpriority 3mean = 0.928, variance = 9.208, std dev = 3.034sum of frequencies = 7978min val = 0.000, max val = 37.472-------------------------------------------------------------------total time spent for a customer with queuingpriority 0mean = 22.350, variance = 270.269, std dev = 16.440sum of frequencies = 5323min val = 0.221, max val = 65.139-------------------------------------------------------------------total time spent for a customer with queuingpriority 1mean = 20.383, variance = 234.780, std dev = 15.323sum of frequencies = 12283min val = 0.217, max val = 66.079-------------------------------------------------------------------total time spent for a customer with queuingpriority 2mean = 13.929, variance = 129.825, std dev = 11.394sum of frequencies = 18727min val = 0.325, max val = 63.692-------------------------------------------------------------------total time spent for a customer with queuingpriority 3mean = 5.183, variance = 33.611, std dev = 5.798sum of frequencies = 7979min val = 0.174, max val = 48.609-------------------------------------------------------------------number of interrupts for a customer with queuingpriority 0mean = 0.147, variance = 0.170, std dev = 0.413sum of frequencies = 14370min val = 0.000, max val = 5.000-------------------------------------------------------------------number of interrupts for a customer with queuingpriority 1mean = 0.101, variance = 0.114, std dev = 0.338sum of frequencies = 12283min val = 0.000, max val = 3.000-------------------------------------------------------------------number of interrupts for a customer with queuingpriority 264

Page 69: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

mean = 0.138, variance = 0.155, std dev = 0.394sum of frequencies = 18727min val = 0.000, max val = 5.000-------------------------------------------------------------------number of interrupts for a customer with queuingpriority 3mean = 0.000, variance = 0.000, std dev = 0.000sum of frequencies = 7979min val = 0.000, max val = 0.000-------------------------------------------------------------------lost jobs0.00 5352.00#############################################################1.00 3288.00#####################################2.00 407.00####3.00 0.00 �g D.4 The results(1)As you can see, jobs having a higher priority have less waiting times. The �rst three priorities havethe same maximal waiting time, since they are removed from the system when their waiting time is toolong. Furthermore, a job having the highest priority can't be interrupted and it can't get lost.-------------------------------------------------------------------life timemean = 21.254, variance = 451.600, std dev = 21.251sum of frequencies = 10000min val = 0.033, max val = 224.8050.00 3777.00#############################################################10.00 2353.00######################################20.00 1434.00#######################30.00 903.00##############40.00 588.00#########50.00 363.00#####60.00 220.00###70.00 149.00##80.00 81.00#90.00 40.00100.00 32.00110.00 21.00120.00 13.00130.00 7.00140.00 8.00150.00 3.00160.00 2.00170.00 2.00 65

Page 70: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

180.00 2.00190.00 1.00over 1.00-------------------------------------------------------------------CONFIDENCE : life timelevel : 95estimated mean : 21.25interval : +/-0.42-------------------------------------------------------------------P(X > t) (%)0.00 100.00#############################################################5.00 79.64#################################################10.00 62.23######################################15.00 49.34##############################20.00 38.70#######################25.00 30.44##################30.00 24.36###############35.00 19.30###########40.00 15.33#########45.00 12.04#######50.00 9.45#####55.00 7.37####60.00 5.82###65.00 4.65##70.00 3.62##75.00 2.72#80.00 2.13#85.00 1.65#90.00 1.3295.00 1.15over 4.96###-------------------------------------------------------------------EXPONENTIAL FIT : P(X > t) (%)a : 18.87chi-square : 5.01degree of freedom : 11P(chi-square > 5.01) = 0.93 �g D.5 The results(2)The statistics of the life time of the server and the chances that this life time is greater then 0,5,10..are given. The exponential distribution has been �tted on the probability histogram of the life times. A�2 statistic of 5.01 suggests a very good �t. The chance that the statistic was greater is equal to 0.93. Ifyou want to be sure that the probability indeed follows an exponential distribution, you have to performthis test several times and make sure that it was no lucky �t.66

Page 71: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

Indexaccuracy, 29analysis, 31, 37antithetic variates, 30arrival pattern, 17rate, 17, 22time dependent, 22balking, 21batch means, 29behavior of the simulation, 34C, 1C++, 1, 43chi-square test, 33, 37clock, 2, 3, 14conditional list, 4, 14, 23con�dence interval, 31con�dence level, 31correlationcoe�cient, 32covariance, 32Csim, 1cumulative frequency graph, 26customer, 17degree of freedom, 33Dining Philosophers Problem, 5Discrete Event Simulation, 1distributions, 16, 37, 44, 50beta, 47binomial, 46chi-square, 46erlang, 45exponential, 45F, 47gamma, 45geometric, 46hyperexponential, 45hypergeometric, 46Laplace, 47lognormal, 45negative binomial, 46normal, 45Poisson, 46Student's t, 47triangular, 47uniform, 45Weibull, 46

entity, 1,5,11state, 4behavior, 1, 11event, 1,5,11state, 4behavior, 1, 6event-based, 1, 5event scheduling strategy, 3experiment, 32unit, 32�le, 26�rst in �rst out (FIFO), 17�tting, 33curves, 33distributions, 33frequency graph, 26generator, 2, 15, 48goodness of �t, 33graphical interface, 38, 39histogram, 25, 28cumulative frequency, 26frequency, 25, 26printing of, 26tables, 26time series, 25weighted, 25hush, 1, 43independence, 32inheritance, 1, 44initial transient, 34least squares, 33estimates, 33curve, 33linear congruential generator, 48mean, 26M/M/1 queue, 17, 50model development, 2, 3, 4, 5, 11model structure, 2, 3, 4, 5, 11moving average, 34object oriented, 1, 43parameter estimation, 3367

Page 72: SIM - pdfs.semanticscholar.org€¦ · C++ library for discrete ev en t ulation. The sim library supp orts b oth an event and pr o c ess-oriente d approac h to dev eloping ulations.

pending tree, (see scheduler)phase of an entity, 5, 11pre-emption, 21primitives, 4passivate, 4hold, 4schedule, 4wait, 4activate, 4terminate, 4append, 4prepend, 4extract, 4removefront, 4removeback, 4withdraw, 4reinstate, 4process-oriented, 11priority queue, 17, 51process, 11process-oriented, 1, 5, 11probability distributions (see distributions)queue, 3, 17behavior, 20, 52priorities, 17, 52service policy, 17size, 19, 24, 50theory, 50waiting time, 19, 24, 50random number generator, 15, 48random number stream, 15, 48regenerative behavior, 35reneging, 21repetition, 29reports, 19, 25reset, 29, 30, 36, 37resource, 2, 17, 27amount, 17results, 25run, 2, 3, 14, 29, 30, 35, 36, 37sample, 25, 26scheduler, 2, 3scheduling priority, 3screen, 2, 39seed, 15server, 19service pattern, 17

service policy, 17set up, 2SIMSCRIPT, 1, 43simulation, 1, 14SIMULA, 1, 43standard deviation, 26states of an event, 3passive, 3active, 4queued, 4pending, 4conditional, 4closed, 4steady state behavior, 34swapping, 20table, 26termination, 2, 14tests, 48coupon collector test, 49gap test, 49poker test, 48serial correlation test, 49uniformity test, 48time stamps, 11time spent, 11transient behavior, 34transition diagram, 5treatment, 32trial, 32type of the histogram, 25frequency, 25weighted, 26series, 26variance, 26variance reduction, 29, 30

68