- why one promise for each product is not one promise for all;
- what a promise costs;
- how a fill-rate target differs;
- why a promise kept in sample can fail out of sample.
56.1 A promise as a chance constraint
Store Operations wants the week's plan to cover demand for the three core products (sourdough, whole wheat, croissants) in at least 90% of weeks. The mid-week top-up stays free for other surprises.
- Individual chance constraint: for each product. Its deterministic equivalent is just the α-quantile of , a newsvendor-style bound.
- Joint chance constraint: . There is no simple formula. With scenarios, give each week a yes/no variable (1 = this week may fall short), and write This is a MIP with one binary per scenario.
Create day56/chance.py:
"""Day 56: chance constraints on the two-stage bakery model. The promise: "the week's plan covers the core products'
demand in at least alpha of the weeks" (the mid-week top-up is kept for surprises elsewhere). One yes/no variable per
scenario (and product) marks a week the plan may fall short.
Import it: from chance import add_service, covered
"""
import numpy as np
import pyomo.environ as pyo
def add_service(m, demand, core, alpha, joint=True, fill=None):
"""Add a service promise to a two-stage model m (Day 53).
joint=True: the plan covers all core products together in at least alpha of the weeks (one binary per week).
joint=False: each core product separately (one binary per product and week).
fill: instead, an expected fill rate: units short <= (1 - fill) x units wanted, over plan + top-up (an LP)."""
W = list(m.W)
if fill is not None:
m.fill_rate = pyo.Constraint(core, rule=lambda m, p: sum(demand[p, w] - m.s[p, w] for w in W)
<= (1 - fill) * sum(demand[p, w] for w in W))
return m
big = {p: max(demand[p, w] for w in W) for p in core} # a miss can't be worse than all demand
misses = np.floor((1 - alpha) * len(W) + 1e-9)
if joint:
m.miss = pyo.Var(m.W, within=pyo.Binary) # 1: the plan may fall short this week
z = lambda p, w: m.miss[w]
m.budget = pyo.Constraint(expr=sum(m.miss[w] for w in W) <= misses)
else:
m.miss = pyo.Var(core, m.W, within=pyo.Binary)
z = lambda p, w: m.miss[p, w]
m.budget = pyo.Constraint(core, rule=lambda m, p: sum(m.miss[p, w] for w in W) <= misses)
m.cover = pyo.Constraint(core, m.W, rule=lambda m, p, w: m.x[p] >= demand[p, w] - big[p] * z(p, w))
return m
def covered(plan, demand, core, n_weeks):
"""Week by week: does the plan cover every core product's demand? Also product by product."""
per = {p: np.array([plan[p] >= demand[p, w] - 1e-6 for w in range(n_weeks)]) for p in core}
return np.all(np.vstack(list(per.values())), axis=0), per
Then day56/run_chance.py:
# ---------- 56.1 A promise as a chance constraint ----------
print("--- individual and joint")
from newsvendor import q_empirical
print("90% quantiles of demand (an individual chance constraint's answer): "
+ ", ".join(f"{p} {q_empirical([demand[p, w] for w in range(W)], 0.90):.2f}" for p in CORE))
rows = [describe("no promise (Day 53)", run()),
describe("each core product 90% of weeks", run(0.90, joint=False)),
describe("all core products together 90%", run(0.90, joint=True))]
print(pd.DataFrame(rows).to_string(index=False))
--- individual and joint
90% quantiles of demand (an individual chance constraint's answer): BK-SD 36.15, BK-WW 46.48, BK-CR 32.25
promise profit all_core_covered BK-SD_covered BK-WW_covered BK-CR_covered worst_fill_rate x_BK-SD x_BK-WW x_BK-CR
no promise (Day 53) 112600.11 0.029 0.029 0.184 0.184 0.8813 30.84 44.11 30.11
each core product 90% of weeks 111629.70 0.854 0.903 0.903 0.903 0.9887 36.15 46.48 32.25
all core products together 90% 111392.60 0.903 0.951 0.951 0.913 0.9890 36.49 46.91 32.37
- The individual promise puts each product exactly at its 90% quantile, the deterministic equivalent. But all three are covered together in only 85% of weeks: each product misses different weeks.
- The joint promise covers all three in 90% of weeks for $237 a week more.
- The gap is small because the misses mostly fall in the same weeks (Christmas again). For independent products, three 90% promises would give about 73% jointly.
- Without any promise, Day 53's plan covers the core products in only 3% of weeks. It plans sourdough low on purpose and relies on the top-up.
56.2 The price of service
# ---------- 56.2 The price of service ----------
print("--- price of service")
rp = rows[0]["profit"]
rows = []
for alpha in (0.80, 0.85, 0.90, 0.95, 0.98, 1.00):
r = describe(f"joint {alpha:.0%}", run(alpha, joint=True))
rows.append((alpha, r["profit"], round(rp - r["profit"], 2), r["all_core_covered"]))
print(pd.DataFrame(rows, columns=["alpha", "profit", "cost_of_promise", "weeks_covered"]).to_string(index=False))
--- price of service
alpha profit cost_of_promise weeks_covered
0.80 111832.78 767.33 0.806
0.85 111661.86 938.25 0.854
0.90 111392.60 1207.51 0.903
0.95 111090.76 1509.35 0.951
0.98 107586.55 5013.56 0.981
1.00 104786.30 7813.81 1.000
Each extra point of service costs more than the last. 80% costs $767 a week, 95% costs $1,509, and 98% costs $5,014: the last weeks to cover are the Christmas weeks, where demand is far above forecast. A promise of 100% costs $7,800 a week ($406,000 a year). Show management this curve before they choose α.
56.3 A fill rate instead
A fill rate (Day 52) is not a chance constraint. It limits the expected units short, and it is linear:
# ---------- 56.3 A fill rate instead: an LP ----------
print("--- fill rate")
rows = [describe(f"expected fill rate {f:.1%}", run(fill=f)) for f in (0.99, 0.995)]
print(pd.DataFrame(rows).to_string(index=False))
--- fill rate
promise profit all_core_covered BK-SD_covered BK-WW_covered BK-CR_covered worst_fill_rate x_BK-SD x_BK-WW x_BK-CR
expected fill rate 99.0% 112488.22 0.058 0.175 0.175 0.252 0.990 34.29 44.09 30.44
expected fill rate 99.5% 112461.52 0.058 0.175 0.175 0.252 0.995 34.29 44.09 30.44
A 99.5% fill rate costs only $139 a week. But the plan covers the core products in 6% of weeks: the top-up covers the shortfalls on average, and the remaining shortfalls are small. Customers feel the fill rate; store managers feel the empty-shelf weeks. Which promise is made matters more than its number.
56.4 In sample and out of sample
A chance constraint kept on the scenarios can fail on new weeks. Solve the joint promise on 40 sampled weeks, then check the plan on all 103:
# ---------- 56.4 In sample and out of sample ----------
print("--- out of sample")
rng = np.random.default_rng(56)
rows = []
for alpha in (0.90, 0.95, 0.98):
out = []
for _ in range(10):
dm, wk = sample_demand(demand, d["products"], 40, rng.integers(W, size=40))
m = run(alpha, joint=True, dem=dm, wk=wk)
allc, _ = covered(plan_of(m), demand, CORE, W) # the same plan on all 103 weeks
out.append(allc.mean())
rows.append((alpha, round(np.mean(out), 3), round(min(out), 3), round(np.mean(np.array(out) >= 0.90), 2)))
print(pd.DataFrame(rows, columns=["alpha_in_40_weeks", "covered_on_103_mean", "covered_worst", "share_meeting_90"])
.to_string(index=False))
--- out of sample
alpha_in_40_weeks covered_on_103_mean covered_worst share_meeting_90
0.90 0.820 0.738 0.0
0.95 0.884 0.864 0.3
0.98 0.974 0.951 1.0
A 90% promise kept on 40 weeks covers only 82% of real weeks, and none of the 10 plans reaches 90%. The plan sits exactly on the edge of its sample, and a new sample has a few more weeks over the edge. To keep 90%, promise 98% in a sample of 40 (97% covered on 103 weeks, every plan above 90%). With few scenarios, tighten the promise or use more scenarios, then check out of sample.
Decision it supports: plans that must keep a promise with high probability, not just on average.
Other decisions you can support the same way: reserve generation in power grids (P(supply ≥ demand) ≥ 99.9%) · bank capital (value at risk) · emergency-room staffing · emissions caps that must hold most days.
The planted bug
day56/bug_budget.py is a colleague's joint 90% promise, written by hand. Run it.
m.miss = pyo.Var(m.W, within=pyo.Binary)
m.budget = pyo.Constraint(expr=sum(m.miss[w] for w in m.W) <= np.floor(alpha * len(weeks)))
m.cover = pyo.Constraint(CORE, m.W, rule=lambda m, p, w: m.x[p] >= demand[p, w] - 1_000 * m.miss[w])
solve(m)
allc, _ = covered({p: pyo.value(m.x[p]) for p in m.P}, demand, CORE, len(weeks))
print(f"profit ${pyo.value(m.expected_profit):,.2f}; promise 'kept'; weeks the plan covers all core products: {allc.mean():.1%}")
What happens, and why
profit $112,538.17; promise 'kept'; weeks the plan covers all core products: 10.7%
The promise is "kept" for $62 a week, but the plan covers the core products in 11% of weeks. The budget lets the model miss weeks, where it should allow . The binaries count the weeks you may miss, so their budget is . Check every chance constraint by counting the covered weeks afterwards, as covered does.
Mini-project: the union's overtime cap
The bakers' union proposes capping the mid-week top-up at 20 overtime oven hours, not 40. Management counters: "at most 20 hours in at least 90% of weeks; up to 40 in the others." Compare three rules: 40 hours always (today), 20 hours always (the union), and the counter-proposal, which is a chance constraint on the second stage. How often does the counter-proposal use more than 20 hours?
Solution
"""Day 56 mini-project: the bakers' union proposes a cap on the mid-week top-up: 20 overtime oven hours, not 40.
Management counters: "at most 20 hours in at least 90% of weeks; up to 40 in the others". Compare the expected
profit of: 40 hours always (today), 20 hours always (the union), and the counter-proposal (a chance constraint on the
second stage). How often does the counter-proposal actually use more than 20 hours?
Run from the repository root (after day06/load_tables.py): python day56/mini_project_overtime.py
"""
import sys
import duckdb
import numpy as np
import pandas as pd
import pyomo.environ as pyo
for folder in ("day06", "day42", "day44", "day53"):
sys.path.insert(0, folder)
from bakery import solve
from two_stage import build_two_stage, load_two_stage
pd.set_option("display.width", 160)
con = duckdb.connect("northbound.duckdb", read_only=True)
d, econ, st, demand, weeks = load_two_stage(con)
oven = lambda p: d["use"].get(("oven_hours", p), 0.0)
def hours_used(m):
return np.array([sum(oven(p) * pyo.value(m.y[p, w]) for p in m.P) for w in m.W])
rows = []
for name, hours, chance in [("40 hours always (today)", 40, None), ("20 hours always (union)", 20, None),
("20 hours in 90% of weeks, 40 in the rest", 40, (20, 0.90))]:
m = build_two_stage(d, econ, {**st, "topup_oven_hours": hours}, demand, weeks)
if chance:
cap, alpha = chance
m.over = pyo.Var(m.W, within=pyo.Binary) # 1: this week may use up to 40 hours
m.soft_cap = pyo.Constraint(m.W, rule=lambda m, w: sum(oven(p) * m.y[p, w] for p in m.P)
<= cap + (hours - cap) * m.over[w])
m.how_often = pyo.Constraint(expr=sum(m.over[w] for w in m.W) <= np.floor((1 - alpha) * len(weeks)))
solve(m)
h = hours_used(m)
rows.append((name, round(pyo.value(m.expected_profit), 2), round(h.mean(), 1), round((h > 20 + 1e-6).mean(), 3)))
t = pd.DataFrame(rows, columns=["rule", "expected_profit", "topup_hours_used", "weeks_over_20h"])
t["vs_today"] = (t.expected_profit - t.expected_profit[0]).round(2)
print(t.to_string(index=False))
rule expected_profit topup_hours_used weeks_over_20h vs_today
40 hours always (today) 112600.11 40.0 1.000 0.00
20 hours always (union) 109921.84 20.0 0.000 -2678.27
20 hours in 90% of weeks, 40 in the rest 110204.15 21.9 0.097 -2395.96
- The union's cap costs $2,678 a week. The counter-proposal recovers only $282 of that, using more than 20 hours in exactly the 10 weeks it is allowed.
- Why so little? The top-up is used to the full every week (40 hours today, 20 under the cap). It isn't a reserve for bad weeks; it's capacity the plan counts on. A chance constraint helps when the resource is needed only sometimes.
- The real question is whether 20 overtime oven hours are worth $2,678 a week, about $134 an hour against the $55 premium. That is a negotiation about capacity, not about bad weeks.
Note for the negotiation: "Every hour of mid-week top-up earns about $134 against a $55 overtime premium. The counter-proposal (20 hours in 90% of weeks) saves little. If the cap is agreed, plan the lost capacity elsewhere (Day 53's oven lease)."
Commit
git add .
git commit -m "Day 56: chance constraints and service levels"
git push
Day 56 checklist
- I can write an individual chance constraint as a quantile and a joint one as a scenario MIP.
- I know three individual promises are not one joint promise, and how correlation narrows the gap.
- I can draw the price-of-service curve and explain its steep end.
- I know a fill rate and a chance constraint promise different things.
- I check a chance constraint out of sample and tighten it if needed.