- Draw scenarios.
- Solve the two-stage model on them.
- Judge the plan on scenarios it has never seen.
Three questions follow: how big must be, how optimistic is the in-sample answer, and how close is the plan to the true optimum when you can't compute the true optimum? Today the 103 weeks play the "true" distribution, so for once you can check the answers.
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 Day 57:
bakery_oven_log: 26 weeks of oven hours, actual against standard, for every product.bakery_robust: what an overrun oven hour costs.
54.1 The true problem
Create day54/saa.py:
"""Day 54: sample average approximation. Solve the two-stage model on a sample of N scenarios, then judge the plan
on scenarios it has never seen.
Import it: from saa import sample_demand, solve_plan, evaluate_plan
"""
import numpy as np
import pyomo.environ as pyo
from bakery import solve
from two_stage import build_two_stage
def sample_demand(demand, products, n_weeks, idx):
"""Scenarios for the sampled week indices idx (drawn with replacement): scenario k is historical week idx[k]."""
return {(p, k): demand[p, int(w)] for p in products for k, w in enumerate(idx)}, [str(int(w)) for w in idx]
def solve_plan(d, econ, st, demand, weeks):
"""Solve the SAA problem; return the plan and its in-sample expected profit (the SAA optimum)."""
m = build_two_stage(d, econ, st, demand, weeks)
solve(m)
return {p: max(0.0, pyo.value(m.x[p])) for p in m.P}, pyo.value(m.expected_profit)
def evaluate_plan(d, econ, st, demand, weeks, plan):
"""The plan's expected profit on other scenarios: first stage fixed, second stage re-optimized in each."""
m = build_two_stage(d, econ, st, demand, weeks, plan=plan)
solve(m)
return pyo.value(m.expected_profit)
Then day54/run_saa.py:
# ---------- 54.1 The true problem ----------
print("--- truth")
best_plan, v_star = solve_plan(d, econ, st, demand, weeks)
print(f"all {W} weeks, equally likely: the true optimum is ${v_star:,.2f} a week")
--- truth
all 103 weeks, equally likely: the true optimum is $112,600.11 a week
54.2 SAA with N sampled weeks
For each , draw 20 independent samples of weeks (with replacement), solve each, and record three numbers:
- The in-sample optimum.
- The plan's true value on all 103 weeks.
- Its optimism: how much the SAA plan beats the true best plan on the SAA plan's own sample. This is never negative.
# ---------- 54.2 SAA with N sampled weeks ----------
print("--- saa")
rng = np.random.default_rng(54)
rows, curve = [], []
for n in (5, 10, 20, 40, 80):
inside, true, optimism = [], [], []
for _ in range(20): # 20 independent samples of n weeks
dm, wk = sample_demand(demand, P, n, rng.integers(W, size=n))
plan, v = solve_plan(d, econ, st, dm, wk)
inside.append(v)
true.append(evaluate_plan(d, econ, st, demand, weeks, plan))
optimism.append(v - evaluate_plan(d, econ, st, dm, wk, best_plan)) # >= 0: it beats the true best plan on its own sample
inside, true = np.array(inside), np.array(true)
rows.append((n, round(inside.mean(), 2), round(inside.std(ddof=1), 2), round(np.mean(optimism), 2),
round(true.mean(), 2), round(true.min(), 2), round(v_star - true.mean(), 2)))
curve.append((n, inside.mean(), true.mean(), 1.96 * inside.std(ddof=1) / np.sqrt(len(inside))))
print(pd.DataFrame(rows, columns=["N", "in_sample_mean", "in_sample_sd", "optimism", "true_value_mean", "true_value_worst",
"loss_vs_optimum"]).to_string(index=False))
c = np.array(curve)
fig, ax = plt.subplots(figsize=(7, 3.6))
ax.errorbar(c[:, 0], c[:, 1], yerr=c[:, 3], fmt="o-", color="#e5484d", capsize=3,
label="SAA optimum, in sample (95% interval)")
ax.plot(c[:, 0], c[:, 2], "o-", color="#3b82f6", label="the SAA plan's true value")
ax.axhline(v_star, ls="--", color="#6b7280", label="true optimum")
ax.set(xscale="log", xlabel="scenarios N (log scale)", ylabel="expected profit a week ($)",
title="SAA: noisy in sample, converging out of sample")
ax.set_xticks(c[:, 0], [str(int(n)) for n in c[:, 0]])
ax.xaxis.set_minor_locator(matplotlib.ticker.NullLocator())
ax.spines[["top", "right"]].set_visible(False)
ax.legend(frameon=False)
fig.tight_layout()
fig.savefig("figures/day54_saa.png", dpi=150)
print("saved figures/day54_saa.png")
--- saa
N in_sample_mean in_sample_sd optimism true_value_mean true_value_worst loss_vs_optimum
5 113070.82 1347.79 202.79 112375.33 112108.44 224.78
10 112937.89 961.48 117.24 112491.96 112407.15 108.15
20 112335.24 1238.08 125.42 112478.92 112240.87 121.19
40 112544.50 526.91 33.05 112562.09 112506.88 38.02
80 112505.64 605.51 29.14 112566.21 112498.02 33.90
saved figures/day54_saa.png

