Module 2 works with the code and database from Module 1. Start from your v1.0-module1 tag, with northbound.duckdb built by day06/load_tables.py.
11.1 Asking the solver for shadow prices
The shadow price of a constraint is how much the objective improves per unit of extra right-hand side, with everything else unchanged. For a capacity, it is what one more hour is worth. Pyomo receives it from the solver if you declare a suffix called dual on the model before solving:
m.dual = pyo.Suffix(direction=pyo.Suffix.IMPORT)
After the solve, m.dual[constraint] holds that constraint's shadow price. Create day11/shadow_prices.py. It reuses Day 6's bakery.py, and compares each shadow price with the Day 2 method, re-solving with one more unit:
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", 120)
con = duckdb.connect("northbound.duckdb", read_only=True)
con.sql("CREATE TEMP VIEW module1_products AS SELECT *, 'module 1' AS category FROM bakery_products")
con.sql("CREATE TEMP VIEW module1_forecast AS SELECT sku, demand_cap_batches FROM forecast_next_week")
def solve_with_duals(m):
"""Ask the solver to send back a dual value (shadow price) for every constraint."""
m.dual = pyo.Suffix(direction=pyo.Suffix.IMPORT)
solve(m)
return m
# ---------- 11.1 The 3-product bakery: re-solving versus asking the solver ----------
d = load_data(con, "module1_products", "bakery_recipe", "bakery_resources", "module1_forecast")
m = solve_with_duals(build_model(d))
base = pyo.value(m.total_profit)
print(f"profit ${base:,.2f}")
print(f"{'resource':<18}{'dual':>10}{'re-solve +1':>14}")
for r in m.R:
more = dict(d, capacity=dict(d["capacity"], **{r: d["capacity"][r] + 1}))
m1 = build_model(more)
solve(m1)
print(f"{r:<18}{m.dual[m.capacity_limit[r]]:>10.2f}{pyo.value(m1.total_profit) - base:>14.2f}")
print("demand caps:", {p: round(m.dual[m.demand[p]], 2) for p in m.P})
profit $17,500.00
resource dual re-solve +1
baker_hours 33.33 33.33
oven_hours 133.33 133.33
sourdough_starter 0.00 0.00
demand caps: {'BK-CR': 0.0, 'BK-SD': 0.0, 'BK-WW': 33.33}
The solver's numbers match the re-solves exactly, at the cost of one solve instead of four:
- Oven $133.33 an hour, bakers $33.33: Day 2's numbers.
- Starter $0: 20 batches of starter are spare, and more of something spare is worth nothing.
- The whole-wheat cap is worth $33.33 a batch: one more batch of whole-wheat demand would add $33.33. Croissant and sourdough caps are worth nothing; the bakery doesn't reach them.
A constraint with slack has a shadow price of zero; a constraint with a positive shadow price is binding. That pairing is called complementary slackness, and it is a quick way to read a plan.
Decision it supports: which limit to relax first, and the most to pay for relaxing it.
Other decisions you can support the same way: what one more truck, nurse shift or warehouse door is worth · the value of a tighter or looser regulation.
11.2 The dual problem: renting out the bakery
Where do shadow prices come from? Every LP has a twin, its dual, and the shadow prices are the dual's solution.
Imagine a competitor wants to rent the whole bakery for a week: the ovens, the bakers, the starter, and the right to sell up to each product's demand cap. They offer a price per oven hour , per baker hour , per batch of starter , and per batch of demand . Northbound will only accept a fair offer: for every product, the rent on what one batch uses must be at least the profit Northbound would make baking it itself. The competitor wants the cheapest fair offer:
Every number of the original model appears, transposed: the original's capacities become the dual's costs, its profits become the dual's limits, and each column of the recipe becomes a row.
# ---------- 11.2 The dual problem: what would someone pay to rent the bakery? ----------
dual = pyo.ConcreteModel()
dual.R = pyo.Set(initialize=d["resources"])
dual.P = pyo.Set(initialize=d["products"])
dual.y = pyo.Var(dual.R, within=pyo.NonNegativeReals) # rent per unit of each resource
dual.z = pyo.Var(dual.P, within=pyo.NonNegativeReals) # rent per batch of each product's demand
dual.rent = pyo.Objective(expr=sum(d["capacity"][r] * dual.y[r] for r in dual.R)
+ sum(d["cap"][p] * dual.z[p] for p in dual.P)) # minimize
dual.fair = pyo.Constraint(dual.P, rule=lambda dm, p: sum(d["use"].get((r, p), 0) * dm.y[r] for r in dm.R) + dm.z[p] >= d["profit"][p])
pyo.SolverFactory("highs").solve(dual)
print(f"cheapest fair rent ${pyo.value(dual.rent):,.2f}")
print({r: round(pyo.value(dual.y[r]), 2) for r in dual.R}, {p: round(pyo.value(dual.z[p]), 2) for p in dual.P})
# Complementary slackness, checked product by product
for p in m.P:
resource_cost = sum(d["use"].get((r, p), 0) * m.dual[m.capacity_limit[r]] for r in m.R)
print(f" {p}: makes {pyo.value(m.x[p]):5.1f}, profit {d['profit'][p]:6.1f}, "
f"resources worth {resource_cost:6.2f}, cap worth {m.dual[m.demand[p]]:5.2f}")
cheapest fair rent $17,500.00
{'baker_hours': 33.33, 'oven_hours': 133.33, 'sourdough_starter': 0.0} {'BK-CR': 0.0, 'BK-SD': 0.0, 'BK-WW': 33.33}
BK-CR: makes 10.0, profit 250.0, resources worth 250.00, cap worth 0.00
BK-SD: makes 20.0, profit 300.0, resources worth 300.00, cap worth 0.00
BK-WW: makes 45.0, profit 200.0, resources worth 166.67, cap worth 33.33
Two results, both true of every LP:
- Strong duality: the cheapest fair rent, $17,500, equals the best profit. Northbound is indifferent between baking and renting out at those prices.
- The rents are the shadow prices. The competitor's prices for oven, bakers and starter are exactly $133.33, $33.33 and $0.
The product-by-product check is complementary slackness again. Every product the bakery makes "pays for" the resources it uses at shadow prices: croissant and sourdough exactly ($250 = $250, $300 = $300), whole-wheat with its cap's value ($166.67 + $33.33 = $200). A product whose resources cost more than its profit would not be made at all; Day 12 calls that gap its reduced cost.
Math corner (optional): why strong duality holds
For any plan that fits and any fair rent , profit ≤ rent: each batch earns at most what its resources rent for, and the bakery uses at most what it has. This is weak duality, and it takes two lines of algebra: multiply each capacity constraint by its , each cap by its , add them up, and compare with the fairness rows. Strong duality says the gap closes at the optimum; the simplex method proves it by construction, because its final basis gives a fair rent equal to the plan's profit. The practical meaning: if someone shows you a plan and a set of prices with equal value, both are optimal, and you can check it by hand.
11.3 Shadow prices for the full range
The same suffix on the 30-product model:
# ---------- 11.3 The full range ----------
d = load_data(con)
m = solve_with_duals(build_model(d))
print(f"full range profit ${pyo.value(m.total_profit):,.2f}")
res = pd.DataFrame([(r, pyo.value(m.capacity_limit[r].body), d["capacity"][r], m.dual[m.capacity_limit[r]]) for r in m.R],
columns=["resource", "used", "capacity", "shadow_price"]).round(2)
print(res.to_string(index=False))
caps = pd.DataFrame([(p, d["name"][p], pyo.value(m.x[p]), d["cap"][p], m.dual[m.demand[p]]) for p in m.P],
columns=["sku", "product", "batches", "cap", "shadow_price"]).round(2)
print("Most valuable demand caps (one more batch of demand is worth):")
print(caps.sort_values("shadow_price", ascending=False).head(6).to_string(index=False))
full range profit $108,351.28
resource used capacity shadow_price
baker_hours 539.62 560 0.00
oven_hours 600.00 600 99.34
packing_hours 300.00 300 94.46
sourdough_starter 60.00 60 54.09
Most valuable demand caps (one more batch of demand is worth):
sku product batches cap shadow_price
BK-10 Raisin bread 20.0 20 134.38
BK-04 Multigrain loaf 18.0 18 107.21
BK-17 Apple turnover 4-pack 9.0 9 73.87
BK-06 Country white loaf 8.0 8 70.60
BK-16 Brioche loaf 9.0 9 60.50
BK-13 Almond croissant 4-pack 27.0 27 57.30
For the bakery manager:
- An oven hour is worth $99.34, a packing hour $94.46, a batch of starter $54.09. Baker hours are worth nothing: 20 are spare.
- Packing overtime costs $60 an hour, less than $94.46: worth booking, at least for the first few hours. That is the Module 1 capstone's overtime decision, read straight from one number.
- The most valuable demand cap is raisin bread ($134.38 a batch): if marketing can sell more of one product, raisin bread is the one. Cakes, absent from this list, have caps worth nothing: the bakery doesn't bake them.
A shadow price is a marginal value: true for a small change, not necessarily for a large one. How small? Day 12 answers that.
Try it 11.1
Which products' demand caps have a shadow price of zero even though the product is made? What does that tell you?
Solution
print(caps[(caps.batches > 0) & (caps.shadow_price == 0)])
sku product batches cap shadow_price
14 BK-18 Butter tart 6-pack 25.0 30 0.0
22 BK-26 Chocolate chip cookies 12-pack 1.6 9 0.0
28 BK-SD Sourdough loaf 35.0 35 0.0
Butter tarts (25 of 30) and chocolate chip cookies (1.6 of 9) are below their caps, so more demand is worth nothing: the bakery can't bake more of them profitably. These are the marginal products, which absorb any extra or missing capacity: the first to move in any what-if.
Sourdough is the odd one: it is at its cap of 35, yet the cap is "worth" nothing. More sourdough demand would need more starter, which is also full, and the solver has put the value on the starter instead. Two limits bind on the same product at once: a degenerate corner, the subject of 11.4, and the first sign that sourdough is fragile (Day 12).
11.4 When shadow prices mislead: degenerate corners
On Day 3 you met a degenerate corner: three lines through one point. With croissants fixed at 10 and whole-wheat capped at 45, the best plan (20, 45) sits on the oven line, the baker line and the cap at once. What are the shadow prices there?
# ---------- 11.4 Degenerate corners: the dual is not unique ----------
deg = pyo.ConcreteModel()
deg.S = pyo.Var(bounds=(0, 35))
deg.W = pyo.Var(bounds=(0, 45))
deg.oven = pyo.Constraint(expr=2 * deg.S + deg.W <= 85) # croissants fixed at 10 (Day 3, Try it 3.2)
deg.bakers = pyo.Constraint(expr=deg.S + deg.W <= 65)
deg.profit = pyo.Objective(expr=300 * deg.S + 200 * deg.W, sense=pyo.maximize)
deg.dual = pyo.Suffix(direction=pyo.Suffix.IMPORT)
pyo.SolverFactory("highs").solve(deg)
print(f"degenerate corner S={pyo.value(deg.S):g}, W={pyo.value(deg.W):g}: "
f"oven dual {deg.dual[deg.oven]:.2f}, bakers dual {deg.dual[deg.bakers]:.2f}")
for change in (+1, -1):
for name, con_ in (("oven", deg.oven), ("bakers", deg.bakers)):
rhs = con_.upper
con_.set_value(con_.body <= rhs + change)
pyo.SolverFactory("highs").solve(deg)
print(f" {name} {change:+d} hour: profit changes by {pyo.value(deg.profit) - 15000:+.2f}")
con_.set_value(con_.body <= rhs)
degenerate corner S=20, W=45: oven dual 150.00, bakers dual 0.00
oven +1 hour: profit changes by +100.00
bakers +1 hour: profit changes by +0.00
oven -1 hour: profit changes by -150.00
bakers -1 hour: profit changes by -100.00
The solver says an oven hour is worth $150 and a baker hour nothing. But one more oven hour adds only $100, one less costs $150, and one less baker hour costs $100 although its "price" is zero. At a degenerate corner, the value of a resource depends on the direction of the change, and the solver reports just one of several valid dual solutions.
The rule: shadow prices are exact for small changes at a non-degenerate corner. When a plan has more binding constraints than usual, or when a decision rides on a shadow price, check it with a re-solve in the direction you care about. It takes a second.
Mini-project: what is an hour worth, week by week?
In the Module 1 capstone, the plan booked packing overtime in 11 of 12 weeks, the full 40 hours in only 3. Shadow prices explain exactly why. Add the dual suffix to the capstone model and report, for each week, the shadow price of oven hours, packing hours (after overtime), starter and freezer, next to the packing overtime booked.
Solution
import sys
import duckdb
import pandas as pd
import pyomo.environ as pyo
sys.path.insert(0, "day08")
sys.path.insert(0, "day10")
from capstone import build_capstone
from planner import solve
pd.set_option("display.width", 120)
con = duckdb.connect("northbound.duckdb", read_only=True)
d, m = build_capstone(con)
m.dual = pyo.Suffix(direction=pyo.Suffix.IMPORT)
solve(m)
rows = []
for t in m.T:
rows.append((t,
m.dual[m.capacity["oven_hours", t]],
m.dual[m.capacity["packing_hours", t]],
pyo.value(m.overtime["packing_hours", t]),
m.dual[m.capacity["sourdough_starter", t]],
m.dual[m.freezer[t]]))
weekly = pd.DataFrame(rows, columns=["week", "oven_$_per_h", "packing_$_per_h", "packing_overtime_h",
"starter_$_per_batch", "freezer_$_per_slot"]).set_index("week").round(2) + 0.0
print(weekly.to_string())
print("Weeks where packing overtime is between 0 and 40 hours have a packing shadow price of exactly $60:")
print(weekly[(weekly.packing_overtime_h > 0) & (weekly.packing_overtime_h < 40)][["packing_$_per_h"]].T.to_string())
oven_$_per_h packing_$_per_h packing_overtime_h starter_$_per_batch freezer_$_per_slot
week
1 126.23 75.88 40.00 9.60 0.0
2 132.57 71.90 40.00 0.00 0.0
3 139.95 66.79 40.00 18.99 0.0
4 149.06 60.00 13.36 12.13 0.0
5 137.65 60.00 22.22 0.00 0.0
6 114.63 60.00 32.80 40.74 0.0
7 117.36 60.00 26.06 35.28 0.0
8 119.36 60.00 6.99 46.70 0.0
9 122.81 60.00 29.37 24.38 0.0
10 125.54 60.00 39.11 40.35 0.0
11 128.27 60.00 26.89 13.47 0.0
12 134.10 56.73 0.00 3.25 0.0
Weeks where packing overtime is between 0 and 40 hours have a packing shadow price of exactly $60:
week 4 5 6 7 8 9 10 11
packing_$_per_h 60.0 60.0 60.0 60.0 60.0 60.0 60.0 60.0
Three patterns, each a lesson:
- Packing is worth exactly $60 in every week where overtime is between 0 and 40 hours. The model books overtime until one more hour is worth exactly what it costs. In weeks 1–3, overtime is at its 40-hour limit, and an hour is worth more ($66.79 to $75.88): the bakery would book more if it could. In week 12, no overtime is booked, and an hour is worth $56.73, less than $60. Complementary slackness, in business terms.
- The oven is worth most in Christmas week ($149.06), when capacity drops to 60% and demand peaks. The busiest hour of the year is the most valuable one.
- The freezer is worth $0 every week: it never fills (Day 8's finding, now in one column).
Commit
git add .
git commit -m "Day 11: shadow prices, the dual, degenerate corners"
git push
Day 11 checklist
- I can get shadow prices from Pyomo with a
dualsuffix. - I can explain a shadow price as the value of one more unit of a limit.
- I can write the dual of a small LP and check that its value equals the plan's profit.
- I use complementary slackness to read a plan: binding limits have prices, slack ones don't.
- I check shadow prices with a re-solve at degenerate corners.
- I explained the capstone's overtime pattern with weekly shadow prices.