3.6 Optional: Discrete-Event Simulations: Examples

The discrete-event simulator for the \(G/G/c\) queue developed in the previous section can be easily adapted to other queueing systems. We first analyze the effects of several server speeds for the \(G/G/c\) queue. Next, we focus on a policy that controls the server based on the number of jobs in the system. Our final example is more extensive: we analyze whether servers dedicated to business customers in an airport check-in process should be shared with economy class customers. This would correspond to a part of a business consultancy project.

Consider a station with three servers with rates \(r_{1} = 1,\) \(r_{2} = 0.1,\) and \(r_{3} = 0.01,\) respectively, and such that whenever multiple servers are free, the fastest available one is chosen. If queue sizes are very long, then it could help to use the extra capacity offered by the two slower servers. However, when the load is small and a job ends up at the slowest server, its sojourn time is large1Because its service time is large.. Should we actually use this extra capacity? To obtain insight into the value of the extra capacity, we use the simulation environment of Section 3.5 to compare this system with an \(M/M/1\) queue with service rate \(1.\)2In other words, a queue with no extra capacity.

Most examples start with a list of jobs with exponential interarrival times and loads.

\begin{algorithm}
\caption{Make jobs with exponential interarrival times and loads.}
\begin{algorithmic}[1]
\State \textbf{Input:} Arrival rate \(\lambda,\) service rate \(\mu,\) and number of jobs \(n.\)
\State \textbf{Output:} A list of \(n\) jobs.
\Function{MakeJobs}{\(\lambda,\,\mu,\,n\)}
    \State \(X\gets\pr{GenerateExponentialRVs}\rb{\lambda,\,n}\)
    \State \(S\gets\pr{GenerateExponentialRVs}\rb{\mu,\,n}\)
    \State \(A\gets\pr{CumSum}\rb{X}\)
    \Return \(\qb{\cl{Job}\rb{i,\,A_i,\,S_i}:i=1,\ldots,n}\)
\EndFunction
\end{algorithmic}

\end{algorithm}
Python code
# Apply, Average, Count, Filter, Maximum and Sum are the functions of
# Algorithmic Patterns; LexLessThan is the one of the heap-queue section.
rng = np.random.default_rng(3)


def MakeJobs(labda, mu, n):
    X = GenerateExponentialRVs(labda, n)
    S = GenerateExponentialRVs(mu, n)
    A = CumSum(X)
    return [Job(i, A[i - 1], S[i - 1]) for i in range(1, n + 1)]
R code
# Apply, Average, Count, Filter, Maximum and Sum are the functions of
# Algorithmic Patterns; LexLessThan is the one of the heap-queue section.
# Jobs are reference objects, so a list of jobs shows their final state
# after the simulation.
set.seed(3)

MakeJobs <- function(lambda, mu, n) {
    X <- GenerateExponentialRVs(lambda, n)
    S <- GenerateExponentialRVs(mu, n)
    A <- CumSum(X)
    lapply(seq_len(n), function(i) Job$new(i, A[[i]], S[[i]]))
}

For the statistics, we count the server identifiers with \(\pr{Count}\) of Alg. 1.2.17.

\begin{algorithm}
\caption{Simulate a station with three servers of different speeds.}
\begin{algorithmic}[1]
\State \textbf{Input:} Arrival rate \(\lambda,\) service rate \(\mu,\) and server rates \(R.\)
\State \textbf{Output:} The simulation after all jobs have departed.
\Function{SimulateSpeeds}{\(\lambda,\,\mu,\,R\)}
    \State \(\var{sim}\gets\cl{Simulation}\rb{}\)
    \State \(\var{sim}.\pr{ScheduleArrivals}\rb{\pr{MakeJobs}\rb{\lambda,\,\mu,\,10^4}}\)
    \State \(\var{sim}.\pr{InitializeServers}\rb{R}\)
    \State \(\var{sim}.\pr{Run}\rb{}\)
    \Return \(\var{sim}\)
\EndFunction
\State \(\var{sim}\gets\pr{SimulateSpeeds}\rb{3,\,4,\,\qb{1,\,0.1,\,0.01}}\)
\State \(\pr{Print}\rb{\var{sim}.\var{stats}.\pr{MeanWaitingTime}\rb{}}\)
\State \(\pr{Print}\rb{\var{sim}.\var{stats}.\pr{MeanSojournTime}\rb{}}\)
\State \(\pr{Print}\rb{\var{sim}.\var{stats}.\pr{MeanQueueLength}\rb{}}\)
\State \(\pr{Print}\rb{\pr{Count}\rb{\pr{Apply}\rb{\var{sim}.\var{stats}.\var{jobs},\,\lambdafun{j}{j.\var{server}.\var{id}}}}}\)
\end{algorithmic}

\end{algorithm}
Python code
def SimulateSpeeds(labda, mu, R):
    sim = Simulation()
    sim.schedule_arrivals(MakeJobs(labda, mu, 10_000))
    sim.initialize_servers(R)
    sim.run()
    return sim


sim = SimulateSpeeds(3, 4, [1, 0.1, 0.01])
K = 1000  # Large enough to approximate the M/M/1 queue.
mm1 = MnMn1K(lambda i: 3 * (i < K), lambda i: 4 * min(i, 1), K, 1)
print(f"W: sim: {sim.stats.mean_waiting_time():0.2f}, M/M/1: {mm1.mean_waiting_time():0.2f}")
print(f"J: sim: {sim.stats.mean_sojourn_time():0.2f}, M/M/1: {mm1.mean_sojourn_time():0.2f}")
print(f"Q: sim: {sim.stats.mean_queue_length():0.2f}, M/M/1: {mm1.mean_queue_length():0.2f}")
print(Count(Apply(sim.stats.jobs, lambda j: j.server.id)))
R code
SimulateSpeeds <- function(lambda, mu, R) {
    sim <- Simulation$new()
    sim$schedule_arrivals(MakeJobs(lambda, mu, 10000))
    sim$initialize_servers(R)
    sim$run()
    sim
}

