The Bank Tutorial (OO API) Part 2: More examples of SimPy Simulation

Authors:

G A Vignaux, K G Muller

Date:

2010 April

SimPy release:

2.3.1

Python-Version:

2.6 and later

OO API Bank Tutorial version

This manual is a rework of the Bank Tutorial Part 2. Its goal is to show how the simple tutorial models can be written in the advanced OO API.

Note

To contrast the OO API with the procedural SimPy API, the reader should read both “Bank Tutorial Part 2” documents side by side.

Introduction

The first Bank tutorial, The Bank, developed and explained a series of simulation models of a simple bank using SimPy. In various models, customers arrived randomly, queued up to be served at one or several counters, modelled using the Resource class, and, in one case, could choose the shortest among several queues. It demonstrated the use of the Monitor class to record delays and showed how a model() mainline for the simulation was convenient to execute replications of simulation runs.

In this extension to The Bank, I provide more examples of SimPy facilities for which there was no room and for some that were developed since it was written. These facilities are generally more complicated than those introduced before. They include queueing with priority, possibly with preemption, reneging, plotting, interrupting, waiting until a condition occurs (waituntil) and waiting for events to occur.

Starting with SimPy 2.0 an object-oriented programmer’s interface was added to the package and it is this version that is described here. It is quite compatible with the procedural approach. The object-oriented interface, however, can support the process of developing and extending a simulation model better than the procedural approach.

The programs are available without line numbers and ready to go, in directory bankprograms. Some have trace statements for demonstration purposes, others produce graphical output to the screen. Let me encourage you to run them and modify them for yourself.

SimPy itself can be obtained from: http://simpy.sourceforge.net/. It is compatible with Python version 2.3 onwards. The examples in this documentation run with SimPy version 1.5 and later.

This tutorial should be read with the SimPy Manual and CheatsheetOO at your side for reference.

Priority Customers

In many situations there is a system of priority service. Those customers with high priority are served first, those with low priority must wait. In some cases, preemptive priority will even allow a high-priority customer to interrupt the service of one with a lower priority.

SimPy implements priority requests with an extra numerical priority argument in the yield request command, higher values meaning higher priority. For this to operate, the requested Resource must have been defined with qType=PriorityQ. This require importing the PriorityQ class from SimPy.Simulation.

Priority Customers without preemption

In the first example, we modify the program with random arrivals, one counter, and a fixed service time (like bank07.py in The Bank tutorial) to process a high priority customer. Warning: the seedVal value has been changed to 98989 to make the story more exciting.

The modifications are to the definition of the counter where we change the qType and to the yield request command in the visit PEM of the customer. We also need to provide each customer with a priority. Since the default is priority=0 this is easy for most of them.

To observe the priority in action, while all other customers have the default priority of 0, in lines 43 to 44 we create and activate one special customer, Guido, with priority 100 who arrives at time 23.0 (line 44). This is to ensure that he arrives after Customer03.

The visit customer method has a new parameter, P=0 (line 20) which allows us to set the customer priority.

In lines 39 to 40 the BankModel ‘s resource attribute k named Counter is defined with qType=PriorityQ so that we can request it with priority (line 25) using the statement yield request,self,self.sim.k,P

In line 23 we print out the number of customers waiting when each customer arrives.

 1""" bank20_OO: One counter with a priority customer """
 2from SimPy.Simulation import Simulation, Process, Resource, PriorityQ, hold, request, release
 3from random import expovariate, seed
 4
 5## Model components ------------------------
 6
 7class Source(Process):
 8    """ Source generates customers randomly """
 9
10    def generate(self, number, interval):
11        for i in range(number):
12            c = Customer(name="Customer%02d" % (i), sim=self.sim)
13            self.sim.activate(c, c.visit(timeInBank=12.0, P=0))
14            t = expovariate(1.0 / interval)
15            yield hold, self, t
16
17
18class Customer(Process):
19    """ Customer arrives, is served and  leaves """
20
21    def visit(self, timeInBank=0, P=0):
22        arrive = self.sim.now()       # arrival time
23        Nwaiting = len(self.sim.k.waitQ)
24        print("%8.3f %s: Queue is %d on arrival" % (self.sim.now(), self.name, Nwaiting))
25
26        yield request, self, self.sim.k, P
27        wait = self.sim.now() - arrive  # waiting time
28        print("%8.3f %s: Waited %6.3f" % (self.sim.now(), self.name, wait))
29        yield hold, self, timeInBank
30        yield release, self, self.sim.k
31
32        print("%8.3f %s: Completed" % (self.sim.now(), self.name))
33
34
35## Model ------------------------------
36class BankModel(Simulation):
37    def run(self, aseed):
38        """ PEM """
39        seed(aseed)
40        self.k = Resource(name="Counter", unitName="Karen",
41             qType=PriorityQ, sim=self)
42        s = Source('Source', sim=self)
43        self.activate(s, s.generate(number=5, interval=10.0), at=0.0)
44        guido = Customer(name="Guido     ", sim=self)
45        self.activate(guido, guido.visit(timeInBank=12.0, P=100), at=23.0)
46        self.simulate(until=maxTime)
47
48## Experiment data -------------------------
49
50maxTime = 400.0  # minutes
51seedVal = 98989
52
53## Experiment ---------------------------
54
55mymodel = BankModel()
56mymodel.run(aseed=seedVal)
57

