You are on page 1of 81

A Java-based Simulation and Animation Environment: JSIM's Foundation Library

by
Zhiwei Zhang

M.A., Nanjing University, China, 1990 M.L.S., University of Maryland at College Park, 1993

A Thesis Submitted to the Graduate Faculty of The University of Georgia in Partial Ful llment of the Requirements for the Degree
Master of Science

Athens, Georgia

1997

c 1997 Zhiwei Zhang All Rights Reserved

A Java-based Simulation and Animation Environment: JSIM's Foundation Library

by
Zhiwei Zhang

Approved: Major Professor Date

Approved: Graduate Dean Date

Acknowledgments

First of all, I would like to thank Dr. John Miller, my major professor, my mentor and my friend for his sincere and constant guidance, help and support during the time when I was studying at the University of Georgia and during the entire process of this project. Without him, this would have been impossible. Second, I would like to thank my committee members, Dr. Je rey Smith, Dr. Dan Everett and Dr. Hamid Arabnia for being on my committee, for their useful and valuable comments on this project and also for the knowledge and things they have taught me. Third, I would like thank the members of our JSIM simulation environment team, Rajesh Nair and Hongwei Zhao for their encouragement and friendship. Next, I am deeply grateful to my wife, Xuan, for her love, constant support and encouragement no matter how hard our situation is. I would like to dedicate this work to her and our new-born daughter, Hannah, who has since birth been working together with Dad in front of computer. Finally and most importantly, I would like to thank my personal savior, Jesus Christ. He is the living source of my life.

iv

Preface

The emergence of Java programming language together with the Internet creates a new exciting area in the eld of simulation, web-based simulation, allows us to develop dynamic simulation models and makes simulation models widely available over the Internet. The main objective of this thesis is to develop a simulation library in Java to make construction, distribution and execution of simulation models easy. The thesis states the motivations and objectives of this project, introduces basic simulation concepts, provides an overview of the major features of the Java programming language and its importance in web-based simulation and presents JSIM, a Java-based simulation and animation foundation library. A bank simulation example developed in JSIM is also discussed. The JSIM library includes six packages: queue, statistic, variate, event, process and qds. It supports both process interaction and event scheduling discreteevent simulation. My work focuses on the rst four packages, while my colleague, Rajesh Nair, focussed on the later two.

Contents

Acknowledgments : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : iv Preface : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : List of Tables : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 1 Introduction : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 1.1 Objectives of the Project : : : : : : : : : : : : : : : : : : : : : : : : : 1.2 Organization of the Thesis : : : : : : : : : : : : : : : : : : : : : : : : 2 Introduction to Simulation : : : : : : : : : 2.1 Discrete Event Simulation Models : : 2.2 Discrete-Event Simulation Strategies 2.3 Discrete Event Simulation Languages v x 1 2 3 List of Figures : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : ix

: : : :

: : : :

: : : :

: : : :

: : : :

: : : :

: : : :

: : : :

: : : :

: : : :

: : : :

: : : :

: : : :

: : : :

: : : :

: : : :

: : : :

: 4 : 6 : 10 : 13

3 Java and Web-Based Simulation : : : : : : : : : : : : : : : : : : : : : : : : 15 3.1 Java: A Programming Language for the Internet : : : : : : : : : : : : 15 3.2 Simulation Languages and JSIM : : : : : : : : : : : : : : : : : : : : : 17 4 The JSIM Foundation Library : : : : : : : : : 4.1 Queue Handling Facilities : : : : : : : : 4.2 Statistical Analysis Capabilities : : : : : 4.3 Random Number and Variate Generators 4.4 Test of Random Number Generators : : vi

: : : : :

: : : : :

: : : : :

: : : : :

: : : : :

: : : : :

: : : : :

: : : : :

: : : : :

: : : : :

: : : : :

: : : : :

: : : : :

: : : : :

: : : : :

: : : : :

20 22 29 34 35

5 Event-Scheduling Facilities : 5.1 Entity : : : : : : : : : 5.2 Event : : : : : : : : : 5.3 Scheduler : : : : : : :

: : : :

: : : :

: : : :

: : : :

: : : :

: : : :

: : : :

: : : :

: : : :

: : : :

: : : :

: : : :

: : : :

: : : :

: : : :

: : : :

: : : :

: : : :

: : : :

: : : :

: : : :

: : : :

: : : :

: : : :

: : : :

: : : :

vii 40 40 41 41

6 Example : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 44 7 Conclusions and Future Work : : : : : : : : : : : : : : : : : : : : : : : : : 54 Bibliography : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : 55 Appendix A Random Number and Variate Generators A.1 LCG Random Number Generator : : : : : : : : A.2 Variate : : : : : : : : : : : : : : : : : : : : : : : A.3 Bernoulli : : : : : : : : : : : : : : : : : : : : : : A.4 Beta : : : : : : : : : : : : : : : : : : : : : : : : A.5 Binomial : : : : : : : : : : : : : : : : : : : : : : A.6 Cauchy : : : : : : : : : : : : : : : : : : : : : : : A.7 Chi Square : : : : : : : : : : : : : : : : : : : : : A.8 Discrete Probability : : : : : : : : : : : : : : : : A.9 Erlang : : : : : : : : : : : : : : : : : : : : : : : A.10 Exponential : : : : : : : : : : : : : : : : : : : : A.11 F Distribution : : : : : : : : : : : : : : : : : : : A.12 Gamma : : : : : : : : : : : : : : : : : : : : : : A.13 Geometric : : : : : : : : : : : : : : : : : : : : : A.14 Hyper-Exponential : : : : : : : : : : : : : : : : A.15 Hyper-Geometric : : : : : : : : : : : : : : : : : A.16 Log Normal : : : : : : : : : : : : : : : : : : : : A.17 Negative Binomial : : : : : : : : : : : : : : : : A.18 Normal : : : : : : : : : : : : : : : : : : : : : : :

: : : : : : : : : : : : : : : : : : :

: : : : : : : : : : : : : : : : : : :

: : : : : : : : : : : : : : : : : : :

: : : : : : : : : : : : : : : : : : :

: : : : : : : : : : : : : : : : : : :

: : : : : : : : : : : : : : : : : : :

: : : : : : : : : : : : : : : : : : :

: : : : : : : : : : : : : : : : : : :

: : : : : : : : : : : : : : : : : : :

: : : : : : : : : : : : : : : : : : :

: : : : : : : : : : : : : : : : : : :

: : : : : : : : : : : : : : : : : : :

60 60 60 61 61 62 62 63 63 63 64 64 64 65 65 65 66 66 67

A.19 Poisson : : A.20 Randi : : A.21 Student t : A.22 Triangular A.23 Uniform : A.24 Weibull : Appendix B

: : : : : :

: : : : : :

: : : : : :

: : : : : :

: : : : : :

: : : : : :

: : : : : :

: : : : : :

: : : : : :

: : : : : :

: : : : : :

: : : : : :

: : : : : :

: : : : : :

: : : : : :

: : : : : :

: : : : : :

: : : : : :

: : : : : :

: : : : : :

: : : : : :

: : : : : :

: : : : : :

: : : : : :

: : : : : :

: : : : : :

: : : : : :

: : : : : :

: : : : : :

: : : : : :

: : : : : :

: : : : : :

: : : : : :

viii 67 67 68 68 68 69

64-bit LCG Random Number Generators : : : : : : : : : : : : 70

List of Figures

2.1 Scheduling Future Events Mechanism (Adapted from Evans, 1988) : 9 2.2 Event Scheduling Strategy (Adapted from Bolier & Eliens, 1995) : : 12 3.1 Java Thread States and State Transitions (Adapted from Cornell & Horstmann, 1996) : : : : : : : : : : : : : : : : : : : : : : : : : : : : 18 3.2 Relationships among Java, JSIM, and Simulation Models : : : : : : : 19 4.1 4.2 4.3 4.4 4.5 JSIM Simulation and Animation Environment Packages in JSIM Library : : : : : : : : : : : Class Hierarchy of queue Package : : : : : : : Class Hierarchy of statistic Package : : : : Class Hierarchy of variate Package : : : : :

: : : : :

: : : : :

: : : : :

: : : : :

: : : : :

: : : : :

: : : : :

: : : : :

: : : : :

: : : : :

: : : : :

: : : : :

: : : : :

20 21 23 31 39

5.1 Class Hierarchy of event Package : : : : : : : : : : : : : : : : : : : : 40 6.1 Event Graph for Simple Bank System : : : : : : : : : : : : : : : : : 45 6.2 Bank Simulation Example (Event Scheduling) : : : : : : : : : : : : : 47 6.3 Standard t-distribution : : : : : : : : : : : : : : : : : : : : : : : : : 51

ix

List of Tables

2.1 Comparison of Event Set Implementations (Adapted from Jones, 1986) 9 4.1 Implementations of enqueue Methods for Queues : : : : : : : : : : : 24 4.2 Critical Values for KS Test : : : : : : : : : : : : : : : : : : : : : : : : 37 4.3 Summary of KS-Test for LCG : : : : : : : : : : : : : : : : : : : : : : 38 6.1 Summary of Bank Sample Run : : : : : : : : : : : : : : : : : : : : : 50 6.2 Summary of Bank Batch Run : : : : : : : : : : : : : : : : : : : : : : 51

Chapter 1 Introduction

Internet technology is an important invention in the history of modern computing. It not only dramatically changes a variety of facets of our daily life, of education and of society, but also a ects computing technology itself. Web-based simulation is the combination of Internet technology (speci cally, World Wide Web or WWW) and simulation (Fishwick, 1996). It is made possible with the emergence of the Java programming language, a language designed for Internet. Never in the history of computer technology has a language like Java attracted so many software developers, operating system vendors, and business organizations in such a short time. It, together with the web technology such as web browsers, makes simulation models more dynamic, more interactive and more widely available. It is evident that webbased simulation forms the trend for future simulation development. However, Java is a general programming language and lacks basic simulation utilities even though it has several classes and packages such as Thread and Applet which are convenient for simulation and animation model construction. Therefore, to facilitate creating simulation models with Java it is necessary to develop a simulation library for the language. The reasons to use Java to build a simulation library have been discussed in several recent papers (Buss, & Stork, 1996; Fishwick, 1996; Nair, Miller, & Zhang, 1996; Miller, Nair, Zhang, & Zhao, 1997). 1. Simulation models implemented as Java applets can be down-loaded and executed on local machines with Java-enabled web browsers. 1

