26.1 Branch and bound by hand
Take the rush truck from Day 24 (pallets only). Its relaxation needs no solver: take orders by value per pallet, and a fraction of the first one that doesn't fit. That fraction is the only thing between the relaxation and a real load, so branch on it: one branch where the order is taken, one where it is left behind. Each branch has its own relaxation, and so its own bound. A branch whose bound can't beat the best load found so far is pruned: nothing below it can be better.
Create day26/by_hand.py:
def lp_bound(orders, capacity, fixed):
"""Best value of the relaxation when some orders are fixed: fixed[o] = 1 (on the truck) or 0 (left behind).
Returns (bound, the order taken as a fraction or None); bound is None if the fixed orders don't fit."""
room = capacity - sum(orders[o][0] for o, f in fixed.items() if f == 1)
if room < 0:
return None, None
value = sum(orders[o][1] for o, f in fixed.items() if f == 1)
for o in sorted((o for o in orders if o not in fixed), key=lambda o: (-orders[o][1] / orders[o][0], o)):
pallets, v = orders[o]
if pallets <= room:
room -= pallets
value += v
else:
return value + v * room / pallets, (o if room > 0 else None)
return value, None
def branch_and_bound_knapsack(orders, capacity, bound=lp_bound, show=print):
"""Depth first: try 'take it' before 'leave it'. Prune a node if its bound can't beat the best load so far."""
best = {"value": 0, "load": None, "nodes": 0}
def node(fixed, depth):
best["nodes"] += 1
b, frac = bound(orders, capacity, fixed)
where = ", ".join(f"{o}={f}" for o, f in fixed.items()) or "root"
if b is None:
show(f"{' ' * depth}{where}: doesn't fit")
return
if b <= best["value"]:
show(f"{' ' * depth}{where}: bound {b:,.2f} <= best {best['value']:,.0f}: prune")
return
if frac is None: # the relaxation took whole orders only: an integer plan
load = sorted([o for o, f in fixed.items() if f == 1] + greedy_rest(orders, capacity, fixed))
best.update(value=b, load=load)
show(f"{' ' * depth}{where}: bound {b:,.2f} is a whole load: new best {', '.join(load)}")
return
show(f"{' ' * depth}{where}: bound {b:,.2f}, {frac} fractional: branch")
node({**fixed, frac: 1}, depth + 1)
node({**fixed, frac: 0}, depth + 1)
node({}, 0)
return best
def greedy_rest(orders, capacity, fixed):
room = capacity - sum(orders[o][0] for o, f in fixed.items() if f == 1)
taken = []
for o in sorted((o for o in orders if o not in fixed), key=lambda o: (-orders[o][1] / orders[o][0], o)):
if orders[o][0] <= room:
room -= orders[o][0]
taken.append(o)
return taken
# ---------- 26.1 The search tree ----------
best = branch_and_bound_knapsack(orders, capacity)
print(f"best {best['value']:,.0f}: {', '.join(best['load'])}; {best['nodes']} nodes "
f"instead of {2 ** len(orders):,} combinations")
root: bound 7,556.67, RO-02 fractional: branch
RO-02=1: bound 7,540.00, RO-16 fractional: branch
RO-02=1, RO-16=1: bound 7,496.67, RO-08 fractional: branch
RO-02=1, RO-16=1, RO-08=1: bound 7,481.67, RO-07 fractional: branch
RO-02=1, RO-16=1, RO-08=1, RO-07=1: doesn't fit
RO-02=1, RO-16=1, RO-08=1, RO-07=0: bound 7,270.00, RO-13 fractional: branch
RO-02=1, RO-16=1, RO-08=1, RO-07=0, RO-13=1: bound 7,270.00 is a whole load: new best RO-02, RO-06, RO-08, RO-13, RO-16
RO-02=1, RO-16=1, RO-08=1, RO-07=0, RO-13=0: bound 7,258.00 <= best 7,270: prune
RO-02=1, RO-16=1, RO-08=0: bound 7,360.00, RO-13 fractional: branch
RO-02=1, RO-16=1, RO-08=0, RO-13=1: bound 7,360.00 is a whole load: new best RO-02, RO-06, RO-07, RO-13, RO-16
RO-02=1, RO-16=1, RO-08=0, RO-13=0: bound 7,348.00 <= best 7,360: prune
RO-02=1, RO-16=0: bound 7,530.00 is a whole load: new best RO-02, RO-06, RO-07, RO-08, RO-10
RO-02=0: bound 7,550.00, RO-13 fractional: branch
RO-02=0, RO-13=1: bound 7,550.00 is a whole load: new best RO-06, RO-07, RO-08, RO-13, RO-16
RO-02=0, RO-13=0: bound 7,538.00 <= best 7,550: prune
best 7,550: RO-06, RO-07, RO-08, RO-13, RO-16; 15 nodes instead of 65,536 combinations
Read the tree from the top. The root bound is $7,556.67 with RO-02 fractional. Taking RO-02 leads, after several branches, to loads worth $7,270, $7,360 and $7,530. Leaving RO-02 behind gives a whole load worth $7,550 at once, and that ends the search: the last open branch has a bound of $7,538, below $7,550. 15 nodes instead of 65,536 combinations. The bound is what lets the search skip almost everything.
26.2 A textbook branch and bound for any model
The same idea works for any Pyomo model: relax the integer variables, solve the LP, pick a fractional variable , and branch with and (for a binary at 0.6: and ). Create day26/bb.py:
"""Day 26: a textbook branch and bound for any Pyomo model with binary or integer variables.
No presolve, no cuts, no heuristics: just LP relaxations, branching and pruning, so you can watch the search.
Import it: from bb import branch_and_bound
"""
import heapq
import itertools
import math
import pyomo.environ as pyo
TOL = 1e-6
def branch_and_bound(m, order="best", max_nodes=10_000, gap=0.0, log=None):
"""Solve m by branch and bound. order: "best" (open node with the best bound first) or "depth" (newest node first).
Stops when no open node could beat the best plan by more than gap (a fraction of it), or after max_nodes nodes.
Returns the best value found, the proven bound, the number of nodes solved, and whether the search finished."""
ints = {v.name: v for v in m.component_data_objects(pyo.Var) if v.is_integer() and not v.fixed}
start = {n: (v.lb if v.lb is not None else 0, v.ub, v.domain) for n, v in ints.items()}
for v in ints.values():
v.domain = pyo.Reals # the LP relaxation: same bounds, any value in between
obj = next(m.component_data_objects(pyo.Objective, active=True))
sign = 1 if obj.sense == pyo.maximize else -1 # work as if maximizing: bigger is better
solver = pyo.SolverFactory("highs")
best, plan, nodes = -math.inf, None, 0
gap_pruned = -math.inf # the best bound among nodes dropped only because of the gap
tie = itertools.count()
todo = [(0, next(tie), math.inf, {})] # (priority, tie-break, parent's bound, {name: (lb, ub)})
def good_enough(bound):
nonlocal gap_pruned
if bound <= best + gap * abs(best) + TOL:
if bound > best + TOL:
gap_pruned = max(gap_pruned, bound)
return True
return False
while todo and nodes < max_nodes:
_, _, parent_bound, fixes = heapq.heappop(todo)
if good_enough(parent_bound):
continue # pruned without solving: a better plan is known already
nodes += 1
for n, v in ints.items():
lo, hi = fixes.get(n, start[n][:2])
v.setlb(lo)
v.setub(hi)
res = solver.solve(m, load_solutions=False)
if res.solver.termination_condition != pyo.TerminationCondition.optimal:
bound, status = None, "infeasible"
else:
m.solutions.load_from(res)
bound = sign * pyo.value(obj)
frac = [n for n, v in ints.items() if abs(pyo.value(v) - round(pyo.value(v))) > TOL]
if good_enough(bound):
status = "pruned by bound"
elif not frac:
best, plan = bound, {n: round(pyo.value(v)) for n, v in ints.items()}
status = "integer: new best"
else: # branch on the most fractional variable
n = max(frac, key=lambda n: (0.5 - abs(pyo.value(ints[n]) % 1 - 0.5), n))
x = pyo.value(ints[n])
lo, hi = fixes.get(n, start[n][:2])
for child in ({**fixes, n: (lo, math.floor(x))}, {**fixes, n: (math.ceil(x), hi)}):
k = next(tie)
heapq.heappush(todo, (-bound if order == "best" else -k, k, bound, child))
status = f"branch on {n} = {x:.3f}"
if log is not None:
log.append((nodes, len(fixes), "-" if bound is None else round(sign * bound, 2),
status, "-" if plan is None else round(sign * best, 2)))
still_open = [b for _, _, b, _ in todo if not good_enough(b)] # (also records open nodes within the gap)
proven = max([best, gap_pruned] + still_open)
for n, v in ints.items(): # put the model back, with the best plan loaded
v.domain = start[n][2]
v.setlb(start[n][0])
v.setub(start[n][1])
if plan is not None:
v.set_value(plan[n])
return {"value": sign * best, "bound": sign * proven, "nodes": nodes, "finished": not any(not good_enough(t[2]) for t in todo)}
Two choices shape the search. Which variable to branch on (here: the most fractional) and which node next: best first (the open node with the best bound) proves optimality fastest; depth first (the newest node) dives towards whole solutions and keeps few nodes in memory.
# ---------- 26.2 The same search on any Pyomo model ----------
for kg in (None, max_kg):
for order in ("best", "depth"):
m = build_knapsack(orders, pallets, max_kg=kg)
r = branch_and_bound(m, order=order)
print(f"{'pallets only' if kg is None else 'pallets and weight':<18} {order:>5} first: {r['value']:,.0f} "
f"in {r['nodes']} nodes")
log = []
branch_and_bound(build_knapsack(orders, pallets, max_kg=max_kg), log=log)
print("first nodes of the pallets-and-weight search (node, fixings, bound, what happened, best so far):")
for row in log[:8]:
print(" ", row)
pallets only best first: 7,550 in 5 nodes
pallets only depth first: 7,550 in 17 nodes
pallets and weight best first: 7,170 in 131 nodes
pallets and weight depth first: 7,170 in 257 nodes
first nodes of the pallets-and-weight search (node, fixings, bound, what happened, best so far):
(1, 0, 7315.0, 'branch on take[RO-16] = 0.875', '-')
(2, 1, 7289.97, 'branch on take[RO-03] = 0.312', '-')
(3, 1, 7307.74, 'branch on take[RO-07] = 0.940', '-')
(4, 2, 7133.3, 'branch on take[RO-03] = 0.979', '-')
(5, 2, 7307.14, 'branch on take[RO-14] = 0.490', '-')
(6, 3, 7296.67, 'branch on take[RO-06] = 0.333', '-')
(7, 3, 7293.75, 'branch on take[RO-08] = 0.932', '-')
(8, 4, 7295.82, 'branch on take[RO-03] = 0.073', '-')
Best first needs 5 nodes for one limit, 131 for two; depth first 17 and 257. The second limit makes the relaxation much less like a whole load, so the tree grows. Read the log: each node fixes one more variable, and the bound falls slowly from $7,315.
26.3 Cutting planes
Instead of branching, you can cut: add a constraint that every whole load satisfies but the current fractional solution breaks. For a knapsack, the classic cut is the cover inequality: if a set of orders together exceeds the truck, at most all-but-one of them can go.
# ---------- 26.3 A cutting plane ----------
m = build_knapsack(orders, pallets, domain=pyo.Reals)
pyo.SolverFactory("highs").solve(m)
print(f"relaxation {pyo.value(m.value):,.2f}:", {o: round(pyo.value(m.take[o]), 3) for o in m.O if pyo.value(m.take[o]) > 1e-6})
cover = [o for o in m.O if pyo.value(m.take[o]) > 1e-6]
print(f"cover {', '.join(cover)}: {orders.pallets[cover].sum()} pallets > {pallets}, so at most {len(cover) - 1} of them")
m.cover = pyo.Constraint(expr=sum(m.take[o] for o in cover) <= len(cover) - 1)
pyo.SolverFactory("highs").solve(m)
print(f"relaxation with the cut {pyo.value(m.value):,.2f}:",
{o: round(pyo.value(m.take[o]), 3) for o in m.O if pyo.value(m.take[o]) > 1e-6})
for kg in (None, max_kg):
for cut in (False, True):
k = build_knapsack(orders, pallets, max_kg=kg)
if cut:
k.cover = pyo.Constraint(expr=sum(k.take[o] for o in cover) <= len(cover) - 1)
print(f"{'pallets only' if kg is None else 'pallets and weight'}, {'with' if cut else 'without'} the cut: "
f"{branch_and_bound(k)['nodes']} nodes")
relaxation 7,556.67: {'RO-02': 0.667, 'RO-06': 1.0, 'RO-07': 1.0, 'RO-08': 1.0, 'RO-16': 1.0}
cover RO-02, RO-06, RO-07, RO-08, RO-16: 22 pallets > 20, so at most 4 of them
relaxation with the cut 7,550.00: {'RO-06': 1.0, 'RO-07': 1.0, 'RO-08': 1.0, 'RO-13': 1.0, 'RO-16': 1.0}
pallets only, without the cut: 5 nodes
pallets only, with the cut: 1 nodes
pallets and weight, without the cut: 131 nodes
pallets and weight, with the cut: 131 nodes
One cut makes the pallets-only relaxation a whole load: the best one, at the root, with no branching. With both limits, this one cut doesn't help: the relaxation moves to other fractions and other covers would be needed. Real solvers generate many families of cuts (covers, cliques, mixed-integer rounding, Gomory cuts) in rounds at the root and sometimes deeper. Branch and cut = branch and bound + cuts.
26.4 What HiGHS adds, and its controls
Now Day 23's capacitated location model (10 binaries for sites and 400 for store assignments):
# ---------- 26.4 What HiGHS adds ----------
sites, stores, lanes = load_sites(con)
m = build_location(sites, stores, lanes)
r = branch_and_bound(m, max_nodes=300)
print(f"Day 23 location, textbook search, 300 nodes: best ${r['value']:,.2f}, bound ${r['bound']:,.2f}, "
f"gap {100 * (r['value'] - r['bound']) / r['value']:.1f}%")
for opts in ({}, {"presolve": "off"}, {"presolve": "off", "mip_heuristic_effort": 0.0}):
h = run_highs(build_location(sites, stores, lanes), **opts)
print(f"Day 23 location, HiGHS {opts or 'defaults'}: ${h['objective']:,.2f} proven in {h['nodes']} node(s)")
Day 23 location, textbook search, 300 nodes: best $95,148.96, bound $91,048.80, gap 4.3%
Day 23 location, HiGHS defaults: $92,492.76 proven in 1 node(s)
Day 23 location, HiGHS {'presolve': 'off'}: $92,492.76 proven in 1 node(s)
Day 23 location, HiGHS {'presolve': 'off', 'mip_heuristic_effort': 0.0}: $92,492.76 proven in 1 node(s)
After 300 nodes, the textbook search has a plan costing $95,148.96 and a gap of 4.3%. HiGHS proves $92,492.76 at the root, even with presolve and its heuristics turned off: its cuts close the gap. What a modern solver adds to the textbook method:
| Component | What it does |
|---|---|
| Presolve | Removes and tightens variables and rows before the search (fixed variables, redundant rows, tighter bounds and big-Ms) |
| Cuts | Tightens the relaxation at the root (covers, cliques, Gomory, MIR…) |
| Heuristics | Finds good whole plans early (rounding, feasibility jump, RINS, RENS…), so pruning starts early |
| Branching rules | Pseudo-costs: branch on variables that moved the bound most in the past |
| Symmetry handling | Detects interchangeable variables (Day 27) |
| Restarts, conflict analysis | Learns from infeasible nodes, restarts with what was learned |
Not every model falls at the root. The Tuesday before Christmas, Montreal has 48 orders and the thaw limit of 16,000 kg applies:
xmas = con.sql("SELECT * FROM christmas_orders ORDER BY order_id").df().set_index("order_id")
trailer, kg16 = con.sql("SELECT pallet_positions, max_kg FROM truck_spec WHERE truck_type = 'trailer'").fetchall()[0][0], 16000
ffd = first_fit_decreasing(xmas.pallets.to_dict(), trailer, xmas.weight_kg.to_dict(), kg16)
print(f"Christmas Tuesday: {len(xmas)} orders; at least {xmas.pallets.sum() / trailer:.2f} trailers by pallets, "
f"{xmas.weight_kg.sum() / kg16:.2f} by weight; first fit decreasing {len(ffd)}")
for opts in ({"mip_max_nodes": 200}, {"mip_max_nodes": 2000}, {"mip_rel_gap": 0.07}):
h = run_highs(build_packing(xmas, trailer, len(ffd), max_kg=kg16), **opts)
print(f" HiGHS {opts}: {h['status']}, {h['objective']:.0f} trailers, bound {h['bound']:.2f}, "
f"gap {h['gap_pct']:.2f}%, {h['nodes']} nodes")
Christmas Tuesday: 48 orders; at least 13.27 trailers by pallets, 14.73 by weight; first fit decreasing 16
HiGHS {'mip_max_nodes': 200}: Solution limit reached, 16 trailers, bound 15.00, gap 6.25%, 244 nodes
HiGHS {'mip_max_nodes': 2000}: Solution limit reached, 16 trailers, bound 15.00, gap 6.25%, 2093 nodes
HiGHS {'mip_rel_gap': 0.07}: Optimal, 16 trailers, bound 15.00, gap 6.25%, 1 nodes
HiGHS finds 16 trailers at once and proves no plan needs fewer than 15 (the weight bound, 14.73, rounded up), but after 2,000 nodes it still can't tell whether 15 is possible. The gap is 1 trailer in 16: 6.25%. Three controls decide when to stop:
mip_rel_gap(default 0.01%): stop when the gap is below this. At 7% HiGHS stops at once and calls 16 "optimal": within tolerance, not proven best.mip_max_nodes(andtime_limit): stop after so many nodes (or seconds) and keep the best plan found. Node limits give the same answer on every run; time limits depend on the computer.mip_abs_gap: the same in the objective's units. For trailers, any gap below 1 means proven.
Day 27 finishes the Christmas problem. (Node counts can differ slightly on your computer, with a different number of threads.)
The planted bug
day26/bug_bound.py speeds up the hand-made search with a "quicker" bound. Run it.
def quick_bound(orders, capacity, fixed):
room = capacity - sum(orders[o][0] for o, f in fixed.items() if f == 1)
if room < 0:
return None, None
value = 0
for o in sorted((o for o in orders if o not in fixed), key=lambda o: (-orders[o][1] / orders[o][0], o)):
pallets, v = orders[o]
if pallets <= room:
room -= pallets
value += v
else:
return value + v * room / pallets, (o if room > 0 else None)
return value, None
What happens, and why
best 7,440: RO-04, RO-06, RO-07, RO-08, RO-10, RO-16; 21 nodes
$7,440, the dispatcher's greedy load from Day 24, not the best one. quick_bound starts value at 0 and forgets the value of the orders already fixed on the truck. Its bounds are too low, so branches containing better loads look worse than the best so far and are pruned. A bound must never be below what the branch can really reach (for a maximization). A wrong bound doesn't crash: it silently prunes the optimum. Test a search against a brute-force answer on small cases (Day 9's known-answer tests).
Mini-project: how good is good enough?
Run the textbook search on the rush truck with both limits, best first and depth first, stopping (a) at gaps of 0%, 1%, 2% and 5%, and (b) after 10, 25 and 50 nodes. Report nodes, the best load found and the proven bound. What does each stopping rule buy?
Solution
"""Day 26 mini-project: how good is good enough? Stop the textbook search at a gap, or after a number of nodes,
on the rush truck with both limits.
Run from the repository root (after day06/load_tables.py): python day26/mini_project_gap.py
"""
import sys
import duckdb
import pandas as pd
for folder in ("day24", "day26"):
sys.path.insert(0, folder)
from bb import branch_and_bound
from knapsack import build_knapsack
con = duckdb.connect("northbound.duckdb", read_only=True)
orders = con.sql("SELECT * FROM rush_orders ORDER BY order_id").df().set_index("order_id")
pallets, max_kg = con.sql("SELECT pallet_positions, max_kg FROM truck_spec WHERE truck_type = 'straight'").fetchall()[0]
rows = []
for order in ("best", "depth"):
for gap in (0.0, 0.01, 0.02, 0.05):
r = branch_and_bound(build_knapsack(orders, pallets, max_kg=max_kg), order=order, gap=gap)
rows.append((order, f"gap {gap:.0%}", r["nodes"], r["value"], r["bound"]))
for limit in (10, 25, 50):
r = branch_and_bound(build_knapsack(orders, pallets, max_kg=max_kg), order=order, max_nodes=limit)
rows.append((order, f"{limit} nodes", r["nodes"], r["value"], r["bound"]))
t = pd.DataFrame(rows, columns=["search", "stop at", "nodes", "best_found", "proven_bound"])
t["best_found"] = t.best_found.map(lambda v: "none" if v == float("-inf") else f"{v:,.0f}")
t["proven_bound"] = t.proven_bound.round(2)
print(t.to_string(index=False))
search stop at nodes best_found proven_bound
best gap 0% 131 7,170 7170.00
best gap 1% 59 7,170 7241.11
best gap 2% 54 7,170 7247.14
best gap 5% 54 7,170 7247.14
best 10 nodes 10 none 7295.82
best 25 nodes 25 none 7276.20
best 50 nodes 50 none 7249.17
depth gap 0% 257 7,170 7170.00
depth gap 1% 137 7,170 7241.11
depth gap 2% 115 7,170 7307.74
depth gap 5% 67 7,170 7315.00
depth 10 nodes 10 none 7315.00
depth 25 nodes 25 none 7315.00
depth 50 nodes 50 6,690 7315.00
- A gap of 1% halves the work (59 nodes instead of 131) and here still finds the best load, $7,170. The bound says only that no load beats $7,241: the last 1% is what proof costs.
- Best first finds no load at all in 50 nodes: it keeps exploring the most promising fractional nodes. Depth first finds a load ($6,690) by node 50, but its bound stays at the root's $7,315. Each search is good at one half of the job: dives find plans, best-first proves them. Real solvers mix both, and add heuristics so a good plan appears in the first seconds.
- For a manager: always report the plan and the gap ("this plan costs at most 2% more than the best possible"). An "optimal" plan with a 5% tolerance is a 5%-plan.
Commit
git add .
git commit -m "Day 26: branch and bound, cuts, solver controls"
git push
Day 26 checklist
- I can run branch and bound by hand: relax, branch, bound, prune.
- I know best-first and depth-first search, and what each is good at.
- I can write a cover cut and say why it is valid.
- I can name what presolve, cuts, heuristics and symmetry handling add to the textbook method.
- I can set
mip_rel_gapand node limits, and report a plan with its gap. - I know a bound that is too low prunes the optimum silently.