The resulting output is as follows. The number of customers in the queue just as each arrives is displayed in the trace. That count does not include any customer in service.

 1   0.000 Customer00: Queue is 0 on arrival
 2   0.000 Customer00: Waited  0.000
 3  12.000 Customer00: Completed
 4  16.359 Customer01: Queue is 0 on arrival
 5  16.359 Customer01: Waited  0.000
 6  23.000 Guido     : Queue is 0 on arrival
 7  28.359 Customer01: Completed
 8  28.359 Guido     : Waited  5.359
 9  29.991 Customer02: Queue is 0 on arrival
10  35.776 Customer03: Queue is 1 on arrival
11  36.650 Customer04: Queue is 2 on arrival
12  40.359 Guido     : Completed
13  40.359 Customer02: Waited 10.368
14  52.359 Customer02: Completed
15  52.359 Customer03: Waited 16.583
16  64.359 Customer03: Completed
17  64.359 Customer04: Waited 27.709
18  76.359 Customer04: Completed

Reading carefully one can see that when Guido arrives Customer00 has been served and left at 12.000), Customer01 is in service and two (customers 02 and 03) are queueing. Guido has priority over those waiting and is served before them at 24.000. When Guido leaves at 36.000, Customer02 starts service.

Priority Customers with preemption

Now we allow Guido to have preemptive priority. He will displace any customer in service when he arrives. That customer will resume when Guido finishes (unless higher priority customers intervene). It requires only a change to one line of the program, adding the argument, preemptable=True to the Resource statement in line 40.

 1""" bank23_OO: One counter with a priority customer with preemption """
 2from SimPy.Simulation import Simulation, Process, Resource, PriorityQ, hold, request, release
 3from random import expovariate, seed
 4
 5## Model components ------------------------
 6
 7class Source(Process):
 8    """ Source generates customers randomly """
 9
10    def generate(self, number, interval):
11        for i in range(number):
12            c = Customer(name="Customer%02d" % (i), sim=self.sim)
13            self.sim.activate(c, c.visit(timeInBank=12.0, P=0))
14            t = expovariate(1.0 / interval)
15            yield hold, self, t
16
17
18class Customer(Process):
19    """ Customer arrives, is served and  leaves """
20
21    def visit(self, timeInBank=0, P=0):
22        arrive = self.sim.now()       # arrival time
23        Nwaiting = len(self.sim.k.waitQ)
24        print("%8.3f %s: Queue is %d on arrival" % (self.sim.now(), self.name, Nwaiting))
25
26        yield request, self, self.sim.k, P
27        wait = self.sim.now() - arrive  # waiting time
28        print("%8.3f %s: Waited %6.3f" % (self.sim.now(), self.name, wait))
29        yield hold, self, timeInBank
30        yield release, self, self.sim.k
31
32        print("%8.3f %s: Completed" % (self.sim.now(), self.name))
33
34
35## Model -----------------------------------
36class BankModel(Simulation):
37    def run(self, aseed):
38        """ PEM """
39        seed(aseed)
40        self.k = Resource(name="Counter", unitName="Karen",
41                          qType=PriorityQ, preemptable=True, sim=self)
42        s = Source('Source', sim=self)
43        self.activate(s, s.generate(number=5, interval=10.0), at=0.0)
44        guido = Customer(name="Guido     ", sim=self)
45        self.activate(guido, guido.visit(timeInBank=12.0, P=100), at=23.0)
46        self.simulate(until=maxTime)
47
48## Experiment data -------------------------
49
50maxTime = 400.0  # minutes
51seedVal = 98989
52
53## Experiment -------- ---------------------
54
55mymodel = BankModel()
56mymodel.run(aseed=seedVal)

Though Guido arrives at the same time, 23.000, he no longer has to wait and immediately goes into service, displacing the incumbent, Customer01. That customer had already completed 23.000-12.000 = 11.000 minutes of his service. When Guido finishes at 35.000, Customer01 resumes service and takes 36.000-35.000 = 1.000 minutes to finish. His total service time is the same as before (12.000 minutes).

 1   0.000 Customer00: Queue is 0 on arrival
 2   0.000 Customer00: Waited  0.000
 3  12.000 Customer00: Completed
 4  16.359 Customer01: Queue is 0 on arrival
 5  16.359 Customer01: Waited  0.000
 6  23.000 Guido     : Queue is 0 on arrival
 7  23.000 Guido     : Waited  0.000
 8  29.991 Customer02: Queue is 1 on arrival
 9  35.000 Guido     : Completed
10  35.776 Customer03: Queue is 1 on arrival
11  36.650 Customer04: Queue is 2 on arrival
12  40.359 Customer01: Completed
13  40.359 Customer02: Waited 10.368
14  52.359 Customer02: Completed
15  52.359 Customer03: Waited 16.583
16  64.359 Customer03: Completed
17  64.359 Customer04: Waited 27.709
18  76.359 Customer04: Completed

Balking and Reneging Customers

