27.1 Strong and weak links
A formulation is stronger than another if its relaxation allows fewer fractional points while keeping the same whole-number plans. Its root bound is closer to the best plan, so the search prunes earlier. Create day27/tighten.py, with functions that change Module 3's models:
"""Day 27: tighter formulations. Helpers to weaken, tighten and de-symmetrize the Module 3 models.
Import it: from tighten import weak_link, total_capacity, break_symmetry, root_bound
"""
import pyomo.environ as pyo
def weak_link(m):
"""Facility location with one linking row per site instead of one per site and store:
sum_j serve[i, j] <= (number of stores) * open[i]. Same integer plans, weaker relaxation."""
m.del_component(m.only_if_open)
m.only_if_open = pyo.Constraint(m.I, rule=lambda m, i: sum(m.serve[i, j] for j in m.J) <= len(m.J) * m.open[i])
return m
def total_capacity(m, sites, stores, margin=1.0):
"""A valid inequality (with margin=1): the sites that open must have room for all the pallets together."""
m.total_capacity = pyo.Constraint(expr=sum(sites.capacity_pallets[i] * m.open[i] for i in m.I)
>= margin * stores.pallets_per_week.sum())
return m
def break_symmetry(m):
"""Bin packing: trucks are identical, so (1) use trucks in order: use[k] >= use[k+1]; and
(2) order number i (counting from 1) goes on one of the first i trucks."""
trucks = list(m.K)
m.in_order = pyo.Constraint(trucks[:-1], rule=lambda m, k: m.use[k] >= m.use[k + 1])
for i, o in enumerate(m.O, start=1):
for k in trucks:
if k > i:
m.put[o, k].fix(0)
return m
def root_bound(m):
"""The LP relaxation's value: relax every integer variable, solve, then put the domains back."""
ints = [v for v in m.component_data_objects(pyo.Var) if v.is_integer()]
saved = [(v.domain, v.lb, v.ub) for v in ints]
for v, (_, lb, ub) in zip(ints, saved):
v.domain = pyo.Reals # any value between the variable's bounds (0 and 1 for a binary)
v.setlb(lb)
v.setub(ub)
pyo.SolverFactory("highs").solve(m)
value = pyo.value(next(m.component_data_objects(pyo.Objective, active=True)))
for v, (d, lb, ub) in zip(ints, saved):
v.domain = d
v.setlb(lb)
v.setub(ub)
return value
weak_link replaces Day 23's 400 rows with 10 rows . Same whole-number plans: if a site is closed, it serves nobody; if open, it may serve all 40 stores. But in the relaxation, lets a site serve four whole stores. Create day27/formulations.py:
def measure(name, make, max_nodes=10_000):
root = root_bound(make())
r = branch_and_bound(make(), max_nodes=max_nodes)
h = run_highs(make())
found = "none" if abs(r["value"]) == float("inf") else round(r["value"], 2)
return (name, round(root, 2), found, round(r["bound"], 2), r["nodes"], "yes" if r["finished"] else "no",
round(h["objective"], 2), h["nodes"])
cols = ["formulation", "root_bound", "textbook_best", "textbook_bound", "textbook_nodes", "finished", "highs", "highs_nodes"]
# ---------- 27.1 Strong and weak links ----------
print("--- uncapacitated location")
rows = [measure("strong: serve[i,j] <= open[i]", lambda: build_location(sites, stores, lanes, capacitated=False)),
measure("weak: sum_j serve[i,j] <= 40 open[i]", lambda: weak_link(build_location(sites, stores, lanes, capacitated=False)))]
print(pd.DataFrame(rows, columns=cols).to_string(index=False))
--- uncapacitated location
formulation root_bound textbook_best textbook_bound textbook_nodes finished highs highs_nodes
strong: serve[i,j] <= open[i] 85450.50 85450.5 85450.5 1 yes 85450.5 1
weak: sum_j serve[i,j] <= 40 open[i] 37636.36 85450.5 85450.5 145 yes 85450.5 1
On the uncapacitated model, the strong link's relaxation is already the best plan ($85,450.50, 1 node). The weak link's root bound is $37,636.36, less than half, and the textbook search needs 145 nodes. HiGHS solves both at the root: its presolve and cuts rebuild what the weak formulation threw away. On large models they can't always, so write the strong form.
Fewer rows is not better. The strong form has 400 linking rows instead of 10, and solves far faster.
27.2 Big-M, again
Day 22 showed that a large M weakens the relaxation. Now count the nodes:
# ---------- 27.2 Big-M, again ----------
d = load_data(con)
setup = con.sql("SELECT * FROM bakery_range_setup").df().set_index("sku")
print("--- set-up model (Day 22)")
rows = [measure(f"M = {label}", lambda M=M: build_with_setups(d, setup, big_m=M))
for label, M in [("demand cap", None), ("100", 100), ("10,000", 10_000), ("1,000,000", 1_000_000)]]
print(pd.DataFrame(rows, columns=cols).to_string(index=False))
--- set-up model (Day 22)
formulation root_bound textbook_best textbook_bound textbook_nodes finished highs highs_nodes
M = demand cap 102372.08 102242.38 102242.38 11 yes 102242.38 1
M = 100 107076.82 102242.38 102242.38 1065 yes 102242.38 1
M = 10,000 108338.54 102242.38 102242.38 1557 yes 102242.38 1
M = 1,000,000 108351.15 102242.38 102242.38 1543 yes 102242.38 1
11 nodes with M = each product's demand cap; over 1,000 with M = 100 or more. Same answer every time. HiGHS needs 1 node for all four: its presolve and cuts tighten what a loose M leaves loose. Don't count on that when M multiplies something the solver can't bound.
27.3 Symmetry
In bin packing, trailers are identical: any plan can be relabelled by swapping trailer 1 and trailer 3, and the relaxation can't tell the copies apart. The search explores each copy of every dead end. Symmetry breaking keeps one copy: use trailers in order (), and put order number on one of the first trailers (any plan can be relabelled this way).
# ---------- 27.3 Symmetry ----------
orders = con.sql("SELECT * FROM truck_orders ORDER BY order_id LIMIT 8").df().set_index("order_id")
trailer = con.sql("SELECT pallet_positions FROM truck_spec WHERE truck_type = 'trailer'").fetchall()[0][0]
n = len(first_fit_decreasing(orders.pallets.to_dict(), trailer, orders.weight_kg.to_dict(), 16000))
print(f"--- bin packing: first 8 Tuesday orders, 16,000 kg limit, {n} trucks available")
rows = [measure("trucks interchangeable", lambda: build_packing(orders, trailer, n, max_kg=16000)),
measure("with symmetry breaking", lambda: break_symmetry(build_packing(orders, trailer, n, max_kg=16000)))]
print(pd.DataFrame(rows, columns=cols).to_string(index=False))
--- bin packing: first 8 Tuesday orders, 16,000 kg limit, 4 trucks available
formulation root_bound textbook_best textbook_bound textbook_nodes finished highs highs_nodes
trucks interchangeable 2.65 3.0 3.0 3581 yes 3.0 1
with symmetry breaking 2.65 3.0 3.0 491 yes 3.0 1
With only 8 orders and 4 trailers, the textbook search needs 3,581 nodes to prove that 3 trailers is the minimum; with symmetry breaking, 491. HiGHS detects the symmetry itself and solves both at the root.
27.4 Capacitated location: four formulations
Back to Day 23's capacitated, single-sourced model, with a second idea: a valid inequality. Any whole plan must open enough capacity for all pallets: . It cuts off no whole plan, so it is safe to add, and it may cut off fractional ones.
# ---------- 27.4 Capacitated location: four formulations ----------
print("--- capacitated location (Day 23)")
rows = [measure(name, make, max_nodes=300) for name, make in [
("weak link", lambda: weak_link(build_location(sites, stores, lanes))),
("weak link + total capacity", lambda: total_capacity(weak_link(build_location(sites, stores, lanes)), sites, stores)),
("strong link (Day 23)", lambda: build_location(sites, stores, lanes)),
("strong link + total capacity", lambda: total_capacity(build_location(sites, stores, lanes), sites, stores))]]
print(pd.DataFrame(rows, columns=cols).to_string(index=False))
--- capacitated location (Day 23)
formulation root_bound textbook_best textbook_bound textbook_nodes finished highs highs_nodes
weak link 72158.68 none 90501.30 300 no 92492.76 0
weak link + total capacity 72158.68 none 90396.27 300 no 92492.76 5
strong link (Day 23) 89717.62 95148.96 91048.80 300 no 92492.76 1
strong link + total capacity 89717.62 92974.23 90942.86 300 no 92492.76 1
- The weak link's root bound is $72,158.68; the strong link's $89,717.62, 3% from the best plan.
- In 300 nodes, the textbook search finds no plan at all with the weak link. With the strong link it finds $95,148.96; adding the total-capacity inequality, $92,974.23, about 0.5% above the best.
- Here the inequality doesn't move the root bound (the relaxation already opens enough capacity), but it changes the path of the search: with the strong link it found a better plan in the same 300 nodes.
- HiGHS: 1 node with the strong link, up to 5 with the weak one.
The planted bug
day27/bug_cut.py adds the total-capacity inequality "with a 10% safety margin". Run it.
con = duckdb.connect("northbound.duckdb", read_only=True)
sites, stores, lanes = load_sites(con)
m = total_capacity(build_location(sites, stores, lanes), sites, stores, margin=1.10)
pyo.SolverFactory("highs").solve(m)
print(f"optimal: ${pyo.value(m.cost):,.2f} a week = fixed ${pyo.value(m.fixed):,.0f} + transport ${pyo.value(m.transport):,.2f}")
print(summary(m, sites, stores).to_string(index=False))
What happens, and why
optimal: $95,148.96 a week = fixed $64,500 + transport $30,648.96
site place open stores pallets capacity
DC-MIS Mississauga 1.0 15 1195.0 1600
DC-MTL Montreal 1.0 15 1380.0 1500
DC-OTT Ottawa 1.0 7 685.0 700
NEW-QUE Quebec City 1.0 3 285.0 700
"Optimal", $95,148.96 a week: Quebec City opens, $2,656 a week more than the real best plan. Today's three DCs have 3,800 pallets of capacity, only 7% more than the 3,545 needed, so a 10% margin forbids the best plan. The inequality is not valid: it changes the problem instead of tightening it. A cut must hold for every whole plan you would accept. If you want a safety margin, that is a business rule: write it as one, report it as one, and price it (here $2,656 a week).
Mini-project: Christmas Tuesday, solved
Day 26 left Christmas Tuesday at 16 trailers with a bound of 15 after 2,000 nodes. Give HiGHS 20,000 nodes and compare three orderings of the orders (as listed, heaviest first, most pallets first), each with and without break_symmetry. Then report the plan and what it saves.
Solution
"""Day 27 mini-project: Christmas Tuesday, solved. Day 26 left it at 16 trailers with a bound of 15.
Run from the repository root (after day06/load_tables.py): python day27/mini_project_christmas.py
"""
import sys
import duckdb
import pyomo.environ as pyo
for folder in ("day24", "day26", "day27"):
sys.path.insert(0, folder)
from highs_run import run_highs
from packing import build_packing, first_fit_decreasing, trucks_used
from tighten import break_symmetry
con = duckdb.connect("northbound.duckdb", read_only=True)
orders = con.sql("SELECT * FROM christmas_orders ORDER BY order_id").df().set_index("order_id")
trailer, cost = con.sql("SELECT pallet_positions, cost_per_day FROM truck_spec WHERE truck_type = 'trailer'").fetchall()[0]
n = len(first_fit_decreasing(orders.pallets.to_dict(), trailer, orders.weight_kg.to_dict(), 16000))
for name, sort_by in [("orders as listed", None), ("heaviest first", ["weight_kg", "pallets"]),
("most pallets first", ["pallets", "weight_kg"])]:
o = orders if sort_by is None else orders.sort_values(sort_by, ascending=False)
for sym in (False, True):
m = build_packing(o, trailer, n, max_kg=16000)
if sym:
break_symmetry(m)
h = run_highs(m, mip_max_nodes=20_000)
print(f"{name:<18} {'symmetry broken' if sym else 'as Day 24':<16} {h['status']:<24} {h['objective']:.0f} trailers, "
f"bound {h['bound']:.2f}, {h['nodes']:,} nodes")
m = break_symmetry(build_packing(orders.sort_values(["weight_kg", "pallets"], ascending=False), trailer, n, max_kg=16000))
pyo.SolverFactory("highs").solve(m)
plan = trucks_used(m, orders)
print(f"{len(plan)} trailers, ${len(plan) * cost:,} for the day (first fit decreasing: {n}, ${n * cost:,})")
print(plan.to_string(index=False))
orders as listed as Day 24 Optimal 15 trailers, bound 15.00, 2,161 nodes
orders as listed symmetry broken Optimal 15 trailers, bound 15.00, 8,963 nodes
heaviest first as Day 24 Optimal 15 trailers, bound 15.00, 1 nodes
heaviest first symmetry broken Optimal 15 trailers, bound 15.00, 3,575 nodes
most pallets first as Day 24 Optimal 15 trailers, bound 15.00, 1,642 nodes
most pallets first symmetry broken Optimal 15 trailers, bound 15.00, 4,970 nodes
15 trailers, $9,750 for the day (first fit decreasing: 16, $10,400)
truck orders pallets kg order_ids
1 2 25 15590 XO-24, XO-14
2 3 19 15530 XO-22, XO-46, XO-13
3 3 20 15290 XO-40, XO-19, XO-43
4 2 22 15830 XO-27, XO-02
5 3 20 15690 XO-11, XO-10, XO-23
6 3 25 15380 XO-03, XO-33, XO-21
7 3 24 15470 XO-25, XO-20, XO-34
8 3 20 15840 XO-44, XO-12, XO-16
9 3 24 15700 XO-05, XO-01, XO-36
10 3 26 15990 XO-17, XO-41, XO-06
11 4 22 15680 XO-18, XO-29, XO-47, XO-26
12 3 25 15910 XO-32, XO-39, XO-45
13 4 24 15960 XO-30, XO-38, XO-08, XO-48
14 4 26 15990 XO-28, XO-35, XO-04, XO-07
15 5 23 15860 XO-42, XO-09, XO-31, XO-37, XO-15
- 15 trailers is possible, and every variant proves it within 20,000 nodes. Day 26's 2,000 nodes stopped just short (the plain model needs 2,161). The plan saves one trailer, $650 for the day, over first fit decreasing.
- Symmetry breaking made HiGHS slower here (8,963 nodes instead of 2,161 as listed). HiGHS already handles symmetry its own way, and the added rows fight with it. A textbook improvement is not always an improvement for a modern solver: measure.
- The order of the rows changes everything: the same model, listed heaviest first, solves at the root; listed by pallets, 1,642 nodes. This is performance variability: small, meaningless changes send the solver down different paths. Never judge a formulation on one run of one instance; test several orderings or instances (or
random_seedvalues) before concluding.
Note to transport planning: "Plan Christmas loads with the model, with a 20,000-node limit: on the Tuesday before Christmas it saves a trailer over the current loading rule."
Commit
git add .
git commit -m "Day 27: formulation strength, symmetry, variability"
git push
Then run the tests: tests/test_search.py checks Days 24–27 (the knapsack three ways, the textbook search against HiGHS, cutting patterns, the cross-dock model against Day 16, weak and strong links). Add "day24" to "day27" to the folders in conftest.py.
"""Module 3, Days 24-27: knapsack, packing, cutting, cross-docks, branch and bound and formulations."""
import pyomo.environ as pyo
import pytest
from bakery import load_data
from bb import branch_and_bound
from by_hand import branch_and_bound_knapsack
from crossdocks import build_crossdocks, load_crossdock_network
from cutting import build_cutting, patterns
from facility import build_location, load_sites
from knapsack import build_knapsack, dp_knapsack
from setup_model import build_with_setups
from tighten import root_bound, weak_link
@pytest.fixture(scope="module")
def rush(con):
return con.sql("SELECT * FROM rush_orders ORDER BY order_id").df().set_index("order_id")
def test_knapsack_three_ways_agree(rush):
m = build_knapsack(rush, 20)
pyo.SolverFactory("highs").solve(m)
value, _ = dp_knapsack(rush.pallets.tolist(), rush.value_if_delivered.tolist(), 20)
hand = branch_and_bound_knapsack({o: (rush.pallets[o], rush.value_if_delivered[o]) for o in rush.index}, 20,
show=lambda line: None)
assert pyo.value(m.value) == value == hand["value"] == 7_550
def test_textbook_search_matches_highs(con, rush):
k = build_knapsack(rush, 20, max_kg=12_000)
assert branch_and_bound(k)["value"] == pytest.approx(7_170)
d = load_data(con)
setup = con.sql("SELECT * FROM bakery_range_setup").df().set_index("sku")
r = branch_and_bound(build_with_setups(d, setup))
assert r["finished"] and r["value"] == pytest.approx(102_242.38, abs=0.01)
def test_cutting_patterns_fit_and_cover_demand(con):
bars = con.sql("SELECT * FROM cake_bars").df().set_index("bar")
lengths, demand = bars.length_cm.to_dict(), bars.bars_per_week.to_dict()
pats = patterns(lengths, 120)
assert all(sum(p[b] * lengths[b] for b in p) <= 120 for p in pats)
m = build_cutting(pats, demand)
pyo.SolverFactory("highs").solve(m)
assert pyo.value(m.slabs) == pytest.approx(50)
def test_crossdocks_reproduce_day16_then_improve(con):
nodes, stores, xds, arcs = load_crossdock_network(con)
today = ("XD-KIN", "XD-TRV")
m = build_crossdocks(nodes, xds, arcs, trucks=False, allowed=today, forced=today)
pyo.SolverFactory("highs").solve(m)
assert pyo.value(m.cost) == pytest.approx(19_603.64, abs=0.01) # Day 16's answer
best = build_crossdocks(nodes, xds, arcs)
pyo.SolverFactory("highs").solve(best)
assert pyo.value(best.cost) == pytest.approx(18_757.88, abs=0.01)
assert [x for x in best.X if pyo.value(best.open[x]) > 0.5] == ["XD-DRU"]
def test_weak_link_has_weaker_bound_same_answer(con):
sites, stores, lanes = load_sites(con)
strong = build_location(sites, stores, lanes, capacitated=False)
weak = weak_link(build_location(sites, stores, lanes, capacitated=False))
assert root_bound(weak) < root_bound(strong) - 1_000
for m in (strong, weak):
pyo.SolverFactory("highs").solve(m)
assert pyo.value(weak.cost) == pytest.approx(pyo.value(strong.cost), abs=0.01)
45 passed
Day 27 checklist
- I can say what makes one formulation stronger than another, and measure it by the root bound.
- I prefer per-pair linking rows and the smallest valid M.
- I can break symmetry in bin packing, and know a modern solver may do it better itself.
- I can add a valid inequality, and check that it cuts off no plan I would accept.
- I compare formulations on several runs, because of performance variability.