Update the course data
Copy the latest make_data.py from the Course data page, add networkx to your packages, and rebuild:
echo "networkx==3.7" >> requirements.txt
pip install -r requirements.txt
python make_data.py
python day01/ladder.py
python day06/load_tables.py
The new tables:
| Table | What it holds |
|---|---|
places | 17 cities and towns with approximate coordinates |
road_segments | 28 road segments: km, driving minutes, and the trucks a week Northbound's carriers can run on each (Day 17) |
dc_logistics | Each DC's weekly capacity in pallets, and whether it stocks French-labelled products (Mississauga doesn't) |
store_logistics | Each store's location and weekly pallets (all products, and chilled only) |
dc_store_lanes | Every DC–store pair: km, minutes and cost per pallet ($4 handling + $0.11 per pallet-km) |
driver_route_minutes | 8 Montreal drivers × 8 routes: minutes each driver needs for each route |
chilled_nodes, chilled_arcs | The chilled network: plants, DCs, cross-docks, stores, and the lanes between them (Day 16) |
14.1 Today's network and its cost
Create day14/transport.py. A load_network function reads DCs, stores and lanes; a build_transport function will hold the model. The script part, under if __name__ == "__main__":, starts with today's situation: every store served by its current DC.
import duckdb
import pandas as pd
import pyomo.environ as pyo
def load_network(con):
"""DCs with capacity, stores with weekly pallets, and the cost of every DC-store lane."""
dcs = con.sql("SELECT * FROM dc_logistics ORDER BY dc_id").df().set_index("dc_id")
stores = con.sql("""
SELECT s.store_id, s.city, s.province, s.dc_id AS current_dc, l.pallets_per_week
FROM stores s JOIN store_logistics l USING (store_id) ORDER BY s.store_id""").df().set_index("store_id")
lanes = con.sql("SELECT * FROM dc_store_lanes").df().set_index(["dc_id", "store_id"])
return dcs, stores, lanes
The if __name__ == "__main__": line lets other files import load_network and build_transport (Day 15 does) without running the analysis below it.
# ---------- 14.1 Today: every store served by its current DC ----------
current = stores.groupby("current_dc").pallets_per_week.sum()
current_cost = sum(lanes.cost_per_pallet[stores.current_dc[s], s] * stores.pallets_per_week[s] for s in stores.index)
print(pd.DataFrame({"pallets_today": current, "capacity": dcs.pallets_per_week_capacity}).to_string())
print(f"total demand {stores.pallets_per_week.sum():,} pallets; today's weekly shipping cost ${current_cost:,.2f}")
pallets_today capacity
DC-MIS 1195 1600
DC-MTL 1427 1500
DC-OTT 923 700
total demand 3,545 pallets; today's weekly shipping cost $35,194.71
Today's routing costs $35,194.71 a week, but it is not feasible: the Ottawa DC ships 923 pallets a week with room for 700. The difference is handled today by overtime and a rented trailer yard, which the lane costs don't show. Montreal is nearly full too. A plan that respects the capacities will cost more than today's on paper.
14.2 The transportation problem
Every DC has a capacity, every store a demand, every lane a cost per pallet. Choose , the pallets a week from to :
def build_transport(dcs, stores, lanes, capacity=None):
"""Minimize the cost of shipping every store's pallets, within each DC's weekly capacity."""
capacity = capacity or dcs.pallets_per_week_capacity.to_dict()
m = pyo.ConcreteModel(name="transportation")
m.D = pyo.Set(initialize=dcs.index.tolist())
m.S = pyo.Set(initialize=stores.index.tolist())
m.ship = pyo.Var(m.D, m.S, within=pyo.NonNegativeReals) # pallets a week
m.demand = pyo.Constraint(m.S, rule=lambda m, s: sum(m.ship[d, s] for d in m.D) == stores.pallets_per_week[s])
m.supply = pyo.Constraint(m.D, rule=lambda m, d: sum(m.ship[d, s] for s in m.S) <= capacity[d])
m.cost = pyo.Objective(expr=sum(lanes.cost_per_pallet[d, s] * m.ship[d, s] for d in m.D for s in m.S))
return m
def loads(m):
return {d: round(sum(pyo.value(m.ship[d, s]) for s in m.S), 2) for d in m.D}
# ---------- 14.2 The transportation problem ----------
m = build_transport(dcs, stores, lanes)
m.dual = pyo.Suffix(direction=pyo.Suffix.IMPORT)
result = pyo.SolverFactory("highs").solve(m)
print(result.solver.termination_condition, f"weekly cost ${pyo.value(m.cost):,.2f}", loads(m))
split = {s: {d: pyo.value(m.ship[d, s]) for d in m.D if pyo.value(m.ship[d, s]) > 1e-6}
for s in m.S if sum(pyo.value(m.ship[d, s]) > 1e-6 for d in m.D) > 1}
print("stores served by two DCs:", split)
moved = [s for s in m.S if pyo.value(m.ship[stores.current_dc[s], s]) < stores.pallets_per_week[s] - 1e-6]
print("stores no longer (fully) served by their current DC:", moved)
flows = [pyo.value(m.ship[d, s]) for d in m.D for s in m.S]
print("every flow a whole number of pallets:", all(abs(f - round(f)) < 1e-6 for f in flows))
optimal weekly cost $39,089.81 {'DC-MIS': 1345.0, 'DC-MTL': 1500.0, 'DC-OTT': 700.0}
stores served by two DCs: {'S16': {'DC-MIS': 16.0, 'DC-MTL': 69.0}, 'S21': {'DC-MTL': 4.0, 'DC-OTT': 108.0}}
stores no longer (fully) served by their current DC: ['S16', 'S21', 'S22', 'S23']
every flow a whole number of pallets: True
The cheapest plan that fits costs $39,089.81 a week. Ottawa and Montreal are exactly full, Mississauga has 255 pallets to spare. Four Ottawa-DC stores change: both Kingston stores (S22, S23) go to Mississauga, and two Ottawa stores are split between two DCs: S16 gets its pallets from Mississauga and Montreal, S21 mostly from Ottawa with 4 pallets from Montreal.
Every flow is a whole number of pallets, though the variables are continuous. This is no accident. The constraint matrix of a transportation problem has a special structure (total unimodularity): with whole-number supplies and demands, every corner of the feasible region has whole-number coordinates, so the simplex method can only land on whole numbers. Transportation, assignment, shortest-path and maximum-flow problems all share it, which is why this week's models need no integer variables.
Decision it supports: how many pallets each DC sends to each store next week.
Other decisions you can support the same way: which warehouse ships each online order · which power plant supplies each region · which school each neighbourhood's students attend.
Try it 14.1
What would capacity cost? Using only today's output, how much more per week does the plan that fits cost than today's routing, and why is that number not a saving waiting to happen?
Solution
$39,089.81 − $35,194.71 = $3,895.10 a week. Today's routing is cheaper on paper only because Ottawa ships 223 pallets a week it has no room for; the overtime and the trailer yard that make that possible are not in the lane costs. The honest comparison is between plans that fit, or a plan that fits against the real cost of today's workaround. Day 15 prices the alternative: a bigger Ottawa DC.
14.3 Shadow prices: the delivered cost of a pallet
# ---------- 14.3 Shadow prices: what a pallet costs to deliver, store by store ----------
print("DC capacity shadow prices ($ saved per extra pallet of capacity):",
{d: round(-m.dual[m.supply[d]], 2) for d in m.D})
prices = pd.Series({s: m.dual[m.demand[s]] for s in m.S}, name="delivered_cost").round(2)
print(prices.to_frame().join(stores[["city"]]).sort_values("delivered_cost").iloc[[0, 1, -3, -2, -1]].to_string())
DC capacity shadow prices ($ saved per extra pallet of capacity): {'DC-MIS': 0.0, 'DC-MTL': 26.18, 'DC-OTT': 48.18}
delivered_cost city
S10 4.39 Mississauga
S11 4.62 Mississauga
S36 59.89 Quebec City
S37 59.94 Quebec City
S38 60.34 Quebec City
Two kinds of shadow price, and each answers a business question:
- DC capacity. One more pallet of capacity in Ottawa would save $48.18 a week; in Montreal $26.18; in Mississauga nothing (it has spare room). The supply constraint is "≤", and in a minimization the solver reports its dual as a negative number, so we flip the sign to read it as a saving.
- Store demand. The shadow price of each store's demand constraint is the delivered cost of one more pallet there: $4.39 in Mississauga, $60.34 in Quebec City. These are location prices: what it costs Northbound, at the margin, to supply each store. Category managers can use them to set regional prices or minimum order sizes.
14.4 The assignment problem
Montreal has 8 delivery routes tomorrow and 8 drivers. Each driver knows some routes better: driver_route_minutes has the minutes each driver needs for each route. Give each driver exactly one route, minimizing total minutes. It is a transportation problem where every supply and demand is 1. Create day14/assignment.py:
import duckdb
import numpy as np
import pandas as pd
import pyomo.environ as pyo
from scipy.optimize import linear_sum_assignment
con = duckdb.connect("northbound.duckdb", read_only=True)
minutes = con.sql("SELECT * FROM driver_route_minutes").df().pivot(index="driver", columns="route", values="minutes")
print(minutes.to_string())
m = pyo.ConcreteModel()
m.D = pyo.Set(initialize=minutes.index.tolist())
m.R = pyo.Set(initialize=minutes.columns.tolist())
m.x = pyo.Var(m.D, m.R, bounds=(0, 1)) # NOT declared binary
m.one_route = pyo.Constraint(m.D, rule=lambda m, d: sum(m.x[d, r] for r in m.R) == 1)
m.one_driver = pyo.Constraint(m.R, rule=lambda m, r: sum(m.x[d, r] for d in m.D) == 1)
m.total = pyo.Objective(expr=sum(minutes.loc[d, r] * m.x[d, r] for d in m.D for r in m.R))
pyo.SolverFactory("highs").solve(m)
plan = {d: r for d in m.D for r in m.R if pyo.value(m.x[d, r]) > 0.5}
values = sorted({round(pyo.value(m.x[d, r]), 6) + 0.0 for d in m.D for r in m.R})
print(f"LP: {pyo.value(m.total):,.0f} minutes; values taken by x: {values}")
print(plan)
rows, cols = linear_sum_assignment(minutes.to_numpy()) # the Hungarian method
print(f"Hungarian method: {minutes.to_numpy()[rows, cols].sum():,} minutes")
print(f"each driver's first-choice route would need {minutes.min(axis=1).sum():,} minutes, but routes repeat: "
f"{minutes.idxmin(axis=1).value_counts().to_dict()}")
route R1 R2 R3 R4 R5 R6 R7 R8
driver
D1 382 330 387 377 326 403 395 320
D2 332 398 427 349 387 425 426 285
D3 368 371 428 404 346 399 441 314
D4 394 372 450 411 364 410 380 313
D5 390 380 408 391 374 348 362 283
D6 411 318 407 386 320 336 387 349
D7 359 351 419 369 399 382 371 288
D8 375 361 409 425 360 371 362 288
LP: 2,768 minutes; values taken by x: [0.0, 1.0]
{'D1': 'R3', 'D2': 'R1', 'D3': 'R5', 'D4': 'R7', 'D5': 'R6', 'D6': 'R2', 'D7': 'R4', 'D8': 'R8'}
Hungarian method: 2,768 minutes
each driver's first-choice route would need 2,409 minutes, but routes repeat: {'R8': 7, 'R2': 1}
The variables are allowed any value from 0 to 1, yet every one comes out 0 or 1: total unimodularity again. scipy.optimize.linear_sum_assignment uses the Hungarian method, a specialized algorithm for exactly this problem, and agrees: 2,768 minutes.
Why not give each driver his fastest route? Because seven of the eight are fastest on R8. The model resolves the conflict globally: D8 keeps R8, and everyone else gets the route where their loss is smallest.
The planted bug
day14/bug_supply.py changes one character in the supply rule. Run it.
m.del_component(m.supply)
m.supply = pyo.Constraint(m.D, rule=lambda m, d: sum(m.ship[d, s] for s in m.S) == dcs.pallets_per_week_capacity[d])
result = pyo.SolverFactory("highs").solve(m, load_solutions=False)
print(result.solver.termination_condition)
What happens, and why
infeasible
== instead of <= says every DC must ship exactly its capacity: 3,800 pallets a week. The stores need 3,545, and the demand constraint says they get exactly that. No plan does both. When a model built from correct data is infeasible, compare the sense of every constraint (==, <=, >=) with the business rule it states.
Mini-project: drivers with rules
Tomorrow's assignment has three rules: D3 has no licence for the tunnel on route R5; D6 must finish by 2 p.m., so at most 330 minutes; no driver may be on the road more than 380 minutes. Solve it in day14/mini_project_drivers.py. Does it still come out in whole numbers?
Solution
def assign(rules=True, max_minutes=380):
m = pyo.ConcreteModel()
m.D = pyo.Set(initialize=minutes.index.tolist())
m.R = pyo.Set(initialize=minutes.columns.tolist())
m.x = pyo.Var(m.D, m.R, bounds=(0, 1))
m.one_route = pyo.Constraint(m.D, rule=lambda m, d: sum(m.x[d, r] for r in m.R) == 1)
m.one_driver = pyo.Constraint(m.R, rule=lambda m, r: sum(m.x[d, r] for d in m.D) == 1)
if rules:
for d in m.D:
for r in m.R:
too_long = minutes.loc[d, r] > max_minutes or (d == "D6" and minutes.loc[d, r] > 330)
if too_long or (d, r) == ("D3", "R5"):
m.x[d, r].fix(0) # this pair is not allowed
m.total = pyo.Objective(expr=sum(minutes.loc[d, r] * m.x[d, r] for d in m.D for r in m.R))
result = pyo.SolverFactory("highs").solve(m, load_solutions=False)
if result.solver.termination_condition != pyo.TerminationCondition.optimal:
return str(result.solver.termination_condition), None
m.solutions.load_from(result)
plan = {d: r for d in m.D for r in m.R if pyo.value(m.x[d, r]) > 0.5}
whole = all(abs(pyo.value(m.x[d, r]) - round(pyo.value(m.x[d, r]))) < 1e-6 for d in m.D for r in m.R)
longest = max(minutes.loc[d, r] for d, r in plan.items())
return f"{pyo.value(m.total):,.0f} minutes, longest route {longest}, whole numbers: {whole}", plan
for rules, limit in ((False, None), (True, 380), (True, 390)):
summary, plan = assign(rules, limit)
print("no rules" if not rules else f"rules, at most {limit} minutes", "->", summary)
if plan:
print(" ", plan)
else:
print(" fastest time on each route:", minutes.min().to_dict())
no rules -> 2,768 minutes, longest route 387, whole numbers: True
{'D1': 'R3', 'D2': 'R1', 'D3': 'R5', 'D4': 'R7', 'D5': 'R6', 'D6': 'R2', 'D7': 'R4', 'D8': 'R8'}
rules, at most 380 minutes -> infeasible
fastest time on each route: {'R1': 332, 'R2': 318, 'R3': 387, 'R4': 349, 'R5': 320, 'R6': 336, 'R7': 362, 'R8': 283}
rules, at most 390 minutes -> 2,784 minutes, longest route 387, whole numbers: True
{'D1': 'R3', 'D2': 'R4', 'D3': 'R1', 'D4': 'R5', 'D5': 'R6', 'D6': 'R2', 'D7': 'R8', 'D8': 'R7'}
At 380 minutes the problem is infeasible: the fastest anyone does R3 is 387 minutes, so no assignment can cover it. The rule as written can't be met by any roster; Day 7's first check (a minimum above its maximum) catches this. At 390 minutes, the rules cost 16 minutes a day (2,784 against 2,768), and the answer is still in whole numbers: removing pairs (fixing variables to 0) keeps the special structure.
Commit
git add .
git commit -m "Day 14: transportation and assignment"
git push
Day 14 checklist
- I can write and solve a transportation problem from tables of supply, demand and lane costs.
- I know why transportation and assignment problems give whole-number answers without integer variables.
- I can read DC capacity duals as savings and store demand duals as delivered costs.
- I solved an assignment problem as an LP and checked it with the Hungarian method.
- I found an infeasibility caused by
==where<=belonged. - I can add forbidden pairs to an assignment and recognise a rule no roster can meet.