37.1 Delivery windows and the time dimension
Time is a second dimension, like racks: it accumulates along a route (driving time plus the time spent at each stop), and each stop's arrival time must fall inside its window. Waiting is allowed (the "slack", up to 2 hours here). Create day37/vrptw.py:
"""Day 37: routes with time windows, service times and a mixed fleet (OR-Tools routing).
Import it: from vrptw import load_fleet, solve_vrptw, simulate
"""
from ortools.constraint_solver import pywrapcp, routing_enums_pb2
def load_fleet(con):
fleet = con.sql("SELECT * FROM delivery_fleet").df()
vehicles = []
for r in fleet.itertuples():
for k in range(1, int(r.vehicles) + 1):
vehicles.append({"name": f"{r.vehicle_type}-{k}", "type": r.vehicle_type, "racks": int(r.racks),
"cost_per_day": float(r.cost_per_day), "cost_per_km": float(r.cost_per_km)})
return vehicles
def hhmm(minute):
return f"{int(minute) // 60:02d}:{int(minute) % 60:02d}"
def solve_vrptw(stops, ids, km, minutes, vehicles, windows=True, vans_only_downtown=True, max_route_minutes=None,
count_service=True, solutions=300, window_shift=0, dispatch_at=None,
starts=("PATH_CHEAPEST_ARC", "SAVINGS", "PARALLEL_CHEAPEST_INSERTION")):
"""Minimize the day's cost (vehicle day costs + cost per km), in cents. Times are minutes after midnight.
window_shift: minutes added to every cafe's latest delivery time; dispatch_at: earliest departure (what-ifs).
starts: first-solution strategies; the search runs once from each, and the cheapest plan wins (multi-start)."""
best = None
for start in starts:
plan = _solve_once(stops, ids, km, minutes, vehicles, windows, vans_only_downtown, max_route_minutes,
count_service, solutions, window_shift, dispatch_at, start)
if plan is not None and (best is None or plan[0]["objective"] < best[0]["objective"]):
best = plan
return best
def _solve_once(stops, ids, km, minutes, vehicles, windows, vans_only_downtown, max_route_minutes,
count_service, solutions, window_shift, dispatch_at, start):
n, V = len(ids), len(vehicles)
manager = pywrapcp.RoutingIndexManager(n, V, 0)
model = pywrapcp.RoutingModel(manager)
cost_of_rate = {}
for v, veh in enumerate(vehicles): # one cost callback per cost rate, shared by vehicles
rate = veh["cost_per_km"]
if rate not in cost_of_rate:
cents = [[int(round(100 * rate * km[a][b])) for b in range(n)] for a in range(n)]
cost_of_rate[rate] = model.RegisterTransitCallback(
lambda i, j, c=cents: c[manager.IndexToNode(i)][manager.IndexToNode(j)])
model.SetArcCostEvaluatorOfVehicle(cost_of_rate[rate], v)
model.SetFixedCostOfVehicle(int(100 * veh["cost_per_day"]), v)
racks = model.RegisterUnaryTransitCallback(lambda i: int(stops.racks[ids[manager.IndexToNode(i)]]))
model.AddDimensionWithVehicleCapacity(racks, 0, [veh["racks"] for veh in vehicles], True, "racks")
service = [int(stops.service_minutes[s]) if count_service else 0 for s in ids]
travel = [[int(minutes[a][b]) + service[a] for b in range(n)] for a in range(n)] # drive + time at the stop we leave
time = model.RegisterTransitCallback(lambda i, j: travel[manager.IndexToNode(i)][manager.IndexToNode(j)])
model.AddDimension(time, 120, 24 * 60, False, "time") # up to 2 hours waiting allowed
clock = model.GetDimensionOrDie("time")
for node, s in enumerate(ids):
if node == 0:
continue
close = int(stops.window_close[s]) + (window_shift if stops.kind[s] == "cafe" else 0)
if windows:
clock.CumulVar(manager.NodeToIndex(node)).SetRange(int(stops.window_open[s]), close)
if vans_only_downtown and stops.downtown[s]: # narrow streets: no trucks
trucks = [v for v, veh in enumerate(vehicles) if veh["type"] != "van"]
if trucks:
model.VehicleVar(manager.NodeToIndex(node)).RemoveValues(trucks)
depot_open, depot_close = int(stops.window_open[ids[0]]), int(stops.window_close[ids[0]])
if dispatch_at is not None:
depot_open = dispatch_at
for v in range(V):
clock.CumulVar(model.Start(v)).SetRange(depot_open, depot_close)
clock.CumulVar(model.End(v)).SetRange(depot_open, depot_close)
model.AddVariableMaximizedByFinalizer(clock.CumulVar(model.Start(v))) # leave as late as possible
model.AddVariableMinimizedByFinalizer(clock.CumulVar(model.End(v)))
if max_route_minutes is not None:
for v in range(V):
model.solver().Add(clock.CumulVar(model.End(v)) - clock.CumulVar(model.Start(v)) <= max_route_minutes)
params = pywrapcp.DefaultRoutingSearchParameters()
params.first_solution_strategy = getattr(routing_enums_pb2.FirstSolutionStrategy, start)
params.local_search_metaheuristic = routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH
params.solution_limit = solutions # stop after this many solutions: the same routes every run
params.time_limit.seconds = 300 # a safety net only
solution = model.SolveWithParameters(params)
if solution is None:
return None
plan = []
for v, veh in enumerate(vehicles):
index, route = model.Start(v), []
leaves = solution.Min(clock.CumulVar(index))
while not model.IsEnd(index):
node = manager.IndexToNode(index)
if node != 0:
route.append((node, solution.Min(clock.CumulVar(index))))
index = solution.Value(model.NextVar(index))
if route:
plan.append({"vehicle": veh["name"], "type": veh["type"], "leaves": leaves,
"back": solution.Min(clock.CumulVar(index)), "stops": route,
"objective": solution.ObjectiveValue()})
return plan
def simulate(plan, stops, ids, km, minutes, vehicles, window_shift=0, dispatch_at=None):
"""Drive each route independently of the solver: leave when the dock opens (or at dispatch_at), wait if early,
serve, drive on. Returns (cost, km, problems)."""
depart = int(stops.window_open[ids[0]]) if dispatch_at is None else dispatch_at
by_name = {veh["name"]: veh for veh in vehicles}
cost, total_km, problems = 0.0, 0.0, []
for r in plan:
veh = by_name[r["vehicle"]]
t, here, racks = depart, 0, 0
route_km = 0.0
for node, _ in r["stops"]:
s = ids[node]
t += minutes[here][node]
route_km += km[here][node]
close = stops.window_close[s] + (window_shift if stops.kind[s] == "cafe" else 0)
if t > close:
problems.append(f"{r['vehicle']} reaches {s} at {hhmm(t)}, after {hhmm(close)}")
t = max(t, stops.window_open[s]) + stops.service_minutes[s]
racks += stops.racks[s]
if stops.downtown[s] and veh["type"] != "van":
problems.append(f"{r['vehicle']} can't enter downtown street of {s}")
here = node
route_km += km[here][0]
t += minutes[here][0]
if racks > veh["racks"]:
problems.append(f"{r['vehicle']} carries {racks} racks, room for {veh['racks']}")
if t > stops.window_close[ids[0]]:
problems.append(f"{r['vehicle']} back at {hhmm(t)}, after {hhmm(stops.window_close[ids[0]])}")
cost += veh["cost_per_day"] + veh["cost_per_km"] * route_km
total_km += route_km
return round(cost, 2), round(total_km, 2), problems
Points to notice:
- Costs per vehicle type:
SetArcCostEvaluatorOfVehiclewith a cents-per-km callback, andSetFixedCostOfVehiclefor the day charge. The objective is the day's cost. - Service time is added to the travel time from a stop: arriving at 05:00 with 6 minutes of unloading, the van can leave at 05:06.
- Downtown stops:
VehicleVar(index).RemoveValues(trucks)takes trucks out of the choices for that stop. - Multi-start: the search runs from three first solutions and keeps the cheapest. Each run stops after 300 solutions, so results repeat.
simulatedrives every route from the dock's opening, waits when early, and reports late arrivals, overloads and trucks downtown. It shares no code with the model.
Then day37/run_vrptw.py:
# ---------- 37.1 Delivery windows ----------
print(stops[stops.kind != "depot"].groupby(["kind", "window_open", "window_close"]).size().rename("stops").to_string())
print(f"loading dock: {hhmm(stops.window_open['DEPOT'])}-{hhmm(stops.window_close['DEPOT'])}")
vans = [{"name": f"van-{k}", "type": "van", "racks": 18, "cost_per_day": 90.0, "cost_per_km": 0.40} for k in range(1, 16)]
for name, kw in [("vans only, no windows (Day 36)", dict(windows=False, vans_only_downtown=False)),
("vans only, with windows", {})]:
show(name, solve_vrptw(stops, ids, km, minutes, vans, **kw), vans)
kind window_open window_close
cafe 300 375 7
405 9
435 8
store 270 420 10
loading dock: 04:00-08:00
vans only, no windows (Day 36): {'van': 9}, 272.92 km, $919.17; longest route 154 min; 2 problems
van-5 reaches C20 at 06:28, after 06:15
van-6 reaches C15 at 06:58, after 06:45
vans only, with windows: {'van': 9}, 264.04 km, $915.62; longest route 157 min; 0 problems
Day 36's van routes, driven against the windows, arrive late twice. With windows in the model, 9 vans keep every window.
37.2 Today's fleet
# ---------- 37.2 Today's fleet: 6 vans, 3 trucks, vans only downtown ----------
print(pd.DataFrame(fleet).groupby("type").first()[["racks", "cost_per_day", "cost_per_km"]].to_string())
plan = solve_vrptw(stops, ids, km, minutes, fleet)
best = show("today's fleet, windows, downtown rule", plan, fleet)
rows = []
for r in plan:
route = [n for n, _ in r["stops"]]
rows.append((r["vehicle"], hhmm(r["leaves"]), hhmm(r["back"]), len(route), sum(int(stops.racks[ids[n]]) for n in route),
round(tour_km(route, km), 2), " ".join(f"{ids[n]}@{hhmm(t)}" for n, t in r["stops"])))
print(pd.DataFrame(rows, columns=["vehicle", "leaves", "back", "stops", "racks", "km", "arrivals"]).to_string(index=False))
racks cost_per_day cost_per_km
type
truck 36 150.0 0.65
van 18 90.0 0.40
today's fleet, windows, downtown rule: {'van': 5, 'truck': 2}, 229.91 km, $864.50; longest route 200 min; 0 problems
vehicle leaves back stops racks km arrivals
van-1 04:51 06:59 7 18 34.80 C09@05:05 C07@05:30 C15@05:48 C23@06:01 C24@06:16 C03@06:34 C18@06:45
van-3 05:38 07:44 4 18 32.03 S32@06:08 S31@06:36 C17@07:00 C01@07:15
van-4 05:21 06:30 3 18 14.25 C11@05:29 S27@05:48 C13@06:15
van-5 05:19 07:37 6 18 37.09 C06@05:34 C12@05:51 C02@06:02 C05@06:15 S28@06:36 C19@07:11
van-6 05:04 06:27 3 18 21.61 C21@05:15 S33@05:36 C20@06:15
truck-1 04:40 08:00 4 36 62.03 S30@04:54 C10@05:22 S35@06:16 S34@06:55
truck-2 05:18 07:40 7 35 28.10 C22@05:28 C08@05:42 S29@05:57 C16@06:21 C14@06:35 C04@06:45 S26@06:58
5 vans and 2 trucks, $864.50 a day, every window kept, no truck downtown. The table is the dispatcher's sheet: departure, return and every arrival time. Vehicles leave as late as their first window allows (the finalizer maximizes the start time), so drivers don't wait at the first stop.
37.3 What each rule costs
# ---------- 37.3 What each rule costs ----------
for name, kw in [("no windows (checked against them)", dict(windows=False)),
("trucks allowed downtown", dict(vans_only_downtown=False)),
("drivers back within 2.5 hours", dict(max_route_minutes=150))]:
cost = show(name, solve_vrptw(stops, ids, km, minutes, fleet, **kw), fleet)
print(f" difference: ${cost - best:+,.2f} a day")
no windows (checked against them): {'van': 3, 'truck': 3}, 206.25 km, $836.20; longest route 225 min; 4 problems
truck-3 reaches C07 at 07:41, after 07:15
truck-3 reaches C15 at 07:59, after 06:45
truck-3 reaches C23 at 08:12, after 06:45
difference: $-28.30 a day
trucks allowed downtown: {'van': 3, 'truck': 3}, 239.32 km, $837.95; longest route 181 min; 3 problems
truck-1 can't enter downtown street of C21
truck-1 can't enter downtown street of C06
truck-1 can't enter downtown street of C09
difference: $-26.55 a day
drivers back within 2.5 hours: {'van': 6, 'truck': 2}, 245.83 km, $949.16; longest route 150 min; 0 problems
difference: $+84.66 a day
- Without windows the plan is about $28 a day cheaper, and 4 deliveries arrive late.
- Trucks downtown would save about $27 a day, but trucks can't use those streets.
- Drivers back within 2.5 hours (a union proposal) costs $85 a day: one more van, about $22,000 a year.
Heuristics and noise
Routing searches are heuristics. Change a limit, a start or a small detail of the data, and the routes and cost move by a few dollars, sometimes in the "wrong" direction: in 37.1, vans with windows came out $3.55 cheaper than vans without them, which a proven-optimal plan could never do. Treat differences of a few dollars as noise. Multi-start, more search and comparing several scenarios together reduce it. Report decisions only when the difference is clearly larger than the noise.
The planted bug
day37/bug_service.py builds the routes with a time callback that "only needs the driving time". Run it.
plan = solve_vrptw(stops, ids, km, minutes, fleet, count_service=False)
print(f"the solver's plan: {len(plan)} vehicles, every stop inside its window")
cost, total_km, problems = simulate(plan, stops, ids, km, minutes, fleet)
print(f"driven for real: ${cost:,.2f}, {total_km:.2f} km, {len(problems)} late arrivals:")
for p in problems:
print(" ", p)
What happens, and why
the solver's plan: 6 vehicles, every stop inside its window
driven for real: $833.67, 227.92 km, 3 late arrivals:
van-3 reaches C24 at 06:51, after 06:45
truck-1 reaches C05 at 06:31, after 06:15
truck-3 reaches C20 at 06:26, after 06:15
The solver's plan is cheaper (6 vehicles, $833.67) and, by its own count, keeps every window. Driven for real, 3 deliveries are late: the unloading time at each stop (6 minutes per café, 20 per store) is missing, and it adds up along a route. The simulator, which serves each stop for its real service time, catches it. Every number a model leaves out is a number reality puts back in.
Mini-project: dispatch time and café windows
Day 34 found the bakery could start at 22:00 and still be ready around 04:45. What would dispatching at 04:30 or 05:00 instead of 04:00 cost on the road? And if cafés accepted deliveries up to 30 minutes later (most open at 07:00 or 07:30), what would that save?
Solution
"""Day 37 mini-project: Day 34 found the bakery can start at 22:00 instead of 21:00 and still be ready by
about 04:45. What does a later dispatch cost on the road? And what if cafes took delivery up to 30 minutes later?
Run from the repository root (after day06/load_tables.py): python day37/mini_project_dispatch.py (about 2 minutes)
"""
import sys
import duckdb
import pandas as pd
for folder in ("day36", "day37"):
sys.path.insert(0, folder)
from routing import load_run
from vrptw import hhmm, load_fleet, simulate, solve_vrptw
con = duckdb.connect("northbound.duckdb", read_only=True)
stops, ids, km, minutes = load_run(con)
fleet = load_fleet(con)
rows = []
for dispatch in (240, 270, 300):
for shift in (0, 30):
plan = solve_vrptw(stops, ids, km, minutes, fleet, dispatch_at=dispatch, window_shift=shift)
if plan is None:
rows.append((hhmm(dispatch), f"+{shift} min", "no plan", None, None, None))
continue
cost, total_km, problems = simulate(plan, stops, ids, km, minutes, fleet, window_shift=shift, dispatch_at=dispatch)
types = pd.Series([r["type"] for r in plan]).value_counts().to_dict()
rows.append((hhmm(dispatch), f"+{shift} min", f"{types.get('van', 0)} vans, {types.get('truck', 0)} trucks",
round(total_km, 2), cost, len(problems)))
print(pd.DataFrame(rows, columns=["dispatch", "cafe_windows", "vehicles", "km", "cost", "late"]).to_string(index=False))
dispatch cafe_windows vehicles km cost late
04:00 +0 min 5 vans, 2 trucks 229.91 864.50 0
04:00 +30 min 3 vans, 3 trucks 243.03 840.35 0
04:30 +0 min 5 vans, 2 trucks 258.95 867.36 0
04:30 +30 min 3 vans, 3 trucks 243.80 840.85 0
05:00 +0 min 4 vans, 3 trucks 213.98 925.42 0
05:00 +30 min 5 vans, 2 trucks 243.52 861.14 0
- Dispatching at 04:30 costs nothing measurable ($867.36 against $864.50: within the search's noise).
- Dispatching at 05:00 costs about $61 a day: everything must happen in a shorter morning, so more vehicles run at once.
- Café windows 30 minutes later save about $24 a day at a 04:00 or 04:30 dispatch, with 3 vans and 3 trucks instead of 5 vans and 2 trucks. At a 05:00 dispatch they almost cancel the cost of the late start.
Memo to the operations manager: "Start the night run at 21:30 rather than 22:00: the run then finishes at 03:43 (Day 34) and the vans can leave at 04:00–04:30 at no extra cost. Starting at 22:00 pushes dispatch towards 05:00, which costs about $61 a day ($16,000 a year) on the road, unless the cafés accept deliveries 30 minutes later. Ask the cafés: later windows save about $24 a day ($6,000 a year) at today's dispatch time."
Commit
git add .
git commit -m "Day 37: time windows, service times, mixed fleet"
git push
Then run the tests: tests/test_shop_and_routes.py checks Days 34–37 (the short-staffed night against the checker, four normal weeks, the proven tour and savings routes, and every window kept). Add "day34" to "day37" to the folders in conftest.py. The suite now takes about a minute.
"""Module 4, Days 34-37: the bakery job shop, the 4-week roster, tours and routes."""
import pytest
from bakery_shop import build_schedule, check_schedule, dispatch_fifo, load_shop, solve_schedule, summary
from four_weeks import build_four_weeks, solve_four_weeks
from roster import load_roster_data
from routing import load_run, savings, tour_km, tsp_exact, two_opt, nearest_neighbour
from vrptw import load_fleet, simulate, solve_vrptw
def test_short_staffed_night_is_proven_and_legal(con):
jobs, ops, machines, rules = load_shop(con)
solver, status, sched = solve_schedule(build_schedule(jobs, ops, machines, rules, one_of_each=True), ops)
assert solver.status_name(status) == "OPTIMAL" and summary(sched, jobs)["makespan"] == 664
assert check_schedule(sched, jobs, machines, rules) == []
assert check_schedule(dispatch_fifo(jobs, ops, machines), jobs, machines, rules) # the hand plan over-proofs
def test_four_normal_weeks_cost_four_day32_weeks(con):
out, roster = solve_four_weeks(build_four_weeks(*load_roster_data(con)), work=40)
assert out["status"] == "OPTIMAL" and out["pay"] == pytest.approx(4 * 28_876.48, abs=0.01)
def test_tours_and_savings(con):
stops, ids, km, minutes = load_run(con)
tour, status, bound = tsp_exact(km)
assert status == "OPTIMAL" and tour_km(tour, km) == pytest.approx(128.15, abs=0.01)
assert tour_km(two_opt(nearest_neighbour(km), km), km) >= tour_km(tour, km) - 1e-9
racks = [int(stops.racks[s]) for s in ids]
routes = savings(km, racks, 18)
assert sorted(n for r in routes for n in r) == list(range(1, len(ids)))
assert all(sum(racks[n] for n in r) <= 18 for r in routes)
def test_fleet_routes_keep_every_window(con):
stops, ids, km, minutes = load_run(con)
fleet = load_fleet(con)
plan = solve_vrptw(stops, ids, km, minutes, fleet)
cost, total_km, problems = simulate(plan, stops, ids, km, minutes, fleet)
assert problems == [] and sum(len(r["stops"]) for r in plan) == len(ids) - 1
57 passed
Day 37 checklist
- I can add a time dimension with windows and service times.
- I can give each vehicle type its own costs and restrict which vehicles may visit a stop.
- I check routes with an independent simulator.
- I price each rule (windows, street access, route length) by removing it.
- I treat small differences between heuristic plans as noise.
- I connected two plans: the bakery's finish time and the vans' dispatch time.