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

Designing Simulation Experiments

A simulation is an experiment run on a computer, and its answers are estimates with noise. Day 46 said one driver costs $417 of detention a night. That is an average over 500 random nights. Is it $417 ± $5 or ± $60? When you compare two options, is the difference real or luck? Today you learn to design simulation experiments: when to throw away a warm-up, how to compare options with common random numbers, how many replications a question needs, and why the best of many noisy options always looks better than it is.

▶
Video for Day 48 coming soon

In this lesson

Today's 5-hour plan

LessonProjectBreakCommit
0:00–0:45
48.1 Terminating or steady state? The warm-up
0:45–1:45
48.2 Comparing two options: common random numbers
1:45–2:00
Break
2:00–2:45
48.3 How many replications?
2:45–3:45
48.4 The optimizer's curse; a planted bug
3:45–4:00
Break
4:00–4:45
Mini-project: how sure are we about the croissants?
4:45–5:00
Commit with Git + checklist

Update the course data

Copy the latest make_data.py from the Course data page and rebuild (python make_data.py, python day01/ladder.py, python day06/load_tables.py). New for Days 48–50: dock_shift_options (shifts a second night driver could work, with their cost) and stress_scenarios (six bad weeks for the Day 50 stress test). No new packages.

48.1 Terminating or steady state? The warm-up

There are two kinds of simulation:

  • A terminating simulation has a natural start and end. The night dock opens empty at 22:00 and closes when the last truck is unloaded. Each night is one replication, and the start is part of the question. There is no warm-up to throw away.
  • A steady-state simulation asks about the long run. Day 47's formulas describe a dock that has been running forever at a constant rate. A run that starts empty is biased at first, so the first part (the warm-up) must be thrown away.

To find the warm-up, use Welch's method: run many replications from an empty start, average the kk-th truck's wait across them, and smooth the result. The warm-up ends where the curve stops climbing. Create day48/experiments.py:

"""Day 48: designing simulation experiments. Warm-up for steady-state runs, confidence intervals for a difference,
common random numbers, and how many replications a question needs.

Import it:  from experiments import lindley_runs, mean_ci, paired_ci, independent_ci, replications_needed
"""
import numpy as np
from scipy import stats


def lindley_runs(rate, service, trucks, reps, rng):
    """reps independent runs of a one-server queue that starts empty (Lindley's recursion, Day 41).
    rate: arrivals a minute; service: the pool of unloading times to resample. Returns waits, shape (reps, trucks)."""
    gaps = rng.exponential(1 / rate, (reps, trucks))
    s = service[rng.integers(len(service), size=(reps, trucks))]
    w = np.zeros((reps, trucks))
    for k in range(1, trucks):
        w[:, k] = np.maximum(0.0, w[:, k - 1] + s[:, k - 1] - gaps[:, k])
    return w


def mean_ci(x, level=0.95):
    """Mean and the half-width of its confidence interval (t distribution: replications are few)."""
    x = np.asarray(x, dtype=float)
    t = stats.t.ppf(0.5 + level / 2, len(x) - 1)
    return x.mean(), t * x.std(ddof=1) / np.sqrt(len(x))


def paired_ci(a, b, level=0.95):
    """The difference a - b when replication i of a and of b used the same random numbers (paired)."""
    return mean_ci(np.asarray(a) - np.asarray(b), level)


def independent_ci(a, b, level=0.95):
    """The difference a - b when the two options were simulated with separate random numbers (Welch)."""
    a, b = np.asarray(a, dtype=float), np.asarray(b, dtype=float)
    va, vb = a.var(ddof=1) / len(a), b.var(ddof=1) / len(b)
    df = (va + vb) ** 2 / (va ** 2 / (len(a) - 1) + vb ** 2 / (len(b) - 1))
    return a.mean() - b.mean(), stats.t.ppf(0.5 + level / 2, df) * np.sqrt(va + vb)


def replications_needed(sd, half_width, level=0.95):
    """Replications for a confidence interval of +/- half_width, from a pilot run's standard deviation."""
    z = stats.norm.ppf(0.5 + level / 2)
    return int(np.ceil((z * sd / half_width) ** 2))

lindley_runs is Day 41's Lindley recursion, run for 400 replications at once with NumPy. Then day48/run_experiments.py:

