Prescriptive Analytics & Decision Intelligence
Overview / Module 1 / Day 10
Module 1 · Decision Modelling and Linear Programming · Day 10 of 80

Capstone: The 12-Week Bakery Plan

The bakery manager needs a plan from 30 November to 21 February: 30 products, 12 weeks, Christmas in the middle. Today you build it alone, from the pieces of Days 1–9, and defend it in a one-page memo. The model solution follows each part; try each part before opening it.

▶
Video for Day 10 coming soon

In this lesson

Today's 5-hour plan

LessonProjectBreakCommit
0:00–0:30
10.1 The brief
0:30–1:45
10.2 Extend the planner: contract, shelf rule, overtime
1:45–2:00
Break
2:00–3:00
10.3 Tests, then the plan
3:00–3:45
10.4 Read the plan: overtime, lost sales, the sourdough question
3:45–4:00
Break
4:00–4:45
10.5 The memo
4:45–5:00
Commit, tag and checklist

10.1 The brief

To: Module 1 analysts From: Bakery manager, Northbound Fresh

I need next quarter's plan by Monday: what to bake each week for all 30 products, from 30 November to the week of 15 February. Rules:

  1. Café Laurier takes 50 batches of whole-wheat every week, on top of what the stores sell. The contract is signed: it must be met.
  2. Every product stays on the shelf: at least 2 batches sold every week.
  3. Christmas, New Year's and Family Day weeks have fewer oven, baker and packing hours (plan_weeks).
  4. We may book overtime: up to 80 baker hours a week at $45 an hour, and up to 40 packing hours a week (a third shift) at $60 an hour. Ovens cannot run longer.
  5. Use the freezer (120 slots) as you see fit.

Tell me: the profit, how much overtime to book and when, which products customers will miss most, and anything I should push back on.

All the data are in northbound.duckdb: plan_weeks, plan_demand, bakery_storage, plan_settings, plus the range tables from Day 6.

Deliverables and marking

DeliverableWeightWhat earns full marks
day10/capstone.py: the model30%Extends Day 8's planner without copying it; every rule from the brief; data from the database
tests/test_capstone.py20%A known answer, every rule of the brief as a property, and one comparison test
The plan, stored and drawn15%capstone_plan and capstone_weeks tables; one clear chart
Analysis15%Overtime value, lost sales by category and week, the sourdough question
day10/memo.md20%One page; every number from a solve; recommendations the manager can act on

10.2 Extend the planner

Day 8's build already has the balance, shelf life, freezer and weekly capacity. You need three additions, made to the model build returns, without editing planner.py:

  1. The contract: raise whole-wheat demand by 50 batches each week, and require at least 52 batches sold (50 for the café, 2 for the shelf rule).
  2. The shelf rule: at least 2 batches of every product sold each week.
  3. Overtime: a variable per week for baker and packing hours, bounded by the brief, added to those capacity constraints, and its cost taken off the objective.

Hints: change d["demand"] before calling build; replace capacity constraints with set_value (Day 7); deactivate m.profit and add a new objective.

Model solution: the model
import os
import sys

import duckdb
import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import pandas as pd
import pyomo.environ as pyo

sys.path.insert(0, "day08")
from planner import build, load_plan_data, plan_table, solve, v, week_table

pd.set_option("display.width", 140)
WEEKS = 12


def settings(con):
    return {k: float(x) for k, x in con.sql("SELECT setting, value FROM plan_settings").fetchall()}


def build_capstone(con, overtime=True):
    s = settings(con)
    d = load_plan_data(con, weeks=WEEKS)
    # The cafe's whole-wheat comes on top of store demand (Day 7, fix 1)
    for t in d["weeks"].week:
        d["demand"]["BK-WW", t] += s["cafe_ww_batches"]
    m = build(d)

    # Minimum sales each week: the shelf rule for every product, the contract for whole-wheat
    def minimum(p):
        return s["cafe_ww_batches"] + s["shelf_minimum_batches"] if p == "BK-WW" else s["shelf_minimum_batches"]

    m.min_sales = pyo.Constraint(m.P, m.T, rule=lambda m, p, t: m.sell[p, t] >= minimum(p))

    # Overtime: extra baker and packing hours at a price
    limit = {"baker_hours": s["overtime_baker_hours_max"] if overtime else 0,
             "packing_hours": s["overtime_packing_hours_max"] if overtime else 0}
    cost = {"baker_hours": s["overtime_baker_cost"], "packing_hours": s["overtime_packing_cost"]}
    m.OT = pyo.Set(initialize=list(limit))
    m.overtime = pyo.Var(m.OT, m.T, bounds=lambda m, r, t: (0, limit[r]))
    for r in m.OT:
        for t in m.T:
            m.capacity[r, t].set_value(sum(m.use[r, p] * m.make[p, t] for p in m.P) <= m.cap[r, t] + m.overtime[r, t])
    m.overtime_cost = pyo.Expression(expr=sum(cost[r] * m.overtime[r, t] for r in m.OT for t in m.T))
    m.profit.deactivate()
    m.net_profit = pyo.Objective(expr=m.revenue - m.ingredients - m.holding - m.overtime_cost, sense=pyo.maximize)
    return d, m

