18.1 The December data
Copy the latest make_data.py from the Course data page and rebuild (python make_data.py, python day01/ladder.py, python day06/load_tables.py). Five new tables:
| Table | What it holds |
|---|---|
dc_weeks | Per DC and week: receiving capacity (pallets in from suppliers), outbound capacity (pallets out to stores; +15% in weeks 3 and 4 with extra shifts), chilled zone capacity, ambient storage, and the ambient stock on hand at the start |
store_week_forecast | The planning team's forecast: ambient and chilled pallets per store for weeks 1–4 (30 November to 21 December) |
store_pallets_history | 53 weeks of actual pallets per store, to the week of 23 November 2026 (Day 19) |
store_week_actual | What each store actually needed in weeks 1–4 (Day 19: only known afterwards) |
distribution_costs | Receiving $3 a pallet, holding $2.50 a pallet-week, chilled lanes 15% dearer, a lost pallet $120 of margin, a same-week rush order $25 extra |
Create day18/run_weeks.py and start by comparing December's forecast with what the DCs can handle:
import sys
import duckdb
import pandas as pd
import pyomo.environ as pyo
sys.path.insert(0, "day18")
from flows import build_weeks, load_weeks, report, v
pd.set_option("display.width", 140)
con = duckdb.connect("northbound.duckdb", read_only=True)
solver = pyo.SolverFactory("highs")
# ---------- 18.1 December's demand against the DCs' capacity ----------
print(con.sql("""
WITH dem AS (
SELECT week, sum(ambient_pallets)::INTEGER AS ambient, sum(chilled_pallets)::INTEGER AS chilled
FROM store_week_forecast GROUP BY week
), cap AS (
SELECT week, sum(receiving_pallets)::INTEGER AS can_receive, sum(outbound_pallets)::INTEGER AS can_ship,
sum(chilled_zone_pallets)::INTEGER AS chilled_zones
FROM dc_weeks GROUP BY week
)
SELECT week, ambient, chilled, ambient + chilled AS total, can_receive, can_ship, chilled_zones
FROM dem JOIN cap USING (week) ORDER BY week"""))
┌───────┬─────────┬─────────┬───────┬─────────────┬──────────┬───────────────┐
│ week │ ambient │ chilled │ total │ can_receive │ can_ship │ chilled_zones │
│ int64 │ int32 │ int32 │ int32 │ int32 │ int32 │ int32 │
├───────┼─────────┼─────────┼───────┼─────────────┼──────────┼───────────────┤
│ 1 │ 2593 │ 911 │ 3504 │ 3910 │ 3800 │ 1040 │
│ 2 │ 2828 │ 991 │ 3819 │ 3910 │ 3800 │ 1040 │
│ 3 │ 3137 │ 1098 │ 4235 │ 3910 │ 4370 │ 1040 │
│ 4 │ 3137 │ 1108 │ 4245 │ 3910 │ 4370 │ 1040 │
└───────┴─────────┴─────────┴───────┴─────────────┴──────────┴───────────────┘
Weeks 3 and 4 need about 4,240 pallets, while the three DCs can receive only 3,910 a week between them. Some of the peak must come in earlier. Chilled demand at the peak (about 1,100 pallets) is also above the chilled zones' 1,040.
18.2 Two commodities: plan them together or apart?
A multi-commodity flow has a flow variable per commodity, per arc, per week, linked by limits the commodities share. Ours:
- Separate: each store's ambient and chilled demand; the chilled zone (chilled pallets only); a balance per commodity at each DC (ambient may be held, chilled may not).
- Shared: receiving (all pallets in) and outbound docks (all pallets out).
Create day18/flows.py, with the model in one function:
"""Day 18: two commodities over four weeks. Ambient and chilled pallets share each DC's docks;
ambient pallets can wait at a DC, chilled pallets cannot.
Import it: from flows import load_weeks, build_weeks, report
"""
import pandas as pd
import pyomo.environ as pyo
KINDS = ["ambient", "chilled"]
def load_weeks(con, demand_table="store_week_forecast", weeks=4):
costs = dict(con.sql("SELECT item, value FROM distribution_costs").fetchall())
dcw = con.sql(f"SELECT * FROM dc_weeks WHERE week <= {weeks}").df().set_index(["dc_id", "week"])
dem = con.sql(f"SELECT * FROM {demand_table} WHERE week <= {weeks}").df()
demand = {}
for r in dem.itertuples():
demand["ambient", r.store_id, r.week] = r.ambient_pallets
demand["chilled", r.store_id, r.week] = r.chilled_pallets
lanes = con.sql("SELECT dc_id, store_id, cost_per_pallet FROM dc_store_lanes").fetchall()
lane = {}
for d, s, c in lanes:
lane["ambient", d, s] = c
lane["chilled", d, s] = round(c * costs["chilled_lane_factor"], 4)
return {
"dcs": sorted(dcw.index.get_level_values(0).unique()),
"stores": sorted(dem.store_id.unique()),
"weeks": list(range(1, weeks + 1)),
"dc_weeks": dcw,
"demand": demand,
"lane": lane,
"costs": costs,
}
def build_weeks(d, link_weeks=True):
"""ship[k, d, s, t]: pallets of kind k from DC d to store s in week t.
receive[d, t]: pallets received at DC d (ambient + chilled); stock[d, t]: ambient pallets held at the end of week t.
short[k, s, t]: pallets a store needed but did not get (lost sales)."""
c, w = d["costs"], d["dc_weeks"]
m = pyo.ConcreteModel(name="distribution_weeks")
m.K = pyo.Set(initialize=KINDS)
m.D = pyo.Set(initialize=d["dcs"])
m.S = pyo.Set(initialize=d["stores"])
m.T = pyo.Set(initialize=d["weeks"], ordered=True)
m.ship = pyo.Var(m.K, m.D, m.S, m.T, within=pyo.NonNegativeReals)
m.receive = pyo.Var(m.K, m.D, m.T, within=pyo.NonNegativeReals)
m.stock = pyo.Var(m.D, m.T, within=pyo.NonNegativeReals)
m.short = pyo.Var(m.K, m.S, m.T, within=pyo.NonNegativeReals)
def out(m, k, dc, t):
return sum(m.ship[k, dc, s, t] for s in m.S)
# Stores: shipments plus shortfall cover demand, kind by kind
m.demand = pyo.Constraint(m.K, m.S, m.T, rule=lambda m, k, s, t:
sum(m.ship[k, dc, s, t] for dc in m.D) + m.short[k, s, t] == d["demand"][k, s, t])
# DCs: ambient stock carries over; chilled goes out the week it comes in
def ambient_balance(m, dc, t):
before = (m.stock[dc, m.T.prev(t)] if t != m.T.first() else w.opening_ambient_stock[dc, 1]) if link_weeks else 0
return before + m.receive["ambient", dc, t] == out(m, "ambient", dc, t) + m.stock[dc, t]
m.ambient_balance = pyo.Constraint(m.D, m.T, rule=ambient_balance)
m.chilled_balance = pyo.Constraint(m.D, m.T, rule=lambda m, dc, t: m.receive["chilled", dc, t] == out(m, "chilled", dc, t))
# Shared and separate limits
m.receiving = pyo.Constraint(m.D, m.T, rule=lambda m, dc, t: sum(m.receive[k, dc, t] for k in m.K) <= w.receiving_pallets[dc, t])
m.outbound = pyo.Constraint(m.D, m.T, rule=lambda m, dc, t: sum(out(m, k, dc, t) for k in m.K) <= w.outbound_pallets[dc, t])
m.chilled_zone = pyo.Constraint(m.D, m.T, rule=lambda m, dc, t: out(m, "chilled", dc, t) <= w.chilled_zone_pallets[dc, t])
m.storage = pyo.Constraint(m.D, m.T, rule=lambda m, dc, t: m.stock[dc, t] <= (w.ambient_storage_pallets[dc, t] if link_weeks else 0))
m.transport = pyo.Expression(expr=sum(d["lane"][k, dc, s] * 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))
m.inbound = pyo.Expression(expr=c["inbound_per_pallet"] * sum(m.receive[k, dc, t] for k in m.K for dc in m.D for t in m.T))
m.holding = pyo.Expression(expr=c["holding_per_pallet_week"] * sum(m.stock[dc, t] for dc in m.D for t in m.T))
m.lost = pyo.Expression(expr=c["lost_sale_per_pallet"] * sum(m.short[k, s, t] for k in m.K for s in m.S for t in m.T))
m.cost = pyo.Objective(expr=m.transport + m.inbound + m.holding + m.lost)
return m
def v(x):
return round(pyo.value(x), 2) + 0.0
def report(m):
rows = []
for t in m.T:
rows.append((t,
v(sum(m.ship[k, dc, s, t] for k in m.K for dc in m.D for s in m.S)),
v(sum(m.receive[k, dc, t] for k in m.K for dc in m.D)),
v(sum(m.stock[dc, t] for dc in m.D)),
v(sum(m.short["ambient", s, t] for s in m.S)),
v(sum(m.short["chilled", s, t] for s in m.S))))
return pd.DataFrame(rows, columns=["week", "shipped", "received", "dc_stock_end", "short_ambient", "short_chilled"])
Points to slow down for:
- Lost sales as a variable.
shortlets a store get less than it needs, at $120 a pallet. Without it, a week where demand exceeds capacity makes the model infeasible; with it, the model tells you how much demand can't be met, and where. - Ambient carries over, chilled doesn't.
ambient_balancelinks the weeks throughstock, as on Day 8.chilled_balancehas no stock: what comes in goes out the same week. link_weeks=Falsegives the week-by-week version: no stock carried over, not even the opening stock.
First, one week, to see why commodities must be planned together:
# ---------- 18.2 One week, two commodities: plan them together or apart? ----------
d1 = load_weeks(con, weeks=1)
together = build_weeks(d1)
solver.solve(together)
apart = build_weeks(d1)
apart.outbound.deactivate() # each commodity planned as if it had the docks to itself
solver.solve(apart)
for name, m in (("together", together), ("apart", apart)):
use = {dc: v(sum(m.ship[k, dc, s, 1] for k in m.K for s in m.S)) for dc in m.D}
print(f"{name:<9} cost ${pyo.value(m.cost):,.2f}; pallets out of each DC {use}")
print("outbound capacity:", {dc: int(d1["dc_weeks"].outbound_pallets[dc, 1]) for dc in d1["dcs"]})
together cost $48,029.08; pallets out of each DC {'DC-MIS': 1304.0, 'DC-MTL': 1500.0, 'DC-OTT': 700.0}
apart cost $45,401.57; pallets out of each DC {'DC-MIS': 1190.0, 'DC-MTL': 1474.0, 'DC-OTT': 840.0}
outbound capacity: {'DC-MIS': 1600, 'DC-MTL': 1500, 'DC-OTT': 700}
Planning each commodity apart (here: without the shared outbound limit) is $2,627 cheaper, and impossible: it sends 840 pallets out of Ottawa, which has docks for 700. Each commodity's plan is fine on its own; together they overload the shared docks. Ambient and chilled must be planned in one model, or the docks must be split between them in advance (which wastes capacity whenever one commodity needs less than its share).
Decision it supports: how to share docks, trucks and zones between product types that compete for them.
Other decisions you can support the same way: passengers and cargo on the same flights · several products on one pipeline · data streams on one network link.
18.3 Four weeks: receive early, hold, ship
# ---------- 18.3 Four weeks ----------
d = load_weeks(con)
m = build_weeks(d)
m.dual = pyo.Suffix(direction=pyo.Suffix.IMPORT)
solver.solve(m)
print(report(m).to_string(index=False))
print(f"4-week cost ${pyo.value(m.cost):,.2f} = transport ${pyo.value(m.transport):,.2f} + inbound ${pyo.value(m.inbound):,.2f} "
f"+ holding ${pyo.value(m.holding):,.2f} + lost sales ${pyo.value(m.lost):,.2f}")
stock = pd.DataFrame({dc: [v(m.stock[dc, t]) for t in m.T] for dc in m.D}, index=list(m.T))
stock.index.name = "week"
print("ambient stock at each DC at the end of each week:")
print(stock.to_string())
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
4-week cost $256,444.53 = transport $190,598.03 + inbound $45,384.00 + holding $3,062.50 + lost sales $17,400.00
ambient stock at each DC at the end of each week:
DC-MIS DC-MTL DC-OTT
week
1 87.0 307.0 30.0
2 137.0 307.0 90.0
3 91.0 131.0 45.0
4 0.0 0.0 0.0
What the plan does:
- Weeks 1 and 2 receive more than they ship (or, in week 1, ship from the opening stock): ambient stock at the DCs rises to 534 pallets by the end of week 2, ready for the peak.
- Weeks 3 and 4 ship 4,177 pallets with only 3,910 received: the difference comes out of stock, which is used up by the end of week 4.
- Ambient demand is always met. Chilled demand is not: 145 chilled pallets are lost over the four weeks, all in weeks 2–4. Chilled pallets can't be received early, and the chilled zones are too small for the peak.
- The cost splits into transport ($190,598), receiving ($45,384), holding ($3,063) and lost sales ($17,400).
18.4 Which limits bind, and when
# ---------- 18.4 Which limits bind, and when? ----------
def prices(con_):
return pd.DataFrame({dc: [round(abs(m.dual[con_[dc, t]]), 2) + 0.0 for t in m.T] for dc in m.D}, index=list(m.T))
for name, con_ in (("receiving", m.receiving), ("outbound", m.outbound), ("chilled zone", m.chilled_zone), ("storage", m.storage)):
p = prices(con_)
p.index.name = "week"
print(f"shadow price of {name} ($ a pallet):")
print(p.to_string())
week_by_week = build_weeks(d, link_weeks=False)
solver.solve(week_by_week)
print(f"without carrying ambient stock between weeks: ${pyo.value(week_by_week.cost):,.2f} "
f"(+${pyo.value(week_by_week.cost) - pyo.value(m.cost):,.2f})")
flows = [pyo.value(x) for x in m.ship.values()]
print("every shipment a whole number of pallets:", all(abs(f - round(f)) < 1e-6 for f in flows))
shadow price of receiving ($ a pallet):
DC-MIS DC-MTL DC-OTT
week
1 0.0 65.23 0.0
2 2.5 67.73 2.5
3 5.0 70.23 5.0
4 7.5 72.73 7.5
shadow price of outbound ($ a pallet):
DC-MIS DC-MTL DC-OTT
week
1 0.00 0.00 48.18
2 9.99 9.99 58.17
3 0.00 0.00 48.18
4 0.00 0.00 48.18
shadow price of chilled zone ($ a pallet):
DC-MIS DC-MTL DC-OTT
week
1 0.00 0.00 0.00
2 0.00 0.00 7.23
3 68.76 7.95 50.30
4 66.26 5.50 47.85
shadow price of storage ($ a pallet):
DC-MIS DC-MTL DC-OTT
week
1 0.0 0.0 0.0
2 0.0 0.0 0.0
3 0.0 0.0 0.0
4 0.0 0.0 0.0
without carrying ambient stock between weeks: $294,124.38 (+$37,679.85)
every shipment a whole number of pallets: True
Read the four tables of shadow prices together:
- Montreal's receiving is the most valuable limit: $65 to $73 a pallet in every week. A pallet received there in week 1 can be held and shipped in week 3, so every week's receiving is worth about the same, rising by the $2.50 holding cost per week (a pallet received later saves holding).
- Ottawa's outbound docks are full every week ($48–58 a pallet). Ottawa is short of docks, not of goods.
- Chilled zones bind at the peak (weeks 3–4), most in Mississauga ($66–69) and Ottawa ($48–50): those are the chilled pallets lost.
- Storage never binds: the DCs have room for more stock than the plan wants to hold. Bigger warehouses wouldn't help this December.
- Carrying stock between weeks is worth $37,679.85 over the four weeks (against planning each week alone).
Unlike Day 14, there is no guarantee of whole-number answers in a multi-commodity flow: the shared limits break the special structure. This plan happens to come out whole; bigger ones often don't, and then rounding (or integer variables) is needed.
The planted bug
day18/bug_opening.py "simplifies" the ambient balance. Run it, then compare pallets in with pallets out.
con = duckdb.connect("northbound.duckdb", read_only=True)
d = load_weeks(con)
w = d["dc_weeks"]
m = build_weeks(d)
for dc in m.D:
for t in m.T:
m.ambient_balance[dc, t].set_value(
w.opening_ambient_stock[dc, 1] + m.receive["ambient", dc, t]
== sum(m.ship["ambient", dc, s, t] for s in m.S) + m.stock[dc, t])
pyo.SolverFactory("highs").solve(m)
received = sum(pyo.value(m.receive["ambient", dc, t]) for dc in m.D for t in m.T)
shipped = sum(pyo.value(m.ship["ambient", dc, s, t]) for dc in m.D for s in m.S for t in m.T)
opening = sum(w.opening_ambient_stock[dc, 1] for dc in m.D)
print(f"4-week cost ${pyo.value(m.cost):,.2f}")
print(f"ambient: opening {opening:,.0f} + received {received:,.0f} = {opening + received:,.0f}, but shipped {shipped:,.0f}")
What happens, and how to spot it
4-week cost $242,891.39
ambient: opening 530 + received 9,575 = 10,105, but shipped 11,695
The model is $13,553 cheaper, and has shipped 1,590 more ambient pallets than ever existed. The balance adds the opening stock in every week instead of last week's stock: the same 530 pallets are counted four times, and stock disappears between weeks. Day 9's conservation check (opening + received = shipped + final stock) exposes it in one line. It is the kind of check that belongs in the tests (tests/test_distribution.py, Day 20).
Mini-project: a storm in Montreal
The weather service forecasts a major snowstorm in week 3: the Montreal DC will receive only half its usual pallets that week. The warning arrives at the start of week 1.
- Re-plan with Montreal's week 3 receiving halved. What does the storm cost?
- How does the plan prepare (stock and receiving at Montreal, week by week)?
- Suppose instead the storm arrives without warning: weeks 1 and 2 go as originally planned. What is the warning worth?
Solution
import sys
import duckdb
import pandas as pd
import pyomo.environ as pyo
sys.path.insert(0, "day18")
from flows import build_weeks, load_weeks, report, v
pd.set_option("display.width", 140)
con = duckdb.connect("northbound.duckdb", read_only=True)
solver = pyo.SolverFactory("highs")
d = load_weeks(con)
base = build_weeks(d)
solver.solve(base)
storm = build_weeks(d)
half = d["dc_weeks"].receiving_pallets["DC-MTL", 3] / 2
storm.receiving["DC-MTL", 3].set_value(sum(storm.receive[k, "DC-MTL", 3] for k in storm.K) <= half)
solver.solve(storm)
print(report(storm).to_string(index=False))
print(f"storm costs ${pyo.value(storm.cost) - pyo.value(base.cost):,.2f} over four weeks")
for name, m in (("normal", base), ("storm", storm)):
print(f"{name:<7} Montreal stock at end of weeks 1-4:", [v(m.stock["DC-MTL", t]) for t in m.T],
" received:", [v(sum(m.receive[k, "DC-MTL", t] for k in m.K)) for t in m.T])
# If the storm comes as a surprise: weeks 1-2 as planned, then the storm hits
surprise = build_weeks(d)
for k in surprise.K:
for dc in surprise.D:
for t in (1, 2):
surprise.receive[k, dc, t].fix(pyo.value(base.receive[k, dc, t]))
surprise.receiving["DC-MTL", 3].set_value(sum(surprise.receive[k, "DC-MTL", 3] for k in surprise.K) <= half)
solver.solve(surprise)
print(f"surprise storm costs ${pyo.value(surprise.cost) - pyo.value(base.cost):,.2f}; "
f"knowing two weeks ahead is worth ${pyo.value(surprise.cost) - pyo.value(storm.cost):,.2f}")
week shipped received dc_stock_end short_ambient short_chilled
1 3435.0 3800.0 895.0 0.0 69.0
2 3740.0 3910.0 1065.0 0.0 79.0
3 4020.0 3160.0 205.0 122.0 93.0
4 4115.0 3910.0 0.0 31.0 99.0
storm costs $56,486.71 over four weeks
normal Montreal stock at end of weeks 1-4: [307.0, 307.0, 131.0, 0.0] received: [1500.0, 1500.0, 1500.0, 1500.0]
storm Montreal stock at end of weeks 1-4: [565.0, 625.0, 0.0, 0.0] received: [1500.0, 1500.0, 750.0, 1500.0]
surprise storm costs $62,464.49; knowing two weeks ahead is worth $5,977.78
- The storm costs $56,486.71 over four weeks, even with two weeks' warning.
- Montreal builds stock to 625 pallets by the end of week 2 (against 307 normally), receives 750 in week 3, and empties its stock that week. Notice the chilled losses in weeks 1 and 2: Montreal's receiving is shared, and the model uses it for ambient stock, giving up chilled pallets now to save ambient pallets later. Both cost $120 when lost, so the model is indifferent; if chilled losses hurt more (customers leave), they need a higher penalty.
- Without warning, the storm costs $62,464.49: the warning is worth $5,977.78. That's a first number for the value of information, which Module 7 studies properly.
fix() on the week 1 and 2 receiving variables freezes decisions already taken: the standard way to model "what's done is done" in a re-plan.
Commit
git add .
git commit -m "Day 18: multi-commodity, multi-week distribution"
git push
Day 18 checklist
- I can model several commodities that share some limits and not others.
- I showed why planning commodities apart can overload a shared limit.
- I modelled stock that carries over for one commodity and not the other.
- I used a lost-sales variable to keep the model feasible and to measure unmet demand.
- I read a table of weekly shadow prices to find the binding limits.
- I used
fix()to model decisions already taken, and valued a warning.