3.5 Optional: Discrete-event Simulation
3.5 Optional: Discrete-event Simulation
The queueing and inventory systems in the previous sections were based on simple recursions, and therefore straightforward to implement. When we need to analyze more difficult situations, we need discrete-event simulation. In this section we build a simulator for a \(G/G/c\) queue with different server speeds and test it. In the next section, we apply this to some non-trivial queueing situations. We will see the power of organizing ideas in classes.
The first class is a \(\cl{Server}\) with an identifier and a service rate. The method \(\cl{Server}.\pr{Faster?}\) enables us to express a preference for a server with a faster service rate.
\begin{algorithm}
\caption{A server with an identifier and a service rate.}
\begin{algorithmic}[1]
\State \textbf{Input:} Server identifier and service rate.
\State \textbf{Output:} A server.
\State \textbf{class} \(\cl{Server}\rb{\var{id},\,\var{rate}}\)
\State \(\quad\) \textbf{instance variables:}
\State \(\quad\quad \var{id},\,\var{rate}\gets\var{id},\,\var{rate}\)
\State \(\quad\) \textbf{methods:}
\State \(\quad\quad \pr{Faster?}\gets\lambdafun{\var{other}}{\var{rate}>\var{other}.\var{rate}}\)
\end{algorithmic}
\end{algorithm}
Python code
from dataclasses import dataclass
@dataclass
class Server:
id: int
rate: float
def faster(self, other):
return self.rate > other.rate
R code
Server <- setRefClass("Server",
fields = list(id = "numeric", rate = "numeric"),
methods = list(
faster = function(other) rate > other$rate
)
)
The \(\cl{Servers}\) class represents the pool of free servers. It uses a \(\cl{Heap}\) ordered by \(\cl{Server}.\pr{Faster?},\) to push and pop servers from the stack. When a job leaves, \(\cl{Servers}\) assigns the next job in queue to a server based on the priority rule stated in \(\cl{Server}.\pr{Faster?}.\) A server that becomes idle after finishing a job is pushed to the server pool. The convenience methods \(\cl{Servers}.\pr{NumFree}\) and \(\cl{Servers}.\pr{ServerFree?}\) improve readability compared to using \(\var{length}\) directly.
\begin{algorithm}
\caption{A heap of free servers with the fastest server first.}
\begin{algorithmic}[1]
\State \textbf{Input:} None.
\State \textbf{Output:} An empty pool of free servers.
\State \textbf{class} \(\cl{Servers}\rb{}\)
\State \(\quad\) \textbf{instance variables:}
\State \(\quad\quad \var{heap}\gets\cl{Heap}\rb{\lambdafun{(x,\,y)}{x.\pr{Faster?}\rb{y}}}\)
\State \(\quad\) \textbf{methods:}
\State \(\quad\quad \pr{Push}\gets \var{heap}.\pr{Push}\)
\State \(\quad\quad \pr{Pop}\gets \var{heap}.\pr{Pop}\)
\State \(\quad\quad \pr{NumFree}\gets\lambdafun{()}{\var{heap}.\var{length}}\)
\State \(\quad\quad \pr{ServerFree?}\gets\lambdafun{()}{\neg\var{heap}.\pr{Empty?}\rb{}}\)
\end{algorithmic}
\end{algorithm}
Python code
class Servers:
def __init__(self):
self.heap = Heap(lambda x, y: x.faster(y))
def push(self, server):
self.heap.push(server)
def pop(self):
return self.heap.pop()
def num_free(self):
return self.heap.length
def server_free(self):
return not self.heap.is_empty()
R code
Servers <- function() {
heap <- Heap$new(function(x, y) x$faster(y))
list(push = heap$push, pop = heap$pop,
num_free = function() heap$length,
server_free = function() !heap$is_empty())
}
The \(\cl{Job}\) class speaks mostly for itself. The service time equals the job’s load divided by the rate of the server that serves the job.1Since servers may have different rates, we can only compute the service time after the job is assigned to a server. The job keeps a reference to its assigned server. The other attributes are used for the statistics computations at the end of the simulation. We implement the sojourn time and waiting time as a property, as this allows us to access them the same way as, for example, the departure time. The properties \(\var{sojourn\_time}\) and \(\var{waiting\_time}\) compute these times from the job’s arrival, departure, and service times. The predicate \(\cl{Job}.\pr{Earlier?}\) compares arrival times for FIFO service, and \(\cl{Job}.\pr{Smaller?}\) compares job loads for shortest-processing-time-first service.
\begin{algorithm}
\caption{A job with its arrival time, load, and service statistics.}
\begin{algorithmic}[1]
\State \textbf{Input:} Job identifier, arrival time, and load.
\State \textbf{Output:} A job.
\State \textbf{class} \(\cl{Job}\rb{\var{id},\,\var{arrival\_time},\,\var{load}}\)
\State \(\quad\) \textbf{instance variables:}
\State \(\quad\quad \var{id}\gets\var{id}\)
\State \(\quad\quad \var{arrival\_time}\gets\var{arrival\_time}\)
\State \(\quad\quad \var{load}\gets\var{load}\)
\State \(\quad\quad \var{service\_time}\gets0\)
\State \(\quad\quad \var{departure\_time}\gets0\)
\State \(\quad\quad \var{q\_length\_at\_arrival}\gets0\)
\State \(\quad\quad \var{q\_length\_at\_departure}\gets0\)
\State \(\quad\quad \var{free\_servers}\gets0\)
\State \(\quad\quad \var{server}\gets\cn{None}\)
\State \(\quad\) \textbf{properties:}
\State \(\quad\quad \var{sojourn\_time}\gets\var{departure\_time}-\var{arrival\_time}\)
\State \(\quad\quad \var{waiting\_time}\gets\var{sojourn\_time}-\var{service\_time}\)
\State \(\quad\) \textbf{methods:}
\State \(\quad\quad \pr{Earlier?}\gets\lambdafun{\var{other}}{\var{arrival\_time}<\var{other}.\var{arrival\_time}}\)
\State \(\quad\quad \pr{Smaller?}\gets\lambdafun{\var{other}}{\var{load}<\var{other}.\var{load}}\)
\end{algorithmic}
\end{algorithm}
Python code
@dataclass
class Job:
id: int
arrival_time: float
load: float
service_time: float = 0
departure_time: float = 0
q_length_at_arrival: int = 0
q_length_at_departure: int = 0
free_servers: int = 0
server: Server = None
@property
def sojourn_time(self):
return self.departure_time - self.arrival_time
@property
def waiting_time(self):
return self.sojourn_time - self.service_time
def earlier(self, other):
return self.arrival_time < other.arrival_time
def smaller(self, other):
return self.load < other.load
R code
Job <- setRefClass("Job",
fields = list(
id = "numeric", arrival_time = "numeric", load = "numeric",
service_time = "numeric", departure_time = "numeric",
q_length_at_arrival = "numeric", q_length_at_departure = "numeric",
free_servers = "numeric", server = "ANY",
sojourn_time = function() departure_time - arrival_time,
waiting_time = function() sojourn_time - service_time
),
methods = list(
initialize = function(id, arrival_time, load) {
callSuper(id = id, arrival_time = arrival_time, load = load,
service_time = 0, departure_time = 0,
q_length_at_arrival = 0, q_length_at_departure = 0,
free_servers = 0, server = NULL)
},
earlier = function(other) arrival_time < other$arrival_time,
smaller = function(other) load < other$load
)
)
The \(\cl{Queue}\) class uses a heap to store jobs and pop jobs according to comparison function \(\pr{LessThan?}.\) If \(\pr{LessThan?}(x,y)\) is true, job \(x\) has priority over job \(y,\) in which case job \(x\) will be popped from the heap2Hence from the queue before job \(y..\)
\begin{algorithm}
\caption{A queue of waiting jobs with a supplied comparison function.}
\begin{algorithmic}[1]
\State \textbf{Input:} A comparison function \(\pr{LessThan?}\) on pairs of jobs.
\State \textbf{Output:} An empty queue ordered by the supplied comparison.
\State \textbf{class} \(\cl{Queue}\rb{\pr{LessThan?}}\)
\State \(\quad\) \textbf{instance variables:}
\State \(\quad\quad \var{heap}\gets\cl{Heap}\rb{\pr{LessThan?}}\)
\State \(\quad\) \textbf{methods:}
\State \(\quad\quad \pr{Push}\gets\var{heap}.\pr{Push}\)
\State \(\quad\quad \pr{Pop}\gets\var{heap}.\pr{Pop}\)
\State \(\quad\quad \pr{Length}\gets\lambdafun{()}{\var{heap}.\var{length}}\)
\State \(\quad\quad \pr{Empty?}\gets\var{heap}.\pr{Empty?}\)
\end{algorithmic}
\end{algorithm}
Python code
class Queue:
def __init__(self, less_than):
self.heap = Heap(less_than)
def push(self, job):
self.heap.push(job)
def pop(self):
return self.heap.pop()
def length(self):
return self.heap.length
def is_empty(self):
return self.heap.is_empty()
R code
Queue <- function(less_than) {
heap <- Heap$new(less_than)
list(push = heap$push, pop = heap$pop,
length = function() heap$length, is_empty = heap$is_empty)
}
A \(\cl{FIFOQueue}\) pops in order of arrival, hence it uses \(\cl{Job}.\pr{Earlier?}\) to select the next job from the queue.
\begin{algorithm}
\caption{A queue that serves the earliest arrival first.}
\begin{algorithmic}[1]
\State \textbf{Input:} None.
\State \textbf{Output:} An empty FIFO queue.
\Function{FIFOQueue}{}
\Return \(\cl{Queue}\rb{\lambdafun{(x,\,y)}{x.\pr{Earlier?}\rb{y}}}\)
\EndFunction
\end{algorithmic}
\end{algorithm}
Python code
def FIFOQueue():
return Queue(lambda x, y: x.earlier(y))
R code
FIFOQueue <- function() Queue(function(x, y) x$earlier(y))
A \(\cl{LIFOQueue}\) pops in reversed order of arrival, hence it reverses the order in \(\cl{Job}.\pr{Earlier?}\) to pop the next job from the queue.
\begin{algorithm}
\caption{A queue that serves the latest arrival first.}
\begin{algorithmic}[1]
\State \textbf{Input:} None.
\State \textbf{Output:} An empty LIFO queue.
\Function{LIFOQueue}{}
\Return \(\cl{Queue}\rb{\lambdafun{(x,\,y)}{y.\pr{Earlier?}\rb{x}}}\)
\EndFunction
\end{algorithmic}
\end{algorithm}
Python code
def LIFOQueue():
return Queue(lambda x, y: y.earlier(x))
R code
LIFOQueue <- function() Queue(function(x, y) y$earlier(x))
The \(\cl{SPTFQueue}\) implements shortest processing time first, which means that the smallest job gets priority.
\begin{algorithm}
\caption{A shortest-processing-time-first queue ordered by job load.}
\begin{algorithmic}[1]
\State \textbf{Input:} None.
\State \textbf{Output:} An empty SPTF queue.
\Function{SPTFQueue}{}
\Return \(\cl{Queue}\rb{\lambdafun{(x,\,y)}{x.\pr{Smaller?}\rb{y}}}\)
\EndFunction
\end{algorithmic}
\end{algorithm}
Python code
def SPTFQueue():
return Queue(lambda x, y: x.smaller(y))
R code
SPTFQueue <- function() Queue(function(x, y) x$smaller(y))
An \(\cl{Event}\) contains a time and a job and an event type. The \(\cl{Event}.\pr{Earlier?}\) method specifies how to order events.3Clearly, this must be by time.
\begin{algorithm}
\caption{An event with a time, a job, and a type.}
\begin{algorithmic}[1]
\State \textbf{Input:} Event time, job, and type (\(\cn{Arrival}\) or \(\cn{Departure}\)).
\State \textbf{Output:} An event.
\State \textbf{class} \(\cl{Event}\rb{\var{time},\,\var{job},\,\var{type}}\)
\State \(\quad\) \textbf{instance variables:}
\State \(\quad\quad \var{time}\gets\var{time}\)
\State \(\quad\quad \var{job}\gets\var{job}\)
\State \(\quad\quad \var{type}\gets\var{type}\)
\State \(\quad\) \textbf{methods:}
\State \(\quad\quad \pr{Earlier?}\gets\lambdafun{\var{other}}{\var{time}<\var{other}.\var{time}}\)
\end{algorithmic}
\end{algorithm}
Python code
ARRIVAL, DEPARTURE = "Arrival", "Departure"
@dataclass
class Event:
time: float
job: Job
type: str
def earlier(self, other):
return self.time < other.time
R code
Event <- function(time, job, type) {
list(time = time, job = job, type = type,
earlier = function(other) time < other$time)
}
The constructors \(\pr{ArrivalEvent}\) and \(\pr{DepartureEvent}\) set the type to \(\cn{Arrival}\) and \(\cn{Departure},\) respectively, to enable us to distinguish these two types of event.
\begin{algorithm}
\caption{Construct an arrival event.}
\begin{algorithmic}[1]
\State \textbf{Input:} The time a job enters the system and the job itself.
\State \textbf{Output:} An arrival event.
\Function{ArrivalEvent}{\(\var{time},\,\var{job}\)}
\Return \(\cl{Event}\rb{\var{time},\,\var{job},\,\cn{Arrival}}\)
\EndFunction
\end{algorithmic}
\end{algorithm}
Python code
def ArrivalEvent(time, job):
return Event(time, job, ARRIVAL)
R code
ArrivalEvent <- function(time, job) Event(time, job, "Arrival")
\begin{algorithm}
\caption{Construct a departure event.}
\begin{algorithmic}[1]
\State \textbf{Input:} The time a job finishes service and the job itself.
\State \textbf{Output:} A departure event.
\Function{DepartureEvent}{\(\var{time},\,\var{job}\)}
\Return \(\cl{Event}\rb{\var{time},\,\var{job},\,\cn{Departure}}\)
\EndFunction
\end{algorithmic}
\end{algorithm}
Python code
def DepartureEvent(time, job):
return Event(time, job, DEPARTURE)
R code
DepartureEvent <- function(time, job) Event(time, job, "Departure")
The \(\cl{Events}\) class is a heap queue and keeps the events chronologically sorted.4Once you understand that the \(\cl{Events}\) class offers the functionality to remove and insert events arbitrarily but still pop them sorted in time, you understand the core of discrete-event simulation.
\begin{algorithm}
\caption{Create the event calendar.}
\begin{algorithmic}[1]
\State \textbf{Input:} None.
\State \textbf{Output:} An empty event calendar, ordered earliest time first.
\State \textbf{class} \(\cl{Events}\rb{}\)
\State \(\quad\) \textbf{instance variables:}
\State \(\quad\quad \var{heap}\gets\cl{Heap}\rb{\lambdafun{(x,\,y)}{x.\pr{Earlier?}\rb{y}}}\)
\State \(\quad\) \textbf{methods:}
\State \(\quad\quad \pr{Push}\gets\var{heap}.\pr{Push}\)
\State \(\quad\quad \pr{Pop}\gets\var{heap}.\pr{Pop}\)
\State \(\quad\quad \pr{Empty?}\gets\var{heap}.\pr{Empty?}\)
\end{algorithmic}
\end{algorithm}
Python code
class Events:
def __init__(self):
self.heap = Heap(lambda x, y: x.earlier(y))
def push(self, event):
self.heap.push(event)
def pop(self):
return self.heap.pop()
def is_empty(self):
return self.heap.is_empty()
R code
Events <- function() {
heap <- Heap$new(function(x, y) x$earlier(y))
list(push = heap$push, pop = heap$pop, is_empty = heap$is_empty)
}
The \(\cl{Statistics}\) class collects all jobs after departing the server for statistical analysis. All performance measures are computed with the same pattern: they average over a property of the jobs. The \(\cl{Statistics}.\pr{Mean}\) method implements this common pattern.
\begin{algorithm}
\caption{Collect jobs at departure and compute sample means.}
\begin{algorithmic}[1]
\State \textbf{Input:} None.
\State \textbf{Output:} Statistics for completed jobs. Means are defined after the first departure.
\State \textbf{class} \(\cl{Statistics}\rb{}\)
\State \(\quad\) \textbf{instance variables:}
\State \(\quad\quad \var{jobs}\gets\qb{}\)
\State \(\quad\) \textbf{methods:}
\State \(\quad\quad \pr{Push}\gets\lambdafun{\var{job}}{\pr{Append}\rb{\var{jobs},\,\var{job}}}\)
\State \(\quad\quad \pr{NumJobs}\gets\lambdafun{()}{\pr{Length}\rb{\var{jobs}}}\)
\State \(\quad\quad \pr{Mean}\gets\lambdafun{f}{\pr{Average}\rb{\pr{Apply}\rb{\var{jobs},\,f}}}\)
\State \(\quad\quad \pr{MeanWaitingTime}\gets\lambdafun{()}{\pr{Mean}\rb{\lambdafun{j}{j.\var{waiting\_time}}}}\)
\State \(\quad\quad \pr{MeanSojournTime}\gets\lambdafun{()}{\pr{Mean}\rb{\lambdafun{j}{j.\var{sojourn\_time}}}}\)
\State \(\quad\quad \pr{MeanQueueLength}\gets\lambdafun{()}{\pr{Mean}\rb{\lambdafun{j}{j.\var{q\_length\_at\_arrival}}}}\)
\State \(\quad\quad \pr{MeanServersFree}\gets\lambdafun{()}{\pr{Mean}\rb{\lambdafun{j}{j.\var{free\_servers}}}}\)
\end{algorithmic}
\end{algorithm}
Python code
class Statistics:
def __init__(self):
self.jobs = []
def push(self, job):
self.jobs.append(job)
def num_jobs(self):
return len(self.jobs)
def mean(self, f):
return Average(Apply(self.jobs, f))
def mean_waiting_time(self):
return self.mean(lambda j: j.waiting_time)
def mean_sojourn_time(self):
return self.mean(lambda j: j.sojourn_time)
def mean_queue_length(self):
return self.mean(lambda j: j.q_length_at_arrival)
def mean_servers_free(self):
return self.mean(lambda j: j.free_servers)
R code
Statistics <- setRefClass("Statistics",
fields = list(jobs = "list"),
methods = list(
push = function(job) {
jobs[[length(jobs) + 1]] <<- job
},
num_jobs = function() length(jobs),
mean = function(f) Average(Apply(jobs, f)),
mean_waiting_time = function() mean(function(j) j$waiting_time),
mean_sojourn_time = function() mean(function(j) j$sojourn_time),
mean_queue_length = function() mean(function(j) j$q_length_at_arrival),
mean_servers_free = function() mean(function(j) j$free_servers)
)
)
The \(\cl{Simulation}\) is the final class 5Study it carefully. and it stores the events, queue, statistics, and servers. The attribute \(\var{now}\) points to the current simulation time. When starting the simulation, we provide a list of jobs to the simulator, which pushes an \(\pr{ArrivalEvent}\) for each new job onto the event stack.
\begin{algorithm}
\caption{The discrete-event simulation class.}
\begin{algorithmic}[1]
\State \textbf{Input:} None.
\State \textbf{Output:} A simulation with an empty event calendar and a FIFO queue.
\State \textbf{class} \(\cl{Simulation}\rb{}\)
\State \(\quad\) \textbf{instance variables:}
\State \(\quad\quad \var{events}\gets\cl{Events}\rb{}\)
\State \(\quad\quad \var{queue}\gets\pr{FIFOQueue}\rb{}\)
\State \(\quad\quad \var{stats}\gets\cl{Statistics}\rb{}\)
\State \(\quad\quad \var{servers}\gets\cl{Servers}\rb{}\)
\State \(\quad\quad \var{now}\gets0\)
\State \(\quad\) \textbf{methods:}
\State \(\quad\quad \pr{ScheduleArrivals}\rb{\var{jobs}}\)
\State \(\quad\quad \pr{InitializeServers}\rb{\var{server\_rates}}\)
\State \(\quad\quad \pr{ServeJob}\rb{\var{job},\,\var{server\_pool}=\var{servers}}\)
\State \(\quad\quad \pr{HandleArrival}\rb{\var{job}}\)
\State \(\quad\quad \pr{HandleDeparture}\rb{\var{job}}\)
\State \(\quad\quad \pr{Run}\rb{}\)
\end{algorithmic}
\end{algorithm}
Python code
class Simulation:
def __init__(self):
self.events = Events()
self.queue = FIFOQueue()
self.stats = Statistics()
self.servers = Servers()
self.now = 0
R code
Simulation <- setRefClass("Simulation",
fields = list(events = "ANY", queue = "ANY", stats = "ANY",
servers = "ANY", now = "numeric"),
methods = list(
initialize = function(...) {
callSuper(events = Events(), queue = FIFOQueue(),
stats = Statistics$new(), servers = Servers(), now = 0,
...)
}
)
)
Scheduling the arriving jobs is now just a matter of pushing the jobs are arrival events on the event heap.
\begin{algorithm}
\caption{Schedule the arrivals.}
\begin{algorithmic}[1]
\State \textbf{Input:} The jobs to simulate.
\State \textbf{Output:} None.
\Function{Simulation.ScheduleArrivals}{\(\var{jobs}\)}
\For{\(\var{job}\in \var{jobs}\)}
\State \(\var{events}.\pr{Push}\rb{\pr{ArrivalEvent}\rb{\var{job}.\var{arrival\_time},\,\var{job}}}\)
\EndFor
\EndFunction
\end{algorithmic}
\end{algorithm}
Python code
def schedule_arrivals(self, jobs):
for job in jobs:
self.events.push(ArrivalEvent(job.arrival_time, job))
R code
Simulation$methods(schedule_arrivals = function(jobs) {
for (job in jobs) {
events$push(ArrivalEvent(job$arrival_time, job))
}
})
To initialize the servers, we instantiate for each service rate a server and push each server on the server stack to become available for handling jobs.
\begin{algorithm}
\caption{Initialize the server pool.}
\begin{algorithmic}[1]
\State \textbf{Input:} The list of server rates.
\State \textbf{Output:} None.
\Function{Simulation.InitializeServers}{\(\var{server\_rates}\)}
\For{\(i=1,\ldots,\pr{Length}\rb{\var{server\_rates}}\)}
\State \(\var{servers}.\pr{Push}\rb{\cl{Server}\rb{i,\,\var{server\_rates}_i}}\)
\EndFor
\EndFunction
\end{algorithmic}
\end{algorithm}
Python code
def initialize_servers(self, server_rates):
for i in range(1, len(server_rates) + 1):
self.servers.push(Server(i, server_rates[i - 1]))
R code
Simulation$methods(initialize_servers = function(server_rates) {
for (i in seq_along(server_rates)) {
servers$push(Server$new(id = i, rate = server_rates[i]))
}
})
When a job service starts, the \(\cl{Simulation}.\pr{ServeJob}\) method asks for a free server from the server pool6At a later stage, we might have different server pools. We therefore add this as an argument. and assigns it to the job. Then it computes the job service time and departure time, and pushes a \(\pr{DepartureEvent}\) to the event calendar to inform the simulator that a job will leave at that time.
\begin{algorithm}
\caption{Start service for a job.}
\begin{algorithmic}[1]
\State \textbf{Input:} A job and a pool with a free server. The default pool is \(\var{servers}.\)
\State \textbf{Output:} None.
\Function{Simulation.ServeJob}{\(\var{job},\,\var{server\_pool}=\var{servers}\)}
\State \(\var{server}\gets \var{server\_pool}.\pr{Pop}\rb{}\)
\State \(\var{job}.\var{free\_servers}\gets \var{server\_pool}.\pr{NumFree}\rb{}\)
\State \(\var{job}.\var{server}\gets \var{server}\)
\State \(\var{job}.\var{service\_time}\gets \var{job}.\var{load}/\var{server}.\var{rate}\)
\State \(\var{job}.\var{departure\_time}\gets \var{now}+\var{job}.\var{service\_time}\)
\State \(\var{event}\gets \pr{DepartureEvent}\rb{\var{job}.\var{departure\_time},\var{job}}\)
\State \(\var{events}.\pr{Push}\rb{\var{event}}\)
\EndFunction
\end{algorithmic}
\end{algorithm}
Python code
def serve_job(self, job, server_pool=None):
if server_pool is None: # The default pool is servers.
server_pool = self.servers
server = server_pool.pop()
job.free_servers = server_pool.num_free()
job.server = server
job.service_time = job.load / server.rate
job.departure_time = self.now + job.service_time
event = DepartureEvent(job.departure_time, job)
self.events.push(event)
R code
Simulation$methods(serve_job = function(job, server_pool = servers) {
server <- server_pool$pop()
job$free_servers <- server_pool$num_free()
job$server <- server
job$service_time <- job$load / server$rate
job$departure_time <- now + job$service_time
event <- DepartureEvent(job$departure_time, job)
events$push(event)
})
In case an event is an \(\cn{Arrival},\) service of the job can start if a server is free; otherwise, the job is queued.
\begin{algorithm}
\caption{Handle an arrival.}
\begin{algorithmic}[1]
\State \textbf{Input:} The arriving job.
\State \textbf{Output:} None.
\Function{Simulation.HandleArrival}{\(\var{job}\)}
\State \(\var{job}.\var{q\_length\_at\_arrival}\gets \var{queue}.\pr{Length}\rb{}\)
\If{\(\var{servers}.\pr{ServerFree?}\rb{}\)}
\State \(\pr{ServeJob}\rb{\var{job},\,\var{servers}}\)
\Else
\State \(\var{queue}.\pr{Push}\rb{\var{job}}\)
\EndIf
\EndFunction
\end{algorithmic}
\end{algorithm}
Python code
def handle_arrival(self, job):
job.q_length_at_arrival = self.queue.length()
if self.servers.server_free():
self.serve_job(job, self.servers)
else:
self.queue.push(job)
R code
Simulation$methods(handle_arrival = function(job) {
job$q_length_at_arrival <- queue$length()
if (servers$server_free()) {
serve_job(job, servers)
} else {
queue$push(job)
}
})
When an event is a \(\cn{Departure},\) the server assigned to the job becomes free and is returned to the server pool so that it becomes available for service again. If there are still jobs in the queue, a new job is taken into service. The \(\var{stats}\) collects the job for the analysis once the simulation finishes.
\begin{algorithm}
\caption{Handle a departure.}
\begin{algorithmic}[1]
\State \textbf{Input:} The departing job.
\State \textbf{Output:} None.
\Function{Simulation.HandleDeparture}{\(\var{job}\)}
\State \(\var{servers}.\pr{Push}\rb{\var{job}.\var{server}}\)
\If{\(\neg \var{queue}.\pr{Empty?}\rb{}\)}
\State \(\pr{ServeJob}\rb{\var{queue}.\pr{Pop}\rb{},\,\var{servers}}\)
\EndIf
\State \(\var{job}.\var{q\_length\_at\_departure}\gets \var{queue}.\pr{Length}\rb{}\)
\State \(\var{stats}.\pr{Push}\rb{\var{job}}\)
\EndFunction
\end{algorithmic}
\end{algorithm}
Python code
def handle_departure(self, job):
self.servers.push(job.server)
if not self.queue.is_empty():
self.serve_job(self.queue.pop(), self.servers)
job.q_length_at_departure = self.queue.length()
self.stats.push(job)
R code
Simulation$methods(handle_departure = function(job) {
servers$push(job$server)
if (!queue$is_empty()) {
serve_job(queue$pop(), servers)
}
job$q_length_at_departure <- queue$length()
stats$push(job)
})
The \(\cl{Simulation}.\pr{Run}\) method checks whether events remain; if so, it pops the next event from the event stack. It then updates \(\var{now}\) to the event time. If the event type is \(\cn{Arrival},\) it passes the job associated to the event to \(\cl{Simulation}.\pr{HandleArrival}\) to take over the details what needs to be done. As there are just two event types, if the event is not an \(\cn{Arrival}\) it must be a \(\cn{Departure}.\)7When there are more types of event, this list is longer.
\begin{algorithm}
\caption{Run the event loop.}
\begin{algorithmic}[1]
\State \textbf{Input:} The initialized simulation.
\State \textbf{Output:} None.
\Function{Simulation.Run}{}
\While{\(\neg \var{events}.\pr{Empty?}\rb{}\)}
\State \(\var{event}\gets \var{events}.\pr{Pop}\rb{}\)
\State \(\var{now}\gets\var{event}.\var{time}\)
\If{\(\var{event}.\var{type}==\cn{Arrival}\)}
\State \(\pr{HandleArrival}\rb{\var{event}.\var{job}}\)
\Else
\State \(\pr{HandleDeparture}\rb{\var{event}.\var{job}}\)
\EndIf
\EndWhile
\EndFunction
\end{algorithmic}
\end{algorithm}
Python code
def run(self):
while not self.events.is_empty():
event = self.events.pop()
self.now = event.time
if event.type == ARRIVAL:
self.handle_arrival(event.job)
else:
self.handle_departure(event.job)
R code
Simulation$methods(run = function() {
while (!events$is_empty()) {
event <- events$pop()
now <<- event$time
if (event$type == "Arrival") {
handle_arrival(event$job)
} else {
handle_departure(event$job)
}
}
})
Testing the code comes next. In Section 5.1, we derive exact results for the expected waiting time of the \(M/M/c\) queue, so this model provides a good test.
The above discrete event simulation implements a \(G/G/c\) server whose servers are allowed to have different speeds. We generate the interarrival times and job loads with Alg. 3.3.2. This is how the code is organized to run.
\begin{algorithm}
\caption{Simulate a G/G/c queue from interarrival times and job loads.}
\begin{algorithmic}[1]
\State \(\lambda,\,\mu,\,c\gets3,\,4,\,2\)
\State \(n\gets10^4\)
\State \(X\gets\pr{GenerateExponentialRVs}\rb{\lambda,\,n}\)
\State \(S\gets\pr{GenerateExponentialRVs}\rb{\mu,\,n}\)
\State \(A\gets\pr{CumSum}\rb{X}\) \Comment{Arrival times}
\State \(\var{jobs}\gets\qb{\cl{Job}\rb{i,\,A_i,\,S_i}:i=1,\ldots,n}\)
\State \(\var{sim}\gets \cl{Simulation}\rb{}\)
\State \(\var{sim}.\pr{ScheduleArrivals}\rb{\var{jobs}}\)
\State \(\var{sim}.\pr{InitializeServers}\rb{\var{server\_rates}}\)
\State \(\var{sim}.\pr{Run}\rb{}\)
\State \(\pr{Print}\rb{\var{sim}.\pr{MeanWaitingTime}\rb{}}\)
\State \(\pr{Print}\rb{\var{sim}.\pr{MeanSojournTime}\rb{}}\)
\State \(\pr{Print}\rb{\var{sim}.\pr{MeanQueueLength}\rb{}}\)
\end{algorithmic}
\end{algorithm}
Python code
import numpy as np
rng = np.random.default_rng(3)
def GenerateExponentialRVs(r, n):
# rng.exponential replaces the loop that computes -log(U)/r.
return rng.exponential(scale=1 / r, size=n)
labda, mu, c = 3, 4, 2
n = 10_000
X = GenerateExponentialRVs(labda, n)
S = GenerateExponentialRVs(mu, n)
A = CumSum(X) # Arrival times
jobs = [Job(i, A[i - 1], S[i - 1]) for i in range(1, n + 1)]
sim = Simulation()
sim.schedule_arrivals(jobs)
sim.initialize_servers(server_rates=[1] * c)
sim.run()
print(f"W: {sim.stats.mean_waiting_time():.4f}")
print(f"J: {sim.stats.mean_sojourn_time():.4f}")
print(f"Q: {sim.stats.mean_queue_length():.4f}")
R code
set.seed(3)
GenerateExponentialRVs <- function(r, n) {
# rexp replaces the loop that computes -log(U)/r.
rexp(n, rate = r)
}
lambda <- 3
mu <- 4
c <- 2
n <- 10000
X <- GenerateExponentialRVs(lambda, n)
S <- GenerateExponentialRVs(mu, n)
A <- CumSum(X) # Arrival times
jobs <- lapply(seq_len(n), function(i) Job$new(i, A[[i]], S[[i]]))
sim <- Simulation$new()
sim$schedule_arrivals(jobs)
sim$initialize_servers(rep(1, c))
sim$run()
print(c(W = sim$stats$mean_waiting_time(), J = sim$stats$mean_sojourn_time(),
Q = sim$stats$mean_queue_length()))
The finite-capacity benchmark in Alg. 3.5.21 uses the \(\cl{MnMn1K}\) class. We need to set the system capacity \(K\) to some level to terminate the recursion.8See the details in In Section 5.1. By setting \(K\) to a very large value, it will not affect the performance measures.
\begin{algorithm}
\caption{Compute the finite-capacity benchmark means.}
\begin{algorithmic}[1]
\State \(K\gets100\)
\State \(\lambda^+\gets\lambdafun{i}{\lambda\cdot\1{i<K}}\)
\State \(\var{mm}\gets\cl{MnMn1K}\rb{\lambda^+,\lambdafun{i}{\mu\cdot\Min{i,c}},\,K,\,c}\)
\State \(\pr{Print}\rb{\var{mm}.\pr{MeanWaitingTime}\rb{}}\)
\State \(\pr{Print}\rb{\var{mm}.\pr{MeanSojournTime}\rb{}}\)
\State \(\pr{Print}\rb{\var{mm}.\pr{MeanQueueLength}\rb{}}\)
\end{algorithmic}
\end{algorithm}
Python code
class MnMn1K:
"""Birth-death queue on the states 0, ..., K with c servers."""
def __init__(self, arrival, service, K, c):
p = [1.0]
for i in range(1, K + 1):
p.append(p[-1] * arrival(i - 1) / service(i))
self.p = [x / sum(p) for x in p]
self.c = c
self.accepted = sum(arrival(i) * self.p[i] for i in range(K + 1))
def mean_queue_length(self):
return sum(max(i - self.c, 0) * p_i for i, p_i in enumerate(self.p))
def mean_number_in_system(self):
return sum(i * p_i for i, p_i in enumerate(self.p))
def mean_waiting_time(self): # Little's law for the queue
return self.mean_queue_length() / self.accepted
def mean_sojourn_time(self): # Little's law for the system
return self.mean_number_in_system() / self.accepted
K = 100
mm = MnMn1K(lambda i: labda * (i < K), lambda i: mu * min(i, c), K, c)
print(f"W: {mm.mean_waiting_time():.4f}")
print(f"J: {mm.mean_sojourn_time():.4f}")
print(f"Q: {mm.mean_queue_length():.4f}")
R code
# Birth-death queue on the states 0, ..., K with c servers.
MnMn1K <- function(arrival, service, K, c) {
p <- numeric(K + 1) # p[i + 1] = P(i jobs in the system)
p[1] <- 1
for (i in seq_len(K)) {
p[i + 1] <- p[i] * arrival(i - 1) / service(i)
}
p <- p / sum(p)
states <- 0:K
accepted <- sum(sapply(states, arrival) * p)
Lq <- sum(pmax(states - c, 0) * p)
L <- sum(states * p)
list(mean_queue_length = function() Lq,
mean_waiting_time = function() Lq / accepted, # Little's law
mean_sojourn_time = function() L / accepted)
}
K <- 100
mm <- MnMn1K(function(i) lambda * (i < K), function(i) mu * min(i, c), K, c)
print(c(W = mm$mean_waiting_time(), J = mm$mean_sojourn_time(),
Q = mm$mean_queue_length()))
When we run the simulation for \(10^4\) jobs, the results are reasonable, but the differences in \(\E \W\) and \(\E \Lq\) are still quite large. If we repeat the experiment, but now with \(10^6\) jobs. The results show a remarkable improvement.9This brings up a philosophical problem. If we need to simulate with one million jobs to see the time-average statistics appear, what is the significance of such time-averages? In how many practical situations will we see such numbers of jobs?
| Measure | \(10^4\) jobs | \(10^6\) jobs | Theory |
|---|---|---|---|
| Mean waiting time \(\E \W\) | 0.0441 | 0.0410 | 0.0409 |
| Mean sojourn time \(\E \J\) | 0.2952 | 0.2915 | 0.2909 |
| Mean queue length \(\E \Lq\) | 0.1467 | 0.1225 | 0.1227 |
Python code
def run_mmc(num, labda=3, mu=4, server_rates=[1, 1]):
global rng
rng = np.random.default_rng(3) # The same random numbers in each run.
X = GenerateExponentialRVs(labda, num)
S = GenerateExponentialRVs(mu, num)
A = CumSum(X)
jobs = [Job(i, A[i - 1], S[i - 1]) for i in range(1, num + 1)]
sim = Simulation()
sim.schedule_arrivals(jobs)
sim.initialize_servers(server_rates)
sim.run()
c, K = len(server_rates), 100
mm = MnMn1K(lambda i: labda * (i < K), lambda i: mu * min(i, c), K, c)
print(f"W: {sim.stats.mean_waiting_time():0.4f}, {mm.mean_waiting_time():.4f}")
print(f"J: {sim.stats.mean_sojourn_time():0.4f}, {mm.mean_sojourn_time():.4f}")
print(f"Q: {sim.stats.mean_queue_length():0.4f}, {mm.mean_queue_length():.4f}")
In the next section we demonstrate with a few examples how flexible this simulation environment actually is.
TF 1.
Claim: This part of the \(\cl{Simulation}\) class handles arrivals correctly.
\begin{algorithm}
\caption{Arrival handler in the claim.}
\begin{algorithmic}[1]
\State \textbf{Input:} An arriving job.
\State \textbf{Output:} None.
\Function{Simulation.HandleArrival}{\(\var{job}\)}
\State \(\var{job}.\var{q\_length\_at\_arrival}\gets \var{queue}.\pr{Length}\rb{}\)
\If{\(\var{servers}.\pr{ServerFree?}\rb{}\)}
\State \(\var{queue}.\pr{Push}\rb{\var{job}}\)
\Else
\State \(\pr{ServeJob}\rb{\var{job}}\)
\EndIf
\EndFunction
\end{algorithmic}
\end{algorithm}
Solution
Did you actually try? Write your solution down first for comparison.
Show the solution
False. Compare with the correct code.
TF 2.
Claim: This part of the \(\cl{Simulation}\) class handles the serving of jobs correctly.
\begin{algorithm}
\caption{Service handler in the claim.}
\begin{algorithmic}[1]
\State \textbf{Input:} A job to serve.
\State \textbf{Output:} None.
\Function{Simulation.ServeJob}{\(\var{job}\)}
\State \(\var{server}\gets \var{servers}.\pr{Pop}\rb{}\)
\State \(\var{job}.\var{server}\gets \var{server}\)
\State \(\var{job}.\var{service\_time}\gets \var{job}.\var{load}/\var{server}.\var{rate}\)
\State \(\var{job}.\var{departure\_time}\gets \var{now}+\var{job}.\var{service\_time}\)
\State \(\var{job}.\var{free\_servers}\gets \var{servers}.\pr{NumFree}\rb{}\)
\State \(\var{event}\gets \pr{DepartureEvent}\rb{\var{job}.\var{departure\_time},\var{job}}\)
\State \(\var{events}.\pr{Push}\rb{\var{event}}\)
\EndFunction
\end{algorithmic}
\end{algorithm}
Solution
Did you actually try? Write your solution down first for comparison.
Show the solution
True.
An interesting variation. Claim: the job records the number of free servers as seen just prior to arrival. This claim is false because the code first pops a server from the pool of free servers, and then sets the \(\var{job}.\var{free\_servers}\) attribute.
TF 3.
Claim: This part of the \(\cl{Simulation}\) class handles departures correctly.
\begin{algorithm}
\caption{Departure handler in the claim.}
\begin{algorithmic}[1]
\State \textbf{Input:} A departing job.
\State \textbf{Output:} None.
\Function{Simulation.HandleDeparture}{\(\var{job}\)}
\State \(\var{servers}.\pr{Push}\rb{\var{job}.\var{server}}\)
\State \(\var{stats}.\pr{Push}\rb{\var{job}}\)
\If{\(\neg \var{queue}.\pr{Empty?}\rb{}\)}
\State \(\pr{ServeJob}\rb{\var{queue}.\pr{Pop}\rb{}}\)
\EndIf
\State \(\var{job}.\var{q\_length\_at\_departure}\gets \var{queue}.\pr{Length}\rb{}\)
\EndFunction
\end{algorithmic}
\end{algorithm}
Solution
Did you actually try? Write your solution down first for comparison.
Show the solution
True. The server is returned before \(\pr{ServeJob}\) pops a server, so a free server is available for the next job. The queue length is recorded after that job has left the queue, so it counts the jobs left behind in the queue.
TF 4.
Claim: In discrete-event simulation, time advances by a fixed increment each step.
Solution
Did you actually try? Write your solution down first for comparison.
Show the solution
False. In discrete-event simulation, time jumps from one event to the next. The time increments are variable and determined by the event schedule.
TF 5.
Claim: In a discrete-event simulation framework based on object-oriented programming, subclassing allows us to reuse the event loop and only override specific behavior such as arrival handling.
Solution
Did you actually try? Write your solution down first for comparison.
Show the solution
True. The base class implements the general event loop and common logic, while subclasses override methods like \(\cl{Simulation}.\pr{HandleArrival}\) to model specific queueing policies.
Exercise 6.
Consider a multi-server queue with \(m\) servers. Suppose that at some time \(t\) it happens that \(\As(t) - D(t) < m\) but \(A(t) - D(t) > m.\) How can this occur?
Solution
Did you actually try? Write your solution down first for comparison.
Show the solution
In this case, there are servers idling while there are still customers in queue. If such events occur, the system is not work-conserving.