2 2. Simulation models implemented in Java can be easily ported to and run on other platforms without re-compilation as long as the local machine has Java run-time environment. 3. Java's built-in Thread class makes it easy to implement the process interaction view of simulation. 4. Java is capable of developing sophisticated animations using its built-in Thread, Applet and AWT classes. Java applets running on Java enabled web browsers can combine text, sound, graphics and images to provide a high degree of dynamism. 5. Java is an object oriented programming language, small and easy to learn. It has a high degree of code re-usability. It encourages simulationists to write more reliable, and bug-free simulation models. 6. Java is free and available for down-loading from the web.
1.1 Objectives of the Project

The goal of this project is to develop an easy-to-use web-based simulation library using Java so as to make construction of simulation and animation models easy. Speci cally, JSIM is intended to provide the following: a basic set of utilities needed in constructing simulation models, an easy-to-learn simulation tool for simulation professionals, a way for simulation professionals to develop simulation and animation models with minimal e ort, a capable and reliable simulation tool for constructing moderately complex simulation models, and

3 a cost-e ective free tool widely available through the web. The JSIM simulation and animation environment includes extensive simulation libraries, animation capabilities, query-driven simulation facilities and a graphical designer. The focus of my work has been on the foundation library for JSIM. This library was created to facilitate the development of a variety of simulation systems as layers above it. I built such a simulation system based on the event scheduling paradigm and assisted my colleague, Rajesh Nair, in building a simulation system based on process interaction paradigm. The foundation library is general and exible enough to allow others to layer their own simulation system on top of it.
1.2 Organization of the Thesis

The thesis has six chapters. The rst chapter is the introduction. It states the motivations for the project. In chapter 2, we introduce basic discrete-event simulation concepts, the components of discrete event simulation and two dominant simulation strategies: event-scheduling and process-interaction. Chapter 3 provides an overview of the Java programming language, its major features and the importance of Java in web-based simulation. Chapter 4 describes in detail each package in the JSIM library. Then, chapter 5 discusses bank simulation example created using JSIM and analyzes its simulation results. Finally, conclusions and future work are discussed.

Chapter 2 Introduction to Simulation

Computer simulation is used to model a physical system, to execute the model, and to analyze the results of the simulation execution (Fishwick, 1996). A system, according to Gordon (1978), is an aggregation of entities and the interaction among them. Simulation is important mainly because \simulation can tell us things we do not already know" (Simon, 1969, p.19) and can help us to make decisions and recommendations. It is expensive and sometimes impossible to experiment on real systems. Therefore, simulation can assist us to make decisions by modeling real systems and by analyzing the simulation results (Gordon, 1978; Seila, 1995). States, events, entities and time are basic concepts in simulation. A state is a collection of variables which describe the system for an interval of time. It is the major task of simulationists to design a model which captures the behavior of the system. As a result, simulation professionals have to select states to represent the system model. For the bank example, where customers queue for service from tellers the state variables could be the availability of tellers and the number of customers in line(s) or in the bank. An event describes a system state change at a particular time. While simulating systems, we model future events based on assumptions or on collected data regarding the occurrence times of these events. Customer arrival and customer departure in the bank model are examples of events. The occurrence times of these events are usually determined by statistical distributions and modeled by sampling from the 4

5 statistical distributions. For example, inter-arrival times of bank customers may be characterized by the exponential distribution and are generated by taking samples from the distribution. Entities are objects which have independent identity in the real world. An entity may be dynamic and ow through a system; or it may be static and only serve other entities (Carson, 1993). Taking the bank example, customer and teller are entities. A customer is an dynamic entity since it ows through a bank system: arriving at bank, waiting in the queue, receiving service, and leaving the bank. On the other hand, a teller can be static or dynamic depending on how we model it. An entity has attributes and properties. For instance, a customer has demand, service time and maybe priority. We normally manage entities using lists. In systems with scarce resources, entities sometimes have to wait for services. Ordered lists such as FirstIn, First-Out (FIFO) queue or Last-In, First-Out (LIFO) queue are usually used to implement the service policies. In virtual time discrete event simulation, when an entity is suspended, for example, a Future Event List (FEL) is used to arrange the entity to continue its activities at a proper future time. Time is represented either by integer or by oat (or double). Float representation is more accurate than integer representation. How time is advanced in simulation is also an important aspect of simulation which we will visit later. There are three important phases in simulating a physical system: model design, model execution and model analysis (Fishwick, 1995). The rst phase of simulation, model design, consists of two steps: building the model structure and providing data for system variables. Building the model structure identi es the entities, attributes and activities. Then the values that attributes can take are provided and the relationships among activities are de ned (Gordon, 1978). The second phase is to convert models to algorithms, to implement them in programming languages, and to

6 execute them on computers. The step after model execution is to run statistical analysis of execution results.
2.1 Discrete Event Simulation Models

Discrete-event system simulation is used to model systems where the state variables change instantaneously at discrete points in time. Discrete event simulation models often concentrate on scarce resources for which simulation entities must wait for service in queues. In addition, delays between state changes are usually represented by statistical distributions.
2.1.1 Components of Discrete Event Simulation

Researchers have identi ed several components common to all discrete-event simulation in the past several decades (Kreutzer, 1986; Law, & Kelton, 1991; Watkins, 1993): 1. Model structuring and execution facilities. As stated previously, a model is a collection of entities interacting with each other. Object-oriented languages, such as C++ (Stroustrup, 1991) and Java (Flanagan, 1996; Naughton, 1996), allow us to represent entities as objects, relationships via inheritance or aggregation, attributes as data members, and actions as member methods. 2. List management. Lists are an implicit part of almost all discrete event simulations. Because discrete event simulation models, as stated above, concentrate on limited resources, entities are forced to wait for service if the resources they request are not available temporally. Lists are therefore important to implement the service policies to allow entities to access resources in certain order.

7 3. Time management. These are two basic time advance mechanisms: the constant increment and the variable increment methods. The constant increment method uses system built-in time which is increased at xed length intervals; on the other hand, in variable increment method time advance is triggered by occurrence of signi cant events regardless of the time elapse between successive events. The time advance mechanism in virtual time clock is a means to bridge the gap between one event and another by assuming nothing happens in the gap (Zeigler, 1976). Variable increment simulation is ideal for speedy simulation. It is particularly helpful if the real world events which are simulated are long lived. Virtual-time clock simulation uses the so-called \next-event" strategy for advancing simulation time. Here, the clock value jumps to the time at which the next event is due to occur. It is usually implemented with a scheduler and a Future Event List (FEL). The scheduler rst schedules an event or entity by inserting it into the FEL based on its activation time. It then transfers to the event or entity at the front of the FEL by removing it from the FEL and updating the simulation clock to the time associated with that event or entity. 4. Random number and variate generators. As stated earlier, one of the important steps in simulation model development is to represent a system model. For most system models, inputs are stochastic and a model variable is determined by sampling from the distribution speci ed for that variable. A particular sample value taken from a statistical distribution is called a random variate. A uniform random number generator produces a sequence of values in the range of (0, 1). Desired characteristics for the random number generator include uniformity, independence, and long period. Linear congruential generators,

8 rst proposed by Lehmer (Lehmer, 1951), are the most commonly used method and have been thoroughly tested over the years. 5. Statistical instrumentation and reporting utilities. In order to provide necessary information helpful in decision making, in evaluation of the decision, and in understanding a system, a simulation library has to have utilities to collect and analyze simulation execution results. Statistical facilities should be able to collect and analyze statistics such as mean, variance and standard deviation regarding the use of resources, queue length, service time, etc. The following are the important steps in data analysis (Fishman, 1978): (a) Calculate the sample mean, (b) Estimate the variance of the sample mean, (c) Determine the degree of freedom, and (d) Calculate the con dence interval using the student t distribution. 6. Scheduler. In order to carry out a resource-limited discrete event simulation, a simulation system needs a mechanism to advance time from current event to next event, to update system state at each event time, and to free or hold system resources. One of the important underlying mechanisms is an event scheduler. Its responsibility is to sequence state transitions. The events in simulation come from future event notices. Each event notice is like an appointment entry in a schedule. When an appointment occurs, new entries are generated and are recorded on the schedule. The next appointment due to happen is the most recently scheduled. In simulation, the schedule is called the Future Event List (FEL). The purpose of FEL is to keep track of pending events and to trigger the occurrence of the next event. Correspondingly, we can apply two operations on the FEL: insert an event notice onto the FEL and

9 Table 2.1: Comparison of Event Set Implementations (Adapted from Jones, 1986) Implementation Code Average Worst Relative Comments size performance performance speed Linked list 47 O(n) O(n) 11 Best for n smaller than 10 Implicit heap 72 O(log n) O(log n) 8 Leftist tree 79 O(log n) O(log n) 9-10 0:5) Two list 104 O(n O(n) 9-10 Good for n smaller than 200 0:5) 0:5) Henriksen's 68 O(n O(n 1-7 Stable Binomial queue 188 O(log n) O(log n) 1-7 Pagoda 110 O(log n) O(n) 4-8 Skew heap, 56 O(log n) O(log n) 5-7 top down Skew heap, 103 O(log n) O(log n) 4-6 bottom up Splay tree 119 O(log n) O(log n) 1-3 Stable Pairing heap 84 O(log n) O(log n) 3-6 retrieve the next event form the FEL (Evans, 1988). With each event notice two types of information are closely associated: the event occurrence time, and a reference to the event action.
Models Future activations Insertion of scheduled events Event Actions retrieval of next event Current activation Future event notices Future event list

Figure 2.1: Scheduling Future Events Mechanism (Adapted from Evans, 1988)

