3.4 Optional: Simulation of Queue Length with Heap Queues
3.4 Optional: Simulation of Queue Length with Heap Queues
We have seen in Section 3.3 that the recursions to compute waiting and sojourn times for a continuous-time single-server queue can be implemented in a straightforward way. Here we handle the work process \(\set{W(t)}\) and the system-size process \(\set{L(t)}.\) This is somewhat complicated because job arrival and departure events are intertwined,1See Fig. 3.2. while to plot properly, these events have to be chronologically sorted. Surely, to sort we can use the Quicksort algorithm Alg. 1.2.22. However, for the discrete event simulator of Section 3.5 we need a more flexible way to sort objects. A suitable data structure for this purpose is the heap queue. Here we explain how it works, and we use it to make Fig. 3.1.
A heap queue stores items such that a pop always returns the smallest item according to a comparison function \(\pr{LessThan?}.\) Alg. 3.4.1 stores the items in a binary tree:2As long as the tree is balanced, \(\cl{Heap}.\pr{Push}\) and \(\cl{Heap}.\pr{Pop}\) take \(O(\log n)\) steps. each node holds a \(\var{value}\) that is not larger than any value in its subtrees \(\var{left}\) and \(\var{right}.\) \(\cl{Heap}.\pr{Push}\) adds an item to the heap, and \(\cl{Heap}.\pr{Pop}\) removes and returns the smallest item.
\begin{algorithm}
\caption{A heap ordered by a comparison function.}
\begin{algorithmic}[1]
\State \textbf{Input:} A comparison function \(\pr{LessThan?}\) on pairs of items.
\State \textbf{Output:} An empty heap.
\State \textbf{class} \(\cl{Heap}\rb{\pr{LessThan?}}\)
\State \(\quad\) \textbf{instance variables:}
\State \(\quad\quad \var{value},\,\var{left},\,\var{right}\gets\cn{Nil},\,\cn{Nil},\,\cn{Nil}\)
\State \(\quad\quad \var{length}\gets0\)
\State \(\quad\quad \pr{LessThan?}\gets\pr{LessThan?}\)
\State \(\quad\) \textbf{methods:}
\State \(\quad\quad \pr{Push}\rb{\var{new\_value}}\)
\State \(\quad\quad \pr{Pop}\rb{}\)
\State \(\quad\quad \pr{Empty?}\gets\lambdafun{()}{\var{length}==0}\)
\end{algorithmic}
\end{algorithm}
Python code
class Heap:
"""Heap ordered by less_than; a direct translation of the pseudocode.
For real use, take heapq from Python's standard library instead. It
stores the heap in one list, so it needs no Heap object per element, and
it keeps the depth of the tree at floor(log2 n) after every push and pop.
"""
def __init__(self, less_than):
self.value, self.left, self.right = None, None, None
self.length = 0
self.less_than = less_than
def is_empty(self):
return self.length == 0
R code
Heap <- setRefClass("Heap",
fields = list(value = "ANY", left = "ANY", right = "ANY",
length = "numeric", less_than = "function"),
methods = list(
initialize = function(less_than = function(x, y) x < y) {
callSuper(value = NULL, left = NULL, right = NULL,
length = 0, less_than = less_than)
},
is_empty = function() length == 0
)
)
\(\cl{Heap}.\pr{Push}\) keeps the smaller of \(\var{value}\) and \(\var{new\_value}\) at the node, and pushes the larger one into the subtree with the fewer items.3In this way, the lengths of the two subtrees differ by at most one, until the first \(\cl{Heap}.\pr{Pop}.\) The subtrees \(\var{left}\) and \(\var{right}\) are heap queues of their own, so \(\var{left}.\pr{Push}\) or \(\var{right}.\pr{Push}\) push into their own subtree. In case the heap is empty, there is no \(\var{value}\) to compare with. Then \(\cl{Heap}.\pr{Push}\) stores \(\var{new\_value}\) as \(\var{value}\) and creates an empty left and right heap.
\begin{algorithm}
\caption{Push a new value on the heap.}
\begin{algorithmic}[1]
\State \textbf{Input:} A new value.
\State \textbf{Output:} None.
\Function{Heap.Push}{\(\var{new\_value}\)}
\If{\(\pr{Empty?}\rb{}\)}
\State \(\var{value},\,\var{length}\gets \var{new\_value},\,1\)
\State \(\var{left},\,\var{right}\gets\cl{Heap}\rb{\pr{LessThan?}},\,\cl{Heap}\rb{\pr{LessThan?}}\)
\Return
\EndIf
\If{\(\pr{LessThan?}\rb{\var{new\_value},\,\var{value}}\)}
\State \(\var{value},\,\var{new\_value}\gets \var{new\_value},\,\var{value}\) \Comment{Swap.}
\EndIf
\If{\(\var{left}.\var{length}\leq \var{right}.\var{length}\)}
\State \(\var{left}.\pr{Push}\rb{\var{new\_value}}\)
\Else
\State \(\var{right}.\pr{Push}\rb{\var{new\_value}}\)
\EndIf
\State \(\var{length}\xleftarrow{+}1\)
\EndFunction
\end{algorithmic}
\end{algorithm}
Python code
def push(self, new_value):
if self.is_empty():
self.value, self.length = new_value, 1
self.left, self.right = Heap(self.less_than), Heap(self.less_than)
return
if self.less_than(new_value, self.value):
self.value, new_value = new_value, self.value # swap
if self.left.length <= self.right.length:
self.left.push(new_value)
else:
self.right.push(new_value)
self.length += 1
R code
Heap$methods(push = function(new_value) {
if (is_empty()) {
value <<- new_value
length <<- 1
left <<- Heap$new(less_than)
right <<- Heap$new(less_than)
return(invisible(NULL))
}
if (less_than(new_value, value)) {
old <- value # swap
value <<- new_value
new_value <- old
}
if (left$length <= right$length) {
left$push(new_value)
} else {
right$push(new_value)
}
length <<- length + 1
invisible(NULL)
})
\(\cl{Heap}.\pr{Pop}\) removes and returns \(\var{value},\) which is the smallest item of the heap. To refill the node, it compares the values at the top of \(\var{left}\) and \(\var{right},\) and takes the smaller of \(\var{left}.\var{value}\) and \(\var{right}.\var{value}\) as the new \(\var{value}.\)4\(\cl{Heap}.\pr{Pop}\) ignores the lengths of the subtrees, so after many pops one subtree can hold many more items than the other. The tree is then deeper than \(\log_2 n,\) and \(\cl{Heap}.\pr{Push}\) and \(\cl{Heap}.\pr{Pop}\) need more steps. As the subtrees are heap queues of their own, \(\var{left}.\pr{Pop}\) or \(\var{right}.\pr{Pop}\) removes that value from its subtree. In case one subtree is empty, \(\cl{Heap}.\pr{Pop}\) takes the value from the other one. At line 7, in case the heap is empty after the removal, there is nothing to refill.
\begin{algorithm}
\caption{Pop the smallest item from the heap.}
\begin{algorithmic}[1]
\State \textbf{Input:} None.
\State \textbf{Output:} The smallest item.
\Function{Heap.Pop}{}
\State \(\var{minimum}\gets \var{value}\)
\State \(\var{length}\xleftarrow{-}1\)
\If{\(\pr{Empty?}\rb{}\)}
\Return \(\var{minimum}\)
\EndIf
\If{\(\var{left}.\pr{Empty?}\rb{}\)}
\State \(\var{value}\gets \var{right}.\pr{Pop}\rb{}\)
\ElsIf{\(\var{right}.\pr{Empty?}\rb{}\)}
\State \(\var{value}\gets \var{left}.\pr{Pop}\rb{}\)
\ElsIf{\(\pr{LessThan?}\rb{\var{right}.\var{value},\,\var{left}.\var{value}}\)}
\State \(\var{value}\gets \var{right}.\pr{Pop}\rb{}\)
\Else
\State \(\var{value}\gets \var{left}.\pr{Pop}\rb{}\)
\EndIf
\Return \(\var{minimum}\)
\EndFunction
\end{algorithmic}
\end{algorithm}
Python code
def pop(self):
minimum = self.value
self.length -= 1
if self.is_empty():
return minimum
if self.left.is_empty():
self.value = self.right.pop()
elif self.right.is_empty():
self.value = self.left.pop()
elif self.less_than(self.right.value, self.left.value):
self.value = self.right.pop()
else:
self.value = self.left.pop()
return minimum
R code
Heap$methods(pop = function() {
minimum <- value
length <<- length - 1
if (is_empty()) {
return(minimum)
}
if (left$is_empty()) {
value <<- right$pop()
} else if (right$is_empty()) {
value <<- left$pop()
} else if (less_than(right$value, left$value)) {
value <<- right$pop()
} else {
value <<- left$pop()
}
minimum
})
Before demonstrating how to use heap queues to sort, we
introduce lexicographic ordering. It compares strings and tuples element by
element, as in a dictionary; the first position at which they differ decides.
For example, “heathen” precedes “heather”: the first five letters are equal,
and n precedes r in the alphabet. Likewise, ("tree", 3) precedes
("tree", 4), because the first elements are equal and \(3<4.\)
Alg. 3.4.4 shows the implementation.
Line 4 deals with the case when one of the two tuples runs out of elements
before they differ. In that casee, the shorter one comes first, for instance,
“heat” precedes “heather”. After four recursive calls, \(x\) is empty and \(y\)
holds the letters h, e and r, so the algorithm returns \(0<3,\) which is
true. In the comparison of “heather” with “heat”, the algorithm returns \(3<0,\)
which is false, so “heather” does not precede “heat”.
\begin{algorithm}
\caption{Lexicographic comparison of two tuples.}
\begin{algorithmic}[1]
\State \textbf{Input:} Tuples \(x=(x_1,\ldots,x_m)\) and \(y=(y_1,\ldots,y_n),\) \(m,n\geq0,\) whose elements can be compared with \(<.\)
\State \textbf{Output:} Whether \(x\) comes before \(y\) in lexicographic order.
\Function{LexLessThan?}{\(x,\,y\)}
\If{\(m==0\) or \(n==0\)}
\Return \(m<n\) \Comment{The shorter tuple comes first.}
\EndIf
\If{\(x_1==y_1\)}
\Return \(\pr{LexLessThan?}\rb{(x_2,\ldots,x_m),\,(y_2,\ldots,y_n)}\)
\EndIf
\Return \(x_1<y_1\)
\EndFunction
\end{algorithmic}
\end{algorithm}
Python code
def LexLessThan(x, y):
if len(x) == 0 or len(y) == 0:
return len(x) < len(y) # The shorter tuple comes first.
if x[0] == y[0]:
return LexLessThan(x[1:], y[1:])
return x[0] < y[0]
R code
LexLessThan <- function(x, y) {
if (length(x) == 0 || length(y) == 0) {
return(length(x) < length(y)) # The shorter tuple comes first.
}
if (x[[1]] == y[[1]]) {
return(LexLessThan(x[-1], y[-1]))
}
x[[1]] < y[[1]]
}
Here is an example of how to initialize and use a heap. We push tuples of ages and animals on the heap, and pop them in lexicographic order. Such tuples can be pushed and popped arbitrarily on the heap.
\begin{algorithm}
\caption{Push and pop tuples of ages and animals.}
\begin{algorithmic}[1]
\State \(\var{heap}\gets\cl{Heap}\rb{\pr{LexLessThan?}}\)
\State \(\var{heap}.\pr{Push}\rb{(25,\,\text{Turtle})}\)
\State \(\var{heap}.\pr{Push}\rb{(14,\,\text{Dog})}\)
\State \(\var{heap}.\pr{Push}\rb{(18,\,\text{Cat})}\)
\State \(\var{heap}.\pr{Push}\rb{(21,\,\text{Horse})}\)
\State \(\pr{Print}\rb{\var{heap}.\pr{Pop}\rb{}}\) \Comment{\((14,\,\text{Dog}).\)}
\State \(\var{heap}.\pr{Push}\rb{(20,\,\text{Lion})}\)
\State \(\pr{Print}\rb{\var{heap}.\pr{Pop}\rb{}}\) \Comment{\((18,\,\text{Cat}).\)}
\State \(\var{heap}.\pr{Push}\rb{(23,\,\text{Elephant})}\)
\end{algorithmic}
\end{algorithm}
Python code
heap = Heap(LexLessThan)
heap.push((25, "Turtle"))
heap.push((14, "Dog"))
heap.push((18, "Cat"))
heap.push((21, "Horse"))
print(heap.pop()) # (14, 'Dog')
heap.push((20, "Lion"))
print(heap.pop()) # (18, 'Cat')
heap.push((23, "Elephant"))
R code
heap <- Heap$new(LexLessThan)
heap$push(list(25, "Turtle"))
heap$push(list(14, "Dog"))
heap$push(list(18, "Cat"))
heap$push(list(21, "Horse"))
str(heap$pop()) # 14, "Dog"
heap$push(list(20, "Lion"))
str(heap$pop()) # 18, "Cat"
heap$push(list(23, "Elephant"))
Next, we pop until the heap is empty. The dog and the cat are no longer on the heap, as we popped them before.
\begin{algorithm}
\caption{Pop until the heap is empty.}
\begin{algorithmic}[1]
\While{\(\neg\var{heap}.\pr{Empty?}\rb{}\)}
\State \(\pr{Print}\rb{\var{heap}.\pr{Pop}\rb{}}\)
\EndWhile
\State
\Comment{\((20,\,\text{Lion}),\,(21,\,\text{Horse}),\,(23,\,\text{Elephant}),\,(25,\,\text{Turtle}).\)}
\end{algorithmic}
\end{algorithm}
Python code
while not heap.is_empty():
print(heap.pop())
# (20, 'Lion'), (21, 'Horse'), (23, 'Elephant'), (25, 'Turtle')
R code
while (!heap$is_empty()) {
str(heap$pop())
}
# 20 "Lion", 21 "Horse", 23 "Elephant", 25 "Turtle"
In summary, a heap queue allows us to push and pop items in any order, and a pop always returns the smallest item. This is what we need to process intertwined arrival and departure events in chronological order.
We now explain the steps to make Fig. 3.1. The top panel shows a sample path of \(\set{W(t)},\) the lower panel a sample path of \(\set{L(t)}.\) Making these graphs takes four steps.
First, we simulate \(n\) jobs with the recursions of Section 3.3 to get \(A_k, D_k, \J_k\) and \(\W_k.\) We sort the arrival and departure times chronologically with a heap queue. For each arrival we push an event \((A_k, 1)\) on the heap, and for each departure an event \((D_k, -1).\)5When an arrival and a departure occur at the same time, \((t,-1) < (t,1),\) so the departure is popped first.
Second, for each job \(k\) we draw a triangle with corners \((A_k,0),\) \((A_k,\J_k)\) and \((D_k,0)\) for the sojourn time, and a triangle with corners \((A_k,0),\) \((A_k,\W_k)\) and \((A_k+\W_k,0)\) for the waiting time. Since the server removes work at rate \(1,\) the height and the base of each triangle are equal.
Third, we need \(W(t-)\) and \(W(t)\) at any time \(t.\) By the definition \(W(t) = [D_{A(t)} - t]^{+},\) this requires \(A(t-)\) and \(A(t).\) As the arrival times are sorted, binary search finds the index \(k\) with \(A_{k-1} \leq t < A_{k}\) in \(O(\log n)\) steps.6For the same reason, we used binary search in Section 1.5. Exercise 6 shows that this index equals \(A(t)+1.\)
Fourth, popping the events one by one gives the epochs at which \(W\) or \(L\) jumps; Alg. 3.4.7 collects the points of both graphs. Between two consecutive events, \(L\) is constant and \(W\) decreases linearly, because \(W\) reaches \(0\) only at a departure, which is itself an event. Hence connecting consecutive points by straight lines gives the graphs.
\begin{algorithm}
\caption{The points of the sample paths of the work and the number of jobs.}
\begin{algorithmic}[1]
\State \textbf{Input:} Arrival times \(A_1,\ldots,A_n\) and departure times \(D_1,\ldots,D_n.\)
\State \textbf{Output:} Lists \(P_W\) and \(P_L\) of points of the graphs of \(W\) and \(L.\)
\Function{SamplePaths}{\(A,\,D\)}
\State \(\var{heap}\gets\cl{Heap}\rb{\pr{LexLessThan?}}\)
\For{\(k=1,\,\ldots,\,n\)}
\State \(\var{heap}.\pr{Push}\rb{(A_k,\,1)}\)
\State \(\var{heap}.\pr{Push}\rb{(D_k,\,-1)}\)
\EndFor
\State \(P_W,\,P_L,\,L\gets\qb{},\,\qb{},\,0\)
\While{\(\neg\var{heap}.\pr{Empty?}\rb{}\)}
\State \((t,\,\delta)\gets\var{heap}.\pr{Pop}\rb{}\)
\State \(\pr{Append}\rb{P_W,\,(t,\,W(t-))}\)
\State \(\pr{Append}\rb{P_W,\,(t,\,W(t))}\)
\State \(\pr{Append}\rb{P_L,\,(t,\,L)}\)
\State \(L\xleftarrow{+}\delta\)
\State \(\pr{Append}\rb{P_L,\,(t,\,L)}\)
\EndWhile
\Return \(P_W,\,P_L\)
\EndFunction
\end{algorithmic}
\end{algorithm}
Python code
from bisect import bisect_left, bisect_right
def SamplePaths(A, D):
"""A and D hold A_1, ..., A_n and D_1, ..., D_n; A is sorted."""
def work(t, left=False):
"W(t-) when left is True, else W(t); bisect is binary search."
k = bisect_left(A, t) if left else bisect_right(A, t) # A(t-) or A(t)
return max(D[k - 1] - t, 0) if k > 0 else 0
heap = Heap(LexLessThan)
for a, d in zip(A, D):
heap.push((a, 1))
heap.push((d, -1))
P_W, P_L, L = [], [], 0
while not heap.is_empty():
t, delta = heap.pop()
P_W.append((t, work(t, left=True)))
P_W.append((t, work(t)))
P_L.append((t, L))
L += delta
P_L.append((t, L))
return P_W, P_L
R code
SamplePaths <- function(A, D) {
# W(t-) when left is TRUE, else W(t); findInterval is binary search.
work <- function(t, left = FALSE) {
k <- findInterval(t, A, left.open = left) # A(t-) or A(t)
if (k == 0) 0 else max(D[k] - t, 0)
}
heap <- Heap$new(LexLessThan)
for (k in seq_along(A)) {
heap$push(list(A[k], 1))
heap$push(list(D[k], -1))
}
P_W <- list()
P_L <- list()
L <- 0
while (!heap$is_empty()) {
event <- heap$pop()
t <- event[[1]]
delta <- event[[2]]
P_W[[length(P_W) + 1]] <- c(t, work(t, left = TRUE))
P_W[[length(P_W) + 1]] <- c(t, work(t))
P_L[[length(P_L) + 1]] <- c(t, L)
L <- L + delta
P_L[[length(P_L) + 1]] <- c(t, L)
}
list(P_W = P_W, P_L = P_L)
}
TF 1.
We have a single-server queue where the inter-arrival and service times have a general distribution. Claim: when \(L(T)=0\) at time \(T,\) then
\begin{equation*} \begin{split} \int_0^T \L(s)\, \d s & = \int_0^T \sum_{k=1}^{A(T)} \1{A_k \leq s < D_k} \, \d s \\ & = \sum_{k=1}^{A(T)}\int_0^T \1{A_k \leq s < D_k} \, \d s = \sum_{k=1}^{A(T)} \J_k. \end{split} \end{equation*}Solution
Did you actually try? Write your solution down first for comparison.
Show the solution
True. Job \(k\) is in the system at time \(s\) iff \(A_k \leq s < D_k.\) Since \(L(T)=0,\) every job that arrived by \(T\) has \(D_k \leq T,\) so its integral equals \(D_k - A_k = \J_k.\)
TF 2.
Claim: the following pseudocode prints \((1.9,\,\text{Long}).\)
\begin{algorithm}
\begin{algorithmic}[1]
\State \(\var{heap}\gets\cl{Heap}\rb{\pr{LexLessThan?}}\)
\State \(\var{heap}.\pr{Push}\rb{(1.9,\,\text{Long})}\)
\State \(\var{heap}.\pr{Push}\rb{(1.7,\,\text{Egg})}\)
\State \(\var{heap}.\pr{Push}\rb{(1.3,\,\text{Zeno})}\)
\State \(\pr{Print}\rb{\var{heap}.\pr{Pop}\rb{}}\)
\end{algorithmic}
\end{algorithm}
Solution
Did you actually try? Write your solution down first for comparison.
Show the solution
False. It prints \((1.3,\,\text{Zeno}),\) because \(1.3\) is the smallest first element among the tuples.
TF 3.
Claim: In the simulation of a single-server queue, the time-average number of jobs \(\E\L = \lim_{T\to\infty}\frac{1}{T}\int_0^T \L(s) \d s\) can be computed from the sojourn times \(\set{\J_k}\) alone, without tracking \(\L(s)\) at every moment.
Solution
Did you actually try? Write your solution down first for comparison.
Show the solution
True. When \(\L(T) = 0,\) \(\int_0^T \L(s) \d s = \sum_{k=1}^{A(T)} \J_k,\) so the time-average follows from the sojourn times and the simulation horizon \(T.\)
TF 4.
Claim: In a discrete-event simulation, events must be processed in the order in which they were created.
Solution
Did you actually try? Write your solution down first for comparison.
Show the solution
False. Events are processed in order of their scheduled time, not their creation order. This is precisely why a heap queue is used: it efficiently retrieves the event with the earliest time.
Exercise 5.
Suppose that we want to compute \(\bar L(t)\) for some time \(t<D_{n},\) i.e., before the departure of the last job. How would you compute this?
Solution
Did you actually try? Write your solution down first for comparison.
Show the solution
First, compute the sum of the sojourn times of all jobs that departed before \(t;\) in a formula \(\sum_{k=1}^{n}\J_k \1{D_k\leq t}.\) Then add to this the times of the jobs arrived before \(t\) but not yet departed: \(\sum_{k=1}^n (t-A_k)\1{A_k\leq t < D_{k}}.\) Divide the total by \(t.\)
Exercise 6.
Binary search finds the index \(k\) with \(A_{k-1} \leq t < A_{k}\) for a given \(t.\) Is this index \(A(t)-1,\) \(A(t)\) or \(A(t)+1\)?
Hint
Let \(k\) be the unique index with \(A_{k-1} \leq t < A_{k}.\) As the epochs \(A_k\) are increasing, \(A_j \leq t\) holds precisely for \(j = 0, \ldots, k-1.\) Count these indices.
Solution
Did you actually try? Write your solution down first for comparison.
Show the solution
We obtain \(A(t)+1.\) Let \(k\) be the index with \(A_{k-1} \leq t < A_{k}.\) Since the \(A_j\) are increasing and \(A_0 = 0,\)
\begin{align*} k = \sum_{j=0}^{\infty} \1{A_{j}\leq t} = 1 + \sum_{j=1}^{\infty} \1{A_{j}\leq t} = 1 + A(t). \end{align*}