sim <- SimulateSpeeds(3, 4, c(1, 0.1, 0.01))
K <- 1000  # Large enough to approximate the M/M/1 queue.
mm1 <- MnMn1K(function(i) 3 * (i < K), function(i) 4 * min(i, 1), K, 1)
print(c(W = sim$stats$mean_waiting_time(), MM1 = mm1$mean_waiting_time()))
print(c(J = sim$stats$mean_sojourn_time(), MM1 = mm1$mean_sojourn_time()))
print(c(Q = sim$stats$mean_queue_length(), MM1 = mm1$mean_queue_length()))
counts <- Count(Apply(sim$stats$jobs, function(j) j$server$id))
print(setNames(unlist(Values(counts)), unlist(Keys(counts))))

Table 3.1 shows the results when \(\mu_i = 4 r_i,\) i.e., \(\mu_1=4,\) \(\mu_2=0.4\) and \(\mu_3=0.04.\) We see that the average queue length is smaller in the multi-server station than for the \(M/M/1\) queue, but the sojourn time is longer.

Table 3.1: Three servers with rates \(1,\) \(0.1\) and \(0.01\) compared to an \(M/M/1\) queue, \(\lambda=3,\) \(\mu=4.\)
Measure Simulation \(M/M/1\)
Mean waiting time \(\E \W\) 0.42 0.75
Mean sojourn time \(\E \J\) 1.24 1.00
Mean queue length \(\E \Lq\) 1.27 2.25

Table 3.2 shows that about \(154\) of the \(10000\) jobs are served by the slowest server, thereby providing the explanation.

Table 3.2: The number of jobs served by each server, \(\mu=4.\)
Server 1 2 3
Jobs served 8692 1154 154

Since the slow servers increase sojourn times, we may question whether to use them at all. Let us examine the output if the job load becomes quite a bit larger. We increase \(\E S\) from \(1/4\) to \(1/3.1,\) so \(\rho\) increases from \(3/4\) to \(3/3.1.\) That is, we call \(\pr{SimulateSpeeds}\rb{3,\,3.1,\,\qb{1,\,0.1,\,0.01}}.\)

Table 3.3 makes it clear that the extra servers do help; the expected waiting and sojourn go down as compared to the \(M/M/1\) queue, i.e., the queue without extra capacity.

Table 3.3: Three servers with rates \(1,\) \(0.1\) and \(0.01\) compared to an \(M/M/1\) queue, \(\lambda=3,\) \(\mu=3.1.\)
Measure Simulation \(M/M/1\)
Mean waiting time \(\E \W\) 1.57 9.68
Mean sojourn time \(\E \J\) 2.51 10.00
Mean queue length \(\E \Lq\) 4.57 29.03

Interestingly, Table 3.4 shows that the fraction of jobs served by the fastest server is larger than when \(\E S =1/4.\)

Table 3.4: The number of jobs served by each server, \(\mu=3.1.\)
Server 1 2 3
Jobs served 8952 948 100

In conclusion, if the load is low, it is best to use only the fastest server and let the slow servers being idle, even when there are jobs waiting.3As a consequence, service is no longer work-conserving. But when the load is high, queueing times form the larger part of the sojourn time, and it then becomes better to use the slower servers as well.

Different scheduling and priority rules are easy to implement. LIFO and SPTF are already available as \(\pr{LIFOQueue}\) and \(\pr{SPTFQueue}\) of Alg. 3.5.6 and Alg. 3.5.7, so to use one of them, we replace the FIFO queue of the simulation before we run it.

In priority queues, higher priority is better, and only when jobs have the same priority, they should be sorted according to FIFO.4A variation would be to provide jobs with due dates: the job with the smaller due date should be served first. Each job \(j\) gets an attribute \(j.\var{priority}\) when we make it; a larger value means a higher priority. We order the jobs by the pair \((-j.\var{priority},\,j.\var{arrival\_time})\) in lexicographic order, using \(\pr{LexLessThan?}\) of Alg. 3.4.4: the first element puts a higher priority first, and for equal priorities the second element puts the earlier arrival first. The function \(\pr{Key}\) of Alg. 3.6.3 maps a job \(j\) to this pair.

\begin{algorithm}
\caption{A queue that serves higher priorities first, and FIFO within a priority.}
\begin{algorithmic}[1]
\State \textbf{Input:} None.
\State \textbf{Output:} An empty priority queue.
\Function{PriorityQueue}{}
    \State \(\pr{Key}\gets\lambdafun{j}{(-j.\var{priority},\,j.\var{arrival\_time})}\)
    \Return \(\cl{Queue}\rb{\lambdafun{(x,\,y)}{\pr{LexLessThan?}\rb{\pr{Key}\rb{x},\,\pr{Key}\rb{y}}}}\)
\EndFunction
\end{algorithmic}

\end{algorithm}
Python code
def PriorityQueue():
    Key = lambda j: (-j.priority, j.arrival_time)
    return Queue(lambda x, y: LexLessThan(Key(x), Key(y)))
R code
PriorityQueue <- function() {
    Key <- function(j) list(-j$priority, j$arrival_time)
    Queue(function(x, y) LexLessThan(Key(x), Key(y)))
}