# ---------- 48.1 Terminating or steady state? The warm-up ----------
print("--- warm-up")
w = lindley_runs(lam, u, 3_000, 400, np.random.default_rng(48))
cv = u.std(ddof=1) / u.mean()
print(f"M/G/1 at {lam * 60:.3f} trucks an hour, formula (Pollaczek-Khinchine): {pk_wait(lam, u.mean(), cv):.2f} min")
for a, b in [(0, 20), (20, 100), (100, 500), (500, 1_500), (1_500, 3_000)]:
    print(f"trucks {a + 1:>5}-{b:<5}: average wait {w[:, a:b].mean():6.2f} min")
curve = w.mean(axis=0)
smooth = pd.Series(curve).rolling(25, center=True, min_periods=1).mean()
fig, ax = plt.subplots(figsize=(8, 3.6))
ax.plot(curve, lw=0.6, color="#9aa4b2", label="average over 400 runs")
ax.plot(smooth, lw=2, color="#3b82f6", label="moving average (25 trucks)")
ax.axhline(pk_wait(lam, u.mean(), cv), ls="--", color="#e5484d", label="steady-state formula")
ax.set(xlabel="truck number (the dock starts empty)", ylabel="wait (min)", xlim=(0, 1_500),
       title="Welch's plot: how long until the queue forgets its empty start")
ax.legend(frameon=False)
fig.tight_layout()
fig.savefig("figures/day48_warmup.png", dpi=150)
print("saved figures/day48_warmup.png")
--- warm-up
M/G/1 at 1.594 trucks an hour, formula (Pollaczek-Khinchine): 70.36 min
trucks     1-20   : average wait  38.66 min
trucks    21-100  : average wait  61.22 min
trucks   101-500  : average wait  72.28 min
trucks   501-1500 : average wait  70.31 min
trucks  1501-3000 : average wait  69.58 min
saved figures/day48_warmup.png

Welch's plot for the dock

The first 20 trucks wait about half the steady-state time. The curve reaches the formula's 70 minutes after about 150 trucks. Even after that it wanders, because each truck's wait depends on the one before. To estimate the steady state, discard the first 200 or so trucks of every run. Day 47 discarded 600 minutes, which is about 16 trucks: too few for this queue, but the 20,000-hour runs made the bias negligible.

48.2 Comparing two options: common random numbers

A dealer offers a faster forklift for $90 a night. It unloads in 85% of today's time. With one driver, does it cut detention by more than $90?

# ---------- 48.2 Comparing two options: common random numbers ----------
# A dealer offers a faster forklift for $90 a night: it unloads in 85% of today's time. Worth it, with one driver?
print("--- two options")
FASTER, RENT = 0.85, 90.0
today = lambda rng: u[rng.integers(len(u))]
faster = lambda rng: FASTER * u[rng.integers(len(u))]          # the same draw, scaled: same truck, faster forklift
kw = dict(free=settings["free_minutes_before_detention"], per_hour=settings["detention_per_hour"])
n = 50
a = simulate_nights(rates, today, 3, 1, n, seed=480, **kw).detention
b_same = simulate_nights(rates, faster, 3, 1, n, seed=480, **kw).detention        # the same 50 nights
b_new = simulate_nights(rates, faster, 3, 1, n, seed=481, **kw).detention         # 50 other nights
for name, (diff, half) in [("separate random numbers", independent_ci(a, b_new)),
                           ("common random numbers", paired_ci(a, b_same))]:
    print(f"{name:>24}: the faster forklift cuts detention by ${diff:,.2f} a night +/- ${half:,.2f} ({n} nights each)")
print(f"correlation of the two options' nights: separate {np.corrcoef(a, b_new)[0, 1]:.2f}, "
      f"common {np.corrcoef(a, b_same)[0, 1]:.2f}")
--- two options
 separate random numbers: the faster forklift cuts detention by $119.92 a night +/- $190.34 (50 nights each)
   common random numbers: the faster forklift cuts detention by $182.76 a night +/- $64.96 (50 nights each)
correlation of the two options' nights: separate 0.09, common 0.97

The estimates are the same size, but the confidence intervals are not. With separate random numbers, each option meets different nights: one option may get a quiet week and the other a busy one, and that noise swamps the difference. With common random numbers (CRN), both options see the same trucks arriving at the same times, and each truck takes 85% of the same unloading time. The two options' nights are 97% correlated, so most of the noise cancels in the difference:

Var(A−B)=Var(A)+Var(B)−2 Cov(A,B)\text{Var}(A - B) = \text{Var}(A) + \text{Var}(B) - 2\,\text{Cov}(A, B)

CRN works only when the random numbers are synchronized: the same draw must mean the same thing in both options. Day 46's model draws each truck's unloading time when the truck arrives, not when it starts unloading. So truck 7 gets the same draw however long it waited. If the draw happened at the start of unloading, a different number of draws would come before it in each option and the streams would drift apart.

48.3 How many replications?

A confidence interval's half-width is about 1.96 s/n1.96\,s/\sqrt{n}. Run a pilot, estimate the standard deviation ss, then solve for nn:

n=(1.96 sh)2n = \left(\frac{1.96\, s}{h}\right)^2

# ---------- 48.3 How many replications? ----------
print("--- how many")
d46 = simulate_nights(rates, today, 3, 1, 500, seed=46, **kw).detention
m46, h46 = mean_ci(d46)
print(f"Day 46's one-driver detention, 500 nights: ${m46:,.2f} +/- ${h46:,.2f} (a night's sd is ${d46.std(ddof=1):,.0f})")
target = 10.0
sd_sep, sd_crn = np.sqrt(a.var(ddof=1) + b_new.var(ddof=1)), (a - b_same).std(ddof=1)
for name, sd in [("separate", sd_sep), ("common", sd_crn)]:
    print(f"{name:>8}: sd of a night's difference ${sd:,.2f} -> {replications_needed(sd, target):,} nights for +/- ${target:.0f}")
need = replications_needed(sd_crn, target)
a = simulate_nights(rates, today, 3, 1, need, seed=482, **kw).detention
b = simulate_nights(rates, faster, 3, 1, need, seed=482, **kw).detention
diff, half = paired_ci(a, b)
print(f"{need:,} nights, common random numbers: saves ${diff:,.2f} +/- ${half:,.2f} a night, "
      f"against ${RENT:.0f} rent: {'worth it' if diff - half > RENT else 'not worth it' if diff + half < RENT else 'too close to call'}")
--- how many
Day 46's one-driver detention, 500 nights: $417.05 +/- $61.55 (a night's sd is $701)
separate: sd of a night's difference $678.19 -> 17,669 nights for +/- $10
  common: sd of a night's difference $228.57 -> 2,007 nights for +/- $10
2,007 nights, common random numbers: saves $193.78 +/- $12.88 a night, against $90 rent: worth it
  • Day 46's $417.05 was ±$62: a night's detention varies by $700, so 500 nights pin the mean down only roughly. Report the interval, not just the number.
  • To know the forklift's saving within ±$10, separate random numbers need about 17,700 nights; CRN needs about 2,000. The same answer for a ninth of the work.
  • The final interval (±$12.88) is wider than planned, because the pilot's 50 nights underestimated the spread of a heavy-tailed quantity. If precision matters, check the interval you got and add replications.
  • The forklift saves about $194 a night against $90 rent: worth it, with the whole interval above $90.

48.4 Many options: the optimizer's curse

# ---------- 48.4 Many options: the optimizer's curse ----------
print("--- the curse")
cost = lambda seed, nights: simulate_nights(rates, today, 3, 1, nights, seed=seed, **kw).detention
estimates = [cost(1_000 + k, 30).mean() for k in range(10)]
best = int(np.argmin(estimates))
truth = cost(9_999, 3_000).mean()
print("ten estimates of the SAME option (today's dock), 30 nights each: " + ", ".join(f"{x:.0f}" for x in estimates))
print(f"the lowest looks like ${estimates[best]:,.2f} a night; 3,000 fresh nights say ${truth:,.2f}: "
      f"the winner of a noisy contest looks ${truth - estimates[best]:,.2f} better than it is")
