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.

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: https://github.com/SimPyClassic/SimPyClassic. It is compatible with Python version 2.7 onwards. The examples in this documentation run with SimPy version 1.5 and later.

This tutorial should be read with the SimPy Manual or Cheatsheet at your side for reference.

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 (label #7).

klaus, a Customer, is interrupted by the call (Label #8). He is in the middle of a yield hold (label #1). 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 (label #2) 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 (label #6) normally. If it is True, he was interrupted by the call, remembers how much conversation he has left (Label #3), resets the interrupt and then deals with the call. When he finishes (label #4) he can resume the conversation, with, now we assume, a thoroughly irritated bank manager (label #5).

""" bank22: An interruption by a phone call """
from SimPy.Simulation import *

# Model components ------------------------


class Customer(Process):
    """ Customer arrives, looks around and leaves """

    def visit(self, timeInBank, onphone):
        print("%7.4f %s: Here I am" % (now(), self.name))
        yield hold, self, timeInBank  # 1
        if self.interrupted():  # 2
            timeleft = self.interruptLeft  # 3
            self.interruptReset()
            print("%7.4f %s: Excuse me" % (now(), self.name))
            print("%7.4f %s: Hello! I'll call back" % (now(), self.name))
            yield hold, self, onphone
            print("%7.4f %s: Sorry, where were we?" % (now(), self.name))  # 4
            yield hold, self, timeleft  # 5
        print("%7.4f %s: I must leave" % (now(), self.name))  # 6


class Call(Process):
    """ Cellphone call arrives and interrupts """

    def ring(self, klaus, timeOfCall):  # 7
        yield hold, self, timeOfCall  # 8
        print("%7.4f Ringgg!" % (now()))
        self.interrupt(klaus)

# Experiment data -------------------------


timeInBank = 20.0
timeOfCall = 9.0
onphone = 3.0
maxTime = 100.0


# Model/Experiment  ----------------------------------

initialize()
klaus = Customer(name="Klaus")
activate(klaus, klaus.visit(timeInBank, onphone))
call = Call(name="klaus")
activate(call, call.ring(klaus, timeOfCall))
simulate(until=maxTime)
 0.0000 Klaus: Here I am
 9.0000 Ringgg!
 9.0000 Klaus: Excuse me
 9.0000 Klaus: Hello! I'll call back
12.0000 Klaus: Sorry, where were we?
23.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.

This model uses the waituntil yield command. In the program listing the door is initially closed (label #1) and a function to test if it is open is defined at label #2.

The Doorman class is defined starting at label #3 and the single doorman is created and activated at at labels #7 and #8. The doorman waits for an average 10 minutes (label #4) and then opens the door.

The Customer class is defined at label #5 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 (label #6), 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.

"""bank14: *waituntil* the Bank door opens"""
from SimPy.Simulation import *
from random import expovariate, seed

# Model components ------------------------
door = 'Shut'  # 1


def dooropen():  # 2
    return door == 'Open'


class Doorman(Process):  # 3
    """ Doorman opens the door"""

    def openthedoor(self):
        """ He will open the door when he arrives"""
        global door
        yield hold, self, expovariate(1.0 / 10.0)  # 4
        door = 'Open'
        print("%7.4f Doorman: Ladies and "
              "Gentlemen! You may all enter." % (now()))


class Source(Process):
    """ Source generates customers randomly"""

    def generate(self, number, rate):
        for i in range(number):
            c = Customer(name="Customer%02d" % (i))
            activate(c, c.visit(timeInBank=12.0))
            yield hold, self, expovariate(rate)


class Customer(Process):  # 5
    """ Customer arrives, is served and leaves """

    def visit(self, timeInBank=10):
        arrive = now()
        if dooropen():
            msg = ' and the door is open.'
        else:
            msg = ' but the door is shut.'
        print("%7.4f %s: Here I am%s" % (now(), self.name, msg))

        yield waituntil, self, dooropen  # 6

        print("%7.4f %s: I can  go in!" % (now(), self.name))
        wait = now() - arrive
        print("%7.4f %s: Waited %6.3f" % (now(), self.name, wait))

        yield request, self, counter
        tib = expovariate(1.0 / timeInBank)
        yield hold, self, tib
        yield release, self, counter

        print("%7.4f %s: Finished    " % (now(), self.name))

# Experiment data -------------------------


maxTime = 2000.0   # minutes
counter = Resource(1, name="Clerk")

# Model  ----------------------------------


def model(SEED=393939):
    seed(SEED)

    initialize()
    door = 'Shut'
    doorman = Doorman()  # 7
    activate(doorman, doorman.openthedoor())  # 8
    source = Source()
    activate(source,
             source.generate(number=5, rate=0.1), at=0.0)
    simulate(until=400.0)


# Experiment  ----------------------------------
model()

The output from a run for this programs shows how the first customer has to wait until the door is opened.

 0.0000 Customer00: Here I am but the door is shut.
 1.1489 Doorman: Ladies and Gentlemen! You may all enter.
 1.1489 Customer00: I can  go in!
 1.1489 Customer00: Waited  1.149
 6.5691 Customer00: Finished    
 8.3438 Customer01: Here I am and the door is open.
 8.3438 Customer01: I can  go in!
 8.3438 Customer01: Waited  0.000
15.5704 Customer02: Here I am and the door is open.
15.5704 Customer02: I can  go in!
15.5704 Customer02: Waited  0.000
21.2664 Customer03: Here I am and the door is open.
21.2664 Customer03: I can  go in!
21.2664 Customer03: Waited  0.000
21.9473 Customer04: Here I am and the door is open.
21.9473 Customer04: I can  go in!
21.9473 Customer04: Waited  0.000
27.6401 Customer01: Finished    
56.5248 Customer02: Finished    
57.3640 Customer03: Finished    
77.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 to be defined (label #1). The Doorman class is defined at label #2 and the doorman is created and activated at labels #7 and #8. The doorman waits for a fixed time (label #3) and then tells the customers that the door is open. This is achieved on label #4 by signalling the dooropen event.

The Customer class is defined at label #5 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 (label #6). When the door is opened by the doorman (that is, he sends the dooropen.signal() the customer and any others waiting may proceed.

""" bank13: Wait for the doorman to give a signal: *waitevent*"""
from SimPy.Simulation import *
from random import *

# Model components ------------------------

dooropen = SimEvent("Door Open")  # 1


class Doorman(Process):  # 2
    """ Doorman opens the door"""

    def openthedoor(self):
        """ He will opens the door at fixed intervals"""
        for i in range(5):
            yield hold, self, 30.0  # 3
            dooropen.signal()  # 4
            print("%7.4f You may enter" % (now()))


class Source(Process):
    """ Source generates customers randomly"""

    def generate(self, number, rate):
        for i in range(number):
            c = Customer(name="Customer%02d" % (i))
            activate(c, c.visit(timeInBank=12.0))
            yield hold, self, expovariate(rate)


class Customer(Process):  # 5
    """ Customer arrives, is served and leaves """

    def visit(self, timeInBank=10):
        arrive = now()

        if dooropen.occurred:
            msg = '.'
        else:
            msg = ' but the door is shut.'
        print("%7.4f %s: Here I am%s" % (now(), self.name, msg))
        yield waitevent, self, dooropen

        print("%7.4f %s: The door is open!" % (now(), self.name))

        wait = now() - arrive
        print("%7.4f %s: Waited %6.3f" % (now(), self.name, wait))

        yield request, self, counter
        tib = expovariate(1.0 / timeInBank)
        yield hold, self, tib
        yield release, self, counter

        print("%7.4f %s: Finished    " % (now(), self.name))

# Experiment data -------------------------


maxTime = 400.0  # minutes

counter = Resource(1, name="Clerk")

# Model  ----------------------------------


def model(SEED=232323):
    seed(SEED)

    initialize()
    doorman = Doorman()  # 7
    activate(doorman, doorman.openthedoor())  # 8
    source = Source()
    activate(source,
             source.generate(number=5, rate=0.1), at=0.0)
    simulate(until=maxTime)


# Experiment  ----------------------------------

model()

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

 0.0000 Customer00: Here I am but the door is shut.
13.6767 Customer01: Here I am but the door is shut.
13.9068 Customer02: Here I am but the door is shut.
30.0000 You may enter
30.0000 Customer02: The door is open!
30.0000 Customer02: Waited 16.093
30.0000 Customer01: The door is open!
30.0000 Customer01: Waited 16.323
30.0000 Customer00: The door is open!
30.0000 Customer00: Waited 30.000
34.0411 Customer03: Here I am but the door is shut.
40.8095 Customer04: Here I am but the door is shut.
55.4721 Customer02: Finished    
57.2363 Customer01: Finished    
60.0000 You may enter
60.0000 Customer04: The door is open!
60.0000 Customer04: Waited 19.190
60.0000 Customer03: The door is open!
60.0000 Customer03: Waited 25.959
77.0409 Customer00: Finished    
90.0000 You may enter
104.8327 Customer04: Finished    
118.4142 Customer03: Finished    
120.0000 You may enter
150.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,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 at label #2, using the arrival time saved at label #1. We create the Monitor, Mon, at label #4 and the times are observed at label #3.

The histogram is constructed from the Monitor, after the simulation has finished, at label #5. The SimPy SimPlot package allows simple plotting of results from simulations. Here we use the SimPlot plotHistogram method. The plotting routines appear between labels #6 and #7. The plotHistogram call is in label #7.

"""bank17: Plotting a Histogram of Monitor results"""
from SimPy.Simulation import *
from SimPy.SimPlot import *
from random import expovariate, seed

# Model components ------------------------


class Source(Process):
    """ Source generates customers randomly"""

    def generate(self, number, rate):
        for i in range(number):
            c = Customer(name="Customer%02d" % (i))
            activate(c, c.visit(timeInBank=12.0))
            yield hold, self, expovariate(rate)


class Customer(Process):
    """ Customer arrives, is served and leaves """

    def visit(self, timeInBank):
        arrive = now()  # 1
        # print("%8.4f %s: Arrived     " % (now(), self.name))

        yield request, self, counter
        # print("%8.4f %s: Got counter " % (now(), self.name))
        tib = expovariate(1.0 / timeInBank)
        yield hold, self, tib
        yield release, self, counter

        # print("%8.4f %s: Finished    " % (now(), self.name))
        t = now() - arrive  # 2
        Mon.observe(t)  # 3

# Experiment data -------------------------


maxTime = 400.0   # minutes
counter = Resource(1, name="Clerk")
Mon = Monitor('Time in the Bank')  # 4
N = 0

# Model  ----------------------------------


def model(SEED=393939):
    seed(SEED)

    initialize()
    source = Source()
    activate(source,
             source.generate(number=20, rate=0.1), at=0.0)
    simulate(until=maxTime)


# Experiment  ----------------------------------
model()
Histo = Mon.histogram(low=0.0, high=200.0, nbins=20)  # 5

plt = SimPlot()  # 6
plt.plotHistogram(Histo, xlab='Time (min)',  # 7
                  title="Time in the Bank",
                  color="red", width=2)
plt.mainloop()  # 8

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 #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 model routine from #3 to #5.The simulation now generates and processes 20 customers (#4). model does not return a value but the Monitors of the counter Resource still exist when the simulation has terminated.

The additional plotting actions take place from #6 to #9. Lines #7 and #8 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.

"""bank16: Plotting from  Resource Monitors"""
from SimPy.Simulation import *
from SimPy.SimPlot import *  # 1
from random import expovariate, seed

# Model components ------------------------


class Source(Process):
    """ Source generates customers randomly"""

    def generate(self, number, rate):
        for i in range(number):
            c = Customer(name="Customer%02d" % (i))
            activate(c, c.visit(timeInBank=12.0))
            yield hold, self, expovariate(rate)


class Customer(Process):
    """ Customer arrives, is served and leaves """

    def visit(self, timeInBank):
        arrive = now()
        # print("%8.4f %s: Arrived     " % (now(), self.name))

        yield request, self, counter
        # print("%8.4f %s: Got counter " % (now(), self.name))
        tib = expovariate(1.0 / timeInBank)
        yield hold, self, tib
        yield release, self, counter

        # print("%8.4f %s: Finished    " % (now(), self.name))

# Experiment data -------------------------


maxTime = 400.0   # minutes
counter = Resource(1, name="Clerk", monitored=True)

# Model -----------------------------------


def model(SEED=393939):  # 3
    seed(SEED)
    initialize()
    source = Source()
    activate(source,  # 4
             source.generate(number=20, rate=0.1), at=0.0)
    simulate(until=maxTime)  # 5

# Experiment -----------------------------------


model()

plt = SimPlot()  # 6
plt.plotStep(counter.waitMon,  # 7
             color="red", width=2)  # 8
plt.mainloop()  # 9

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