Here is how to use it in a simulation. In the simulation we give ten percent of the jobs a higher priority, and then we compare the results of the simulation to a regular \(M/M/1\) queue with the same service capacity but without job priorities. The mean waiting time per priority class follows from \(\pr{Filter}\) of Alg. 1.2.9, \(\pr{Apply}\) of Alg. 1.2.6, and \(\pr{Average}.\)

\begin{algorithm}
\caption{Simulate an \(M/M/1\) queue in which ten percent of the jobs have priority.}
\begin{algorithmic}[1]
\State \(\lambda,\,\mu,\,n\gets3,\,3.2,\,10^4\)
\State \(\var{jobs}\gets\pr{MakeJobs}\rb{\lambda,\,\mu,\,n}\)
\For{\(\var{job}\in\var{jobs}\)}
    \State \(U\gets\Unif{(0,1)}\)
    \State \(\var{job}.\var{priority}\gets\1{U\leq0.1}\)
\EndFor
\State \(\var{sim}\gets\cl{Simulation}\rb{}\)
\State \(\var{sim}.\var{queue}\gets\pr{PriorityQueue}\rb{}\)
\State \(\var{sim}.\pr{ScheduleArrivals}\rb{\var{jobs}}\)
\State \(\var{sim}.\pr{InitializeServers}\rb{\qb{1}}\)
\State \(\var{sim}.\pr{Run}\rb{}\)
\For{\(k\in\{0,\,1\}\)}
    \State \(\var{jobs}_k\gets\pr{Filter}\rb{\var{sim}.\var{stats}.\var{jobs},\,\lambdafun{j}{j.\var{priority}==k}}\)
    \State \(\pr{Print}\rb{k,\,\pr{Average}\rb{\pr{Apply}\rb{\var{jobs}_k,\,\lambdafun{j}{j.\var{waiting\_time}}}}}\)
\EndFor
\end{algorithmic}

\end{algorithm}
Python code
rng = np.random.default_rng(3)  # Same random numbers as in the other runs.
labda, mu, n = 3, 3.2, 10_000
jobs = MakeJobs(labda, mu, n)
for job in jobs:
    U = rng.uniform()
    job.priority = int(U <= 0.1)

sim = Simulation()
sim.queue = PriorityQueue()
sim.schedule_arrivals(jobs)
sim.initialize_servers([1])
sim.run()

K = 1000  # Large enough to approximate the M/M/1 queue.
mm1 = MnMn1K(lambda i: labda * (i < K), lambda i: mu * min(i, 1), K, 1)
print(f"W: sim: {sim.stats.mean_waiting_time():0.2f}, M/M/1: {mm1.mean_waiting_time():0.2f}")
print(f"J: sim: {sim.stats.mean_sojourn_time():0.2f}, M/M/1: {mm1.mean_sojourn_time():0.2f}")
print(f"Q: sim: {sim.stats.mean_queue_length():0.2f}, M/M/1: {mm1.mean_queue_length():0.2f}")
for k in [0, 1]:
    jobs_k = Filter(sim.stats.jobs, lambda j: j.priority == k)
    print(f"Priority: {k}, EW: {Average(Apply(jobs_k, lambda j: j.waiting_time)):.2f}")
R code
set.seed(3)  # Same random numbers as in the other runs.
lambda <- 3
mu <- 3.2
n <- 10000
# Reference classes have fixed fields, so we extend Job with a priority field.
PriorityJob <- setRefClass("PriorityJob", contains = "Job",
                           fields = list(priority = "numeric"))
jobs <- lapply(MakeJobs(lambda, mu, n),
               function(j) PriorityJob$new(j$id, j$arrival_time, j$load))
for (job in jobs) {
    U <- runif(1)
    job$priority <- as.numeric(U <= 0.1)
}

sim <- Simulation$new()
sim$queue <- PriorityQueue()
sim$schedule_arrivals(jobs)
sim$initialize_servers(1)
sim$run()

for (k in c(0, 1)) {
    jobs_k <- Filter(sim$stats$jobs, function(j) j$priority == k)
    print(c(priority = k,
            EW = Average(Apply(jobs_k, function(j) j$waiting_time))))
}
Table 3.5: An \(M/M/1\) queue in which ten percent of the jobs have priority, \(\lambda=3,\) \(\mu=3.2.\)
Measure Simulation \(M/M/1\)
Mean waiting time \(\E \W\) 4.84 4.69
Mean sojourn time \(\E \J\) 5.16 5.00
Mean queue length \(\E \Lq\) 14.53 14.06
Mean waiting time \(\E \W,\) priority \(1\) 0.32  
Mean waiting time \(\E \W,\) priority \(0\) 5.34  

From Table 3.5 we see that for the population as a whole, there is no difference in average waiting time:5Which is in accordance with our intuition. there is hardly any difference in waiting time between the simulation and the \(M/M/1\) queue.6For the \(M/M/1\) queue we use the closed-form solution, not a simulation. The small difference is due to sampling noise in the simulation. However, for the jobs with the higher priority class \(\E \W = 0.32,\) while for the lower priority \(\E \W = 5.34.\) That is, the lower priority jobs do wait somewhat (but not much) longer than in the case without priorities. We explain this by the fact that the fraction of jobs with higher priority is just 10%.

With the code we developed up to now, implementing the \(N\) policy takes very little work.7See Exercise 6. We only have to extend the \(\cl{Simulation}\) class by adding the threshold \(N\) and override \(\cl{Simulation}.\pr{HandleArrival},\) and nothing else!