Balking occurs when a customer refuses to join a queue if it is too long. Reneging (or, better, abandonment) occurs if an impatient customer gives up while still waiting and before being served.

Balking Customers

Another term for a system with balking customers is one where “blocked customers” are “cleared”, termed by engineers a BCC system. This is very convenient analytically in queueing theory and formulae developed using this assumption are used extensively for planning communication systems. The easiest case is when no queueing is allowed.

As an example let us investigate a BCC system with a single server but the waiting space is limited. We will estimate the rate of balking when the maximum number in the queue is set to 1. On arrival into the system the customer must first check to see if there is room. We will need the number of customers in the system or waiting. We could keep a count, incrementing when a customer joins the queue or, since we have a Resource, use the length of the Resource’s waitQ. Choosing the latter we test (on line 23). If there is not enough room, we balk, incrementing a class variable Customer.numBalking at line 32 to get the total number balking during the run.

 1""" bank24_OO. BCC system with several counters """
 2from SimPy.Simulation import Simulation, Process, Resource, hold, request, release
 3from random import expovariate, seed
 4
 5## Model components ------------------------
 6
 7class Source(Process):
 8    """ Source generates customers randomly """
 9
10    def generate(self, number, meanTBA):
11        for i in range(number):
12            c = Customer(name="Customer%02d" % (i), sim=self.sim)
13            self.sim.activate(c, c.visit())
14            t = expovariate(1.0 / meanTBA)
15            yield hold, self, t
16
17
18class Customer(Process):
19    """ Customer arrives,  is served and leaves """
20
21    def visit(self):
22        arrive = self.sim.now()
23        print("%8.4f %s: Here I am " % (self.sim.now(), self.name))
24        if len(self.sim.k.waitQ) < maxInQueue:     # the test
25            yield request, self, self.sim.k
26            wait = self.sim.now() - arrive
27            print("%8.4f %s: Wait %6.3f" % (self.sim.now(), self.name, wait))
28            tib = expovariate(1.0 / timeInBank)
29            yield hold, self, tib
30            yield release, self, self.sim.k
31            print("%8.4f %s: Finished  " % (self.sim.now(), self.name))
32        else:
33            Customer.numBalking += 1
34            print("%8.4f %s: BALKING   " % (self.sim.now(), self.name))
35
36
37## Model
38class BankModel(Simulation):
39    def run(self, aseed):
40        """ PEM """
41        seed(aseed)
42        Customer.numBalking = 0
43        self.k = Resource(capacity=numServers,
44             name="Counter", unitName="Clerk", sim=self)
45        s = Source('Source', sim=self)
46        self.activate(s, s.generate(number=maxNumber, meanTBA=ARRint), at=0.0)
47        self.simulate(until=maxTime)
48
49## Experiment data -------------------------------
50
51timeInBank = 12.0  # mean, minutes
52ARRint = 10.0      # mean interarrival time, minutes
53numServers = 1     # servers
54maxInSystem = 2    # customers
55maxInQueue = maxInSystem - numServers
56
57maxNumber = 8
58maxTime = 4000.0  # minutes
59theseed = 12345
60
61## Experiment --------------------------------------
62
63mymodel = BankModel()
64mymodel.run(aseed=theseed)
65## Results -----------------------------------------
66
67nb = float(Customer.numBalking)
68print("balking rate is %8.4f per minute" % (nb / mymodel.now()))

The resulting output for a run of this program showing balking occurring is given below:

 1  0.0000 Customer00: Here I am 
 2  0.0000 Customer00: Wait  0.000
 3  0.1227 Customer00: Finished  
 4  5.3892 Customer01: Here I am 
 5  5.3892 Customer01: Wait  0.000
 6  9.6460 Customer01: Finished  
 7 22.8307 Customer02: Here I am 
 8 22.8307 Customer02: Wait  0.000
 9 25.4137 Customer02: Finished  
10 27.4258 Customer03: Here I am 
11 27.4258 Customer03: Wait  0.000
12 29.5422 Customer03: Finished  
13 35.7731 Customer04: Here I am 
14 35.7731 Customer04: Wait  0.000
15 37.1001 Customer05: Here I am 
16 42.5805 Customer04: Finished  
17 42.5805 Customer05: Wait  5.480
18 44.8795 Customer05: Finished  
19 45.3572 Customer06: Here I am 
20 45.3572 Customer06: Wait  0.000
21 50.6175 Customer06: Finished  
22 53.4141 Customer07: Here I am 
23 53.4141 Customer07: Wait  0.000
24 54.5629 Customer07: Finished  
25balking rate is   0.0000 per minute

When Customer02 arrives, numbers 00 is already in service and 01 is waiting. There is no room so 02 balks. By the vagaries of exponential random numbers, 00 takes a very long time to serve (55.0607 minutes) so the first one to find room is number 07 at 73.0765.

Reneging (or abandoning) Customers

Often in practice an impatient customer will leave the queue before being served. SimPy can model this reneging behaviour using a compound yield statement. In such a statement there are two yield clauses. An example is:

yield (request,self,counter),(hold,self,maxWaitTime)

The first tuple of this statement is the usual yield request, asking for a unit of counter Resource. The process will either get the unit immediately or be queued by the Resource. The second tuple is a reneging clause which has the same syntax as a yield hold. The requesting process will renege if the wait exceeds maxWaitTime.

