40.1 The brief
- Routes: each day's racks are the usual racks times the day's factor (
delivery_days: 0.90 on Monday to 1.20 on Friday). Today's fleet, windows and downtown rule (Day 37). - Drivers (
delivery_drivers): 7 full-timers (4 or 5 days a week), 4 part-timers (at most 3 days); 4 hold a truck licence. A driver's day is the route plus 30 minutes of checks, paid at least 4 hours. - Warehouse: Day 33's roster with the union's proposal (at most 2 nights, at most 1 weekend day).
Create day40/next_week.py:
"""Day 40 capstone: next week's bread run, Monday to Saturday, and the drivers who drive it.
Import it: from next_week import day_stops, route_week, build_driver_roster, solve_drivers
"""
import pandas as pd
from ortools.sat.python import cp_model
from vrptw import simulate, solve_vrptw
def day_stops(stops, factor):
"""That day's racks: the usual racks times the day's factor, at least one rack per stop."""
s = stops.copy()
s["racks"] = [0 if kind == "depot" else max(1, round(r * factor)) for kind, r in zip(s.kind, s.racks)]
return s
def route_week(stops, ids, km, minutes, fleet, days, **kw):
"""Route every day (Day 37's model). Returns one row per route, and one summary row per day."""
routes, summary = [], []
for day, factor in days:
s = day_stops(stops, factor)
plan = solve_vrptw(s, ids, km, minutes, fleet, **kw)
cost, total_km, problems = simulate(plan, s, ids, km, minutes, fleet, window_shift=kw.get("window_shift", 0))
for k, r in enumerate(plan, start=1):
routes.append((day, f"{day}-{k}", r["vehicle"], r["type"], r["leaves"], r["back"], len(r["stops"])))
summary.append((day, int(s.racks.sum()), len(plan), sum(r["type"] == "truck" for r in plan), round(total_km, 2),
cost, len(problems)))
return (pd.DataFrame(routes, columns=["day", "route", "vehicle", "type", "leaves", "back", "stops"]),
pd.DataFrame(summary, columns=["day", "racks", "vehicles", "trucks", "km", "fleet_cost", "problems"]))
def build_driver_roster(routes, drivers, rules):
"""drive[d, route] = 1 if driver d drives that route. Every route gets one driver with the right licence;
one route a day; full-timers work 4 or 5 days, part-timers at most 3. A driver's day is the route plus 30
minutes of checks, paid at least 4 hours. Minimize the week's driver pay (cents)."""
m = cp_model.CpModel()
extra, minimum = rules["pre_and_post_trip_minutes"], 60 * rules["min_paid_hours_per_day"]
drive, pay = {}, []
for d in drivers.index:
for r in routes.itertuples():
if r.type == "truck" and not drivers.truck_licence[d]:
continue
drive[d, r.route] = x = m.new_bool_var(f"{d}_{r.route}")
paid_minutes = max(minimum, r.back - r.leaves + extra)
pay.append(int(round(100 * drivers.hourly_wage[d] * paid_minutes / 60)) * x)
for r in routes.itertuples():
m.add_exactly_one(drive[d, r.route] for d in drivers.index if (d, r.route) in drive)
for d in drivers.index:
days = []
for day, g in routes.groupby("day", sort=False):
works = m.new_bool_var(f"{d}_works_{day}")
m.add(sum(drive[d, r] for r in g.route if (d, r) in drive) == works) # at most one route a day
days.append(works)
if drivers.contract[d] == "full-time":
m.add(sum(days) >= int(rules["full_time_min_days"]))
m.add(sum(days) <= int(rules["full_time_max_days"]))
else:
m.add(sum(days) <= int(rules["part_time_max_days"]))
m.minimize(sum(pay))
return m, drive
def solve_drivers(m, drive, routes):
s = cp_model.CpSolver()
s.parameters.num_workers = 8
s.parameters.interleave_search = True
s.parameters.max_deterministic_time = 20
status = s.solve(m)
if status not in (cp_model.OPTIMAL, cp_model.FEASIBLE):
return s.status_name(status), None, None
who = {r: d for (d, r), x in drive.items() if s.value(x)}
table = routes.assign(driver=routes.route.map(who))
return s.status_name(status), round(s.objective_value / 100, 2), table
The plan is built in sequence: routes first, then drivers for the routes. That's a decomposition (Day 39): a cheaper route plan could need more drivers, and the sequence can't see that. Here it's safe because driver pay depends mostly on how many routes there are, which the route model already minimizes through the day charges.
Then day40/run_capstone.py:
# ---------- 40.1 Routes for every day ----------
routes, summary = route_week(stops, ids, km, minutes, fleet, days)
print(summary.to_string(index=False))
print(f"week: {summary.vehicles.sum()} vehicle-days ({summary.trucks.sum()} truck-days), {summary.km.sum():,.2f} km, "
f"fleet ${summary.fleet_cost.sum():,.2f}")
day racks vehicles trucks km fleet_cost problems
Mon 151 6 3 218.25 831.51 0
Tue 156 6 3 232.49 837.94 0
Wed 161 7 2 229.91 864.50 0
Thu 166 7 3 232.41 923.84 0
Fri 190 8 3 238.31 1024.26 0
Sat 181 8 3 238.97 1016.81 0
week: 42 vehicle-days (17 truck-days), 1,390.34 km, fleet $5,498.86
Six to eight vehicles a day, every window kept every day; $5,498.86 of fleet costs for the week. The trucks run 17 of 18 possible truck-days: trucks are the cheapest way to carry racks (Day 36).
40.2 Who drives: the drivers' roster
# ---------- 40.2 Who drives: the drivers' roster ----------
print(drivers.groupby(["contract", "truck_licence"]).size().rename("drivers").to_string())
m, drive = build_driver_roster(routes, drivers, rules)
status, driver_pay, table = solve_drivers(m, drive, routes)
print(f"drivers: {status}, ${driver_pay:,.2f} for the week")
grid = table.assign(slot=table.vehicle + " " + table.leaves.map(hhmm) + "-" + table.back.map(hhmm))
grid = grid.pivot(index="driver", columns="day", values="slot").reindex(index=drivers.index,
columns=[d for d, _ in days]).fillna("off")
print(grid.to_string())
print("days worked:", grid.ne("off").sum(axis=1).to_dict())
contract truck_licence
full-time 0 4
1 3
part-time 0 3
1 1
drivers: OPTIMAL, $4,515.40 for the week
day Mon Tue Wed Thu Fri Sat
driver_id
DR01 off truck-1 04:19-07:41 truck-1 04:40-08:00 truck-3 05:15-07:37 truck-2 05:28-07:40 truck-3 05:28-07:40
DR02 truck-1 04:55-07:41 truck-2 05:05-07:40 off truck-2 04:46-06:27 truck-1 04:53-07:09 truck-2 04:41-07:41
DR03 truck-2 04:41-07:50 off off truck-1 04:59-07:50 truck-3 04:52-08:00 truck-1 05:35-07:14
DR04 van-3 05:29-08:00 van-4 04:58-07:17 off van-4 04:58-07:17 van-5 06:30-07:30 van-5 06:06-06:59
DR05 van-1 04:27-07:10 off van-3 05:38-07:44 van-5 06:34-07:34 van-3 05:56-07:49 off
DR06 off van-2 04:50-07:31 van-1 04:51-06:59 van-2 05:18-07:49 van-6 05:35-06:46 van-6 05:27-07:04
DR07 off van-5 05:10-07:06 van-4 05:21-06:30 van-6 04:41-06:44 van-1 04:59-06:30 van-1 06:01-06:59
DR08 truck-3 05:28-07:30 truck-3 05:19-07:12 truck-2 05:18-07:40 off off off
DR09 van-2 05:28-06:35 off van-5 05:19-07:37 off off van-3 04:43-07:07
DR10 off off van-6 05:04-06:27 off van-2 05:58-07:50 van-2 04:50-07:13
DR11 off off off off off off
days worked: {'DR01': 5, 'DR02': 5, 'DR03': 4, 'DR04': 5, 'DR05': 4, 'DR06': 5, 'DR07': 5, 'DR08': 3, 'DR09': 3, 'DR10': 3, 'DR11': 0}
- $4,515.40 of driver pay, proven optimal.
- The truck routes set the pace: 17 truck routes need the 4 truck licences almost every day (DR01 and DR02 drive five days, DR08 three).
- DR11, the most expensive part-timer, isn't needed this week.
40.3 The warehouse; 40.4 the budget and a what-if
# ---------- 40.3 The warehouse roster for the same week ----------
staff, shifts, coverage, wrules, last_sunday = load_roster_data(con)
requests = con.sql("SELECT * FROM staff_requests").df()
warehouse = plan_week(staff, shifts, coverage, wrules, last_sunday, requests, max_nights=2, max_weekend_days=1)
print(f"warehouse (Day 33, union rules): {warehouse['status']}, ${warehouse['pay']:,.2f}, "
f"{warehouse['broken']} requests broken")
# ---------- 40.4 The week's budget, and one what-if ----------
budget = {"delivery fleet": summary.fleet_cost.sum(), "delivery drivers": driver_pay, "warehouse staff": warehouse["pay"]}
for k, v in budget.items():
print(f"{k:<18} ${v:>11,.2f}")
print(f"{'total':<18} ${sum(budget.values()):>11,.2f}")
later_routes, later = route_week(stops, ids, km, minutes, fleet, days, window_shift=30)
m2, drive2 = build_driver_roster(later_routes, drivers, rules)
status2, pay2, _ = solve_drivers(m2, drive2, later_routes)
print(f"if cafes took deliveries 30 minutes later: {later.vehicles.sum()} vehicle-days, fleet ${later.fleet_cost.sum():,.2f}, "
f"drivers ${pay2:,.2f} ({status2}): saves ${summary.fleet_cost.sum() + driver_pay - later.fleet_cost.sum() - pay2:,.2f} a week")
warehouse (Day 33, union rules): OPTIMAL, $28,896.88, 2 requests broken
delivery fleet $ 5,498.86
delivery drivers $ 4,515.40
warehouse staff $ 28,896.88
total $ 38,911.14
if cafes took deliveries 30 minutes later: 41 vehicle-days, fleet $5,462.44, drivers $4,411.52 (OPTIMAL): saves $140.30 a week
The week's delivery and warehouse labour cost $38,911.14. If cafés took deliveries 30 minutes later (Day 37), one vehicle-day fewer and shorter driver days would save $140 a week (about $7,300 a year).
40.5 The memo
A model memo
To: the Operations Director. Re: next week's plan, and five decisions from Module 4.
Next week. Delivery routes for Monday to Saturday, the drivers' roster and the warehouse roster are attached. Every café and store window is met, every labour rule holds, and the union's warehouse proposal is applied. Cost: fleet $5,499, drivers $4,515, warehouse staff $28,897; total $38,911.
Five decisions:
- Start the bakery's night run at 21:30, not 21:00 (Day 34). Everything is still packed by 03:43, before the vans load at 04:00. Starting at 22:00 would push dispatch towards 05:00, which costs about $61 a day on the road (Day 37).
- Ask the cafés for 30 minutes more on their delivery windows (Days 37, 40): about $140 a week with the current fleet.
- Certify two pickers as forklift drivers ($3,600 once, Day 35). It makes every-other-weekend off possible, even in peak weeks.
- Re-plan rosters with a change penalty when people are absent (Day 39): the same cost, a tenth of the changes.
- Plan the bakery four weeks ahead, re-planning weekly (Day 39): one-week plans lose about $2,500 a quarter by never building stock before peaks.
How sure. The drivers' roster is proven optimal for these routes. The routes come from a heuristic search (multi-start, fixed limits): repeatable, not proven; differences under about $5 a day between options are noise (Day 37). Labour rules follow Ontario's general hours-of-work rules as modelled on Day 32; they should be confirmed for our agreements.
Not in the model. Traffic and weather on the day; driver preferences and seniority; sick days (re-plan as on Day 39).
Module 4 wrap-up
| Day | Idea | Northbound decision |
|---|---|---|
| 31 | CP-SAT, global constraints | Driver assignment with depot rules |
| 32 | Coverage and labour rules | A legal warehouse week |
| 33 | Soft constraints, fairness | Requests and the union's proposal |
| 34 | Interval variables, job shop | Tonight's bakery run |
| 35 | Multi-week rosters | December, and two new forklift drivers |
| 36 | TSP, CVRP | Van routes |
| 37 | Time windows, mixed fleets | The real morning run |
| 38 | Local search, annealing | Better routes; Christmas trailers |
| 39 | Decomposition, rolling horizons | Lookahead; re-planning for sickness |
| 40 | Putting it together | Next week's routes and rosters |
Commit and tag
git add .
git commit -m "Day 40: capstone, next week's routes and rosters"
git tag v4.0-module4
git push --tags
Then run the tests: tests/test_heuristics_and_plans.py checks Days 38–40 (legal heuristic routes, 15 Christmas trailers, rolling horizons and the infeasible no-state plan, the drivers' rules on a small example). Add "day38", "day39", "day40" to the folders in conftest.py.
"""Module 4, Days 38-40: heuristics, rolling horizons and the drivers' roster."""
import pandas as pd
import pytest
from decompose import evaluate_bakery, rolling_bakery
from metaheuristics import anneal_packing, local_search, simulated_annealing, total_km
from next_week import build_driver_roster, solve_drivers
from packing import first_fit_decreasing
from routing import load_run, savings, sweep
def test_local_search_and_annealing_keep_routes_legal(con):
stops, ids, km, minutes = load_run(con)
racks = [int(stops.racks[s]) for s in ids]
start = sweep(stops, ids, racks, 18)
improved, cost = local_search(start, km, racks, 18)
assert cost < total_km(start, km)
routes, k = simulated_annealing(savings(km, racks, 18), km, racks, 18, seed=0, steps=20_000)
for r in (improved, routes):
assert sorted(n for x in r for n in x) == list(range(1, len(ids)))
assert all(sum(racks[n] for n in x) <= 18 for x in r)
def test_annealing_loads_christmas_on_15_trailers(con):
o = con.sql("SELECT * FROM christmas_orders").df().set_index("order_id")
pallets, kg = o.pallets.to_dict(), o.weight_kg.to_dict()
ffd = first_fit_decreasing(pallets, 26, kg, 16000)
start = {x: (k if k < 15 else 0) for k, (_, _, on) in enumerate(ffd) for x in on}
put, overflow, _ = anneal_packing(pallets, kg, 15, start, seed=0)
assert overflow == 0
for k in range(15):
assert sum(pallets[x] for x in put if put[x] == k) <= 26 and sum(kg[x] for x in put if put[x] == k) <= 16000
def test_rolling_horizons(con):
full, _ = rolling_bakery(con, 12)
short, _ = rolling_bakery(con, 1)
assert evaluate_bakery(con, short) < evaluate_bakery(con, full) - 1000
no_state, _ = rolling_bakery(con, 2, fix=())
with pytest.raises(RuntimeError):
evaluate_bakery(con, no_state)
def test_driver_roster_rules():
routes = pd.DataFrame([(day, f"{day}-{k}", f"v{k}", "truck" if k == 1 else "van", 300, 420, 5)
for day in ("Mon", "Tue", "Wed") for k in (1, 2)],
columns=["day", "route", "vehicle", "type", "leaves", "back", "stops"])
drivers = pd.DataFrame({"contract": ["part-time", "part-time", "part-time"], "truck_licence": [1, 0, 0],
"hourly_wage": [30.0, 25.0, 26.0]}, index=["A", "B", "C"])
rules = {"pre_and_post_trip_minutes": 30, "min_paid_hours_per_day": 4, "full_time_min_days": 4,
"full_time_max_days": 5, "part_time_max_days": 3}
status, pay, table = solve_drivers(*build_driver_roster(routes, drivers, rules), routes)
assert status == "OPTIMAL" and (table[table.type == "truck"].driver == "A").all()
assert table.groupby(["driver", "day"]).size().max() == 1
assert pay == pytest.approx(3 * 4 * 30.0 + 3 * 4 * 25.0) # B is cheaper than C for the vans
61 passed
Day 40 checklist
- I built a week's plan from several models, in sequence, and said what the sequence can't see.
- I checked every day's routes against windows, capacity and street access.
- I assigned drivers to routes with licences, contracts and paid hours.
- I priced one what-if across the whole week.
- I wrote one memo that turns a module of analyses into decisions.