13.1 Sweeps: one limit, fifty values
A sweep solves the model for a list of values of one parameter. Two ways to do it: rebuild the model each time, or build it once and change one constraint with set_value (Day 7). Create day13/sweeps.py:
import os
import sys
import time
import duckdb
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import pyomo.environ as pyo
sys.path.insert(0, "day06")
from bakery import build_model, load_data, solve
os.makedirs("figures", exist_ok=True)
con = duckdb.connect("northbound.duckdb", read_only=True)
d = load_data(con)
hours = list(range(400, 901, 10))
# ---------- 13.1 Rebuild for every value, or build once and change one limit ----------
start = time.perf_counter()
rebuilt = []
for h in hours:
m = build_model(dict(d, capacity=dict(d["capacity"], oven_hours=h)))
solve(m)
rebuilt.append(pyo.value(m.total_profit))
t_rebuild = time.perf_counter() - start
start = time.perf_counter()
m = build_model(d)
oven = m.capacity_limit["oven_hours"]
changed = []
for h in hours:
oven.set_value(oven.body <= h)
solve(m)
changed.append(pyo.value(m.total_profit))
t_change = time.perf_counter() - start
print(f"{len(hours)} solves: rebuild {t_rebuild:.2f} s, change one limit {t_change:.2f} s, "
f"same answers: {np.allclose(rebuilt, changed)}")
profit = np.array(changed)
slope = np.diff(profit) / 10 # $ per extra oven hour, between sweep points
for h, p, s in zip(hours[::10], profit[::10], list(slope[::10]) + [None]):
print(f" oven {h} h: ${p:,.2f}" + (f" (next 10 h worth ${s:,.2f}/h)" if s is not None else ""))
fig, (a1, a2) = plt.subplots(1, 2, figsize=(11, 4))
a1.plot(hours, profit / 1000, "-", color="#4f7bd9")
a1.axvline(600, color="grey", ls=":")
a1.set_xlabel("oven hours a week")
a1.set_ylabel("profit ($ thousand a week)")
a1.set_title("Profit as oven hours change")
a2.step(hours[1:], slope, where="pre", color="#e08a2c")
a2.axvline(600, color="grey", ls=":")
a2.set_xlabel("oven hours a week")
a2.set_ylabel("$ per extra oven hour")
a2.set_title("Value of one more oven hour")
fig.tight_layout()
fig.savefig("figures/day13_oven_sweep.png", dpi=120)
51 solves: rebuild 0.35 s, change one limit 0.23 s, same answers: True
oven 400 h: $79,802.73 (next 10 h worth $165.94/h)
oven 500 h: $95,577.40 (next 10 h worth $149.07/h)
oven 600 h: $108,351.28 (next 10 h worth $83.07/h)
oven 700 h: $109,434.90 (next 10 h worth $0.00/h)
oven 800 h: $109,434.90 (next 10 h worth $0.00/h)
oven 900 h: $109,434.90
(Your times will differ.) Fifty-one solves of the 30-product model take a third of a second either way. On models this size, rebuild if it keeps the code simple; on big models (Module 3), changing the model in place matters.

