Prescriptive Analytics & Decision Intelligence
Overview / Module 4 / Day 38
Module 4 · Scheduling, Routing and Constraint Programming · Day 38 of 80

Heuristics and Metaheuristics

OR-Tools' routing search (Days 36–37) is a metaheuristic: a general strategy for improving plans without proving anything. Today you write two yourself, local search and simulated annealing, to see what's inside, and learn how to compare heuristics honestly (several seeds, the right objective, a bound when one exists).

▶
Video for Day 38 coming soon

In this lesson

Today's 5-hour plan

LessonProjectBreakCommit
0:00–0:45
38.1 Local search: neighbourhoods and local optima
0:45–1:45
38.2 Simulated annealing
1:45–2:00
Break
2:00–2:45
38.3 Comparing methods; 38.4 the right objective
2:45–3:45
When to use a heuristic; a planted bug
3:45–4:00
Break
4:00–4:45
Mini-project: Christmas trailers by annealing
4:45–5:00
Commit with Git + checklist

Update the course data

Copy the latest make_data.py from the Course data page and rebuild (python make_data.py, python day01/ladder.py, python day06/load_tables.py). New for Day 40: delivery_days (next week's racks by day), delivery_drivers and driver_rules.

38.1 Local search: neighbourhoods and local optima

A neighbourhood is the set of plans one small change away. For van routes, three classic moves:

  • relocate: move one stop to another position, in its route or another one;
  • swap: exchange two stops between routes;
  • 2-opt: reverse a piece of one route (Day 36).

Local search takes the best neighbour while it is better, and stops when none is: a local optimum. Create day38/metaheuristics.py:

import math
import random


def route_km(route, km):
    path = [0] + route + [0]
    return sum(km[a][b] for a, b in zip(path, path[1:]))


def total_km(routes, km):
    return sum(route_km(r, km) for r in routes)


def load(route, racks):
    return sum(racks[n] for n in route)


def neighbours(routes, racks, capacity):
    """Every plan one move away: relocate a stop (to any position, in any route), swap two stops in different
    routes, or reverse a piece of one route (2-opt)."""
    n = len(routes)
    for a in range(n):
        for i, stop in enumerate(routes[a]):
            for b in range(n):
                if b != a and load(routes[b], racks) + racks[stop] > capacity:
                    continue
                for j in range(len(routes[b]) + (0 if b == a else 1)):
                    if b == a and j == i:
                        continue
                    new = [r[:] for r in routes]
                    new[a].pop(i)
                    new[b].insert(j, stop)
                    yield "relocate", new
    for a in range(n):
        for b in range(a + 1, n):
            for i, x in enumerate(routes[a]):
                for j, y in enumerate(routes[b]):
                    if (load(routes[a], racks) - racks[x] + racks[y] <= capacity
                            and load(routes[b], racks) - racks[y] + racks[x] <= capacity):
                        new = [r[:] for r in routes]
                        new[a][i], new[b][j] = y, x
                        yield "swap", new
    for a in range(n):
        for i in range(len(routes[a]) - 1):
            for j in range(i + 1, len(routes[a])):
                new = [r[:] for r in routes]
                new[a][i:j + 1] = reversed(new[a][i:j + 1])
                yield "2-opt", new


def local_search(routes, km, racks, capacity, log=None):
    """Best improvement: take the best neighbour while it is shorter. Stops at a local optimum."""
    current, cost = [r[:] for r in routes], total_km(routes, km)
    while True:
        best = min(((total_km(new, km), kind, new) for kind, new in neighbours(current, racks, capacity)),
                   key=lambda x: x[0], default=None)
        if best is None or best[0] >= cost - 1e-9:
            return [r for r in current if r], cost
        cost, kind, current = best
        current = [r for r in current if r]
        if log is not None:
            log.append((kind, round(cost, 2)))


def random_move(routes, racks, capacity, rng):
    """One random relocate, swap or 2-opt move that respects capacity (None if the try fails)."""
    new = [r[:] for r in routes]
    kind = rng.choice(["relocate", "swap", "2-opt"])
    a = rng.randrange(len(new))
    if not new[a]:
        return None
    i = rng.randrange(len(new[a]))
    if kind == "relocate":
        b = rng.randrange(len(new) + 1)                        # len(new): open a new route
        if b == len(new):
            new.append([])
        stop = new[a][i]
        if b != a and load(new[b], racks) + racks[stop] > capacity:
            return None
        new[a].pop(i)
        new[b].insert(rng.randrange(len(new[b]) + 1), stop)
    elif kind == "swap":
        b = rng.randrange(len(new))
        if b == a or not new[b]:
            return None
        j = rng.randrange(len(new[b]))
        x, y = new[a][i], new[b][j]
        if load(new[a], racks) - racks[x] + racks[y] > capacity or load(new[b], racks) - racks[y] + racks[x] > capacity:
            return None
        new[a][i], new[b][j] = y, x
    else:
        j = rng.randrange(len(new[a]))
        i, j = min(i, j), max(i, j)
        new[a][i:j + 1] = reversed(new[a][i:j + 1])
    return [r for r in new if r]


def simulated_annealing(routes, km, racks, capacity, seed=0, start_temp=5.0, cooling=0.9995, steps=40_000,
                        vehicle_km=0.0):
    """Accept every better move, and a worse one with probability exp(-worse / temperature). The temperature
    falls a little each step, so the search wanders early and settles late. vehicle_km: a penalty per route."""
    rng = random.Random(seed)

    def cost(rs):
        return total_km(rs, km) + vehicle_km * len(rs)

    current, current_cost = [r[:] for r in routes], cost(routes)
    best, best_cost = current, current_cost
    temp = start_temp
    for _ in range(steps):
        new = random_move(current, racks, capacity, rng)
        temp *= cooling
        if new is None:
            continue
        delta = cost(new) - current_cost
        if delta <= 0 or rng.random() < math.exp(-delta / temp):
            current, current_cost = new, current_cost + delta
            if current_cost < best_cost - 1e-9:
                best, best_cost = [r[:] for r in current], current_cost
    return best, total_km(best, km)

Then day38/run_heuristics.py:

# ---------- 38.1 Local search ----------
for name, start in [("sweep", sweep(stops, ids, racks, VAN)), ("savings", savings(km, racks, VAN))]:
    log = []
    routes, cost = local_search(start, km, racks, VAN, log=log)
    print(f"{name}: {total_km(start, km):.2f} km -> local search {cost:.2f} km after {len(log)} moves "
          f"({', '.join(sorted({k for k, _ in log})) or 'none: already a local optimum'})")
    rows += [(name, len(start), round(total_km(start, km), 2)), (f"{name} + local search", len(routes), round(cost, 2))]
sweep: 344.29 km -> local search 276.89 km after 21 moves (2-opt, relocate, swap)
savings: 266.93 km -> local search 266.93 km after 0 moves (none: already a local optimum)

From the dispatcher's sweep routes, 21 moves cut 344 km to 277 km and two vans. From the savings routes, no single move helps: they are already a local optimum, yet 3% longer than OR-Tools' 258 km. Local search stops at the first valley it finds.

38.2 Simulated annealing

Simulated annealing (Kirkpatrick and others, 1983) escapes valleys by sometimes accepting a worse plan: a move that adds Δ\Delta km is accepted with probability e−Δ/Te^{-\Delta / T}. The temperature TT starts high (the search wanders) and falls step by step (the search settles). The name comes from cooling metal slowly so its atoms settle into a strong structure.

# ---------- 38.2 Simulated annealing ----------
start = savings(km, racks, VAN)
for steps in (40_000, 200_000):
    results = [float(simulated_annealing(start, km, racks, VAN, seed=s, steps=steps, cooling=1e-4 ** (1 / steps))[1])
               for s in range(10)]
    print(f"annealing from savings, {steps:,} steps, 10 seeds: best {min(results):.2f}, median "
          f"{statistics.median(results):.2f}, worst {max(results):.2f} km")
    rows.append((f"annealing, {steps:,} steps (best of 10 seeds)", 10, round(min(results), 2)))
    rows.append((f"annealing, {steps:,} steps (median of 10)", 10, round(statistics.median(results), 2)))
routes = solve_cvrp(km, racks, [VAN] * 15, solutions=1000)
rows.append(("OR-Tools, 1,000 solutions (Day 36)", len(routes), round(total_km(routes, km), 2)))
annealing from savings, 40,000 steps, 10 seeds: best 258.30, median 266.93, worst 266.93 km
annealing from savings, 200,000 steps, 10 seeds: best 258.30, median 260.15, worst 266.93 km
  • The best of 10 seeds reaches 258.30 km, the same as OR-Tools.
  • The median matters as much as the best: with 40,000 steps more than half the seeds never improve on the savings plan; with 200,000 the median is 260.15 km.
  • A heuristic's result is a distribution. Report the best and the spread over several seeds, and fix the seeds so others can repeat the runs.

38.3 Comparing methods

# ---------- 38.3 Comparing methods, and a question for an exact model ----------
print(pd.DataFrame(rows, columns=["method", "vans", "km"]).to_string(index=False))
van_day, van_km = con.sql("SELECT cost_per_day, cost_per_km FROM delivery_fleet WHERE vehicle_type = 'van'").fetchall()[0]
m = cp_model.CpModel()                                          # can 9 vans carry the racks at all?
x = {(n, v): m.new_bool_var(f"x{n}_{v}") for n in range(1, len(ids)) for v in range(9)}
for n in range(1, len(ids)):
    m.add_exactly_one(x[n, v] for v in range(9))
for v in range(9):
    m.add(sum(racks[n] * x[n, v] for n in range(1, len(ids))) <= VAN)
s = cp_model.CpSolver()
s.parameters.num_workers = 8
s.parameters.interleave_search = True
print(f"can 9 vans of {VAN} racks carry the {sum(racks)} racks (ignoring the roads)? {s.status_name(s.solve(m))}")
                                     method  vans     km
                                      sweep    12 344.29
                       sweep + local search    10 276.89
                                    savings    10 266.93
                     savings + local search    10 266.93
 annealing, 40,000 steps (best of 10 seeds)    10 258.30
     annealing, 40,000 steps (median of 10)    10 266.93
annealing, 200,000 steps (best of 10 seeds)    10 258.30
    annealing, 200,000 steps (median of 10)    10 260.15
         OR-Tools, 1,000 solutions (Day 36)    10 258.30
can 9 vans of 18 racks carry the 161 racks (ignoring the roads)? OPTIMAL

Every method uses 10 vans, but a quick exact model of the packing alone says 9 vans can carry the racks. None of the heuristics looked for 9 vans, because the objective was kilometres, and the tenth van makes the routes shorter.

38.4 The right objective

# ---------- 38.4 The right objective: a van costs a day charge too ----------
penalty = van_day / van_km                                       # one more van costs as much as this many km
print(f"a van's day charge ${van_day:.0f} = {penalty:.0f} km at ${van_km:.2f}/km")
best = None
for seed in range(10):
    r, k = simulated_annealing(start, km, racks, VAN, seed=seed, steps=200_000, cooling=1e-4 ** (1 / 200_000),
                               vehicle_km=penalty)
    cost = van_day * len(r) + van_km * float(k)
    if best is None or cost < best[0]:
        best = (cost, len(r), float(k), seed)
print(f"annealing on cost (best of 10 seeds): {best[1]} vans, {best[2]:.2f} km, ${best[0]:,.2f} a day (seed {best[3]})")
routes = solve_cvrp(km, racks, [VAN] * 15, solutions=1000, fixed_cost=1000 * penalty)
print(f"OR-Tools on cost: {len(routes)} vans, {total_km(routes, km):.2f} km, "
      f"${van_day * len(routes) + van_km * total_km(routes, km):,.2f} a day")
print(f"annealing on km (38.2): 10 vans, 258.30 km, ${van_day * 10 + van_km * 258.30:,.2f} a day")
a van's day charge $90 = 225 km at $0.40/km
annealing on cost (best of 10 seeds): 9 vans, 261.68 km, $914.67 a day (seed 7)
OR-Tools on cost: 9 vans, 265.02 km, $916.01 a day
annealing on km (38.2): 10 vans, 258.30 km, $1,003.32 a day

A van costs $90 a day, as much as 225 km of driving. With that in the objective, annealing finds 9 vans and 261.68 km: $914.67 a day, against $1,003.32 for the shortest 10-van plan. OR-Tools, given the same fixed cost, finds 9 vans too. The best heuristic is worthless if it optimizes the wrong thing.

When to use a heuristic

Use a heuristic whenUse an exact method when
The problem is large or messy (thousands of stops, odd rules)The problem fits a MIP or CP model and solves in time
A good plan now beats a proven plan laterA proof matters (contracts, audits, big money)
You need many plans quickly (what-ifs, every hour)You need duals, bounds or gaps

Often the answer is both: an exact model for a piece (38.3's packing check), a heuristic for the whole, and a bound to say how good the heuristic is.

Decision it supports: good plans for problems too large or messy for exact methods.

Other decisions you can support the same way: timetables for a whole university · chip layouts · warehouse slotting · large crew schedules.

The planted bug

day38/bug_capacity.py: a colleague's "faster" relocate move for annealing. Run it.

def relocate(routes, rng):
    new = [r[:] for r in routes]
    a, b = rng.randrange(len(new)), rng.randrange(len(new))
    if a == b or not new[a]:
        return None
    stop = new[a].pop(rng.randrange(len(new[a])))
    if load(new[a], racks) + racks[stop] > 18:                 # does the stop fit?
        return None
    new[b].insert(rng.randrange(len(new[b]) + 1), stop)
    return [r for r in new if r]
What happens, and why
annealing result: 5 vans, 254.49 km
racks per van: [22, 37, 24, 51, 27]

Five vans and 254 km: better than anything so far, and impossible. One van carries 51 racks. The capacity check looks at route a after removing the stop instead of route b, which receives it, so every move passes. A heuristic you write yourself has no solver checking its constraints: check every result independently (load of every route), as on Days 32 and 37.

Mini-project: Christmas trailers by annealing

Days 26–28: HiGHS needed up to 16,000 nodes to prove that Christmas Tuesday fits on 15 trailers. Write an annealing search that tries to load the 48 orders on exactly 15 trailers, minimizing the overflow (pallets over 26 plus tonnes over 16). Run 10 seeds. Who proves 15 is the best?

Solution
def anneal_packing(pallets, kg, n_trucks, start, cap=26, max_kg=16000, seed=0, steps=200_000, start_temp=2.0):
    """Simulated annealing for loading orders on exactly n_trucks trailers. The cost is how far the trailers are
    over their limits (pallets over 26, plus tonnes over 16); a cost of 0 means every trailer is legal.
    start: {order: trailer}. Returns (assignment, overflow, steps used)."""
    rng = random.Random(seed)
    orders = sorted(pallets)
    put = dict(start)
    lp, lw = [0] * n_trucks, [0] * n_trucks
    for o, k in put.items():
        lp[k] += pallets[o]
        lw[k] += kg[o]

    def overflow():
        return sum(max(0, p - cap) + max(0, (w - max_kg) / 1000) for p, w in zip(lp, lw))

    current, temp = overflow(), start_temp
    cooling = 1e-4 ** (1 / steps)
    for step in range(steps):
        if current == 0:
            return put, 0.0, step
        temp *= cooling
        if rng.random() < 0.5:                               # move one order to another trailer
            o = rng.choice(orders)
            a, b = put[o], rng.randrange(n_trucks)
            if a == b:
                continue
            changes = [(a, -pallets[o], -kg[o]), (b, pallets[o], kg[o])]
            swap = {o: b}
        else:                                                # swap two orders on different trailers
            o1, o2 = rng.sample(orders, 2)
            a, b = put[o1], put[o2]
            if a == b:
                continue
            dp, dw = pallets[o2] - pallets[o1], kg[o2] - kg[o1]
            changes = [(a, dp, dw), (b, -dp, -dw)]
            swap = {o1: b, o2: a}
        for k, dp, dw in changes:
            lp[k] += dp
            lw[k] += dw
        new = overflow()
        if new <= current or rng.random() < math.exp(-(new - current) / temp):
            current = new
            put.update(swap)
        else:
            for k, dp, dw in changes:
                lp[k] -= dp
                lw[k] -= dw
    return put, current, steps
"""Day 38 mini-project: Christmas Tuesday's trailers (Days 26-28) by simulated annealing.
HiGHS needed up to 16,000 nodes to prove 15 trailers. Can a heuristic find 15, and who proves it is the best?

Run from the repository root (after day06/load_tables.py):  python day38/mini_project_trailers.py
"""
import math
import sys

import duckdb

for folder in ("day24", "day38"):
    sys.path.insert(0, folder)
from metaheuristics import anneal_packing
from packing import first_fit_decreasing

con = duckdb.connect("northbound.duckdb", read_only=True)
orders = con.sql("SELECT * FROM christmas_orders ORDER BY order_id").df().set_index("order_id")
pallets, kg = orders.pallets.to_dict(), orders.weight_kg.to_dict()
ffd = first_fit_decreasing(pallets, 26, kg, 16000)
bound = max(math.ceil(sum(pallets.values()) / 26), math.ceil(sum(kg.values()) / 16000))
print(f"first fit decreasing: {len(ffd)} trailers; no plan can use fewer than {bound} (the weight bound)")
start = {}
for k, (_, _, on) in enumerate(ffd):                  # FFD's plan, with the 16th trailer's orders spread over the 15
    for o in on:
        start[o] = k if k < bound else 0
for seed in range(10):
    put, overflow, steps = anneal_packing(pallets, kg, bound, start, seed=seed)
    loads = [(sum(pallets[o] for o in put if put[o] == k), sum(kg[o] for o in put if put[o] == k)) for k in range(bound)]
    legal = all(p <= 26 and w <= 16000 for p, w in loads)
    print(f"seed {seed}: {'15 legal trailers' if legal else f'overflow {overflow:.2f}'} after {steps:,} steps; "
          f"fullest {max(p for p, _ in loads)} pallets, heaviest {max(w for _, w in loads):,} kg")
first fit decreasing: 16 trailers; no plan can use fewer than 15 (the weight bound)
seed 0: 15 legal trailers after 85,197 steps; fullest 26 pallets, heaviest 16,000 kg
seed 1: 15 legal trailers after 72,655 steps; fullest 26 pallets, heaviest 15,990 kg
seed 2: 15 legal trailers after 84,952 steps; fullest 24 pallets, heaviest 16,000 kg
seed 3: 15 legal trailers after 62,692 steps; fullest 26 pallets, heaviest 15,960 kg
seed 4: 15 legal trailers after 71,783 steps; fullest 25 pallets, heaviest 15,970 kg
seed 5: 15 legal trailers after 88,185 steps; fullest 26 pallets, heaviest 15,970 kg
seed 6: 15 legal trailers after 68,034 steps; fullest 26 pallets, heaviest 15,990 kg
seed 7: 15 legal trailers after 70,383 steps; fullest 26 pallets, heaviest 15,990 kg
seed 8: 15 legal trailers after 72,439 steps; fullest 26 pallets, heaviest 15,990 kg
seed 9: 15 legal trailers after 62,597 steps; fullest 26 pallets, heaviest 15,950 kg
  • Every seed finds 15 legal trailers, each in well under a second (62,000 to 88,000 steps).
  • Annealing can't prove anything, but it doesn't need to: the weight bound (Day 24) says no plan uses fewer than 15 trailers. A heuristic plan that meets a bound is proven optimal.
  • The lesson for hard MIPs: give the solver a good plan as a warm start (Day 28's checklist), or find one by heuristic and check it against a bound.

Commit

git add .
git commit -m "Day 38: local search and simulated annealing"
git push

Day 38 checklist

  • I can write a local search with relocate, swap and 2-opt moves.
  • I can write simulated annealing and choose a starting temperature and cooling.
  • I report a heuristic's best and spread over several fixed seeds.
  • I put the real costs (day charges, not only km) into a heuristic's objective.
  • I check every heuristic plan independently.
  • I prove a heuristic plan optimal when it meets a bound.