20.1 The brief
To: Module 2 analysts From: Director of Operations
I have budget for some temporary capacity for the four weeks from 30 November. The options on the table:
Option Adds Cost A: Montreal second receiving shift 200 pallets a week in, weeks 1–4 $6,000 B: Mississauga reefer trailers 60 chilled pallets a week, weeks 3–4 $5,000 C: Ottawa reefer trailers 40 chilled pallets a week, weeks 3–4 $2,400 D: Ottawa extra outbound shift 100 pallets a week out, weeks 1–4 $12,000 I need the December plan, what it will really cost, and which options to buy. Keep it to one page.
Deliverables and marking
| Deliverable | Weight | What earns full marks |
|---|---|---|
day20/december_plan.py | 25% | Reuses Days 18–19; options as data, applied by one function |
| Stored plan and chart | 15% | december_shipments and december_dc_plan tables; one clear chart |
tests/test_distribution.py | 20% | A known answer, conservation, every limit, and the perfect-forecast check |
| Option analysis | 20% | Each option valued by duals, by re-solving and in the actual December, with an explanation of the differences |
day20/memo.md | 20% | One page; a decision for each option; every number from a run |
Name the script december_plan.py, not capstone.py: Day 10 already has a capstone.py, and with both folders on the test path, Python would import whichever it finds first. (It happened while writing this lesson: 36 tests became "1 error".)
20.2 The plan, stored
Model solution: options as data
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, "day18")
sys.path.insert(0, "day19")
from evaluate import plan_and_live
from flows import build_weeks, load_weeks, report, v
pd.set_option("display.width", 160)
WEEKS = [1, 2, 3, 4]
OPTIONS = {
# name: (limit, DC, weeks, extra pallets a week, total cost over the weeks)
"A: Montreal second receiving shift": ("receiving_pallets", "DC-MTL", WEEKS, 200, 6000),
"B: Mississauga reefer trailers": ("chilled_zone_pallets", "DC-MIS", [3, 4], 60, 5000),
"C: Ottawa reefer trailers": ("chilled_zone_pallets", "DC-OTT", [3, 4], 40, 2400),
"D: Ottawa extra outbound shift": ("outbound_pallets", "DC-OTT", WEEKS, 100, 12000),
}
CONSTRAINT = {"receiving_pallets": "receiving", "chilled_zone_pallets": "chilled_zone", "outbound_pallets": "outbound"}
def with_options(*names):
"""A function that adds the chosen options' capacity to the data."""
def adjust(d):
w = d["dc_weeks"].copy()
for n in names:
limit, dc, weeks, extra, _ = OPTIONS[n]
for t in weeks:
if (dc, t) in w.index:
w.loc[(dc, t), limit] += extra
return dict(d, dc_weeks=w)
return adjust
def plan(con, adjust=None):
m = build_weeks((adjust or (lambda d: d))(load_weeks(con)))
m.dual = pyo.Suffix(direction=pyo.Suffix.IMPORT)
pyo.SolverFactory("highs").solve(m)
return m
Each option is a row of data: which limit, which DC, which weeks, how much, at what cost. with_options returns a function that adds the chosen options to a copy of the data: the same adjust hook plan_and_live now accepts (Day 19's evaluate.py, final version).
if __name__ == "__main__":
con = duckdb.connect("northbound.duckdb")
# ---------- 20.2 The plan ----------
m = plan(con)
weekly = report(m)
print(weekly.to_string(index=False))
print(f"planned 4-week cost ${pyo.value(m.cost):,.2f}")
dc_rows = []
w = load_weeks(con)["dc_weeks"]
for dc in m.D:
for t in m.T:
dc_rows.append((dc, t, v(sum(m.receive[k, dc, t] for k in m.K)), w.receiving_pallets[dc, t],
v(sum(m.ship[k, dc, s, t] for k in m.K for s in m.S)), w.outbound_pallets[dc, t],
v(sum(m.ship["chilled", dc, s, t] for s in m.S)), w.chilled_zone_pallets[dc, t], v(m.stock[dc, t])))
dc_plan = pd.DataFrame(dc_rows, columns=["dc_id", "week", "received", "receiving_cap", "shipped", "outbound_cap",
"chilled", "chilled_cap", "stock_end"])
print(dc_plan.to_string(index=False))
ships = pd.DataFrame([(k, dc, s, t, v(m.ship[k, dc, s, t])) for k in m.K for dc in m.D for s in m.S for t in m.T
if pyo.value(m.ship[k, dc, s, t]) > 1e-6], columns=["kind", "dc_id", "store_id", "week", "pallets"])
con.sql("CREATE OR REPLACE TABLE december_shipments AS SELECT * FROM ships")
con.sql("CREATE OR REPLACE TABLE december_dc_plan AS SELECT * FROM dc_plan")
print(con.sql("""
SELECT week, count(DISTINCT store_id) AS stores, count(*) AS lanes_used,
count(*) FILTER (WHERE kind = 'chilled') AS chilled_lanes, sum(pallets)::INTEGER AS pallets
FROM december_shipments GROUP BY week ORDER BY week"""))
week shipped received dc_stock_end short_ambient short_chilled
1 3504.0 3398.0 424.0 0.0 0.0
2 3800.0 3910.0 534.0 0.0 19.0
3 4177.0 3910.0 267.0 0.0 58.0
4 4177.0 3910.0 0.0 0.0 68.0
planned 4-week cost $256,444.53
dc_id week received receiving_cap shipped outbound_cap chilled chilled_cap stock_end
DC-MIS 1 1248.0 1650 1411.0 1600 342.0 400 87.0
DC-MIS 2 1650.0 1650 1600.0 1600 374.0 400 137.0
DC-MIS 3 1650.0 1650 1696.0 1840 400.0 400 91.0
DC-MIS 4 1650.0 1650 1741.0 1840 400.0 400 0.0
DC-MTL 1 1500.0 1500 1393.0 1500 358.0 420 307.0
DC-MTL 2 1500.0 1500 1500.0 1500 378.0 420 307.0
DC-MTL 3 1500.0 1500 1676.0 1725 420.0 420 131.0
DC-MTL 4 1500.0 1500 1631.0 1725 420.0 420 0.0
DC-OTT 1 650.0 760 700.0 700 211.0 220 30.0
DC-OTT 2 760.0 760 700.0 700 220.0 220 90.0
DC-OTT 3 760.0 760 805.0 805 220.0 220 45.0
DC-OTT 4 760.0 760 805.0 805 220.0 220 0.0
┌───────┬────────┬────────────┬───────────────┬─────────┐
│ week │ stores │ lanes_used │ chilled_lanes │ pallets │
│ int64 │ int64 │ int64 │ int64 │ int32 │
├───────┼────────┼────────────┼───────────────┼─────────┤
│ 1 │ 40 │ 81 │ 40 │ 3504 │
│ 2 │ 40 │ 83 │ 41 │ 3800 │
│ 3 │ 40 │ 81 │ 40 │ 4177 │
│ 4 │ 40 │ 81 │ 39 │ 4177 │
└───────┴────────┴────────────┴───────────────┴─────────┘
The plan ships every store every week, through 81–83 lanes a week (most stores get ambient and chilled from the same DC). Every receiving dock is full except Mississauga's and Ottawa's in week 1; Ottawa's outbound docks are full every week; Mississauga's and Montreal's chilled zones are full at the peak.
20.3 Live through December
# ---------- 20.3 Live through the actual weeks ----------
planned, actual, rushed, wasted, lost = plan_and_live(con, "store_week_forecast")
print(f"lived through December: ${actual:,.2f} (planned ${planned:,.2f}); rushed {rushed:.0f}, lost {lost:.0f}")
lived through December: $269,362.74 (planned $256,444.53); rushed 0, lost 250
December really costs $269,362.74, $12,918 more than planned: actual demand was 105 pallets higher than forecast, and 250 pallets go short instead of 145.
20.4 Which capacity should we buy?
Each option is valued three ways:
- Predicted by duals: shadow price × extra capacity, summed over the weeks (Day 11). Instant.
- Re-solved: the plan's cost with and without the option (Day 13).
- In the actual December: plan with the option, then live through the actual weeks (Day 19). The number the director cares about.
# ---------- 20.4 Which capacity should we buy? ----------
rows = []
base_live = actual
for name, (limit, dc, weeks, extra, cost) in OPTIONS.items():
con_ = getattr(m, CONSTRAINT[limit])
predicted = sum(abs(m.dual[con_[dc, t]]) * extra for t in weeks)
resolved = pyo.value(m.cost) - pyo.value(plan(con, with_options(name)).cost)
lived = base_live - plan_and_live(con, "store_week_forecast", with_options(name))[1]
rows.append((name, cost, round(predicted, 2), round(resolved, 2), round(lived, 2), round(lived - cost, 2)))
options = pd.DataFrame(rows, columns=["option", "cost", "saving_predicted_by_duals", "saving_re_solved",
"saving_in_actual_december", "net"])
print(options.to_string(index=False))
good = [r.option for r in options.itertuples() if r.net > 0]
both = base_live - plan_and_live(con, "store_week_forecast", with_options(*good))[1]
cost_good = sum(OPTIONS[g][4] for g in good)
print(f"buy {good}: saves ${both:,.2f} for ${cost_good:,}, net ${both - cost_good:,.2f}")
option cost saving_predicted_by_duals saving_re_solved saving_in_actual_december net
A: Montreal second receiving shift 6000 55184.00 9492.14 13993.77 7993.77
B: Mississauga reefer trailers 5000 8101.20 4687.12 3576.60 -1423.40
C: Ottawa reefer trailers 2400 3925.98 3757.46 3424.51 1024.51
D: Ottawa extra outbound shift 12000 20270.60 5489.53 5489.99 -6510.01
buy ['A: Montreal second receiving shift', 'C: Ottawa reefer trailers']: saves $17,388.63 for $8,400, net $8,988.63
- The duals overstate every option, Montreal's receiving shift by a factor of six ($55,184 predicted, $9,492 re-solved). 200 extra pallets a week is far outside the range over which Montreal's $65–73 shadow price holds (Day 12): after the first few dozen pallets, other limits bind. Use duals to rank; never to price a big change.
- A forecast-based plan can understate an option: Montreal's shift saves $9,492 on the forecast but $13,994 in the actual December, because actual demand was higher than forecast. Capacity is worth most when demand surprises upward.
- Buy A and C. Montreal's receiving shift nets $7,994; Ottawa's reefer trailers $1,025. Together they save $17,388.63 for $8,400: net $8,988.63.
- Don't buy B or D. Mississauga's trailers save $3,577 for $5,000. Ottawa's outbound shift saves $5,490 for $12,000: Ottawa's docks are full, but each extra pallet out of Ottawa is worth little once nearby stores are covered from Montreal.
20.5 The chart and the memo
# ---------- 20.5 The chart ----------
os.makedirs("figures", exist_ok=True)
fig, axes = plt.subplots(1, 3, figsize=(13, 4), sharey=False)
for ax, (dc, g) in zip(axes, dc_plan.groupby("dc_id")):
ax.bar(g.week - 0.2, g.received, width=0.4, color="#4f7bd9", label="received")
ax.bar(g.week + 0.2, g.shipped, width=0.4, color="#e08a2c", label="shipped")
ax.plot(g.week, g.receiving_cap, "b--", lw=1, label="receiving capacity")
ax.plot(g.week, g.outbound_cap, "--", color="#e08a2c", lw=1, label="outbound capacity")
ax.plot(g.week, g.stock_end, "k-o", label="ambient stock (end of week)")
ax.set_title(dc)
ax.set_xticks(WEEKS)
ax.set_xlabel("December week")
axes[0].set_ylabel("pallets")
axes[0].legend(fontsize=7)
fig.suptitle("December distribution plan: pallets received, shipped and stocked at each DC")
fig.tight_layout()
fig.savefig("figures/day20_december_plan.png", dpi=120)
print("saved figures/day20_december_plan.png")
con.close()

Model solution: the tests
"""Module 2, Days 18-20: the multi-commodity, multi-week distribution plan."""
import pyomo.environ as pyo
import pytest
from evaluate import plan_and_live
from flows import build_weeks, load_weeks
TOL = 1e-6
@pytest.fixture(scope="module")
def december(con):
d = load_weeks(con)
m = build_weeks(d)
pyo.SolverFactory("highs").solve(m)
return d, m
def test_known_answer(december):
_, m = december
assert pyo.value(m.cost) == pytest.approx(256_444.53, abs=0.01)
def test_ambient_pallets_are_conserved(december):
d, m = december
w = d["dc_weeks"]
for dc in m.D:
opening = w.opening_ambient_stock[dc, 1]
received = sum(pyo.value(m.receive["ambient", dc, t]) for t in m.T)
shipped = sum(pyo.value(m.ship["ambient", dc, s, t]) for s in m.S for t in m.T)
assert opening + received == pytest.approx(shipped + pyo.value(m.stock[dc, m.T.last()]), abs=TOL)
def test_limits_hold_and_stores_get_at_most_their_demand(december):
d, m = december
w = d["dc_weeks"]
for dc in m.D:
for t in m.T:
assert sum(pyo.value(m.ship["chilled", dc, s, t]) for s in m.S) <= w.chilled_zone_pallets[dc, t] + TOL
assert sum(pyo.value(m.receive[k, dc, t]) for k in m.K) <= w.receiving_pallets[dc, t] + TOL
for (k, s, t), dem in d["demand"].items():
assert sum(pyo.value(m.ship[k, dc, s, t]) for dc in m.D) <= dem + TOL
def test_perfect_forecast_costs_nothing_extra(con):
planned, actual, rushed, wasted, lost = plan_and_live(con, "store_week_actual")
assert actual == pytest.approx(planned, abs=0.01)
assert rushed == pytest.approx(0, abs=TOL)
def test_forecast_error_never_helps(con):
_, perfect, *_ = plan_and_live(con, "store_week_actual")
_, official, *_ = plan_and_live(con, "store_week_forecast")
assert official >= perfect - TOL
Add "day18", "day19" and "day20" to the folders in conftest.py.
36 passed
Write day20/memo.md.
Model answer
To: Director of Operations Re: December capacity
Buy two options, for $8,400: Montreal's second receiving shift ($6,000) and Ottawa's reefer trailers ($2,400). Against December's actual demand they save $17,389, a net gain of $8,989. Don't buy Mississauga's trailers (they save $3,577 for $5,000) or Ottawa's outbound shift (saves $5,490 for $12,000).
Why Montreal's receiving. It is our tightest limit in December: every pallet the DCs can receive in weeks 1–2 can be held for the Christmas peak. With the extra shift, Montreal receives more early and ships it at the peak.
The plan. Receive at full capacity from week 2, build 534 pallets of ambient stock by mid-December, ship 4,177 pallets a week in weeks 3–4. It meets every store's ambient demand. Chilled pallets can't be received early, so about 1 in 20 chilled pallets in the peak weeks can't be delivered.
What December will cost. About $269,000 with our current forecast: $13,000 more than the plan says, because demand will run slightly above forecast. Our forecast (last year's week plus 3%) is within $1,200 of perfect hindsight; inflating it would make things worse, because receiving capacity is full.
Caveat. Shadow prices overstate the value of large additions by up to six times; every saving above comes from re-planning with the option, and from living through the actual weeks.
Commit and tag
The end of Module 2:
git add .
git commit -m "Day 20: December distribution plan, capacity options, tests and memo"
git tag v2.0-module2
git push --tags
Day 20 checklist
- My plan covers both commodities and four weeks, and is stored in two tables.
- I lived through the actual December and explained why it costs more than planned.
- I valued each option by duals, by re-solving and in the actual December.
- I can explain why duals overstate large changes and forecasts can understate them.
- My tests check a known answer, conservation, every limit and the perfect forecast.
- My memo gives the director a decision on each option, with its net value.