\begin{algorithm}
\caption{A simulation under an \(N\) policy.}
\begin{algorithmic}[1]
\State \textbf{Input:} The threshold \(N.\)
\State \textbf{Output:} A simulation under an \(N\) policy.
\State \textbf{class} \(\cl{NPolicySimulation}\rb{N}\) \textbf{extends} \(\cl{Simulation}\)
\State \(\quad\) \textbf{instance variables:}
\State \(\quad\quad N\gets N\)
\State \(\quad\) \textbf{methods:}
\State \(\quad\quad \pr{HandleArrival}\rb{\var{job}}\) \Comment{Overrides \(\cl{Simulation}.\pr{HandleArrival}.\)}
\end{algorithmic}

\end{algorithm}
Python code
class NPolicySimulation(Simulation):
    def __init__(self, N):
        super().__init__()
        self.N = N
R code
NPolicySimulation <- setRefClass("NPolicySimulation",
    contains = "Simulation",
    fields = list(N = "numeric"),
    methods = list(
        initialize = function(N = 1, ...) {
            callSuper(...)
            N <<- N
        }
    )
)

An arriving job joins the queue. Only when the queue contains at least \(N\) jobs and the server is free, the server takes a job from the queue. Once the server is switched on, Alg. 3.5.18 does not check the queue length, but continues serving jobs until the system is empty. Fig. 3.1 shows a sample path of the queue length process.

\begin{algorithm}
\caption{Handle an arrival under an \(N\) policy.}
\begin{algorithmic}[1]
\State \textbf{Input:} The arriving job.
\State \textbf{Output:} None.
\Function{NPolicySimulation.HandleArrival}{\(\var{job}\)}
    \State \(\var{job}.\var{q\_length\_at\_arrival}\gets \var{queue}.\pr{Length}\rb{}\)
    \State \(\var{queue}.\pr{Push}\rb{\var{job}}\)
    \If{\(\var{queue}.\pr{Length}\rb{}\geq N\) and \(\var{servers}.\pr{ServerFree?}\rb{}\)}
        \State \(\pr{ServeJob}\rb{\var{queue}.\pr{Pop}\rb{},\,\var{servers}}\)
    \EndIf
\EndFunction
\end{algorithmic}

\end{algorithm}
Python code
def handle_arrival(self, job):
    job.q_length_at_arrival = self.queue.length()
    self.queue.push(job)
    if self.queue.length() >= self.N and self.servers.server_free():
        self.serve_job(self.queue.pop(), self.servers)
R code
NPolicySimulation$methods(handle_arrival = function(job) {
    job$q_length_at_arrival <- queue$length()
    queue$push(job)
    if (queue$length() >= N && servers$server_free()) {
        serve_job(queue$pop(), servers)
    }
})
n_policies.png
Figure 3.1: A queue under an \(N\) policy for \(N=20.\) Clearly, the queue builds up to 20, then the server switches on, and continues serving jobs until the system is empty. Then the server switches off until the system again contains \(N=20\) jobs, switches on, and so on.

The check-in process at an airport is a somewhat more involved queueing system, because at a check-in desk business and economy class customers typically have their own set of servers. Here, we are going to use simulation to compare different ways to organize the server allocation. One policy is like this: some of the servers are strictly allocated to business class customers, and the rest of the servers are strictly used for the economy class customers. Another policy is that if a business server is free, this server accepts just one economy customer for service8Assuming there is such a customer in queue.. When, after this service, there is still no business customer, the business server serves a second economy customer. Once a business customer arrives, the business server finishes the economy customer,9If one is in service. and then serves the business customer.10Note that this system is not identical to a priority queue. When the business servers are shared, business customers are served with priority; however, the economy servers are not shared. Which of these two policies is best?

Assume that a flight departing at 11 am consists of \(300\) economy class and 100 business class people. For ease, assume that all \(N\) customers arrive between 8 and 10, and that the desks are open from 8 to 10h30 to serve the demand.

Clearly, this is a transient queueing process that ends when all jobs are served. As this system is mathematically intractable, we only have simulation at our disposal.

We extend \(\cl{Job}\) and \(\cl{Server}\) with the attribute \(\var{type},\) which is \(\cn{Economy}\) or \(\cn{Business}.\)’’

\begin{algorithm}
\caption{Jobs and servers with a type.}
\begin{algorithmic}[1]
\State \textbf{Input:} The arguments of \(\cl{Job}\) or \(\cl{Server},\) and a type.
\State \textbf{Output:} A job or server with a type.
\State \textbf{class} \(\cl{TypedJob}\rb{\var{id},\,\var{arrival\_time},\,\var{load},\,\var{type}}\) \textbf{extends} \(\cl{Job}\)
\State \(\quad\) \textbf{instance variables:}
\State \(\quad\quad \var{type}\gets\var{type}\)
\State \textbf{class} \(\cl{TypedServer}\rb{\var{id},\,\var{rate},\,\var{type}}\) \textbf{extends} \(\cl{Server}\)
\State \(\quad\) \textbf{instance variables:}
\State \(\quad\quad \var{type}\gets\var{type}\)
\end{algorithmic}

\end{algorithm}
Python code
ECONOMY, BUSINESS = "Economy", "Business"


@dataclass
class TypedJob(Job):
    type: str = ECONOMY


@dataclass
class TypedServer(Server):
    type: str = ECONOMY
R code
TypedJob <- setRefClass("TypedJob",
    contains = "Job",
    fields = list(type = "character"),
    methods = list(
        initialize = function(id, arrival_time, load, type = "Economy") {
            callSuper(id, arrival_time, load)
            type <<- type
        }
    )
)