There is a complication, though. The requesting PEM must discover what actually happened. Did the process get the resource or did it renege? This involves a mandatory test of self.acquired(resource). In our example, this test is in line 26.

 1""" bank21_OO: One counter with impatient customers """
 2from SimPy.Simulation import Simulation, Process, Resource, hold, request, release
 3from random import expovariate, seed
 4
 5## Model components ------------------------
 6
 7class Source(Process):
 8    """ Source generates customers randomly """
 9
10    def generate(self, number, interval):
11        for i in range(number):
12            c = Customer(name="Customer%02d" % (i), sim=self.sim)
13            self.sim.activate(c, c.visit(timeInBank=15.0))
14            t = expovariate(1.0 / interval)
15            yield hold, self, t
16
17
18class Customer(Process):
19    """ Customer arrives, is served and  leaves """
20
21    def visit(self, timeInBank=0):
22        arrive = self.sim.now()       # arrival time
23        print("%8.3f %s: Here I am     " % (self.sim.now(), self.name))
24
25        yield (request, self, self.sim.counter), (hold, self, maxWaitTime)
26        wait = self.sim.now() - arrive  # waiting time
27        if self.acquired(self.sim.counter):
28            print("%8.3f %s: Waited %6.3f" % (self.sim.now(), self.name, wait))
29            yield hold, self, timeInBank
30            yield release, self, self.sim.counter
31            print("%8.3f %s: Completed" % (self.sim.now(), self.name))
32        else:
33            print("%8.3f %s: Waited %6.3f. I am off" % (self.sim.now(), self.name, wait))
34
35
36## Model  ----------------------------------
37class BankModel(Simulation):
38    def run(self, aseed):
39        """ PEM """
40        seed(aseed)
41        self.counter = Resource(name="Karen", sim=self)
42        source = Source('Source', sim=self)
43        self.activate(source,
44             source.generate(number=5, interval=10.0), at=0.0)
45        self.simulate(until=maxTime)
46
47## Experiment data -------------------------
48
49maxTime = 400.0     # minutes
50maxWaitTime = 12.0  # minutes. maximum time to wait
51seedVal = 98989
52
53## Experiment  ----------------------------------
54
55mymodel = BankModel()
56mymodel.run(aseed=seedVal)
 1   0.000 Customer00: Here I am     
 2   0.000 Customer00: Waited  0.000
 3  15.000 Customer00: Completed
 4  16.359 Customer01: Here I am     
 5  16.359 Customer01: Waited  0.000
 6  29.991 Customer02: Here I am     
 7  31.359 Customer01: Completed
 8  31.359 Customer02: Waited  1.368
 9  35.776 Customer03: Here I am     
10  36.650 Customer04: Here I am     
11  46.359 Customer02: Completed
12  46.359 Customer03: Waited 10.583
13  48.650 Customer04: Waited 12.000. I am off
14  61.359 Customer03: Completed

Customer01 arrives after 00 but has only 12 minutes patience. After that time in the queue (at time 14.166) he abandons the queue to leave 02 to take his place. 03 also abandons. 04 finds an empty system and takes the server without having to wait.

Processes

In some simulations it is valuable for one SimPy Process to interrupt another. This can only be done when the victim is “active”; that is when it has an event scheduled for it. It must be executing a yield hold statement.

A process waiting for a resource (after a yield request statement) is passive and cannot be interrupted by another. Instead the yield waituntil and yield waitevent facilities have been introduced to allow processes to wait for conditions set by other processes.

Interrupting a Process.

Klaus goes into the bank to talk to the manager. For clarity we ignore the counters and other customers. During his conversation his cellphone rings. When he finishes the call he continues the conversation.

In this example, call is an object of the Call Process class whose only purpose is to make the cellphone ring after a delay, timeOfCall, an argument to its ring PEM (line 26).

klaus, a Customer, is interrupted by the call (line 29). He is in the middle of a yield hold (line 12). When he exits from that command it is as if he went into a trance when talking to the bank manager. He suddenly wakes up and must check (line 13) to see whether has finished his conversation (if there was no call) or has been interrupted.

If self.interrupted() is False he was not interrupted and leaves the bank (line 21) normally. If it is True, he was interrupted by the call, remembers how much conversation he has left (line 14), resets the interrupt (line 15) and then deals with the call. When he finishes (line 19) he can resume the conversation, with, now we assume, a thoroughly irritated bank manager v(line 20).

 1""" bank22_OO: An interruption by a phone call """
 2from SimPy.Simulation  import Simulation, Process, hold
 3
 4## Model components ------------------------
 5
 6class Customer(Process):
 7    """ Customer arrives, looks around and leaves """
 8
 9    def visit(self, timeInBank, onphone):