The left chart is profit against oven hours: a line made of straight pieces, each steeper than the next one to its right. The right chart is its slope, the value of one more oven hour: a staircase going down. Each step is a range from Day 12; each riser is a product reaching its cap or leaving the plan. Three things to see:
- Below 600 hours an oven hour is worth $100 to $165: ovens are the bakery's main bottleneck.
- Just above 600 the value drops fast, to $83 and then $25.
- Beyond about 620 hours an oven hour is worth nothing: packing and starter bind instead. Leasing ovens beyond that point would buy idle capacity.
Every LP's value curve has this shape (concave and piecewise linear): diminishing returns are built into linear programming.
13.2 Two limits at once
Limits interact. Sweep oven and packing hours together:
# ---------- 13.2 Two limits at once: oven hours x packing hours ----------
ovens = list(range(500, 801, 50))
packs = list(range(240, 381, 20))
grid = np.zeros((len(packs), len(ovens)))
pack = m.capacity_limit["packing_hours"]
for i, ph in enumerate(packs):
pack.set_value(pack.body <= ph)
for j, oh in enumerate(ovens):
oven.set_value(oven.body <= oh)
solve(m)
grid[i, j] = pyo.value(m.total_profit)
fig, ax = plt.subplots(figsize=(7, 5))
im = ax.imshow(grid / 1000, origin="lower", cmap="viridis", aspect="auto",
extent=[ovens[0] - 25, ovens[-1] + 25, packs[0] - 10, packs[-1] + 10])
for i, ph in enumerate(packs):
for j, oh in enumerate(ovens):
light = grid[i, j] > grid.min() + 0.6 * (grid.max() - grid.min())
ax.text(oh, ph, f"{grid[i, j] / 1000:.1f}", ha="center", va="center", fontsize=8,
color="black" if light else "white")
ax.add_patch(plt.Rectangle((575, 290), 50, 20, fill=False, edgecolor="red", lw=2))
ax.set_xlabel("oven hours a week")
ax.set_ylabel("packing hours a week")
ax.set_title("Weekly profit ($ thousand); red box = today")
fig.colorbar(im, ax=ax)
fig.tight_layout()
fig.savefig("figures/day13_oven_packing.png", dpi=120)
print("row = packing hours, column = oven hours, profit in $ thousand")
print(" " + "".join(f"{o:>7}" for o in ovens))
for i, ph in enumerate(packs):
print(f"{ph:>5} " + "".join(f"{grid[i, j] / 1000:>7.1f}" for j in range(len(ovens))))
row = packing hours, column = oven hours, profit in $ thousand
500 550 600 650 700 750 800
240 92.1 96.1 96.4 96.4 96.4 96.4 96.4
260 94.2 99.1 101.3 101.3 101.3 101.3 101.3
280 95.6 101.5 105.6 105.7 105.7 105.7 105.7
300 95.6 103.0 108.4 109.4 109.4 109.4 109.4
320 95.6 103.0 109.9 111.7 111.7 111.7 111.7
340 95.6 103.0 109.9 111.7 111.7 111.7 111.7
360 95.6 103.0 109.9 111.7 111.7 111.7 111.7
380 95.6 103.0 109.9 111.7 111.7 111.7 111.7