10 The FEL is implemented as a priority or temporal queue: events are inserted and removed on the basis of their time/priority. FELs are designed so that the next event can be removed and a future event can be placed on the FEL quickly. The mechanism for scheduling future events is shown in Figure 2.1. A number of implementations have been developed and evolved for such priority/temporal queues. Jones (Jones, 1986) compared eleven priority/temporal queue implementations based on two operations, enqueue and dequeue. His empirical results are shown in Table 2.1. His research concluded that simple link lists with performance bound O(n) perform best when the size of priority queue is smaller than 10, but its performance decreases with increasing size. On the other hand, splay tree implementations have stable, nearly optimal performance and the fastest relative speed (1 is the fastest, 11 the slowest). Its performance bound is O(log n). Calendar queue is another implementation of FEL which has an average O(1) performance. However, its application is limited because it is sensitive to priority distribution (Brown, 1988).
2.2 Discrete-Event Simulation Strategies

Event-scheduling and process interaction are two dominant strategies or world views in discrete-event simulation. In the following subsections we introduce both of the strategies.
2.2.1 Event Scheduling

This strategy views a model of a system as a set of event descriptions, and it requires the model developer to identify signi cant events which may change the system state. It is assumed that the system state does not change and nothing happens between

11 events. Each event is taken individually, described and implemented as a procedure, module, or class in terms of interaction between entities. The event scheduling mechanism is the central component is the strategy. It should consist of a method to schedule an event, a method to select and execute the next event, a variable to represent the current simulation time, and a data structure to implement a Future Event List (FEL). The schedule of events is stored in the FEL. The event list is ordered in ascending values of event times; events with the same activation time can be ordered on the basis of priority or of arrival order. When an event occurs, an event notice is created and inserted onto the FEL by its relative event time. If the two entities have the same time values and/or priorities, they can be ordered by FirstIn, First-Out principle. Because the splay tree is stable (Jones, 1986), clearly it is well suited for the FEL implementation. An event notice usually contains the event identity, entity associated with the event, and the event activation time. For the customer arrival example, arrival is an event and customer is the entity associated with the event. When a simulation program nishes processing an event, it selects the next event by extracting it from the FEL and executes it. The basic steps in event scheduling consists of (Carson, 1993): 1. Create the initial event and start simulation; 2. Extract the imminent event (event with the smallest event time) from the Future Event List. If no event can be extracted, go to step 6; 3. Advance simulation clock to the time when the imminent event is due to occur; 4. Execute the imminent event; 5. Go to step 2; 6. Output results.

12 The following diagram (Figure 2.2) depicts the event scheduling strategy:
Schedule initial event

No Any event?

Select next event

Advance clock

Execute event

Output results

Figure 2.2: Event Scheduling Strategy (Adapted from Bolier & Eliens, 1995)
2.2.2 Process Interaction

The process interaction strategy views a system as a set of entities and resources owing through. A logical process is used to produce a life history for an entity. The implementation of this strategy focuses on the sequence of events, activities and delays of a logical process. A set of process management primitives for initiating, controlling, and terminating are essential to the process interaction strategy. A simple bank model would primarily contain customer processes accessing limited resources. The life history of a customer in a bank is: entering the bank, waiting in teller queue if teller is busy serving other customers, receiving service, and leaving the bank. The following pseudo-code is for the customer process:

13
Customer: /* Customer arrives */ if (teller is busy) { Join teller queue; Suspend; }; /* Begin service */ Capture a teller; Be served for t units of time; /* Leave bank */ Free teller; if (teller queue is not empty) Take next customer from queue; Resume; };

To have a complete bank model, we have to have another process to create customer arrivals which do not correspond to the real situation. The pseudo-code for this process is as below:
int no_of_customers; // number of customers generated int max_customers; // number of customers we intend to simulate CustomerGenerator: while (no_of_customers < max_customers) { Generate new customer; no_of_customer++; Start the generated customer process; Wait for t units of time; };

2.3 Discrete Event Simulation Languages

In the past several decades, many discrete event simulation languages and packages have been developed. Commercial discrete-event simulation languages such as GPSS (Schriber, 1991), SLAM (Pritsker, 1986), SIMSCRIPT (Markowitz, Kiviat, & Villaneuva, 1987), SIMAN (Pegden, Sadowski, & Shannon, 1990), and Simula (Dahl, & Nygaard, 1970) have been widely used in constructing simulation models. Most

14 of these languages support both event scheduling and process interaction simulation strategies except that GPSS only supports process interaction. In addition to simulation languages, simulation packages and libraries for popular general programming languages such as Pascal, Modula-2, C, and C++ have been developed. For example, SIMTOOLS (Seila, 1988) is a tool kit developed for Pascal; SIMODULA (Miller & Weyrich, 1989; Miller & et al, 1996) for Modula-2; SMPL (MacDougall, 1987) for C; CSIM (Schwetman, 1988; 1990), SIM++ (Lomow, & Baezner, 1990), SIM (Bolier, & Eliens, 1995) and AWESIME (Grunwald, 1991, 1993) for C++; SimPack (Fishwick, 1992) for C or C++. SIMTOOLS, SMPL, and SIM++ implement event scheduling approach of simulation; CSIM and AWESIME (modeled after CSIM) support process interaction world view; SimPack, Sim, and SIMODULA are developed to construct both event scheduling and process interaction simulation models.

Chapter 3 Java and Web-Based Simulation

3.1 Java: A Programming Language for the Internet

Java is a revolutionary language designed to support programming for the Internet. We have rarely seen in the history of modern computing a language like Java developed into a hot phenomena in such a short time. It quickly attracted many business organizations, software developers, and operating system vendors to adopt it, use it and support it. It has been proven capable of sophisticated applications as well as completely new applications (Halfhill, 1997). Why has Java become so popular almost \overnight"? Let us look at the major features of the Java language and its libraries. Sun describes Java as: A simple, object-oriented, distributed, interpreted, robust, secure, architecture neutral, portable, high-performance, multi-threaded, and dynamic language. (Sun Microsystems, 1996) Java is designed to allow programmers to learn quickly, and to closely resemble C++ so that experienced C++ programmers can easily migrate to Java. Java does not support pointers, a bug-prone feature of C and C++. Java's automatic garbage collection feature leaves programmers free from worrying about memory management. These make it easy to write bug-free code. Unlike C++ which evolved from C, Java is designed from scratch, and is a pure object-oriented programming language. A Java program is a collection 15

16 of classes and instances of classes (objects); data and methods are meaningful only inside classes or objects (called encapsulation). Therefore, its code reusability is high. Besides its networking capabilities, Java programs (applets) can be downloaded and run on local machines through web browsers which support Java. Java brings a network into local machines, and breaks the barrier of locally running remote programs. Java's enhanced features make it more likely that program developers will write reliable code. Java is a strongly typed language, which requires extensive type checking at compile time and eliminates potential errors at run-time. For example, Java supports neither implicit method declarations nor implicit type casting. Memory management is a tedious task for C or C++ programmers; they have to keep track of all memory allocated and deallocate after nishing with it. However, Java's automatic garbage collection feature prevents such memory leaks caused by programmers forgetting to deallocate memory they have already allocated. Furthermore, Java's exception handling simpli es the recovery task when an exception or error arises, and makes programs more robust. Java is a secure language. Because of Java's ability to be down-loaded from the Internet, and run on a local machine, security becomes a major issue for Java. Java implements strict security mechanism. It performs several safety checks before executing a down-loaded applet. The byte-code veri er does byte-code format and static type checking. The security manager carries out run-time checks on dangerous methods, such as le or network methods (McGraw, & Felten, 1997).

17 Java language is platform independent and Java class les are portable. Java compiler produces intermediate Java byte code which is not speci c to a particular machine (or chip). As long as a machine has a Java run-time environment, it can run Java programs. Java run-time environment includes the Java Virtual Machine, byte-code veri er, and byte-code interpreter. Java's built-in class Thread supports multiple threads of execution. This simpli es current or quasi-concurrent programming. Web-based simulation represents the connection between web technology and simulation. Java, together with web technology, makes web-based simulation possible. It provides simulationists with an enhanced dynamic simulation development environment. The advantages of using Java to implement simulation models go hand in hand with its features summarized above. As we discussed in the introduction, Java is the language which is particularly suitable for simulation and animation model development.
3.2 Simulation Languages and JSIM

Simulation languages have developed and used in building simulation models. However, most of existing simulation languages are commercial and learning them is an additional burden for simulationists. That is why there have been so many packages and libraries developed for popular general programming languages. Java provides useful classes suitable for simulation. Its built-in Thread class consisting such methods (primitives) as start, run, init, suspend, resume, sleep, and stop, which is ideal for process interaction simulation. Threads in Java can be in one of four states: new, runnable, blocked, and dead (Cornell & Horstmann, 1996). Figure 3.1 shows the thread states and possible transitions from one state to another.

18
wake up new sleep

suspend runnable resume blocked

dead

wait notify

Figure 3.1: Java Thread States and State Transitions (Adapted from Cornell & Horstmann, 1996) However, as stated above, Java as a general programming language lacks facilities such as random variate generators, sophisticated queuing handling utilities and statistical instrumentation to support easy construction of working simulation models. A simulation library, called JSIM, is developed to extend the capabilities of Java so as to create simulation models. The relationship among Java, JSIM, simulation models is shown in Figure 3.2. Java provides built-in foundation classes such as Thread, and Applet. On this basis, we build our simulation classes such as Queue, Statistic and Variate. A number of closely related classes then form packages, for example, queue, statistic and variate. Using these foundation packages complete simulation systems can be created.

19

Java

Java Foundation Classes and Packages

Java Simulation and Animation Classes and Packages

JSIM: Java Simulation and Animation Environment

Simulation Models

Figure 3.2: Relationships among Java, JSIM, and Simulation Models

Chapter 4 The JSIM Foundation Library

The JSIM library is a collection of Java classes which provide basic utilities for constructing both process interaction and event scheduling discrete event simulation. The class hierarchy of JSIM provides \common" methods to subclasses and saves substantial amount of coding. The basis of the JSIM environment is the foundation library which includes three packages: queue, statistic and variate, upon which we built a layer of two packages to support the two dorminant simulation strategies. On the top of these two layers is the qds package to facilitate query-driven simulation (see Figure 4.1).
Support Environment
qds

