Lesson 12 - Reading from and Writing to External Files
GPSS World has Blocks that are designed to read from and write to external ASCII files. These Blocks can be very useful if you want to read an external data file, format your own report, or simply collect one or two pieces of data at given time intervals in an external file.
Please take the time now to read the section titled Data Streams in Chapter 4 of the GPSS World Reference Manual. Also, you should refer to Chapter 7 to better understand the use of the I/O Stream Blocks, OPEN, READ, SEEK, WRITE and CLOSE. There are equivalent library procedures, as well. When these Blocks or library procedures are used in conjunction with the string procedures in GPSS World, you can accomplish powerful data handling and formatting tasks.
In this lesson, we will use some very simple models that are designed to do nothing other than exercise the actions of the Data Stream Blocks. Each model is supplied with a matching Text Object file with which it interacts. Text Objects are simply plain text files with a (.txt) filename extension. In the case of the files that are used for writing, we have provided you with a file TSTTEMPL.TXT that can be used to restore each of the files to its original state, if you or others wish to use this lesson again.
Another way to restore the changed files is to copy the TST*.TXT files to a safe place before you start this lesson. They are located in the Sample Models folder.
When you are done with the lesson, either copy back the TST*.TXT files or copy the TSTTEMPL.TXT file to the following files.
TSTSKINW.TXT
TSTAPPW.TXT
TSTSKRW.TXT
TSTSQRW.TXT
TSTSQR2W.TXT
Next, delete these two files.
TSTCATW.TXT
The TSTRD.TXT file and the TSTSTRD file are only used to read data. They will not be altered and do not have to be initialized before you use this lesson again.
The names of the test files used in this lesson are created by a code. Here are the letters and the I/O actions that they represent.
CAT = Catenate (String Procedure) SK = Seek
I N = Insert SQ = Sequential
R = Replace ST = String
RD = Read W = Write
You will notice in the OPEN Blocks of these sample models, that there is no path specified. That means that GPSS World will use the Sample Folder as the destination for all files that are written to disk.
Let’s start by reading a file sequentially and storing the values in a GPSS World Matrix. We’ll use the model TSTRD.GPS and the data file TSTRD.TXT shown below.
Model: TSTRD.GPS
; GPSS World Sample File - TSTRD.GPS
**************************************************
; Reads a file sequentially and stores
; the values in a matrix.
; At end of file goes to label Finis
**************************************************
Total MATRIX ,10,1
GENERATE ,,,1
OPEN
("TSTRD.TXT"),,flag
Again READ Numero,,Finis
SAVEVALUE Nrow+,1
ASSIGN Numrow,X$Nrow
MSAVEVALUE Total,P$Numrow,1,P$Numero
TRANSFER ,Again
Finis CLOSE Prob,,Flag1
TERMINATE 1
Flag TERMINATE 1
Flag1 TERMINATE 1
Datafile: TSTRD.TXT
1
2
3
4
5
6
7
Now, let’s run the simulation
CHOOSE
File / OpenIn the dialog box
SELECT
Tstrdand
SELECT
OpenNow, create the simulation and open the Matrix Window so we can watch it as the simulation reads the data file and updates the Matrix.
CHOOSE
Command / Create Simulationand
CHOOSE
Window / Simulation Window / Matrix WindowThen in the Open Matrix dialog box you will see the Matrix "Total" in the drop-down box since it is the only one in this model.
SELECT
OKand size the window to a comfortable viewing size.
CHOOSE
Command / STARTand in the dialog box we will suppress the Standard Report. Replace START 1
TYPE
START 1,NPSELECT
OK

Figure 12—1. The Total Matrix.
The simulation has run very quickly filling the Matrix with the values 1 through 7 that are found in the data file. Let’s briefly discuss the way the I/O Stream Blocks are working here.
The OPEN Block is placed in a separate segment of the model since the file only needs to be opened once. A high priority Transaction opens the file to be read as the first action in the running of the simulation.
Then the Transaction that will be doing the reading of the files begins to read the file sequentially looping through the READ Block and the four Blocks that follow it. Each value read is placed into the Transaction Parameter "Numero". The next three Blocks update a SAVEVALUE counter that is then moved to a Parameter and used as the row number in the matrix. Then in the MSAVEVALUE Block, the value that has been read into P$Numero is placed in the appropriate row of the Matrix, Total. When the end of file is reached, the Transaction is sent to the CLOSE Block labeled Finis, closing the data file. Then the Transaction enters a TERMINATE Block, ending the simulation.
If any errors occur in the OPEN or CLOSE Blocks, the Transaction will go to the Blocks labeled Flag or Flag1 respectively. Such an error would be easy to spot since normally those two Blocks should have an entry count of 0.
If we were doing multiple reads and writes, we could use a high priority Transaction to open the file. After all the data is read, the file is CLOSEd.
OK. Now close all the windows related to this example. You should have a Main GPSS Window with a blank client area.
The next file will demonstrate seeking data from selected locations in a file and placing it in specific locations in a matrix.
Model: TSTSKRD.GPS
; GPSS World Sample File - TSTSKRD.GPS
*************************************************
; Read two separate text lines of a file
; using SEEK and stores the values
; in a matrix. Close file after second value
; is read and stored.
*************************************************
Total MATRIX ,10,1
GENERATE ,,,1
OPEN
("TSTRD.TXT"),,Flag
SEEK
4
TRANSFER ,DoRead
Again SEEK 6
DoRead READ Numero,,Finis
MSAVEVALUE Total,P$numero,1,P$numero
TEST E
P$Numero,4,Finis
TRANSFER ,Again
Finis CLOSE Prob,,Flag1
TERMINATE 1
Flag TERMINATE 1
Flag1 TERMINATE 1
Datafile: TSTRD.TXT
1
2
3
4
5
6
7
Now, let’s run the simulation
CHOOSE
File / OpenIn the dialog box
SELECT
Tstskrdand
SELECT
OpenNow, create a simulation and open the Matrix Window. We can watch as the simulation reads the data file and updates the Matrix.
CHOOSE
Command / Create Simulationand
CHOOSE
Window / Simulation Window / Matrix WindowThe Open Matrix dialog box has the correct name in the drop-down box.
SELECT
OKand
CHOOSE
Command / STARTand in the dialog box we will suppress the Standard Report. Replace START 1
TYPE
START 1,NPSELECT
OK