TypedServer <- setRefClass("TypedServer",
    contains = "Server",
    fields = list(type = "character")
)

In the simulator we configure separate queues and servers for the economy and the business customers. The boolean argument \(\var{share}\) indicates whether the business servers have to be shared or not. When handling arrivals and departures, we need to take the type of job and server into account. For the rest, we extend the \(\cl{Simulation}\) class.

\begin{algorithm}
\caption{A check-in simulation with economy and business queues and servers.}
\begin{algorithmic}[1]
\State \textbf{Input:} Whether the business servers are shared.
\State \textbf{Output:} A check-in simulation without servers.
\State \textbf{class} \(\cl{CheckInSimulation}\rb{\var{share}}\) \textbf{extends} \(\cl{Simulation}\)
\State \(\quad\) \textbf{instance variables:}
\State \(\quad\quad \var{share}\gets\var{share}\)
\State \(\quad\quad \var{e\_queue},\,\var{b\_queue}\gets\pr{FIFOQueue}\rb{},\,\pr{FIFOQueue}\rb{}\)
\State \(\quad\quad \var{e\_servers},\,\var{b\_servers}\gets\cl{Servers}\rb{},\,\cl{Servers}\rb{}\)
\State \(\quad\) \textbf{methods:}
\State \(\quad\quad \pr{InitializeDesks}\rb{\var{num\_e},\,\var{num\_b}}\)
\State \(\quad\quad \pr{HandleArrival}\rb{\var{job}}\) \Comment{Overrides \(\cl{Simulation}.\pr{HandleArrival}.\)}
\State \(\quad\quad \pr{HandleDeparture}\rb{\var{job}}\) \Comment{Overrides \(\cl{Simulation}.\pr{HandleDeparture}.\)}
\end{algorithmic}

\end{algorithm}
Python code
class CheckInSimulation(Simulation):
    def __init__(self, share=False):
        super().__init__()
        self.share = share
        self.e_queue, self.b_queue = FIFOQueue(), FIFOQueue()
        self.e_servers, self.b_servers = Servers(), Servers()
R code
CheckInSimulation <- setRefClass("CheckInSimulation",
    contains = "Simulation",
    fields = list(share = "logical", e_queue = "list", b_queue = "list",
                  e_servers = "list", b_servers = "list"),
    methods = list(
        initialize = function(share = FALSE, ...) {
            callSuper(...)
            share <<- share
            e_queue <<- FIFOQueue()
            b_queue <<- FIFOQueue()
            e_servers <<- Servers()
            b_servers <<- Servers()
        }
    )
)

Each desk is a server with rate \(1.\) In the same way as \(\cl{Simulation}.\pr{InitializeServers},\) we make heap queues for each type of server pool.

\begin{algorithm}
\caption{Open the economy and business desks.}
\begin{algorithmic}[1]
\State \textbf{Input:} The numbers of economy and business desks.
\State \textbf{Output:} None.
\Function{CheckInSimulation.InitializeDesks}{\(\var{num\_e},\,\var{num\_b}\)}
    \For{\(i=1,\ldots,\var{num\_e}\)}
        \State \(\var{e\_servers}.\pr{Push}\rb{\cl{TypedServer}\rb{i,\,\var{rate}=1,\,\var{type}=\cn{Economy}}}\)
    \EndFor
    \For{\(i=1,\ldots,\var{num\_b}\)}
        \State \(\var{b\_servers}.\pr{Push}\rb{\cl{TypedServer}\rb{i,\,\var{rate}=1,\,\var{type}=\cn{Business}}}\)
    \EndFor
\EndFunction
\end{algorithmic}

\end{algorithm}
Python code
def initialize_desks(self, num_e, num_b):
    for i in range(1, num_e + 1):
        self.e_servers.push(TypedServer(i, rate=1, type=ECONOMY))
    for i in range(1, num_b + 1):
        self.b_servers.push(TypedServer(i, rate=1, type=BUSINESS))
R code
CheckInSimulation$methods(initialize_desks = function(num_e, num_b) {
    for (i in seq_len(num_e)) {
        e_servers$push(TypedServer$new(id = i, rate = 1, type = "Economy"))
    }
    for (i in seq_len(num_b)) {
        b_servers$push(TypedServer$new(id = i, rate = 1, type = "Business"))
    }
})

An arriving economy customer takes a free economy desk. If there is none and the desks are shared, the customer takes a free business desk; otherwise the customer joins the economy queue. A business customer only uses business desks.

\begin{algorithm}
\caption{Handle an arrival at the check-in desks.}
\begin{algorithmic}[1]
\State \textbf{Input:} The arriving job.
\State \textbf{Output:} None.
\Function{CheckInSimulation.HandleArrival}{\(\var{job}\)}
    \If{\(\var{job}.\var{type}==\cn{Economy}\)}
        \If{\(\var{e\_servers}.\pr{ServerFree?}\rb{}\)}
            \State \(\pr{ServeJob}\rb{\var{job},\,\var{e\_servers}}\)
        \ElsIf{\(\var{share}\) and \(\var{b\_servers}.\pr{ServerFree?}\rb{}\)}
            \State \(\pr{ServeJob}\rb{\var{job},\,\var{b\_servers}}\)
        \Else
            \State \(\var{e\_queue}.\pr{Push}\rb{\var{job}}\)
        \EndIf
    \ElsIf{\(\var{b\_servers}.\pr{ServerFree?}\rb{}\)}
        \State \(\pr{ServeJob}\rb{\var{job},\,\var{b\_servers}}\)
    \Else
        \State \(\var{b\_queue}.\pr{Push}\rb{\var{job}}\)
    \EndIf