Event Scheduling
event

Process Interaction
process

Foundation Library
queue, statistic, variate

Figure 4.1: JSIM Simulation and Animation Environment In building our library, we followed both the process interaction paradigm and the event scheduling paradigm. Java's built-in support for threads helped us in implementing a true process interaction paradigm. The simulation entities have 20

21 been coded as threads and are truly independent and may perform actions on their own. In order to facilitate the construction of simulation models following the event scheduling paradigm, we coded several classes into the JSIM library. For each event, a method needs to be coded to carry out any state changes as well as schedule future events.
jsim

queue

statistic

variate

event

process

qds

Figure 4.2: Packages in JSIM Library The JSIM library consists of six packages: queue, variate, statistic, event, process, and qds (see Figure 4.2). In the gure, dashed-line boxes represents Java built-in classes, solid-line boxes JSIM packages or classes. They are summarized as following: - The queue package implements list management facility. It includes classes for implementing four types of queues: FIFO queue, LIFO queue, priority queue and temporal queue.
queue variate

- This package includes random number generators and many commonly used random variate generators.
statistic

- The statistic package implements facilities to gather, analyze, and report results of simulation executions.

22 event - The event package provides classes for realizing the event scheduling simulation paradigm. - This package includes classes to implement process interaction simulation paradigm (see (Nair, 1997) for details).
process

- This package implements query driven simulation for retrieving and storing simulation results and model meta data in database (again see (Nair, 1997) for details).
qds

In this chapter we discuss the rst three packages in detail and the event package in a seperate chapter. Java code for the important classes is also given; this includes class member data, class member methods (signature only), and constructors as well.
4.1 Queue Handling Facilities

The queue package includes the following classes: Queue, FIFO Queue, LIFO Queue, PriorityQueue, TemporalQueue, BQ Node, PQ Node, TQ Node, EmptyQueueException, and FullQueueException. The class hierarchy is shown in Figure 4.3.
4.1.1 Queue

class de nes an abstract class serving as a base class, from which FIFO Queue (First-In, First-Out queue), LIFO Queue (Last-In, First-Out queue), PriorityQueue, and TemporalQueue are derived.
Queue abstract class Queue extends Object { protected int size = 0; protected int capacity = (int)1E31 - 1;

23
Object Runtime Exception

PQ_Node

BQ_Node

Queue

EmptyQueue Exception

FullQueue Exception

TQ_Node

FIFO

LIFO Queue

Priority Queue

Temporal Queue

Figure 4.3: Class Hierarchy of queue Package


public boolean empty (); public boolean full (); public int length (); public abstract void enqueue (Object item) throws FullQueueException; public abstract Object dequeue () throws EmptyQueueException; public abstract Object front () throws EmptyQueueException; public abstract void clear (); }; // Queue

In the Queue class, member data size de nes number of elements in the queue, and capacity the maximum number of elements the queue can hold. The default capacity is in nite. We de ne two types of exceptions in the queue package: EmptyQueueException and FullQueueException. Both derive from Java's builtin class RuntimeException. EmptyQueueException is thrown when an attempt is made to return (dequeue and/or examine front ) an element from an empty queue; and FullQueueException is thrown when an attempt is made to insert (enqueue) an element into a full queue (the size of a queue has reached its capacity). The empty method determines whether the queue is empty. If the queue is empty, it returns true, otherwise, false. The full method determines whether the queue is full, and returns a boolean value. The length method returns the number

24 of elements in the queue. The clear method clear the queue by removing all its elements and setting its size to zero. The enqueue method inserts an element into the queue. There are multiple implementations of enqueue for PriorityQueue and TemporalQueue depending on the number of parameters (see Table 4.1). For instance, PriorityQueue implements enqueue (Object item) method by using the default priority. In addition, it also implements the following de nition:
public void enqueue (Object item, int priority) throws FullQueueException;

Table 4.1: Implementations of enqueue Methods for Queues FIFO LIFO Priority
enqueue (item)

Yes Yes

enqueue (item, priority)

enqueue (item, time, priority)

+Default Priority Yes Yes

Temporal +Default Priority +current time +current time

Methods front and dequeue are abstract, so they must be explicitly implemented in subclasses. The front method returns the rst entity in the queue, but does not remove it. The dequeue method removes and returns the entity at the front of the queue. Since both methods returns entities of type Object, one may need to cast the entities based on the application. Java's object-oriented features facilitate code re-usability. The implementation of the empty, full and length methods are common to all subclasses, so the subclasses

25 inherit these methods without further implementation. However, all of the abstract methods must be implemented in the subclasses.
4.1.2 FIFO Queue

A FIFO Queue e ciently implements a First-In, First-Out list, and is derived from the base class Queue.
public class FIFO_Queue extends Queue { private BQ_Node head; private BQ_Node tail; public FIFO_Queue (); public FIFO_Queue (int initialCapacity); public void enqueue (Object item) throws FullQueueException; public Object dequeue () throws EmptyQueueException; public Object front () throws EmptyQueueException; public void clear (); }; // FIFO_Queue

is implemented as a singly linked list. Each node in the linked list, BQ Node, has a data member of type Object and a reference to the next node. FIFO Queue has head and tail. Two constructors are used to create FIFO Queue objects. The rst constructor takes no parameter and creates a FIFO Queue instance with default in nite capacity, while FIFO Queue (int initialCapacity) creates an instance with nite capacity. As stated above, the class implements the enqueue (Object item) abstract method de ned in the base class. The enqueue method always inserts an element at the tail, while the dequeue method always removes the element at the head of the queue. In addition, the class implements other abstract methods from the base class: front and clear.
FIFO Queue

26
4.1.3 LIFO Queue

Derived from Queue, a LIFO Queue implements a Last-In, First-Out list. Java has its built-in LIFO queue (Stack) which is implemented from Java's built-in Vector class. It assumes in nite capacity and its functionality is limited. In order to be consistent with other queue classes in our simulation library and to be more exible and more powerful, we implement our own LIFO queue class.
public class LIFO_Queue extends Queue { private BQ_head; public LIFO_Queue (); public LIFO_Queue (int initialCapacity); public void enqueue (Object item) throws FullQueueException; public Object dequeue () throws EmptyQueueException; public Object front () throws EmptyQueueException; public void clear (); }; // LIFO_Queue

has only one reference, head. Both insertion and deletion happen at the head. Besides inheriting \regular" methods (empty, full, and length) from the based class, it implements all the abstract methods, enqueue, dequeue, front and clear). FIFO and LIFO queues are generally used to realize service policy in simulation. A client is served according to the service policy when arriving. Service policy for the FIFO queue is modeled by adding an incoming customer to the end of the queue with the enqueue method and for LIFO queue by adding an incoming customer to the front of the queue with the same method. In either case, customers are removed from the front of the queues with the dequeue method.
LIFO Queue

27
4.1.4 Priority Queue

The PriorityQueue class maintains a priority queue using a self-adjusting binary tree (a splay tree). The implementation is based on Daniel Sleator's C implementation of splay trees (http://gs213.sp.cs.cmu.edu/prog/splay/). The data structure was rst proposed by Sleator and Tarjan (Sleator & Tarjan, 1985). The performance of splay trees is nearly optimal based on Jones' research (Jones, 1986). Since Java is currently an interpreted language and its performance is not as fast as compiled languages such as C and C++, it is important to choose the right data structures to implement the library (Just-in-time and native code compilers will also substantially improve performance).
public class PriorityQueue extends Queue { private PQ_Node root; PriorityQueue (); PriorityQueue (int initialCapacity); void enqueue (Object item) throws FullQueueException; void enqueue (Object item, int priority) throws FullQueueException; public Object dequeue () throws EmptyQueueException; public Object front () throws EmptyQueueException; public void clear (); private void splay (PQ_Node node); private void splay (); }; // PriorityQueue public public public public

within a PriorityQueue has four data members, an item, a priority, and references to left and right children. The PriorityQueue class inherits and implements methods from the base class. As before, two constructors are provided, PriorityQueue () and PriorityQueue (int initialCapacity). The class has two enqueue methods. The enqueue (Object item, int priority) method inserts an entity according to its associated priority. The smaller the value, Each
PQ Node

28 the lower the priority. Java's Thread class de nes 1 as the minimum priority, 5 the medium and 10 the maximum. The enqueue (Object item) method takes one parameter and calls enqueue (Object item, int priority) method by using default priority. In addition, the splay (PQ Node node) method splays the tree when inserting nodes while the splay () method is used when a deletion operation is performed.
public void enqueue (Object item) throws FullQueueException { this.enqueue (item, Thread.NORM_PRIORITY); }; // enqueue

4.1.5 Temporal Queue

is also implemented as a splay tree. The di erence is that PriorityQueue orders elements solely on values of priority while TemporalQueue orders rst on time and then on priority if two entities have the same time values. TQ Node is derived from PQ Node adding a time data member.
TemporalQueue public class TQ_Node extends PQ_Node { protected double time = 0.0; TQ_Node (); TQ_Node (Object item, double time, int priority); public double getTime (); int compare (TQ_Node item); }; // TQ_Node \begin{verbatim} public class TemporalQueue extends Queue { private TQ_Node root; public TemporalQueue (); public TemporalQueue (int initialCapacity);

The

29
public void enqueue (Object item) throws FullQueueException; public void enqueue (Object item, int priority) throws FullQueueException; public void enqueue (Object item, double time, int priority) throws FullQueueException; public Object dequeue () throws EmptyQueueException; public Object front () throws EmptyQueueException; public void clear (); private void splay (TQ_Node node); private void splay (); }; // TemporalQueue

This class implements three enqueue methods, The rst two enqueue methods call the last method by setting parameters to their defaults.
public void enqueue (Object item) throws FullQueueException { this.enqueue (item, (double) System.currentTimeMillis (), Thread.NORM_PRIORITY); }; // enqueue public void enqueue (Object item, double time) throws FullQueueException { this.enqueue (item, time, Thread.NORM_PRIORITY); }; // enqueue

