Python Sim
Python Sim
Simulation Programming
with Python
This chapter shows how simulations of some of the examples in Chap. 3 can be
programmed using Python and the SimPy simulation library[1]. The goals of
the chapter are to introduce SimPy, and to hint at the experiment design and
analysis issues that will be covered in later chapters. While this chapter will
generally follow the flow of Chap. 3, it will use the conventions and patterns
enabled by the SimPy library.
1
2 CHAPTER 4. SIMULATION PROGRAMMING WITH PYTHON
ries as necessary software libraries are being ported and tested. SimPy itself
supports the Python 3.x series as of version 2.3. In addition, SimPy is undergo-
ing a major overhaul from SimPy 2.3 to version 3.0. This chapter and the code
on the website will assume use of Python 2.7.x and SimPy 2.3. In the future,
the book website will also include versions of the code based on SimPy 3.02 and
Python 3.2 as they and their supporting libraries are developed.
SimPy comes with data collection capabilities. But for other data analysis
tasks such as statistics and plotting it is intended to be used along with other
libraries that make up the Python scientific computing ecosystem centered on
Numpy and Scipy[3]. As such, it can easily be used with other Python packages
for plotting (Matplotlib), GUI (WxPython, TKInter, PyQT, etc.), statistics
(scipy.stats, statsmodels), and databases. This chapter will assume that you
have Numpy, Scipy3 , Matplotlib4 , and Statsmodels5 installed. In addition the
network/graph library Networkx will be used in a network model, but it can
be skipped with no loss of continuity. The easiest way to install Python along
with its scientific libraries (including SimPy) is to install a scientifically oriented
distribution, such as Enthought Canopy6 for Windows, Mac OS X, or Linux;
or Python (x,y)7 for Windows or Linux. If you are installing using a standard
Python distribution, you can install SimPy by using easy install or pip. Note
the capitalization of ‘SimPy’ throughout.
or
The other required libraries can be installed in a similar manner. See the
specific library webpages for more information.
This chapter will assume that you have the Numpy, Scipy, Matplotlib, and
Statsmodels libraries installed.
The Scipy module includes a larger list of random variate generators includ-
ing over 80 continuous and 10 discrete random variable distributions. For each
distribution, a number of functions are available:
import numpy as np
import scipy as sp
2. Set the random number seed. Scipy uses the Numpy random number gen-
erators so the Numpy seed function should be used: np.random.seed(1234)
• yield request: used to cause a process to join a queue for a given re-
source (and start using it immediately if no other jobs are waiting for the
resource);
8 this method is known in the documentation as freezing a distribution.
4.1. SIMPY OVERVIEW 5
• yield release: used to indicate that the process is done using the given
resource, thus enabling the next thread in the queue, if any, to use the
resource;
The simulation must also collect data for use in later calculating statistics
on the performance of the system. In SimPy, this is done through creating a
Monitor.
Collecting data within a simulation is done through a Monitor or a Tally.
As the Monitor is the more general version, this chapter will use that. You
can go to the SimPy website for more information. The Monitor makes ob-
servations and records the value and the time of the observation, allowing for
statistics to be saved for analysis after the end of the simulation. The Mon-
itor can also be included in the definition of any Resource (to be discussed
in the main simulation program) so statistics on queues and other resources
can be collected as well. In the Car object; the Monitor parking tracks the
value of the variable self.sim.parkedcars at every point where the value of
self.sim.parkedcars changes, as cars enter and leave the parking lot.
In the main part of the simulation program, the simulation object is defined,
then resources, processes, and monitors are defined and activated as needed to
start the simulation. In addition, the following function calls can be made:
6 CHAPTER 4. SIMULATION PROGRAMMING WITH PYTHON
class Arrival(Sim.Process):
""" Source generates cars at random
def generate(self):
i=0
while (self.sim.now() < G.maxTime):
tnow = self.sim.now()
arrivalrate = 100 + 10 * math.sin(math.pi * tnow/12.0)
t = random.expovariate(arrivalrate)
yield Sim.hold, self, t
c = Car(name="Car%02d" % (i), sim=self.sim)
timeParking = random.expovariate(1.0/G.parkingtime)
self.sim.activate(c, c.visit(timeParking))
i += 1
class Car(Sim.Process):
""" Cars arrives, parks for a while, and leaves
Maintain a count of the number of parked cars as cars arrive and leave
"""
Within the Car object, the yield Sim.hold, self, timeParking line is
used to represent the car remaining in the parking lot. To look at this line more
closely
3. self: A reference to the current object (Car). The first parameter passed
to the Sim.hold command. In this case it means the currently created Car
should wait for a period of time. If the yield hold line was preceded by
a yield request, the resource required by yield request would be in-
cluded in the yield hold, i.e. both the current process and any resources
the process is using would wait for the specified period of time.
4. timeParking: The time that the Car should wait. This is the second
parameter passed to the Sim.hold command.
Typically, yield, request, hold, release are used in sequence. For ex-
ample, if the number of parking spaces were limited, the act of a car taking a
parking space for a period of time would be represented as follows within the
Car.visit() function.
In this case, since the purpose of the simulation is to determine demand for
parking spaces, we assume there are unlimited spaces and we count the number
of cars in the parking lot at any point in time.
In SimPy, resources such as parking spaces are represented by Resources.
There are three types of resources.
class G:
maxTime = 24.0 # hours
arrivalrate = 100 # per hour
parkingtime = 2.0 # hours
parkedcars = 0
seedVal = 9999
Figure 4.3: Global declarations.
Global declarations are in Fig. 4.3. While Python allows these to be in the
global namespace, it is preferred that these be put into a class created for the
purpose as shown here. In particular, this is generally used as a central location
for parameters of the model.
The main simulation class is shown in Fig. 4.4. The simulation class Parkingsim
is a subclass of Sim.Simulation. While it can have other functions, the central
function is the run(self) function. Note that the first argument of a member
function of a class is self, indicating that the function has access to the other
functions and variables of the class. The run function takes one argument, the
random number seed. Sim.initialize() sets all Monitors and the simulation
clock. Then processes and resources are created. In this simulation there is one
process, the generation of arriving cars in Arrival. Note that at this point,
there are no Car’s, as the Arrival process will create the cars. This simulation
does not have any resources; but if, for example, the parking lot had a limited
capacity of 20 spaces, it could have been created here by:
self.parkinglot = Sim.Resource(capacity = 20, name=’Parking lot’,
unitName=’Space’, monitored=True, sim=self)
This creates the parking lot with 20 spaces. By default, resources are a
FIFO, non-priority queue with no preemption. In addition to the capacity of
the Resource (number of servers), there are two queues (lists) associated with
the resource. First is the activeQ, which is the list of process objects currently
using the resource. Second is the waitQ, which is the number of processes that
have requested but have not yet received a unit of the resource. If when creating
the resource the option monitored=True is set, then a Monitor is created for
each queue, and statistics can be collected on resource use and the wait queue for
further analysis. The last option is sim=self, which declares that the Process
or Resource is part of the simulation defined in the current class derived from
Sim.Simulation. If the simulation was defined in the global namespace (not
inside of a class), then this option would not be needed.
After Processes and Resources are created, any additional Monitors are cre-
ated here. Note that Processes, Resources, and Monitors are created using
self. constructs. This classifies the object as part of the class, and not only
local to the run() function. Other classes and methods that are part of this
simulation (declared using sim = self) can refer to any object created here
using self.sim.objectname. This includes Monitors as well as variables that
need to be updated from anywhere in the simulation. For example, the vari-
able self.parkedcars can be updated from the Car class in Fig. 4.2 using
10 CHAPTER 4. SIMULATION PROGRAMMING WITH PYTHON
class Parkingsim(Sim.Simulation):
def run(self, aseed):
random.seed(seed)
Sim.initialize()
s = Arrival(name=’Arrivals’, sim=self)
self.parking = Sim.Monitor(name=’Parking’, ylab=’cars’,
tlab=’time’, sim=self)
self.activate(s, s.generate(), at=0.0)
self.simulate(until=G.maxTime)
parkinglot = Parkingsim()
parkinglot.run(1234)
self.sim.parkedcars.
Following the main simulation class, the class is instantiated using parkinglot
= Parkingsim(), then the simulation is run using parkinglot.run(seedvalue).
One advantage of using a simulation class and object is that the monitors cre-
ated in the simulation are available to the object instance parkinglot after the
simulation is run. If the simulation is run from within the Python command
line or the IPython notebook9 , this allows for interactive exploration of the sim-
ulation results. For example, the monitor parking monitors the number of cars
that are in the parking lot by time. So a graph can be plotted that tracks the
number of cars over the course of the 24 hour day. (Fig. 4.5) The steps are:
loop.10 For each replication, initialize the parkinglot instance of the simulation
object, then run using a new random number seed. Then, append the simulation
results to a list object that was initialized using parkingdemand = []. Note
that any object can be appended to a list. In this case the monitor parking for
each simulation run was saved to the list parkingdemand.
From this list of simulation monitor results, one can then extract a particular
data element, then calculate statistics from it. So, for each simulation monitor
saved to parkingdemand, the time average number of cars in the lot is given
by parkingdemand[i].timeAverage(). So, to have a list of the time average
number of cars for each replication, we can use the list comprehension
[parkingdemand[i].timeAverage() for i in range(daysrep)].
The construct [function(i) for i in range(datasetlength)] is known
as a list comprehension. It is a compact method for stating:
10 The Python scientific libraries include provisions for working with multi-core processors
for i in range(datasetlength):
function(i)
maxparkingdailyparking = [max(parkingdemand[i].yseries())
for i in range(daysrep)]
plt.hist(maxparkingdailyparking, bins=25, cumulative = False)
plt.xlabel(’Maximum number of cars’)
plt.ylabel(’Days (cumulative)’)
0.761955484599
Figure 4.12: Test for normality for average cars parked.
We think that the distribution of the average number of cars in the lot
on any given day follows a normal distribution. We can test this using the
the sp.stats.normaltest function. (Figure 4.12) In addition, we can plot a
normal probability plot using the sp.stats.statsplot function. Figure 4.13
shows a normal probability plot that is consistant with a hypothesis that the
average number of cars in a day follows a normal distribution.
Figure 4.13: Normal probability plot of average cars parked in a day generated
by scipy.stats.statsplot().
4. When this example was introduced in Sect. 3.1 , it was suggested that
we size the garage based on the (Poisson) distribution of the number of
cars in the garage at the point in time when the mean number in the
garage was maximum. Is that what we did, empirically, here? If not,
how is the quantity we estimated by simulation related to the suggestion
in Sect. 3.1(for instance, will the simulation tend to suggest a bigger or
smaller garage than the analytical solution in Sect. 3.1
5. One reason that this simulation executes quite slowly when λ(t) = 1000 +
100 sin(πt/12) is that the thinning method we used is very inefficient (lots
of possible arrivals are rejected). Speculate about ways to make it faster.
Y0 = 0 X0 = 0
Yi = max{0, Yi−1 + Xi−1 − Ai }, i = 1, 2, . . .
where Yi is the ith customer’s waiting time, Xi is that customer’s service time,
and Ai is the interarrival time between customers i−1 and i. Lindley’s equation
avoids the need for an event-based simulation, but is limited in what it produces
(how would you track the time-average number of customers in the queue?). In
this section we will describe both recursion-based and event-based simulations
of this queue, starting with the recursion.
Table 4.1: Ten replications of the M/G/1 queue using Lindley’s equation.
In addition, we will not make a single run of m customers, but instead will make
n replications. This yields n i.i.d. averages Ȳ1 (m, d), Ȳ2 (m, d), . . . , Ȳn (m, d) to
which we can apply standard statistical analysis. This avoids the need to directly
estimate the asymptotic variance γ 2 , a topic we defer to later chapters.
Figure 4.14 shows a Python simulation of the M/G/1 queue using Lindley’s
equation. In this simulation m = 55,000 customers, we discard the first d = 5000
of them, and make n = 10 replications.
The ten replication averages can be then individually written to an comma
separated value (csv) file named “lindley.csv” (Fig. 4.15) and also printed out
to the screen with the mean and standard deviation as in Table 4.1.
Notice that the average waiting time is a bit over 2 minutes, and that Python,
like all programming languages, could display a very large number of output
digits. How many are really meaningful? A confidence interval is one way to
provide an answer.
Since the across-replication averages are i.i.d., and since each across-replication
average is itself the within-replication average of a large number of individual
waiting times (50,000 to be exact), the assumption of independent, normally dis-
tributed output data is reasonable. This justifies a t-distribution confidence in-
terval on µ. The key ingredient is t1−α/2,n−1 , the 1−α/2 quantile of the t distri-
bution with n−1 degrees of freedom. If we want a 95% confidence interval, then
1−α/2 = 0.975, and our degrees of freedom √ are 10−1 = 9. Since t0.975,9 = 2.26,
we get 2.156175535 ± (2.26)(0.075074639)/ 10 or 2.156175535 ± 0.053653949.
This implies that we can claim with high confidence that µ is around 2.1 min-
utes, or we could give a little more complete information as 2.15 ± 0.05 minutes.
Any additional digits are statistically meaningless.
Is an average of 2 minutes too long to wait? To actually answer that question
would require some estimate of the corresponding wait to see the receptionist,
4.3. SIMULATING THE M/G/1 QUEUE 17
import numpy as np
# Use scipy.stats because it includes the Erlang distribution
from scipy.stats import expon, erlang
import matplotlib.pyplot as plt
def lindley(m=55000, d = 5000):
’’’ Estimates waiting time with m customers, discarding the first d
import csv
with open("lindley.csv"), "rb") as myFile:
lindleyout = csv.writer(myFile)
lindleyout.writerow("Waitingtime")
for row in result:
print row
for i in range(len(result)):
print ("%1d & %11.9f " % (i+1, result[i]))
print("average & %11.9f" % (mean(result)))
print("std dev & %11.9f" % (std(result)))
class G:
maxTime = 55000.0 # minutes
warmuptime = 5000.0
timeReceptionist = 0.8 # mean, minutes
phases = 3
ARRint = 1.0 # mean, minutes
theseed = 99999
\textbf
• Resource objects including Level and Store are used to designate re-
4.3. SIMULATING THE M/G/1 QUEUE 19
class Hospitalsim(Sim.Simulation):
def run(self, theseed):
np.random.seed(theseed)
self.receptionist = Sim.Resource(name="Reception", capacity=1,
unitName="Receptionist", monitored=True, sim=self)
s = Arrivals(’Source’, sim=self)
self.initialize()
self.activate(s, s.generate(meanTBA=G.ARRint,
resource=self.receptionist), at=0.0)
self.simulate(until=G.maxTime)
avgutilization = self.receptionist.actMon.timeAverage()[0]
avgwait = self.receptionist.waitMon.mean()
avgqueue = self.receptionist.waitMon.timeAverage()[0]
leftinqueue= mg1.receptionist.waitMon.yseries()[-1:][0]
return [avgwait, avgqueue, leftinqueue,avgutilization]
sources that are required by a Process over the course of the simulation.
Any of these can have a Process utilizing a unit of resource, or there
could be Process in a queue waiting for a resource to be available.
– A Resource has units that are required by a Process.
– A Level is an undifferentiated item that can be taken or produced
by a Process.
– A Store is an inventory of heterogeneous items where a Process will
require a specific type of item from the Store.
• Monitor objects are used to record observations so that they may be
analyzed later. In particular, a Resource can also have a Monitor to
observe Process that are utilizing or waiting in a queue to utilize a unit
of a Resource.
Figure 4.17 shows the declarations of the Process and Resource objects,
specifically:
self.receptionist = Sim.Resource(name="Reception", capacity=1,
unitName="Receptionist", monitored=True, sim=self)
s = Arrivals(’Source’, sim=self)
These are both declared within the Simulation object Hospitalsim, and
both specify that they are a part of the current simulation (sim=self). While
these could be declared as a local variable, the Resource self.receptionist
is declared as part of the simulation object self. When it is declared, it can
be given a capacity, a qtype (queue type, FIFO, LIFO, or priority), if it
20 CHAPTER 4. SIMULATION PROGRAMMING WITH PYTHON
class Arrivals(Sim.Process):
""" Source generates customers randomly """
class Patient(Sim.Process):
""" Patient arrives, is served and leaves """
hospitalreception = []
for i in range(10):
mg1 = Hospitalsim()
mg1.startCollection(when=G.warmuptime,
monitors=mg1.allMonitors)
result = mg1.run(4321 + i)
hospitalreception.append(result)
Table 4.2: Ten replications of the M/G/1 queue using the event-based simula-
tion.
Rep Total Wait Queue Remaining Utilization
1 3.213462878 2.160833599 0 0.798567300
2 3.280708784 2.246598372 1 0.808480012
3 3.165536548 2.108143837 12 0.793258928
4 2.879284462 1.919272701 6 0.794702843
5 3.222073305 2.176042086 0 0.800707100
6 3.179741189 2.145124000 4 0.800669924
7 3.201467600 2.170802331 1 0.801600605
8 3.095751521 2.062482343 3 0.795603232
9 3.445755412 2.331405016 5 0.802041612
10 3.039486198 2.032295429 2 0.796786730
average 3.172326790 2.135299972 3.400000000 0.799241829
std dev 0.141778429 0.108549951 3.469870315 0.004231459
95 C.I. 0.320725089 0.245557048 7.849391986 0.009572226
Again there are meaningless digits, but the confidence intervals can be used
to prune them. For instance, for the mean total wait we could report 3.17 ± 0.32
minutes. How does this statistic relate to the 2.16±0.08 minutes reported for the
simulation via Lindley’s equation? Mean total time in the kiosk system (which
is what the event-based simulation estimates) consists of mean time waiting
to be served (which is what the Lindley simulation estimates) plus the mean
service time (which we know to be 0.8 minutes). So it is not surprising that
these two estimates differ by about 0.8 minutes.
Y = max{X1 + X4 , X1 + X3 + X5 , X2 + X5 }
where Xi is the duration of the ith activity. This simple representation requires
that we enumerate all paths through the SAN, so that the project comple-
tion time is the longest of these paths. Path enumeration itself can be time
consuming, and this approach does not easily generalize to projects that have
resources shared between activities, for instance. Therefore, we also present a
discrete-event representation which is more complicated, but also more general.
1. set s = 0
2. repeat n times:
(a) generate X1 , X2 , . . . , X5
(b) set Y = max{X1 + X4 , X1 + X3 + X5 , X2 + X5 }
(c) if Y > tp then set s = s + 1
3. estimate θ by θb = s/n
Since Pr{Y ≤ tp } is known for this example (see Eq. 3.12), the true θ =
Pr{Y > tp } = 0.16533 when tp = 5 is also computed by the program so that
we can compare it to the simulation estimate. Of course, in a practical problem
we would not know the answer, and we would be wasting our time simulating
it if we did. Notice that even if all of the digits in this probability estimate are
correct, they certainly are not practically useful.
The simulation estimate turns out to be θb = 0.15400. A nice feature of a
probability estimate that is based on i.i.d. outputs is that an estimate of its
standard error is easily computed:
s
b − θ)
θ(1 b
se
b = .
n
Thus, se
b is approximately 0.011, and the simulation has done its job since the
true value θ is well within ±1.96 se
b of θ.
b This is a reminder that simulations do
not deliver the answer, like Eq. 3.12, but do provide the capability to estimate
the simulation error, and to reduce that error to an acceptable level by increasing
the simulation effort (number of replications).
class SAN:
N = 1000
tp = 5.0
def constructionsan(seed):
random.seed(seed)
X = [random.expovariate(1.0) for i in range(5)]
Y = max(X[0]+X[3], X[0]+X[2] + X[4], X[1] + X[4])
return Y
initialseed = 2124
Y = [constructionsan(initialseed + i) for i in range(SAN.N)]
Ytp = [1.0 if Y[i]>SAN.tp else 0 for i in range(SAN.N)]
thetahat = sum(Ytp)/SAN.N
sethetahat = math.sqrt((thetahat*(1-thetahat))/SAN.N)
Figure 4.20: Simulation of the SAN as the maximum path through the network.
26 CHAPTER 4. SIMULATION PROGRAMMING WITH PYTHON
import random
import SimPy.Simulation as Sim
import networkx as nx
class SANglobal:
F = nx.DiGraph()
a = 0
b = 1
c = 2
d = 3
inTo = 0
outOf = 1
F.add_nodes_from([a, b, c, d])
F.add_edges_from([(a,b), (a,c), (b,c), (b,d), (c,d)])
Of course, this approach shifts the effort from enumerating all of the paths
through the SAN to creating the sets I, O, D, but these sets have to be either
explicitly or implicitly defined to define the project itself. The key lesson from
this example, which applies to many simulations, is that it is possible to program
a single event routine to handle many simulation events that are conceptually
distinct, and this is done by passing event-specific information to the event
routine.
In this case we need to develop the configuration of that activity network
and use that description to direct the simulation. To do so we will use the
NetworkX11 graph library. NetworkX is a Python language software library for
the creation, manipulation, and study of the structure, dynamics, and functions
of complex networks. While it includes a wide range of graph algorithms, we
will use it as a standard representation of graphs such as the stochastic activity
network.
Using NetworkX, we create a directed graph (nx.DiGraph()) with four nodes
with five directed edges. (Figure 4.21) Implicitely, it also creates predecessor
and successor lists for each node that can be accessed using F.predecessors(i)
or F.successors(i).
We then define events as the completion of activities that go into a given
node. Events trigger a signal that can be used to trigger other activities.
In the first block of code in Figure 4.22 an event is defined for each node in
the network and added to a list of events (nodecomplete) which corresponds to
the list of nodes. Then, for each node, the list of predecessor events is created
(preevents) and the node is created as an ActivityProcess. (Figure )
For each ActivityProcess, the waitup() function is focused on the waitevent
event. This takes as an arguement myEvent, which is the list of predecessor
11 http://networkx.github.io/
4.4. SIMULATING THE STOCHASTIC ACTIVITY NETWORK 27
SANglobal.finishtime = 0
Sim.initialize()
SANglobal.F.nodecomplete= []
for i in range(len(SANglobal.F.nodes())):
eventname = ’Complete%1d’ % i
SANglobal.F.nodecomplete.append(Sim.SimEvent(eventname))
SANglobal.F.nodecomplete
activitynode = []
for i in range(len(SANglobal.F.nodes())):
activityname = ’Activity%1d’ % i
activitynode.append(ActivityProcess(activityname))
for i in range(len(SANglobal.F.nodes())):
if i <> SANglobal.inTo:
prenodes = SANglobal.F.predecessors(i)
preevents = [SANglobal.F.nodecomplete[j] for j in prenodes]
Sim.activate(activitynode[i], activitynode[i].waitup(i,preevents))
startevent = Sim.SimEvent(’Start’)
Sim.activate(activitynode[SANglobal.inTo],
activitynode[SANglobal.inTo].waitup(SANglobal.inTo, startevent))
sstart = StartSignaller(’Signal’)
Sim.activate(sstart, sstart.startSignals())
Sim.simulate(until=50)
class ActivityProcess(Sim.Process):
def waitup(self,node, myEvent): # PEM illustrating "waitevent"
# wait for "myEvent" to occur
yield Sim.waitevent, self, myEvent
tis = random.expovariate(1.0)
print (’ The activating event(s) were %s’ %
([x.name for x in self.eventsFired]))
yield Sim.hold, self, tis
finishtime = Sim.now()
if finishtime >SANglobal.finishtime:
SANglobal.finishtime = finishtime
SANglobal.F.nodecomplete[node].signal()
class StartSignaller(Sim.Process):
# here we just schedule some events to fire
def startSignals(self):
yield Sim.hold, self, 0
startevent.signal()
events that were identified in the main simulation. As each in the myEvent list
occurs, it broadcasts its associated signal using the signal() function. When all
the events in a ActivityProcess waitevent list (myEvent in Figure ?? have
occurred, the yield condition is met and the next line in ActivityProcess
begins.
To start the simulation, we create a Process that will provide the initiating
event of the simulation. (Figure 4.24) Similarly, we treat the initial node of the
simulation differently by having it wait for the start signal to begin instead of
waiting for predecessor events like the other nodes.
Notice (see Fig. 4.22) that the simulation ends when there are no additional
activities remaining to be completed.
A difference between this implementation of the SAN simulation and the one
in Sect. 4.4.1 is that here we write out the actual time the project completes on
each replication. By doing so, we can estimate Pr{Y > tp } for any value of tp by
sorting the data and counting how many out of 1000 replications were greater
4.5. SIMULATING THE ASIAN OPTION 29
than tp . Figure 4.25 shows the empirical cdf of the 1000 project completion
times, which is the simulation estimate of Eq. (3.12).
time. The value of the option from each replication is saved to a list for post-
simulation analysis.
The estimated value of ν is $2.20 with a relative error of just over 2% (recall
that the relative error is the standard error divided by the mean). As the
histogram in Fig. 4.27 shows, the option is frequently worthless (approximately
68% of the time), but the average payoff, conditional on the payoff being positive,
is approximately $6.95.
Example 4.1 (Fax Center Staffing) A service center receives faxed orders
throughout the day, with the rate of arrival varying hour by hour. The ar-
rivals are modeled by a nonstationary Poisson process with the rates shown in
Table 4.3.
A team of Entry Agents select faxes on a first-come-first-served basis from
the fax queue. Their time to process a fax is modeled as normally distributed
with mean 2.5 minutes and standard deviation 1 minute. There are two possible
outcomes after the Entry Agent finishes processing a fax: either it was a simple
fax and the work on it is complete, or it was not simple and it needs to go to a
Specialist for further processing. Over the course of a day, approximately 20%
of the faxes require a Specialist. The time for a Specialist to process a fax is
modeled as normally distributed with mean 4.0 minutes and standard deviation
1 minute.
Minimizing the number of staff minimizes cost, but certain service-level re-
quirements much be achieved. In particular, 96% of all simple faxes should be
4.6. CASE STUDY: SERVICE CENTER SIMULATION 31
The first step in building any simulation model is deciding what question or
questions that the model should answer. Knowing the questions helps identify
the system performance measures that the simulation needs to estimate, which
in turn drives the scope and level of detail in the simulation model.
The grand question for the service center is, what is the minimum number of
Entry Agents and Specialists needed for both time periods to meet the service-
level requirements? Therefore, the simulation must at least provide an estimate
of the percentage of faxes of each type entered within 10 minutes, given a specific
staff assignment.
Even when there seems to be a clear overall objective (minimize the staff re-
quired to achieve the service-level requirement), we often want to consider trade
offs around that objective. For instance, if meeting the requirement requires a
staff that is so large that they are frequently underutilized, or if employing the
minimal staff means that the Entry Agents or Specialists frequently have to
work well past the end of the day, then we might be willing to alter the service
requirement a bit. Statistics on the number and the time spent by faxes in
queue, and when the last fax of each day is actually completed, provide this
information. Including additional measures of system performance, beyond the
most critical ones, makes the simulation more useful.
Many discrete-event, stochastic simulations involve entities that dynamically
flow through some sort of queueing network where they compete for resources.
In such simulations, identifying the entities and resources is a good place to
start the model. For this service center the faxes are clearly the dynamic en-
tities, while the Entry Agents and Specialists are resources. The fax machines
themselves might also be considered a resource, especially if they are heavily
utilized or if outgoing as well as incoming faxes use the same machines. It turns
out that for this service center there is a bank of fax machines dedicated to in-
coming faxes, so it is reasonable to treat the arrival of faxes as an unconstrained
external arrival process. This fact was not stated in the original description of
the problem; follow-up questions are often needed to fully understand the system
of interest.
Whenever there are scarce resources, queues may form. Queues are often
first-in-first-out, with one queue for each resource, as they are in this service
center. However, queues may have priorities, and multiple queues may be served
by the same resource, or a single queue may feed multiple resources. Queueing
32 CHAPTER 4. SIMULATION PROGRAMMING WITH PYTHON
"""
sumx = 0.0
# Create instance of a random number object
generator = random.Random()
generator.seed(seed)
x = initialValue
sigma2 = (sigma*sigma)/2.0
for j in range(steps):
z = generator.normalvariate(0, 1)
x = x * math.exp((interestRate - sigma2) * interval + sigma * math.sqrt(interval) * z)
sumx = sumx + x
value = math.exp(-interestRate * maturity) * max(sumx / float(steps) - strikePrice, 0.0)
return value
replications = 10000
initialSeed = 1234
maturity = 1.0
steps = 32
sigma = 0.3
interestRate = 0.05
initialValue = 50.0
strikePrice = 55.0
interval = maturity / float(steps)
6000
4000
2000
0
0 10 20 30 40
Asian
Figure 4.27: Histogram of the realized value of the Asian option from 10,000
replications.
import random
import SimPy.Simulation as Sim
class F:
maxTime = 100 # hours
seedval = 1234
period = 60.0
nPeriods = 8 # periods per day
meanRegular = 2.5/period # hours
varRegular = 1.0/period # hours
stdRegular = math.sqrt(1.0)/period
meanSpecial = 4.0/period # hours
varSpecial = 1.0/period # hours
stdSpecial = math.sqrt(1.0)/period
tPMshiftchange = 4.0
numAgents = 15
numAgentsPM = 9
numSpecialists = 6
numSpecialistsPM = 3
maxRate = 6.24
aRate= [4.37, 6.24, 5.29, 2.97, 2.03, 2.79, 2.36, 1.04]
aRateperhour = [aRate[i] * period for i in range(len(aRate))]
meanTBA = 1/(maxRate * period) # hours
pSpecial = 0.20
The main program for the simulation is in Fig. 4.29. Of particular note are
the two Monitor statements defining Regular10 and Special10. These will
be used to obtain the fraction of regular and special faxes that are processed
within the 10-minute requirement by recording a 1 for any fax that meets the
requirement, and a 0 otherwise. The mean of these values is the desired fraction.
Also notice is the condition that ends the main simulation loop:
self.simulate(until=F.maxTime)
Because the simulation ends well after the arrivals cease, any faxes still in
the queue will be completed prior to the end of the simulation. When the event
calendar is empty, then there are no additional faxes to process, and no pending
arrival of a fax. This condition will only hold after 4 PM and once all remaining
faxes have been entered.
36 CHAPTER 4. SIMULATION PROGRAMMING WITH PYTHON
class Faxcentersim(Sim.Simulation):
def run(self, aseed):
random.seed(aseed)
self.agents = Sim.Resource(capacity=F.numAgents,
name="Service Agents", unitName="Agent", monitored = True,
qType=Sim.PriorityQ, sim=self)
self.specialagents = Sim.Resource(capacity=F.numSpecialists,
name="Specialist Agents", unitName="Specialist", monitored=True,
qType=Sim.PriorityQ, sim=self)
self.meanTBA = 0.0
self.initialize()
s = Source(’Source’, sim=self)
a = ArrivalRate(’Arrival Rate’, sim=self)
tchange = SecondShift(’PM Shift’, sim=self)
self.Regularwait = Sim.Monitor(name="Regular time",
ylab=’hours’, sim=self)
self.Specialistwait = Sim.Monitor(name="Special time",
ylab=’hours’, sim=self)
self.activate(a, a.generate(F.aRateperhour))
self.activate(s,
s.generate(resourcenormal=self.agents,
resourcespecial=self.specialagents), at=0.0)
self.activate(tchange, tchange.generate(F.tPMshiftchange,
resourcenormal=self.agents,
resourcespecial=self.specialagents))
self.simulate(until=F.maxTime)
def reporting(self):
regularcount = self.Regularwait.count()
regularwait = self.Regularwait.mean()
regularQ = self.agents.waitMon.timeAverage()
regularagents = self.agents.actMon.timeAverage()
regular10min = sum([1.0 if waittime < 1./6 else 0
for waittime in self.Regularwait.yseries()])
fractionregular10min = regular10min/regularcount
specialcount = self.Specialistwait.count()
specialwait = self.Specialistwait.mean()
specialQ = self.specialagents.waitMon.timeAverage()
specialagents = self.specialagents.actMon.timeAverage()
special10min = sum([1.0 if waittime < 1./6 else 0
for waittime in self.Specialistwait.yseries()])
fractionspecial10min = special10min/specialcount
result = [regularwait, regularQ, regularagents,
specialwait, specialQ, specialagents,
fractionregular10min, fractionspecial10min]
return result
reps=10
faxsimulation = []
for i in range(reps):
faxsim = Faxcentersim()
faxsim.run(F.seedval + i)
result = faxsim.reporting()
faxsimulation.append(result)
mean(faxsimulation, axis=0)
std(faxsimulation, axis=0)
Figure 4.29: Main program and statistics reporting for service center simulation.
4.6. CASE STUDY: SERVICE CENTER SIMULATION 37
Figure 4.30 includes processes that generate faxes (Source) and determine
how they are routed to agents (Fax). As faxes are routed, the simulation de-
termines if they require special handling after the regular agent is complete
(if (checkSpecial < F.pSpecial)). There are also two Monitor present,
Regularwait and Specialistwait which record the total wait time for each
fax that is completed.
self.sim.Regularwait.observe(finished)
Later, in the reporting()) function of the main program shown in Figure
4.29, this Monitor will be used to both get the number of total faxes of this
type, the number that waited less than 10 minutes before completing processing,
and the fraction.
regularcount = self.Regularwait.count()
regular10min = sum([1.0 if waittime < 1./6 else 0
for waittime in self.Regularwait.yseries()])
fractionregular10min = regular10min/regularcount
While collecting statistics in this fashion provides the most flexibility as it
keeps the wait time observations for future use, we could have instead recorded
if the wait time was less than 10 minutes.
if finished < 1.0/6: # 10 minutes
self.sim.Regularwait.observe(1)
else:
self.sim.Regularwait.observe(0)
Then we could have calculated the fraction by taking the sum of the obser-
vations divided by the number of observations.
fractionregular10min = float(sum(self.Regularwait))/
len(self.Regularwait)
The Fax.reporting() then uses the Monitor for wait time as well as the
monitors associated with the agents and specialagents resources. The actMon
monitors track how the resources are being used while the waitMon monitors
track the waiting queue for each monitor. For resources, we tend to be inter-
ested in the time average value of the size of the queue or the number of units of
resource in use so the agents.actMon.timeAverage() function returns the av-
erage utilization of the agents while specialagents.waitMon.timeAverage()
function returns the average number of special faxes in queue.
Ten replications of this simulation with a staffing policy of 15 Entry Agents
in the morning and 9 in the afternoon, and 6 Specialists in the morning and 3
in the afternoon, gives 0.98 ± 0.04 for the fraction of regular faxes entered in 10
minutes or less, and 0.84±0.08 for the special faxes. The “±” are 95% confidence
intervals. This policy appears to be close to the requirements, although if we
absolutely insist on 80% for the special faxes then additional replications are
needed to narrow the confidence interval.
38 CHAPTER 4. SIMULATION PROGRAMMING WITH PYTHON
class Source(Sim.Process):
""" Source generates customers randomly """
class Fax(Sim.Process):
""" Fax arrives and is procossed
class ArrivalRate(Sim.Process):
""" update the arrival rate every hour
Reads in the arrival rate table and updates the arrival rate every hour
One hour after the last hour begins, changes arrival rate to 0
"""
def generate(self, arrivalrate):
for i in range(len(arrivalrate)):
self.sim.meanTBA = 1.0/(arrivalrate[i])
yield Sim.hold, self, 1.0
# After the end of the day, set the arrival rate = 0
self.sim.meanTBA = 0.0
class SecondShift(Sim.Process):
""" Trigger the change in shifts for agents
The effect should be to move the wait queue to the new set of agents
"""
for i in range(reduceagents):
a = Agentoff(name="removeagent%02d" % (i), sim=self.sim)
self.sim.activate(a, a.visit(resourcenormal))
for j in range(reducespecial):
a = Agentoff(name="removespecial%02d" % (i) , sim=self.sim)
self.sim.activate(a, a.visit(resourcespecial))
class Agentoff(Sim.Process):
def visit(self, agent):
tremain = F.maxTime - self.sim.now()+1
# use priority 100 to ensure agent is removed as soon as current fax is done
yield Sim.request, self, agent, 100
yield Sim.hold, self, tremain
yield Sim.release, self, agent
class F:
maxTime = 100.0 # hours
theseed = 9999
period = 60.0
nPeriods = 8
meanRegular = 2.5/period # hours
varRegular = 1.0/period # hours
stdRegular = math.sqrt(1.0)/period
meanSpecial = 4.0/period # hours
varSpecial = 1.0/period # hours
stdSpecial = math.sqrt(1.0)/period
tPMshiftchange = 4.0
numAgents = 15
numAgentsPM = 9
numSpecialists = 6
numSpecialistsPM = 3
maxRate = 6.24
aRate= [4.37, 6.24, 5.29, 2.97, 2.03, 2.79, 2.36, 1.04] # per minute
aRateperhour = [aRate[i] * period for i in range(len(aRate))] # per hour
meanTBA = 1/(maxRate * period) # hours
pSpecial = 0.20
2. The fax entry times were modeled as being normally distributed. However,
the normal distribution admits negative values, which certainly does not
make sense. What should be done about this? Consider mapping negative
values to 0, or generating a new value whenever a negative value occurs.
Which is more likely to be realistic and why?
Exercises
1. For the hospital problem, simulate the current system in which the recep-
tionist’s service time is well modeled as having an Erlang-4 distribution
4.6. CASE STUDY: SERVICE CENTER SIMULATION 41
with mean 0.6 minutes. Compare the waiting time to the proposed elec-
tronic kiosk alternative.
3. Modify the SAN simulation to allow each activity to have a different mean
time to complete (currently they all have mean time 1). Use a Collection
to hold these mean times.
4. Try the following numbers of steps for approximating the value of the
Asian option to see how sensitive the value is to the step size: m =
8, 16, 32, 64, 128.
5. In the simulation of the Asian option, the sample mean of 10,000 repli-
cations was 2.198270479, and the standard deviation was 4.770393202.
Approximately how many replications would it take to decrease the rela-
tive error to less than 1%?
6. For the service center, increase the number of replications until you can
be confident that that suggested policy does or does not achieve the 80%
entry in less than 10 minutes requirement for special faxes.
7. For the service center, find the minimum staffing policy (in terms of total
number of staff) that achieves the service-level requirement. Examine the
other statistics generated by the simulation to make sure you are satisfied
with this policy.
8. For the service center, suppose that Specialists earn twice as much as
Entry Agents. Find the minimum cost staffing policy that achieves the
service-level requirement. Examine the other statistics generated by the
simulation to make sure you are satisfied with this policy.
9. For the service center, suppose that the staffing level can change hourly,
but once an Agent or Specialist comes on duty they must work for four
hours. Find the minimum staffing policy (in terms of total number of
staff) that achieves the service-level requirement.
10. For the service center, pick a staffing policy that fails to achieve the service
level requirements by 20% or more. Rerun the simulation with a replica-
tion being defined as exactly 8 hours, but do not carry waiting faxes over
to the next day. How much do the statistics differ using the two different
ways to end a replication?
11. The function NSPP_Fax is listed below. This function implements the
thinning method described in Sect. 4.2 for a nonstationary Poisson process
with piecewise-constant rate function. Study it and describe how it works.
42 CHAPTER 4. SIMULATION PROGRAMMING WITH PYTHON
12. Beginning with the event-based M/G/1 simulation, implement the changes
necessary to make it an M/G/s simulation (a single queue with any num-
ber of servers). Keeping λ = 1 and τ /s = 0.8, simulate s = 1, 2, 3 servers
and compare the results. What you are doing is comparing queues with
the same service capacity, but with 1 fast server as compared to two or
more slower servers. State clearly what you observe.
13. Modify the SimPy event-based simulation of the M/G/1 queue to simulate
an M/G/1/c retrial queue. This means that customers who arrive to
find c customers in the system (including the customer in service) leave
immediately, but arrive again after an exponentially distributed amount
of time with mean MeanTR. Hint: The existence of retrial customers should
not affect the arrival process for first-time arrivals.
these cars departs is exponentially distributed with mean 1/(N β). Use
this insight to build an M (t)/M/∞ simulation with at most two pending
events, next arrival and next departure. Hint: Whenever an arrival oc-
curs the distribution of the time until the next departure changes, so the
scheduled next departure time must again be generated.
15. The phone desk for a small office is staffed from 8 AM to 4 PM by a
single operator. Calls arrive according to a Poisson process with rate 6
per hour, and the time to serve a call is uniformly distributed between 5
and 12 minutes. Callers who find the operator busy are placed on hold, if
there is space available, otherwise they receive a busy signal and the call
is considered “lost.” In addition, 10% of callers who do not immediately
get the operator decide to hang up rather than go on hold; they are not
considered lost, since it was their choice. Because the hold queue occupies
resources, the company would like to know the smallest capacity (number
of callers) for the hold queue that keeps the daily fraction of lost calls
under 5%. In addition, they would like to know the long-run utilization
of the operator to make sure he or she will not be too busy. Use SimPy
to simulate this system and find the required capacity for the hold queue.
Model the callers as a Process and the operator as a Resource. Use the
functions random.expovariate and random.uniform for random-variate
generation. Estimate the fraction of calls lost (record a 0 for calls not lost,
a 1 for those that are lost so that the sample mean is the fraction lost).
Use the statistics collected by class Resource to estimate the utilization.
16. Software Made Personal (SMP) customizes software products in two ar-
eas: financial tracking and contact management. They currently have a
customer support call center that handles technical questions for owners
of their software from the hours of 8 AM to 4 PM Eastern Time.
When a customer calls they the first listen to a recording that asks them to
select among the product lines; historically 59% are financial products and
41% contact management products. The number of customers who can be
connected (talking to an agent or on hold) at any one time is essentially
unlimited. Each product line has its own agents. If an appropriate agent is
available then the call is immediately routed to the agent; if an appropriate
agent is not available, then the caller is placed in a hold queue (and listens
to a combination of music and ads). SMP has observed that hang ups very
rarely happen.
SMP is hoping to reduce the total number of agents they need by cross-
training agents so that they can answer calls for any product line. Since
the agents will not be experts across all products, this is expected to
increase the time to process a call by about 5%. The question that SMP
has asked you to answer is how many cross-trained agents are needed to
provide service at the same level as the current system.
Incoming calls can be modeled as a Poisson arrival process with a rate of
60 per hour. The mean time required for an agent to answer a question
44 CHAPTER 4. SIMULATION PROGRAMMING WITH PYTHON
is 5 minutes, with the actual time being Erlang-2 for financial calls, and
Erlang-3 for contact management calls. The current assignment of agents
is 4 for financial and 3 for contact management. Simulate the system to
find out how many agents are needed to deliver the same level of service
in the cross-trained system as in the current system.
Bibliography
45