39.1 Cluster first, route second
Split vehicle routing in two: first decide which stops share a vehicle (a packing problem), then the order within each group (a small TSP, solved exactly). Create day39/decompose.py:
"""Day 39: splitting big plans into smaller ones. Cluster-first route-second for the vans, and rolling
horizons for the 12-week bakery plan (Day 8).
Import it: from decompose import route_clusters, rolling_bakery, evaluate_bakery
"""
import numpy as np
import pyomo.environ as pyo
from planner import build, load_plan_data, solve
from routing import tour_km, tsp_exact
def route_clusters(clusters, km):
"""Route second: the shortest tour through each cluster, proven with CP-SAT (Day 36)."""
routes = []
for c in clusters:
nodes = [0] + list(c)
sub = np.array([[km[a][b] for b in nodes] for a in nodes])
tour, status, _ = tsp_exact(sub)
assert status == "OPTIMAL"
routes.append([nodes[i] for i in tour])
return routes
def rolling_bakery(con, lookahead, weeks=12, fix=("make", "sell", "keep")):
"""Plan weeks t .. t+lookahead-1, keep only week t's decisions, move on. Earlier weeks stay as decided:
the variables named in `fix` are fixed to the values already chosen."""
decided = {}
for t in range(1, weeks + 1):
horizon = min(t + lookahead - 1, weeks)
d = load_plan_data(con, weeks=horizon)
m = build(d)
for (name, p, w), value in decided.items():
if name in fix:
getattr(m, name)[p, w].fix(value)
solve(m)
for name in ("make", "sell", "keep"):
for p in m.P:
decided[name, p, t] = max(0.0, round(pyo.value(getattr(m, name)[p, t]), 9)) # no -1e-14
last = m
return decided, last
def evaluate_bakery(con, decided, weeks=12):
"""The real profit of a 12-week plan: the full model with every decision fixed."""
d = load_plan_data(con, weeks=weeks)
m = build(d)
for (name, p, w), value in decided.items():
getattr(m, name)[p, w].fix(value)
solve(m)
return pyo.value(m.profit)
Then day39/run_decomposition.py:
# ---------- 39.1 Cluster first, route second ----------
stops, ids, km, minutes = load_run(con)
racks = [int(stops.racks[s]) for s in ids]
rows = []
for name, clusters in [("sweep", sweep(stops, ids, racks, 18)), ("savings", savings(km, racks, 18)),
("OR-Tools (Day 36)", solve_cvrp(km, racks, [18] * 15, solutions=1000))]:
routed = route_clusters(clusters, km)
rows.append((name, len(clusters), round(total_km(clusters, km), 2), round(total_km(routed, km), 2)))
print(pd.DataFrame(rows, columns=["clusters_from", "vans", "km_as_found", "km_each_cluster_routed_optimally"])
.to_string(index=False))
clusters_from vans km_as_found km_each_cluster_routed_optimally
sweep 12 344.29 330.54
savings 10 266.93 266.93
OR-Tools (Day 36) 10 258.30 258.30
- Re-routing the sweep's clusters optimally saves 14 km, but they stay 72 km worse than OR-Tools: the clusters decide most of the cost.
- The savings and OR-Tools routes are already optimal within their clusters. Their difference is all in the grouping.
Decomposition makes each part easy, but the parts must be cut where the problem is loosely connected. Here, clustering and routing are tightly connected, so a joint method (OR-Tools, annealing) does better.
39.2 Rolling horizons: how far to look ahead
Day 8's 12-week bakery plan in one model is the benchmark. A rolling plan sees only lookahead weeks at a time: plan weeks to , keep week , move to . Everything already decided stays fixed (rolling_bakery fixes make, sell and keep for past weeks).
# ---------- 39.2 Rolling horizons ----------
d = load_plan_data(con, weeks=12)
full = build(d)
solve(full)
best = pyo.value(full.profit)
print(f"12 weeks in one model: ${best:,.2f}")
rows = []
for lookahead in (1, 2, 3, 4, 6, 12):
decided, _ = rolling_bakery(con, lookahead)
profit = evaluate_bakery(con, decided)
rows.append((lookahead, round(profit, 2), round(best - profit, 2) + 0.0))
print(pd.DataFrame(rows, columns=["weeks_seen_each_time", "profit_over_12_weeks", "lost_against_one_model"])
.to_string(index=False))
12 weeks in one model: $1,229,959.05
weeks_seen_each_time profit_over_12_weeks lost_against_one_model
1 1227461.02 2498.03
2 1229276.87 682.18
3 1229700.22 258.82
4 1229942.29 16.75
6 1229956.59 2.45
12 1229959.05 0.00
Seeing one week at a time loses $2,498 over 12 weeks; two weeks $682; four weeks only $17; six weeks $2. Beyond a few weeks, more lookahead buys almost nothing here, because what the bakery does now affects the next 2 to 4 weeks (shelf life up to 4 weeks, the Christmas peak). A good lookahead is a little longer than the effects of today's decisions.
39.3 Why short horizons lose
# ---------- 39.3 Why short horizons lose: the end of the window ----------
decided, _ = rolling_bakery(con, 1)
stock = {t: sum(v for (name, p, w), v in decided.items() if name == "keep" and w == t) for t in range(1, 13)}
plan = {t: sum(pyo.value(full.keep[p, t]) for p in full.P) for t in range(1, 13)}
print("batches kept at the end of each week (one week seen / one model):")
print(" ", " ".join(f"w{t}:{stock[t]:.0f}/{plan[t]:.0f}" for t in range(1, 13)))
batches kept at the end of each week (one week seen / one model):
w1:0/62 w2:0/120 w3:0/140 w4:0/0 w5:0/0 w6:0/9 w7:0/26 w8:0/14 w9:0/7 w10:0/6 w11:0/25 w12:0/0
With one week in view, the plan never stores anything: stock at the end of the window is worth nothing to the model. The full plan builds up 140 batches by the end of week 3, ahead of the Christmas peak. This is the end-of-horizon effect. Fixes: look further ahead, or give leftover stock a value at the end of the window.
Decision it supports: how far ahead to plan, and how often to re-plan.
Other decisions you can support the same way: production planning every week · supply plans every month · rosters every period · energy dispatch every hour.
State
What a rolling plan carries from one period to the next is its state: stock on hand, who worked last Sunday (Day 32), nights already worked this month (Day 35), trucks already on the road. Get the state wrong and the next plan is built on a world that doesn't exist.
The planted bug
day39/bug_history.py re-plans "everything up to the look-ahead each week, to stay flexible". Run it.
decided, last = rolling_bakery(con, 2, fix=()) # nothing already decided is kept
try:
print(f"profit: ${evaluate_bakery(con, decided):,.2f}")
except RuntimeError as error:
print("the 12-week plan, checked:", error)
What happens, and why
the 12-week plan, checked: no optimal plan: infeasible
5 product-weeks sell more than they have, e.g.
week 3 BK-27: sells 47.20 batches, had 17.67 in store + made 18.27
week 7 BK-18: sells 27.90 batches, had 2.32 in store + made 23.05
week 8 BK-18: sells 27.50 batches, had 2.54 in store + made 17.32
week 9 BK-27: sells 25.40 batches, had 0.00 in store + made 24.64
Nothing already decided is kept, so each week's plan re-decides the past. Week 7's plan assumes pastries (BK-18) were stored in week 6 that the week-6 plan didn't keep. Put together, the 12 weeks are infeasible: in 5 product-weeks the bakery sells more than it has. The past is not a decision. Fix what has happened, and plan only what hasn't.
Mini-project: three people off sick
December's roster (Day 35) is published. On the Sunday before week 2, three people report sick for weeks 2 and 3: E07 (a forklift driver), E19 and E23. Week 1 has been worked. Re-plan weeks 2 to 4 week by week, (a) freely, (b) charging $25 for every shift that differs from the published roster. Compare pay and how many shifts change.
Solution
Day 35's build_four_weeks takes two more options for this: unavailable (employee and week) and previous with change_cost (a penalty for each shift added or removed against an earlier roster). rolling can start at any week, with the nights worked so far.
"""Day 39 mini-project: December's roster is published (Day 35). On the Sunday before week 2, three people
report sick for weeks 2 and 3: E07 (forklift), E19 and E23 (pickers). Re-plan weeks 2-4, week by week,
keeping week 1 as worked. Compare a free re-plan with one that pays $25 for every shift it changes.
Run from the repository root (after day06/load_tables.py): python day39/mini_project_sick.py (about 1.5 minutes)
"""
import sys
import duckdb
import pandas as pd
for folder in ("day32", "day35"):
sys.path.insert(0, folder)
from four_weeks import rolling
from roster import load_roster_data
pd.set_option("display.width", 160)
con = duckdb.connect("northbound.duckdb", read_only=True)
staff, shifts, coverage, rules, last_sunday = load_roster_data(con)
requests = con.sql("SELECT * FROM staff_requests").df()
december = {"peak": {4: 0.10}}
published, roster = rolling(staff, shifts, coverage, rules, last_sunday, requests=requests, **december)
print(f"published December roster: ${published['pay']:,.2f}, {published['agency_shifts']} agency shifts")
week1 = roster[roster.week == 1]
sunday = week1[week1.day == "Sun"].set_index("employee_id")["shift"].to_dict()
after_week1 = {e: sunday.get(e, "off") for e in staff.index}
nights = week1[week1["shift"] == "N"].groupby("employee_id").size().to_dict()
pay_week1 = rolling(staff, shifts, coverage, rules, last_sunday, weeks=1, requests=requests, **december)[0]["pay"]
sick = {(e, w) for e in ("E07", "E19", "E23") for w in (2, 3)}
published_later = roster[roster.week >= 2]
lost = published_later[[(e, w) in sick for e, w in zip(published_later.employee_id, published_later.week)]]
print(f"shifts the sick staff were due to work in weeks 2-3: {len(lost)}")
rows = []
for name, cost in [("free re-plan", 0.0), ("re-plan, $25 a changed shift", 25.0)]:
out, new = rolling(staff, shifts, coverage, rules, after_week1, first=2, nights=nights, unavailable=sick,
previous=roster, change_cost=cost, **december)
rows.append((name, round(pay_week1 + out["pay"], 2), out["agency_shifts"], out["changes"], out["most_nights"]))
print(pd.DataFrame(rows, columns=["plan", "december_pay", "agency_shifts_weeks_2_4", "shifts_changed", "most_nights"])
.to_string(index=False))
published December roster: $125,861.40, 8 agency shifts
shifts the sick staff were due to work in weeks 2-3: 30
plan december_pay agency_shifts_weeks_2_4 shifts_changed most_nights
free re-plan 132179.96 8 682 8
re-plan, $25 a changed shift 132219.96 8 62 8
- Covering 30 lost shifts raises December's pay by about $6,300 (sick full-timers are still paid their guaranteed shifts in this model, and their shifts go to part-timers and overtime).
- A free re-plan changes 682 shifts: the solver doesn't care which of many equally cheap rosters it returns, so most of the published roster changes.
- Charging $25 a change keeps all but 62 shifts as published, for $40 more. That is the price of a stable plan: almost nothing.
Memo to the DC manager: "When someone falls sick, re-plan with a change penalty. Covering this week's three absences costs about $6,300 either way; with the penalty, only 62 shifts change instead of 682, for $40. Publish only the changed shifts."
Commit
git add .
git commit -m "Day 39: decomposition and rolling horizons"
git push
Day 39 checklist
- I can split routing into clustering and routing, and say when that loses.
- I can run a rolling horizon and measure the cost of a short lookahead.
- I can explain the end-of-horizon effect and how to soften it.
- I carry the state correctly from one period to the next.
- I can re-plan with a penalty for changes, to keep plans stable.