settings reads plan_settings once, so every number in the brief comes from the database, not the code. build_capstone(con, overtime=False) gives the same model with overtime limits of zero, for comparison.

10.3 Tests, then the plan

Write the tests before you read the plan. Each rule in the brief becomes a property test; the profit becomes a known answer once you trust it.

Model solution: the tests
"""Tests for the Day 10 capstone plan."""
import pyomo.environ as pyo
import pytest
from capstone import build_capstone, settings
from planner import solve

TOL = 1e-6


@pytest.fixture(scope="module")
def capstone(con):
    d, m = build_capstone(con)
    solve(m)
    return d, m, settings(con)


def test_known_answer(capstone):
    _, m, _ = capstone
    assert pyo.value(m.net_profit) == pytest.approx(1_255_362.50, abs=0.01)


def test_cafe_contract_and_shelf_rule_hold_every_week(capstone):
    _, m, s = capstone
    for t in m.T:
        assert pyo.value(m.sell["BK-WW", t]) >= s["cafe_ww_batches"] + s["shelf_minimum_batches"] - TOL
        for p in m.P:
            assert pyo.value(m.sell[p, t]) >= s["shelf_minimum_batches"] - TOL


def test_overtime_within_limits(capstone):
    _, m, s = capstone
    for t in m.T:
        assert pyo.value(m.overtime["baker_hours", t]) <= s["overtime_baker_hours_max"] + TOL
        assert pyo.value(m.overtime["packing_hours", t]) <= s["overtime_packing_hours_max"] + TOL


def test_overtime_option_never_hurts(con, capstone):
    _, m, _ = capstone
    _, no_ot = build_capstone(con, overtime=False)
    solve(no_ot)
    assert pyo.value(m.net_profit) >= pyo.value(no_ot.net_profit) - TOL


def test_christmas_week_uses_less_than_a_normal_week(capstone):
    _, m, _ = capstone
    oven = {t: pyo.value(m.capacity["oven_hours", t].body) for t in m.T}
    assert oven[4] == pytest.approx(0.6 * 600)
    assert oven[3] == pytest.approx(600)

conftest.py from Day 9 already puts day10 on the path. The Christmas test checks that week 4 uses exactly 60% of a normal week's oven hours: the ovens are full in both weeks, and the holiday cut is applied.

22 passed

Then the plan itself:

Model solution: running the plan
if __name__ == "__main__":
    con = duckdb.connect("northbound.duckdb")

    # ---------- 10.1 The plan ----------
    d, m = build_capstone(con)
    solve(m)
    weeks = week_table(m, d)
    weeks["overtime_baker_h"] = [v(m.overtime["baker_hours", t]) for t in m.T]
    weeks["overtime_packing_h"] = [v(m.overtime["packing_hours", t]) for t in m.T]
    print(weeks.to_string(index=False))
    print(f"12-week profit ${pyo.value(m.net_profit):,.2f} = revenue ${pyo.value(m.revenue):,.2f} "
          f"- ingredients ${pyo.value(m.ingredients):,.2f} - holding ${pyo.value(m.holding):,.2f} "
          f"- overtime ${pyo.value(m.overtime_cost):,.2f}")

    # ---------- 10.2 What overtime is worth ----------
    _, no_ot = build_capstone(con, overtime=False)
    solve(no_ot)
    print(f"without overtime ${pyo.value(no_ot.net_profit):,.2f}; overtime adds "
          f"${pyo.value(m.net_profit) - pyo.value(no_ot.net_profit):,.2f} for ${pyo.value(m.overtime_cost):,.2f} of overtime")
 week  capacity  demand   sold  freezer_slots_used  spare_oven_hours  overtime_baker_h  overtime_packing_h
    1       1.0   652.6 421.20               35.79               0.0               0.0               40.00
    2       1.0   655.6 401.80               92.53               0.0               0.0               40.00
    3       1.0   915.9 497.32               95.12               0.0               0.0               40.00
    4       0.6   915.8 426.80                0.00               0.0               0.0               13.36
    5       0.8   602.3 384.46                0.00               0.0               0.0               22.22
    6       1.0   587.1 436.20               14.23               0.0               0.0               32.80
    7       1.0   593.5 443.90               25.71               0.0               0.0               26.06
    8       1.0   667.3 488.30                8.45               0.0               0.0                6.99
    9       1.0   657.9 458.80               13.60               0.0               0.0               29.37
   10       1.0   663.6 454.70               23.14               0.0               0.0               39.11
   11       1.0   670.0 461.00               29.20               0.0               0.0               26.89
   12       0.8   663.2 431.60                0.00               0.0               0.0                0.00