Priority and temporal queues can be used to realize lines ordered by priority, and to implement Future Event Lists. For instance, we can insert an incoming process or event into a Future Event List (FEL), implemented as a temporal queue, based on its process activation or event time.
4.2 Statistical Analysis Capabilities

In general, we collect two types of simulation data: observational data and timepersistent data. Observational data are equally weighted values which do not persist over a period of time. The recording of observational data is triggered by signi cant events such as customer arrivals or departures. For example, service time of a

30 customer is observational data. If we want to calculate the mean service time, we can simply take the average of all recorded observations of service time by the number of observations. The formula for computing the mean of observational statistic is:

x = 1=n

n X xi i=0

(4.1)

Time-persistent data are values which persist over a period of time, and the values are weighted by the period of time they persist. A change of value of timepersistent variable triggers the recording of data. An example of time-persistent statistic is the number of entities in a queue. If the queue length changes, we record the old queue length and length of time length for which this queue length persisted. If xi denotes ith queue length and ti the period of time this queue length lasts. The average queue length is computed using the formula given below:
n X xiti x = 1=T i=0

(4.2)

The statistic package includes ve classes: Statistic, SampleStat, TimeStat, BatchStat and Format. They provide capabilities to collect, calculate and analyze statistics on sample data, display summary results of simulation runs and facilitate statistical decision making. The class hierarchy in this package is shown in Figure 4.4: The Statistic class is an abstract base class. Both SampleStat and TimeStat are derived from Statistic. SampleStat is used to collect and analyze observational data; TimeStat time-persistent data. BatchStat, derived from SampleStat, collects and analyzes batch statistic. Format class, like printf function in C, is used to format output. It was developed by Cornell and Hosrstmann (Cornell, & Horstmann, 1996).

31
Object

Format

Statistic

SampleStat

TimeStat

BatchStat

Figure 4.4: Class Hierarchy of statistic Package


4.2.1 Statistic

The Statistic class provides basic utilities to collect, analyze, and report data. It is de ned as an abstract base class from which other subclasses may be derived.
public abstract class Statistic extends Object { protected double nobs; protected double lastTime; protected double minValue; protected double maxValue; protected double sum; protected double sumSquares; protected String name; protected final static double MAX_DOUBLE = java.lang.Double.MAX_VALUE; protected final static boolean MONITOR = false; public Statistic (String name); public double min (); public double max ();

32
public double public double public double public double protected double public double public int public void public static public void }; // Statistic mean (); variance (); rms (); stdDev (); tValue (double p, double df); confidence (double level); samples () printStat (); void printLabel (); resetStat (double time);

The min, max, mean, variance, rms, stdDev, and samples methods return the minimum, the maximum, the mean, variance, root mean square, and standard deviation of recorded sample data and number of observations, respectively. Our statistic package also includes utilities to make statistical inference upon simulation data. tValue (double p, double df) returns t-value (the upper pth quantile of the student t distribution) given p and degree of freedom df. Given interval or p, confidence (double level) method returns con dence intervals for the data. The level parameter must be less than one (e.g., .95 represents 95% con dence). The printLabel and printStat methods print labels and summary simulation results respectively. The resetStat (double time) is used to reset statistic counters and to set lastTime to time.
4.2.2 Sample Statistic

The sample statistic class, called SampleStat, is used to collect, analyze, and display sample observational data. It extends the Statistic class, and adds a tally method to collect observational data.
public class SampleStat extends Statistic {

33
public SampleStat (String name); public SampleStat tally (double val); }; // SampleStat

4.2.3 Time Persistent Statistic

While SampleStat gathers statistics on observational data, TimeStat collects statistics on time-persistent data. It is derived from the base class Statistic, but adds an accumulate method to gather time-persistent data.
public class TimeStat extends Statistic { public TimeStat (String name); public TimeStat accumulate (double val, double time); }; // TimeStat

4.2.4 Batch Statistic

The BatchStat class extends batched runs.

SampleStat

and is used to compute statistics on

public class BatchStat extends SampleStat { private int batchSize; private SampleStat stat = new SampleStat ("In batch"); public BatchStat (String name, int batchSize); public void batch (double val); }; // BatchStat

The batch means method divides a long run into k sub-runs and calculate means for each batch and a grand mean for the entire run. The constructor BatchStat (String name, int batchSize) is used to initialize the class instance, assigning name and setting batchSize. batch (double val) calls the tally method of its own SampleStatistic object stat, then determines whether stat.nobs is greater than the batchSize. If it is, it tallies the mean of the batch.

34
4.3 Random Number and Variate Generators

The variate package provides random number and random variate generators. The basic random number generator implemented in jsim is a multiplicative Linear Congruential Generator, called LCGRandom. The recursive formula for LCG is:

Zi = aZi 1 % m

(4.3)

where the multiplier a is 75 and the modulus m 231 1. The LCG random number generator has a very long period, and it has been statistically proven that it provides good inter-sample independence (Law, & Kelton, 1991). It produces random numbers in the range of (0, 1). The Variate class serves a base class for all other variate generators. It uses the LCGRandom random number generator. However, users of this simulation library can easily change to use some other random number generator, such as Java's Random class, by modifying the code of Variate class.
public class Variate extends Object { private LCGRandom rand; protected Variate (int i); public double gen (); };

The class constructor sets the stream, and the gen method returns the next random number generated. We have implemented 14 continuous random variates and 8 discrete random variates (See Figure 4.5). The continuous random variate generators are Beta, Cauchy, ChiSquare, Erlang, Exponential, F Distribution, Gamma, HyperExponential, LogNormal, Normal, StudentT, Triang, Uniform, and Weibull. The discrete

35 random variate generators are Binomial, DiscreteProb, Geometric, HyperGeometric, NegativeBinomial, Poisson, Randi. All the random variate generator classes extend the Variate class and use its LCG generator to implement their gen methods. For example, the de nition of the Exponential class is as following:
public class Exponential extends Variate { private double mu; // mean public Exponential (double mu, int i); public double gen (){ return - mu * Math.log (super.gen ()); }; // gen }; // Exponential

The constructor Exponential (double mu, int i) initializes the variable mu and its super class with seed array index i. The gen method returns an exponential random variate. The algorithms for these random variate generators can be found in simulation works by Fishman (1978), Law and Kelton (1991) and Bratley, Fox, & Schrage (1987).
4.4 Test of Random Number Generators

We performed the test to validate the uniformity of random numbers generated. The test we implemented is the Kolmogorov-Smirnov goodness-of- t test (Bank, & Carson, 1984; Daniel, 1990; Law, & Kelton, 1991). It is used to determine the degree of agreement between the distribution of generated random numbers and the theoretical uniform distribution. To apply Kolmogorov-Smirnov test we are concerned with two cumulative distribution functions: a hypothesized cumulative distribution and the observed cumulative distribution. F(x) designates the theoretical uniform

36 distribution, the probability that the value of the random variable X is less than or equal to x for a given x. The Kolmogorov-Smirnov goodness-of- t test compares cdf F(x) of the uniform distribution to the empirical cdf, Sn (x), of the sample of n observations to determine if F(x) = S(x). If the samples drawn from a random number generator are R1, R2, ..., Rn , the empirical distribution function Sn(x) is de ned by:
0 Sn(x) = numberofRis x n

(4.4)

The Kolmogorov-Smirnov test is based on the statistic:

D = maxjF (x) Sn(x)j

(4.5)

That is, the largest deviation between F(x) and Sn (x) over the range of the random variable. The Kolmogorov-Smirnov test follows the following steps for testing against a uniform distribution (Bank, & Carson, 1984; Law, & Kelton, 1991): 1. Rank data from the smallest to the largest; 2. Compute D+ and D :
N i D+ = maxf N Rig i=1 N D = maxfRi i N 1 g i=1

(4.6) (4.7)

3. Compute D = max (D+ , D ); 4. Compute

pn Dtest = ( n + 0:12 + 0:11 )D

(4.8)

5. Determine the critical value, D1 ;

37 6. Make statistical decision. If Dtest > D1 , we reject the null hypothesis, that is, the samples are not drawn from the uniform distribution. If Dtest D1 , we accept the null hypothesis and conclude that there is no di erence between the empirical distribution and the theoretical uniform distribution. The KS Test in variate package of jsim library implements KolmogorovSmirnov test of our LCGRandom random number generator.
public class KS_Test { private LCGRandom rng; private int n; double maxD; double testValue; private double dPlus; private double dMinus; private double randArray

// // // // // // ]; //

random number generator number of observations D = max (D+, D-) Test value calculated D+ Dhold generated random numbers

public KS_Test (LCGRandom rng, int n); public void test (); public void insertionSort (); }; // KS_Test

Table 4.2: Critical Values for KS Test 0.850 0.900 0.950 0.975 0.990 1.138 1.224 1.358 1.480 1.628 The constructor initialize data for an KS Test object. The method insertionSort sorts the generated random numbers in order from the smallest to the largest in order to obtain the cfd for the sample random numbers. The test method performs the Kolmogorov-Smirnov test based on step 1 to step 4 above. We tested LCGRandom against the critical values from Law & Kelton's work (1991). The critical values are shown in Table 4.2.

38 Using KS Test, we tested all ten seeds for the LCGRandom and at = 0:15 level by generating 1000 samples (see also Table 4.2). We failed to reject the null hypothesis that LCGRandom produces uniformly distributed random numbers. The results are shown in Table 4.3. A whole battery of tests (uniformity, independence, etc.) could have been applied, but we chose to use the following quick method (Law, & Kelton, 1991). If the rst seed, SEED 0], is set to 1, then the 1000th random number generated should be 522,329,230. Table 4.3: Summary of KS-Test for LCG Seed 428956419 1954324947 1145661099 1835732737 794161987 1329531353 200496737 633816299 1410143363 1282538739 Dmax 0.0222922 0.0186856 0.032522 0.0131061 0.0148092 0.0269069 0.0120573 0.010573 0.00195252 0.0201469 Dtest 0.707692 0.593197 1.03245 0.41607 0.470136 0.854194 0.382775 0.56857 0.0619851 0.639587 0.15 0.15 0.15 0.15 0.15 0.15 0.15 0.15 0.15 0.15

