The Bank

Introduction

In this tutorial, SimPy is used to develop a simple simulation of a bank with a number of tellers. This Python package provides Processes to model active components such as messages, customers, trucks, and planes. It has three classes to model facilities where congestion might occur: Resources for ordinary queues, Levels for the supply of quantities of material, and Stores for collections of individual items. Only examples of Resources are described here. It also provides Monitors and Tallys to record data like queue lengths and delay times and to calculate simple averages. It uses the standard Python random package to generate random numbers.

Starting with SimPy 2.0 an object-oriented programmer’s interface was added to the package. It is compatible with the current procedural approach which is used in most of the models described here.

SimPy can be obtained from: https://github.com/SimPyClassic/SimPyClassic. The examples run with SimPy version 1.5 and later. This tutorial is best read with the SimPy Manual or Cheatsheet at your side for reference.

Before attempting to use SimPy you should be familiar with the Python language. In particular you should be able to use classes. Python is free and available for most machine types. You can find out more about it at the Python web site. SimPy is compatible with Python version 2.7 and Python 3.x.

A customer arriving at a fixed time

In this tutorial we model a simple bank with customers arriving at random. We develop the model step-by-step, starting out simply, and producing a running program at each stage. The programs we develop are available without line numbers and ready to go, in the bankprograms directory. Please copy them, run them and improve them - and in the tradition of open-source software suggest your modifications to the SimPy users list. Object-Oriented versions of all the models are included in the bankprograms_OO sub directory.

A simulation should always be developed to answer a specific question; in these models we investigate how changing the number of bank servers or tellers might affect the waiting time for customers.

We first model a single customer who arrives at the bank for a visit, looks around at the decor for a time and then leaves. There is no queueing. First we will assume his arrival time and the time he spends in the bank are fixed.

We define a Customer class derived from the SimPy Process class. We create a Customer object, c who arrives at the bank at simulation time 5.0 and leaves after a fixed time of 10.0 minutes.

Examine the following listing which is a complete runnable Python script. We use comments to divide the script up into sections. This makes for clarity later when the programs get more complicated. At #1 is a normal Python documentation string; #2 imports the SimPy simulation code.

The Customer class definition at #3 defines our customer class and has the required generator method (called visit #4) having a yield statement #6. Such a method is called a Process Execution Method (PEM) in SimPy.

The customer’s visit PEM at #4, models his activities. When he arrives (it will turn out to be a ‘he’ in this model), he will print out the simulation time, now(), and his name at #5. The function now() can be used at any time in the simulation to find the current simulation time though it cannot be changed by the programmer. The customer’s name will be set when the customer is created later in the script at #10.

He then stays in the bank for a fixed simulation time timeInBank at #6. This is achieved by the yield hold,self,timeInBank statement. This is the first of the special simulation commands that SimPy offers.

After a simulation time of timeInBank, the program’s execution returns to the line after the yield statement at #6. The customer then prints out the current simulation time and his name at #7. This completes the declaration of the Customer class.

The call initialize() at #9 sets up the simulation system ready to receive activate calls. At #10, we create a customer, c, with name Klaus. All SimPy Processes have a name attribute. We activate Klaus at #11 specifying the object (c) to be activated, the call of the action routine (c.visit(timeInBank = 10.0)) and that it is to be activated at time 5 (at = 5.0). This will activate Klaus exactly 5 minutes after the current time, in this case after the start of the simulation at 0.0. The call of an action routine such as c.visit can specify the values of arguments, here the timeInBank.

Finally the call of simulate(until=maxTime) at #12 will start the simulation. This will run until the simulation time is maxTime unless stopped beforehand either by the stopSimulation() command or by running out of events to execute (as will happen here). maxTime was set to 100.0 at #8.

""" bank01: The single non-random Customer """  # 1
from SimPy.Simulation import *  # 2

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


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

    def visit(self, timeInBank):  # 4
        print("%2.1f %s  Here I am" % (now(), self.name))  # 5
        yield hold, self, timeInBank  # 6
        print("%2.1f %s  I must leave" % (now(), self.name))  # 7

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


maxTime = 100.0     # minutes #8
timeInBank = 10.0   # minutes

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

initialize()  # 9
c = Customer(name="Klaus")  # 10
activate(c, c.visit(timeInBank), at=5.0)  # 11
simulate(until=maxTime)  # 12

The short trace printed out by the print statements shows the result. The program finishes at simulation time 15.0 because there are no further events to be executed. At the end of the visit routine, the customer has no more actions and no other objects or customers are active.

5.0 Klaus  Here I am
15.0 Klaus  I must leave

The Bank in object-oriented style

Now look at the same model developed in object-oriented style. As before Klaus arrives at the bank for a visit, looks around at the decor for a time and then leaves. There is no queueing. The arrival time and the time he spends in the bank are fixed.

The key point is that we create a Simulation object and run that. In the program at #1 we import a new class, Simulation together with the familiar Process class, and the hold verb. Here we are using the recommended explicit form of import rather than the deprecated import *.

Just as before, we define a Customer class, derived from the SimPy Process class, which has the required generator method (PEM), here called visit.