Read the grid from today's plan (the red box, $108.4 thousand):
- More oven hours alone (moving right) stop paying at 650: $109.4 thousand, whatever the ovens.
- More packing alone (moving up) stops at 320: $109.9 thousand.
- Both together reach $111.7 thousand: more than either alone, and more than the sum of the two gains. Ovens and packing are complements: each is worth more when you have more of the other.
A one-at-a-time analysis would miss this. Shadow prices are one-at-a-time by construction.
13.3 A scenario table
Real what-ifs change several numbers at once, and managers want to compare many of them. Keep scenarios as data: a CSV with one row per change, read into the database, so anyone can add a scenario without touching code. Create day13/scenarios.csv:
scenario,change,target,value,description
base,none,,,today's plan
lose_two_ovens,capacity_add,oven_hours,-100,two deck ovens out for repair
extra_ovens,capacity_add,oven_hours,100,lease two more deck ovens
extra_baker,capacity_add,baker_hours,40,hire one more baker
packing_shift,capacity_add,packing_hours,40,third packing shift on one line
starter_tank,capacity_add,sourdough_starter,12,second sourdough starter tank
ovens_and_packing,capacity_add,oven_hours,100,lease two ovens ...
ovens_and_packing,capacity_add,packing_hours,40,... and add the packing shift
butter_up_20,cost_multiply,viennoiserie,1.20,butter price rises 20% (viennoiserie ingredients)
cookie_demand_up,demand_multiply,cookie,1.5,cookie promotion lifts demand 50%
demand_down_10,demand_multiply,all,0.90,a weak week: all demand down 10%
ovens_and_packing has two rows: both changes apply. Three kinds of change cover these scenarios: add to a capacity, multiply demand caps (for a category, or all), multiply ingredient costs for a category (which lowers profit per batch). Then day13/run_scenarios.py:
import copy
import sys
import duckdb
import pandas as pd
import pyomo.environ as pyo
sys.path.insert(0, "day06")
from bakery import build_model, load_data, solve
pd.set_option("display.width", 160)
con = duckdb.connect("northbound.duckdb")
con.sql("CREATE OR REPLACE TABLE scenarios AS SELECT * FROM read_csv('day13/scenarios.csv')")
base_data = load_data(con)
ingredients = dict(con.sql("SELECT sku, units_per_batch * ingredient_cost FROM bakery_range").fetchall())
def apply(d, change, target, value):
"""Return a copy of the model data with one change applied."""
d = copy.deepcopy(d)
in_target = [p for p in d["products"] if target == "all" or d["category"][p] == target]
if change == "capacity_add":
d["capacity"][target] += value
elif change == "demand_multiply":
for p in in_target:
d["cap"][p] *= value
elif change == "cost_multiply":
for p in in_target:
d["profit"][p] -= ingredients[p] * (value - 1)
elif change != "none":
raise ValueError(f"unknown change {change}")
return d
def run(d):
m = build_model(d)
m.dual = pyo.Suffix(direction=pyo.Suffix.IMPORT)
solve(m)
binding = [r for r in m.R if m.dual[m.capacity_limit[r]] > 1e-6]
return m, pyo.value(m.total_profit), binding
results = []
base_m, base_profit, _ = run(base_data)
for name, rows in con.sql("SELECT * FROM scenarios").df().groupby("scenario", sort=False):
d = base_data
for r in rows.itertuples():
d = apply(d, r.change, r.target, r.value)
m, profit, binding = run(d)
moved = sum(abs(pyo.value(m.x[p]) - pyo.value(base_m.x[p])) > 1e-6 for p in m.P)
results.append((name, round(profit, 2), round(profit - base_profit, 2), moved, ", ".join(b.replace("_hours", "") for b in binding)))
out = pd.DataFrame(results, columns=["scenario", "profit", "change_vs_base", "products_changed", "binding_limits"])
con.sql("CREATE OR REPLACE TABLE scenario_results AS SELECT * FROM out")
print(con.sql("SELECT * FROM scenario_results ORDER BY change_vs_base DESC"))
con.close()
┌───────────────────┬───────────┬────────────────┬──────────────────┬─────────────────────────────────────────┐
│ scenario │ profit │ change_vs_base │ products_changed │ binding_limits │
│ varchar │ double │ double │ int64 │ varchar │
├───────────────────┼───────────┼────────────────┼──────────────────┼─────────────────────────────────────────┤
│ ovens_and_packing │ 111657.2 │ 3305.92 │ 3 │ baker, sourdough_starter │
│ packing_shift │ 109906.6 │ 1555.32 │ 5 │ baker, oven, sourdough_starter │
│ extra_ovens │ 109434.9 │ 1083.62 │ 5 │ baker, packing, sourdough_starter │
│ cookie_demand_up │ 108993.33 │ 642.05 │ 7 │ oven, packing, sourdough_starter │
│ starter_tank │ 108956.52 │ 605.24 │ 4 │ oven, packing, sourdough_starter │
│ base │ 108351.28 │ 0.0 │ 0 │ oven, packing, sourdough_starter │
│ extra_baker │ 108351.28 │ 0.0 │ 0 │ oven, packing, sourdough_starter │
│ demand_down_10 │ 106183.95 │ -2167.33 │ 27 │ baker, oven, packing, sourdough_starter │
│ butter_up_20 │ 105165.89 │ -3185.39 │ 4 │ oven, packing, sourdough_starter │
│ lose_two_ovens │ 95577.4 │ -12773.88 │ 5 │ oven │
└───────────────────┴───────────┴────────────────┴──────────────────┴─────────────────────────────────────────┘
10 rows 5 columns
copy.deepcopy gives each scenario its own copy of the data, so changes never leak into the next scenario: a classic source of silent errors in what-if code. products_changed counts products whose batches moved; binding_limits lists limits with a positive shadow price.
What the table says:
- Losing two ovens costs $12,774 a week, 12% of profit. Ovens become the only binding limit.
- Ovens and packing together add $3,306, more than ovens ($1,084) plus packing ($1,555): the complementarity from 13.2.
- An extra baker adds nothing on its own: bakers are not a bottleneck. Remember this for the mini-project.
- A 20% butter rise costs $3,185, but changes only 4 products: the viennoiserie mostly stays in the plan, earning less.
- A weak week (demand −10%) costs $2,167 and moves 27 of 30 products: with less demand, caps bind, and every limit binds, bakers included.
The results are stored in scenario_results, so the next step (a dashboard, a memo, Module 8's app) reads them from the database.
Decision it supports: a ranked list of what could go right or wrong, with a dollar value on each.
Other decisions you can support the same way: budget scenarios for a hospital · supply disruption plans · regulatory change impact studies.
13.4 Predict with shadow prices, or re-solve?
Shadow prices give instant predictions; re-solves give answers. How far apart are they?
import sys
import duckdb
import pyomo.environ as pyo
sys.path.insert(0, "day06")
from bakery import build_model, load_data, solve
con = duckdb.connect("northbound.duckdb", read_only=True)
d = load_data(con)
m = build_model(d)
m.dual = pyo.Suffix(direction=pyo.Suffix.IMPORT)
solve(m)
base = pyo.value(m.total_profit)
price = {r: m.dual[m.capacity_limit[r]] for r in m.R}
print(f"{'change':<26}{'predicted':>12}{'re-solved':>12}{'error':>10}")
for r, delta in [("oven_hours", 2), ("oven_hours", 10), ("oven_hours", 100), ("oven_hours", -100),
("packing_hours", 4), ("packing_hours", 40), ("sourdough_starter", 12), ("baker_hours", 40)]:
m2 = build_model(dict(d, capacity=dict(d["capacity"], **{r: d["capacity"][r] + delta})))
solve(m2)
predicted = price[r] * delta
actual = pyo.value(m2.total_profit) - base
print(f"{r + f' {delta:+d}':<26}{predicted:>12,.2f}{actual:>12,.2f}{actual - predicted:>10,.2f}")
change predicted re-solved error
oven_hours +2 198.68 198.68 -0.00
oven_hours +10 993.40 830.73 -162.67
oven_hours +100 9,934.00 1,083.62 -8,850.38
oven_hours -100 -9,934.00 -12,773.88 -2,839.88
packing_hours +4 377.84 377.84 -0.00
packing_hours +40 3,778.40 1,555.32 -2,223.08
sourdough_starter +12 649.08 605.24 -43.84
baker_hours +40 0.00 0.00 0.00
Inside the ranges from Day 12 (oven +2, packing +4) the prediction is exact. Beyond them it is always too optimistic for increases (it ignores diminishing returns) and too optimistic for losses too (losing 100 oven hours costs $12,774, not the predicted $9,934). For 100 extra oven hours the prediction is off by a factor of nine.
| Use shadow prices to… | Re-solve to… |
|---|---|
| Rank which limits matter | Value any change bigger than its range |
| Explain a plan to a manager | Answer any question about money |
| Spot complementary slackness (overtime at $60) | Combine several changes |
Mini-project: which investments to make
The plant manager has three options, each with a weekly cost, plus packing overtime by the hour:
| Option | Adds | Cost a week |
|---|---|---|
| Lease 2 deck ovens | 100 oven hours | $900 |
| Hire a baker | 40 baker hours | $1,600 |
| Second starter tank | 12 batches of starter | $250 |
| Packing overtime | up to 40 hours | $60 an hour |
Evaluate all 8 combinations of the three yes/no options. In each, let the model choose packing overtime hours (a variable, as in the capstone). Rank the combinations by net weekly profit after costs, and recommend.
Solution
import itertools
import sys
import duckdb
import pandas as pd
import pyomo.environ as pyo
sys.path.insert(0, "day06")
from bakery import build_model, load_data, solve
pd.set_option("display.width", 140)
con = duckdb.connect("northbound.duckdb", read_only=True)
d = load_data(con)
OPTIONS = { # name: (resource, extra capacity a week, cost a week in $)
"lease 2 ovens": ("oven_hours", 100, 900),
"hire a baker": ("baker_hours", 40, 1600),
"starter tank": ("sourdough_starter", 12, 250),
}
OVERTIME_PACKING = (40, 60) # up to 40 hours a week at $60 an hour
rows = []
for choice in itertools.product([False, True], repeat=len(OPTIONS)):
cap = dict(d["capacity"])
fixed = 0
for take, (name, (r, extra, cost)) in zip(choice, OPTIONS.items()):
if take:
cap[r] += extra
fixed += cost
m = build_model(dict(d, capacity=cap))
# packing overtime as a variable: the model books as many hours as pay
m.ot = pyo.Var(bounds=(0, OVERTIME_PACKING[0]))
pk = m.capacity_limit["packing_hours"]
pk.set_value(pk.body <= cap["packing_hours"] + m.ot)
m.total_profit.deactivate()
m.net = pyo.Objective(expr=sum(m.profit[p] * m.x[p] for p in m.P) - OVERTIME_PACKING[1] * m.ot, sense=pyo.maximize)
solve(m)
rows.append((" + ".join(n for t, n in zip(choice, OPTIONS) if t) or "nothing", round(pyo.value(m.ot), 2),
round(pyo.value(m.net), 2), fixed, round(pyo.value(m.net) - fixed, 2)))
t = pd.DataFrame(rows, columns=["investments", "packing_overtime_h", "profit_after_overtime", "weekly_cost", "net"])
t["vs_nothing"] = (t.net - t.net[t.investments == "nothing"].iloc[0]).round(2)
print(t.sort_values("net", ascending=False).to_string(index=False))
investments packing_overtime_h profit_after_overtime weekly_cost net vs_nothing
lease 2 ovens + hire a baker + starter tank 31.66 115738.56 2750 112988.56 4151.27
lease 2 ovens + hire a baker 28.78 114041.28 2500 111541.28 2703.99
lease 2 ovens + starter tank 16.62 112470.58 1150 111320.58 2483.29
lease 2 ovens 13.25 110862.50 900 109962.50 1125.21
starter tank 12.92 109359.46 250 109109.46 272.17
nothing 17.66 108837.29 0 108837.29 0.00
hire a baker + starter tank 12.92 109359.46 1850 107509.46 -1327.83
hire a baker 17.66 108837.29 1600 107237.29 -1600.00
Recommendation: "Do all three: lease the ovens, hire a baker and install the starter tank, and book about 32 hours of packing overtime a week. Net gain $4,151 a week. The baker is the surprise: alone he loses $1,600 a week, because bakers are not a bottleneck today; with two more ovens, bakers become one, and adding the baker to the oven lease raises the net gain by a further $1,579 a week after his cost."
itertools.product([False, True], repeat=3) lists the 8 combinations. Eight solves are fine; with 30 options there would be a billion combinations, and the yes/no choices belong inside the model as binary variables. That is Module 3.
Commit
git add .
git commit -m "Day 13: sweeps, scenario table, investments"
git push
Day 13 checklist
- I can sweep a parameter by rebuilding the model or by changing one constraint.
- I can read a value curve and its staircase of marginal values.
- I found complementary limits with a two-way sweep.
- My scenarios are data in a CSV and a table, and the results are stored in the database.
- I know when a shadow price predicts well and when to re-solve.
- I evaluated every combination of three investments and found why a useless baker becomes useful.