12-week profit $1,255,362.50 = revenue $1,962,410.20 - ingredients $685,737.42 - holding $2,302.34 - overtime $19,007.94
without overtime $1,244,588.77; overtime adds $10,773.73 for $19,007.94 of overtime

10.4 Read the plan

Overtime. The plan books packing overtime in 11 of 12 weeks, at the full 40 hours in the three weeks before Christmas, and no baker overtime at all. Packing overtime costs $19,007.94 and earns $29,781.67 of extra margin: a net gain of $10,773.73. Baker overtime earns nothing because bakers are not the bottleneck (Day 6 found 20 spare baker hours a week). The brief offered both; the model says book only one.

The rest of capstone.py looks at what customers will miss:

    # ---------- 10.3 Lost sales by category, and the products to talk about ----------
    plan = plan_table(m, d)
    lost = plan.pivot_table(index="category", columns="week", values="lost", aggfunc="sum").round(0)
    print("Batches of demand not met, by category and week:")
    print(lost.to_string())
    by_product = plan.groupby("sku").agg(sold=("sell", "sum"), demand=("demand", "sum")).join(d["products"]["product_name"])
    by_product["fill_rate"] = (by_product.sold / by_product.demand).round(3)
    print("Lowest fill rates:")
    print(by_product.sort_values("fill_rate").head(6).to_string())

    # ---------- 10.4 Store the plan and draw it ----------
    con.sql("CREATE OR REPLACE TABLE capstone_plan AS SELECT * FROM plan")
    con.sql("CREATE OR REPLACE TABLE capstone_weeks AS SELECT * FROM weeks")
    print(con.sql("""
        SELECT category, round(sum(sell), 1) AS sold, round(sum(demand), 1) AS demand,
               round(sum(sell) / sum(demand), 3) AS fill_rate, round(max(keep), 1) AS max_stock_batches
        FROM capstone_plan GROUP BY category ORDER BY fill_rate"""))

    os.makedirs("figures", exist_ok=True)
    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 7), sharex=True)
    ax1.bar(weeks.week, weeks.demand, color="#d0d7e5", label="demand (batches)")
    ax1.bar(weeks.week, weeks.sold, color="#4f7bd9", label="sold (batches)")
    ax1.set_ylabel("batches")
    ax1.set_title("Northbound Fresh bakery: 12-week plan")
    ax1.legend()
    ax2.bar(weeks.week - 0.2, weeks.overtime_baker_h, width=0.4, color="#e08a2c", label="baker overtime (h)")
    ax2.bar(weeks.week + 0.2, weeks.overtime_packing_h, width=0.4, color="#8a5cd1", label="packing overtime (h)")
    ax2.plot(weeks.week, weeks.freezer_slots_used, "k-o", label="freezer slots used (of 120)")
    ax2.set_xlabel("week (week 4 = Christmas, capacity 60%)")
    ax2.legend()
    ax2.set_xticks(weeks.week)
    fig.tight_layout()
    fig.savefig("figures/day10_plan.png", dpi=120)
    print("saved figures/day10_plan.png")
    con.close()
Batches of demand not met, by category and week:
week             1      2      3      4      5     6     7     8     9     10    11     12
category                                                                                  
bread          57.0   63.0   77.0   77.0   58.0  37.0  38.0  53.0  48.0  51.0  53.0   58.0
cake          110.0  114.0  184.0  182.0  101.0  84.0  81.0  94.0  96.0  97.0  96.0  113.0
cookie          7.0    7.0   46.0   78.0    6.0   0.0   0.0   0.0   0.0   0.0   0.0    0.0
viennoiserie   57.0   69.0  111.0  151.0   53.0  30.0  31.0  32.0  55.0  61.0  61.0   61.0
Lowest fill rates:
       sold  demand        product_name  fill_rate
sku                                               
BK-18  24.0   381.6  Butter tart 6-pack      0.063
BK-24  24.0   367.4    Maple layer cake      0.065
BK-20  24.0   317.4     Lemon loaf cake      0.076
BK-19  24.0   309.2         Carrot cake      0.078
BK-SD  42.6   431.1      Sourdough loaf      0.099
BK-08  24.0   233.8    Seeded sourdough      0.103
┌──────────────┬────────┬────────┬───────────┬───────────────────┐
│   category   │  sold  │ demand │ fill_rate │ max_stock_batches │
│   varchar    │ double │ double │  double   │      double       │
├──────────────┼────────┼────────┼───────────┼───────────────────┤
│ cake         │  249.4 │ 1602.8 │     0.156 │               4.0 │
│ viennoiserie │ 1198.7 │ 1969.9 │     0.608 │              26.6 │
│ bread        │ 2533.9 │ 3203.3 │     0.791 │               0.0 │
│ cookie       │ 1324.1 │ 1468.8 │     0.901 │              79.4 │
└──────────────┴────────┴────────┴───────────┴───────────────────┘

