36.1 The stops
delivery_stops lists the depot (the bakery dock beside DC-MTL), the stores and the cafés, with their racks; delivery_matrix the road kilometres and minutes between every pair (straight-line distance × 1.35 for the road network, at 30 km/h in the early morning). Create day36/routing.py:
"""Day 36: the morning bread run. Tours and routes with simple heuristics, OR-Tools routing and CP-SAT.
Import it: from routing import load_run, tour_km, nearest_neighbour, two_opt, tsp_exact, sweep, savings, solve_cvrp
"""
import math
from ortools.constraint_solver import pywrapcp, routing_enums_pb2
from ortools.sat.python import cp_model
def load_run(con):
stops = con.sql("SELECT * FROM delivery_stops").df().set_index("stop_id")
ids = list(stops.index) # DEPOT first
mat = con.sql("SELECT * FROM delivery_matrix").df()
km = mat.pivot(index="from_stop", columns="to_stop", values="km").loc[ids, ids].to_numpy()
minutes = mat.pivot(index="from_stop", columns="to_stop", values="minutes").loc[ids, ids].to_numpy()
return stops, ids, km, minutes
def tour_km(tour, km):
"""Length of a closed tour or route that starts and ends at the depot (node 0)."""
path = [0] + [n for n in tour if n != 0] + [0]
return float(sum(km[a][b] for a, b in zip(path, path[1:])))
def nearest_neighbour(km, nodes=None):
nodes = set(range(1, len(km))) if nodes is None else set(nodes)
tour, here = [], 0
while nodes:
here = min(nodes, key=lambda n: (km[here][n], n))
tour.append(here)
nodes.remove(here)
return tour
def two_opt(tour, km):
"""Reverse any piece of the tour that makes it shorter, until no reversal helps."""
best = [0] + tour + [0]
improved = True
while improved:
improved = False
for i in range(1, len(best) - 2):
for j in range(i + 1, len(best) - 1):
a, b, c, d = best[i - 1], best[i], best[j], best[j + 1]
if km[a][c] + km[b][d] < km[a][b] + km[c][d] - 1e-9:
best[i:j + 1] = reversed(best[i:j + 1])
improved = True
return best[1:-1]
def tsp_exact(km, seconds=60):
"""The shortest tour, proven, with CP-SAT's circuit constraint (distances in metres)."""
n = len(km)
m = cp_model.CpModel()
arcs, x = [], {}
for i in range(n):
for j in range(n):
if i != j:
x[i, j] = m.new_bool_var(f"x_{i}_{j}")
arcs.append((i, j, x[i, j]))
m.add_circuit(arcs)
m.minimize(sum(int(round(1000 * km[i][j])) * v for (i, j), v in x.items()))
s = cp_model.CpSolver()
s.parameters.num_workers = 8
s.parameters.interleave_search = True
s.parameters.max_time_in_seconds = seconds
status = s.solve(m)
nxt = {i: j for (i, j), v in x.items() if s.value(v)}
tour, here = [], nxt[0]
while here != 0:
tour.append(here)
here = nxt[here]
return tour, s.status_name(status), s.best_objective_bound / 1000
def sweep(stops, ids, demand, capacity):
"""The dispatcher's method: sort customers by compass angle around the depot, fill a van, start the next."""
lat0, lon0 = stops.latitude[ids[0]], stops.longitude[ids[0]]
angle = {n: math.atan2(stops.latitude[ids[n]] - lat0, (stops.longitude[ids[n]] - lon0) * math.cos(math.radians(lat0)))
for n in range(1, len(ids))}
routes, load = [[]], 0
for n in sorted(angle, key=angle.get):
if load + demand[n] > capacity:
routes.append([])
load = 0
routes[-1].append(n)
load += demand[n]
return routes
def savings(km, demand, capacity):
"""Clarke and Wright (1964): start with one route per customer, then merge the two routes whose
joining saves the most distance (km[0,i] + km[0,j] - km[i,j]), as long as the van has room."""
n = len(km)
route_of = {i: [i] for i in range(1, n)}
load = {id(r): demand[r[0]] for r in route_of.values()}
pairs = sorted(((km[0][i] + km[0][j] - km[i][j], i, j) for i in range(1, n) for j in range(i + 1, n)), reverse=True)
for save, i, j in pairs:
if save <= 0:
break
ri, rj = route_of[i], route_of[j]
if ri is rj or load[id(ri)] + load[id(rj)] > capacity:
continue
if ri[-1] != i: # join only at route ends: [... i] + [j ...]
ri.reverse()
if rj[0] != j:
rj.reverse()
if ri[-1] != i or rj[0] != j:
continue # i or j is inside its route: can't join there
merged = ri + rj
load[id(merged)] = load.pop(id(ri)) + load.pop(id(rj))
for k in merged:
route_of[k] = merged
unique = {id(r): r for r in route_of.values()}
return sorted(unique.values(), key=lambda r: r[0])
def solve_cvrp(km, demand, capacities, solutions=200, fixed_cost=None, with_vehicle=False):
"""OR-Tools routing: vehicles with capacities; minimize km (plus a fixed cost per vehicle used, if given).
Guided local search stopped after a number of improving solutions, so every run gives the same routes."""
n = len(km)
manager = pywrapcp.RoutingIndexManager(n, len(capacities), 0)
model = pywrapcp.RoutingModel(manager)
metres = [[int(round(1000 * km[i][j])) for j in range(n)] for i in range(n)]
def distance(from_index, to_index):
return metres[manager.IndexToNode(from_index)][manager.IndexToNode(to_index)]
transit = model.RegisterTransitCallback(distance)
model.SetArcCostEvaluatorOfAllVehicles(transit)
load = model.RegisterUnaryTransitCallback(lambda index: int(demand[manager.IndexToNode(index)]))
model.AddDimensionWithVehicleCapacity(load, 0, list(capacities), True, "racks")
if fixed_cost is not None:
model.SetFixedCostOfAllVehicles(int(fixed_cost))
params = pywrapcp.DefaultRoutingSearchParameters()
params.first_solution_strategy = routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC
params.local_search_metaheuristic = routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH
params.solution_limit = solutions
solution = model.SolveWithParameters(params)
routes = []
for v in range(len(capacities)):
index, route = model.Start(v), []
while not model.IsEnd(index):
node = manager.IndexToNode(index)
if node != 0:
route.append(node)
index = solution.Value(model.NextVar(index))
if route:
routes.append((v, route) if with_vehicle else route)
return routes
36.2 One tour through every stop (TSP)
Suppose one vehicle could carry everything: what is the shortest tour from the dock through all 34 stops and back? Create day36/run_routes.py:
# ---------- 36.1 The stops ----------
print(stops.groupby("kind").agg(stops=("name", "size"), racks=("racks", "sum")).to_string())
print(f"farthest pair {km.max():.1f} km; a van takes {van} racks")
# ---------- 36.2 One tour through every stop (TSP) ----------
nn = nearest_neighbour(km)
better = two_opt(nn, km)
exact, status, bound = tsp_exact(km)
ortools = solve_cvrp(km, [0] * len(ids), [10 ** 6])[0]
for name, tour in [("nearest neighbour", nn), ("nearest neighbour + 2-opt", better), ("OR-Tools routing", ortools),
("CP-SAT circuit", exact)]:
print(f"{name:<26} {tour_km(tour, km):7.2f} km")
print(f"CP-SAT: {status}, no tour shorter than {bound:.2f} km")
stops racks
kind
cafe 24 59
depot 1 0
store 10 102
farthest pair 33.8 km; a van takes 18 racks
nearest neighbour 147.68 km
nearest neighbour + 2-opt 131.45 km
OR-Tools routing 128.15 km
CP-SAT circuit 128.15 km
CP-SAT: OPTIMAL, no tour shorter than 128.15 km
- Nearest neighbour (always drive to the closest stop not yet visited) is quick and 15% too long: the last stops are left scattered far apart.
- 2-opt (reverse any piece of the tour that makes it shorter) brings it within 2.6% of the best.
- OR-Tools' routing solver and CP-SAT's
add_circuitboth find 128.15 km, and CP-SAT proves nothing shorter exists.
The TSP is the textbook hard problem, but at this size exact methods are quick. They stop being quick with hundreds of stops, or with capacities and time windows. That is where heuristics earn their keep.
36.3 Routes for vans (CVRP)
A van carries 18 racks, so the run needs at least vans.
# ---------- 36.3 Routes for vans (CVRP) ----------
print(f"{sum(racks)} racks / {van} per van: at least {math.ceil(sum(racks) / van)} vans")
results = {}
for name, routes in [("sweep (the dispatcher's method)", sweep(stops, ids, racks, van)),
("savings (Clarke and Wright)", savings(km, racks, van)),
("OR-Tools, guided local search", solve_cvrp(km, racks, [van] * 15, solutions=1000))]:
results[name] = routes
loads = [sum(racks[n] for n in r) for r in routes]
print(f"{name:<32} {len(routes)} vans, {sum(tour_km(r, km) for r in routes):7.2f} km, fullest {max(loads)}, emptiest {min(loads)}")
161 racks / 18 per van: at least 9 vans
sweep (the dispatcher's method) 12 vans, 344.29 km, fullest 18, emptiest 7
savings (Clarke and Wright) 10 vans, 266.93 km, fullest 18, emptiest 12
OR-Tools, guided local search 10 vans, 258.30 km, fullest 18, emptiest 7
- Sweep (the dispatcher's method: sort stops by compass direction around the depot, fill a van, start the next) needs 12 vans and 344 km.
- Savings (Clarke and Wright, 1964): start with one van per stop, then repeatedly join the two routes whose joining saves the most kilometres, while the van has room. 10 vans, 267 km. A method from 1964, in 30 lines, is a strong baseline.
- OR-Tools with guided local search: 10 vans, 258 km.
None of these proves anything about the best possible plan: 9 vans would be enough by capacity alone, but no method found a 9-van plan, and none can say whether one exists.
36.4 More search, better routes
OR-Tools' routing solver starts from a quick first solution (PATH_CHEAPEST_ARC: extend each route to the nearest stop), then improves it with guided local search: moves stops between and within routes, and penalizes features of the plan it keeps returning to, to escape local optima. It never proves optimality; it stops when told.
# ---------- 36.4 More search, better routes ----------
for n in (50, 200, 1000):
routes = solve_cvrp(km, racks, [van] * 15, solutions=n)
print(f"OR-Tools stopped after {n:>4} solutions: {len(routes)} vans, {sum(tour_km(r, km) for r in routes):.2f} km")
OR-Tools stopped after 50 solutions: 10 vans, 284.61 km
OR-Tools stopped after 200 solutions: 10 vans, 272.11 km
OR-Tools stopped after 1000 solutions: 10 vans, 258.30 km
After 200 solutions OR-Tools is still behind savings; after 1,000 it is 3% ahead. We stop after a number of solutions, not seconds, so every run gives the same routes. A time limit gives better routes on faster computers and different ones on each run.

The OR-Tools routing pattern, which every routing model follows:
- A
RoutingIndexManager(stops, vehicles, depot) and aRoutingModel. - Callbacks that give the cost or time between two indexes: always convert with
manager.IndexToNode. - Dimensions for quantities that accumulate along a route: racks (capacity), time (Day 37).
- Search parameters: first solution strategy, metaheuristic, limit.
Decision it supports: which vehicle visits which customers, in what order.
Other decisions you can support the same way: parcel delivery · waste collection · home-care visits · school buses · field technicians.
The planted bug
day36/bug_index.py: a colleague's distance callback crashed with an IndexError, so they "fixed" it. Run it.
metres = [[int(round(1000 * km[i][j])) for j in range(len(ids))] for i in range(len(ids))]
cost = model.RegisterTransitCallback(lambda i, j: metres[i % len(ids)][j % len(ids)]) # i and j: the stops
model.SetArcCostEvaluatorOfAllVehicles(cost)
load = model.RegisterUnaryTransitCallback(lambda i: racks[manager.IndexToNode(i)])
model.AddDimensionWithVehicleCapacity(load, 0, [18] * vans, True, "racks")
What happens, and why
the solver's objective: 131.67 km
10 vans; the routes really drive 310.05 km
The solver thinks its routes drive 131.67 km; they really drive 310.05 km. OR-Tools passes indexes to callbacks, not stop numbers: each vehicle has its own start and end index, numbered after the stops. metres[i][j] crashed on those, and % len(ids) hid the crash by mapping them to the wrong stops. The fix is manager.IndexToNode(i). A crash is a gift; never silence it without understanding it. The independent check (tour_km on the routes) shows the gap at once.
Mini-project: vans or trucks?
The bakery has 6 vans (18 racks, $90 a day, $0.40 a km) and 3 trucks (36 racks, $150 a day, $0.65 a km). Ignoring delivery windows for now, what would the run cost with vans only, with trucks only (any number), and with today's fleet? Is the plan with the fewest kilometres the cheapest?
Solution
"""Day 36 mini-project: vans or trucks? Ignoring time windows for now, what does the morning run cost
with vans only, with trucks only (unlimited numbers), and with today's fleet of 6 vans and 3 trucks?
Run from the repository root (after day06/load_tables.py): python day36/mini_project_fleet.py (about 1 minute)
"""
import sys
import duckdb
import pandas as pd
sys.path.insert(0, "day36")
from routing import load_run, solve_cvrp, tour_km
con = duckdb.connect("northbound.duckdb", read_only=True)
stops, ids, km, minutes = load_run(con)
racks = [int(stops.racks[s]) for s in ids]
fleet = con.sql("SELECT * FROM delivery_fleet").df().set_index("vehicle_type")
rows = []
for name, types in [("vans only", ["van"] * 15), ("trucks only", ["truck"] * 8),
("6 vans + 3 trucks, shortest km", ["van"] * 6 + ["truck"] * 3)]:
found = solve_cvrp(km, racks, [int(fleet.racks[t]) for t in types], solutions=1000, with_vehicle=True)
used = [types[v] for v, _ in found]
routes = [r for _, r in found]
day = sum(fleet.cost_per_day[t] for t in used)
drive = sum(fleet.cost_per_km[t] * tour_km(r, km) for t, r in zip(used, routes))
rows.append((name, used.count("van"), used.count("truck"), round(sum(tour_km(r, km) for r in routes), 2),
day, round(drive, 2), round(day + drive, 2)))
print(pd.DataFrame(rows, columns=["fleet", "vans", "trucks", "km", "day_costs", "km_costs", "total"]).to_string(index=False))
fleet vans trucks km day_costs km_costs total
vans only 10 0 258.30 900 103.32 1003.32
trucks only 0 5 170.10 750 110.56 860.56
6 vans + 3 trucks, shortest km 4 3 184.19 810 107.86 917.86
- Trucks only is cheapest ($860.56 a day): 5 trucks, 170 km. A truck costs 1.67 times a van but carries twice as much.
- Vans only costs $1,003: 10 day charges.
- The fewest-kilometres plan with today's fleet costs $917.86, more than trucks only: minimizing kilometres is not minimizing cost when vehicles have day charges. Day 37 puts the costs into the objective.
- Before buying trucks: the windows and downtown streets of Day 37 change this answer.
Commit
git add .
git commit -m "Day 36: TSP and CVRP"
git push
Day 36 checklist
- I can build tours with nearest neighbour and 2-opt, and prove a short tour optimal with
add_circuit. - I can implement the savings method.
- I can set up an OR-Tools routing model: manager, callbacks, a capacity dimension, search parameters.
- I stop the search by solution count when I need repeatable routes.
- I always convert indexes with
IndexToNode, and check routes independently. - I know shortest is not cheapest when vehicles have fixed costs.