- the Day 43 routes planned with a 5% time buffer;
- the Day 45 critical-ratio croissants;
- the Day 49 second driver from 23:00 to 05:00.
The question for management: does the network hold up when bad things happen, and do the recommendations still pay when they do?
50.1 The brief, the scenarios and the two policies
| Scenario | What happens |
|---|---|
| normal | weeks drawn from history |
| holiday_rush | December demand weeks (Day 44's whole weeks), stores +15%, trucks +25% |
| snowstorm_week | every morning snows (Day 42's snow trips), stores −10% |
| oven_breakdown | ovens at 70% all week: the bakery re-plans (Day 44) |
| dock_surge | 40% more trucks at night |
| perfect_storm | all of it at once |
Create day50/stress.py. It reuses a module's worth of code: Day 6's bakery model, Day 37's routes, Day 42's trip sampler, Day 44's whole weeks, Day 45's stores and Day 49's driver shifts:
"""Day 50 capstone: one simulated week of the Northbound network (bakery, morning routes, store croissants, the
night dock), under a stress scenario and an operating policy.
Import it: from stress import load_network, stress_test
"""
import numpy as np
import pandas as pd
import pyomo.environ as pyo
from scipy import stats
from bakery import build_model, load_data, solve
from correlated import error_table
from dock import hourly_rates, load_receiving
from inputs import clean_trips, load_trips, travel_sampler
from montecarlo import bakery_economics, bakery_profit, drive_routes
from routing import load_run
from shifts import evaluate_option
from stockouts import simulate_store_days, store_day_means
from vrptw import load_fleet, simulate, solve_vrptw
POLICIES = {
"today": {"routes": "day37", "croissants": "average", "second_driver": "none"},
"recommended": {"routes": "buffer_1.05", "croissants": "critical_ratio", "second_driver": "6h_from_23"},
}
def load_network(con):
"""Everything the weekly simulation needs, prepared once: plans, histories and settings."""
net = {"con": con}
d = load_data(con)
net["bakery"], net["econ"] = d, bakery_economics(con)
net["make"] = {}
for left in sorted(set(con.sql("SELECT oven_capacity_left FROM stress_scenarios").df().oven_capacity_left)):
week = {**d, "capacity": {**d["capacity"], "oven_hours": d["capacity"]["oven_hours"] * left}}
m = build_model(week)
solve(m) # the plan the bakery makes with the ovens it has
net["make"][left] = {p: pyo.value(m.x[p]) for p in m.P if pyo.value(m.x[p]) > 1e-6}
e = error_table(con)
net["errors"] = {"bread": ((e["BK-SD"] + e["BK-WW"]) / 2).to_numpy(), "other": e["BK-CR"].to_numpy(),
"december": np.array([w.month == 12 for w in pd.to_datetime(e.index)])}
stops, ids, km, minutes = load_run(con)
fleet = load_fleet(con)
net["routes"] = {"stops": stops, "ids": ids, "minutes": minutes, "trips": clean_trips(load_trips(con))[0]}
net["route_plans"], net["fleet_cost"] = {}, {}
for name, buffer in [("day37", 1.00), ("buffer_1.05", 1.05), ("buffer_1.30", 1.30)]:
padded = np.ceil(minutes * buffer)
plan = solve_vrptw(stops, ids, km, padded, fleet)
net["route_plans"][name], net["fleet_cost"][name] = plan, simulate(plan, stops, ids, km, padded, fleet)[0]
price, cost = con.sql("SELECT transfer_price, ingredient_cost FROM bakery_range WHERE sku = 'BK-CR'").fetchall()[0]
means = store_day_means(con)
net["croissant"] = {"means": means, "price": price, "cost": cost,
"average": np.round(means["mean"]).astype(int).to_numpy(),
"critical_ratio": stats.poisson.ppf((price - cost) / price, means["mean"]).astype(int)}
log, settings = load_receiving(con)
net["dock"] = {"rates": hourly_rates(log), "unload": log.unload_minutes.to_numpy(), "settings": settings,
"options": con.sql("SELECT * FROM dock_shift_options").df().set_index("option")}
net["scenarios"] = con.sql("SELECT * FROM stress_scenarios").df().set_index("scenario")
return net
def driver_shifts(options, name):
o = options.loc[name]
if o.hours == 0:
return [(0, None)]
start, end = int(o.start_after_22h_minutes), int(o.start_after_22h_minutes + 60 * o.hours)
return [(0, None), (start, None if end >= 480 else end)]
def stress_test(net, scenario, policy, weeks, seed, arrivals_factor=None):
"""`weeks` simulated weeks of the network. Each part draws from its own random stream (seeded from `seed`),
so two policies run with the same seed face the same weeks: common random numbers."""
s = net["scenarios"].loc[scenario]
pol = POLICIES[policy] if isinstance(policy, str) else policy
r_bak, r_rt, r_cr, r_dk = (np.random.default_rng([seed, k]) for k in range(4))
# bakery: whole historical weeks of forecast errors (Day 44); December only in a holiday scenario
e, d = net["errors"], net["bakery"]
pool = np.flatnonzero(e["december"]) if s.demand_weeks == "december" else np.arange(len(e["bread"]))
make = net["make"][s.oven_capacity_left]
bakery = []
for _ in range(weeks):
k = pool[r_bak.integers(len(pool))]
demand = {p: c * (e["bread"][k] if d["category"][p] == "bread" else e["other"][k]) for p, c in d["cap"].items()}
bakery.append(bakery_profit(make, demand, net["econ"]))
# morning routes: six mornings a week, one weather a morning (all snow in a snowstorm week)
rt = net["routes"]
plan = net["route_plans"][pol["routes"]]
morning = travel_sampler(rt["trips"], r_rt, {"snow": 1.0} if s.weather == "snow" else None)
late = []
for _ in range(weeks):
n = 0
for _ in range(6):
_, factor = morning()
n += sum(v > 0 for v in drive_routes(plan, rt["stops"], rt["ids"], rt["minutes"], factor).values())
late.append(n)
# store croissants: Poisson demand with a chain-wide factor each day (Day 45.5)
c = net["croissant"]
means = c["means"].assign(mean=c["means"]["mean"] * s.store_demand_factor)
dem, q, sold = simulate_store_days(means, c[pol["croissants"]], r_cr, weeks=weeks, common_sd=0.10)
margin = (c["price"] * sold - c["cost"] * q).sum(axis=1)
days_out = (dem > q).mean(axis=1)
# the night dock: six nights a week, more trucks in a surge
k = net["dock"]
st = k["settings"]
factor = s.truck_arrivals_factor if arrivals_factor is None else arrivals_factor
nights = evaluate_option(k["rates"] * factor, lambda g: k["unload"][g.integers(len(k["unload"]))], int(st["doors"]),
driver_shifts(k["options"], pol["second_driver"]), 6 * weeks, seed=int(r_dk.integers(1 << 31)),
free=st["free_minutes_before_detention"], per_hour=st["detention_per_hour"])
nights["week"] = np.repeat(np.arange(weeks), 6)
w = nights.groupby("week").sum()
driver = 6 * k["options"].cost_per_night[pol["second_driver"]]
return pd.DataFrame({"bakery_profit": bakery, "late_deliveries": late,
"fleet_cost": 6 * net["fleet_cost"][pol["routes"]],
"croissant_margin": margin, "croissant_days_out": days_out,
"dock_cost": w.detention.to_numpy() + driver,
"trucks_within_30": (w.on_time / w.trucks).to_numpy()})
Each part of the network draws from its own random stream, seeded from the same number. The two policies therefore face exactly the same weeks (Day 48's common random numbers).
# ---------- 50.1 The scenarios and the two policies ----------
print("--- scenarios")
print(net["scenarios"].to_string())
for name, pol in POLICIES.items():
print(f"{name:>12}: " + "; ".join(f"{k} {v}" for k, v in pol.items()))
print("fleet cost a day: " + ", ".join(f"{k} ${v:,.2f}" for k, v in net["fleet_cost"].items()))
--- scenarios
demand_weeks store_demand_factor weather oven_capacity_left truck_arrivals_factor
scenario
normal all 1.00 draw 1.0 1.00
holiday_rush december 1.15 draw 1.0 1.25
snowstorm_week all 0.90 snow 1.0 1.00
oven_breakdown all 1.00 draw 0.7 1.00
dock_surge all 1.00 draw 1.0 1.40
perfect_storm december 1.15 snow 0.7 1.40
today: routes day37; croissants average; second_driver none
recommended: routes buffer_1.05; croissants critical_ratio; second_driver 6h_from_23
fleet cost a day: day37 $864.50, buffer_1.05 $860.22, buffer_1.30 $934.23
50.2 One week of the network
# ---------- 50.2 One scenario, both policies ----------
print("--- normal week")
runs = {(s, p): stress_test(net, s, p, WEEKS, seed=50) for s in net["scenarios"].index for p in POLICIES}
summary = {p: runs[("normal", p)].agg(["mean", lambda x: x.quantile(0.05), "median", lambda x: x.quantile(0.95)])
.set_axis(["mean", "p5", "median", "p95"]) for p in POLICIES}
print(pd.concat(summary).round(2).to_string())
--- normal week
bakery_profit late_deliveries fleet_cost croissant_margin croissant_days_out dock_cost trucks_within_30
today mean 105747.96 5.50 5187.00 5637.36 0.39 2189.57 0.49
p5 102289.04 3.00 5187.00 5256.65 0.32 333.95 0.30
median 107210.87 5.00 5187.00 5638.50 0.39 1891.61 0.48
p95 108351.28 9.00 5187.00 5978.00 0.47 5577.10 0.67
recommended mean 105747.96 1.42 5161.32 5826.87 0.23 1228.20 0.92
p5 102289.04 0.00 5161.32 5305.95 0.17 1200.00 0.82
median 107210.87 1.00 5161.32 5825.00 0.22 1200.00 0.93
p95 108351.28 4.05 5161.32 6308.00 0.29 1343.05 0.99
In a normal week the bakery's result is the same under both policies: the recommendations don't touch the production plan. The other three parts all improve:
- Late deliveries: 1.4 a week instead of 5.5.
- Croissants: shelves empty on 23% of store-days instead of 39%, with a higher margin.
- The dock: $1,228 a week instead of $2,190, and 92% of trucks within 30 minutes instead of 49%.
The recommended dock cost is also predictable: its 95th percentile is $1,343 a week, against $5,577 today.
50.3 Six scenarios
# ---------- 50.3 All six scenarios ----------
print("--- stress table")
def kpis(r):
return {"bakery_mean": r.bakery_profit.mean(), "bakery_p5": np.quantile(r.bakery_profit, 0.05),
"late_a_week": r.late_deliveries.mean(), "late_p95": np.quantile(r.late_deliveries, 0.95),
"days_out": r.croissant_days_out.mean(), "croissant_margin": r.croissant_margin.mean(),
"dock_cost": r.dock_cost.mean(), "dock_p95": np.quantile(r.dock_cost, 0.95),
"within_30": r.trucks_within_30.mean()}
table = pd.DataFrame([{"scenario": s, "policy": p, **kpis(r)} for (s, p), r in runs.items()])
print(table.round({"bakery_mean": 0, "bakery_p5": 0, "late_a_week": 2, "late_p95": 0, "days_out": 3,
"croissant_margin": 0, "dock_cost": 0, "dock_p95": 0, "within_30": 3})
.to_string(index=False))
print("--- recommended minus today: croissant margin - dock cost - fleet cost, a week")
for s in net["scenarios"].index:
a, b = runs[(s, "recommended")], runs[(s, "today")]
gain = (a.croissant_margin - a.dock_cost - a.fleet_cost) - (b.croissant_margin - b.dock_cost - b.fleet_cost)
m, h = paired_ci(gain, np.zeros(len(gain)))
print(f"{s:>15}: ${m:,.2f} +/- ${h:,.2f} a week; late deliveries {a.late_deliveries.mean() - b.late_deliveries.mean():+.2f}")
--- stress table
scenario policy bakery_mean bakery_p5 late_a_week late_p95 days_out croissant_margin dock_cost dock_p95 within_30
normal today 105748.0 102289.0 5.50 9.0 0.391 5637.0 2190.0 5577.0 0.487
normal recommended 105748.0 102289.0 1.42 4.0 0.227 5827.0 1228.0 1343.0 0.921
holiday_rush today 107717.0 105783.0 5.50 9.0 0.526 6204.0 5546.0 11425.0 0.344
holiday_rush recommended 107717.0 105783.0 1.42 4.0 0.346 6694.0 1330.0 1820.0 0.865
snowstorm_week today 105748.0 102289.0 16.47 22.0 0.299 5134.0 2190.0 5577.0 0.487
snowstorm_week recommended 105748.0 102289.0 10.43 16.0 0.156 5124.0 1228.0 1343.0 0.921
oven_breakdown today 81121.0 78411.0 5.50 9.0 0.391 5637.0 2190.0 5577.0 0.487
oven_breakdown recommended 81121.0 78411.0 1.42 4.0 0.227 5827.0 1228.0 1343.0 0.921
dock_surge today 105748.0 102289.0 5.50 9.0 0.391 5637.0 9090.0 17930.0 0.278
dock_surge recommended 105748.0 102289.0 1.42 4.0 0.227 5827.0 1480.0 2393.0 0.807
perfect_storm today 82623.0 81176.0 16.47 22.0 0.526 6204.0 9090.0 17930.0 0.278
perfect_storm recommended 82623.0 81176.0 10.43 16.0 0.346 6694.0 1480.0 2393.0 0.807
--- recommended minus today: croissant margin - dock cost - fleet cost, a week
normal: $1,176.55 +/- $177.62 a week; late deliveries -4.07
holiday_rush: $4,732.44 +/- $320.25 a week; late deliveries -4.07
snowstorm_week: $976.94 +/- $177.34 a week; late deliveries -6.05
oven_breakdown: $1,176.55 +/- $177.62 a week; late deliveries -4.07
dock_surge: $7,824.45 +/- $469.86 a week; late deliveries -4.07
perfect_storm: $8,125.52 +/- $469.89 a week; late deliveries -6.05

- The recommendations pay in every scenario, and the worse the week, the more they pay: $1,177 ± $178 a week in a normal week, $4,732 in a holiday rush, and $7,800–$8,100 in a dock surge or the perfect storm. That is a sign of a robust policy: it helps most when help is most needed.
- The bakery's risk is the ovens: a breakdown week costs about $24,600 whatever the policy. Day 44's maintenance contract is the answer there, not the weekly plan.
- Snow beats the route buffer: 10.4 late deliveries a week instead of 16.5. Better, but still twice a normal week under today's plan (5.5).
- A dock surge breaks the 30-minute promise (81% within 30 minutes), even though detention stays low.
50.4 Breaking points
A stress test should also find where the system breaks:
# ---------- 50.4 Breaking points ----------
print("--- breaking point")
rows = []
for factor in (1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6):
row = {"truck_arrivals": f"x{factor:.1f}"}
for driver in ("6h_from_23", "all_night"):
pol = {**POLICIES["recommended"], "second_driver": driver}
r = stress_test(net, "normal", pol, 100, seed=51, arrivals_factor=factor)
row[f"{driver}_within_30"] = round(r.trucks_within_30.mean(), 3)
row[f"{driver}_cost_a_night"] = round(r.dock_cost.mean() / 6, 2)
rows.append(row)
print(pd.DataFrame(rows).to_string(index=False))
print("--- a snow-day plan")
for routes in ("day37", "buffer_1.05", "buffer_1.30"):
r = stress_test(net, "snowstorm_week", {**POLICIES["recommended"], "routes": routes}, WEEKS, seed=50)
print(f"{routes:>12}: fleet ${net['fleet_cost'][routes]:,.2f} a day; snowstorm week {r.late_deliveries.mean():.2f} late "
f"(p95 {np.quantile(r.late_deliveries, 0.95):.0f})")
--- breaking point
truck_arrivals 6h_from_23_within_30 6h_from_23_cost_a_night all_night_within_30 all_night_cost_a_night
x1.0 0.907 209.27 0.922 251.77
x1.1 0.886 211.59 0.907 252.96
x1.2 0.871 214.61 0.894 255.74
x1.3 0.821 237.34 0.847 272.81
x1.4 0.802 243.98 0.833 275.94
x1.5 0.774 280.94 0.808 292.36
x1.6 0.704 340.69 0.742 337.32
--- a snow-day plan
day37: fleet $864.50 a day; snowstorm week 16.47 late (p95 22)
buffer_1.05: fleet $860.22 a day; snowstorm week 10.43 late (p95 16)
buffer_1.30: fleet $934.23 a day; snowstorm week 8.50 late (p95 14)
- The 23:00–05:00 driver keeps the promise only at today's volume (90.7%). 10% more trucks breaks it. A second driver all night lasts to about +10%. Beyond that, the promise needs a third driver at the peak, or appointment slots that move trucks out of 00:00–02:00 (Day 47's note).
- A snow-day route plan (travel times × 1.30, re-planned the evening before) cuts snow-week late deliveries only from 10.4 to 8.5, for $74 a day more. Snow is mostly beyond what a buffer can fix. Ask the cafés to widen their windows on snow days, or dispatch earlier (Day 37).
50.5 The memo
A model memo
To: the Northbound operations committee. Re: how the network holds up in a bad week.
"We simulated 300 weeks of the whole network (bakery, morning deliveries, store croissants, the Montreal night dock) under six scenarios, from a normal week to a holiday rush with snow, an oven breakdown and 40% more trucks at once.
Adopt three changes now. They cost nothing to try and pay in every scenario:
- Plan delivery routes with 5% extra travel time: 4 fewer late deliveries a week, at the same fleet cost.
- Send each store the croissants it sells out of only 29% of the time: 16 fewer empty-shelf days in every 100, and higher margin.
- Add a second night forklift driver from 23:00 to 05:00 ($200 a night): it keeps the carriers' 30-minute promise at today's volume.
Together they save about $1,200 in a normal week and $8,000 in a bad one.
Three risks remain:
- Oven breakdowns cost about $25,000 a week each time. Sign the maintenance contract (Day 44).
- Snow: late deliveries rise three- to sevenfold however we plan. Agree wider windows with the cafés for snow days.
- Growth at the dock: 10% more night trucks breaks the 30-minute promise. Before volumes grow, introduce appointment slots for carriers arriving between midnight and 02:00, or plan a second driver all night."
Module 5 wrap-up
| Day | Idea | Northbound decision |
|---|---|---|
| 41 | The flaw of averages | Plans look better at the forecast than they are |
| 42 | Input distributions | Trip times by weather; forecast errors |
| 43 | Monte Carlo | The production plan's and the routes' risk |
| 44 | Correlated risks, disruptions | Holiday weeks; an oven maintenance contract |
| 45 | Service vs waste | Croissants for 40 stores |
| 46 | Discrete-event simulation | A second night driver |
| 47 | Queueing formulas | Checking the dock model; a promise to carriers |
| 48 | Experiment design, CRN | A faster forklift? How sure are we? |
| 49 | Simulation-optimization | The cheapest dock that keeps the promise |
| 50 | Stress testing | The network in a bad week |
Module 6 turns these simulations into decisions made under uncertainty: the newsvendor in general (Day 51), stochastic programs that plan for many scenarios at once, and robust plans.
Commit and tag
git add .
git commit -m "Day 50: capstone, stress-testing the network"
git tag v5.0-module5
git push
git push --tags
Then run the tests: tests/test_experiments_and_search.py checks Days 48–50. It covers a paired difference with no noise, the replication formula, Lindley's recursion against M/M/1 after the warm-up, two all-night drivers against Day 46, one driver before a shift starts, and the shift options. Add "day48", "day49" and "day50" to the folders in conftest.py.
"""Known answers for Days 48-50: confidence intervals, the warm-up queue, driver shifts."""
import numpy as np
import pandas as pd
import pytest
from dock import simulate_night
from experiments import lindley_runs, paired_ci, replications_needed
from queueing import mm1_wait
from shifts import simulate_night_shifts
from stress import driver_shifts
def test_paired_and_replications():
a = np.array([10.0, 12.0, 9.0, 15.0])
assert paired_ci(a, a - 2.0) == pytest.approx((2.0, 0.0)) # a constant difference has no noise at all
assert replications_needed(100.0, 10.0) == 385 # (1.96 x 100 / 10)^2 = 384.1 -> 385
def test_lindley_matches_mm1_after_warm_up():
rng = np.random.default_rng(0)
service = rng.exponential(10.0, 200_000) # exponential service, mean 10 min
w = lindley_runs(0.05, service, 3_000, 200, np.random.default_rng(1)) # utilization 0.5
assert w[:, 500:].mean() == pytest.approx(mm1_wait(0.05, 10.0), rel=0.05)
def test_two_drivers_all_night_is_day_46():
rates = [1.5, 2.5, 3.0, 2.0, 1.0, 1.0, 1.0, 1.0]
a = simulate_night(rates, lambda: 25.0, 3, 2, np.random.default_rng(5))
b = simulate_night_shifts(rates, lambda: 25.0, 3, [(0, None), (0, None)], np.random.default_rng(5))
pd.testing.assert_frame_equal(a, b)
def test_one_driver_before_the_shift():
t = simulate_night_shifts([3.0] * 8, lambda: 30.0, 3, [(0, None), (120, 240)], np.random.default_rng(3))
early = t[t.start < 120].sort_values("start")
assert (early.start.to_numpy()[1:] >= early.end.to_numpy()[:-1] - 1e-9).all() # one at a time before 00:00
def test_shift_options():
options = pd.DataFrame({"start_after_22h_minutes": [0, 60, 0], "hours": [0, 6, 8], "cost_per_night": [0, 200, 245]},
index=["none", "6h_from_23", "all_night"])
assert driver_shifts(options, "none") == [(0, None)]
assert driver_shifts(options, "6h_from_23") == [(0, None), (60, 420)]
assert driver_shifts(options, "all_night") == [(0, None), (0, None)]
75 passed
Day 50 checklist
- I can combine several simulations into one model of a week, with common random numbers across policies.
- I can define stress scenarios and report averages, bad tails and promises for each.
- I can find a breaking point by sweeping one stress.
- I can tell which risks a policy fixes and which need another decision.
- I can write a memo that a committee can act on.