--- the curse
ten estimates of the SAME option (today's dock), 30 nights each: 286, 356, 341, 132, 400, 340, 196, 377, 406, 441
the lowest looks like $132.42 a night; 3,000 fresh nights say $361.20: the winner of a noisy contest looks $228.79 better than it is

The ten options are identical (today's dock, ten different sets of 30 nights), yet the "best" one looks $229 cheaper than the truth. Pick the best of many noisy estimates and you pick the one that was luckiest. This is the optimizer's curse, and it is why Day 49 always re-checks a winner on fresh runs.

Decision it supports: whether a difference between options is real, and how much simulation it takes to know.

Other decisions you can support the same way: A/B tests on a website (the same statistics) · comparing staffing plans in a call centre · trying a new layout in a factory simulation.

The planted bug

day48/bug_warmup.py estimates the dock's steady-state wait (one driver, arrivals at the night's average rate all day long) from 40 runs of 60 trucks each. Run it.

w = lindley_runs(lam, u, 60, 40, np.random.default_rng(1))       # 40 runs of 60 trucks, each from an empty dock
mean, half = mean_ci(w.mean(axis=1))
print(f"steady-state wait: {mean:.2f} +/- {half:.2f} min (95% confidence, 40 runs)")
What happens, and why
steady-state wait: 56.33 +/- 11.12 min (95% confidence, 40 runs)

The answer is 56 minutes ± 11, and the interval doesn't even contain the true 70. Every run starts with an empty dock, and 60 trucks is less than the warm-up, so every run is biased low in the same direction. More replications only make the interval narrower around the wrong number: a confidence interval measures noise, not bias. Fixes: discard the warm-up (Welch's plot says about 200 trucks) and make each run much longer than that.

Mini-project: how sure are we about the croissants?

Day 45 found the critical-ratio rule earns about $194 a week more than sending each store its average. Put a 95% confidence interval on that difference, with separate and with common random numbers, and work out how many simulated weeks each needs for ±$10.

Solution
"""Day 48 mini-project: Day 45 said the critical-ratio rule earns about $194 a week more than sending each store its
average. How sure is that? Build a 95% confidence interval for the difference, with and without common random
numbers, and work out how many simulated weeks each needs for +/- $10.

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

import duckdb
import numpy as np
import pandas as pd
from scipy import stats

for folder in ("day45", "day48"):
    sys.path.insert(0, folder)
from experiments import independent_ci, paired_ci, replications_needed
from stockouts import simulate_store_days, store_day_means

con = duckdb.connect("northbound.duckdb", read_only=True)
price, cost = con.sql("SELECT transfer_price, ingredient_cost FROM bakery_range WHERE sku = 'BK-CR'").fetchall()[0]
means = store_day_means(con)
today = np.round(means["mean"]).astype(int).to_numpy()
best = stats.poisson.ppf((price - cost) / price, means["mean"]).astype(int)


def weekly_profit(quantity, seed, weeks=52):
    demand, q, sold = simulate_store_days(means, quantity, np.random.default_rng(seed), weeks=weeks)
    return (price * sold - cost * q).sum(axis=1)                # one profit per simulated week


rows = []
for name, a, b in [("separate random numbers", weekly_profit(best, 1), weekly_profit(today, 2)),
                   ("common random numbers", weekly_profit(best, 1), weekly_profit(today, 1))]:
    diff, half = (independent_ci if name.startswith("separate") else paired_ci)(a, b)
    sd = np.sqrt(a.var(ddof=1) + b.var(ddof=1)) if name.startswith("separate") else (a - b).std(ddof=1)
    rows.append((name, round(diff, 2), round(half, 2), round(sd, 2), replications_needed(sd, 10.0)))
print(pd.DataFrame(rows, columns=["comparison", "gain_a_week", "plus_minus", "sd_of_difference",
                                  "weeks_for_10_dollars"]).to_string(index=False))
             comparison  gain_a_week  plus_minus  sd_of_difference  weeks_for_10_dollars
separate random numbers       177.35       65.79            238.80                  2191
  common random numbers       187.58       20.75             74.54                   214
  • With CRN, the gain is $188 ± $21 a week from 52 weeks, consistent with Day 45's $194.
  • For ±$10, CRN needs about 210 weeks and separate random numbers about 2,200, ten times as many.
  • CRN works here because both rules face the same demand at every store on every day: only the quantities differ.

Note for Store Operations: "The new croissant rule earns $190 a week more (95% confidence: $167 to $208). The gain is real, not luck in the simulation."

Commit

git add .
git commit -m "Day 48: designing simulation experiments"
git push

Day 48 checklist

  • I know when a simulation is terminating and when it needs a warm-up, and I can find the warm-up with Welch's plot.
  • I compare options with common random numbers, and I keep the streams synchronized.
  • I report a confidence interval for a difference, paired when the runs are paired.
  • I can work out how many replications a question needs from a pilot run.
  • I know the optimizer's curse, and that more replications don't fix bias.