17.1 The road network as a graph
road_segments has 28 roads between 17 places, each with km, driving minutes and the trucks a week Northbound's carriers have contracted on it. networkx is Python's graph library: nodes, edges, and the classic algorithms. Create day17/paths.py:
import duckdb
import networkx as nx
import pandas as pd
import pyomo.environ as pyo
pd.set_option("display.width", 140)
con = duckdb.connect("northbound.duckdb", read_only=True)
roads = con.sql("SELECT * FROM road_segments").df()
# ---------- 17.1 The road network as a graph ----------
G = nx.Graph() # roads go both ways
for r in roads.itertuples():
G.add_edge(r.from_place, r.to_place, km=r.km, minutes=r.minutes, road=r.road)
print(f"{G.number_of_nodes()} places, {G.number_of_edges()} road segments")
for weight in ("km", "minutes"):
path = nx.shortest_path(G, "Mississauga", "Quebec City", weight=weight)
km = nx.path_weight(G, path, "km")
minutes = nx.path_weight(G, path, "minutes")
print(f"shortest by {weight:<7}: {' - '.join(path)} ({km} km, {minutes} min)")
17 places, 28 road segments
shortest by km : Mississauga - Toronto - Belleville - Kingston - Cornwall - Montreal - Saint-Hyacinthe - Drummondville - Quebec City (858 km, 570 min)
shortest by minutes: Mississauga - Toronto - Belleville - Kingston - Cornwall - Montreal - Trois-Rivieres - Quebec City (863 km, 565 min)
Dijkstra's algorithm (what shortest_path uses for weighted graphs) grows a set of places whose shortest distance is known, always adding the nearest unknown one. The shortest route by distance (858 km, via Drummondville) is not the fastest: the route via Trois-Rivières is 5 km longer and 5 minutes quicker. A dispatcher wants minutes, a fuel budget wants km: the "shortest" path depends on what you measure.
17.2 Shortest path as a flow
The shortest path is a min-cost flow: send one truck from Mississauga to Quebec City, where each road costs its km. Roads go both ways, so each becomes two arcs.
# ---------- 17.2 The same answer as a minimum-cost flow ----------
# Send one truck from Mississauga to Quebec City; each road can be used in either direction.
arcs = [(a, b) for a, b in G.edges()] + [(b, a) for a, b in G.edges()]
m = pyo.ConcreteModel()
m.N = pyo.Set(initialize=list(G.nodes()))
m.A = pyo.Set(initialize=arcs, dimen=2)
m.use = pyo.Var(m.A, within=pyo.NonNegativeReals)
supply = {n: 0 for n in G.nodes()}
supply["Mississauga"], supply["Quebec City"] = 1, -1
m.balance = pyo.Constraint(m.N, rule=lambda m, n: sum(m.use[n, j] for i, j in m.A if i == n)
- sum(m.use[i, n] for i, j in m.A if j == n) == supply[n])
m.km = pyo.Objective(expr=sum(G.edges[i, j]["km"] * m.use[i, j] for i, j in m.A))
m.dual = pyo.Suffix(direction=pyo.Suffix.IMPORT)
pyo.SolverFactory("highs").solve(m)
used = [(i, j) for i, j in m.A if pyo.value(m.use[i, j]) > 0.5]
print(f"LP: {pyo.value(m.km):g} km using {used}")
# The duals are distances: dual(n) - dual(Quebec City) = km from n to Quebec City
d_end = m.dual[m.balance["Quebec City"]]
for n in ("Mississauga", "Kingston", "Montreal", "Drummondville"):
print(f" {n:<14} dual gives {m.dual[m.balance[n]] - d_end:6.1f} km to Quebec City; "
f"networkx gives {nx.shortest_path_length(G, n, 'Quebec City', weight='km')}")
LP: 858 km using [('Mississauga', 'Toronto'), ('Toronto', 'Belleville'), ('Belleville', 'Kingston'), ('Kingston', 'Cornwall'), ('Cornwall', 'Montreal'), ('Montreal', 'Saint-Hyacinthe'), ('Saint-Hyacinthe', 'Drummondville'), ('Drummondville', 'Quebec City')]
Mississauga dual gives 858.0 km to Quebec City; networkx gives 858
Kingston dual gives 560.0 km to Quebec City; networkx gives 560
Montreal dual gives 265.0 km to Quebec City; networkx gives 265
Drummondville dual gives 150.0 km to Quebec City; networkx gives 150
The LP finds the same 858 km. Its duals are distances: the shadow price of a place's balance, minus Quebec City's, is that place's distance to Quebec City. Each node's dual is the cost of getting one more truck from there to the end, which, for a shortest path, is the distance. Dijkstra's algorithm and the LP's dual are two ways of computing the same numbers.
17.3 Where the lane distances come from
all_pairs_dijkstra_path_length gives the road distance between every pair of places:
# ---------- 17.3 All pairs: where the lane distances come from ----------
dist = dict(nx.all_pairs_dijkstra_path_length(G, weight="km"))
dcs = {"DC-MIS": "Mississauga", "DC-OTT": "Ottawa", "DC-MTL": "Montreal"}
table = pd.DataFrame({dc: {c: dist[city][c] for c in ["Toronto", "Hamilton", "Kingston", "Ottawa", "Gatineau",
"Montreal", "Laval", "Sherbrooke", "Quebec City"]}
for dc, city in dcs.items()})
print("road km from each DC's city:")
print(table.T.to_string())
check = con.sql("""
SELECT l.dc_id, l.store_id, s.city, l.km
FROM dc_store_lanes l JOIN stores s USING (store_id)
WHERE l.store_id IN ('S01', 'S23', 'S36') ORDER BY l.store_id, l.dc_id""").df()
check["road_km"] = [dist[dcs[r.dc_id]][r.city] for r in check.itertuples()]
check["in_town_km"] = (check.km - check.road_km).round(1)
print(check.to_string(index=False))
road km from each DC's city:
Toronto Hamilton Kingston Ottawa Gatineau Montreal Laval Sherbrooke Quebec City
DC-MIS 28 55 298 438 446 593 613 743 858
DC-OTT 410 480 195 0 8 200 220 350 465
DC-MTL 565 635 295 200 208 0 20 150 265
dc_id store_id city km road_km in_town_km
DC-MIS S01 Toronto 31.6 28 3.6
DC-MTL S01 Toronto 568.6 565 3.6
DC-OTT S01 Toronto 413.6 410 3.6
DC-MIS S23 Kingston 305.5 298 7.5
DC-MTL S23 Kingston 302.5 295 7.5
DC-OTT S23 Kingston 202.5 195 7.5
DC-MIS S36 Quebec City 863.1 858 5.1
DC-MTL S36 Quebec City 270.1 265 5.1
DC-OTT S36 Quebec City 470.1 465 5.1
Each lane in dc_store_lanes is the road distance between the DC's city and the store's city, plus a few km in town to the store's door (in_town_km, the same for every DC). The Day 14 to 16 models rested on exactly this computation.
Decision it supports: the route, and the distance and time behind every lane cost.
Other decisions you can support the same way: emergency response times · the cheapest sequence of currency conversions · project critical paths (longest paths).
17.4 Maximum flow
Before Christmas, Northbound wants to move as many trucks as possible from the Mississauga DC to Quebec City. Each carrier contract allows a number of trucks a week on one road, eastbound: the network is now directed, with a capacity on each arc. The maximum flow is the most trucks a week the contracts allow, end to end. Create day17/max_flow.py:
import duckdb
import networkx as nx
import pyomo.environ as pyo
con = duckdb.connect("northbound.duckdb", read_only=True)
roads = con.sql("SELECT from_place, to_place, truck_slots_per_week FROM road_segments").fetchall()
# Carrier contracts are eastbound: a directed graph, one arc per contract
G = nx.DiGraph()
for a, b, slots in roads:
G.add_edge(a, b, capacity=slots)
# ---------- 17.4 Maximum flow as an LP ----------
m = pyo.ConcreteModel()
m.N = pyo.Set(initialize=list(G.nodes()))
m.A = pyo.Set(initialize=list(G.edges()), dimen=2)
m.trucks = pyo.Var(m.A, bounds=lambda m, i, j: (0, G.edges[i, j]["capacity"]))
m.through = pyo.Var(within=pyo.NonNegativeReals) # trucks a week from start to end
start, end = "Mississauga", "Quebec City"
net = {n: (1 if n == start else -1 if n == end else 0) for n in G.nodes()}
m.balance = pyo.Constraint(m.N, rule=lambda m, n: sum(m.trucks[n, j] for i, j in m.A if i == n)
- sum(m.trucks[i, n] for i, j in m.A if j == n) == net[n] * m.through)
m.most = pyo.Objective(expr=m.through, sense=pyo.maximize)
m.dual = pyo.Suffix(direction=pyo.Suffix.IMPORT)
pyo.SolverFactory("highs").solve(m)
print(f"LP: at most {pyo.value(m.through):g} trucks a week from {start} to {end}")
busy = {a: pyo.value(m.trucks[a]) for a in m.A if pyo.value(m.trucks[a]) > 1e-6}
print("trucks on each contract used:", {f"{i}->{j}": round(v) for (i, j), v in busy.items()})
LP: at most 33 trucks a week from Mississauga to Quebec City
trucks on each contract used: {'Mississauga->Toronto': 33, 'Toronto->Peterborough': 8, 'Toronto->Belleville': 25, 'Peterborough->Belleville': 2, 'Peterborough->Ottawa': 6, 'Belleville->Kingston': 27, 'Kingston->Ottawa': 12, 'Kingston->Cornwall': 15, 'Ottawa->Gatineau': 6, 'Ottawa->Montreal': 12, 'Cornwall->Montreal': 15, 'Montreal->Laval': 8, 'Montreal->Saint-Hyacinthe': 18, 'Montreal->Trois-Rivieres': 7, 'Gatineau->Montreal': 6, 'Laval->Trois-Rivieres': 8, 'Saint-Hyacinthe->Drummondville': 18, 'Drummondville->Quebec City': 18, 'Trois-Rivieres->Quebec City': 15}
m.through is a variable: the flow leaves Mississauga and arrives in Quebec City at the same rate, conserved everywhere in between. At most 33 trucks a week can get through.
(Don't name a script bottleneck.py: pandas imports an optional package called bottleneck, and Python would find your file first. Your own file names can shadow packages: name scripts after what they do, not after common words.)
17.5 The minimum cut: finding the bottleneck
Why 33? The max-flow min-cut theorem: the maximum flow equals the smallest total capacity of a set of arcs whose removal disconnects start from end. That set is the bottleneck.
# ---------- 17.5 networkx, and the minimum cut ----------
value, _ = nx.maximum_flow(G, start, end)
cut_value, (reach, rest) = nx.minimum_cut(G, start, end)
cut = sorted((a, b, G.edges[a, b]["capacity"]) for a in reach for b in G.successors(a) if b in rest)
print(f"networkx maximum flow {value}; minimum cut {cut_value}: {cut}")
print("places still reachable on the Mississauga side of the cut:", sorted(reach))
networkx maximum flow 33; minimum cut 33: [('Kingston', 'Cornwall', 15), ('Kingston', 'Ottawa', 12), ('Peterborough', 'Ottawa', 6)]
places still reachable on the Mississauga side of the cut: ['Belleville', 'Brampton', 'Hamilton', 'Kingston', 'Mississauga', 'Peterborough', 'Toronto']
The bottleneck is east of Kingston: the 401 to Cornwall (15 trucks), Kingston to Ottawa (12) and Peterborough to Ottawa (6). Everything west of it can carry more than 33 a week; everything east of it too. Adding trucks anywhere else changes nothing. Max flow and min cut are a primal–dual pair, like Day 11's bakery and the rent for it: the flow model's dual is the cut.
The planted bug
day17/bug_units.py loads the contracts with one copy-paste slip. Run it, then find the slip.
import duckdb
import networkx as nx
con = duckdb.connect("northbound.duckdb", read_only=True)
G = nx.DiGraph()
for a, b, km, slots in con.sql("SELECT from_place, to_place, km, truck_slots_per_week FROM road_segments").fetchall():
G.add_edge(a, b, capacity=km)
print("trucks a week from Mississauga to Quebec City:", nx.maximum_flow_value(G, "Mississauga", "Quebec City"))
What happens, and how to spot it
trucks a week from Mississauga to Quebec City: 48
48 trucks: plausible, and wrong. The capacity is the road's km, not its truck slots. The minimum cut gives it away: with km as capacity, the bottleneck is the two short roads out of Mississauga (28 km to Toronto + 20 km to Brampton = 48). A bottleneck in the middle of the suburbs should make anyone suspicious. Day 9's lesson again: check the units, and check that the explanation makes sense, not just the number.
Mini-project: a winter storm closes the 401
A storm closes the 401 between Kingston and Cornwall for a week. Recompute the fastest route and the maximum flow from Mississauga to Quebec City, find the new bottleneck, and test which single carrier contract would gain most from 10 more trucks a week.
Solution
import duckdb
import networkx as nx
con = duckdb.connect("northbound.duckdb", read_only=True)
roads = con.sql("SELECT from_place, to_place, km, minutes, truck_slots_per_week FROM road_segments").fetchall()
START, END, CLOSED = "Mississauga", "Quebec City", {"Kingston", "Cornwall"}
def graphs(closed=False, extra=None):
roadmap, contracts = nx.Graph(), nx.DiGraph()
for a, b, km, minutes, slots in roads:
if closed and {a, b} == CLOSED:
continue
roadmap.add_edge(a, b, km=km, minutes=minutes)
contracts.add_edge(a, b, capacity=slots + (extra or {}).get((a, b), 0))
return roadmap, contracts
for closed in (False, True):
roadmap, contracts = graphs(closed)
path = nx.shortest_path(roadmap, START, END, weight="minutes")
print(f"{'storm' if closed else 'normal'}: fastest {nx.path_weight(roadmap, path, 'minutes')} min via "
f"{' - '.join(path)}; at most {nx.maximum_flow_value(contracts, START, END)} trucks a week")
# During the storm, where is the bottleneck, and which single contract would gain most from 10 more trucks?
_, contracts = graphs(True)
base, (reach, rest) = nx.minimum_cut(contracts, START, END)
print("storm bottleneck:", sorted((a, b, contracts.edges[a, b]["capacity"]) for a in reach for b in contracts.successors(a) if b in rest))
gains = []
for a, b in contracts.edges():
_, more = graphs(True, {(a, b): 10})
gains.append((nx.maximum_flow_value(more, START, END) - base, f"{a}->{b}"))
print("best single contracts to extend by 10 trucks:", sorted(gains, reverse=True)[:4])
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 fastest route detours through Ottawa: 639 minutes instead of 565.
- Capacity falls from 33 to 18 trucks a week: the storm removed the 401's 15.
- The new bottleneck is the two roads into Ottawa (12 + 6). But 10 more trucks on either adds only 2: as soon as one road into Ottawa widens, the next limit appears (Ottawa to Montreal and Gatineau to Montreal). To restore 33 trucks, Northbound needs several contracts at once, or a different route altogether (the Peterborough route, or rail).
The lesson of Day 13 in network form: relieving one bottleneck reveals the next. Always recompute the cut after a change.
Commit
git add .
git commit -m "Day 17: shortest paths, maximum flow, minimum cut"
git push
Then run the tests. tests/test_network.py checks Days 14–17: the transportation and single-sourcing costs, the Hungarian method against the LP, flow conservation, the shortest path and max flow = min cut. Add "day14", "day15", "day16" to the folders in conftest.py.
"""Module 2, Days 14-17: transportation, assignment, network flow, shortest paths and maximum flow."""
import networkx as nx
import numpy as np
import pyomo.environ as pyo
import pytest
from network import build_flow, load_chilled
from scipy.optimize import linear_sum_assignment
from store_assignment import build_assignment, chosen_dc
from transport import build_transport, load_network
TOL = 1e-6
@pytest.fixture(scope="module")
def network(con):
return load_network(con)
def test_transportation_known_answer_and_whole_pallets(network):
dcs, stores, lanes = network
m = build_transport(dcs, stores, lanes)
pyo.SolverFactory("highs").solve(m)
assert pyo.value(m.cost) == pytest.approx(39_089.81, abs=0.01)
for d in m.D:
assert sum(pyo.value(m.ship[d, s]) for s in m.S) <= dcs.pallets_per_week_capacity[d] + TOL
assert all(abs(pyo.value(v) - round(pyo.value(v))) < TOL for v in m.ship.values())
def test_single_sourcing_costs_at_least_the_split_plan(network):
dcs, stores, lanes = network
lp, mip = build_transport(dcs, stores, lanes), build_assignment(dcs, stores, lanes)
pyo.SolverFactory("highs").solve(lp)
pyo.SolverFactory("highs").solve(mip)
assert pyo.value(mip.cost) >= pyo.value(lp.cost) - TOL
assert pyo.value(mip.cost) == pytest.approx(41_492.76, abs=0.01)
plan = chosen_dc(mip)
assert all(not (stores.province[s] == "QC" and d == "DC-MIS") for s, d in plan.items())
def test_assignment_lp_matches_hungarian(con):
minutes = con.sql("SELECT * FROM driver_route_minutes").df().pivot(index="driver", columns="route", values="minutes")
rows, cols = linear_sum_assignment(minutes.to_numpy())
m = pyo.ConcreteModel()
m.x = pyo.Var(minutes.index, minutes.columns, bounds=(0, 1))
m.a = pyo.Constraint(minutes.index, rule=lambda m, d: sum(m.x[d, r] for r in minutes.columns) == 1)
m.b = pyo.Constraint(minutes.columns, rule=lambda m, r: sum(m.x[d, r] for d in minutes.index) == 1)
m.o = pyo.Objective(expr=sum(minutes.loc[d, r] * m.x[d, r] for d in minutes.index for r in minutes.columns))
pyo.SolverFactory("highs").solve(m)
assert pyo.value(m.o) == pytest.approx(minutes.to_numpy()[rows, cols].sum())
def test_chilled_flow_is_conserved_and_known(con):
nodes, arcs = load_chilled(con)
m = build_flow(nodes, arcs)
pyo.SolverFactory("highs").solve(m)
assert pyo.value(m.cost) == pytest.approx(18_203.64, abs=0.01)
shipped = sum(pyo.value(m.flow[i, j]) for i, j in m.A if nodes.kind[i] == "plant")
assert shipped == pytest.approx(nodes.demand_pallets.sum())
def test_shortest_path_and_max_flow(con):
roads = con.sql("SELECT * FROM road_segments").df()
G = nx.Graph()
D = nx.DiGraph()
for r in roads.itertuples():
G.add_edge(r.from_place, r.to_place, km=r.km)
D.add_edge(r.from_place, r.to_place, capacity=r.truck_slots_per_week)
assert nx.shortest_path_length(G, "Mississauga", "Quebec City", weight="km") == 858
flow = nx.maximum_flow_value(D, "Mississauga", "Quebec City")
cut, _ = nx.minimum_cut(D, "Mississauga", "Quebec City")
assert flow == cut == 33
31 passed
Day 17 checklist
- I can load a road network into networkx and find shortest paths by km and by minutes.
- I solved a shortest path as a min-cost flow and read distances from its duals.
- I reproduced the lane distances from road segments.
- I can solve a maximum flow as an LP and with networkx.
- I can find the bottleneck with a minimum cut, and know max flow equals min cut.
- I recomputed the cut after a change, and saw the next bottleneck appear.