10        print("%7.4f %s: Here I am" % (self.sim.now(), self.name))
11        yield hold, self, timeInBank
12        if self.interrupted():
13            timeleft = self.interruptLeft
14            self.interruptReset()
15            print("%7.4f %s: Excuse me" % (self.sim.now(), self.name))
16            print("%7.4f %s: Hello! I'll call back" % (self.sim.now(), self.name))
17            yield hold, self, onphone
18            print("%7.4f %s: Sorry, where were we?" % (self.sim.now(), self.name))
19            yield hold, self, timeleft
20        print("%7.4f %s: I must leave" % (self.sim.now(), self.name))
21
22
23class Call(Process):
24    """ Cellphone call arrives and interrupts """
25
26    def ring(self, klaus, timeOfCall):
27        yield hold, self, timeOfCall
28        print("%7.4f Ringgg!" % (self.sim.now()))
29        self.interrupt(klaus)
30
31## Model -----------------------------------
32
33class BankModel(Simulation):
34    def run(self):
35        """ PEM """
36        klaus = Customer(name="Klaus", sim=self)
37        self.activate(klaus, klaus.visit(timeInBank, onphone))
38        call = Call(sim=self)
39        self.activate(call, call.ring(klaus, timeOfCall))
40        self.simulate(until=maxTime)
41
42## Experiment data -------------------------
43
44timeInBank = 20.0
45timeOfCall = 9.0
46onphone = 3.0
47maxTime = 100.0
48
49## Experiment  -----------------------------
50mymodel = BankModel()
51mymodel.run()
52
1 0.0000 Klaus: Here I am
2 9.0000 Ringgg!
3 9.0000 Klaus: Excuse me
4 9.0000 Klaus: Hello! I'll call back
512.0000 Klaus: Sorry, where were we?
623.0000 Klaus: I must leave

As this has no random numbers the results are reasonably clear: the interrupting call occurs at 9.0. It takes klaus 3 minutes to listen to the message and he resumes the conversation with the bank manager at 12.0. His total time of conversation is 9.0 + 11.0 = 20.0 minutes as it would have been if the interrupt had not occurred.

waituntil the Bank door opens

Customers arrive at random, some of them getting to the bank before the door is opened by a doorman. They wait for the door to be opened and then rush in and queue to be served. The door is modeled by an attribute door of BankModel.

This model uses the waituntil yield command. In the program listing the door is initially closed (line 58) and a method to test if it is open is defined at line 54.

The Doorman class is defined starting at line 7 and the single doorman is created and activated at at lines 59 and 60. The doorman waits for an average 10 minutes (line 11) and then opens the door.

The Customer class is defined at 24 and a new customer prints out Here I am on arrival. If the door is still closed, he adds but the door is shut and settles down to wait (line 35), using the yield waituntil command. When the door is opened by the doorman the dooropen state is changed and the customer (and all others waiting for the door) proceed. A customer arriving when the door is open will not be delayed.

 1"""bank14_OO: *waituntil* the Bank door opens"""
 2from SimPy.Simulation import Simulation, Process, Resource, hold, waituntil, request, release
 3from random import expovariate, seed
 4
 5## Model components ------------------------
 6
 7class Doorman(Process):
 8    """ Doorman opens the door"""
 9    def openthedoor(self):
10        """ He will open the door when he arrives"""
11        yield hold, self, expovariate(1.0 / 10.0)
12        self.sim.door = 'Open'
13        print("%7.4f Doorman: Ladies and "\
14              "Gentlemen! You may all enter." % (self.sim.now()))
15
16
17class Source(Process):
18    """ Source generates customers randomly"""
19    def generate(self, number, rate):
20        for i in range(number):
21            c = Customer(name="Customer%02d" % (i), sim=self.sim)
22            self.sim.activate(c, c.visit(timeInBank=12.0))
23            yield hold, self, expovariate(rate)
24
25
26class Customer(Process):
27    """ Customer arrives, is served and leaves """
28    def visit(self, timeInBank=10):
29        arrive = self.sim.now()
30
31        if self.sim.dooropen():
32            msg = ' and the door is open.'
33        else:
34            msg = ' but the door is shut.'
35        print("%7.4f %s: Here I am%s" % (self.sim.now(), self.name, msg))
36
37        yield waituntil, self, self.sim.dooropen
38
39        print("%7.4f %s: I can  go in!" % (self.sim.now(), self.name))
40        wait = self.sim.now() - arrive
41        print("%7.4f %s: Waited %6.3f" % (self.sim.now(), self.name, wait))
42
43        yield request, self, self.sim.counter
44        tib = expovariate(1.0 / timeInBank)
45        yield hold, self, tib
46        yield release, self, self.sim.counter
47
48        print("%7.4f %s: Finished    " % (self.sim.now(), self.name))
49
50## Model  ----------------------------------
51
52class BankModel(Simulation):
53    def dooropen(self):
54        return self.door == 'Open'
55
56    def run(self, aseed):
57        """ PEM """
58        seed(aseed)
59        self.counter = Resource(capacity=1, name="Clerk", sim=self)
60        self.door = 'Shut'
61        doorman = Doorman(sim=self)
62        self.activate(doorman, doorman.openthedoor())
63        source = Source(sim=self)
64        self.activate(source,
65             source.generate(number=5, rate=0.1), at=0.0)
66        self.simulate(until=400.0)
67
68## Experiment data -------------------------
69
70maxTime = 2000.0   # minutes
71seedVal = 393939
72
73## Experiment  ----------------------------------
74
75mymodel = BankModel()
76mymodel.run(aseed=seedVal)
77