The 12-week plan

  • Cookies are stocked ahead of Christmas (up to 79 batches of a single cookie product in store) and lose almost nothing after week 5: shelf-stable products are what the freezer is for.
  • Cakes get only the shelf minimum (2 batches a week each): 16% of cake demand is met. Every cake batch takes oven and baker time that earns more elsewhere.
  • Sourdough is the surprise: the chain's best-known loaf, $300 profit a batch, and the plan meets 10% of its demand. It needs 2 oven hours a batch, the most of any bread, and the ovens are the binding resource; olive sourdough shares its starter and needs only 1.2 oven hours.

That last finding is exactly what to push back on, so price it. day10/sourdough_question.py adds a minimum share of sourdough demand:

import sys

import duckdb
import pyomo.environ as pyo

sys.path.insert(0, "day08")
sys.path.insert(0, "day10")
from capstone import build_capstone
from planner import solve

con = duckdb.connect("northbound.duckdb", read_only=True)
d, base = build_capstone(con)
solve(base)

for share in (0.5, 0.8, 1.0):
    _, m = build_capstone(con)
    m.sourdough = pyo.Constraint(m.T, rule=lambda m, t: m.sell["BK-SD", t] >= share * m.demand["BK-SD", t])
    solve(m)
    cost = pyo.value(base.net_profit) - pyo.value(m.net_profit)
    sold = sum(pyo.value(m.sell["BK-SD", t]) for t in m.T)
    print(f"sourdough at {share:.0%} of demand: {sold:,.1f} batches over 12 weeks, "
          f"profit ${pyo.value(m.net_profit):,.2f}, costs ${cost:,.2f} (${cost / 12:,.2f} a week)")
sourdough at 50% of demand: 215.6 batches over 12 weeks, profit $1,251,051.12, costs $4,311.38 ($359.28 a week)
sourdough at 80% of demand: 344.9 batches over 12 weeks, profit $1,247,025.83, costs $8,336.67 ($694.72 a week)
sourdough at 100% of demand: 431.1 batches over 12 weeks, profit $1,242,195.09, costs $13,167.41 ($1,097.28 a week)

Keeping sourdough at 80% of demand costs $695 a week, 0.7% of profit. The model cannot know that shoppers who don't find their sourdough may shop elsewhere; the manager can. That trade-off belongs in the memo.

10.5 The memo

Write day10/memo.md: one page for the bakery manager. Use only numbers from your solves.

Model answer

To: Bakery manager Re: Bakery plan, 30 November to 21 February

Recommendation. Bake to the attached plan: $1.26 million of contribution over 12 weeks (revenue $1.96 million, ingredients $686,000, freezer $2,300, overtime $19,000). It meets the Café Laurier contract and keeps every product on the shelf every week.

Overtime. Book a third packing shift in 11 of 12 weeks, the full 40 hours in the three weeks before Christmas. It costs $19,000 and adds $29,800 of margin: +$10,800 net. Do not book baker overtime: bakers are not the bottleneck, and extra baker hours earn nothing.

Christmas. Build up stock in the first three weeks of December (up to 95 freezer slots, mostly cookies and viennoiserie) and sell it in Christmas week, when the ovens run at 60%.

What customers will miss. Demand exceeds what the ovens can bake in every week. The plan sells 16% of cake demand, 61% of viennoiserie, 79% of bread and 90% of cookies.

Push back on: sourdough. The plan meets only 10% of sourdough demand, because sourdough uses the most oven time of any bread. Keeping it at 80% of demand costs $695 a week (0.7% of profit). I recommend paying it: losing the chain's best-known loaf from the shelves risks customers the model cannot see.

Next steps. Oven hours limit everything; a business case for more ovens (Module 3) is the biggest lever. Re-plan every Monday with fresh demand (rolling horizon).

Commit and tag

The end of Module 1. Commit, and tag the repository so you can always return to this state:

git add .
git commit -m "Day 10: capstone 12-week plan, tests and memo"
git tag v1.0-module1
git push --tags

Day 10 checklist

  • My capstone extends the Day 8 planner without copying it.
  • Every rule in the brief is a constraint and a test.
  • The plan is stored in northbound.duckdb and drawn in one chart.
  • I measured what overtime is worth, and found which kind not to book.
  • I priced the sourdough question rather than guessing.
  • My memo uses only numbers from solves, and tells the manager what to do.