Prescriptive Analytics & Decision Intelligence
Overview / Module 5 / Day 47
Module 5 · Simulation and Monte Carlo · Day 47 of 80

Queueing Theory as a Check

A hundred years of queueing theory gives formulas for waiting lines. They need simple assumptions (steady arrivals at a constant rate, a long run) that real systems rarely meet, but they are perfect checks: run the simulation under the formula's assumptions, and if they disagree, the simulation is wrong. Then use the simulation for the cases the formulas can't handle. Today you check Day 46's model and learn where the formulas stop working.

▶
Video for Day 47 coming soon

In this lesson

Today's 5-hour plan

LessonProjectBreakCommit
0:00–0:45
47.1 M/M/1 and M/M/c
0:45–1:45
47.2 Real unloading times; 47.3 Little's law
1:45–2:00
Break
2:00–2:45
47.4 The real night: where formulas stop
2:45–3:45
Units; a planted bug
3:45–4:00
Break
4:00–4:45
Mini-project: a promise to the carriers
4:45–5:00
Commit with Git + checklist

47.1 M/M/1 and M/M/c

Kendall's notation: arrivals / service / servers. M means Markovian: Poisson arrivals or exponential service times; G means any distribution. With arrival rate λ\lambda, mean service time ss, cc servers and utilization ρ=λs/c<1\rho = \lambda s / c < 1:

QueueAverage wait before service WqW_q
M/M/1ρ1−ρ s\frac{\rho}{1-\rho}\, s
M/M/cC(c,λs)⋅sc(1−ρ)C(c, \lambda s) \cdot \frac{s}{c(1-\rho)}, with CC Erlang's formula for the chance of waiting
M/G/1 (Pollaczek–Khinchine)ρ1−ρ⋅1+cvs22 s\frac{\rho}{1-\rho} \cdot \frac{1 + cv_s^2}{2}\, s
G/G/c (Allen–Cunneen, approximate)Wq(M/M/c)⋅cva2+cvs22W_q(\text{M/M/c}) \cdot \frac{cv_a^2 + cv_s^2}{2}

The 11−ρ\frac{1}{1-\rho} is Day 41's lesson as a formula: at 80% busy, waits are 4 times the service time; at 90%, 9 times; at 100%, infinite. Create day47/queueing.py:

"""Day 47: queueing formulas, to check a simulation (and to size a resource in a minute).
Rates are per minute, times in minutes: keep one unit of time everywhere.

Import it:  from queueing import mm1_wait, erlang_c, mmc_wait, mmc_wait_over, pk_wait, allen_cunneen
"""
import math


def utilization(lam, mean_service, servers=1):
    rho = lam * mean_service / servers
    if rho >= 1:
        raise ValueError(f"utilization {rho:.2f} >= 1: the line grows without limit, no steady state")
    return rho


def mm1_wait(lam, mean_service):
    """M/M/1: Poisson arrivals, exponential service, one server. Average wait before service."""
    rho = utilization(lam, mean_service)
    return rho / (1 - rho) * mean_service


def erlang_c(lam, mean_service, servers):
    """M/M/c: the chance that an arriving customer has to wait (Erlang's C formula)."""
    a = lam * mean_service                                   # offered load, in servers
    rho = utilization(lam, mean_service, servers)
    top = a ** servers / math.factorial(servers) / (1 - rho)
    return top / (sum(a ** k / math.factorial(k) for k in range(servers)) + top)


def mmc_wait(lam, mean_service, servers):
    """M/M/c: average wait before service."""
    return erlang_c(lam, mean_service, servers) * mean_service / (servers * (1 - utilization(lam, mean_service, servers)))


def mmc_wait_over(lam, mean_service, servers, t):
    """M/M/c: the chance that a customer waits more than t."""
    mu = 1 / mean_service
    return erlang_c(lam, mean_service, servers) * math.exp(-(servers * mu - lam) * t)


def pk_wait(lam, mean_service, cv_service):
    """M/G/1 (Pollaczek-Khinchine): any service distribution, through its coefficient of variation."""
    rho = utilization(lam, mean_service)
    return rho / (1 - rho) * (1 + cv_service ** 2) / 2 * mean_service