\EndFunction
\end{algorithmic}

\end{algorithm}
Python code
def handle_arrival(self, job):
    if job.type == ECONOMY:
        if self.e_servers.server_free():
            self.serve_job(job, self.e_servers)
        elif self.share and self.b_servers.server_free():
            self.serve_job(job, self.b_servers)
        else:
            self.e_queue.push(job)
    elif self.b_servers.server_free():
        self.serve_job(job, self.b_servers)
    else:
        self.b_queue.push(job)
R code
CheckInSimulation$methods(handle_arrival = function(job) {
    if (job$type == "Economy") {
        if (e_servers$server_free()) {
            serve_job(job, e_servers)
        } else if (share && b_servers$server_free()) {
            serve_job(job, b_servers)
        } else {
            e_queue$push(job)
        }
    } else if (b_servers$server_free()) {
        serve_job(job, b_servers)
    } else {
        b_queue$push(job)
    }
})

A departing customer frees a desk of its type. An economy desk then serves the next economy customer. A business desk serves the next business customer, if any. Otherwise, when it is shared with the economy class, it serves the next economy customer, if any.

\begin{algorithm}
\caption{Handle a departure from the check-in desks.}
\begin{algorithmic}[1]
\State \textbf{Input:} The departing job.
\State \textbf{Output:} None.
\Function{CheckInSimulation.HandleDeparture}{\(\var{job}\)}
    \State \(\var{stats}.\pr{Push}\rb{\var{job}}\)
    \If{\(\var{job}.\var{server}.\var{type}==\cn{Economy}\)}
        \State \(\var{e\_servers}.\pr{Push}\rb{\var{job}.\var{server}}\)
        \If{\(\neg\var{e\_queue}.\pr{Empty?}\rb{}\)}
            \State \(\pr{ServeJob}\rb{\var{e\_queue}.\pr{Pop}\rb{},\,\var{e\_servers}}\)
        \EndIf
    \Else
        \State \(\var{b\_servers}.\pr{Push}\rb{\var{job}.\var{server}}\)
        \If{\(\neg\var{b\_queue}.\pr{Empty?}\rb{}\)}
            \State \(\pr{ServeJob}\rb{\var{b\_queue}.\pr{Pop}\rb{},\,\var{b\_servers}}\)
        \ElsIf{\(\var{share}\) and \(\neg\var{e\_queue}.\pr{Empty?}\rb{}\)}
            \State \(\pr{ServeJob}\rb{\var{e\_queue}.\pr{Pop}\rb{},\,\var{b\_servers}}\)
        \EndIf
    \EndIf
\EndFunction
\end{algorithmic}

\end{algorithm}
Python code
def handle_departure(self, job):
    self.stats.push(job)
    if job.server.type == ECONOMY:
        self.e_servers.push(job.server)
        if not self.e_queue.is_empty():
            self.serve_job(self.e_queue.pop(), self.e_servers)
    else:
        self.b_servers.push(job.server)
        if not self.b_queue.is_empty():
            self.serve_job(self.b_queue.pop(), self.b_servers)
        elif self.share and not self.e_queue.is_empty():
            self.serve_job(self.e_queue.pop(), self.b_servers)
R code
CheckInSimulation$methods(handle_departure = function(job) {
    stats$push(job)
    if (job$server$type == "Economy") {
        e_servers$push(job$server)
        if (!e_queue$is_empty()) {
            serve_job(e_queue$pop(), e_servers)
        }
    } else {
        b_servers$push(job$server)
        if (!b_queue$is_empty()) {
            serve_job(b_queue$pop(), b_servers)
        } else if (share && !e_queue$is_empty()) {
            serve_job(e_queue$pop(), b_servers)
        }
    }
})

The next step is to configure the jobs and the time the desks have to be open to serve all customers. The customers arrive at uniformly distributed times in a check-in window of \(T=120\) minutes. These times need not be sorted, because the event queue processes the arrivals in the order of time. The loads are exponential with a mean of \(2\) minutes. The desks stay open for \(30\) minutes after the window closes.

\begin{algorithm}
\caption{Make the jobs of one class of customers.}
\begin{algorithmic}[1]
\State \textbf{Input:} Number of customers \(n,\) their type, and the length \(T\) of the check-in window.
\State \textbf{Output:} A list of \(n\) typed jobs.
\Function{MakeCheckInJobs}{\(n,\,\var{type},\,T\)}
    \For{\(i=1,\ldots,n\)}
        \State \(A_i\gets T\cdot\Unif{(0,1)}\)
    \EndFor
    \State \(S\gets\pr{GenerateExponentialRVs}\rb{1/2,\,n}\)
    \Return \(\qb{\cl{TypedJob}\rb{i,\,A_i,\,S_i,\,\var{type}}:i=1,\ldots,n}\)
\EndFunction
\State \(T\gets120\) \Comment{Minutes.}
\State \(\var{desks\_open}\gets T+30\)
\State \(\var{e\_jobs}\gets\pr{MakeCheckInJobs}\rb{300,\,\cn{Economy},\,T}\)
\State \(\var{b\_jobs}\gets\pr{MakeCheckInJobs}\rb{100,\,\cn{Business},\,T}\)
\end{algorithmic}

\end{algorithm}
Python code
def MakeCheckInJobs(n, type, T):
    A = T * rng.uniform(size=n)
    S = GenerateExponentialRVs(1 / 2, n)
    return [TypedJob(i, A[i - 1], S[i - 1], type=type) for i in range(1, n + 1)]


