16.1 Nodes, arcs and flow conservation
A network is nodes (places) and arcs (one-way links). The chilled network has:
| Kind | Nodes | What happens there |
|---|---|---|
| Plant | Saint-Hyacinthe dairy (PL-SHY), Brampton chilled foods (PL-BRA) | Pallets start, up to the plant's weekly capacity |
| DC | DC-MIS, DC-OTT, DC-MTL | Pallets pass through, up to the DC's chilled throughput |
| Cross-dock | Kingston (XD-KIN), Trois-Rivières (XD-TRV) | Pallets pass through, up to the cross-dock's throughput |
| Store | 40 stores | Pallets stop: exactly the store's chilled demand |
Arcs have a cost per pallet and sometimes a capacity: full-truck linehaul from plants to DCs and cross-docks ($0.08 per pallet-km, limited by the trucks contracted), and store deliveries from DCs and cross-docks ($0.11 per pallet-km, 15% more for refrigerated trucks).
The model has one rule per node, flow conservation: what comes in minus what goes out equals what the node keeps.
16.2 A model built from two tables
Create day16/network.py. Nothing in it knows about plants or Kingston: it reads two tables and builds a constraint per node and a variable per arc.
"""Day 16: a general minimum-cost flow model, built from a table of nodes and a table of arcs.
Import it: from network import load_chilled, build_flow, flow_table
"""
import pandas as pd
import pyomo.environ as pyo
def load_chilled(con):
nodes = con.sql("SELECT * FROM chilled_nodes").df().set_index("node")
arcs = con.sql("SELECT * FROM chilled_arcs").df().set_index(["from_node", "to_node"])
return nodes, arcs
def build_flow(nodes, arcs, closed=()):
"""Plants send pallets out (up to their capacity); DCs and cross-docks pass them on (up to their throughput);
stores keep what they need. Arcs have a cost per pallet and, sometimes, a capacity."""
m = pyo.ConcreteModel(name="chilled_flow")
m.N = pyo.Set(initialize=nodes.index.tolist())
m.A = pyo.Set(initialize=arcs.index.tolist(), dimen=2)
def arc_bounds(m, i, j):
cap = arcs.capacity_pallets[i, j]
return (0, None if pd.isna(cap) else float(cap))
m.flow = pyo.Var(m.A, bounds=arc_bounds)
for i, j in m.A:
if i in closed or j in closed:
m.flow[i, j].fix(0)
inflow = {n: [] for n in nodes.index}
outflow = {n: [] for n in nodes.index}
for i, j in arcs.index:
outflow[i].append((i, j))
inflow[j].append((i, j))
def balance(m, n):
net_in = sum(m.flow[a] for a in inflow[n]) - sum(m.flow[a] for a in outflow[n])
kind = nodes.kind[n]
if kind == "plant":
return -net_in <= float(nodes.throughput_capacity[n]) # what leaves a plant, up to its capacity
if kind == "store":
return net_in == float(nodes.demand_pallets[n]) # what a store receives, exactly its demand
return net_in == 0 # DCs and cross-docks keep nothing
m.balance = pyo.Constraint(m.N, rule=balance)
hubs = [n for n in nodes.index if nodes.kind[n] in ("dc", "cross_dock")]
m.throughput = pyo.Constraint(hubs, rule=lambda m, n: sum(m.flow[a] for a in inflow[n]) <= float(nodes.throughput_capacity[n]))
m.cost = pyo.Objective(expr=sum(float(arcs.cost_per_pallet[a]) * m.flow[a] for a in m.A))
return m
def flow_table(m, nodes):
rows = []
for n in m.N:
if nodes.kind[n] == "store":
continue
out = sum(pyo.value(m.flow[i, j]) for i, j in m.A if i == n)
inn = sum(pyo.value(m.flow[i, j]) for i, j in m.A if j == n)
rows.append((n, nodes.kind[n], nodes.place[n], round(inn, 1) + 0.0, round(out, 1) + 0.0, nodes.throughput_capacity[n]))
return pd.DataFrame(rows, columns=["node", "kind", "place", "pallets_in", "pallets_out", "capacity"])
Points worth slowing down for:
- Arc lists per node (
inflow,outflow) are built once. Searching all 156 arcs inside every node's rule would work, but get slow on big networks. m.Ais a set of pairs (dimen=2), som.flow["DC-MTL", "S33"]reads like the arc it is.closedfixes every arc into or out of a closed node to zero: closing a site is a data question, not a new model.
16.3 The chilled network: what flows where
Create day16/run_chilled.py:
import sys
import duckdb
import pandas as pd
import pyomo.environ as pyo
sys.path.insert(0, "day16")
from network import build_flow, flow_table, load_chilled
pd.set_option("display.width", 140)
con = duckdb.connect("northbound.duckdb", read_only=True)
nodes, arcs = load_chilled(con)
print(nodes.kind.value_counts().to_dict(), f"{len(arcs)} arcs, {nodes.demand_pallets.sum():.0f} pallets of chilled demand")
m = build_flow(nodes, arcs)
m.dual = pyo.Suffix(direction=pyo.Suffix.IMPORT)
result = pyo.SolverFactory("highs").solve(m)
print(result.solver.termination_condition, f"weekly chilled cost ${pyo.value(m.cost):,.2f}")
print(flow_table(m, nodes).to_string(index=False))
# Which stores are served through a cross-dock?
via = {j: i for i, j in m.A if i.startswith("XD-") and pyo.value(m.flow[i, j]) > 1e-6}
print("served through a cross-dock:", {s: f"{x} ({nodes.place[s]})" for s, x in via.items()})
flows = [pyo.value(m.flow[a]) for a in m.A]
print("every flow a whole number of pallets:", all(abs(f - round(f)) < 1e-6 for f in flows))
{'store': 40, 'dc': 3, 'plant': 2, 'cross_dock': 2} 156 arcs, 922 pallets of chilled demand
optimal weekly chilled cost $18,203.64
node kind place pallets_in pallets_out capacity
PL-SHY plant Saint-Hyacinthe 0.0 578.0 950
PL-BRA plant Brampton 0.0 344.0 900
DC-MIS dc Mississauga 344.0 344.0 480
DC-OTT dc Ottawa 200.0 200.0 200
DC-MTL dc Montreal 255.0 255.0 460
XD-KIN cross_dock Kingston 35.0 35.0 160
XD-TRV cross_dock Trois-Rivieres 123.0 123.0 220
served through a cross-dock: {'S22': 'XD-KIN (Kingston)', 'S23': 'XD-KIN (Kingston)', 'S36': 'XD-TRV (Quebec City)', 'S37': 'XD-TRV (Quebec City)', 'S38': 'XD-TRV (Quebec City)', 'S39': 'XD-TRV (Sherbrooke)', 'S40': 'XD-TRV (Sherbrooke)'}
every flow a whole number of pallets: True
922 chilled pallets a week cost $18,203.64 to move. Reading the flows:
- Saint-Hyacinthe supplies 578 pallets, Brampton 344: each plant serves its own side of the network. Neither plant is full.
- The Ottawa DC is full (200 of 200). Mississauga and Montreal have room.
- Kingston's two stores come through the Kingston cross-dock (35 pallets, by full truck from Mississauga). Quebec City and Sherbrooke stores come through Trois-Rivières (123 pallets, straight from the Saint-Hyacinthe plant), skipping the Montreal DC entirely.
- Flows are whole pallets again: min-cost flow shares the transportation problem's special structure.
Decision it supports: which plant, DC and cross-dock each store's chilled pallets go through.
Other decisions you can support the same way: routing parcels through sorting hubs · supply chains from farms through packers to stores · blood from donor clinics through labs to hospitals.
16.4 Node prices and what a cross-dock saves
# Shadow prices: the cost of one more chilled pallet delivered at each store, and of hub capacity
prices = pd.Series({n: m.dual[m.balance[n]] for n in m.N if nodes.kind[n] == "store"}).round(2)
print("delivered cost of one more chilled pallet, cheapest and dearest stores:")
print(prices.sort_values().to_frame("cost").join(nodes.place).iloc[[0, 1, -2, -1]].to_string())
print("hub capacity worth ($ a pallet):", {n: round(-m.dual[m.throughput[n]], 2) for n in m.throughput})
# What does each cross-dock save?
for xd in ("XD-KIN", "XD-TRV"):
closed = build_flow(nodes, arcs, closed=(xd,))
pyo.SolverFactory("highs").solve(closed)
print(f"without {xd}: ${pyo.value(closed.cost):,.2f} (+${pyo.value(closed.cost) - pyo.value(m.cost):,.2f})")
delivered cost of one more chilled pallet, cheapest and dearest stores:
cost place
S10 9.15 Mississauga
S11 9.41 Mississauga
S25 39.09 Gatineau
S24 39.48 Gatineau
hub capacity worth ($ a pallet): {'DC-MIS': 0.0, 'DC-OTT': 9.3, 'DC-MTL': 0.0, 'XD-KIN': 0.0, 'XD-TRV': 0.0}
without XD-KIN: $18,762.12 (+$558.48)
without XD-TRV: $19,391.57 (+$1,187.93)
- The dearest chilled pallets go to Gatineau ($39.48), not Quebec City: Ottawa's DC is full, so Gatineau is served from Montreal, 208 km away, while Quebec City gets cheap full trucks to Trois-Rivières.
- Ottawa DC capacity is worth $9.30 a pallet; every other hub has room.
- Closing Kingston costs $558.48 a week, closing Trois-Rivières $1,187.93. Those are what the cross-docks save in transport, before their own running costs.
The planted bug
day16/bug_sign.py rewrites every store's balance as "out minus in equals demand". Run it.
m = build_flow(nodes, arcs)
for n in m.N:
if nodes.kind[n] == "store":
out = sum(m.flow[i, j] for i, j in m.A if i == n)
inn = sum(m.flow[i, j] for i, j in m.A if j == n)
m.balance[n].set_value(out - inn == float(nodes.demand_pallets[n]))
print(pyo.SolverFactory("highs").solve(m, load_solutions=False).solver.termination_condition)
What happens, and why
infeasible
With "out − in = demand", every store must send out its demand: stores become sources. Nothing can absorb those pallets (nothing downstream of a store), so the model is infeasible. Every network model needs one sign convention, stated once and used everywhere. Ours: inflow minus outflow equals what the node keeps.
Mini-project: keep both cross-docks?
Each cross-dock costs money to run: Kingston $500 a week, Trois-Rivières $900. Compare all four combinations of open and closed, with transport and fixed costs, and recommend.
Solution
import itertools
import sys
import duckdb
import pyomo.environ as pyo
sys.path.insert(0, "day16")
from network import build_flow, load_chilled
FIXED = {"XD-KIN": 500, "XD-TRV": 900}
con = duckdb.connect("northbound.duckdb", read_only=True)
nodes, arcs = load_chilled(con)
for keep in itertools.product([True, False], repeat=2):
open_xd = [x for x, k in zip(FIXED, keep) if k]
m = build_flow(nodes, arcs, closed=[x for x in FIXED if x not in open_xd])
pyo.SolverFactory("highs").solve(m)
fixed = sum(FIXED[x] for x in open_xd)
print(f"open {', '.join(open_xd) or 'none':<16} flow ${pyo.value(m.cost):,.2f} + fixed ${fixed:,} = ${pyo.value(m.cost) + fixed:,.2f}")
open XD-KIN, XD-TRV flow $18,203.64 + fixed $1,400 = $19,603.64
open XD-KIN flow $19,391.57 + fixed $500 = $19,891.57
open XD-TRV flow $18,762.12 + fixed $900 = $19,662.12
open none flow $19,950.05 + fixed $0 = $19,950.05
Keep both, at $19,603.64 a week in total. Trois-Rivières saves $1,187.93 for $900: a clear yes. Kingston saves $558.48 for $500: yes, but only by $58 a week. A small rise in Kingston's rent, or a small drop in Kingston's volume, would flip it. Here the savings simply add up (closing both costs $558.48 + $1,187.93 more), because the two cross-docks serve different stores. When sites compete for the same customers, the four combinations stop adding up, and with dozens of candidate sites you can't list them all: Module 3's facility location model chooses with binary variables.
Commit
git add .
git commit -m "Day 16: min-cost flow from node and arc tables, cross-docks"
git push
Day 16 checklist
- I can write flow conservation for plants, hubs and stores with one sign convention.
- My flow model is built from a node table and an arc table, and knows nothing else.
- I can read node shadow prices as delivered costs and hub duals as the value of capacity.
- I priced each cross-dock by closing it, and added fixed costs to decide.
- I know transportation and assignment are special cases of min-cost flow.
- I found a sign error by its infeasibility.