As we can see that KS test is useful in testing random number generator, in addition, it can be generalized to test other variate generators.

Figure 4.5: Class Hierarchy of variate Package

Object

Variate

LCGRandom

Random

LCG_Test

KS_Test

Bernoulli

Binomial

DiscreteProb

Geometric

Hyper Geometric

Negative Binomial

Poisson

Randi

Beta

Erlang

Exponential

Gamma

Normal

Unifom

Weibull

39

Chapter 5 Event-Scheduling Facilities

The event is built upon the JSIM foundation library which consists of the three packages we introduced above. It is used to realized the implementation of event scheduling simulation paradigm. There are three classes in this package: Entity, Event, and Scheduler. Figure 5.1 shows the class hierarchy of the package.
Object

Entity

Event

Scheduler

Figure 5.1: Class Hierarchy of event Package


5.1 Entity

inherits from the Java Object class and represents an entity in discrete-event simulation such as a customer, patient or passenger.
Entity public class Entity extends Object { private long counter = 0; private long entityId; private double createTime;

40

41
public Entity (double createTime); public long getEntityId (); public long getCreateTime (); }; // Entity

The constructor initializes an Entity object by setting its createTime, and assigning its entityId. The getEntityId returns its entityId, and getCreatetime the time when it was created.
5.2 Event

The Event class has three data members: counter, eventId, and entity associated with the event. The abstract method occur is subclass dependent. Each derived subclass has to implement the method.
public abstract class Event private long private long protected Entity { counter = 0; eventId; entity;

public Event (Entity ent); public abstract void occur (); }; // Event

5.3 Scheduler

The Scheduler class is the essential component of this package. It is used to schedule future events, activate and execute future events by their activation time and advance the simulation clock.
public class Scheduler { private static double currentTime; private final static int MID_PRIORITY = Thread.NOR_PRIORITY;

42
private static TemporalQueue = eventList; public static void schedule (Event event, double timeDelay); public static void schedule (Event event, double timeDelay, int priority); public static void startSim (); public double currentTime (); }; // Scheduler

The Scheduler class has a variable to represent a simulation clock and an event list to schedule events. The schedule methods inserts an event into the event list on the basis of its relative occurrence time and its priority. The rst method assumes all events have the same priority and the second method places an event on the FEL rst by its event time and next by priority. The startSim method controls the whole simulation process. It continues pulling the imminent event from the FEL, updating the simulation clock and executing the event until there are no more events on the FEL. The implementation for the method is as following:
public void startSim () { Event nextEvent; TQ_Node tpNode; while (! eventList.empty () ) { // remove the imminent event from the FEL tpNode = (TQ_Node) eventList.dequeue (); // update the simulation clock currentTime = tpNode.getTime (); // execute the event nextEvent = (Event) tpNode.getItem (); nextEvent.occur (); }; // while }; // startSim

43 Finally, the method currentTime of the class returns the current simulation time.

Chapter 6 Example

We use the classical bank example, an M/M/1 queuing system, which we have referred to test and demonstrate the capabilities of the JSIM simulation library. The example exercise most of the capabilities provided by foundation library (queue, statistic and variate packages) as well as the event. The same example has also been coded using the process interaction package (see (Nair, 1997) for details). The bank model implements an M/M/1 queuing system. It has one queue, and both its service time and its inter-arrival time follow an exponential distribution. The output data we are interested include average delay in queue and average queue length. The bank model implemented following the event-scheduling strategy is illustrated as below:

System state Number of customers waiting in the queue at time t Entities Events
Availability of the teller Customer Customer arrival Customer departure

Figure 6.1 shows the event graph (Schruben, 1983, 1995) for a simple bank system. Each customer is created at Ta time interval if the simulation is not completed (condition 1). If teller is free when a customer arrives (condition 2), a departure event for the customer after being served for Ts time is scheduled. When a customer 44

45
C1 C3 Ta C2 Departure

Ts Ts Arrival

Conditions: C1: Current time is less than the time to stop simulation C2: Teller queue is empty C3: Teller queue is not empty Time Consumption Variables: Ta: Customer inter-arrival time Ts: Service time

Figure 6.1: Event Graph for Simple Bank System departs, if the teller queue is not empty (condition 3) a departure event for the next customer on the queue after being served for Ts time is scheduled Following we examine each event and its algorithm. The algorithm for customer arrival is as following:
Arrival: If (teller is not free) { Place the customer entity into teller queue; } else { Obtain the teller; Schedule a departure event for the current customer; }; //if if (current time < stop time) { Create new customer entity; Schedule an arrival event for the customer; }; // if

When an arrival event happens, whether the teller is free is rst checked. If the teller is busy, the customer joins the teller queue; otherwise, the teller is freed and the departure event for the customer is scheduled. At the end of arrival routine, if the simulation is not completed, another arrival event is generated and scheduled. The algorithm for the departure event is presented as following:

46
Departure: if (teller queue is not empty) { Take the next customer entity from teller queue; Schedule a departure event for the customer; } else { Free the teller; };

When a departure event occurs, it rst of all checks whether the teller queue is empty. If it is not empty, the customer at the front of the queue is removed and a departure event for the customer is scheduled. If the queue is empty, the teller is set free. The bank model implemented under the event scheduling paradigm consists of four objects. They are teller(s), customer(s), a FIFO queue and a scheduler. The customers are represented as Entity. The relationships between these objects are represented in Figure 6.2 using Object Modeling Technique (OMT) diagram (Rumbaugh et al, 1991). After setting all parameters, the Bank schedules the arrival event for a customer and starts the simulation.
public class Bank { // Input Parameters final static double final static double final static long final static double

meanInterArrival meanService maxCustomers NOW

= 10.0; // 1 / lamda = 8.0; // 1 / mu = 30000; = 0.0;

// Model Components static FIFO_Queue tellerQueue = new FIFO_Queue (); static boolean tellerFree = true; static Entity customerInService = null; // Distributions

47

Arrival

Departure

Event

Queue

Bank

Figure 6.2: Bank Simulation Example (Event Scheduling)

Teller

Scheduler

Entity

48
static Exponential expService = new Exponential (meanService, 0); static Exponential expInterArrival = new Exponential (meanInterArrival, 1); // Statistical Collectors static SampleStat waitStat = new SampleStat (" Waiting Time "); static SampleStat serviceStat = new SampleStat (" Service Time "); static SampleStat residenceStat = new SampleStat (" Total Residence Time "); static SampleStat interArrivalStat = new SampleStat (" InterArrival Time "); static TimeStat queueStat = new TimeStat (" Num in Queue "); public static void main (String argv ]) { Entity customer = new Entity (NOW); Arrival arrEvent = new Arrival (customer); Scheduler.schedule (arrEvent, NOW); System.out.println ("***Start simulation***"); Scheduler.startSim (); Statistic.printLabel (); waitStat.printStat (); serviceStat.printStat (); residenceStat.printStat (); queueStat.printStat (); interArrivalStat.printStat (); System.out.println ("H for Wq = " + waitStat.confidence (0.95)); System.out.println ("H for W = " + residenceStat.confidence (0.95)); System.out.println ("H for Lq = " + queueStat.confidence (0.95)); }; // main }; // Bank

The model has two critical events that must be coded, namely Arrival, and Departure. Both events are derived from the Event class. An arrival event may schedule a departure event as well as a new arrival event. When a customer entity arrives at the bank, if the teller is busy, s/he joins the queue; otherwise, a departure event is scheduled for the current customer entity. If current simulation time is smaller than the stop time (or the number of customer is less than the maximum number of customer), the Arrival event schedules the next Arrival event.

49
public class Arrival extends Event { private static int numCustomers = 0; public Arrival (Entity customer) { super (customer); }; // Arrival public void occur () { double interArrivalTime; double serviceTime; numCustomers++; if ( ! Bank.tellerFree ) { Bank.queueStat.accumulate (Bank.tellerQueue.length (), Scheduler.currentTime ()); Bank.tellerQueue.enqueue (entity); } else { Bank.waitStat.tally (0.0); Bank.customerInService = entity; Bank.tellerFree = false; Departure depEvent = new Departure (entity); serviceTime = Bank.expService.gen (); Scheduler.schedule (depEvent, serviceTime); Bank.serviceStat.tally (serviceTime); }; // if // Schedule the next customer arrival event if (numCustomers < Bank.maxCustomers) { Entity customer = new Entity (Scheduler.currentTime ()); Arrival arrEvent = new Arrival (customer); interArrivalTime = Bank.expInterArrival.gen (); Scheduler.schedule (arrEvent, interArrivalTime); Bank.interArrivalStat.tally (interArrivalTime); }; // if }; // occur }; // Arrival

The Departure event schedules a new departure event for next customer entity in the queue. If the queue is empty, the teller is freed.

50
public class Departure extends Event { public Departure (Entity customer) { super (customer); }; // Departure public void occur () { double currentTime = Scheduler.currentTime (); Bank.residenceStat.tally (currentTime Bank.customerInService.getCreateTime ()); Bank.queueStat.accumulate (Bank.tellerQueue.length (), currentTime); if ( ! Bank.tellerQueue.empty() ) { Bank.customerInService = (Entity) Bank.tellerQueue.dequeue (); double waitTime = currentTime Bank.customerInService.getCreateTime (); Bank.waitStat.tally (waitTime); Departure depEvent = new Departure (Bank.customerInService); double serviceTime = Bank.expService.gen (); Scheduler.schedule (depEvent, serviceTime); Bank.serviceStat.tally (serviceTime); } else { Bank.tellerFree = true; }; // if }; // occur }; // Departure

Table 6.1: Summary of Bank Sample Run Name Service time Wait time Residence time Queue length Inter-arrival time Num of Obs 70000 70000 70000 70000 Min 0.000 0.000 0.000 0.000 0.000 Max 92.774 321.197 328.254 40.000 102.374 Mean 8.055 31.848 39.903 3.169 10.048 Variance 64.729 1559.005 1625.371 18.546 100.311 Std dev 8.045 39.484 40.316 4.306 10.016

For the rst execution of the model, we simulated 70,000 customers with the mean service time of 8.0 and the mean inter-arrival time of 10.0. We collected the

51 simulation data using SampleStat and the summary results are shown in Table 6.1. The simulation also calculates and outputs the con dence interval half width for both waiting time and residence time at 0.95 con dence level. They are 0.350114 and 0.357489 respectively. Table 6.2: Summary of Bank Batch Run Name Service time Wait time Residence time Inter-arrival time Num of Obs 30000 30 (batches) 30 (batches) 30000 Min 0.000 15.915 23.862 0.000 Max 79.115 58.292 66.824 102.374 Mean 8.122 34.129 42.241 10.043 Variance 66.139 120.688 125.181 100.456 Std dev 8.133 10.986 11.188 10.023

For the second execution, we completed 30000 customers given the same mean service time and mean inter-arrival time. We performed batch runs (30 batches of each 1000) for wait time and residence time and collected batch means for the two variables. The execution results are presented in Tables 6.2. The con dence interval half width for wait time and residence time at 0.95 con dence level are 5.0465 and 5.13958 respectively.
Reject H0 Do not reject H 0 Reject H0

/2

/2

-t /2

t /2

Figure 6.3: Standard t-distribution We use the student t-test to determine how close the sample mean X obtained from simulation execution is to the theoretical mean (see Figure 6.3). The student t-distribution is de ned as a distribution with a mean of 0 and a standard deviation

52 of 1. If is the error we make to reject the true null hypothesis (H0) that X = , then 1 (called con dence level) is de ned as the probability that the absolute di erence between sample mean and theoretical mean is less than or equal to H, the con dence interval half-width (MacDougall, 1987):

P jX

j H] = 1

(6.1)

The probability of the theoretical mean falling in the range of X H; X + H ] is 1 . X H; X + H ] is called the con dence interval. H is a function of random variable, and is de ned as:

H =t

=2;N 1s=

(6.2)

where t =2;N 1 is the upper =2 quantile for the student t distribution with N 1 degree of freedom and the standard deviation of s. Let us now look at our simulation results. For M/M/1 queue, given the mean service time and mean inter-arrival time, we can calculate the theoretical mean waiting time of customers in the queue denoted by wq and the theoretical mean residence time in the system denoted by w using following formula (Banks, & Carson, 1988, p.201):

w = 1 = (1 1 ) wq = (

(6.3)

(6.4) ) = (1 ) where = 1/mean inter arrival time, = 1/mean service time, and = = . Plug our data, mean inter arrival time = 10.0 and mean service time = 8.0, into the formula, we get: wq = 32 and w = 40. The simulation of 70000 customer completions returns data as shown in Table 6.1 summarized here:

53

P (1 ) = 0:95 Sample waiting time mean = 31.848 Sample residence time mean = 39.903 Con dence half width H for waiting time = 0.350114 Con dence interval half width H for residence time = 0.357489 Con dence interval for waiting time = 31:848+0:350114 Con dence interval for residence time = 39:903+0:357489 Therefore, there are 95 percent chances that the true waiting time mean (theoretical mean wq = 32) is given by 31:597886; 32:198114] and that the true residence time mean (theoretical mean w = 40) is within the range 39:54551; 40:260489].

