Update the course data
Copy the latest make_data.py from the Course data page, then rebuild the data and the database:
python make_data.py
python day01/ladder.py
python day06/load_tables.py
Four new tables matter today:
| Table | What it holds |
|---|---|
plan_weeks | 12 weeks from 30 November 2026, with each week's share of normal capacity (Christmas week 0.6, New Year's week 0.8, Family Day week 0.8) |
plan_demand | Demand for each of the 30 products in each week, in batches, with the Christmas peak (bread ×1.15, viennoiserie ×1.45, cakes ×1.6, cookies ×1.8 in weeks 3 and 4) |
bakery_storage | For each category: how many weeks a batch keeps, the cost of holding it a week, and the freezer slots it takes |
plan_settings | Freezer size (120 slots), overtime limits and prices, the café contract, the shelf rule |
category,shelf_life_weeks,holding_cost_per_batch_week,freezer_slots_per_batch,note
bread,0,0,0,baked and sold the same week
viennoiserie,3,8.0,1.0,"frozen unbaked, baked off in stores"
cake,2,12.0,1.5,frozen finished cakes
cookie,4,3.0,0.5,"packed, shelf-stable"
Bread cannot be stored: it is baked and sold the same week. Everything else can wait in the freezer or dry store for a few weeks, at a price.
8.1 Two weeks, one product, by hand
The smallest version of the idea. Croissants: the bakery can make 10 batches a week; demand is 5 batches in week 1 and 15 in week 2. A batch sells for $350, its ingredients cost $100, and a batch kept in the freezer for a week costs $8.
Week by week, the bakery makes 5 in week 1 (no point making more) and 10 in week 2 (its limit): 15 batches sold. Planning both weeks together, it makes 10 in week 1, sells 5 and keeps 5, then makes 10 more in week 2 and sells 15. That is 20 sold.
Three variables per product and week do the job:
- make : batches baked in week
- sell : batches sold in week
- keep : batches in stock at the end of week
tied together by a balance constraint, one per product and week: what you had, plus what you bake, equals what you sell plus what you keep.
Create day08/toy.py:
import pyomo.environ as pyo
m = pyo.ConcreteModel()
m.T = pyo.Set(initialize=[1, 2], ordered=True)
demand = {1: 5, 2: 15} # batches of croissants
m.make = pyo.Var(m.T, bounds=(0, 10)) # at most 10 batches a week
m.sell = pyo.Var(m.T, within=pyo.NonNegativeReals)
m.keep = pyo.Var(m.T, within=pyo.NonNegativeReals)
m.balance = pyo.Constraint(m.T, rule=lambda m, t: (m.keep[t - 1] if t > 1 else 0) + m.make[t] == m.sell[t] + m.keep[t])
m.sales = pyo.Constraint(m.T, rule=lambda m, t: m.sell[t] <= demand[t])
m.profit = pyo.Objective(expr=sum(350 * m.sell[t] - 100 * m.make[t] - 8 * m.keep[t] for t in m.T), sense=pyo.maximize)
pyo.SolverFactory("highs").solve(m)
for t in m.T:
print(f"week {t}: make {pyo.value(m.make[t]):g}, sell {pyo.value(m.sell[t]):g}, keep {pyo.value(m.keep[t]):g}")
print(f"profit ${pyo.value(m.profit):,.2f}")
week 1: make 10, sell 5, keep 5
week 2: make 10, sell 15, keep 0
profit $4,960.00
Check by hand: 20 batches sold × $350 = $7,000, minus 20 baked × $100 = $2,000, minus 5 kept × $8 = $40: $4,960.
Notice the profit is no longer "profit per batch × batches". Ingredients are paid when you bake, revenue arrives when you sell, and holding costs accrue while you wait. In a one-week model these moments coincide; across weeks they do not, so each gets its own term.
8.2 The model: make, sell, keep
For the full range we put the model in a module, day08/planner.py, built like Day 6's bakery.py: load the data, build, solve, report. On paper:
The shelf-life rule says stock at the end of week must have been baked in the last weeks. For bread : the sum is empty and stock must be zero. For cookies : stock can't exceed what was baked in the last four weeks.
"""Day 8: a multi-week bakery plan with storage. Used again on Days 9 and 10.
Import it: from planner import load_plan_data, build, solve, plan_table, week_table
"""
import duckdb
import pandas as pd
import pyomo.environ as pyo
def load_plan_data(con, weeks=6):
"""Everything the multi-week model needs, as plain Python objects."""
p = con.sql("""
SELECT p.sku, p.product_name, p.category,
p.units_per_batch * p.transfer_price AS revenue_per_batch,
p.units_per_batch * p.ingredient_cost AS ingredients_per_batch,
s.shelf_life_weeks, s.holding_cost_per_batch_week, s.freezer_slots_per_batch
FROM bakery_range p JOIN bakery_storage s USING (category)
ORDER BY p.sku""").df().set_index("sku")
w = con.sql(f"SELECT week, week_start, capacity_factor FROM plan_weeks WHERE week <= {weeks} ORDER BY week").df()
dem = con.sql(f"SELECT sku, week, demand_batches FROM plan_demand WHERE week <= {weeks}").fetchall()
use = con.sql("SELECT resource, sku, use_per_batch FROM bakery_range_recipe").fetchall()
cap = dict(con.sql("SELECT resource, weekly_capacity FROM bakery_range_resources").fetchall())
settings = dict(con.sql("SELECT setting, value FROM plan_settings").fetchall())
missing = set(p.index) - {s for s, _, _ in dem}
if missing or len(dem) != len(p) * len(w):
raise ValueError(f"demand must have one row per product and week; missing products: {sorted(missing)}")
return {
"products": p,
"weeks": w,
"demand": {(s, t): d for s, t, d in dem},
"use": {(r, s): u for r, s, u in use},
# Holidays cut oven, baker and packing hours; the starter culture works every day
"capacity": {(r, t): c * (f if r.endswith("_hours") else 1)
for r, c in cap.items() for t, f in zip(w.week, w.capacity_factor)},
"resources": list(cap),
"freezer_slots": float(settings["freezer_slots"]),
}
def build(d, storage=True):
"""make: batches baked in week t; sell: batches sold; keep: batches in stock at the end of week t."""
P, products = list(d["products"].index), d["products"]
m = pyo.ConcreteModel(name="bakery_weeks")
m.P = pyo.Set(initialize=P)
m.R = pyo.Set(initialize=d["resources"])
m.T = pyo.Set(initialize=d["weeks"].week.tolist(), ordered=True)
m.demand = pyo.Param(m.P, m.T, initialize=d["demand"])
m.use = pyo.Param(m.R, m.P, initialize=d["use"], default=0)
m.cap = pyo.Param(m.R, m.T, initialize=d["capacity"], mutable=True)
m.freezer_slots = pyo.Param(initialize=d["freezer_slots"], mutable=True)
m.make = pyo.Var(m.P, m.T, within=pyo.NonNegativeReals)
m.sell = pyo.Var(m.P, m.T, within=pyo.NonNegativeReals)
m.keep = pyo.Var(m.P, m.T, within=pyo.NonNegativeReals)
def balance(m, p, t):
before = m.keep[p, m.T.prev(t)] if t != m.T.first() else 0 # the plan starts with empty stores
return before + m.make[p, t] == m.sell[p, t] + m.keep[p, t]
def shelf_life(m, p, t):
L = int(products.loc[p, "shelf_life_weeks"]) if storage else 0
return m.keep[p, t] <= sum(m.make[p, k] for k in m.T if t - L < k <= t)
m.balance = pyo.Constraint(m.P, m.T, rule=balance)
m.sales_limit = pyo.Constraint(m.P, m.T, rule=lambda m, p, t: m.sell[p, t] <= m.demand[p, t])
m.capacity = pyo.Constraint(m.R, m.T, rule=lambda m, r, t: sum(m.use[r, p] * m.make[p, t] for p in m.P) <= m.cap[r, t])
m.shelf_life = pyo.Constraint(m.P, m.T, rule=shelf_life)
m.freezer = pyo.Constraint(m.T, rule=lambda m, t: sum(
products.loc[p, "freezer_slots_per_batch"] * m.keep[p, t] for p in m.P) <= m.freezer_slots)
m.revenue = pyo.Expression(expr=sum(products.loc[p, "revenue_per_batch"] * m.sell[p, t] for p in m.P for t in m.T))
m.ingredients = pyo.Expression(expr=sum(products.loc[p, "ingredients_per_batch"] * m.make[p, t] for p in m.P for t in m.T))
m.holding = pyo.Expression(expr=sum(products.loc[p, "holding_cost_per_batch_week"] * m.keep[p, t] for p in m.P for t in m.T))
m.profit = pyo.Objective(expr=m.revenue - m.ingredients - m.holding, sense=pyo.maximize)
return m
def solve(m):
result = pyo.SolverFactory("highs").solve(m, load_solutions=False)
if result.solver.termination_condition != pyo.TerminationCondition.optimal:
raise RuntimeError(f"no optimal plan: {result.solver.termination_condition}")
m.solutions.load_from(result)
return result
def v(x):
return round(pyo.value(x), 2) + 0.0 # + 0.0 turns -0.0 into 0.0
def plan_table(m, d):
rows = [(t, p, d["products"].loc[p, "category"], v(m.make[p, t]), v(m.sell[p, t]), v(m.demand[p, t]), v(m.keep[p, t]))
for t in m.T for p in m.P]
df = pd.DataFrame(rows, columns=["week", "sku", "category", "make", "sell", "demand", "keep"])
df["lost"] = (df.demand - df.sell).round(2) + 0.0
return df
def week_table(m, d):
slots = d["products"]["freezer_slots_per_batch"]
rows = []
for t in m.T:
rows.append((t, d["weeks"].set_index("week").loc[t, "capacity_factor"],
v(sum(m.demand[p, t] for p in m.P)), v(sum(m.sell[p, t] for p in m.P)),
v(sum(slots[p] * m.keep[p, t] for p in m.P)),
v(sum(m.cap[r, t] - m.capacity[r, t].body for r in ["oven_hours"]))))
return pd.DataFrame(rows, columns=["week", "capacity", "demand", "sold", "freezer_slots_used", "spare_oven_hours"])
Points to slow down for:
m.Tis an ordered set, som.T.prev(t)andm.T.first()work. Writingm.keep[p, t - 1]instead fails in week 1 with aKeyError: there is no week 0. Every multi-period model needs a rule for the first period; here, the plan starts with empty stores.- Capacity per week:
load_datamultiplies oven, baker and packing hours by the week's factor. The starter culture is alive every day, so it is not cut. m.capandm.freezer_slotsare mutable, so what-ifs change them without rebuilding.week_tablereports the week as a whole: demand, sales, freezer use and spare oven hours.
Decision it supports: how much of each product to bake each week, and what to build up ahead of a peak.
Other decisions you can support the same way: staffing ahead of a busy season · building stock before a plant shutdown · hydro reservoir releases over a season.
8.3 Six weeks of the full range
Create day08/run_weeks.py:
import sys
import duckdb
import pandas as pd
sys.path.insert(0, "day08")
from planner import build, load_plan_data, plan_table, solve, week_table
pd.set_option("display.width", 120)
con = duckdb.connect("northbound.duckdb", read_only=True)
d = load_plan_data(con, weeks=6)
m = build(d)
solve(m)
print(week_table(m, d).to_string(index=False))
plan = plan_table(m, d)
stock = plan[plan.keep > 0].pivot_table(index="sku", columns="week", values="keep", aggfunc="sum", fill_value=0)
print("Batches in stock at the end of each week:")
print(stock.join(d["products"]["product_name"]).to_string())
print(plan.groupby("category")[["make", "sell", "demand", "lost"]].sum().round(1).to_string())
print(f"profit ${m.profit():,.2f} = revenue ${m.revenue():,.2f} - ingredients ${m.ingredients():,.2f} - holding ${m.holding():,.2f}")
week_by_week = build(d, storage=False)
solve(week_by_week)
print(f"without storage: ${week_by_week.profit():,.2f}; planning ahead adds ${m.profit() - week_by_week.profit():,.2f}")
week capacity demand sold freezer_slots_used spare_oven_hours
1 1.0 602.6 365.29 43.27 0.0
2 1.0 605.6 366.40 83.87 0.0
3 1.0 865.9 427.01 106.36 0.0
4 0.6 865.8 426.40 0.00 0.0
5 0.8 552.3 349.41 0.00 0.0
6 1.0 537.1 421.48 0.00 0.0
Batches in stock at the end of each week:
1 2 3 product_name
sku
BK-12 0.00 20.65 20.90 Pain au chocolat 4-pack
BK-16 24.67 26.60 13.40 Brioche loaf
BK-27 37.19 73.23 44.30 Nanaimo bars 6-pack
BK-28 0.00 0.00 23.84 Date squares 6-pack
BK-CR 0.00 0.00 37.98 Croissant 6-pack
make sell demand lost
category
bread 1005.0 1005.0 1310.1 305.1
cake 97.4 97.4 862.7 765.3
cookie 527.9 527.9 813.7 285.8
viennoiserie 725.7 725.7 1042.8 317.1
profit $597,870.27 = revenue $909,487.71 - ingredients $309,928.06 - holding $1,689.37
without storage: $595,836.82; planning ahead adds $2,033.45
Read it as the bakery manager would:
- The freezer fills before Christmas (43, 84, then 106 slots) and is empty after Christmas week: everything built up is sold in week 4, when capacity drops to 60% while demand stays at its peak.
- What gets stored is Nanaimo bars, brioche, pain au chocolat, date squares and croissants: products that keep, earn well, and whose Christmas demand far exceeds what week 4 can bake.
- Planning ahead adds $2,033.45 over six weeks against a week-by-week plan (
storage=Falsesets every shelf life to 0). Small against a $600,000 total, because the bakery is short of capacity every single week: there is little spare time to bake ahead. Spare capacity is what makes inventory valuable. - Demand is far above what the bakery can make in every week (602 batches of demand, 365 sold in week 1). That is not a planning failure; it is Days 1–7's finding, and the reason Module 3 will look at a bigger plant.
m.profit() is shorthand for pyo.value(m.profit); Pyomo objectives and expressions can be called like functions.
Try it 8.1
Which category loses the most demand, in batches and as a share of its demand? Using the numbers above, why does the model let it happen?
Solution
Cakes: 765.3 of 862.7 batches lost, 89% of cake demand. Bread loses 305.1 of 1,310.1 (23%), cookies 35%, viennoiserie 30%. Cakes use the most baker and oven time per dollar of profit (Day 6, Try it 6.1), so when capacity is short, they are the first to go. Whether that is acceptable is a business question: Day 10 adds a rule that keeps every product on the shelf.
8.4 Horizons and end effects
The model plans six weeks. What happens after week 6 doesn't exist for it, so it ends with empty stores: nothing is kept for week 7, because stock left at the end earns nothing. That is the end effect: every finite plan behaves oddly near its last period.
Planning 12 weeks instead, with the same code:
# Does a longer horizon change the first weeks?
d12 = load_plan_data(con, weeks=12)
m12 = build(d12)
solve(m12)
print(week_table(m12, d12).to_string(index=False))
week capacity demand sold freezer_slots_used spare_oven_hours
1 1.0 602.6 365.29 43.27 0.0
2 1.0 605.6 366.40 83.87 0.0
3 1.0 865.9 427.01 106.36 0.0
4 0.6 865.8 426.40 0.00 0.0
5 0.8 552.3 349.41 0.00 0.0
6 1.0 537.1 414.32 7.87 0.0
7 1.0 543.5 408.39 21.14 0.0
8 1.0 617.3 442.70 10.13 0.0
9 1.0 607.9 436.20 3.70 0.0
10 1.0 613.6 431.34 3.23 0.0
11 1.0 620.0 412.40 23.23 0.0
12 0.8 613.2 378.66 0.00 0.0
Weeks 1–5 are identical. Week 6 changes: in the 12-week plan it sells 414.32 batches instead of 421.48 and keeps 7.87 freezer slots of stock for the weeks after. The six-week plan sold that stock in week 6 because, for it, there was no week 7.
The practical rule: plan further ahead than you act. Planners run a long horizon, carry out only the first week or two, and re-plan next week with fresh data: a rolling horizon (Day 39 and Module 8). The weeks you act on should be far from the end of the horizon.
The planted bug
day08/bug_balance.py rebuilds the balance with a single character changed. Run it and look at the two numbers it prints.
def balance(m, p, t):
before = m.keep[p, m.T.prev(t)] if t != m.T.first() else 0
return before + m.make[p, t] == m.sell[p, t] - m.keep[p, t]
m.del_component(m.balance)
m.balance = pyo.Constraint(m.P, m.T, rule=balance)
solve(m)
print(f"profit ${m.profit():,.2f}")
made = sum(pyo.value(m.make[p, t]) for p in m.P for t in m.T)
sold = sum(pyo.value(m.sell[p, t]) for p in m.P for t in m.T)
print(f"batches made {made:,.1f}, batches sold {sold:,.1f}")
What happens, and how to spot it
profit $1,022,646.51
batches made 1,838.2, batches sold 3,400.7
The model sells 3,400 batches having made 1,838. The balance says before + make == sell - keep: a minus sign where a plus belongs, so every batch "kept" lets the bakery sell one more batch it never baked. Profit nearly doubles.
The check that catches it is a conservation law: over the horizon, batches sold plus final stock can never exceed batches made. Day 9 turns checks like this into automatic tests.
Mini-project: the freezer is replaced in December
The freezer is being replaced. During weeks 1–3, a rented freezer gives only 40 slots. What does it cost, and how big a freezer is worth having?
- Re-solve with 40 slots in weeks 1–3 (change those three constraints with
set_value). - Solve with freezers of 0 to 150 slots.
- Write two sentences for the plant manager.
Solution
import sys
import duckdb
sys.path.insert(0, "day08")
from planner import build, load_plan_data, solve, week_table
con = duckdb.connect("northbound.duckdb", read_only=True)
d = load_plan_data(con, weeks=6)
base = build(d)
solve(base)
# A temporary freezer with 40 slots in weeks 1-3: one constraint per week, so replace the
# single freezer size by a size per week
small = build(d)
for t in [1, 2, 3]:
small.freezer[t].set_value(
sum(d["products"].loc[p, "freezer_slots_per_batch"] * small.keep[p, t] for p in small.P) <= 40)
solve(small)
print(week_table(small, d).to_string(index=False))
print(f"full freezer ${base.profit():,.2f}; 40 slots in weeks 1-3 ${small.profit():,.2f}; "
f"cost of the small freezer ${base.profit() - small.profit():,.2f}")
# How big a freezer is worth having?
for slots in (0, 20, 40, 60, 80, 100, 120, 150):
m = build(d)
m.freezer_slots = slots
solve(m)
print(f" {slots:>3} slots: ${m.profit():,.2f}")
week capacity demand sold freezer_slots_used spare_oven_hours
1 1.0 602.6 429.24 0.0 0.0
2 1.0 605.6 366.51 40.0 0.0
3 1.0 865.9 445.42 40.0 0.0
4 0.6 865.8 338.62 0.0 0.0
5 0.8 552.3 349.41 0.0 0.0
6 1.0 537.1 421.48 0.0 0.0
full freezer $597,870.27; 40 slots in weeks 1-3 $597,086.15; cost of the small freezer $784.12
0 slots: $595,836.82
20 slots: $596,542.40
40 slots: $597,086.15
60 slots: $597,479.63
80 slots: $597,717.30
100 slots: $597,856.98
120 slots: $597,870.27
150 slots: $597,870.27
set_value replaces one week's freezer constraint; m.freezer_slots = slots changes the mutable size for every week.
Memo: "Renting a 40-slot freezer for the first three weeks of December costs about $784 in lost profit over the Christmas period, so a larger rental for those weeks is worth up to $784 more than the 40-slot one. Beyond about 110 slots extra freezer space is worth nothing this season: the bakery is short of oven time, not freezer space."
Each extra 20 slots is worth less than the last ($706, $544, $393, $238, $140, $13): diminishing returns, the usual shape of the value of a resource.
Commit
git add .
git commit -m "Day 8: multi-week plan with storage, horizons, freezer value"
git push
Day 8 checklist
- I can write a stock balance with make, sell and keep variables, and a rule for the first week.
- I separate revenue (at sale), ingredients (at baking) and holding (while waiting) in the objective.
- I can model shelf life and a shared freezer.
- I measured what planning ahead is worth ($2,033.45 over six weeks).
- I can explain end effects and why planners use rolling horizons.
- I can value a resource by sweeping its size.