rng = np.random.default_rng(3)
T = 120  # minutes
desks_open = T + 30
e_jobs = MakeCheckInJobs(300, ECONOMY, T)
b_jobs = MakeCheckInJobs(100, BUSINESS, T)
R code
MakeCheckInJobs <- function(n, type, T) {
    A <- T * runif(n)
    S <- GenerateExponentialRVs(1 / 2, n)
    lapply(seq_len(n), function(i) TypedJob$new(i, A[i], S[i], type))
}

set.seed(3)
T <- 120  # minutes
desks_open <- T + 30
e_jobs <- MakeCheckInJobs(300, "Economy", T)
b_jobs <- MakeCheckInJobs(100, "Business", T)

With the model in place we need to determine the required number of servers \(c\) such that the performance is acceptable. Alg. 3.6.13 prints the total capacity and the demand so that we can check whether the available server capacity suffices. Table 3.6 shows that the capacities suffice to get the work done.

\begin{algorithm}
\caption{Compare the work of each class with the capacity of its desks.}
\begin{algorithmic}[1]
\State \(\var{num\_e},\,\var{num\_b}\gets4,\,2\)
\State \(\pr{Work}\gets\lambdafun{L}{\pr{Sum}\rb{\pr{Apply}\rb{L,\,\lambdafun{j}{j.\var{load}}}}}\)
\State \(\pr{Print}\rb{\pr{Work}\rb{\var{e\_jobs}},\,\var{num\_e}\cdot\var{desks\_open}}\)
\State \(\pr{Print}\rb{\pr{Work}\rb{\var{b\_jobs}},\,\var{num\_b}\cdot\var{desks\_open}}\)
\end{algorithmic}

\end{algorithm}
Python code
num_e, num_b = 4, 2
Work = lambda L: Sum(Apply(L, lambda j: j.load))
print(f"Economy: work {Work(e_jobs):.0f}, capacity {num_e * desks_open}")
print(f"Business: work {Work(b_jobs):.0f}, capacity {num_b * desks_open}")
R code
num_e <- 4L
num_b <- 2L
Work <- function(L) Sum(Apply(L, function(j) j$load))
print(c(economy_work = Work(e_jobs), capacity = num_e * desks_open))
print(c(business_work = Work(b_jobs), capacity = num_b * desks_open))
Table 3.6: The total work and the service capacity per class.
Class Work Capacity
Economy 556 600
Business 194 300

We can run the simulation. To compare policies, we run it for a given number of economy and business desks, and with or without sharing.

\begin{algorithm}
\caption{Run the check-in simulation for one configuration.}
\begin{algorithmic}[1]
\State \textbf{Input:} The numbers of economy and business desks, and whether the business desks are shared.
\State \textbf{Output:} The simulation after the run.
\Function{RunCheckIn}{\(\var{num\_e},\,\var{num\_b},\,\var{share}\)}
    \State \(\var{sim}\gets\cl{CheckInSimulation}\rb{\var{share}}\)
    \State \(\var{sim}.\pr{InitializeDesks}\rb{\var{num\_e},\,\var{num\_b}}\)
    \State \(\var{sim}.\pr{ScheduleArrivals}\rb{\var{e\_jobs}}\)
    \State \(\var{sim}.\pr{ScheduleArrivals}\rb{\var{b\_jobs}}\)
    \State \(\var{sim}.\pr{Run}\rb{}\)
    \Return \(\var{sim}\)
\EndFunction
\end{algorithmic}

\end{algorithm}
Python code
def RunCheckIn(num_e, num_b, share):
    sim = CheckInSimulation(share)
    sim.initialize_desks(num_e, num_b)
    sim.schedule_arrivals(e_jobs)
    sim.schedule_arrivals(b_jobs)
    sim.run()
    return sim
R code
RunCheckIn <- function(num_e, num_b, share) {
    sim <- CheckInSimulation$new(share = share)
    sim$initialize_desks(num_e, num_b)
    sim$schedule_arrivals(e_jobs)
    sim$schedule_arrivals(b_jobs)
    sim$run()
    sim
}

And we can print the KPIs. It is reasonable11Within this context, that is. that besides the mean waiting time the largest waiting time is important. For each class we therefore compute the time of the last departure, the largest waiting time and the mean waiting time, with \(\pr{Maximum}\) and \(\pr{Average}\) of Section 1.2.

\begin{algorithm}
\caption{Print the performance measures of each class.}
\begin{algorithmic}[1]
\State \(\var{sim}\gets\pr{RunCheckIn}\rb{4,\,2,\,\cn{False}}\)
\For{\(\var{jobs}\in\qb{\var{e\_jobs},\,\var{b\_jobs}}\)}
    \State \(D\gets\pr{Apply}\rb{\var{jobs},\,\lambdafun{j}{j.\var{departure\_time}}}\)
    \State \(W\gets\pr{Apply}\rb{\var{jobs},\,\lambdafun{j}{j.\var{waiting\_time}}}\)
    \State \(\pr{Print}\rb{\pr{Maximum}\rb{D},\,\pr{Maximum}\rb{W},\,\pr{Average}\rb{W}}\)
\EndFor
\State \(\pr{Print}\rb{\var{sim}.\var{stats}.\pr{MeanWaitingTime}\rb{}}\)
\end{algorithmic}

\end{algorithm}
Python code
sim = RunCheckIn(4, 2, False)
for name, jobs in [("Economy", e_jobs), ("Business", b_jobs)]:
    D = Apply(jobs, lambda j: j.departure_time)
    W = Apply(jobs, lambda j: j.waiting_time)
    print(name, Maximum(D), Maximum(W), Average(W))
