57.1 How long the ovens really take
Day 6 assumed each batch takes exactly its standard oven time. bakery_oven_log records 26 weeks of actual oven hours. Create day57/robust.py:
"""Day 57: robust optimization. Oven hours per batch vary (bakery_oven_log); plan so the oven constraint holds even
if up to Gamma products take their longest observed time (Bertsimas and Sim's budget of uncertainty).
Import it: from robust import oven_deviations, build_robust, oven_overrun
"""
import numpy as np
import pandas as pd
import pyomo.environ as pyo
from bakery import build_model
def oven_deviations(con, quantile=0.95):
"""Actual / standard oven hours, per product and logged week; and each product's deviation: the given quantile
of (ratio - 1). The deviation is how much longer than standard a batch can take, as a share."""
log = con.sql("""SELECT week_start, sku, actual_oven_hours / standard_oven_hours AS ratio
FROM bakery_oven_log""").df()
table = log.pivot(index="week_start", columns="sku", values="ratio")
eps = (table - 1).quantile(quantile).clip(lower=0)
return table, eps
def build_robust(d, eps, gamma, resource="oven_hours"):
"""Day 6's model, with the oven row protected: sum a x + Gamma lam + sum mu <= H, lam + mu_p >= eps_p a_p x_p.
The dual of 'the worst Gamma products run long' (gamma = 0: the nominal model; gamma = all: every product long)."""
m = build_model(d)
a = {p: d["use"].get((resource, p), 0.0) for p in d["products"]}
m.lam = pyo.Var(within=pyo.NonNegativeReals)
m.mu = pyo.Var(m.P, within=pyo.NonNegativeReals)
m.capacity_limit[resource].deactivate()
m.robust_oven = pyo.Constraint(expr=sum(a[p] * m.x[p] for p in m.P) + gamma * m.lam + sum(m.mu[p] for p in m.P)
<= d["capacity"][resource])
m.protect = pyo.Constraint(m.P, rule=lambda m, p: m.lam + m.mu[p] >= eps[p] * a[p] * m.x[p])
return m
def oven_overrun(plan, d, table, resource="oven_hours"):
"""For each logged week (its real ratios, all products together): hours beyond capacity if this plan were baked."""
a = pd.Series({p: d["use"].get((resource, p), 0.0) for p in d["products"]})
x = pd.Series(plan)
used = (table[a.index] * a * x).sum(axis=1)
return np.maximum(used - d["capacity"][resource], 0.0).to_numpy()
Then day57/run_robust.py:
# ---------- 57.1 How long the ovens really take ----------
print("--- oven times")
table, eps = oven_deviations(con)
cat = pd.Series(d["category"])
summary = pd.DataFrame({"mean_ratio": table.mean(), "deviation_95": eps}).join(cat.rename("category"))
print(summary.groupby("category").agg(products=("mean_ratio", "size"), mean_ratio=("mean_ratio", "mean"),
deviation_95=("deviation_95", "mean")).round(3).to_string())
week_total = (table * pd.Series({p: d["use"].get(("oven_hours", p), 0.0) for p in d["products"]})).sum(axis=1) / \
sum(d["use"].get(("oven_hours", p), 0.0) for p in d["products"])
print(f"a whole week's oven time vs standard: {week_total.min():.3f} to {week_total.max():.3f} (26 weeks)")
--- oven times
products mean_ratio deviation_95
category
bread 10 1.012 0.065
cake 6 0.997 0.147
cookie 6 1.023 0.087
viennoiserie 8 1.012 0.106
a whole week's oven time vs standard: 0.962 to 1.053 (26 weeks)
Batches take about 1% longer than standard on average. In a bad week (the 95th percentile), a cake takes 15% longer and a bread 6.5% longer. A whole week's oven time ranges from 4% under to 5% over standard: Day 6's plan uses all 600 hours, so most weeks it overruns.
57.2 The budget of uncertainty
Protect the oven row against products running long. Each product's oven time per batch lies in .
- Protecting against every product at its worst (a box set) is too pessimistic: they never all run long at once.
- Bertsimas and Sim's budget protects against the worst products running long at once:
The inner maximum is an LP. Its dual turns the constraint into linear rows, the robust counterpart:
is Day 6's model; is the box.
# ---------- 57.2 The budget of uncertainty ----------
print("--- gamma")
rows, curve = [], []
for gamma in (0, 1, 2, 3, 5, 8, 12, 30):
m = build_robust(d, eps, gamma)
solve(m)
plan = {p: pyo.value(m.x[p]) for p in m.P}
over = oven_overrun(plan, d, table)
profit = pyo.value(m.total_profit)
net = profit - overrun_cost * over.mean()
rows.append((gamma, round(profit, 2), round(sum(d["use"].get(("oven_hours", p), 0) * x for p, x in plan.items()), 1),
round((over > 0).mean(), 3), round(over.mean(), 2), round(over.max(), 1), round(net, 2)))
curve.append((gamma, profit, net, (over > 0).mean()))
t = pd.DataFrame(rows, columns=["gamma", "planned_profit", "standard_oven_hours", "weeks_overrun", "mean_overrun_h",
"worst_overrun_h", "profit_after_overruns"])
print(t.to_string(index=False))
base = t.iloc[0]
for r in t.iloc[1:].itertuples():
print(f"gamma {r.gamma:>2}: beats the nominal plan if an overrun hour costs more than "
f"${(base.planned_profit - r.planned_profit) / (base.mean_overrun_h - r.mean_overrun_h):,.0f}")
c = np.array(curve)
fig, ax = plt.subplots(figsize=(7, 3.6))
ax.plot(c[:, 3] * 100, c[:, 1], "o-", color="#3b82f6", label="planned profit")
ax.plot(c[:, 3] * 100, c[:, 2], "o-", color="#e5484d", label="after overrun costs")
for g, x, y in zip(c[:, 0], c[:, 3] * 100, c[:, 1]):
ax.annotate(f"Γ={g:.0f}", (x, y), textcoords="offset points", xytext=(4, 6), fontsize=7, color="#6b7280")
ax.set(xlabel="weeks the ovens overrun (% of 26 logged weeks)", ylabel="profit a week ($)",
title="The price of robustness: oven times that vary")
ax.spines[["top", "right"]].set_visible(False)
ax.legend(frameon=False)
fig.tight_layout()
fig.savefig("figures/day57_robust.png", dpi=150)
print("saved figures/day57_robust.png")
--- gamma
gamma planned_profit standard_oven_hours weeks_overrun mean_overrun_h worst_overrun_h profit_after_overruns
0 108351.28 600.0 0.692 11.98 49.7 106913.64
1 107719.21 593.6 0.538 8.07 42.7 106750.41
2 107194.26 588.5 0.462 5.57 37.1 106525.96
3 106731.12 586.2 0.385 4.07 33.8 106242.29
5 106049.26 579.3 0.192 1.97 26.0 105812.60
8 105256.51 570.2 0.077 0.71 16.0 105171.57
12 104443.85 563.7 0.038 0.31 8.1 104406.57
30 102829.64 549.2 0.000 0.00 0.0 102829.64
gamma 1: beats the nominal plan if an overrun hour costs more than $162
gamma 2: beats the nominal plan if an overrun hour costs more than $181
gamma 3: beats the nominal plan if an overrun hour costs more than $205
gamma 5: beats the nominal plan if an overrun hour costs more than $230
gamma 8: beats the nominal plan if an overrun hour costs more than $275
gamma 12: beats the nominal plan if an overrun hour costs more than $335
gamma 30: beats the nominal plan if an overrun hour costs more than $461
saved figures/day57_robust.png