An output run for this programs shows how the first three customers have to wait until the door is opened.

 1 0.0000 Customer00: Here I am but the door is shut.
 2 1.1489 Doorman: Ladies and Gentlemen! You may all enter.
 3 1.1489 Customer00: I can  go in!
 4 1.1489 Customer00: Waited  1.149
 5 6.5691 Customer00: Finished    
 6 8.3438 Customer01: Here I am and the door is open.
 7 8.3438 Customer01: I can  go in!
 8 8.3438 Customer01: Waited  0.000
 915.5704 Customer02: Here I am and the door is open.
1015.5704 Customer02: I can  go in!
1115.5704 Customer02: Waited  0.000
1221.2664 Customer03: Here I am and the door is open.
1321.2664 Customer03: I can  go in!
1421.2664 Customer03: Waited  0.000
1521.9473 Customer04: Here I am and the door is open.
1621.9473 Customer04: I can  go in!
1721.9473 Customer04: Waited  0.000
1827.6401 Customer01: Finished    
1956.5248 Customer02: Finished    
2057.3640 Customer03: Finished    
2177.3587 Customer04: Finished    

Wait for the doorman to give a signal: waitevent

Customers arrive at random, some of them getting to the bank before the door is open. This is controlled by an automatic machine called the doorman which opens the door only at intervals of 30 minutes (it is a very secure bank). The customers wait for the door to be opened and all those waiting enter and proceed to the counter. The door is closed behind them.

This model uses the yield waitevent command which requires a SimEvent attribute for BankModel to be defined (line 56). The Doorman class is defined at line 7 and the doorman is created and activated at at labels 56 and 57. The doorman waits for a fixed time (label 12) and then tells the customers that the door is open. This is achieved on line 13 by signalling the dooropen event.