Figure 12—2. The Total Matrix.
The simulation will run very quickly, but this time only the values 4 and 6 will be entered into the Matrix in rows 4 and 6. Let’s briefly discuss the way the I/O Stream Blocks are working.
The OPEN Block is placed in a separate segment of the model since the file only needs to be opened once. First, a high priority Transaction opens the file to be read.
Then, the Transaction that will cause the reading of the files enters a SEEK Block that places the Current Line Position at line 4. Next, entry into a READ Block causes the fourth text line to be read. The value that has been read is put into the matrix and then a test is performed to see if another read should be done. Another READ is done and the second number retrieved and loaded into the Matrix. Finally, the file is closed and the simulation ended.
If any errors occur in the OPEN or CLOSE Blocks, the Transaction will go to Flag, or Flag1, respectively. Such an error would be easy to spot, since normally those two Blocks should have and entry count of 0.
OK. Now close all the windows related to this example. You should have a Main GPSS Window with a blank client area.
The next example file will demonstrate writing to a selected line in a file using random access.
CLICK ON The X-Upper Right of the Matrix Window
Model: TSTSKINW.GPS
; GPSS World Sample File - TSTSKINW.GPS
****************************************************
; Test for random write.
; Inserts 123456 before line 3 of data
; file TSTSKINW.TXT
****************************************************
GENERATE ,,,1
OPEN
("TSTSKINW.TXT"),,Flag
SEEK
3
WRITE
123456,,Flag1,On
CLOSE
Prob,,Flag2
TERMINATE 1
Flag TERMINATE 1
Flag1 TERMINATE 1
Flag2 TERMINATE 1
Datafile: TSTSKINW.TXT
This is line1
This is the info on line 2
This is line 3
Line 4
Now, let’s run the simulation
CHOOSE
File / OpenIn the dialog box
SELECT
Tstskinwand
SELECT
OpenNow, create a simulation and run it.
CHOOSE
Command / Create Simulationand
CHOOSE
Command / STARTand in the dialog box we will suppress the Standard Report. Replace START 1
TYPE
START 1,NPSELECT
OKNow, let’s look at the altered data file.
CHOOSE
File / Openand in the dialog box you must first
CLICK ON The Down Arrow at the End of the Files of type box
CHOOSE
Text File (*.txt)then from the list
SELECT
Tstskinwand
SELECT
Open
You will see that 123456 has been inserted before the third line of the file. If we had not used a SEEK Block, the data would have been inserted before the first line of the file. In this example, we have not isolated the OPEN Block since we are only doing one write and then closing the file and ending the simulation. You will see that the SEEK Block is used to position the Current Line Position to the location in the data file before text line 3 where the information in the WRITE Block is to be written.
OPEN, WRITE and CLOSE all have alternate exits in case an I/O error occurs. Not only will the Transaction go to the indicated Block, when an error occurs, but a subsequent CLOSE retrieves the Error Code, and places it into a Transaction Parameter.
OK. Now close all the windows related to this example. You should have a Main GPSS Window with a blank client area.
Next, we’ll look at a write operation that appends data to the end of a file.
Model: TSTAPPW.GPS
; GPSS World Sample File - TSTAPPW.GPS
*************************************************
; Appends 123456 at end of data file TSTAPPW.TXT.
*************************************************
GENERATE ,,,1
OPEN
("TSTAPPW.TXT"),,Flag
SEEK
10000
WRITE
123456,,Flag1,On
CLOSE
Prob,,Flag2
TERMINATE 1
Flag TERMINATE 1
Flag1 TERMINATE 1
Flag2 TERMINATE 1
Datafile: TSTAPPW.TXT
This is line1
This is the info on line 2
This is line 3
Line 4
Now, let’s run the simulation
CHOOSE
File / OpenIn the dialog box
SELECT
Tstappwand
SELECT
OpenNow, create a simulation and run it.
CHOOSE
Command / Create Simulationand
CHOOSE
Command / STARTand in the dialog box we will suppress the Standard Report. Replace START 1
TYPE
START 1,NPSELECT
OKNow, let’s look at the altered data file.
CHOOSE
File / Openand in the dialog box you must first
CLICK ON The Down Arrow at the End of the Files of type box
CHOOSE
Text File (*.txt)then from the list
SELECT
Tstappwand
SELECT
OpenThe only way that this use of the WRITE Block differs from the previous one is that we have chosen to append a value to the end of the file. You will see that the value 123456 has been added to the end of the file. We have done two things differently here. First, the SEEK Block has the value 10000 in it and the WRITE Block is in insert mode (indicated by the on). In Insert mode when the Current Line Position is set past the end of the file, the data will be appended to the end of the file.
Although we will not show it here, if Insert mode is off, meaning that the WRITE Block is operating in Replace mode, then GPSS World would fill any empty gaps with null text lines up to the line number in the SEEK, and add the data at that position.
OK. Now close all the windows related to this example. You should have a Main GPSS Window with a blank client area.
Next on the agenda is a model that uses the WRITE Replace mode. We’ve used the code SKRW in the name to indicate Seek, Replace, and Write. The SEEK Block is used to place the Current Line Position at a chosen location.
Model: TSTSKRW.GPS
; GPSS World Sample File - TSTSKRW.GPS
********************************************
; Writes 123456 on line 2 of data file
; TSTSKRW.TXT replacing original line.
********************************************
GENERATE ,,,1
OPEN
("TSTSKRW.TXT"),,Flag
SEEK
2
WRITE
123456,,Flag1,Off
CLOSE
Prob,,Flag2
TERMINATE 1
Flag TERMINATE 1
Flag1 TERMINATE 1
Flag2 TERMINATE 1
Datafile: TSTSKRW.TXT
This is line1
This is the info on line 2
This is line 3
Line 4
Now, let’s run the simulation
CHOOSE
File / OpenIn the dialog box
SELECT
Tstskrwand
SELECT
OpenNow, translate the model and run it.
CHOOSE
Command / Create Simulationand
CHOOSE
Command / STARTand in the dialog box we will suppress the Standard Report. Replace START 1
TYPE
START 1,NPSELECT
OKNow, let’s look at the altered data file.
CHOOSE
File / Openand in the dialog box you must first
CLICK ON The Down Arrow at the End of the Files of type box
CHOOSE
Text File (*.txt)CHOOSE
File / Openthen from the list
SELECT
Tstskrwand
SELECT
OpenWhat happened? Line two of the data file was overwritten with the value 123456. Once again, we did not need to isolate the OPEN or the CLOSE Blocks since we were only going once through the model. The difference here from the previous model is that the WRITE Block is in Replace mode. You have to specify
OFF for replace mode. In this example, we also used the SEEK Block to choose the line that we wanted to be overwritten.OK. Now close all the windows related to this example. You should have a Main GPSS Window with a blank client area.
Next let’s look at how Replace mode works if there is no line position specified in a SEEK Block.
Model: TSTSQRW.GPS
; GPSS World Sample File - TSTSQRW.GPS
********************************************
; Writes 123456 on line 1 of data file
; TSTSQRW.TXT replacing original line.
********************************************
GENERATE ,,,1
OPEN
("TSTSQRW.TXT"),,Flag
WRITE
123456,,Flag1,Off
CLOSE
Prob,,Flag2
TERMINATE 1
Flag TERMINATE 1
Flag1 TERMINATE 1
Flag2 TERMINATE 1
Datafile: TSTSQRW.TXT
This is line1
This is the info on line 2
This is line 3
Line 4
Now, let’s run the simulation
CHOOSE
File / OpenIn the dialog box
SELECT
Tstsqrwand
SELECT
OpenNow, create a simulation and run it.
CHOOSE
Command / Create Simulationand
CHOOSE
Command / STARTand in the dialog box we will suppress the Standard Report. Replace START 1
TYPE
START 1,NPSELECT
OKNow, let’s look at the altered data file.
CHOOSE
File / Openand in the dialog box you must first
CLICK ON The Down Arrow at the End of the Files of type box
CHOOSE
Text File (*.txt)then from the list
SELECT
Tstsqrwand
SELECT
OpenAs you might have guessed, this works just like the last model, but this time the Current Line Position has not been relocated so it is line number 1 that is replaced. Next, we’ll replace two lines, one with a text string and one with a calculation result. You can put any values in the string that you want. In a minute we’ll show you how to combine multiple values from different sources in a string.
OK. Now close all the windows related to this example. You should have a Main GPSS Window with a blank client area.
Next let’s try the multiple sequential WRITEs in replace mode.
Model: TSTSQR2W.GPS
; GPSS World Sample File - TSTSQR2W.GPS
***********************************************
; Does 2 sequential writes in replace mode
***********************************************
GENERATE ,,,1
OPEN
("TSTSQR2W.TXT"),,Flag
WRITE ("This is fun."),,Flag1,Off
WRITE
(5+5),,Flag2,Off
CLOSE
Prob,,Flag3
TERMINATE 1
Flag TERMINATE 1
Flag1 TERMINATE 1
Flag2 TERMINATE 1
Flag3 TERMINATE 1
Datafile: TSTSQR2W.TXT
This is line1
This is the info on line 2
This is line 3
Line 4
Now, let’s run the simulation
CHOOSE
File / OpenIn the dialog box
SELECT
Tstsqr2wand
SELECT
OpenNow, create a simulation and run it.
CHOOSE
Command / Create Simulationand
CHOOSE
Command / STARTand in the dialog box we will suppress the Standard Report. Replace START 1
TYPE
START 1,NPSELECT
OKNow, let’s look at the altered data file.
CHOOSE
File / Openand in the dialog box you must first
CLICK ON The Down Arrow at the End of the Files of type box
CHOOSE
Text File (*.txt)then from the list
SELECT
Tstsqr2wand
SELECT
OpenThe only difference here is that after each WRITE Block entry, the Current Line Position is increased one line. Hence, text lines 1 and 2 are replaced. We have also included an error flag for each WRITE so that if an I/O error occurs, we will know which Block is the cause of the problem.
OK. Now close all the windows related to this example. You should have a Main GPSS Window with a blank client area.
In our final two examples, we will work with strings. You can manipulate data in powerful ways using String Procedures with data that has been read in or data that you may wish to write. You can format report headers and data as well as read in and extract portions of data from a file. You might want to read further about Strings in Chapter 8 of the GPSS World Reference Manual.
Model: TSTCATW.GPS
; GPSS World Sample File - TSTCATW.GPS
***********************************************************************
*
* Barber Shop Simulation
* Time is in Minutes
*
***********************************************************************
GENERATE 5,2.5
;Create next customer.
SAVEVALUE Custnum+,1
;Total customers who stay
ASSIGN Custno,X$Custnum ;Assign number to customer
QUEUE
Barber ;Begin queue time.
SEIZE
Barber ;Own or wait for barber.
DEPART Barber
;End queue time.
ADVANCE 10,2.5
;Haircut takes a few minutes.
RELEASE Barber
;Haircut done.
; Give up the barber.
TEST G TG1,1,Fin
;Write final Avg. Queue Residence
TERMINATE 1
;Customer leaves.
Fin OPEN ("TSTCATW.TXT"),,Flg1
WRITE
(Catenate("Avg. Barber Queue Time Is ",QT$Barber)),,Flg
CLOSE
Prob,,Flg2
TERMINATE 1
Flg TERMINATE 1
Flg1 TERMINATE 1
Flg2 TERMINATE 1
Datafile: TSTCATW.TXT
This file is to be created.
Now, let’s run the simulation
CHOOSE
File / OpenIn the dialog box
SELECT
Tstcatwand
SELECT
OpenNow, create a simulation and run it.
CHOOSE
Command / Create Simulationand
CHOOSE
Command / STARTand in the dialog box we will suppress the Standard Report. Replace START 1
TYPE
START 1,NPSELECT
OKNow, let’s look at the altered data file.
CHOOSE
File / Openand in the dialog box you must first
CLICK ON The Down Arrow at the End of the Files of type box
CHOOSE
Text File (*.txt)then from the list
SELECT
Tstcatwand
SELECT
OpenIn the WRITE Block in this model, we’ve used the String Procedure "Catenate" to take text data and mix it with actual data from the simulation run. You can see that this would be most valuable in formatting reports or putting out selected information at given time intervals in a simulation run. You could have a segment of your model with the sole purpose of generating Transactions to write simulation statistics. The values from the simulation could be labeled as we have done here for easy interpretation after the simulation run is complete.
OK. Now close all the windows related to this example. You should have a Main GPSS Window with a blank client area.
Next, let’s see how we can manipulate data that we read in from a file.
Model: TSTSTRDW.GPS
; GPSS World Sample File - TSTSTRDW.GPS
*************************************************************************
* Movie Theater Food Buying Analysis
* Takes info on age and sex, reads it in and analyzes
* how mix of people will influence needs at concession
* stand. Then writes a report on wait times, queue size
* and total people served.
*************************************************************************
Fem EQU 1
Male EQU 2
GENERATE 1
TEST
E X$Finish,0,In ;After End of File-destroy
next xact
READ
Info,1,Fin ;Get Cust Age and Sex
SAVEVALUE
Info1,(Substring(P$Info,1,2))
SAVEVALUE
Info2,(Substring(P$Info,3,1))
SAVEVALUE Counter+,1
TEST
G X$Info1,8,In ;Older than 8
may buy
TEST LE
X$Info1,17,In ;Older than 17 don’t buy
TEST
E X$Info2,Male,Ques ;All Males buy
Ques TRANSFER
.50,In ;50% of Females are
dieting-don’t buy
QUEUE
Wait ;Begin queue
time.
SEIZE Salesperson
;Customer gets salesperson
DEPART
Wait ;End queue
time.
ADVANCE
6,1 ;Get
service
SAVEVALUE
Served+,1 ;Keep track of number served
RELEASE
Salesperson ;Done with Salesperson
In
TERMINATE
;Enter the viewing area
*************************************************************************
GENERATE ,,,1,10
;Make this first Transaction
OPEN ("TSTSTRD.TXT"),1,Er
;Read file
OPEN ("TSTSTW.TXT"),2,Er1
;Write file
TERMINATE
Fin SAVEVALUE
Finish,1 ;Signal EOF to new xacts
WRITE (Catenate("Average
"," Average ")),2,Er2
WRITE (Catenate(" Wait
","Line Size")),2,Er3
WRITE (Polycatenate(" ",
INT(QT$Wait)," ", INT(QA$Wait) )),2,Er4
WRITE "Total People
Served",2,Er7
WRITE (Catenate(" ",X$Served)),2,Er8
CLOSE Prob,1,Er9
CLOSE Prob1,2,Er10
TERMINATE 1
Er TERMINATE 1
Er1 TERMINATE 1
Er2 TERMINATE 1
Er3 TERMINATE 1
Er4 TERMINATE 1
Er5 TERMINATE 1
Er6 TERMINATE 1
Er7 TERMINATE 1
Er8 TERMINATE 1
Er9 TERMINATE 1
Er10 TERMINATE 1
Datafile: TSTSTRD.TXT
161
021
252
162
151
131
172
172
182
352
341
152
152
162
151
131
172
172
182
352
341
202
141
161
171
151
112
142
142
122
132
142
152
Datafile: TSTSTW.TXT
This file is to be created.
Now, let’s run the simulation
CHOOSE
File / OpenIn the dialog box
SELECT
Tststrdwand
SELECT
OpenNow, create a simulation and run it.
CHOOSE
Command / Create Simulationand
CHOOSE
Command / STARTand in the dialog box we will suppress the Standard Report. Replace START 1
TYPE
START 1,NPSELECT
OKand wait for the simulation to run. Now, let’s look at the altered data file.
CHOOSE
File / Openand in the dialog box you must first
CLICK ON The Down Arrow at the End of the Files of type box
CHOOSE
Text File (*.txt)then from the list
SELECT
Tststwand
SELECT
OpenIn this final model, we have read in values from the file TSTRDST.TXT, manipulated them first by dividing them into smaller pieces and second by taking only a portion of the information that we read at a given location in the data string. You can see how powerful String Procedures can be. Take some time to examine the String Procedures in Chapter 8 of the GPSS World Reference Manual. Also, you may want to take a breather before you tackle the ANOVA Command.
Don’t forget to initialize the data files as described in the beginning of this lesson and delete the two string output files. You may also want to delete the reports that we have created along the way. You can do that in the Windows file management system. See you when you’re ready for the next lesson.
You have probably noticed that changing nothing other than the random number seeds in a simulation can cause what appear to be large differences in output. If we are to use simulation in real problems, how can we tell which effects are random and which are real? The GPSS World ANOVA command provides a way.
This lesson is a brief introduction in the use of the statistical method known as analysis of variance. In it, we consider the ANOVA PLUS Library Procedure, which makes a first level of statistical analysis relatively easy. However, to become proficient in the application of simulation methods, you must become familiar with elementary statistical inference and the design of experiments. These topics are not covered in detail here.
When you use statistical methods to see if two alternatives are really different, you must not allow extraneous uncontrolled events to occur during the simulations. It would not be fair to load one run with additional activities at some unknown place in the simulation, and not to do precisely the same thing in all other runs. Therefore, you should generally not use interactive methods when you are running simulations that will be used for the statistics in your final report.
Let’s return now to the example of the barber who cannot keep up with arriving customers. As manager of the barber shop, you want to determine what effect a faster barber will have on the situation. You do not want to hire another barber. You want to see if a barber, who can cut hair in an average time of 5 minutes, causes a significant reduction in waiting time for the customers.
The treatment to be tested is that of barber 1 against barber 2. The barbers differ only in their average haircut times. Our experiment, then, consists of two treatment levels: 6.8 minute average haircut time, and 5 minute average haircut time. We will run 3 simulations at each level. In general, you will want to run more.
If our results are in the form of an arithmetic average of many items, we are justified in using the ANOVA command to do a statistical analysis. We can satisfy this criterion by using the average waiting time of customers as the overall measure.
We are going to build a Results Matrix of a special format that can be used by the ANOVA procedure. Let’s begin.
Since we have 1 treatment with two levels, we need 2 dimensions in our Results Matrix. The last dimension of a Results Matrix is always for replications, and we will have three of them at each treatment level. Therefore we will use a 2 x 3 matrix.
Now start the GPSS World Session.
CHOOSE
File / OpenIn the dialog box
SELECT
AnovaSELECT
OpenHere’s a copy of the program that you should now see in the Model Window.
; GPSS World Sample File - ANOVA.GPS
***********************************************************************
*
* Barber Shop Simulation
* Time is in minutes
***********************************************************************
GENERATE 5,1.7
;Create next customer.
QUEUE
Barber ;Begin queue time.
SEIZE
Barber ;Own or wait for barber.
DEPART
Barber ;End queue time.
ADVANCE Cut_Time
;Cut takes a few min.
RELEASE Barber
;Give up the barber.
TEST G
TG1,1,Doout ;Last XN writes Anova data.
TERMINATE 1
;Customer leaves.
Doout OPEN ("BARBER.RST"),,Prob ;Open Anova database.
SEEK
10000 ;Place pointer at end of file.
WRITE
(Polycatenate(QT$Barber," ",Treatment,"
")),,Prob,On
CLOSE
Errorcode,,Prob ;Close,send to Prob if error.
TERMINATE 1
Prob TERMINATE 1
;Terminate here if I/O error.
Notice that our main experimental parameter in the ADVANCE Block is represented by a User Variable, Cut_Time. This will allow us to change the time it takes to complete a haircut. We will use a three digit random number seed varying only the middle digit to indicate which run of the simulation is being executed, run 1, 2 or 3. In the second set of runs with the faster barber, we will use the same random number seeds and change only the speed at which the barber works.
Before starting the simulation, let’s take a look at the Include-file that we will use to execute multiple simulation runs for us.
RESULTS MATRIX ,2,3 ; Set up for 3 replicates of two levels
Cut_Time EQU 6.8
Treatment EQU 1
RMULT 411
Start 100,NP
MSAVEVALUE RESULTS,1,1,QT$Barber
Clear Off
RMULT 421
Start 100,NP
MSAVEVALUE RESULTS,1,2,QT$Barber
Clear Off
RMULT 431
Start 100,NP
MSAVEVALUE RESULTS,1,3,QT$Barber
Clear Off
Cut_Time EQU 5
Treatment EQU 2
RMULT 411
Start 100,NP
MSAVEVALUE RESULTS,2,1,QT$Barber
Clear Off
RMULT 421
Start 100,NP
MSAVEVALUE RESULTS,2,2,QT$Barber
Clear Off
RMULT 431
Start 100,NP
MSAVEVALUE RESULTS,2,3,QT$Barber
Let’s look at what will happen when we Translate the Include-file. First, it defines a Global Matrix named Results, which will be used to hold the numeric values for the Analysis of Variance. The Matrix has two dimensions, supporting 2 treatment levels, with 3 replicates of each.
Next, you will see that an EQU Command has been used to set the average haircut time equal to 6.8 minutes. Then, after three runs of the simulation and collection of appropriate data, the time is set to 5 minutes, allowing for a faster barber than in the first series of runs. You will also see that we set a Treatment value before each series of runs. This will differentiate the runs done with the 6.8 minute Cut_Time (Treatment 1) from those done with the 5 minute Cut_Time (Treatment 2).
Notice that we CLEAR OFF statistics between runs to avoid correlation between one simulation and the next. The OFF parameter is necessary to avoid resetting the Results Matrix. Also, in our simple example, we have not built in allowance for an empty barber shop at the start of each simulation. In your own simulation studies, you will want to ensure that startup effects are insignificant. This can be done by ignoring a transient startup period, using the RESET command some time into the simulation. The GPSS World PLOT command is useful for identifying transient periods that you might want to exclude. We could then gather the waittime values for each of the runs based on a start with a full shop. For now, let’s just concentrate on our simpler example.
Finally, we do two additional things. We run with the NP option as the B operand of START. This suppresses the Standard Report. Reports can also be controlled by the Settings of the Simulation Object. Also, we set the seeds of the random number generators in the Command File. The same seeds are used in the second series of runs so that the only difference in the model is in the time it takes to cut hair. This reduces variance in the results.
Now, create a simulation.
CHOOSE
Command / Create SimulationThis creates the Simulation Object and opens its Journal View. Next, we’ll use an Include-file to run the simulations. Remember, GPSS World will look for the Include-file in the same folder where the model object exists, if the simulation has not been saved, as in this case. If the simulation has been saved, it will look in the folder where the simulation object resides. Now do the Commands in the Include-file:
CHOOSE
Command / CustomTYPE
INCLUDE "ctlanova.txt"SELECT
OKWhat happened? The simulation started to run automatically. You will see that the simulation has run 6 times in a few seconds. Now, let’s look at the Results Matrix we have built for the Analysis of Variance.
CHOOSE
Window / Simulation Window / Matrix Windowand when the Matrix Window Cross Section Dialog appears,
CHOOSE
OKThis opens the Matrix Window on the Results Matrix. You may want to expand the window if all the cells in the Matrix are not visible. Here, we can see the results of each individual simulation.

Figure 13—1. The Results Matrix.
Now, its time for the analysis.
CHOOSE
Command / Custom TYPE SHOW ANOVA(Results,2,1)and
SELECT
OKThe ANOVA Procedure writes an ANOVA Table into the Journal Window and returns the F value of the analysis.

Figure 13—2. An ANOVA Table in the Journal Window.
Let’s now interpret our results. The primary question is whether or not the effect of the faster barber is above the random noise level.
Look at the line for factor A in the ANOVA Table in the Journal Window. We find that the critical value of F for this experiment, at the 95% level, is 7.71. Since our calculated F value is much greater, we conclude that the effect of the faster barber is statistically significant.
Sometimes it is possible to expose real effects by increasing the durations of the simulations and/or the number of replications. We don’t need to worry about that here. The statistical significance of the faster barber is overwhelming.
Now look at the last line in the Journal. It shows the value returned by the ANOVA Library Procedure, 3.8797650. This is the Standard Error of the analysis and is available for use by Procedures which call the ANOVA routine.
The GPSS World ANOVA feature provides a very easy first level of statistical analysis. However, you may want to do more. In that case you may find that you want to create a results text file for input to a separate statistical analysis program. This is relatively easy using the OPEN, CLOSE, READ, WRITE, and SEEK GPSS Blocks, and the String formatting routines in the PLUS Library.
Also, the powerful GPSS World EXPERIMENT Procedure can be used to automatically direct and analyze the progress of an experiment involving many simulation runs. Lesson 19, below, goes deeper into the subject. We have really only touched the surface here.
As usual, close up all the windows before going on to the next lesson. You can leave the Main Window open if you don’t intend to stop now.
In the next lesson, we turn to an easier topic. We will look at how Reports are handled in GPSS World. See you then.
The Report management system contains a number of unique capabilities. First you should know that reports are never automatically deleted and are always created unless you suppress them using NP as the B operand of the START Command. Each report is given a name that indicates the simulation that produced it. e.g., SAMPLE2.1.1, SAMPLE2.1.2, etc. The default name is derived from the file name of your model, the sequence number of the simulation created from that model and finally, the report number for that simulation version. These reports will remain even after the Session is ended.
If you choose to use a REPORT Command you can only use it interactively as
REPORT
You can no longer give your reports names. Since reports are specially formatted files, if you wish to name them differently, you can copy the report to the clipboard and from there to a file with the name you choose to assign. Reports have an extension of "gpr". The numbering scheme is meant to keep your reports ordered. If you wish to reset the simulation number, you can do so in the Settings Notebook.
CHOOSE
File / Openand
SELECT
Sample9and
SELECT
OpenCHOOSE
Edit / SettingsCLICK ON The Random Numbers Page
The setting "Child Object Sequence Number" sets the number of the simulation filename. If you have saved simulations from this model, the number would be >1. You can reset it to any value. This is the value used in the report name.
When you start a new GPSS World Session, reports generated during that Session using the default name (simulation name plus simulation sequence number plus report sequence number) will be numbered starting with the first available sequence number after the highest number. Therefore, if you have deleted selected reports, you could have sequence numbers in a Session that are not contiguous.
The REPORT Command
REPORT used in a Custom Command dialog box is used to produce a report interactively at any time. The A operand of the Report Command, as used in GPSS/PC
tm, is no longer used.
The REPORT Settings
Now let’s look at some report settings.
Move to the Reports Page in the Model Settings Notebook.
CLICK ON The Reports Page
You can see the default information that is included in reports created by running the simulation that we just created. You can try changing the choices if you like.
Also, the settings are discussed in detail in chapter 2 of the GPSS World Reference Manual.
Let’s create a simulation from the opened model. first close the Settings Notebook.
Then
CHOOSE
Command / Create SimulationNow, see how a report is generated
CHOOSE
Command / STARTWe’ll use the 1 that’s already there.
SELECT
OKWhen the simulation completes, you’ll notice that a Report Window appears automatically as we expected. If you wish, you can increase the size of the window and examine the report more closely. For a detailed discussion of the items in the report, read Chapter 11 in the GPSS World Reference Manual.

Figure 14—1. The Report Window.
Let’s run the simulation one more time so we have two reports.
CHOOSE
Command / STARTWe’ll use the 1 that’s already there.
SELECT
OKWhen the simulation ends, you should see a second Report Window. Next, let’s close one of the Report Windows.
CLICK ON The X-Upper Right - SAMPLE9.1.2 Window
CLICK ON No
when asked if you want to save the file. Then close the second report window, but save this one.
CLICK ON The X-Upper Right - SAMPLE9.1.1 Window
CLICK ON Yes
CHOOSE
SaveNow let’s open the report again.
CHOOSE
File / OpenCLICK ON
The down arrow at the end of the Files of type boxSELECT
ReportSELECT
Sample9.1.1SELECT
OpenExamine this report now if you like. Remember that you can always print any report from a Report Window by using the
File / Print option in the Main Menu.Let’s try using the REPORT Command. First, we’ll start the simulation running for a long time and interrupt it.
CLICK ON
Anywhere in the Journal WindowCHOOSE
Command / ClearCHOOSE
Command / STARTReplace the 1,
TYPE
11111SELECT
OKOnce the simulation is running, interrupt it.
PRESS
[F4]CHOOSE
Command / Customand
TYPE
REPORTSELECT
OKIn this lesson, we’ve learned about the sequence numbering that is used for reports; have examined the settings for reports and the contents of the GPSS World Report. We have also used the REPORT command.
If you wish to go on to the next lesson, close all windows. Don’t forget to delete all the reports that we have created that you no longer wish to keep using the Windows file management system.
CLICK ON The X-Upper Right of Each Window
and answer the appropriate questions.
In the next lesson, we will look at the Simulation Journal use in GPSS World.
This lesson considers the GPSS World Journal. We have used the Journal earlier in the this manual, but now we will examine it in a little more detail.
The Journal is a chronology of statements written to the Journal / Simulation Window. When you save a simulation, all messages in the Journal / Simulation Window are saved.
The Session Journal collects trace messages, error messages, and any interactive Commands.
Let’s use SAMPLE5 to study the Journal / Simulation Window.
CHOOSE
File / Openand
SELECT
Sample5and
SELECT
OpenWhen we create a simulation and run it, the Journal / Simulation Window will record any errors as well as any interactive actions such as SHOW or STEP commands. Now, let’s see how we can use the Journal Window for interactive debugging.
CHOOSE
Command / Create SimulationLet’s put a universal Stop Condition on the model so we can use the STEP Command and see the record in the Journal.
CHOOSE
Command / Customand in the dialog box
TYPE
StopSELECT
OKand then
CHOOSE
Command / STARTand in the dialog box replace the 1
TYPE
11and
SELECT
OKThe simulation will stop immediately. Let’s use the STEP command.
PRESS
[F5]a few times. Then look at the Journal Window. You may want to enlarge its size or print it to look at the messages created. You can imagine how helpful this window can be in tracking down errors.
Let’s try something new. Let’s end the GPSS World Session with no questions asked!
CHOOSE
Command / Customand
TYPE
EXIT(1)SELECT
OKWow! The whole GPSS World environment disappeared!
It was quick, but it also bypassed the "Do you want to save ..." queries designed to prevent you from losing your precious work. So be very careful with this. The EXIT Command is discussed more fully in Chapter 6 of the GPSS World Reference Manual.
In the next lesson, we will go into the use of the INTEGRATE Command.
When you can express changes to variables in terms of their derivatives with respect to time, GPSS World can automatically keep their values up to date. By using the INTEGRATE Command, you can incorporate a system of ordinary differential equations of any order into your simulation. Although continuous modeling is quite general, and easily handles nonlinear systems, it is usually slower than other methods.
Please familiarize yourself with the basic concepts by reading the section, Continuous Simulation, in Chapter 4 of the GPSS World Reference Manual. See you when you get back.
As you have seen, the primary tools for continuous modeling are the INTEGRATE Command, which sets up the differential equation and thresholds, and the INTEGRATION Block, which can turn each integration on or off.
It’s easy to set up a continuous variable. All you have to do is to initialize the User Variable and assert the INTEGRATE Command. This gives GPSS World the starting value and all it needs to know in order to keep updating it. Let’s try it.
CHOOSE
File / NewCHOOSE
Modelin the dialog box.
SELECT
OKLet’s assume that we have a manufacturing system that creates 2 widgets a second. When a full truckload of widgets has been produced, the supervisor sends for a truck to hauls away a full load to one of the distribution centers. We start the simulation with an inventory of 0.
TYPE
Inventory EQU 0to set up the initial condition. On the next line
TYPE
Inventory INTEGRATE 2,Full_Load,Get_Truckto set up the derivative. Usually, you will need to use a PLUS Procedure to define the derivative. Then, you would use a parenthesized procedure call in Operand A of the INTEGRATE Command.
Notice that when the threshold is crossed a transaction will be generated. We will use this to end the simulation.
TYPE
Full_Load EQU 50Now when 50 widgets are created, a transaction will be sent to the Block labeled Get_Truck.
That is all you need for the continuous part. For the discrete part, add the following statements to the model.
TYPE
You always need the discrete part to start and end the simulation. In this case we will use the threshold to decrease the Termination Count.
Save the model if you might want to experiment later and don’t want to type it in again.
CHOOSE
Command / Create SimulationBefore we start the simulation, open a Plot of the User Variable Inventory,
CHOOSE
Window / Simulation Window / Plot WindowThen in the Edit Plot Window
TYPE
Inventoryin all three fields: Label, Expression, and Title. Leave the other values as they are.
CLICK ON The Plot ButtonCLICK ON The Memorize Button
Let's mark the threshold on the plot, as well. In the Edit Plot Window in the Label entry field replace the current value
TYPE
Thresholdand in the Expression entry field replace the current value
TYPE
Full_LoadLeave the other values as they are and
CLICK ON The Plot Button
CLICK ON The Memorize Button
SELECT
OKExpand the Plot Window to a good viewable size. Now start the simulation.
CHOOSE
Command / STARTSELECT
OKYour Plot Window should look like this.

Figure 16—1. Inventory Plot.
You should see the Inventory value increase to 50 very quickly, causing the simulation to end. In the Standard Report, it shows that it only took 25 simulated minutes to do the job. Therefore, you can determine that two widgets were manufactured per minute. The threshold was crossed at 25 simulated minutes, a transaction was created and sent to the Block labeled Get_Truck. The INTEGRATION Block is available for Transaction-level control. It’s described in Chapter 7 of the GPSS World Reference Manual.
This was a very simple example for showing the basics. Most integrated variables do not have constant derivatives. A more realistic model is in Chapter 2 of this manual, under PREDATOR.GPS.
If we had wanted to cause the Inventory value to drop when the truck left, we would have to decrease the value in a User Variable. Since the EQU Command cannot be asserted by a Transaction, how would we do this?
The answer is a PLUS Procedure, which we will consider in the next lesson. Close the Plot Window before you move on to the next example.
Now let’s turn to an example where we know the solution before we even start.
Consider the following system of ordinary differential equations:
x_’ = y_
y_’ = -x_
and at time t = 0,
x_ = 1
y_ = 0
The solution is
x_ = sin( t )
y_ = -cos ( t )
Here we are using underscores to ensure that our variables will not clash with GPSS World keywords.
Let’s see what happens when we simulate this system. First close all open windows, leaving only the GPSS World Main Window.
To run the simulation and create a Plot, in the Model Window.
CHOOSE
File / OpenSELECT
Sample13and then
SELECT
OpenNext, the simulation must be created.
CHOOSE
Command / Create SimulationNow, we set up a Plot of the User Variables, to observe the dynamics.
CHOOSE
Window / Simulation Window / Plot WindowThen in the Edit Plot Window,
for the Label,
TYPE
x_and in the Expression field
TYPE
x_In the Plot Title,
TYPE
Sine / Cosine Sampleand for a Time Range
TYPE
120For Y values for the Min
TYPE
-2and for Max
TYPE
2and
CLICK ON
The Plot ButtonCLICK ON The Memorize Button
Now, add the other variable to the plot. In the Edit Plot Window, replace the Label and Expression fields
TYPE
y_in both and leave the other values as they are.
CLICK ON
The Plot ButtonCLICK ON The Memorize Button
CHOOSE
OKBefore we begin the simulation, arrange the Plot Window so that it is large enough to view the details.
Now, play out the integration. From the Main Window menu
CHOOSE
Command / STARTand
SELECT
OKYour plot should look like this.

Figure 16—2. Sine Wave Plot.
As you can see, the familiar sine wave unfolds for both variables. When the simulation completes, examine the Standard Report. Compare the x_ variable with the Savevalue x_exact, which is calculated from the analytic solution. Do the values agree?
When you have the solution to the differential equations, consider yourself lucky and use it everywhere you can. Most real world systems of equations are much too unwieldy for that. Usually, you will be forced to play out the integration numerically, using one or more INTEGRATE Commands, which takes a lot more computer time.
Now, close all open windows.
We.., that's all for now. In the next lesson, we will learn about GPSS World's built-in Programming language called PLUS.
This lesson considers PLUS, the Programming Language Under Simulation. See the "PLUS Primer" at the end of this lesson for practical examples of the use of PLUS.
As we have learned, Model Statements are the building blocks of Models, and they can be sent interactively to an existing simulation.
However, the only PLUS Statements that are Model Statements are the PROCEDURE and EXPERIMENT Statements. All other PLUS Statements can exist only within the body of a Procedure. PLUS Expressions are a little different. They can exist within PLUS Statements, or, when parenthesized, within the operands of GPSS Statements.
There are only a few different PLUS Statement types. They are:
EXPERIMENT — Define a PLUS Experiment.
PROCEDURE — Define a PLUS Procedure.
TEMPORARY — Define and restrict the scope of a User Variable.
TEMPORARY MATRIX — Define and restrict the scope of a Matrix Entity.
BEGIN / END — Compound Statement. Create a block of PLUS Statements.
Assignment — Set the value of a Named Value or Matrix element.
Procedure Call — Invoke a Library Procedure.
IF / THEN — Test an expression and act on a "TRUE" result.
IF / THEN / ELSE — Test an expression and act on the result.
WHILE / DO — Perform action repetitively.
GOTO — Jump to a new location within the Procedure.
RETURN — Finish the processing and, optionally, give a result to the caller.
Please turn now to Chapter 8 in the GPSS World Reference Manual, and read about the PLUS Language.
Welcome back. Did you notice that a PROCEDURE Statement has a slot for only one statement? Usually, you will use a Compound Statement there, and it will enclose a Statement List. However, any single valid PLUS Statement goes there just as well.
In this lesson we will not use all the PLUS Statements. Here we will demonstrate the definition and interactive redefinition of Procedures, and some tips on debugging PLUS Procedures interactively.
Let’s begin by defining a Procedure that can set the value of a User Variable.
CHOOSE
File / NewCHOOSE
ModelThen
SELECT
OKTYPE
PROCEDURE SetPop(level) Foxes = level ;Although most PLUS Procedures are more complex, this is all that is needed to define one. It doesn’t even declare a return value, so a return value of 0 would be used by default. Return values are useful when a PLUS Procedure passes information to a calling Procedure. We don’t use it in this simple example.
Now save the model.
CHOOSE
File / Save AsThen
TYPE
Foxfor the name of the model and
SELECT
SaveCHOOSE
Command / Create SimulationWe have included the Procedure SetPop as part of the Model and then created the Simulation. Any invocations of SetPop interactively or within the simulation will now use this definition.
CHOOSE
Command / SHOWand in the dialog box
TYPE
SetPop(100)and
SELECT
OKNotice that the return value from the SetPop Procedure was 0. Let’s look at the population level.
CHOOSE
Command / SHOWand in the dialog box
TYPE
Foxesand
SELECT
OKSee? The User Variable Foxes was updated when we did the first SHOW. Now lets redefine the SetPop Procedure interactively.
CHOOSE
Command / CustomTYPE
PROCEDURE SetPop(level) Foxes = level # 10 ;and
SELECT
OKNow, when the SetPop Procedure is invoked, the population will be set to ten times the argument. Again
CHOOSE
Command / SHOWand in the dialog box
TYPE
SetPop(100)and
SELECT
OKNotice that the return value from the SetPop Procedure was 0 again. We could have inserted a RETURN Statement into SetPop. In fact, SetPop could be nothing more than a single RETURN Statement.
Let’s look at the population level.
CHOOSE
Command / SHOWand in the dialog box
TYPE
Foxesand
SELECT
OKAs you can see, although the simulation had already been sent to the Simulation Object, we were able to redefine the Procedure interactively. This can be useful when you need to debug your own PLUS Procedures, as we will discover next.
For now, close both the Model Window and the Journal Window.
Debugging PLUS Procedures
When you are debugging your PLUS Procedures, the first thing to do is to turn on the PLUS Trace in the Reports Pages of the Settings. Then every invocation causes a record to be written to the Journal Window. These traces are indented to show the depth of the processing, and they list the evaluated arguments of the invocation. It’s easy to trace within PLUS Procedures as well. Just create one or more dummy PLUS Procedures that do nothing. Then you can pepper your primary PLUS Procedure(s) with calls to this debugging Procedure, and when the PLUS Trace is on you will receive traces in the Journal Window showing the state of your variables.
CHOOSE
File / Newand since Model is already highlighted
SELECT
OKEnter the following PLUS Procedures.
TYPE
PROCEDURE RabbitRate() BEGIN
PROCEDURE Dummy( argument ) RETURN;
Don’t forget the final semicolons. We have defined a dummy procedure for the sole purpose of tracing the value of our local variable. The PLUS Trace must be on for this to work. Let’s turn it on
CHOOSE
Edit / SettingsCLICK ON The Reports Page of the Settings Notebook
CLICK ON The PLUS Trace box
Now, save the model.
CHOOSE
File / Save AsThen for the name of the file
TYPE
RatesSELECT
SaveNext, create the simulation
CHOOSE
Command / Create SimulationSo far, so good. If you inadvertently made typing errors, use
Search / Next Error in the Model Window to find and correct them. Now invoke the Procedure.CHOOSE
Command / SHOWand in the dialog box
TYPE
RabbitRate()and
SELECT
OKWe got an error message. Take a close look at each line in the message. It tells us the line number where the error occurred. Let’s put the cursor at that point. Make sure that the Model Window has the focus.
CHOOSE
Search / Go To LineTYPE
5and
SELECT
OKApparently, this line is trying to use a value from a Temporary User Variable that was never initialized. As we can see this is true for the TotRate Variable. We forgot to initialize it. Just above the line in error,
TYPE
TotRate = BirthRate - DeathRate ;and, after that
TYPE
Dummy(TotRate);This time we are NOT going to Retranslate the Model. We are going to redefine the Procedure and still maintain the existing simulation environment. We do this by using an Interactive INCLUDE Command. This may seem cumbersome, but it is meant to show you the power of the INCLUDE Command.
First, copy the text in the Model Window to the Window Clipboard. Next, we will create a text file.
CHOOSE
File / NewSELECT
Text FileSELECT
OKand then paste the Clipboard contents into the new Text File and save the file.
CHOOSE
File / Save AsTYPE
RateDeffor the file name and
SELECT
SaveThis creates a TEXT file that can be used as the Include-file. All Include-files must be plain text files. Now, let’s redefine SetPop() in the existing simulation. That means using INCLUDE, not Retranslate.
CHOOSE
Command / Customand in the dialog box
TYPE
INCLUDE "RateDef.txt"and
SELECT
OKSo far, so good. Notice that we did not Retranslate. Now invoke the Procedure.
CHOOSE
Command / SHOWand in the dialog box
TYPE
RabbitRate()There. That fixed the problem. It was easy to redefine the Procedure interactively.
You may find it convenient to make minor modifications to the PLUS Procedure when you are testing it. First, you may want to "comment out" TEMPORARY Statements, as long as none of the Temporary User Variable or Matrix Names clash with global entities. If there is a conflict, global variables could be altered. It is best to keep the Temporary names unique. Simply place /* at the beginning of each TEMPORARY or TEMPORARY MATRIX Statement, and */ after it. This will cause your intermediate results to be available after the Procedure ends. Second, you can add additional Assignment Statements and RETURN Statements to stop the Procedure wherever you like.
Don’t forget that you can always insert calls to a dummy PLUS Procedure to get watch how your variables are changing. Of course, the PLUS Trace must be turned on in the Settings of the Simulation in order to get the traces in the Journal Window.
Hopefully, reviewing the example models in this lesson and the examples in the Plus Primer that follows will help you to understand some of the potential of PLUS. Also, the sample model PREDATOR.GPS in Chapter 2 of this manual uses a PLUS Procedure.
PLUS PRIMER
PLUS is a powerful programming language that can be used nearly anywhere in a GPSS World model. Most GPSS Statement operands can take a PLUS expression wrapped in a pair of parentheses. Stop for a moment to consider what that means. Sure, PLUS expressions can be a set of elements including SNAs and numeric values. But they can also contain calls to PLUS Procedures defined by you. You may only need a special calculation to be incorporated into the expression evaluation. But at times you may want to use a PLUS Procedure for its ability to change permanent values.
The purpose of this section is to augment the PLUS Lesson with uses for this powerful language that is included in your GPSS World software. It gives some additional practical examples, and a step by step description of how each Model and Plus Procedure work. The examples are included with the sample models. Unless you have changed their destination on installation, you will find them in the GPSS World Samples Folder.
PLUS Procedures must be defined before you can use them. You define them in PROCEDURE Statements, and you use them by placing Procedure Calls in expressions.
Every PLUS Procedure Statement starts with your Procedure name and the formal argument list. This latter is a list of zero or more replacement names that determine how arguments supplied in the Procedure Call are to be used.
Although the arguments used in a Procedure Call are called "Actual Arguments", each one can be a complicated expression, which is evaluated at the time the Procedure Call is evaluated. It is the result of each of these argument evaluations which is used in place of the "Formal Arguments" declared in the Procedure definition. The final value of each argument is matched by position only.
In the examples that follow, you will find PLUS reserved names in upper case letters. They need not be upper case when you use them in your Models.
; GPSS World Sample File - PLUSANS.GPS
;
; This model uses the same PLUS Procedure to do
; different operations dependent on the Arguments
; passed to it.
;
GENERATE ,,,1
ASSIGN 1,500
ASSIGN 2,1234
ASSIGN Type,1 ;Assign calc type.
SAVEVALUE Ans,(Comp(P1,P2,P$Type))
;1st result
TERMINATE 1
GENERATE ,,,1
ASSIGN 1,260
ASSIGN 2,2
ASSIGN Type,2 ;Assign calc type.
SAVEVALUE Ans1,(Comp(P1,P2,P$Type))
;2nd result
TERMINATE 1
PROCEDURE Comp(Arg1,Arg2,Arg3)BEGIN
TEMPORARY Name1;
IF (Arg3=1) THEN BEGIN
Name1=((Arg1#Arg2)/3);
RETURN (Catenate(Name1," is the answer."));
END;
ELSE BEGIN
Name1=(Arg1+Arg2);
RETURN (Catenate(Name1," is the second answer."));
END;
END;
In this example, a PLUS Procedure is called when operand B of a SAVEVALUE block is evaluated. The same Procedure is used in two different places in the model and the action in the Procedure is determined by one of the arguments that identifies the type of operation to be used. When the Type passed as Arg3 is 1, the first part of the IF..THEN..ELSE is executed, if the Type is 2, the ELSE portion of the statement is executed. In both cases, a TEMPORARY variable is created inside the Procedure to receive the results of the calculation. The calculation could also be done directly in the RETURN statement and then the TEMPORARY variable would not be necessary. It is used more for clarity. A TEMPORARY variable only survives until the Procedure returns. In the call to the Procedure where the value to be placed in the SAVEVALUE Ans is being calculated, The values 500 and 1234 are received by the Procedure in Arg1 and Arg2. Arg3 receives the value in the Type parameter. Since Arg3=1 the following two steps after the IF....THEN statement are performed. The RETURN statement uses the String Library command CATENATE to combine two values into a single string which is then placed in the SAVEVALUE Ans and the Procedure ends. The BEGIN and END statements surrounding the IF and ELSE are necessary to insure that both actions are performed.
Note that all PROCEDURE definitions surround the PROCEDURE with a BEGIN and END. Also each statement ends with a ";". Even Statements within an IF...THEN....ELSE Statement end in a ";".
To run this model, after it is translated, use a Start 2. When the model has run to completion, you can view the values in the SAVEVALUES Ans and Ans1 by pressing [F8] and [F9]. These Function keys have been preloaded with Show commands on the Function Keys page of the Model Settings Notebook.
; GPSS World Sample File - MIN.GPS
;
; This model takes a series of numbers that are picked according
; to probabilities as defined in the Function, Myfunc and then
; uses a PLUS procedure to select the minimum value. The result
; is placed in the Savevalue, Low. When the model has run, the
; four values, Val1, Val2, Val3, and Val4 can be displayed in
; the status line by pressing the function keys [F5], [F6], [F7]
; and [F8],
respectively. The lowest value is displayed by pressing
; function key [F9].
These keys have been preset in the Model
; Settings Notebook on the Keys page.
;
GENERATE ,,,1 ;Create 1 Xact.
Myfunc FUNCTION RN2,D4 ;Random probabilistic pick of values.
.25,5/.50,7/.80,8/1,2
SAVEVALUE Val1,FN$Myfunc ;Assign value.
SAVEVALUE Val2,FN$Myfunc ;Assign value.
SAVEVALUE Val3,FN$Myfunc ;Assign value.
SAVEVALUE Val4,FN$Myfunc ;Assign value.
;Send values to PLUS to select
; min value and put in Savevalue.
SAVEVALUE Low,(Minimum(X$Val1,X$Val2,X$Val3,X$Val4))
TERMINATE 1 ;End simulation.
PROCEDURE Minimum(Arg1,Arg2,Arg3,Arg4) BEGIN
TEMPORARY Lowval;
IF (Arg1<=Arg2) THEN Lowval=Arg1;
ELSE Loval=Arg2;
IF (Lowval>Arg3) THEN Lowval=Arg3;
IF (Lowval>Arg4) THEN Lowval=Arg4;
RETURN (Lowval);
END;
This model can be run with a START 1. After four
values have been assigned to four SAVEVALUES using the GPSS Discrete
Random Function called Myfunc, the lowest value is placed in the
SAVEVALUE "Low" by calling the Procedure "Minimum".
This PLUS Procedure compares the values by using a series of IF
Statements. The TEMPORARY variable "Lowval" is used to hold
the intermediary values and finally the value that is determined to be
lowest by comparison. That value is then returned to Operand B of the
SAVEVALUE block. When the model run completes, press [F5], [F6],
[F7],
and [F8] to
see the values that were compared in the Status Line of the Main Window.
[F9] will
show you the lowest value chosen from the four.
; GPSS World Sample File - FACTORL.GPS
;
; This model uses a PLUS Procedure to calculate
; factorials.
; You can either change the Initial statement to
; calculate factorials based on different values
; or use the Initial command after the model is
; Translated to Initialize the SAVEVALUE Facval.
; After the model has run, you can press the
; function key s
to display the value of the
; calculation in the status line. This function
; key has been preset to display X$Answer.
; This PLUS Procedure is designed to calculate
; Factorials for positive integers only.
;
INITIAL X$Facval,10
GENERATE 1
SAVEVALUE Answer,(Factorial(X$Facval))
TERMINATE 1
PROCEDURE Factorial(Arg1) BEGIN
TEMPORARY Result;
Result=1;
WHILE(Arg1>1) DO BEGIN
Result=Result#Arg1;
Arg1=(Arg1-1);
END;
RETURN Result;
END;
This PLUS Procedure uses a WHILE loop. It takes an Argument that is provided via the evaluation of a SAVEVALUE and finds the factorial of that value by looping through the WHILE DO, accumulating a result by multiplying the TEMPORARY "Result" (which is originally set equal to 1) by the variable Arg1. With each loop, Arg1 is decreased by one until it reaches 1. At this point, the loop is ended and the RETURN is executed which passes the final accumulated value back to Operand B of the SAVEVALUE Answer. You can