- The price of robustness: each step of gives up profit to overrun less often. Day 6's plan overruns in 69% of weeks (12 hours on average). overruns in 19% of weeks for $2,302 a week less, and never overruns, for $5,522 less.
- Whether that's worth it depends on what an overrun costs. At $120 an overrun hour (late bread, overtime), the nominal plan still earns the most after overruns. wins only if an overrun hour costs more than $230: for example, if a late run means trucks leave without bread.
- Robust protection is insurance. Price it against what it protects.
57.3 A robust reorder point
The olive oil supplier (SUP-B) delivered in 3 to 17 days. A robust reorder point covers the longest lead time in the record, plus "high" days of demand (the 90th percentile of daily demand above the mean). Compare with Day 52's stochastic reorder point:
# ---------- 57.3 A robust reorder point ----------
print("--- robust reorder point")
items, settings = load_items(con)
item = "AM-04"
i = items.loc[item]
dem, lead = demand_history(con, item), lead_history(con, item)
q = np.round(eoq(i.mean_day * 365, settings["order_cost_per_po"], i.hold_per_case_year))
l_max = lead.max()
high = np.quantile(dem, 0.90) - dem.mean() # a "high" day: 90th percentile above the mean
print(f"{item}: lead time {lead.min()} to {l_max} days (mean {lead.mean():.2f}); a high day is +{high:.1f} cases")
rows = []
for name, s in [("Day 52 (stochastic, 98% fill)", 266.0), ("nominal: mean x mean lead", np.round(i.mean_day * lead.mean())),
("robust, Gamma = 0", np.round(i.mean_day * l_max)),
("robust, Gamma = sqrt(Lmax)", np.round(i.mean_day * l_max + np.sqrt(l_max) * high)),
("robust, Gamma = Lmax (box)", np.round(i.mean_day * l_max + l_max * high))]:
rng = np.random.default_rng(57)
sims = pd.DataFrame([simulate_policy(dem, lead, rng, 730, reorder_point=s, order_qty=q) for _ in range(20)]).mean()
rows.append((name, s, round(sims.fill_rate, 4), round(sims.avg_on_hand, 1)))
print(pd.DataFrame(rows, columns=["reorder_point", "s", "fill_rate", "avg_on_hand"]).to_string(index=False))
--- robust reorder point
AM-04: lead time 3 to 17 days (mean 11.77); a high day is +11.3 cases
reorder_point s fill_rate avg_on_hand
Day 52 (stochastic, 98% fill) 266.0 0.9868 262.5
nominal: mean x mean lead 209.0 0.9464 215.3
robust, Gamma = 0 302.0 0.9971 303.3
robust, Gamma = sqrt(Lmax) 348.0 0.9997 346.5
robust, Gamma = Lmax (box) 493.0 1.0000 491.5
- Covering the mean lead time with mean demand fills only 94.6%.
- The robust point for the worst lead time () already fills 99.7%, with 41 more cases on hand than Day 52's. One 17-day delivery in the record sets the policy.
- More piles on stock for almost nothing.
- Robust policies are only as sensible as their sets: a set built from the single worst observation is driven by that observation.
Robust or stochastic?
| Use stochastic models when | Use robust models when |
|---|---|
| you can estimate probabilities (history, a simulator) | you know ranges but not probabilities |
| shortfalls cost money you can price | a constraint must hold (safety, contracts, physics) |
| you care about the average (or a tail: Day 58) | the worst case matters, or an adversary chooses it |
| the model with scenarios stays solvable | scenarios would make the model too big |
Both can be combined: robust constraints inside a stochastic objective, or an uncertainty set sized so the constraint holds with probability α. That is how Bertsimas and Sim relate to a chance constraint.
Decision it supports: plans that must stay feasible for every case in a range, and a clear price for that protection.
Other decisions you can support the same way: power-grid dispatch under uncertain renewables · portfolio limits under uncertain returns · network capacity against link failures · schedules with uncertain task times.
The planted bug
day57/bug_protection.py writes the robust oven row by hand, with . Run it.
m.lam = pyo.Var(within=pyo.NonNegativeReals)
m.mu = pyo.Var(m.P, within=pyo.NonNegativeReals)
m.capacity_limit["oven_hours"].deactivate()
m.robust_oven = pyo.Constraint(expr=sum(a[p] * m.x[p] for p in m.P) + 5 * m.lam + sum(m.mu[p] for p in m.P) <= 600)
m.protect = pyo.Constraint(m.P, rule=lambda m, p: m.lam + m.mu[p] >= eps[p] * a[p])
solve(m)
over = oven_overrun({p: pyo.value(m.x[p]) for p in m.P}, d, table)
print(f"gamma 5: profit ${pyo.value(m.total_profit):,.2f}; weeks the ovens overrun {(over > 0).mean():.1%}")
What happens, and why
gamma 5: profit $108,203.88; weeks the ovens overrun 65.4%
"Robust" at for only $147 of profit, yet the ovens overrun in 65% of weeks, almost as often as with no protection. The protection rows read : they protect against one batch of each product running long, not batches. The protection must scale with the decision: . Check a robust model by simulating its plan against the data that motivated it.
Mini-project: yule logs without probabilities
Suppose the yule log history were lost, and all you knew was that a store sells between the smallest and the largest share of its forecast ever seen. How many logs should an average store order? Compare three robust rules with Day 51's newsvendor, judged on the real history:
- Max-min profit: the best worst case.
- Min-max regret: regret is what you lose against the best order for the demand that happens. Minimize its worst case.
- The middle of the range.
Solution
"""Day 57 mini-project: suppose the yule log history were lost, and all we knew was that a store sells between
the smallest and largest share of its forecast ever seen. Without probabilities, how many logs should an average
store order? Compare three robust rules (max-min profit, min-max regret, and the middle of the range) with Day 51's
newsvendor, judged on the real history.
Run from the repository root (after day06/load_tables.py): python day57/mini_project_regret.py
"""
import sys
import duckdb
import numpy as np
import pandas as pd
sys.path.insert(0, "day51")
from newsvendor import critical_ratio, q_empirical
pd.set_option("display.width", 160)
con = duckdb.connect("northbound.duckdb", read_only=True)
e = dict(con.sql("SELECT * FROM yule_log_economics").fetchall())
price, cost, salvage = e["price"], e["cost"], e["boxing_day_price"] * e["boxing_day_sell_share"]
hist = con.sql("SELECT demand_logs / forecast_logs AS ratio FROM yule_log_history").df().ratio.to_numpy()
fc = con.sql("SELECT avg(forecast_logs) FROM yule_log_forecast").fetchall()[0][0]
low, high = fc * hist.min(), fc * hist.max()
print(f"an average store: forecast {fc:.1f} logs; demand somewhere in [{low:.1f}, {high:.1f}]")
def profit(q, dem):
sold = np.minimum(q, dem)
return price * sold - cost * q + salvage * (q - sold)
qs = np.arange(0, int(high) + 2)
grid = np.linspace(low, high, 401) # possible demands in the range
table = np.array([[profit(q, x) for x in grid] for q in qs])
regret = np.array([[profit(x, x) - profit(q, x) for x in grid] for q in qs])
rules = {"max-min profit (the worst case)": qs[table.min(axis=1).argmax()],
"min-max regret": qs[regret.max(axis=1).argmin()],
"the middle of the range": round((low + high) / 2),
"the forecast": round(fc),
"newsvendor on the history (Day 51)": np.ceil(q_empirical(fc * hist, critical_ratio(price, cost, salvage)))}
dem = fc * hist
rows = [(name, q, round(profit(q, low), 2), round(regret[int(q)].max(), 2), round(profit(q, dem).mean(), 2))
for name, q in rules.items()]
print(pd.DataFrame(rows, columns=["rule", "logs", "profit_if_lowest", "worst_regret", "expected_on_history"])
.to_string(index=False))
r = critical_ratio(price, cost, salvage)
print(f"min-max regret formula: low + (high - low) x critical ratio = {low + (high - low) * r:.1f}")
an average store: forecast 48.0 logs; demand somewhere in [20.8, 93.8]
rule logs profit_if_lowest worst_regret expected_on_history
max-min profit (the worst case) 21.0 425.29 1492.38 430.46
min-max regret 88.0 297.99 127.74 938.67
the middle of the range 57.0 356.89 754.38 923.40
the forecast 48.0 373.99 938.88 866.48
newsvendor on the history (Day 51) 76.0 320.79 364.88 949.50
min-max regret formula: low + (high - low) x critical ratio = 87.6
- Max-min profit orders 21 logs, the lowest demand. It protects the worst case and earns half the newsvendor's profit on the real history. Pure worst-case thinking is too timid when shortages are what cost money.
- Min-max regret orders 88 logs. For a newsvendor with demand in , the answer has a formula, the critical ratio. It earns $939, within 1.1% of the newsvendor's $950, without any probabilities.
- Regret is the robust criterion to use when the downside of the worst case isn't the real concern. Here, missed sales hurt more than leftovers.
Note: "If the history is unreliable, order 88 logs per average store (the min-max regret rule). It is almost as good as the newsvendor with the history (76), and much better than planning for the worst case (21)."
Commit
git add .
git commit -m "Day 57: robust optimization"
git push
Then run the tests: tests/test_uncertainty_models.py checks Days 54–57. It covers:
- sampling scenarios, and error scaling;
- EEV ≤ RP ≤ WS;
- the individual chance constraint kept for each product;
- Γ = 0 equal to the nominal model, and the box set keeping every product 10% long within the ovens.
Add "day54" to "day57" to the folders in conftest.py.
"""Known answers for Days 54-57: SAA samples, VSS and EVPI, chance constraints, robust budgets."""
import numpy as np
import pyomo.environ as pyo
import pytest
from bakery import build_model, load_data, solve
from chance import add_service, covered
from robust import build_robust
from saa import sample_demand
from two_stage import build_two_stage, load_two_stage
from values import four_numbers, scale_demand
def test_sample_demand():
demand = {("A", 0): 1.0, ("A", 1): 2.0, ("A", 2): 3.0}
dm, wk = sample_demand(demand, ["A"], 4, [2, 2, 0, 1])
assert [dm["A", k] for k in range(4)] == [3.0, 3.0, 1.0, 2.0] and wk == ["2", "2", "0", "1"]
assert scale_demand(demand, {"A": 2.0}, 0.0) == {k: 2.0 for k in demand} # no error: every week = forecast
def test_value_ordering(con):
d, econ, st, demand, weeks = load_two_stage(con)
r = four_numbers(d, econ, st, demand, weeks)
assert r["EEV"] <= r["RP"] + 1e-6 <= r["WS"] + 2e-6 # a stochastic plan is never worse; foresight never hurts
def test_each_product_covered(con):
d, econ, st, demand, weeks = load_two_stage(con)
core = ["BK-SD", "BK-CR"]
m = build_two_stage(d, econ, st, demand, weeks)
add_service(m, demand, core, 0.90, joint=False)
solve(m)
_, per = covered({p: pyo.value(m.x[p]) for p in m.P}, demand, core, len(weeks))
assert all(per[p].mean() >= 0.90 for p in core)
def test_robust_budget(con):
d = load_data(con)
nominal = build_model(d)
solve(nominal)
eps = {p: 0.1 for p in d["products"]}
m0 = build_robust(d, eps, 0)
solve(m0)
assert pyo.value(m0.total_profit) == pytest.approx(pyo.value(nominal.total_profit)) # gamma 0 = nominal
m = build_robust(d, eps, len(d["products"]))
solve(m)
used = sum(1.1 * d["use"].get(("oven_hours", p), 0) * pyo.value(m.x[p]) for p in m.P)
assert used <= d["capacity"]["oven_hours"] + 1e-6 # every product 10% long still fits
84 passed
Day 57 checklist
- I can write a robust counterpart for a budget-of-uncertainty set.
- I can draw the price of robustness and price it against the cost of a violation.
- I know robust policies inherit the quirks of their uncertainty sets.
- I can choose between stochastic and robust models for a decision.
- I can use max-min profit and min-max regret, and know when each makes sense.