Chapter 7 Conclusions and Future Work

The focus of my project has been on the design, implementation and testing of the foundation library (including queue, statistic and variate packages) and the event package. In addition, I also assisted my colleague, Rajesh Nair, to develop the virtual scheduler for the process package. The foundation library is developed to be general and exible in order for others to easily develop their own simulation systems on top of it. To demonstrate the capabilities of our simulation library, we have developed the bank simulation model following both event scheduling and process interaction paradigm (see also Nair's thesis (Nair, 1997)). Even though our library is relatively small, it contains useful utilities su cient for easily constructing moderately complex simulation models. As the part of an ongoing project (Nair, Miller, & Zhang, 1996; Miller, Nair, Zhang, & Zhao, 1997), this project only implements simulation utilities. An animation component, graphic designer, and database access facility will de nitely enhance JSIM, and allow developers design simulation models using graphic designer which will then generate codes, run simulation and animation models, and store simulation results into database. In addition, we only tested LCG random number generator using KS test in this project. However, KS test can be easily generalized to test other random variate generators.

54

Bibliography

Bank, J, & Carson, J.S. (1984). Discrete-event system simulation. Englewood Cli s, NJ: Prentice Hall. Bolier, D., & Eliens, A. (1995). SIM: A C++ library for discrete event simulation. Unpublished manuscript. Bratley, P., Fox, B.L., & Schrage, L.E. (1987). A guide to simulation. New York: Springer-Verlag. Brown, R. (1988). Calendar queue: A rst O(1) priority queue implementation for the simulation event set problem. Communications of the ACM, 31(10), 1220-1227. Buss, H.A., & Stork, K.A. (1996). Discrete event simulation on the World Wide Web using Java. Proceedings of the 1996 Winter Simulation Conference (pp. 781-785). Coronado, CA. Carson, J.S. (1993). Modeling and simulation worldviews. Proceedings of the 1993 Winter Simulation Conference (pp. 18-23). Los Angles, CA. Cornell, G., & Horstmann, C.S. (1996). Core Java. Mountain View, CA: SunSoft Pr. Dahl, O.J., , Myhrhaug, B, & Nygaard, K. (1970). Norwegian Computing Center.
Common base language.

Oslo:

Daniel, W.W. (1990). Applied nonparametric statistics (2nd ed.). Boston: PWSKent Publishing Co. 55

56 Evans, J.B. (1988). Structures of discrete event simulation: An introduction to the engagement strategy. Chichester, England: Ellis Horwood Limited. Fishman, G.S. (1978). Principles of discrete event simulation. New York: John Wiley & Sons. Fishwick, P.A. (1992). SimPack: Getting started with simulation programming in C and C++. In J.J. Swain, D. Goldsman, R. Crain, & J.R. Wilson (Eds.), Proceedings of the 1992 Winter Simulation Conference (pp. 154-162). Arlington, VA. Fishwick, P.A. (1995). Simulation model design and execution: Building digital worlds. Englewood Cli s, NJ: Prentice Hall. Fishwick, P.A. (1996). Web-based simulation: Some personal observations. Proceedings of the 1996 Winter Simulation Conference (pp. 772-779). Coronado, CA. Flanagan, D. (1996). Java in a nutshell: A desktop quick reference for Java programmers. Bonn: O'Reilly & Associates, Inc. Gordon, G. (1978). System simulation (2nd ed). Englewood Cli s, NJ: Prentice Hall. Grunwald, D.C. (1991). A User's guide to AWESIME: An object oriented parallel programming and simulation environment. Boulder, Colorado: Department of Computer Science, University of Colorado. Grunwald, D.C. (1993). User's guide to AWESIME-II: A widely extensible simulation environment. Boulder, Colorado: Department of Computer Science, University of Colorado. Halfhill, T.R. (1997). Today the web, tomorrow the world. Byte. 22(1): 68-80.

57 Jones, D.W. (1986). An empirical comparison of priority-queue and event-set implementations. Communications of the ACM, 29(4): 300-311. Kreutzer, W. (1986). System simulation: Programming styles and languages. Sydney: Addison-Wesley. Law, A.M., & Kelton, W.D. (1991). Simulation modeling & analysis (2nd ed.). New York: McGraw-Hill. Lehmer, D.H. (1951). Mathematical methods in large-scale computing units. Proceedings of the Second Symposium on Large-Scale Digital Computing Machinery (pp. 141-146). Cambridge, MA: Harvard University Press. Lomow, G. & Baezner, D. (1990). A tutorial introduction to object-oriented simulation and Sim++. In O. Balci, R.P. Sadowski, & R.E. Nance (Eds.), Proceedings of the 1990 Winter Simulation Conference (pp. 149-153). New Orleans, Louisiana. MacDougall, M.H. (1987). Simulation computer systems: Techniques and tools. Cambridge, MA: MIT Press. Markowitz, H.M., Kiviat, P.J., & Villaneuva, R. (1987). Simscript II.5 Programming Language. Los Angeles: CACI, Inc. McGraw, G., & Felten, E. (1997). Java security and type safety. Byte. 22(1): 63-64. Miller, J.A., Rajesh, S.N., Zhang, Z., & Zhao, H. (1997). JSIM: A Java-based simulation and animation environment. Submitted to Annual Simulation Conference, Atlanta, GA. April 1997. Miller, J.A., & Weyrich, O.R. (1989). Query driven simulation using SIMODULA. Proceedings of the 22nd Annual Simulation Symposium, (pp. 167-181). Tampa, Florida.

58 Miller, J.A., Weyrich, O.R., Potter, W.D., & Kessler, V.C. (1996). The SIMODULA/ OBJECTR query driven simulation support environment. In Leonard-Zobrist (Ed.), Progress in Simulation, Vol.3. (to appear). Nair, R., Miller, J.A., & Zhang, Z. (1996). A Java-based query-driven simulation environment. Proceedings of the 1996 Winter Simulation Conference (pp. 786-793). Coronado, CA. Nair, R. (1997). JSIM: A Java-based simulation and animation environment (unpublished thesis). Naughton, P. (1996). Java handbook. Berkeley, CA: Osborne McGraw-Hill. Pegden, C.D., Sadowski, R.P., & Shannon, R.E. (1990). Introduction to simulation using SIMAN. New York: McGraw-Hill. Pritsker, A.A. (1986). Introduction to simulation and SLAM II. 3rd ed. New York: John Wiley & Sons. Rumbaugh, J., Blaha, M., Premerlani, W., Eddy, F., & Lorensen, W. (1991). Objectoriented modeling and design. Englewood Cli s, NJ: Prentice Hall. Schruben, L. (1983). Simulation modeling with event graphs. Communications of the ACM, 26: 957-963. Schruben, L (1995). Graphical simulation modeling and analysis using Sigma for Windows. Danvers, MA: Boyd and Fraser Publishing Co. Schwetman, H. (1988). Using CSIM to model complex systems. Proceedings of the 1992 Winter Simulation Conference (pp. 246-253). San Diego, VA. Schwetman, H. (1995). Object-oriented simulation modeling with C++/CSIM17. In C. Alexopoulos, K. Kang, W.R. Lilegdon, & D. Goldsman (Eds.), Proceedingso of the 1995 Winter Simulation Conference (pp. 529-533). Arlington, VA.

59 Schriber, T.J. (1991). An introduction to simulation using GPSS/H. New York: John Wiley & Sons. Seila, A.F. (1988). SIMMTOOLS: A software tool kit for discrete event simulation in Pascal. Simulation, 50(3), 93-99. Simon, H.A. (1969). The Science of the arti cial. Cambridge: MIT. Sleator, D.D., & Tarjan, R.E. (1985). Self-adjusting binary search trees. Journal of the Association for Computing Machinery. 32(3): 652-686. Stroustrup, B. (1991). The C++ programming language, (2nd ed). Reading, MA: Addison-Wesley. Sun Microsystems (1996?). Java language: An overview. http://www.javasoft.com/ doc/Overviews/java/java-overview-1.html. Watkins, K. (1993). Discrete event simulation in C. New York, NY: McGraw-Hill. Zeigler, B.P. (1976). Theory of modeling and simulation. New York: Wiley & Sons.

Appendix A Random Number and Variate Generators

A.1 LCG Random Number Generator

It is the basic random number generator. It is a multiplicative Linear Congruential Generator (LCG). The generator can be adjusted simply by changing the constants MULTIPIER and MODULUS. The complete generated stream of MODULUS numbers is split into MAX STREAMS (stream from 0 to MAX STREAMS - 1) by appropriate setting of the SEED array.
public class LCGRandom { public LCGRandom (int stream); public double gen (); public long igen (); }; // LCGRandom

The constructor public LCGRandom (int stream) constructs an LCG-based Random Number Generatora. The parameter stream is an integer from 0 to MAX STREAMS - 1. There are two methods in the class: gen and igen. public double gen () generates a real-valued random number in the range 0 to 1 and returns a double value. public long igen () generates an integer-valued random number in the range 0 to MODULUS - 1 and returns a long value.
A.2 Variate
public

60

61
class Variate { public Variate (int i); public double gen (); }; // Variate

The constructor public Variate (int i) constructs a random variate. The parameter int i is the stream. The public double gen () generates a random number in the interval 0 to 1 and returns a double value.
A.3 Bernoulli

The Bernoulli random variate generator.


public class Bernoulli extends Variate { public Beunoulli (double p, int i); public double gen (); }; // Bernoulli

The constructor public Bernoulli (double p, int i) constructs a Bernoulli random variate with p probability of success and i stream. The public double gen () method generates a random number from the Bernoulli distribution and return an integer number.
A.4 Beta

Beta random variate generator. The value of the random number generated is in the range of (0, 1). Beta = Gamma1=(Gamma1 + Gamma2).
public class Beta extends Variate { public Beta (double alpha, double beta, int i); public double gen (); }; // Beta

62 The public Beta (double alpha, double beta, int i) constructor constructs a Beta random variate for which alpha is the shape parameter for Gamma1, and beta for Gamma2. The method public double gen () generates a random number from a Beta distribution and the returned value is double.
A.5 Binomial

Binomial random variate generator.


public class Binomial extends Variate { public Binomial (int n, double p, int i); public double gen (); }; // Binomial

constructs a Binomial random variate with n number of trials and p probability of success. The method public double gen () generates a random number from binomial distribution.
public Binomial (int n, double p, int i)

A.6 Cauchy
Cauchy

class is used to generate a random number from a Cauchy distribution with mean mu and standard deviation sigma.
public class Cauchy extends Variate { public Cauchy (double mu, double sigma, int i); public double gen (); }; // Cauchy

The constructor constructs the Cauchy variate generator with mean mu, standard deviation sigma and stream i. The gen method generates an double-typed random number.

63
A.7 Chi Square

The ChiSquare class generates a random variate from Chi-Square distribution with n degrees of freedom.
public class ChiSquare extends Variate { public ChiSquare (int n, int i); public double gen (); }; // ChiSquare

A.8 Discrete Probability

The discrete probability random variate generator.


public class DiscreteProb extends Variate { public DiscreteProb (double cumProb public double gen (); }; // Erlang

], double value

], int i);