The customer’s visit PEM models his activities. When he arrives at the bank Klaus will print out both the current simulation time, self.sim.now(), and his name, self.name. The prefix self.sim is a reference to the simulation object where this customer exists, thus self.sim.now() refers to the clock for that simulation object. Every Process instance is linked to the simulation in which it is created by assigning to its sim parameter when it is created (at #4).

Now comes the major difference from the Classical SimPy program structure. We define a class BankModel from the Simulation class at #3. Now any instance of BankModel is an independent simulation with its own event list and its own time axis. A BankModel instance can activate processes and start the execution of a simulation on its time axis.

In the BankModel class, we define a run method which, when executes the BankModel instance, i.e. performs a simulation experiment. When it starts it initializes the simulation with it event list and sets the time to 0.

#4 creates a Customer object and the parameter assignment sim = self ties the customer instance to this and only this simulation. The customer does not exist outside this simulation. The call of simulate(until=maxTime) at #5 starts the simulation. It will run until the simulation time is maxTime unless stopped beforehand either by the stopSimulation() command or by running out of events to execute (as will happen here). maxTime is set to 100.0 at #6.

Note

If model classes like the BankModel are to be given any other attributes, they must have an __init__ method in which these attributes are assigned. Such an __init__ method must first call Simulation.__init__(self) to also initialize the Simulation class from which the model inherits.

A new, independent simulation object, mymodel, is created at #7. Its run method is executed at #8.

""" bank01_OO: The single non-random Customer """
from SimPy.Simulation import Simulation, Process, hold  # 1
# Model components -----------------------------


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

    def visit(self, timeInBank):
        print("%2.1f %s  Here I am" %
              (self.sim.now(), self.name))
        yield hold, self, timeInBank
        print("%2.1f %s  I must leave" %
              (self.sim.now(), self.name))

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


class BankModel(Simulation):  # 3
    def run(self):
        """ An independent simulation object """
        c = Customer(name="Klaus", sim=self)  # 4
        self.activate(c, c.visit(timeInBank), at=tArrival)
        self.simulate(until=maxTime)  # 5


# Experiment data ------------------------------
maxTime = 100.0     # minutes                            #6
timeInBank = 10.0   # minutes
tArrival = 5.0      # minutes

# Experiment -----------------------------------
mymodel = BankModel()  # 7
mymodel.run()  # 8

The short trace printed out by the print statements shows the result. The program finishes at simulation time 15.0 because there are no further events to be executed. At the end of the visit routine, the customer has no more actions and no other objects or customers are active.

5.0 Klaus  Here I am
15.0 Klaus  I must leave

All of The Bank programs have been written in both the procedural and object orientated styles.

A customer arriving at random

Now we extend the model to allow our customer to arrive at a random simulated time though we will keep the time in the bank at 10.0, as before.

The change occurs at #1, #2, #3, and #4 in the program. At #1 we import from the standard Python random module to give us expovariate to generate the random time of arrival. We also import the seed function to initialize the random number stream to allow control of the random numbers. At #2 we provide an initial seed of 99999. An exponential random variate, t, is generated at #3. Note that the Python Random module’s expovariate function uses the average rate (that is, 1.0/mean) as the argument. The generated random variate, t, is used at #4 as the at argument to the activate call.

""" bank05: The single Random Customer """
from SimPy.Simulation import *
from random import expovariate, seed  # 1

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


class Customer(Process):
    """ Customer arrives at a random time,
        looks around and then leaves """

    def visit(self, timeInBank):
        print("%f %s Here I am" % (now(), self.name))
        yield hold, self, timeInBank
        print("%f %s I must leave" % (now(), self.name))

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


maxTime = 100.0    # minutes
timeInBank = 10.0
# Model/Experiment ------------------------------

seed(99999)  # 2
initialize()
c = Customer(name="Klaus")
t = expovariate(1.0 / 5.0)  # 3
activate(c, c.visit(timeInBank), at=t)  # 4
simulate(until=maxTime)

The result is shown below. The customer now arrives at about 0.64195, (or 10.58092 if you are not using Python 3). Changing the seed value would change that time.

0.641954 Klaus Here I am
10.641954 Klaus I must leave

The display looks pretty untidy. In the next example I will try and make it tidier.

If you are not using Python 3, your output may differ. The output for Python 2, for all examples, is given in Appendix A.

More customers

Our simulation does little so far. To consider a simulation with several customers we return to the simple deterministic model and add more Customers.

The program is almost as easy as the first example (A Customer arriving at a fixed time). The main change is between #4 to #5 where we create, name, and activate three customers. We also increase the maximum simulation time to 400 (at #3 and referred to at #6). Observe that we need only one definition of the Customer class and create several objects of that class. These will act quite independently in this model.

Each customer stays for a different timeinbank so, instead of setting a common value for this we set it for each customer. The customers are started at different times (using at=). Tony's activation time occurs before Klaus's, so Tony will arrive first even though his activation statement appears later in the script.

As promised, the print statements have been changed to use Python string formatting (at #1 and #2). The statements look complicated but the output is much nicer.

""" bank02: More Customers """
from SimPy.Simulation import *

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


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

    def visit(self, timeInBank):
        print("%7.4f %s: Here I am" % (now(), self.name))  # 1
        yield hold, self, timeInBank
        print("%7.4f %s: I must leave" % (now(), self.name))  # 2

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


maxTime = 400.0  # minutes                                   #3

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

initialize()

c1 = Customer(name="Klaus")  # 4
activate(c1, c1.visit(timeInBank=10.0), at=5.0)
c2 = Customer(name="Tony")
activate(c2, c2.visit(timeInBank=7.0), at=2.0)
c3 = Customer(name="Evelyn")
activate(c3, c3.visit(timeInBank=20.0), at=12.0)  # 5

simulate(until=maxTime)  # 6

The trace produced by the program is shown below. Again the simulation finishes before the 400.0 specified in the simulate call as it has run out of events.

 2.0000 Tony: Here I am
 5.0000 Klaus: Here I am
 9.0000 Tony: I must leave
12.0000 Evelyn: Here I am
15.0000 Klaus: I must leave
32.0000 Evelyn: I must leave

Many customers

Another change will allow us to have more customers. As it is tedious to give a specially chosen name to each one, we will call them Customer00, Customer01,... and use a separate Source class to create and activate them. To make things clearer we do not use the random numbers in this model.

The following listing shows the new program. At #1 to #4 a Source class is defined. Its PEM, here called generate, is defined between #2 to #4. This PEM has a couple of arguments: the number of customers to be generated and the Time Between Arrivals, TBA. It consists of a loop that creates a sequence of numbered Customers from 0 to (number-1), inclusive. We create a customer and give it a name at #3. It is then activated at the current simulation time (the final argument of the activate statement is missing so that the default value of now() is used as the time). We also specify how long the customer is to stay in the bank. To keep it simple, all customers stay exactly 12 minutes. After each new customer is activated, the Source holds for a fixed time (yield hold,self,TBA) before creating the next one (at #4).

A Source, s, is created at #5 and activated at #6 where the number of customers to be generated is set to maxNumber = 5 and the interval between customers to ARRint = 10.0. Once started at time 0.0 it creates customers at intervals and each customer then operates independently of the others:

""" bank03: Many non-random Customers """
from SimPy.Simulation import *

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


class Source(Process):  # 1
    """ Source generates customers regularly """

    def generate(self, number, TBA):  # 2
        for i in range(number):
            c = Customer(name="Customer%02d" % (i))  # 3
            activate(c, c.visit(timeInBank=12.0))
            yield hold, self, TBA  # 4


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

    def visit(self, timeInBank):
        print("%7.4f %s: Here I am" % (now(), self.name))
        yield hold, self, timeInBank
        print("%7.4f %s: I must leave" % (now(), self.name))

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


maxNumber = 5
maxTime = 400.0  # minutes
ARRint = 10.0    # time between arrivals, minutes

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

initialize()
s = Source()  # 5
activate(s, s.generate(number=maxNumber,  # 6
                       TBA=ARRint), at=0.0)
simulate(until=maxTime)

The output is:

 0.0000 Customer00: Here I am
10.0000 Customer01: Here I am
12.0000 Customer00: I must leave
20.0000 Customer02: Here I am
22.0000 Customer01: I must leave
30.0000 Customer03: Here I am
32.0000 Customer02: I must leave
40.0000 Customer04: Here I am
42.0000 Customer03: I must leave
52.0000 Customer04: I must leave

Many random customers

We now extend this model to allow arrivals at random. In simulation this is usually interpreted as meaning that the times between customer arrivals are distributed as exponential random variates. There is little change in our program, we use a Source object, as before.

The exponential random variate is generated at #1 with meanTBA as the mean Time Between Arrivals and used at #2. Note that this parameter is not exactly intuitive. As already mentioned, the Python expovariate method uses the rate of arrivals as the parameter not the average interval between them. The exponential delay between two arrivals gives pseudo-random arrivals. In this model the first customer arrives at time 0.0.

The seed method is called to initialize the random number stream in the model routine (at #3). It is possible to leave this call out but if we wish to do serious comparisons of systems, we must have control over the random variates and therefore control over the seeds. Then we can run identical models with different seeds or different models with identical seeds. We provide the seeds as control parameters of the run. Here a seed is assigned at #3 but it is clear it could have been read in or manually entered on an input form.

""" bank06: Many Random Customers """
from SimPy.Simulation import *
from random import expovariate, seed

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


class Source(Process):
    """ Source generates customers at random """

    def generate(self, number, meanTBA):
        for i in range(number):
            c = Customer(name="Customer%02d" % (i))
            activate(c, c.visit(timeInBank=12.0))
            t = expovariate(1.0 / meanTBA)  # 1
            yield hold, self, t  # 2


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

    def visit(self, timeInBank=0):
        print("%7.4f %s: Here I am" % (now(), self.name))
        yield hold, self, timeInBank
        print("%7.4f %s: I must leave" % (now(), self.name))

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


maxNumber = 5
maxTime = 400.0  # minutes
ARRint = 10.0    # mean arrival interval, minutes

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

seed(99999)  # 3
initialize()
s = Source(name='Source')
activate(s, s.generate(number=maxNumber,
                       meanTBA=ARRint), at=0.0)
simulate(until=maxTime)

with the following output:

 0.0000 Customer00: Here I am
 1.2839 Customer01: Here I am
 4.9842 Customer02: Here I am
12.0000 Customer00: I must leave
13.2839 Customer01: I must leave
16.9842 Customer02: I must leave
35.5432 Customer03: Here I am
47.5432 Customer03: I must leave
48.9918 Customer04: Here I am
60.9918 Customer04: I must leave

Service Counters

We introduce a service counter at the Bank using a SimPy Resource.

A service counter

So far, the model has been more like an art gallery, the customers entering, looking around, and leaving. Now they are going to require service from the bank clerk. We extend the model to include a service counter which will be modelled as an object of SimPy’s Resource class with a single resource unit. The actions of a Resource are simple: a customer requests a unit of the resource (a clerk). If one is free he gets service (and removes the unit). If there is no free clerk the customer joins the queue (managed by the resource object) until it is their turn to be served. As each customer completes service and releases the unit, the clerk can start serving the next in line.

The service counter is created as a Resource (k) in at #8. This is provided as an argument to the Source (at #9) which, in turn, provides it to each customer it creates and activates (at #1).

The actions involving the service counter, k, in the customer’s PEM are:

  • the yield request statement at #3. If the server is free then the customer can start service immediately and the code moves on to #4. If the server is busy, the customer is automatically queued by the Resource. When it eventually comes available the PEM moves on to #4.
  • the yield hold statement at #5 where the operation of the service counter is modelled. Here the service time is a fixed timeInBank. During this period the customer is being served.
  • the yield release statement at #6. The current customer completes service and the service counter becomes available for any remaining customers in the queue.

Observe that the service counter is used with the pattern (yield request..; yield hold..; yield release..).

To show the effect of the service counter on the activities of the customers, I have added #2 to record when the customer arrived and #4 to record the time between arrival in the bank and starting service. #4 is after the yield request command and will be reached only when the request is satisfied. It is before the yield hold that corresponds to the start of service. The variable wait will record how long the customer waited and will be 0 if he received service at once. This technique of saving the arrival time in a variable is common. So the print statement also prints out how long the customer waited in the bank before starting service.

""" bank07: One Counter,random arrivals """
from SimPy.Simulation import *
from random import expovariate, seed

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


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

    def generate(self, number, meanTBA, resource):
        for i in range(number):
            c = Customer(name="Customer%02d" % (i))
            activate(c, c.visit(timeInBank=12.0,
                                res=resource))  # 1
            t = expovariate(1.0 / meanTBA)
            yield hold, self, t


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

    def visit(self, timeInBank, res):
        arrive = now()  # 2  arrival time
        print("%8.3f %s: Here I am" % (now(), self.name))

        yield request, self, res  # 3
        wait = now() - arrive  # 4  waiting time
        print("%8.3f %s: Waited %6.3f" % (now(), self.name, wait))
        yield hold, self, timeInBank  # 5
        yield release, self, res  # 6

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

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


maxNumber = 5  # 7
maxTime = 400.0   # minutes
ARRint = 10.0     # mean, minutes
k = Resource(name="Counter", unitName="Clerk")  # 8

# Model/Experiment ------------------------------
seed(99999)
initialize()
s = Source('Source')
activate(s, s.generate(number=maxNumber,
                       meanTBA=ARRint, resource=k), at=0.0)  # 9
simulate(until=maxTime)

Examining the trace we see that the first, and last, customers get instant service but the others have to wait. We still only have five customers (#7) so we cannot draw general conclusions.

   0.000 Customer00: Here I am
   0.000 Customer00: Waited  0.000
   1.284 Customer01: Here I am
   4.984 Customer02: Here I am
  12.000 Customer00: Finished
  12.000 Customer01: Waited 10.716
  24.000 Customer01: Finished
  24.000 Customer02: Waited 19.016
  35.543 Customer03: Here I am
  36.000 Customer02: Finished
  36.000 Customer03: Waited  0.457
  48.000 Customer03: Finished
  48.992 Customer04: Here I am
  48.992 Customer04: Waited  0.000
  60.992 Customer04: Finished

A server with a random service time

This is a simple change to the model in that we retain the single service counter but make the customer service time a random variable. As is traditional in the study of simple queues we first assume an exponential service time and set the mean to timeInBank.

The service time random variable, tib, is generated at #1 and used at #2. The argument to be used in the call of expovariate is not the mean of the distribution, timeInBank, but is the rate 1/timeInBank.

We have also collected together a number of constants by defining a number of appropriate variables and giving them values. These are in lines between marks #3 and #4.

""" bank08: A counter with a random service time """
from SimPy.Simulation import *
from random import expovariate, seed

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


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

    def generate(self, number, meanTBA, resource):
        for i in range(number):
            c = Customer(name="Customer%02d" % (i,))
            activate(c, c.visit(b=resource))
            t = expovariate(1.0 / meanTBA)
            yield hold, self, t


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

    def visit(self, b):
        arrive = now()
        print("%8.4f %s: Here I am     " % (now(), self.name))
        yield request, self, b
        wait = now() - arrive
        print("%8.4f %s: Waited %6.3f" % (now(), self.name, wait))
        tib = expovariate(1.0 / timeInBank)  # 1
        yield hold, self, tib  # 2
        yield release, self, b
        print("%8.4f %s: Finished      " % (now(), self.name))

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


maxNumber = 5  # 3
maxTime = 400.0    # minutes
timeInBank = 12.0  # mean, minutes
ARRint = 10.0      # mean, minutes
theseed = 99999  # 4

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

seed(theseed)
k = Resource(name="Counter", unitName="Clerk")

initialize()
s = Source('Source')
activate(s, s.generate(number=maxNumber, meanTBA=ARRint,
                       resource=k), at=0.0)
simulate(until=maxTime)

And the output:

  0.0000 Customer00: Here I am     
  0.0000 Customer00: Waited  0.000
  1.2839 Customer01: Here I am     
  4.4403 Customer00: Finished      
  4.4403 Customer01: Waited  3.156
 20.5786 Customer01: Finished      
 31.8430 Customer02: Here I am     
 31.8430 Customer02: Waited  0.000
 34.5594 Customer02: Finished      
 36.2308 Customer03: Here I am     
 36.2308 Customer03: Waited  0.000
 41.4313 Customer04: Here I am     
 67.1315 Customer03: Finished      
 67.1315 Customer04: Waited 25.700
 87.9241 Customer04: Finished      

This model with random arrivals and exponential service times is an example of an M/M/1 queue and could rather easily be solved analytically to calculate the steady-state mean waiting time and other operating characteristics. (But not so easily solved for its transient behavior.)

Several service counters

When we introduce several counters we must decide on a queue discipline. Are customers going to make one queue or are they going to form separate queues in front of each counter? Then there are complications - will they be allowed to switch lines (jockey)? We first consider a single queue with several counters and later consider separate isolated queues. We will not look at jockeying.

Here we model a bank whose customers arrive randomly and are to be served at a group of counters, taking a random time for service, where we assume that waiting customers form a single first-in first-out queue.

The only difference between this model and the single-server model is at #1. We have provided two counters by increasing the capacity of the counter resource to 2. These units of the resource correspond to the two counters. Because both clerks cannot be called Karen, we have used a general name of Clerk.

""" bank09: Several Counters but a Single Queue """
from SimPy.Simulation import *
from random import expovariate, seed

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


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

    def generate(self, number, meanTBA, resource):
        for i in range(number):
            c = Customer(name="Customer%02d" % (i))
            activate(c, c.visit(b=resource))
            t = expovariate(1.0 / meanTBA)
            yield hold, self, t


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

    def visit(self, b):
        arrive = now()
        print("%8.4f %s: Here I am     " % (now(), self.name))
        yield request, self, b
        wait = now() - arrive
        print("%8.4f %s: Waited %6.3f" % (now(), self.name, wait))
        tib = expovariate(1.0 / timeInBank)
        yield hold, self, tib
        yield release, self, b
        print("%8.4f %s: Finished      " % (now(), self.name))

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


maxNumber = 5
maxTime = 400.0    # minutes
timeInBank = 12.0  # mean, minutes
ARRint = 10.0      # mean, minutes
theseed = 99999

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

seed(theseed)
k = Resource(capacity=2, name="Counter", unitName="Clerk")  # 1

initialize()
s = Source('Source')
activate(s, s.generate(number=maxNumber, meanTBA=ARRint,
                       resource=k), at=0.0)
simulate(until=maxTime)

The waiting times in this model are very different from those for the single service counter. For example, none of the customers had to wait. But, again, we have observed too few customers to draw general conclusions.

  0.0000 Customer00: Here I am     
  0.0000 Customer00: Waited  0.000
  1.2839 Customer01: Here I am     
  1.2839 Customer01: Waited  0.000
  4.4403 Customer00: Finished      
 17.4222 Customer01: Finished      
 31.8430 Customer02: Here I am     
 31.8430 Customer02: Waited  0.000
 34.5594 Customer02: Finished      
 36.2308 Customer03: Here I am     
 36.2308 Customer03: Waited  0.000
 41.4313 Customer04: Here I am     
 41.4313 Customer04: Waited  0.000
 62.2239 Customer04: Finished      
 67.1315 Customer03: Finished      

Several counters with individual queues

Each counter now has its own queue. The programming is more complicated because the customer has to decide which one to join. The obvious technique is to make each counter a separate resource and it is useful to make a list of resource objects (#7).

In practice, a customer will join the shortest queue. So we define a Python function, NoInSystem(R) (#1 to #2) to return the sum of the number waiting and the number being served for a particular counter, R. This function is used at #3 to list the numbers at each counter. It is then easy to find which counter the arriving customer should join. We have also modified the trace printout, #4 to display the state of the system when the customer arrives. We choose the shortest queue at #5 to #6 (using the variable choice).

The rest of the program is the same as before.

""" bank10: Several Counters with individual queues"""
from SimPy.Simulation import *
from random import expovariate, seed

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


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

    def generate(self, number, interval, counters):
        for i in range(number):
            c = Customer(name="Customer%02d" % (i))
            activate(c, c.visit(counters))
            t = expovariate(1.0 / interval)
            yield hold, self, t


def NoInSystem(R):  # 1
    """ Total number of customers in the resource R"""
    return (len(R.waitQ) + len(R.activeQ))  # 2


class Customer(Process):
    """ Customer arrives, chooses the shortest queue
        is served and leaves
    """

    def visit(self, counters):
        arrive = now()
        Qlength = [NoInSystem(counters[i]) for i in range(Nc)]  # 3
        print("%7.4f %s: Here I am. %s" % (now(), self.name, Qlength))  # 4
        for i in range(Nc):  # 5
            if Qlength[i] == 0 or Qlength[i] == min(Qlength):
                choice = i    # the index of the shortest line
                break  # 6

        yield request, self, counters[choice]
        wait = now() - arrive
        print("%7.4f %s: Waited %6.3f" % (now(), self.name, wait))
        tib = expovariate(1.0 / timeInBank)
        yield hold, self, tib
        yield release, self, counters[choice]

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

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


maxNumber = 5
maxTime = 400.0    # minutes
timeInBank = 12.0  # mean, minutes
ARRint = 10.0      # mean, minutes
Nc = 2             # number of counters
theseed = 787878

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

seed(theseed)
kk = [Resource(name="Clerk0"), Resource(name="Clerk1")]  # 7
initialize()
s = Source('Source')
activate(s, s.generate(number=maxNumber, interval=ARRint,
                       counters=kk), at=0.0)
simulate(until=maxTime)

The results show how the customers choose the counter with the smallest number. Unlucky Customer03 who joins the wrong queue has to wait until Customer01 finishes before his service can be started. There are, however, too few arrivals in these runs, limited as they are to five customers, to draw any general conclusions about the relative efficiencies of the two systems.

 0.0000 Customer00: Here I am. [0, 0]
 0.0000 Customer00: Waited  0.000
 9.7519 Customer00: Finished
12.0829 Customer01: Here I am. [0, 0]
12.0829 Customer01: Waited  0.000
25.9167 Customer02: Here I am. [1, 0]
25.9167 Customer02: Waited  0.000
38.2349 Customer03: Here I am. [1, 1]
40.4032 Customer04: Here I am. [2, 1]
43.0677 Customer02: Finished
43.0677 Customer04: Waited  2.664
44.0242 Customer01: Finished
44.0242 Customer03: Waited  5.789
60.1271 Customer03: Finished
70.2500 Customer04: Finished

Customer’s Priority

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.

Priority customers

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.

In the first example, we modify the program with random arrivals, one counter, and a fixed service time with the addition of a high priority customer. Warning: The seed() value has been changed to 787878 to make the story more exciting. To make things even more confusing, your results may be different from those here because the random module gives different results for Python 2.x and 3.x.,

The main 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 must 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, at between #5 and #6 we create and activate one special customer, Guido, with priority 100 who arrives at time 23.0.

The visit customer method has a new parameter, P (at #3), which allows us to set the customer priority.

At #4, counter is defined with qType=PriorityQ so that we can request it with priority (at #3) using the statement yield request,self,counter,P

At #2, we now print out the number of customers waiting when each customer arrives.

""" bank20: One counter with a priority customer """
from SimPy.Simulation import *
from random import expovariate, seed

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


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

    def generate(self, number, interval, resource):
        for i in range(number):
            c = Customer(name="Customer%02d" % (i))
            activate(c, c.visit(timeInBank=12.0,
                                res=resource, P=0))
            t = expovariate(1.0 / interval)
            yield hold, self, t


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

    def visit(self, timeInBank=0, res=None, P=0):  # 1
        arrive = now()       # arrival time
        Nwaiting = len(res.waitQ)
        print("%8.3f %s: Queue is %d on arrival" %  # 2
              (now(), self.name, Nwaiting))

        yield request, self, res, P  # 3
        wait = now() - arrive  # waiting time
        print("%8.3f %s: Waited %6.3f" %
              (now(), self.name, wait))
        yield hold, self, timeInBank
        yield release, self, res

        print("%8.3f %s: Completed" %
              (now(), self.name))

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


maxTime = 400.0  # minutes
k = Resource(name="Counter", unitName="Karen",  # 4
             qType=PriorityQ)

# Model/Experiment ------------------------------
seed(787878)
initialize()
s = Source('Source')
activate(s, s.generate(number=5, interval=10.0,
                       resource=k), at=0.0)
guido = Customer(name="Guido     ")  # 5
activate(guido, guido.visit(timeInBank=12.0, res=k,  # 6
                            P=100), at=23.0)
simulate(until=maxTime)

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.

   0.000 Customer00: Queue is 0 on arrival
   0.000 Customer00: Waited  0.000
  12.000 Customer00: Completed
  12.083 Customer01: Queue is 0 on arrival
  12.083 Customer01: Waited  0.000
  20.210 Customer02: Queue is 0 on arrival
  23.000 Guido     : Queue is 1 on arrival
  24.083 Customer01: Completed
  24.083 Guido     : Waited  1.083
  34.043 Customer03: Queue is 1 on arrival
  36.083 Guido     : Completed
  36.083 Customer02: Waited 15.873
  48.083 Customer02: Completed
  48.083 Customer03: Waited 14.040
  60.083 Customer03: Completed
  60.661 Customer04: Queue is 0 on arrival
  60.661 Customer04: Waited  0.000
  72.661 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 Customer02 is waiting in the queue. Guido has priority over any waiting customers and is served before the at 24.083. When Guido leaves at 36.083, Customer02 starts service having waited 15.873 minutes.

A priority customer 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 at #1.

""" bank23: One counter with a priority customer with preemption """
from SimPy.Simulation import *
from random import expovariate, seed

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


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

    def generate(self, number, interval, resource):
        for i in range(number):
            c = Customer(name="Customer%02d" % (i))
            activate(c, c.visit(timeInBank=12.0,
                                res=resource, P=0))
            t = expovariate(1.0 / interval)
            yield hold, self, t


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

    def visit(self, timeInBank=0, res=None, P=0):
        arrive = now()       # arrival time
        Nwaiting = len(res.waitQ)
        print("%8.3f %s: Queue is %d on arrival" %
              (now(), self.name, Nwaiting))

        yield request, self, res, P
        wait = now() - arrive  # waiting time
        print("%8.3f %s: Waited %6.3f" %
              (now(), self.name, wait))
        yield hold, self, timeInBank
        yield release, self, res

        print("%8.3f %s: Completed" %
              (now(), self.name))

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


maxTime = 400.0  # minutes
k = Resource(name="Counter", unitName="Karen",  # 1
             qType=PriorityQ, preemptable=True)

# Model/Experiment ------------------------------
seed(989898)
initialize()
s = Source('Source')
activate(s, s.generate(number=5, interval=10.0,
                       resource=k), at=0.0)
guido = Customer(name="Guido     ")
activate(guido, guido.visit(timeInBank=12.0, res=k,
                            P=100), at=23.0)
simulate(until=maxTime)

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.083 = 10.917 minutes of his service. When Guido finishes at 36.083, Customer01 resumes service and takes 36.083-35.000 = 1.083 minutes to finish. His total service time is the same as before (12.000 minutes).

   0.000 Customer00: Queue is 0 on arrival
   0.000 Customer00: Waited  0.000
   8.634 Customer01: Queue is 0 on arrival
  12.000 Customer00: Completed
  12.000 Customer01: Waited  3.366
  16.016 Customer02: Queue is 0 on arrival
  19.882 Customer03: Queue is 1 on arrival
  20.246 Customer04: Queue is 2 on arrival
  23.000 Guido     : Queue is 3 on arrival
  23.000 Guido     : Waited  0.000
  35.000 Guido     : Completed
  36.000 Customer01: Completed
  36.000 Customer02: Waited 19.984
  48.000 Customer02: Completed
  48.000 Customer03: Waited 28.118
  60.000 Customer03: Completed
  60.000 Customer04: Waited 39.754
  72.000 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 (at #1). If there is not enough room, we balk, incrementing a Class variable Customer.numBalking at #2 to get the total number balking during the run.

""" bank24. BCC system with several counters """
from SimPy.Simulation import *
from random import expovariate, seed

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


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

    def generate(self, number, meanTBA, resource):
        for i in range(number):
            c = Customer(name="Customer%02d" % (i))
            activate(c, c.visit(b=resource))
            t = expovariate(1.0 / meanTBA)
            yield hold, self, t


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

    numBalking = 0

    def visit(self, b):
        arrive = now()
        print("%8.4f %s: Here I am " %
              (now(), self.name))
        if len(b.waitQ) < maxInQueue:  # 1
            yield request, self, b
            wait = now() - arrive
            print("%8.4f %s: Wait %6.3f" %
                  (now(), self.name, wait))
            tib = expovariate(1.0 / timeInBank)
            yield hold, self, tib
            yield release, self, b
            print("%8.4f %s: Finished  " %
                  (now(), self.name))
        else:
            Customer.numBalking += 1  # 2
            print("%8.4f %s: BALKING   " %
                  (now(), self.name))

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


timeInBank = 12.0  # mean, minutes
ARRint = 10.0      # mean interarrival time, minutes
numServers = 1     # servers
maxInSystem = 2    # customers
maxInQueue = maxInSystem - numServers

maxNumber = 8
maxTime = 4000.0  # minutes
theseed = 212121

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

seed(theseed)
k = Resource(capacity=numServers,
             name="Counter", unitName="Clerk")

initialize()
s = Source('Source')
activate(s, s.generate(number=maxNumber,
                       meanTBA=ARRint,
                       resource=k), at=0.0)
simulate(until=maxTime)

# Results -----------------------------------------

nb = float(Customer.numBalking)
print("balking rate is %8.4f per minute" % (nb / now()))

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

  0.0000 Customer00: Here I am 
  0.0000 Customer00: Wait  0.000
  4.3077 Customer01: Here I am 
  5.6957 Customer02: Here I am 
  5.6957 Customer02: BALKING   
  6.9774 Customer03: Here I am 
  6.9774 Customer03: BALKING   
  8.2476 Customer00: Finished  
  8.2476 Customer01: Wait  3.940
 21.1312 Customer04: Here I am 
 22.4840 Customer01: Finished  
 22.4840 Customer04: Wait  1.353
 23.0923 Customer05: Here I am 
 23.1537 Customer06: Here I am 
 23.1537 Customer06: BALKING   
 36.0653 Customer04: Finished  
 36.0653 Customer05: Wait 12.973
 38.4851 Customer07: Here I am 
 53.1056 Customer05: Finished  
 53.1056 Customer07: Wait 14.620
 60.3558 Customer07: Finished  
balking rate is   0.0497 per minute

When Customer02 arrives, Customer00 is already in service and Customer01 is waiting. There is no room so Customer02 balks. In fact another customer, Customer03 arrives and balks before Customer00 is finished.

The balking pattern for python 2.x is different.

Reneging or abandoning

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 at #1.

""" bank21: One counter with impatient customers """
from SimPy.Simulation import *
from random import expovariate, seed

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


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

    def generate(self, number, interval):
        for i in range(number):
            c = Customer(name="Customer%02d" % (i))
            activate(c, c.visit(timeInBank=15.0))
            t = expovariate(1.0 / interval)
            yield hold, self, t


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

    def visit(self, timeInBank=0):
        arrive = now()       # arrival time
        print("%8.3f %s: Here I am     " % (now(), self.name))

        yield (request, self, counter), (hold, self, maxWaitTime)
        wait = now() - arrive  # waiting time
        if self.acquired(counter):  # 1
            print("%8.3f %s: Waited %6.3f" % (now(), self.name, wait))
            yield hold, self, timeInBank
            yield release, self, counter
            print("%8.3f %s: Completed" % (now(), self.name))
        else:
            print("%8.3f %s: Waited %6.3f. I am off" %
                  (now(), self.name, wait))

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


maxTime = 400.0  # minutes
maxWaitTime = 12.0  # minutes. maximum time to wait

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


def model():
    global counter
    seed(989898)
    counter = Resource(name="Karen")
    initialize()
    source = Source('Source')
    activate(source,
             source.generate(number=5, interval=10.0), at=0.0)
    simulate(until=maxTime)

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


model()
   0.000 Customer00: Here I am     
   0.000 Customer00: Waited  0.000
   8.634 Customer01: Here I am     
  15.000 Customer00: Completed
  15.000 Customer01: Waited  6.366
  16.016 Customer02: Here I am     
  19.882 Customer03: Here I am     
  20.246 Customer04: Here I am     
  28.016 Customer02: Waited 12.000. I am off
  30.000 Customer01: Completed
  30.000 Customer03: Waited 10.118
  32.246 Customer04: Waited 12.000. I am off
  45.000 Customer03: Completed

Customer02 arrives at 16.016 but has only 12 minutes patience. After that time in the queue (at time 28.016) he abandons the queue to leave 03 to take his place. 04 also abandons.

The reneging pattern for python 2.x is different due to a different expovariate implementation.

Gathering Statistics

SimPy Monitors allow statistics to be gathered and simple summaries calculated.

The bank with a monitor

The traces of output that have been displayed so far are valuable for checking that the simulation is operating correctly but would become too much if we simulate a whole day. We do need to get results from our simulation to answer the original questions. What, then, is the best way to summarize the results?

One way is to analyze the traces elsewhere, piping the trace output, or a modified version of it, into a real statistical program such as R for statistical analysis, or into a file for later examination by a spreadsheet. We do not have space to examine this thoroughly here. Another way of presenting the results is to provide graphical output.

SimPy offers an easy way to gather a few simple statistics such as averages: the Monitor and Tally classes. The Monitor records the values of chosen variables as time series (but see the comments in Final Remarks).

We now demonstrate a Monitor that records the average waiting times for our customers. We return to the system with random arrivals, random service times and a single queue and remove the old trace statements. In practice, we would make the printouts controlled by a variable, say, TRACE which is set in the experimental data (or read in as a program option - but that is a different story). This would aid in debugging and would not complicate the data analysis. We will run the simulations for many more arrivals.

A Monitor, wM, is created at #2. It observes and records the waiting time mentioned at #1. We run maxNumber=50 customers (in the call of generate at #3) and have increased maxTime to 1000 minutes. Brief statistics are given by the Monitor methods count() and mean() at #4.

""" bank11: The bank with a Monitor"""
from SimPy.Simulation import *
from random import expovariate, seed

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


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

    def generate(self, number, interval, resource):
        for i in range(number):
            c = Customer(name="Customer%02d" % (i))
            activate(c, c.visit(b=resource))
            t = expovariate(1.0 / interval)
            yield hold, self, t


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

    def visit(self, b):
        arrive = now()
        yield request, self, b
        wait = now() - arrive
        wM.observe(wait)  # 1
        tib = expovariate(1.0 / timeInBank)
        yield hold, self, tib
        yield release, self, b

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


maxNumber = 50
maxTime = 1000.0    # minutes
timeInBank = 12.0   # mean, minutes
ARRint = 10.0    # mean, minutes
Nc = 2           # number of counters
theseed = 99999

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

seed(theseed)
k = Resource(capacity=Nc, name="Clerk")
wM = Monitor()  # 2
initialize()
s = Source('Source')
activate(s, s.generate(number=maxNumber, interval=ARRint,
                       resource=k), at=0.0)  # 3
simulate(until=maxTime)

# Result  ----------------------------------

result = wM.count(), wM.mean()  # 4
print("Average wait for %3d completions was %5.3f minutes." % result)

The average waiting time for 50 customers in this 2-counter system is more reliable (i.e., less subject to random simulation effects) than the times we measured before but it is still not sufficiently reliable for real-world decisions. We should also replicate the runs using different random number seeds. The result of this run (using Python 3.2) is:

Average wait for  50 completions was 8.941 minutes.

Result for Python 2.x is given in Appendix A.

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 #1 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.

At the end of the run in the model function, we calculate the timeAverage of both waitMon and actMon and return them from the model call (at #2). These can then be printed at the end of the program (at #3).

"""bank15: Monitoring a Resource"""
from SimPy.Simulation 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()
        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)  # 1

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


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

    return (counter.waitMon.timeAverage(),
            counter.actMon.timeAverage())  # 2
# Experiment  ----------------------------------


print('Avge waiting = %6.4f\nAvge active = %6.4f\n' % model())  # 3

With the following output:

  0.0000 Customer00: Arrived     
  0.0000 Customer00: Got counter 
  1.1489 Customer01: Arrived     
  5.6657 Customer02: Arrived     
 10.0126 Customer00: Finished    
 10.0126 Customer01: Got counter 
 12.8923 Customer03: Arrived     
 18.5883 Customer04: Arrived     
 29.3088 Customer01: Finished    
 29.3088 Customer02: Got counter 
 44.1219 Customer02: Finished    
 44.1219 Customer03: Got counter 
 73.0066 Customer03: Finished    
 73.0066 Customer04: Got counter 
 73.8458 Customer04: Finished    
Avge waiting = 1.6000
Avge active = 1.0000

Multiple runs

To get a number of independent measurements we must replicate the runs using different random number seeds. Each replication must be independent of previous ones so the Monitor and Resources must be redefined for each run. We can no longer allow them to be global objects as we have before.

We will define a function, model with a parameter runSeed so that the random number seed can be different for different runs (between between #2 and #5). The contents of the function are the same as the Model/Experiment in bank11: The bank with a monitor, except for one vital change.

This is required since the Monitor, wM, is defined inside the model function (#3). A customer can no longer refer to it. In the spirit of quality computer programming we will pass wM as a function argument. Unfortunately we have to do this in two steps, first to the Source (#4) and then from the Source to the Customer (#1).

model() is run for four different random-number seeds to get a set of replications (between #6 and #7).

""" bank12: Multiple runs of the bank with a Monitor"""
from SimPy.Simulation import *
from random import expovariate, seed

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


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

    def generate(self, number, interval, resource, mon):
        for i in range(number):
            c = Customer(name="Customer%02d" % (i))
            activate(c, c.visit(b=resource, M=mon))  # 1
            t = expovariate(1.0 / interval)
            yield hold, self, t


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

    def visit(self, b, M):
        arrive = now()
        yield request, self, b
        wait = now() - arrive
        M.observe(wait)
        tib = expovariate(1.0 / timeInBank)
        yield hold, self, tib
        yield release, self, b

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


maxNumber = 50
maxTime = 2000.0  # minutes
timeInBank = 12.0   # mean, minutes
ARRint = 10.0     # mean, minutes
Nc = 2            # number of counters
theSeed = 393939

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


def model(runSeed=theSeed):  # 2
    seed(runSeed)
    k = Resource(capacity=Nc, name="Clerk")
    wM = Monitor()  # 3

    initialize()
    s = Source('Source')
    activate(s, s.generate(number=maxNumber, interval=ARRint,
                           resource=k, mon=wM), at=0.0)  # 4
    simulate(until=maxTime)
    return (wM.count(), wM.mean())  # 5

# Experiment/Result  ----------------------------------


theseeds = [393939, 31555999, 777999555, 319999771]  # 6
for Sd in theseeds:
    result = model(Sd)
    print("Avge wait for %3d completions was %6.2f min." %
          result)  # 7

The results show some variation. Remember, though, that the system is still only operating for 50 customers so the system may not be in steady-state.

Avge wait for  50 completions was   3.66 min.
Avge wait for  50 completions was   2.62 min.
Avge wait for  50 completions was   8.97 min.
Avge wait for  50 completions was   5.34 min.

Final Remarks

This introduction is too long and the examples are getting longer. There is much more to say about simulation with SimPy but no space. I finish with a list of topics for further study:

Topics not yet mentioned

  • GUI input. Graphical input of simulation parameters could be an advantage in some cases. SimPy allows this and programs using these facilities have been developed (see, for example, program MM1.py in the examples in the SimPy distribution)
  • Graphical Output. Similarly, graphical output of results can also be of value, not least in debugging simulation programs and checking for steady-state conditions. SimPlot is useful here.
  • Statistical Output. The Monitor class is useful in presenting results but more powerful methods of analysis are often needed. One solution is to output a trace and read that into a large-scale statistical system such as R.
  • Priorities and Reneging in queues. SimPy allows processes to request units of resources under a priority queue discipline (preemptive or not). It also allows processes to renege from a queue.
  • Other forms of Resource Facilities. SimPy has two other resource structures: Levels to hold bulk commodities, and Stores to contain an inventory of different object types.
  • Advanced synchronization/scheduling commands. SimPy allows process synchronization by events and signals.

Acknowledgements

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

References

Appendix A

With Python 3 the definition of expovariate changed. In some cases this was back ported to some distributions of Python 2.7. Because of this the output for the bank programs varies. This section contains the older output produced by the original definition of expovariate.

A Customer arriving at a fixed time

5.0 Klaus  Here I am
15.0 Klaus  I must leave

A Customer arriving at random

10.580923 Klaus Here I am
20.580923 Klaus I must leave

More Customers

 2.0000 Tony: Here I am
 5.0000 Klaus: Here I am
 9.0000 Tony: I must leave
12.0000 Evelyn: Here I am
15.0000 Klaus: I must leave
32.0000 Evelyn: I must leave

Many Customers

 0.0000 Customer00: Here I am
10.0000 Customer01: Here I am
12.0000 Customer00: I must leave
20.0000 Customer02: Here I am
22.0000 Customer01: I must leave
30.0000 Customer03: Here I am
32.0000 Customer02: I must leave
40.0000 Customer04: Here I am
42.0000 Customer03: I must leave
52.0000 Customer04: I must leave

Many Random Customers

 0.0000 Customer00: Here I am
12.0000 Customer00: I must leave
21.1618 Customer01: Here I am
32.8968 Customer02: Here I am
33.1618 Customer01: I must leave
33.3790 Customer03: Here I am
36.3979 Customer04: Here I am
44.8968 Customer02: I must leave
45.3790 Customer03: I must leave
48.3979 Customer04: I must leave

A Service Counter

   0.000 Customer00: Here I am
   0.000 Customer00: Waited  0.000
  12.000 Customer00: Finished
  21.162 Customer01: Here I am
  21.162 Customer01: Waited  0.000
  32.897 Customer02: Here I am
  33.162 Customer01: Finished
  33.162 Customer02: Waited  0.265
  33.379 Customer03: Here I am
  36.398 Customer04: Here I am
  45.162 Customer02: Finished
  45.162 Customer03: Waited 11.783
  57.162 Customer03: Finished
  57.162 Customer04: Waited 20.764
  69.162 Customer04: Finished

A server with a random service time

  0.0000 Customer00: Here I am     
  0.0000 Customer00: Waited  0.000
 14.0819 Customer00: Finished      
 21.1618 Customer01: Here I am     
 21.1618 Customer01: Waited  0.000
 21.6441 Customer02: Here I am     
 24.7845 Customer01: Finished      
 24.7845 Customer02: Waited  3.140
 31.9954 Customer03: Here I am     
 41.0215 Customer04: Here I am     
 43.9441 Customer02: Finished      
 43.9441 Customer03: Waited 11.949
 49.9552 Customer03: Finished      
 49.9552 Customer04: Waited  8.934
 52.2900 Customer04: Finished      

Several Counters but a Single Queue

  0.0000 Customer00: Here I am     
  0.0000 Customer00: Waited  0.000
 14.0819 Customer00: Finished      
 21.1618 Customer01: Here I am     
 21.1618 Customer01: Waited  0.000
 21.6441 Customer02: Here I am     
 21.6441 Customer02: Waited  0.000
 24.7845 Customer01: Finished      
 31.9954 Customer03: Here I am     
 31.9954 Customer03: Waited  0.000
 32.9459 Customer03: Finished      
 40.8037 Customer02: Finished      
 41.0215 Customer04: Here I am     
 41.0215 Customer04: Waited  0.000
 43.3562 Customer04: Finished      

Several Counters with individual queues

 0.0000 Customer00: Here I am. [0, 0]
 0.0000 Customer00: Waited  0.000
 3.5483 Customer01: Here I am. [1, 0]
 3.5483 Customer01: Waited  0.000
 4.4169 Customer01: Finished
 6.4349 Customer02: Here I am. [1, 0]
 6.4349 Customer02: Waited  0.000
 7.0368 Customer00: Finished
 9.7200 Customer02: Finished
 9.8846 Customer03: Here I am. [0, 0]
 9.8846 Customer03: Waited  0.000
19.8340 Customer03: Finished
26.2357 Customer04: Here I am. [0, 0]
26.2357 Customer04: Waited  0.000
29.8709 Customer04: Finished

Priority Customers

   0.000 Customer00: Queue is 0 on arrival
   0.000 Customer00: Waited  0.000
   3.548 Customer01: Queue is 0 on arrival
   9.412 Customer02: Queue is 1 on arrival
  12.000 Customer00: Completed
  12.000 Customer01: Waited  8.452
  12.299 Customer03: Queue is 1 on arrival
  13.023 Customer04: Queue is 2 on arrival
  23.000 Guido     : Queue is 3 on arrival
  24.000 Customer01: Completed
  24.000 Guido     : Waited  1.000
  36.000 Guido     : Completed
  36.000 Customer02: Waited 26.588
  48.000 Customer02: Completed
  48.000 Customer03: Waited 35.701
  60.000 Customer03: Completed
  60.000 Customer04: Waited 46.977
  72.000 Customer04: Completed

A priority Customer with Preemption

   0.000 Customer00: Queue is 0 on arrival
   0.000 Customer00: Waited  0.000
   5.477 Customer01: Queue is 0 on arrival
  11.978 Customer02: Queue is 1 on arrival
  12.000 Customer00: Completed
  12.000 Customer01: Waited  6.523
  23.000 Guido     : Queue is 1 on arrival
  23.000 Guido     : Waited  0.000
  23.350 Customer03: Queue is 2 on arrival
  35.000 Guido     : Completed
  36.000 Customer01: Completed
  36.000 Customer02: Waited 24.022
  48.000 Customer02: Completed
  48.000 Customer03: Waited 24.650
  56.664 Customer04: Queue is 0 on arrival
  60.000 Customer03: Completed
  60.000 Customer04: Waited  3.336
  72.000 Customer04: Completed

Balking Customers

  0.0000 Customer00: Here I am 
  0.0000 Customer00: Wait  0.000
  8.3884 Customer00: Finished  
 10.4985 Customer01: Here I am 
 10.4985 Customer01: Wait  0.000
 30.9314 Customer02: Here I am 
 33.7131 Customer03: Here I am 
 33.7131 Customer03: BALKING   
 35.9122 Customer01: Finished  
 35.9122 Customer02: Wait  4.981
 37.3562 Customer04: Here I am 
 41.2491 Customer05: Here I am 
 41.2491 Customer05: BALKING   
 56.6185 Customer02: Finished  
 56.6185 Customer04: Wait 19.262
 59.5365 Customer04: Finished  
 92.2071 Customer06: Here I am 
 92.2071 Customer06: Wait  0.000
 94.9740 Customer07: Here I am 
102.7425 Customer06: Finished  
102.7425 Customer07: Wait  7.769
133.5005 Customer07: Finished  
balking rate is   0.0150 per minute

Reneging or Abandoning


The Bank with a Monitor

Average wait for  50 completions was 3.430 minutes.

Monitoring a Resource

  0.0000 Customer00: Arrived     
  0.0000 Customer00: Got counter 
  6.8329 Customer00: Finished    
 22.2064 Customer01: Arrived     
 22.2064 Customer01: Got counter 
 30.1802 Customer01: Finished    
 32.3277 Customer02: Arrived     
 32.3277 Customer02: Got counter 
 34.5627 Customer03: Arrived     
 42.3374 Customer02: Finished    
 42.3374 Customer03: Got counter 
 46.4642 Customer03: Finished    
 61.7697 Customer04: Arrived     
 61.7697 Customer04: Got counter 
 94.1098 Customer04: Finished    
Avge waiting = 0.0826
Avge active = 0.6512

Multiple runs

Avge wait for  50 completions was   2.75 min.
Avge wait for  50 completions was   6.01 min.
Avge wait for  50 completions was   5.53 min.
Avge wait for  50 completions was   3.76 min.