def allen_cunneen(lam, mean_service, servers, cv_arrival, cv_service):
    """G/G/c approximation: the M/M/c wait scaled by the variability of arrivals and service."""
    return mmc_wait(lam, mean_service, servers) * (cv_arrival ** 2 + cv_service ** 2) / 2

Then day47/run_queueing.py runs Day 46's SimPy model with a constant arrival rate (the night's average) for 20,000 hours, five times:

def steady(lam_per_hour, unload, drivers, hours=20_000, reps=5, seed=47):
    """Long runs at a constant rate: the steady state that the formulas describe. Near full utilization one long
    run is not enough (each wait depends on the one before), so: 5 independent runs, and a confidence interval."""
    waits = []
    for k in range(reps):
        t = simulate_night([lam_per_hour] * hours, unload, drivers, drivers, np.random.default_rng(seed + k))
        t = t[t.arrived > 600]                                  # drop the first 10 hours (warm-up)
        waits.append((t.start - t.arrived).mean())
    half = 1.96 * np.std(waits, ddof=1) / np.sqrt(reps)
    return np.mean(waits), half, t


# ---------- 47.1 Exponential unloading: M/M/1 and M/M/2 ----------
rng = np.random.default_rng(1)
rows = []
for c, formula in [(1, mm1_wait(lam, mean_s)), (2, mmc_wait(lam, mean_s, 2))]:
    w, half, _ = steady(lam_h, lambda: rng.exponential(mean_s), c)
    rows.append((f"M/M/{c}", round(formula, 2), round(w, 2), round(half, 2)))
# ---------- 47.2 Real unloading times: M/G/1 and G/G/2 ----------
for c, formula in [(1, pk_wait(lam, mean_s, cv_s)), (2, allen_cunneen(lam, mean_s, 2, 1.0, cv_s))]:
    w, half, t = steady(lam_h, lambda: u[rng.integers(len(u))], c)
    rows.append((f"M/G/{c}", round(formula, 2), round(w, 2), round(half, 2)))
print(pd.DataFrame(rows, columns=["model", "formula_wait", "simulated_wait", "plus_minus_95"]).to_string(index=False))
average arrival rate 1.594 trucks an hour = 0.0266 a minute; unloading 29.75 min (cv 0.51)
model  formula_wait  simulated_wait  plus_minus_95
M/M/1        112.09          108.34           5.91
M/M/2          5.50            5.47           0.25
M/G/1         70.36           71.01           3.63
M/G/2          3.45            3.59           0.07

The formulas and the simulation agree, within the simulation's confidence interval (Allen–Cunneen, an approximation, within 4%). Day 46's model passes the check. Notice the intervals: at 79% busy with one driver, even 20,000 hours give ±6 minutes, because each truck's wait depends on the one before. Near full utilization, simulations need long runs and replications.

47.3 Little's law

L=λWL = \lambda W: the average number in a system equals the arrival rate times the average time spent there. It holds for any queue, any distribution, any discipline, in the long run. It's the simplest check on any simulation's bookkeeping.

# ---------- 47.3 Little's law ----------
span = t.end.max() - t.arrived.min()
in_line = (t.start - t.arrived).sum() / span                    # time-average number of trucks waiting
print(f"Little's law, M/G/2 run: trucks waiting on average {in_line:.4f}; "
      f"arrival rate x average wait = {len(t) / span:.4f} x {(t.start - t.arrived).mean():.2f} = "
      f"{len(t) / span * (t.start - t.arrived).mean():.4f}")
Little's law, M/G/2 run: trucks waiting on average 0.0989; arrival rate x average wait = 0.0266 x 3.71 = 0.0989

47.4 The real night: where formulas stop

# ---------- 47.4 The real night: formulas against the simulation ----------
rates = hourly_rates(log)
night = simulate_nights(rates, lambda r: u[r.integers(len(u))], 3, 1, 500, seed=46)
print(f"Day 46 simulation, 1 driver, real nights: average wait {night.mean_wait.mean():.2f} min")
print(f"formula at the night's average rate ({lam_h:.2f}/h): {pk_wait(lam, mean_s, cv_s):.2f} min")
for name, peak in [("the busiest hour", rates.max())]:
    rho = peak * mean_s / 60
    print(f"formula at {name} ({peak:.2f}/h): utilization {rho:.2f}: "
          + ("no steady state, the line grows all hour" if rho >= 1 else f"{pk_wait(peak / 60, mean_s, cv_s):.2f} min"))