The constructor public DiscreteProb (double cumProb ], double value ], int i) constructs a Discrete Probability random variate. The parameter cumProb is the cumulative probability, value the value array, and i the stream.
A.9 Erlang

The Erlang class is used to generates a random number drawn from a k-stage Erlang distribution with mean mu.
public class Erlang extends Variate { public Erlang (double mu, int k, int i); public double gen (); }; // Erlang

64
A.10 Exponential

The Exponential random variate generator.


public class Exponential extends Variate { public Exponential (double mu, int i); public double gen (); }; // Exponential

The constructor constructs an Exponential random variate with the mean mu, and the i stream.
A.11 F Distribution

This variate generates a random number from the F distribution with degrees of freedom m and n for Chi-Square distributions chi1 and chi2.
public class F_Distribution extends Variate { public F_Distribution (int n, int m, int i); public double gen (); }; // F_Distribution

The parameter n to the constructor public F Distribution (int n, int m, int i) is the degrees of freedom for numerator Chi-Square and m the degrees of freedom for denominator Chi-Square.
A.12 Gamma

The Gamma random variate generator.


public class Gamma extends Variate { public Gamma (double beta, double alpha, int i); public double gen (); }; // Gamma

65 The constructor public Gamma (double beta, double alpha, int i) constructs a Gamma random variate with scale parameter beta and shape parameter alpha.
A.13 Geometric

The Geometric class implements a discrete geometric distribution with event probability p.
public class Geometric extends Variate { public Geometric (double p, int i); public double gen (); }; // Geometric

The parameters the stream i.

Geometric

constructor takes are event probability p and

A.14 Hyper-Exponential

The HyperExponential class generates a hyper exponentially distributed random number with mean mu and standard deviation sigma.
public class HyperExponential extends Variate { public HyperExponential (double mu, double sigma, int i); public double gen (); }; // HyperExponential

A.15 Hyper-Geometric

The variate generates a random number drawn from HyperGeometric distribution.

66
public class HyperGeometric extends Variate { public HyperGeometric (int m, int n, double p, int i); public double gen (); }; // HyperGeometric

The HyperGeometric class constructor takes four parameters. The rst parameter is the population m, the second number of items drawn from the population n, the third the probability of success to draw p, and the stream i.
A.16 Log Normal

The LogNormal class is used to generate a random number from LogNormal distribution.
public class LogNormal extends Variate { public LogNormal (double mu, double sigma, int i); public double gen (); }; // LogNormal

In addition to index parameter i for an array of streams, the constructor takes additional two parameters: the mean mu and standard deviation sigma.
A.17 Negative Binomial

The class generates a random number from the negative binomial distribution with probability of success p and number of success n.
public class NegativeBinomial extends Variate { public NegativeBinomial (double p, int n, int i); public double gen (); }; // NegativeBinomial

67
A.18 Normal

The Normal class generates a random number from a normal distribution. The rst parameter to the constructor is mean mu, the second standard deviation sigma, and the third the index for an array of streams i.
public class Normal extends Variate { public Normal (double mu, double sigma, int i); public double gen (); }; // Normal

A.19 Poisson

This class is used to generate a random number from a Poisson distribution with mean mu.
public class Poisson extends Variate { public Poisson (double mu, int i); public double gen (); }; // Poisson

A.20 Randi

The Randi class implements a random integer (discrete uniform) random variate generator.
public class Randi extends Variate { public Randi (int min, int max, int i); public double gen (); }; // Randi

68 The constructor public Randi (int min, int max, int i) constructs the class with parameters min as the minimum value, max the maximum value, and i the stream index.
A.21 Student t

The class implements a student t distribution with n degrees of freedom.


public class Student extends Variate { public Student (int n, int i); public double gen (); }; // Student

A.22 Triangular

The class Triangular is used to generate a random number from the Triangular distribution. The rst parameter to the constructor is the minimum value min, the second the peak of distribution mode, and the third the maximum value max.
public class Triang extends Variate { public Triang (double min, double mode, double max, int i); public double gen (); }; // Triang

A.23 Uniform

The Uniform class is to generate an random variate from the uniform distribution.
public class Uniform extends Variate { public Uniform (double min, double max, int i); public double gen (); }; // Uniform

69
A.24 Weibull

The Weibull class implements a Weibull random variate generator.


public class Weibull extends Variate { public Weibull (double scale, double shape, int i); public double gen (); }; // Weibull

Appendix B 64-bit LCG Random Number Generators

public class LCGRandom { private final static long MULTIPIER = 16807; // 7^5 private final static long MODULUS = 2147483647; // 2^31 - 1 private final static double SCALER = 1.0 / MODULUS; private int stream; // random number stream private final static int MAX_STREAMS = 10; private final static long SEED ] = { //1, // for testing: if seed is 1, z 1000 should be 522,329,230 428956419, 1954324947, 1145661099, 1835732737, 794161987, 1329531353, 200496737, 633816299, 1410143363, 1282538739 }; /** * Constructs an LCG-based Random Number Generator */ public LCGRandom (int stream) { this.stream = stream; }; // LCGRandom /** * Generates a real-valued random number in the range 0 to 1 */ public double gen () { long z = SEED stream];

70

71
z = (MULTIPIER * z) % MODULUS; // 64-bit integer arithmetic SEED stream] = z; return (double) z * SCALER; }; // gen /** * Generates an integer-valued random number in the * range 0 to MODULUS - 1 */ public long igen () { long z = SEED stream]; z = (MULTIPIER * z) % MODULUS; // 64-bit integer arithmetic SEED stream] = z; return z; }; // igen }; // LCGRandom

You might also like