print("Overall mean waiting time:", sim.stats.mean_waiting_time())
R code
sim <- RunCheckIn(4, 2, FALSE)
for (jobs in list(e_jobs, b_jobs)) {
    D <- Apply(jobs, function(j) j$departure_time)
    W <- Apply(jobs, function(j) j$waiting_time)
    print(c(Maximum(D), Maximum(W), Average(W)))
}
print(sim$stats$mean_waiting_time())

Table 3.7 shows that all customers are served in time, but the waiting times of the economy class customers are quite long.

Table 3.7: The KPIs with \(4\) economy and \(2\) business desks, without sharing.
Class Last departure Largest waiting time Mean waiting time
Economy 150.0 29.2 11.96
Business 122.6 8.4 1.18
Overall     9.27

One way to reduce the waiting times for the economy class is by opening an extra economy desk, that is, use \(5+2\) desks instead of \(4+2.\)12This comes at the expense of hiring an extra server: 7 instead of 6. That is, we call \(\pr{RunCheckIn}\rb{5,\,2,\,\cn{False}}.\) Table 3.8 shows that this decision has a large impact on the waiting time.

Table 3.8: The KPIs with \(5\) economy and \(2\) business desks, without sharing.
Class Last departure Largest waiting time Mean waiting time
Economy 128.8 11.7 3.55
Business 122.6 8.4 1.18
Overall     2.96

However, rather than paying for this extra desk, we can share the business class servers and keep using \(4+2=6\) desks. That is, we call \(\pr{RunCheckIn}\rb{4,\,2,\,\cn{True}}.\) Table 3.9 shows that the mean waiting time of the business customers increases from \(1.18\) to \(2.16,\) while that of the economy class decreases from \(11.96\) to \(7.65,\) as compared to the situation without server sharing and 6 servers.

Table 3.9: The KPIs with \(4\) economy and \(2\) business desks, with sharing.
Class Last departure Largest waiting time Mean waiting time
Economy 138.9 22.0 7.65
Business 122.7 10.3 2.16
Overall     6.27

To conclude, adding extra service capacity has the largest effect on waiting time, but server sharing can also be an effective strategy.

TF 1.

Claim: this function implements a sorting rule in which jobs with the same priority are served in LIFO order.

\begin{algorithm}
\begin{algorithmic}[1]
\Function{PriorityQueue}{}
    \State \(\pr{Key}\gets\lambdafun{j}{(-j.\var{priority},\,j.\var{arrival\_time})}\)
    \Return \(\cl{Queue}\rb{\lambdafun{(x,\,y)}{\pr{LexLessThan?}\rb{\pr{Key}\rb{x},\,\pr{Key}\rb{y}}}}\)
\EndFunction
\end{algorithmic}

\end{algorithm}
Solution

Did you actually try? Write your solution down first for comparison.

Show the solution

False. Compare with Alg. 3.6.3: for equal priorities, the earlier arrival comes first.

TF 2.

Claim: This method of the simulation class switches on the server when the system contains \(N\) jobs or more.

\begin{algorithm}
\begin{algorithmic}[1]
\Function{NPolicySimulation.HandleArrival}{\(\var{job}\)}
    \State \(\var{job}.\var{q\_length\_at\_arrival}\gets \var{queue}.\pr{Length}\rb{}\)
    \If{\(\var{queue}.\pr{Length}\rb{}\geq N\) and \(\var{servers}.\pr{ServerFree?}\rb{}\)}
        \State \(\pr{ServeJob}\rb{\var{queue}.\pr{Pop}\rb{},\,\var{servers}}\)
    \Else
        \State \(\var{queue}.\pr{Push}\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. It waits until the system contains \(N\) plus one jobs. Also, the arriving job is never queued when the server switches on, so that job is lost.

TF 3.

Consider the check-in process at an airport when the business servers are shared with the economy customers. Claim: This method of the simulation class handles the arrivals correctly.

\begin{algorithm}
\begin{algorithmic}[1]
\Function{CheckInSimulation.HandleArrival}{\(\var{job}\)}
    \If{\(\var{job}.\var{type}==\cn{Economy}\)}
        \If{\(\var{e\_servers}.\pr{ServerFree?}\rb{}\)}
            \State \(\pr{ServeJob}\rb{\var{job},\,\var{e\_servers}}\)
        \ElsIf{\(\var{share}\)}
            \State \(\pr{ServeJob}\rb{\var{job},\,\var{b\_servers}}\)
        \Else
            \State \(\var{e\_queue}.\pr{Push}\rb{\var{job}}\)
        \EndIf
    \EndIf
\EndFunction
\end{algorithmic}

\end{algorithm}
Solution

Did you actually try? Write your solution down first for comparison.

Show the solution

False. Compare with Alg. 3.6.10. There is no check on the availability of the business servers.

TF 4.

Claim: In a discrete-event simulation of a multi-server queue, the server with the shortest remaining service time should always be chosen for new arrivals.

Solution

Did you actually try? Write your solution down first for comparison.

Show the solution

False. Our simulator gives an arriving job the fastest free server. A job only meets a server when one is free, so there is no remaining service time to compare.

TF 5.

Claim: In a priority queue, jobs with higher priority always have a shorter expected sojourn time than jobs with lower priority.

Solution

Did you actually try? Write your solution down first for comparison.

Show the solution

True, provided the system is stable and both classes have the same service-time distribution, as in our example. Higher priority jobs are served before lower priority jobs, so their expected waiting time and hence sojourn time is shorter.