The Customer class is defined at 24 and in its PEM, when a customer arrives, he prints out Here I am. If the door is still closed, he adds “but the door is shut` and settles down to wait for the door to be opened using the yield waitevent command (line 34). When the door is opened by the doorman (that is, he sends the dooropen.signal() the customer and any others waiting may proceed.

 1""" bank13_OO: Wait for the doorman to give a signal: *waitevent*"""
 2from SimPy.Simulation import Simulation, Process, Resource, SimEvent, hold, request, release, waitevent
 3from random import *
 4
 5## Model components ------------------------
 6
 7class Doorman(Process):
 8    """ Doorman opens the door"""
 9    def openthedoor(self):
10        """ He will opens the door at fixed intervals"""
11        for i in range(5):
12            yield hold, self,  30.0
13            self.sim.dooropen.signal()
14            print("%7.4f You may enter" % (self.sim.now()))
15
16
17class Source(Process):
18    """ Source generates customers randomly"""
19    def generate(self, number, rate):
20        for i in range(number):
21            c = Customer(name="Customer%02d" % (i), sim=self.sim)
22            self.sim.activate(c, c.visit(timeInBank=12.0))
23            yield hold, self, expovariate(rate)
24
25
26class Customer(Process):
27    """ Customer arrives, is served and leaves """
28    def visit(self, timeInBank=10):
29        arrive = self.sim.now()
30
31        if self.sim.dooropen.occurred:
32            msg = '.'
33        else:
34            msg = ' but the door is shut.'
35        print("%7.4f %s: Here I am%s" % (self.sim.now(), self.name, msg))
36        yield waitevent, self, self.sim.dooropen
37
38        print("%7.4f %s: The door is open!" % (self.sim.now(), self.name))
39
40        wait = self.sim.now() - arrive
41        print("%7.4f %s: Waited %6.3f" % (self.sim.now(), self.name, wait))
42
43        yield request, self, self.sim.counter
44        tib = expovariate(1.0 / timeInBank)
45        yield hold, self, tib
46        yield release, self, self.sim.counter
47
48        print("%7.4f %s: Finished    " % (self.sim.now(), self.name))
49
50## Model  ----------------------------------
51
52class BankModel(Simulation):
53    def run(self, aseed):
54        """ PEM """
55        seed(aseed)
56        self.dooropen = SimEvent("Door Open", sim=self)
57        self.counter = Resource(1, name="Clerk", sim=self)
58        doorman = Doorman(sim=self)
59        self.activate(doorman, doorman.openthedoor())
60        source = Source(sim=self)
61        self.activate(source,
62             source.generate(number=5, rate=0.1), at=0.0)
63        self.simulate(until=maxTime)
64
65## Experiment data -------------------------
66
67maxTime = 400.0  # minutes
68seedVal = 393939
69
70## Experiment  ----------------------------------
71
72mymodel = BankModel()
73mymodel.run(aseed=seedVal)

An output run for this programs shows how the first three customers have to wait until the door is opened.

 1 0.0000 Customer00: Here I am but the door is shut.
 2 1.1489 Customer01: Here I am but the door is shut.
 3 9.4928 Customer02: Here I am but the door is shut.
 414.0096 Customer03: Here I am but the door is shut.
 521.2361 Customer04: Here I am but the door is shut.
 630.0000 You may enter
 730.0000 Customer04: The door is open!
 830.0000 Customer04: Waited  8.764
 930.0000 Customer03: The door is open!
1030.0000 Customer03: Waited 15.990
1130.0000 Customer02: The door is open!
1230.0000 Customer02: Waited 20.507
1330.0000 Customer01: The door is open!
1430.0000 Customer01: Waited 28.851
1530.0000 Customer00: The door is open!
1630.0000 Customer00: Waited 30.000
1736.8352 Customer04: Finished    
1837.6524 Customer03: Finished    
1952.4654 Customer02: Finished    
2060.0000 You may enter
2181.3502 Customer01: Finished    
2282.1893 Customer00: Finished    
2390.0000 You may enter
24120.0000 You may enter
25150.0000 You may enter

Monitors

Monitors (and Tallys) are used to track and record values in a simulation. They store a list of [time,value] pairs, one pair being added whenever the observe method is called. A particularly useful characteristic is that they continue to exist after the simulation has been completed. Thus further analysis of the results can be carried out.

Monitors have a set of simple statistical methods such as mean and var to calculate the average and variance of the observed values – useful in estimating the mean delay, for example.

They also have the timeAverage method that calculates the time-weighted average of the recorded values. It determines the total area under the time~value graph and divides by the total time. This is useful for estimating the average number of customers in the bank, for example. There is an important caveat in using this method. To estimate the correct time average you must certainly observe the value (say the number of customers in the system) whenever it changes (as well as at any other time you wish) but, and this is important, observing the new value. The old value was recorded earlier. In practice this means that if we wish to observe a changing value, n, using the Monitor, Mon, we must keep to the the following pattern:

n = n+1
Mon.observe(n,self.sim.now())

Thus you make the change (not only increases) and then observe the new value. Of course the simulation time now() has not changed between the two statements.

Plotting a Histogram of Monitor results

A Monitor can construct a histogram from its data using the histogram method. In this model we monitor the time in the system for the customers. This is calculated for each customer in line 29, using the arrival time saved in line 19. We create the Monitor attribute of BankModel, Mon, at line 39 and the times are observed at line 30.

The histogram is constructed from the Monitor, after the simulation has finished, at line 58. The SimPy SimPlot package allows simple plotting of results from simulations. Here we use the SimPlot plotHistogram method. The plotting routines appear in lines 60-64. The plotHistogram call is in line 61.

 1"""bank17_OO: Plotting a Histogram of Monitor results"""
 2from SimPy.Simulation  import Simulation, Process, Resource, Monitor, hold, request, release
 3from SimPy.SimPlot import *
 4from random import  expovariate, seed
 5
 6## Model components ------------------------
 7
 8class Source(Process):
 9    """ Source generates customers randomly"""
10    def generate(self, number, rate):
11        for i in range(number):
12            c = Customer(name="Customer%02d" % (i), sim=self.sim)
13            self.sim.activate(c, c.visit(timeInBank=12.0))
14            yield hold, self, expovariate(rate)
15
16
17class Customer(Process):
18    """ Customer arrives, is served and leaves """
19    def visit(self, timeInBank):
20        arrive = self.sim.now()
21        #print("%8.4f %s: Arrived     "%(now(), self.name))
22
23        yield request, self, self.sim.counter
24        #print("%8.4f %s: Got counter "%(now(), self.name))
25        tib = expovariate(1.0 / timeInBank)
26        yield hold, self, tib
27        yield release, self, self.sim.counter
28
29        #print("%8.4f %s: Finished    " % (now(), self.name))
30        t = self.sim.now() - arrive
31        self.sim.Mon.observe(t)
32
33## Model  ----------------------------------
34
35class BankModel(Simulation):
36    def run(self, aseed):
37        """ PEM """
38        seed(aseed)
39        self.counter = Resource(1, name="Clerk", sim=self)
40        self.Mon = Monitor('Time in the Bank', sim=self)
41        source = Source(sim=self)
42        self.activate(source,
43             source.generate(number=20, rate=0.1), at=0.0)
44        self.simulate(until=maxTime)
45
46## Experiment data -------------------------
47
48maxTime = 400.0   # minutes
49
50N = 0
51seedVal = 393939
52
53## Experiment  -----------------------------
54
55modl = BankModel()
56modl.run(aseed=seedVal)
57
58## Output ----------------------------------
59Histo = modl.Mon.histogram(low=0.0, high=200.0, nbins=20)
60
61plt = SimPlot()
62plt.plotHistogram(Histo, xlab='Time (min)',
63                  title="Time in the Bank",
64                  color="red", width=2)
65plt.mainloop()

Monitoring a Resource

Now consider observing the number of customers waiting or executing in a Resource. Because of the need to observe the value after the change but at the same simulation instant, it is impossible to use the length of the Resource’s waitQ directly with a Monitor defined outside the Resource. Instead Resources can be set up with built-in Monitors.

Here is an example using a Monitored Resource. We intend to observe the average number waiting and active in the counter resource. counter is defined at line 35 as a BankModel attribute and we have set monitored=True. This establishes two Monitors: waitMon, to record changes in the numbers waiting and actMon to record changes in the numbers active in the counter. We need make no further change to the operation of the program as monitoring is then automatic. No observe calls are necessary.

After completion of the run method, we calculate the timeAverage of both waitMon and actMon (lines 53-54). These can then be printed at the end of the program (line 55).

 1"""bank15_OO: Monitoring a Resource"""
 2from SimPy.Simulation  import Simulation, Process, Resource, Monitor, hold, request, release
 3from random import *
 4
 5## Model components ------------------------
 6
 7class Source(Process):
 8    """ Source generates customers randomly"""
 9    def generate(self, number, rate):
10        for i in range(number):
11            c = Customer(name="Customer%02d" % (i), sim=self.sim)
12            self.sim.activate(c, c.visit(timeInBank=12.0, counter=self.sim.counter))
13            yield hold, self, expovariate(rate)
14
15
16class Customer(Process):
17    """ Customer arrives, is served and leaves """
18    def visit(self, timeInBank, counter):
19        arrive = self.sim.now()
20        print("%8.4f %s: Arrived     " % (self.sim.now(), self.name))
21
22        yield request, self, counter
23        print("%8.4f %s: Got counter " % (self.sim.now(), self.name))
24        tib = expovariate(1.0 / timeInBank)
25        yield hold, self, tib
26        yield release, self, counter
27
28        print("%8.4f %s: Finished    " % (self.sim.now(), self.name))
29
30## Model  ----------------------------------
31
32class BankModel(Simulation):
33    def run(self, aseed):
34        """ PEM """
35        seed(aseed)
36        self.counter = Resource(capacity=1, name="Clerk", monitored=True, sim=self)
37        source = Source(sim=self)
38        self.activate(source,
39                 source.generate(number=5, rate=0.1), at=0.0)
40        self.simulate(until=maxTime)
41
42        return
43
44## Experiment data -------------------------
45
46maxTime = 400.0    # minutes
47seedVal = 393939
48
49## Experiment  ----------------------------------
50
51modl = BankModel()
52modl.run(aseed=seedVal)
53
54nrwaiting = modl.counter.waitMon.timeAverage()
55nractive = modl.counter.actMon.timeAverage()
56print('Average waiting = %6.4f\nAverage active  = %6.4f\n' % (nrwaiting, nractive))

Plotting from Resource Monitors

Like all Monitors, waitMon and actMon in a monitored Resource contain information that enables us to graph the output. Alternative plotting packages can be used; here we use the simple SimPy.SimPlot package just to graph the number of customers waiting for the counter. The program is a simple modification of the one that uses a monitored Resource.

The SimPlot package is imported at line 3. No major changes are made to the main part of the program except that I commented out the print statements. The changes occur in the run method from lines 38 to 39. The simulation now generates and processes 20 customers (line 39). The Monitors of the counter Resource attribute still exist when the simulation has terminated.

The additional plotting actions take place in lines 54 to 57. Line 55-56 construct a step plot and graphs the number in the waiting queue as a function of time. waitMon is primarily a list of [time,value] pairs which the plotStep method of the SimPlot object, plt uses without change. On running the program the graph is plotted; the user has to terminate the plotting mainloop on the screen.

 1"""bank16_OO: Plotting from  Resource Monitors"""
 2from SimPy.Simulation import Simulation, Process, Resource, hold, request, release
 3from SimPy.SimPlot import *
 4from random import expovariate, seed
 5
 6## Model components ------------------------
 7
 8class Source(Process):
 9    """ Source generates customers randomly"""
10    def generate(self, number, rate):
11        for i in range(number):
12            c = Customer(name="Customer%02d" % (i), sim=self.sim)
13            self.sim.activate(c, c.visit(timeInBank=12.0))
14            yield hold, self, expovariate(rate)
15
16
17class Customer(Process):
18    """ Customer arrives,  is served and leaves """
19    def visit(self, timeInBank):
20        arrive = self.sim.now()
21        #print("%8.4f %s: Arrived     " % (now(), self.name))
22
23        yield request, self, self.sim.counter
24        #print("%8.4f %s: Got counter " % (now(), self.name))
25        tib = expovariate(1.0 / timeInBank)
26        yield hold, self, tib
27        yield release, self, self.sim.counter
28
29        #print("%8.4f %s: Finished    " % (now(), self.name))
30
31## Model -----------------------------------
32
33class BankModel(Simulation):
34    def run(self, aseed):
35        """ PEM """
36        seed(aseed)
37        self.counter = Resource(1, name="Clerk", monitored=True, sim=self)
38        source = Source(sim=self)
39        self.activate(source,
40             source.generate(number=20, rate=0.1), at=0.0)
41        self.simulate(until=maxTime)
42
43## Experiment data -------------------------
44
45maxTime = 400.0   # minutes
46seedVal = 393939
47
48## Experiment -----------------------------------
49
50mymodel = BankModel()
51mymodel.run(aseed=seedVal)
52
53## Output ---------------------------------------
54
55plt = SimPlot()
56plt.plotStep(mymodel.counter.waitMon,
57        color="red", width=2)
58plt.mainloop()

Acknowledgements

I thank Klaus Muller, Bob Helmbold, Mukhlis Matti and the other developers and users of SimPy for improving this document by sending their comments. I would be grateful for any further corrections or suggestions. Please send them to: vignaux at users.sourceforge.net.

References