print(f"with 2 drivers: simulation {simulate_nights(rates, lambda r: u[r.integers(len(u))], 3, 2, 500, seed=46).mean_wait.mean():.2f} min, "
      f"formula (average rate) {allen_cunneen(lam, mean_s, 2, 1.0, cv_s):.2f} min, "
      f"formula (busiest hour) {allen_cunneen(rates.max() / 60, mean_s, 2, 1.0, cv_s):.2f} min")
Day 46 simulation, 1 driver, real nights: average wait 47.95 min
formula at the night's average rate (1.59/h): 70.36 min
formula at the busiest hour (2.92/h): utilization 1.45: no steady state, the line grows all hour
with 2 drivers: simulation 5.22 min, formula (average rate) 3.45 min, formula (busiest hour) 20.47 min
  • At the night's average rate, the formula says 70 minutes, more than the simulated 48: real nights start with an empty dock and last only 8 hours, so the line never reaches the steady state the formula describes.
  • At the busiest hour (2.92 trucks an hour), one driver is 145% busy: the formula has no answer, because no steady state exists.
  • With two drivers, the formula at the average rate says 3.5 minutes, at the busiest hour 20.5; the simulation's 5.2 lies between.

Formulas answer quickly and check simulations; time-varying arrivals, short horizons and starting conditions need the simulation. A useful habit: the formula at the average and at the peak rate bracket the truth.

Decision it supports: quick sizing of servers, and checks that a simulation is built right.