- The SAA plan's true value rises toward the optimum: it loses $225 a week at and $34 at . Even 5 sampled weeks give a decent plan. The worst of 20 plans at is within $94 of the optimum.
- The in-sample optimum is optimistic: on its own sample, the SAA plan always looks better than the truly best plan, by $203 at and $29 at . On average, then, an SAA optimum overstates what its plan will earn (Day 48's optimizer's curse again).
- The in-sample numbers are also very noisy. A sample that happens to include a Christmas week looks much better than one without, so with these heavy-tailed weeks the noise can hide the optimism. Never report an in-sample optimum as the expected profit.
54.3 Bounds without knowing the truth
In practice there is no "all 103 weeks" to check against. Two estimates bracket the true optimum (for a maximization):
- An upper bound: the average of several independent SAA optima. They are optimistic on average, so their mean is at least the true optimum.
- A lower bound: one plan's value, estimated on a fresh sample. Any plan's true value is at most the optimum.
Choose the plan on one sample and judge it on another, so the choice doesn't flatter its own estimate.
# ---------- 54.3 Bounds without knowing the truth ----------
print("--- bounds")
n, reps = 20, 20
rng = np.random.default_rng(540)
optima, plans = [], []
for _ in range(reps):
dm, wk = sample_demand(demand, P, n, rng.integers(W, size=n))
plan, v = solve_plan(d, econ, st, dm, wk)
optima.append(v)
plans.append(plan)
upper, half_u = mean_ci(optima)
pick, pwk = sample_demand(demand, P, 500, rng.integers(W, size=500)) # sample A: to choose among the plans
values = [evaluate_plan(d, econ, st, pick, pwk, plan) for plan in plans]
k = int(np.argmax(values))
check, cwk = sample_demand(demand, P, 500, rng.integers(W, size=500)) # sample B: to judge the chosen plan
m = build_two_stage(d, econ, st, check, cwk, plan=plans[k])
solve(m)
lower, half_l = mean_ci(scenario_profits(m))
print(f"upper bound (average SAA optimum, {reps} samples of {n}): ${upper:,.2f} +/- ${half_u:,.2f}")
print(f"the best of the {reps} plans on sample A (500 weeks): ${values[k]:,.2f}; the worst ${min(values):,.2f}")
print(f"lower bound (the chosen plan on sample B, 500 other weeks): ${lower:,.2f} +/- ${half_l:,.2f}")
print(f"estimated gap: ${upper - lower:,.2f} +/- ${np.hypot(half_u, half_l):,.2f}; "
f"true value of the chosen plan ${evaluate_plan(d, econ, st, demand, weeks, plans[k]):,.2f} vs optimum ${v_star:,.2f}")
--- bounds
upper bound (average SAA optimum, 20 samples of 20): $112,590.77 +/- $518.96
the best of the 20 plans on sample A (500 weeks): $112,728.55; the worst $112,539.98
lower bound (the chosen plan on sample B, 500 other weeks): $112,276.94 +/- $476.57
estimated gap: $313.83 +/- $704.58; true value of the chosen plan $112,574.89 vs optimum $112,600.11
The estimated gap is $314 ± $705 a week: with 95% confidence, the chosen plan is within about $1,000 of the best possible (0.9%). The truth, here known, is $25. The intervals are wide because weekly profit has heavy tails. Tighter bounds need more replications or larger evaluation samples, not cleverer optimization.
Decision it supports: planning with many possible futures, when you can only sample them; and knowing how close to optimal the plan is.
Other decisions you can support the same way: portfolio choices over simulated returns · capacity plans over simulated demand · any two-stage model whose scenarios come from a simulator.
The planted bug
day54/bug_independent.py builds 103 scenarios by drawing a historical week for each product separately ("more combinations, more realistic"). Run it.
mixed = {(p, k): demand[p, int(rng.integers(W))] for p in P for k in range(W)} # every product its own week
plan, inside = solve_plan(d, econ, st, mixed, weeks)
m = build_two_stage(d, econ, st, mixed, weeks, plan=plan)
solve(m)
print(f"in its own scenarios: ${inside:,.2f} a week, worst week ${scenario_profits(m).min():,.2f}")
m = build_two_stage(d, econ, st, demand, weeks, plan=plan)
solve(m)
print(f"on the real weeks: ${scenario_profits(m).mean():,.2f} a week, worst week ${scenario_profits(m).min():,.2f}")
best, v_star = solve_plan(d, econ, st, demand, weeks)
print(f"Day 53's plan on the real weeks: ${v_star:,.2f}")
What happens, and why
in its own scenarios: $112,662.79 a week, worst week $108,690.39
on the real weeks: $112,588.08 a week, worst week $79,042.97
Day 53's plan on the real weeks: $112,600.11
The plan earns almost the same on average. But in its own scenarios, the worst week is $108,690, a reassuring picture. On the real weeks, the worst is $79,043. Mixing weeks product by product breaks the Christmas and January weeks into pieces that cancel out (Day 44's lesson). The average survives; the risk disappears from view, and Day 58 needs that risk. Sample whole scenarios, never their pieces separately.
Mini-project: would SAA still lease the ovens?
Day 53 decided to lease the extra ovens using all 103 weeks. With = 5, 10, 20 or 40 sampled weeks, solve the lease model 20 times each. How often does it lease? What is the decision (lease and plan) really worth, judged on all 103 weeks?
Solution
"""Day 54 mini-project: Day 53 decided to lease the extra ovens using all 103 historical weeks. With fewer scenarios,
would SAA still say "lease"? For N = 5, 10, 20, 40 sampled weeks, solve the lease model 20 times and count how often
it leases, and what the decision is really worth (judged on all 103 weeks).
Run from the repository root (after day06/load_tables.py): python day54/mini_project_lease_saa.py (about 2 minutes)
"""
import sys
import duckdb
import numpy as np
import pandas as pd
import pyomo.environ as pyo
for folder in ("day06", "day42", "day44", "day53", "day54"):
sys.path.insert(0, folder)
from bakery import solve
from saa import sample_demand
from two_stage import build_two_stage, load_two_stage
pd.set_option("display.width", 160)
con = duckdb.connect("northbound.duckdb", read_only=True)
hours, cost = con.sql("SELECT extra_capacity, cost_per_week FROM bakery_investments WHERE option = 'lease_ovens'").fetchall()[0]
d, econ, st, demand, weeks = load_two_stage(con)
P, W = d["products"], len(weeks)
def true_value(lease, plan):
m = build_two_stage(d, econ, st, demand, weeks, plan=plan, lease=(hours, cost))
m.lease.fix(lease)
solve(m)
return pyo.value(m.expected_profit)
m = build_two_stage(d, econ, st, demand, weeks, lease=(hours, cost))
solve(m)
best = pyo.value(m.expected_profit)
print(f"all 103 weeks: lease = {pyo.value(m.lease):.0f}, ${best:,.2f} a week")
rng = np.random.default_rng(54)
rows = []
for n in (5, 10, 20, 40):
leases, values = 0, []
for _ in range(20):
dm, wk = sample_demand(demand, P, n, rng.integers(W, size=n))
s = build_two_stage(d, econ, st, dm, wk, lease=(hours, cost))
solve(s)
lease = int(round(pyo.value(s.lease)))
leases += lease
values.append(true_value(lease, {p: max(0.0, pyo.value(s.x[p])) for p in P}))
rows.append((n, f"{leases}/20", round(np.mean(values), 2), round(best - np.mean(values), 2), round(best - min(values), 2)))
print(pd.DataFrame(rows, columns=["N", "times_leased", "true_value_mean", "average_loss", "worst_loss"]).to_string(index=False))
all 103 weeks: lease = 1, $113,084.92 a week
N times_leased true_value_mean average_loss worst_loss
5 20/20 112882.07 202.85 692.99
10 20/20 112980.67 104.26 223.01
20 20/20 112987.12 97.80 438.56
40 20/20 113060.13 24.79 55.35
- The yes/no decision is stable: every sample, even 5 weeks, says lease. The lease is worth about $485 a week net, well clear of zero, so sampling noise doesn't flip it.
- The plan that goes with it is less stable: with 5 weeks it loses $203 a week on average, and up to $693. Forty weeks bring that to $25.
- In general, a decision that is far from its break-even is easy to get right with few scenarios. The fine details of a plan need more.
Commit
git add .
git commit -m "Day 54: sample average approximation"
git push
Day 54 checklist
- I can solve a two-stage model on N sampled scenarios and evaluate the plan out of sample.
- I know an SAA optimum is optimistic and noisy, and never report it as the expected value.
- I can bound the optimality gap with replications and a fresh evaluation sample.
- I choose plans on one sample and judge them on another.
- I sample whole scenarios, so dependence between products survives.