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 Days 28–30: christmas_week_orders (Montreal's orders for December 21–24, Day 28), flour_discounts, flour_all_units_offer, flour_delivery and overtime_tiers (Day 29), network_options and network_settings (expansions and planning settings for the capstone, Day 30).
Optional: Gurobi
Gurobi is optional in this course. pip install gurobipy==14.0.0 installs it with a free licence limited to 2,000 variables and 2,000 constraints: enough for today's models, not for the Day 30 capstone. Students can get a full academic licence from Gurobi's website. Every script runs without it and says so.
28.1 Measure: five seeds, one model
A MIP solver makes many arbitrary choices (ties between branching variables, the order of cuts), and a random seed decides them. Changing the seed changes nothing about the problem, so it is the honest way to see how much luck is in one run. Measure nodes and LP iterations, not seconds: they are the same on every run of the same seed, while seconds depend on the computer and whatever else it is doing.
run_highs (Day 26) now also returns the LP iterations. Create day28/tuning.py:
import sys
import duckdb
import pandas as pd
for folder in ("day24", "day26", "day28"):
sys.path.insert(0, folder)
from gurobi_run import have_gurobi, run_gurobi
from highs_run import run_highs
from loads import lower_bound
from packing import build_packing
pd.set_option("display.width", 160)
con = duckdb.connect("northbound.duckdb", read_only=True)
orders = con.sql("SELECT * FROM christmas_orders ORDER BY order_id").df().set_index("order_id")
capacity = con.sql("SELECT pallet_positions FROM truck_spec WHERE truck_type = 'trailer'").fetchall()[0][0]
MAX_KG, SEEDS = 16000, range(5)
def runs(solver, run, n, **options):
rows = []
for seed in SEEDS:
seed_option = {"random_seed": seed} if solver == "HiGHS" else {"Seed": seed}
r = run(build_packing(orders, capacity, n, max_kg=MAX_KG), **seed_option, **options)
rows.append((solver, n, seed, r["status"], round(r["objective"]), round(r["bound"], 2), r["nodes"], r["lp_iterations"]))
return rows
cols = ["solver", "trailers_allowed", "seed", "status", "trailers", "bound", "nodes", "lp_iterations"]
# ---------- 28.1 Measure: five seeds, same model ----------
print("--- HiGHS, 16 trailers allowed (as on Day 27)")
t = pd.DataFrame(runs("HiGHS", run_highs, 16, mip_max_nodes=20_000), columns=cols)
print(t.to_string(index=False))
print(f"nodes: median {t.nodes.median():,.0f}, smallest {t.nodes.min():,}, largest {t.nodes.max():,}")
--- HiGHS, 16 trailers allowed (as on Day 27)
solver trailers_allowed seed status trailers bound nodes lp_iterations
HiGHS 16 0 Optimal 15 15.0 2161 38901
HiGHS 16 1 Optimal 15 15.0 16124 253217
HiGHS 16 2 Optimal 15 15.0 1 1198
HiGHS 16 3 Optimal 15 15.0 4166 90431
HiGHS 16 4 Optimal 15 15.0 11001 216987
nodes: median 4,166, smallest 1, largest 16,124
Same model, same answer (15 trailers), and the work ranges from 1 node to 16,124. One run tells you almost nothing about a model's speed. Report the median and the worst case over several seeds, and compare models on the same seeds.
28.2 A smaller model: size it with the bound
The model allows 16 trailers (first fit decreasing's count), so every plan with 15 has many copies: any of the 16 trailers can be the empty one. The weight bound says at least 15 are needed. Ask a smaller question: is 15 possible? Allow exactly 15 trailers; if the solver proves that infeasible, try 16. Create day28/loads.py:
"""Day 28: the fewest trailers for a day's orders, found by sizing the model with the lower bound.
Import it: from loads import lower_bound, fewest_trailers
"""
import math
from packing import build_packing
def lower_bound(orders, capacity, max_kg):
return max(math.ceil(orders.pallets.sum() / capacity), math.ceil(orders.weight_kg.sum() / max_kg))
def fewest_trailers(orders, capacity, max_kg, run, max_tries=3, **options):
"""Try n = lower bound trailers; if the solver proves n impossible, try n + 1, and so on.
run is run_highs or run_gurobi; options go to the solver. Returns (trailers, proven, total nodes, tries)."""
n, nodes = lower_bound(orders, capacity, max_kg), 0
for tries in range(1, max_tries + 1):
r = run(build_packing(orders, capacity, n, max_kg=max_kg), **options)
nodes += max(r["nodes"], 0)
if r["status"] == "Optimal":
return n, True, nodes, tries
if r["status"] != "Infeasible":
return None, False, nodes, tries # stopped by a limit: no answer either way
n += 1
return None, False, nodes, max_tries
# ---------- 28.2 A smaller model: allow only as many trailers as the bound ----------
n = lower_bound(orders, capacity, MAX_KG)
print(f"--- HiGHS, lower bound: {n} trailers allowed")
t = pd.DataFrame(runs("HiGHS", run_highs, n, mip_max_nodes=20_000), columns=cols)
print(t.to_string(index=False))
print(f"nodes: median {t.nodes.median():,.0f}, smallest {t.nodes.min():,}, largest {t.nodes.max():,}")
--- HiGHS, lower bound: 15 trailers allowed
solver trailers_allowed seed status trailers bound nodes lp_iterations
HiGHS 15 0 Optimal 15 15.0 2352 64871
HiGHS 15 1 Optimal 15 15.0 1694 39965
HiGHS 15 2 Optimal 15 15.0 1586 32442
HiGHS 15 3 Optimal 15 15.0 0 12494
HiGHS 15 4 Optimal 15 15.0 0 9732
nodes: median 1,586, smallest 0, largest 2,352
The median falls from 4,166 nodes to 1,586, and the worst case from 16,124 to 2,352. Fewer trailers means fewer variables and fewer equivalent plans. The best speed-ups usually come from the model, not from solver settings: tighter formulations (Day 27), smaller index sets, better bounds.
28.3 Gurobi (optional)
def run_gurobi(m, **params):
"""Write the model as an LP file, solve it with Gurobi on one thread with the given parameters
(for example Seed=1, NodeLimit=20000, MIPGap=0.01), and return what the solver reports."""
path = os.path.join(tempfile.mkdtemp(), "model.lp")
m.write(path, io_options={"symbolic_solver_labels": True})
env = gp.Env(params={"OutputFlag": 0})
g = gp.read(path, env)
g.Params.Threads = 1
for k, v in params.items():
g.setParam(k, v)
g.optimize()
status = {gp.GRB.OPTIMAL: "Optimal", gp.GRB.NODE_LIMIT: "Node limit", gp.GRB.INFEASIBLE: "Infeasible",
gp.GRB.TIME_LIMIT: "Time limit"}.get(g.Status, str(g.Status))
return {"status": status, "objective": g.ObjVal if g.SolCount else float("nan"), "bound": g.ObjBound,
"gap_pct": 100 * g.MIPGap if g.SolCount else float("inf"), "nodes": int(g.NodeCount),
"lp_iterations": int(g.IterCount)}
# ---------- 28.3 Gurobi (optional) ----------
if have_gurobi():
print("--- Gurobi, one thread")
t = pd.DataFrame(runs("Gurobi", run_gurobi, 16, NodeLimit=20_000) + runs("Gurobi", run_gurobi, n, NodeLimit=20_000),
columns=cols)
print(t.to_string(index=False))
print(t.groupby("trailers_allowed").nodes.agg(["median", "min", "max"]).to_string())
else:
print("gurobipy is not installed: skipping Gurobi (pip install gurobipy for the free size-limited licence)")
--- Gurobi, one thread
solver trailers_allowed seed status trailers bound nodes lp_iterations
Gurobi 16 0 Node limit 16 15.0 20000 72130
Gurobi 16 1 Optimal 15 15.0 5183 22059
Gurobi 16 2 Optimal 15 15.0 4790 26509
Gurobi 16 3 Node limit 16 15.0 20000 70036
Gurobi 16 4 Optimal 15 15.0 14361 69260
Gurobi 15 0 Optimal 15 15.0 1 1924
Gurobi 15 1 Optimal 15 15.0 159 3238
Gurobi 15 2 Optimal 15 15.0 261 3082
Gurobi 15 3 Optimal 15 15.0 1321 12831
Gurobi 15 4 Optimal 15 15.0 1036 10693
median min max
trailers_allowed
15 261.0 1 1321
16 14361.0 4790 20000
(Run on one thread so the counts are repeatable; yours may differ.) Two lessons:
- On the 16-trailer model, Gurobi is not faster here: two seeds out of five stop at the 20,000-node limit without proving 15. Commercial solvers are usually faster on large, hard models, often by a wide margin. On any one model, measure.
- On the bound-sized model, Gurobi's worst case is 1,321 nodes, its median 261. The reformulation helped both solvers. A better model is worth more than a better solver.
Decision it supports: which solver and model to put into a planning process, based on evidence instead of reputation.
Other decisions you can support the same way: whether a commercial licence pays for itself · which settings a production system should use · how long planners must wait for a plan.
28.4 A speed checklist
When a MIP is slow, work down this list, measuring over several seeds at each step:
- Is it the model? Tight links, the smallest valid big-M, no needless symmetry (Day 27). Smaller index sets (28.2).
- Bounds. Give every variable the tightest bounds you know (capacities, demand caps).
- A starting plan. If you have a good plan (yesterday's, a heuristic's), pass it to the solver as a warm start, so pruning starts at once.
- Stopping rules. Agree a gap with the business (Day 26): proving the last 0.1% can take most of the time.
- Solver settings. Heuristic effort, cut effort, threads. Change one at a time, test on several instances.
- Another solver. Last, and measured, not assumed.
The planted bug
day28/bug_gap.py asks for Christmas Tuesday "to within 0.1%". Run it.
con = duckdb.connect("northbound.duckdb", read_only=True)
orders = con.sql("SELECT * FROM christmas_orders ORDER BY order_id").df().set_index("order_id")
r = run_highs(build_packing(orders, 26, 16, max_kg=16000), mip_rel_gap=0.1)
print(f"{r['status']}: {r['objective']:.0f} trailers")
What happens, and why
Optimal: 16 trailers
16 trailers, "Optimal". mip_rel_gap is a fraction: 0.1 means 10%, and 16 trailers against a bound of 15 is a 6.25% gap, inside the tolerance. 0.1% is mip_rel_gap=0.001. Gurobi's MIPGap is also a fraction. Whenever a status says "Optimal", check the gap you asked for, and read the bound.
Mini-project: Christmas week
Montreal ships on December 21, 22, 23 and 24, all under the 16,000 kg limit. For each day, compare first fit decreasing with the bound-sized model (fewest_trailers), using HiGHS (and Gurobi if you have it). How many trailers does the model save over the week?
Solution
"""Day 28 mini-project: Christmas week. Four days of Montreal orders under the 16,000 kg limit:
first fit decreasing against the bound-sized model, with each solver.
Run from the repository root (after day06/load_tables.py): python day28/mini_project_week.py
"""
import sys
import duckdb
import pandas as pd
for folder in ("day24", "day26", "day28"):
sys.path.insert(0, folder)
from gurobi_run import have_gurobi, run_gurobi
from highs_run import run_highs
from loads import fewest_trailers, lower_bound
from packing import first_fit_decreasing
pd.set_option("display.width", 160)
con = duckdb.connect("northbound.duckdb", read_only=True)
week = con.sql("SELECT * FROM christmas_week_orders ORDER BY ship_date, order_id").df()
capacity, cost = con.sql("SELECT pallet_positions, cost_per_day FROM truck_spec WHERE truck_type = 'trailer'").fetchall()[0]
MAX_KG = 16000
solvers = [("HiGHS", run_highs, {"mip_max_nodes": 20_000})]
if have_gurobi():
solvers.append(("Gurobi", run_gurobi, {"NodeLimit": 20_000}))
rows = []
for day, orders in week.groupby("ship_date"):
orders = orders.set_index("order_id")
ffd = len(first_fit_decreasing(orders.pallets.to_dict(), capacity, orders.weight_kg.to_dict(), MAX_KG))
row = [str(day)[:10], len(orders), lower_bound(orders, capacity, MAX_KG), ffd]
for name, run, options in solvers:
trailers, proven, nodes, tries = fewest_trailers(orders, capacity, MAX_KG, run, **options)
row += [trailers, nodes]
rows.append(row)
cols = ["ship_date", "orders", "bound", "ffd"] + [f"{name.lower()}_{c}" for name, *_ in solvers for c in ("trailers", "nodes")]
t = pd.DataFrame(rows, columns=cols)
print(t.to_string(index=False))
saved = (t.ffd - t.highs_trailers).sum()
print(f"the model saves {saved} trailers in the week: ${saved * cost:,}")
ship_date orders bound ffd highs_trailers highs_nodes gurobi_trailers gurobi_nodes
2026-12-21 44 16 16 16 1 16 1
2026-12-22 48 15 16 15 2352 15 1
2026-12-23 52 18 18 18 1 18 1
2026-12-24 40 16 17 16 4464 16 2739
the model saves 2 trailers in the week: $1,300
- On Monday and Wednesday, first fit decreasing already meets the bound: nothing to gain, and the model proves it in one node.
- On Tuesday and Thursday the model saves a trailer each: $1,300 for the week.
- With the model sized by the bound, both solvers answer every day within a few thousand nodes, and the answer is proven: no plan uses fewer trailers.
Note to transport planning: "For Christmas week, plan loads with the bound-sized model. It saves 2 trailers ($1,300) over first fit decreasing and proves that no loading uses fewer. Allow a 20,000-node limit per day; it was never reached."
Commit
git add .
git commit -m "Day 28: measuring and speeding up MIPs, HiGHS vs Gurobi"
git push
Day 28 checklist
- I measure solver work in nodes and LP iterations over several seeds, not one run in seconds.
- I can make a model smaller using a bound (fix the number of trailers, then increase).
- I can run the same Pyomo model with HiGHS and, optionally, Gurobi.
- I know reformulating usually helps more than switching solvers.
- I know
mip_rel_gapis a fraction, and check the gap behind every "Optimal".