Other decisions you can support the same way: call-centre staffing (Erlang C is the industry's standard) · server capacity for a website · hospital emergency rooms.

The planted bug

day47/bug_units.py checks the dock with the M/M/1 formula. Run it.

log = con.sql("SELECT * FROM receiving_log").df()
lam = len(log) / log.night_of.nunique() / 8                    # trucks an hour
service = log.unload_minutes.mean()                            # minutes a truck
rho = lam * service
wait = rho / (1 - rho) * service
print(f"utilization {rho:.2f}; average wait {wait:.1f} minutes: the dock is fine")
What happens, and why
utilization 47.42; average wait -30.4 minutes: the dock is fine

A utilization of 47 and a negative wait, reported as "fine". The arrival rate is per hour, the service time in minutes: their product is 60 times too big. Two checks would have caught it: put every rate and time in one unit (Day 47's queueing.py uses minutes throughout), and never use a queueing formula without checking ρ<1\rho < 1 (utilization raises an error).

Mini-project: a promise to the carriers

Carriers ask for a promise: "90% of trucks start unloading within 30 minutes". How many night drivers does that take? Answer first with the M/M/c formula, P(Wq>t)=C(c,λs) e−(c/s−λ)tP(W_q > t) = C(c, \lambda s)\, e^{-(c/s - \lambda) t}, at the average and at the busiest hour; then check with Day 46's simulation of real nights.

Solution
"""Day 47 mini-project: carriers ask for a promise: "90% of trucks start unloading within 30 minutes".
How many night drivers would that take? Answer in a minute with the M/M/c formula, then check with Day 46's simulation.

Run from the repository root (after day06/load_tables.py):  python day47/mini_project_promise.py
"""
import sys

import duckdb
import numpy as np
import pandas as pd

for folder in ("day46", "day47"):
    sys.path.insert(0, folder)
from dock import hourly_rates, load_receiving, simulate_night
from queueing import mmc_wait_over

pd.set_option("display.width", 160)
con = duckdb.connect("northbound.duckdb", read_only=True)
log, settings = load_receiving(con)
u = log.unload_minutes.to_numpy()
rates = hourly_rates(log)
avg, peak = len(log) / log.night_of.nunique() / 8 / 60, rates.max() / 60
rows = []
for c in (1, 2, 3):
    def formula(lam):
        try:
            return round(1 - mmc_wait_over(lam, u.mean(), c, 30), 3)
        except ValueError:
            return "overloaded"
    rng = np.random.default_rng(470)
    waits = np.concatenate([(lambda t: (t.start - t.arrived).to_numpy())(
        simulate_night(rates, lambda: u[rng.integers(len(u))], 3, c, rng)) for _ in range(500)])
    rows.append((c, formula(avg), formula(peak), round(float((waits <= 30).mean()), 3)))
print(pd.DataFrame(rows, columns=["drivers", "formula_average_rate", "formula_busiest_hour", "simulated_real_nights"])
      .to_string(index=False))
 drivers  formula_average_rate formula_busiest_hour  simulated_real_nights
       1                 0.360           overloaded                  0.475
       2                 0.934                0.653                  0.927
       3                 0.995                0.955                  0.994
  • One driver can't promise anything: half the trucks wait more than 30 minutes.
  • Two drivers: the formula at the average rate says 93%, at the busiest hour 65%; the simulation of real nights says 92.7%. The promise can be made, just.
  • Three drivers would give 99%.

Note to the DC manager: "With two night drivers (Day 46) we can promise carriers that 90% of trucks start unloading within 30 minutes; we'd meet it at about 93%. The promise fails during the 00:00–02:00 peak on busy nights: offer appointment slots outside the peak to the carriers that arrive then."

Commit

git add .
git commit -m "Day 47: queueing formulas as a check"
git push

Then run the tests: tests/test_risk_and_queues.py checks Days 44–47 (whole-week errors, disruption-free years, the Poisson formula against simulation, known queueing answers, one driver at a time in SimPy). Add "day44" to "day47" to the folders in conftest.py.

"""Module 5, Days 44-47: correlated risks, stock-outs, the SimPy dock and queueing formulas."""
import numpy as np
import pandas as pd
import pytest
from correlated import demand_weeks, simulate_years
from dock import simulate_night
from queueing import erlang_c, mm1_wait, mmc_wait, utilization
from stockouts import poisson_check, simulate_store_days, store_day_means


def test_whole_weeks_move_products_together(con):
    week = demand_weeks(con, np.random.default_rng(0), together=True)
    cap = {"A": 10.0, "B": 20.0, "C": 5.0}
    d = week(cap, {"A": "bread", "B": "bread", "C": "cake"})
    assert d["A"] / 10 == pytest.approx(d["B"] / 20)


def test_years_without_disruptions_are_just_the_weeks():
    events = pd.DataFrame({"event": ["x"], "chance_per_week": [0.0]})
    annual, count = simulate_years(np.ones(52 * 3), events, {"x": 100.0}, np.random.default_rng(0), years=3)
    assert list(annual) == [52, 52, 52] and count.sum() == 0


def test_poisson_formula_matches_simulation(con):
    means = store_day_means(con)
    q = np.round(means["mean"]).astype(int)
    p_out, _ = poisson_check(means, q)
    demand, qq, sold = simulate_store_days(means, q, np.random.default_rng(1), weeks=400)
    assert (demand > qq).mean() == pytest.approx(p_out, abs=0.01)


def test_queueing_formulas():
    assert mm1_wait(0.5, 1.0) == pytest.approx(1.0)
    assert erlang_c(0.5, 1.0, 1) == pytest.approx(0.5)                   # one server: P(wait) = utilization
    assert mmc_wait(1.0, 1.0, 2) == pytest.approx(1 / 3)
    with pytest.raises(ValueError):
        utilization(2.0, 1.0)


def test_simpy_night_respects_one_driver():
    t = simulate_night([2.0] * 4, lambda: 25.0, 3, 1, np.random.default_rng(2)).sort_values("start")
    assert (t.start >= t.arrived).all()
    assert (t.start.to_numpy()[1:] >= t.end.to_numpy()[:-1] - 1e-9).all()   # one truck unloads at a time
70 passed

Day 47 checklist

  • I know M/M/1, M/M/c, M/G/1 and an approximation for G/G/c, and when they apply.
  • I checked a simulation against formulas under the formulas' assumptions.
  • I used Little's law to check a simulation's bookkeeping.
  • I can explain why formulas fail for time-varying, short, empty-start systems.
  • I keep one unit of time, and check utilization before using a formula.