Prescriptive Analytics & Decision Intelligence
Overview / Module 3 / Day 24
Module 3 · Integer and Combinatorial Optimization · Day 24 of 80

Knapsack, Bin Packing and Cutting Stock

Three classic integer problems run through every warehouse and bakery. The knapsack asks what fits in one container. Bin packing asks how few containers hold everything. Cutting stock asks how to cut standard pieces into the sizes customers want. Today you meet all three at Northbound: the Monday rush truck, Tuesday's trailers and the bakery's cake bars. Each time a quick rule of thumb does well, and a model does better or proves the rule of thumb can't be beaten.

▶
Video for Day 24 coming soon

In this lesson

Today's 5-hour plan

LessonProjectBreakCommit
0:00–0:45
24.1–24.3 The knapsack: the rush truck
0:45–1:45
24.4–24.5 Bin packing: Tuesday's trailers
1:45–2:00
Break
2:00–2:45
24.6–24.7 Cutting stock: cake bars from slabs
2:45–3:45
Relaxations of the three problems; a planted bug
3:45–4:00
Break
4:00–4:45
Mini-project: spring thaw
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 Days 24–27: truck_spec (a 26-pallet trailer and a 20-pallet straight truck, with weight limits and day costs), rush_orders (16 Monday top-up orders for Montreal stores), truck_orders (24 Tuesday orders), christmas_orders (48 orders for the Tuesday before Christmas, Days 26–27), cake_slab and cake_bars (sheet-cake slabs and the bars cut from them), crossdock_candidates and crossdock_arcs (six cross-dock sites for the chilled network, Day 25).

24.1 Greedy loading

Sixteen Montreal stores ran short over the weekend. Monday's rush truck (20 pallet positions, 12,000 kg) can carry some of their top-up orders; each order delivered saves the sales it brings (value_if_delivered). Which orders go? Create day24/knapsack.py. First, the dispatcher's rule: best value per pallet first, skipping what no longer fits.

    # ---------- 24.1 Greedy: best value per pallet first ----------
    room, greedy = pallets, []
    for o in orders.sort_values("value_per_pallet", ascending=False).index:
        if orders.pallets[o] <= room:
            greedy.append(o)
            room -= orders.pallets[o]
    print(f"greedy: {orders.value_if_delivered[greedy].sum():,} with {orders.pallets[greedy].sum()} pallets: {', '.join(sorted(greedy))}")
order_id
RO-01         S28        4       2800                 900            225.00
RO-02         S32        6       4280                2110            351.67
RO-03         S29        5       3300                1730            346.00
RO-04         S32        3       1840                 940            313.33
RO-05         S30        2       1240                 460            230.00
RO-06         S37        1        720                 380            380.00
RO-07         S38        6       4200                2390            398.33
RO-08         S28        6       3680                2300            383.33
RO-09         S38        1        530                 260            260.00
RO-10         S37        1        710                 350            350.00
RO-11         S31        4       2130                 790            197.50
RO-12         S32        4       2080                 800            200.00
RO-13         S29        4       1880                1400            350.00
RO-14         S39        1        490                 280            280.00
RO-15         S38        5       3450                1560            312.00
RO-16         S39        3       2000                1080            360.00
16 orders, 56 pallets, $17,730 of value; the rush truck takes 20 pallets and 12,000 kg
greedy: 7,440 with 20 pallets: RO-04, RO-06, RO-07, RO-08, RO-10, RO-16

24.2 The knapsack model

One binary per order, to=1t_o = 1 if order oo goes on the truck:

max⁡∑ovalueo tos.t.∑opalletso to≤20,to∈{0,1}\max \sum_o \text{value}_o\, t_o \quad \text{s.t.} \quad \sum_o \text{pallets}_o\, t_o \le 20, \qquad t_o \in \{0, 1\}
def build_knapsack(orders, pallets, max_kg=None, domain=pyo.Binary):
    """take[o] = 1 if order o goes on the trailer. Maximize the value delivered within the pallet positions
    (and, if max_kg is given, the weight limit)."""
    m = pyo.ConcreteModel(name="knapsack")
    m.O = pyo.Set(initialize=orders.index.tolist())
    m.take = pyo.Var(m.O, within=domain, bounds=(0, 1))
    m.positions = pyo.Constraint(expr=sum(orders.pallets[o] * m.take[o] for o in m.O) <= pallets)
    if max_kg is not None:
        m.weight = pyo.Constraint(expr=sum(orders.weight_kg[o] * m.take[o] for o in m.O) <= max_kg)
    m.value = pyo.Objective(expr=sum(orders.value_if_delivered[o] * m.take[o] for o in m.O), sense=pyo.maximize)
    return m
    # ---------- 24.2 The knapsack model ----------
    m = build_knapsack(orders, pallets)
    solver.solve(m)
    best = loaded(m)
    print(f"knapsack: {pyo.value(m.value):,.0f} with {orders.pallets[best].sum()} pallets, {orders.weight_kg[best].sum():,} kg: {', '.join(best)}")
    print("greedy loads but the model leaves:", ", ".join(sorted(set(greedy) - set(best))),
          "| the model loads instead:", ", ".join(sorted(set(best) - set(greedy))))
    value, chosen = dp_knapsack(orders.pallets.tolist(), orders.value_if_delivered.tolist(), pallets)
    print(f"dynamic programming: {value:,} with {', '.join(orders.index[k] for k in chosen)}")
    r = build_knapsack(orders, pallets, domain=pyo.Reals)
    solver.solve(r)
    print("relaxation:", f"{pyo.value(r.value):,.2f};", "fractional:",
          {o: round(pyo.value(r.take[o]), 3) for o in r.O if 1e-6 < pyo.value(r.take[o]) < 1 - 1e-6})
knapsack: 7,550 with 20 pallets, 12,480 kg: RO-06, RO-07, RO-08, RO-13, RO-16
greedy loads but the model leaves: RO-04, RO-10 | the model loads instead: RO-13
dynamic programming: 7,550 with RO-06, RO-07, RO-08, RO-13, RO-16
relaxation: 7,556.67; fractional: {'RO-02': 0.667}

The model delivers $7,550, $110 more than the dispatcher's rule. Greedy filled the truck with RO-04 (3 pallets) and RO-10 (1); the model swaps them for RO-13 (4 pallets, $1,400). Greedy looks at each order alone; the model looks at what fits together.

Dynamic programming gives the same answer another way: the best value with cc pallet positions, built up one order at a time. It is fast when the capacity is a small whole number, and a good known-answer check for the model (Day 9). It doesn't extend easily to a second limit; the model does.

The relaxation takes two-thirds of RO-02 and earns $7,556.67: only $6.67 above the best whole load. That is why the knapsack is "easy" for MIP solvers, as long as there is only one limit.

Decision it supports: which items to take when they can't all fit.

Other decisions you can support the same way: which projects to fund from a budget · which promotions get the end-of-aisle display · which orders to rush when capacity is short.

24.3 Two limits

The truck also has a weight limit. One more constraint:

    # ---------- 24.3 A second limit: weight ----------
    w = build_knapsack(orders, pallets, max_kg=max_kg)
    solver.solve(w)
    both = loaded(w)
    print(f"with the {max_kg:,} kg limit: {pyo.value(w.value):,.0f}, {orders.pallets[both].sum()} pallets, "
          f"{orders.weight_kg[both].sum():,} kg: {', '.join(both)}")
with the 12,000 kg limit: 7,170, 19 pallets, 11,760 kg: RO-07, RO-08, RO-13, RO-16

The best load from 24.2 weighed 12,480 kg, over the limit. With both limits the truck carries $7,170 of orders in 19 pallets and 11,760 kg: weight, not space, decides. With two limits, "value per pallet" and "value per kilo" rank the orders differently, and no simple rule fixes that. The model handles it with one line.

24.4 First fit decreasing

Tuesday's 24 Montreal orders (200 pallets) go on 26-pallet trailers. How few trailers? Create day24/packing.py. First the warehouse's rule, first fit decreasing (FFD): biggest order first, onto the first trailer with room.

def first_fit_decreasing(sizes, capacity, weights=None, max_kg=None):
    """Biggest order first; put each order on the first truck with room; open a new truck when none has."""
    trucks = []                                   # each truck: [pallets used, kg used, [orders]]
    for o in sorted(sizes, key=lambda o: (-sizes[o], o)):
        for t in trucks:
            if t[0] + sizes[o] <= capacity and (max_kg is None or t[1] + weights[o] <= max_kg):
                t[0] += sizes[o]
                t[1] += weights[o] if weights else 0
                t[2].append(o)
                break
        else:
            trucks.append([sizes[o], weights[o] if weights else 0, [o]])
    return trucks

24.5 The bin-packing model

min⁡∑kuks.t.∑kpok=1∀o (every order on one trailer)∑opalletso pok≤26 uk∀k (only on a trailer that leaves)pok, uk∈{0,1}\begin{aligned} \min\quad & \textstyle\sum_k u_k \\ \text{s.t.}\quad & \textstyle\sum_k p_{ok} = 1 && \forall o \text{ (every order on one trailer)} \\ & \textstyle\sum_o \text{pallets}_o\, p_{ok} \le 26\, u_k && \forall k \text{ (only on a trailer that leaves)} \\ & p_{ok},\ u_k \in \{0, 1\} \end{aligned}

The trailers kk go up to FFD's count: the model never needs more than a plan we already have.

def build_packing(orders, capacity, n_trucks, max_kg=None):
    """put[o, k] = 1 if order o goes on truck k; use[k] = 1 if truck k leaves. Minimize the trucks used."""
    m = pyo.ConcreteModel(name="bin_packing")
    m.O = pyo.Set(initialize=orders.index.tolist())
    m.K = pyo.RangeSet(1, n_trucks)
    m.put = pyo.Var(m.O, m.K, within=pyo.Binary)
    m.use = pyo.Var(m.K, within=pyo.Binary)
    m.one_truck = pyo.Constraint(m.O, rule=lambda m, o: sum(m.put[o, k] for k in m.K) == 1)
    m.positions = pyo.Constraint(m.K, rule=lambda m, k: sum(orders.pallets[o] * m.put[o, k] for o in m.O) <= capacity * m.use[k])
    if max_kg is not None:
        m.weight = pyo.Constraint(m.K, rule=lambda m, k: sum(orders.weight_kg[o] * m.put[o, k] for o in m.O) <= max_kg * m.use[k])
    m.trucks = pyo.Objective(expr=sum(m.use[k] for k in m.K))
    return m
if __name__ == "__main__":
    con = duckdb.connect("northbound.duckdb", read_only=True)
    orders = con.sql("SELECT * FROM truck_orders ORDER BY order_id").df().set_index("order_id")
    capacity, max_kg = con.sql("SELECT pallet_positions, max_kg FROM truck_spec WHERE truck_type = 'trailer'").fetchall()[0]
    total = orders.pallets.sum()
    print(f"{len(orders)} orders, {total} pallets; a trailer takes {capacity}: at least {total / capacity:.2f} "
          f"-> {math.ceil(total / capacity)} trailers")

    # ---------- 24.4 First fit decreasing ----------
    ffd = first_fit_decreasing(orders.pallets.to_dict(), capacity)
    print(f"first fit decreasing: {len(ffd)} trailers, pallets per trailer {[t[0] for t in ffd]}")

    # ---------- 24.5 The bin-packing model ----------
    m = build_packing(orders, capacity, n_trucks=len(ffd))
    pyo.SolverFactory("highs").solve(m)
    print(f"bin-packing model: {pyo.value(m.trucks):.0f} trailers")
    print(trucks_used(m, orders).to_string(index=False))
24 orders, 200 pallets; a trailer takes 26: at least 7.69 -> 8 trailers
first fit decreasing: 8 trailers, pallets per trailer [26, 26, 24, 26, 26, 24, 25, 23]
bin-packing model: 8 trailers
 truck  orders  pallets    kg                  order_ids
     1       4       26 16540 TO-06, TO-07, TO-08, TO-17
     2       4       25 16010 TO-02, TO-11, TO-14, TO-18
     3       2       26 15440               TO-03, TO-22
     4       3       24 13330        TO-01, TO-15, TO-19
     5       3       25 17100        TO-13, TO-21, TO-23
     6       3       26 14390        TO-09, TO-16, TO-24
     7       3       24 14620        TO-05, TO-10, TO-20
     8       2       24 15210               TO-04, TO-12

FFD needs 8 trailers, and 200 pallets need at least ⌈200/26⌉=8\lceil 200 / 26 \rceil = 8. So FFD's plan is already optimal, and the simple bound proves it without a solver. Always compute a bound: it tells you when to stop looking. (The model's plan differs from FFD's, but uses the same number of trailers: bin packing usually has many optimal plans. Day 27 comes back to that.)

Decision it supports: how few vehicles, containers or shifts can hold a set of jobs.

Other decisions you can support the same way: how many pallets for an order of cases · how many servers for a set of programs · how many exam rooms for a set of classes.

24.6 Cutting patterns

The bakery bakes sheet cake in 120 cm slabs ($18 each) and cuts them into bars of five lengths for the cafés. Create day24/cutting.py. A pattern is one way to cut a slab: say, one 24 cm bar, one 45 and one 50 (119 cm, 1 cm wasted). The code lists every maximal pattern, one where not even the shortest bar fits in the leftover.

def patterns(lengths, slab, fits=lambda used, slab: used <= slab):
    """Every way to cut one slab: how many bars of each length, as long as they fit.
    Only maximal patterns are kept: ones where not even the shortest bar would fit in what is left."""
    names = list(lengths)
    found = []

    def extend(k, counts, used):
        if k == len(names):
            if not fits(used + min(lengths.values()), slab) and any(counts):
                found.append(dict(zip(names, counts)))
            return
        n = 0
        while fits(used + n * lengths[names[k]], slab):
            extend(k + 1, counts + [n], used + n * lengths[names[k]])
            n += 1

    extend(0, [], 0)
    return found
if __name__ == "__main__":
    con = duckdb.connect("northbound.duckdb", read_only=True)
    bars = con.sql("SELECT * FROM cake_bars ORDER BY length_cm").df().set_index("bar")
    slab, cost = con.sql("SELECT * FROM cake_slab").fetchall()[0]
    print(bars.to_string())
    lengths, demand = bars.length_cm.to_dict(), bars.bars_per_week.to_dict()
    need = sum(lengths[b] * demand[b] for b in lengths)
    print(f"bars need {need:,} cm of cake: at least {need / slab:.2f} -> {math.ceil(need / slab)} slabs of {slab} cm")
    today = {b: math.ceil(demand[b] / (slab // lengths[b])) for b in lengths}
    print(f"today, one kind of bar per slab: {today} = {sum(today.values())} slabs, ${sum(today.values()) * cost:,.2f} a week")

    # ---------- 24.6 Cutting patterns ----------
    pats = patterns(lengths, slab)
    print(f"{len(pats)} maximal patterns, for example:")
    for p in pats[:4]:
        print("   ", {b: n for b, n in p.items() if n})
                 product  length_cm  bars_per_week
bar
BAR-18         Lemon bar         18             64
BAR-24       Brownie bar         24             52
BAR-30        Carrot bar         30             40
BAR-45         Opera bar         45             28
BAR-50  Black forest bar         50             22
bars need 5,960 cm of cake: at least 49.67 -> 50 slabs of 120 cm
today, one kind of bar per slab: {'BAR-18': 11, 'BAR-24': 11, 'BAR-30': 10, 'BAR-45': 14, 'BAR-50': 11} = 57 slabs, $1,026.00 a week
35 maximal patterns, for example:
    {'BAR-30': 1, 'BAR-45': 2}
    {'BAR-30': 2, 'BAR-50': 1}
    {'BAR-30': 2, 'BAR-45': 1}
    {'BAR-30': 4}

Today the bakery cuts each slab into one kind of bar: 57 slabs a week.

24.7 The cutting-stock model

One integer variable per pattern, cpc_p = how many slabs to cut with pattern pp; abpa_{bp} = bars of length bb in pattern pp:

min⁡∑pcps.t.∑pabp cp≥demandb  ∀b,cp∈{0,1,2,… }\min \sum_p c_p \quad \text{s.t.} \quad \sum_p a_{bp}\, c_p \ge \text{demand}_b \ \ \forall b, \qquad c_p \in \{0, 1, 2, \dots\}
def build_cutting(pats, demand, domain=pyo.NonNegativeIntegers):
    """cut[p] = number of slabs cut with pattern p. Make at least the bars needed, from as few slabs as possible."""
    m = pyo.ConcreteModel(name="cutting_stock")
    m.P = pyo.RangeSet(0, len(pats) - 1)
    m.B = pyo.Set(initialize=list(demand))
    m.cut = pyo.Var(m.P, within=domain)
    m.enough = pyo.Constraint(m.B, rule=lambda m, b: sum(pats[p][b] * m.cut[p] for p in m.P) >= demand[b])
    m.slabs = pyo.Objective(expr=sum(m.cut[p] for p in m.P))
    return m
    # ---------- 24.7 The cutting-stock model ----------
    solver = pyo.SolverFactory("highs")
    m = build_cutting(pats, demand)
    solver.solve(m)
    print(f"cutting-stock model: {pyo.value(m.slabs):.0f} slabs, ${pyo.value(m.slabs) * cost:,.2f} a week")
    print(show(m, pats, lengths, slab).to_string(index=False))
    r = build_cutting(pats, demand, domain=pyo.NonNegativeReals)
    solver.solve(r)
    rounded = sum(math.ceil(pyo.value(r.cut[p]) - 1e-9) for p in r.P)
    print(f"relaxation: {pyo.value(r.slabs):.2f} slabs; rounding every pattern up: {rounded} slabs")
    print(show(r, pats, lengths, slab).to_string(index=False))
cutting-stock model: 50 slabs, $900.00 a week
pattern (bars x cm)  slabs  waste_cm
        1x30 + 2x45    3.0         0
               4x30    4.0         0
 1x24 + 1x45 + 1x50   22.0         1
 1x18 + 3x24 + 1x30   10.0         0
        5x18 + 1x30   11.0         0
relaxation: 49.85 slabs; rounding every pattern up: 51 slabs
pattern (bars x cm)  slabs  waste_cm
        1x30 + 2x45   3.00         0
               4x30   4.05         0
 1x24 + 1x45 + 1x50  22.00         1
 1x18 + 3x24 + 1x30  10.00         0
        5x18 + 1x30  10.80         0

50 slabs, the least possible (⌈5,960/120⌉\lceil 5{,}960 / 120 \rceil), with 22 cm of trim in the whole week: 7 slabs and $126 a week less than one kind of bar per slab. The relaxation's 49.85 slabs is a good bound, but rounding each pattern up gives 51: rounding is not a method, again (Day 21).

With five bar lengths there are only 35 patterns. With 50 lengths there would be millions; real cutting-stock solvers generate patterns as they need them (column generation, see the math corner).

Decision it supports: how to cut standard stock into the sizes needed, with the least waste.

Other decisions you can support the same way: cutting steel bars, paper rolls, fabric or timber · splitting a work week into shifts · loading a truck in layers.

The planted bug

day24/bug_patterns.py uses a colleague's pattern generator, "so bars never touch the end of the slab". Run it.

pats = patterns(lengths, slab, fits=lambda used, slab: used < slab)
m = build_cutting(pats, demand)
pyo.SolverFactory("highs").solve(m)
print(f"{len(pats)} patterns; optimal: {pyo.value(m.slabs):.0f} slabs, ${pyo.value(m.slabs) * cost:,.2f} a week")
What happens, and why
32 patterns; optimal: 52 slabs, $936.00 a week

used < slab instead of used <= slab drops every pattern that uses exactly 120 cm, and four of the five patterns in the best plan use the slab exactly. The model is still "optimal": for the patterns it was given. The model can only choose from what you generate. Test generators on a case you can check by hand (does 4 × 30 cm appear?), and compare the best plan with the bound: 52 slabs against a bound of 50 is a warning.

Math corner (optional): column generation

The cutting-stock relaxation has a dual price πb\pi_b for each bar length: what one more bar of that length costs in slabs. A new pattern is worth adding only if its bars are worth more than one slab: ∑bπb ab>1\sum_b \pi_b\, a_b > 1. Finding the best such pattern is a knapsack (bar lengths as sizes, πb\pi_b as values, 120 cm as capacity). Column generation alternates: solve the relaxation with the patterns so far, solve a knapsack for a new pattern, add it, repeat until no pattern is worth more than 1. Then solve the integer model on the patterns found. This is how industrial cutting and crew-scheduling models handle millions of possible patterns (Gilmore and Gomory, 1961).

Mini-project: spring thaw

From March to May, Quebec lowers truck weight limits on roads softened by the thaw. Planning asks: how many trailers do Tuesday's orders need at weight limits of 20,000, 18,000, 16,000, 15,000 and 14,000 kg? Does first fit decreasing (by pallets, checking both limits) still do the job? Show the 16,000 kg plan.

Solution
"""Day 24 mini-project: spring thaw. From March to May, Quebec limits truck weights on thawing roads.
How many trailers do Tuesday's Montreal orders need at each weight limit, and does first fit decreasing still do?

Run from the repository root (after day06/load_tables.py):  python day24/mini_project_thaw.py
"""
import sys

import duckdb
import pyomo.environ as pyo

sys.path.insert(0, "day24")
from packing import build_packing, first_fit_decreasing, trucks_used

con = duckdb.connect("northbound.duckdb", read_only=True)
orders = con.sql("SELECT * FROM truck_orders ORDER BY order_id").df().set_index("order_id")
capacity, cost = con.sql("SELECT pallet_positions, cost_per_day FROM truck_spec WHERE truck_type = 'trailer'").fetchall()[0]
total_kg = orders.weight_kg.sum()
for max_kg in (20000, 18000, 16000, 15000, 14000):
    ffd = first_fit_decreasing(orders.pallets.to_dict(), capacity, orders.weight_kg.to_dict(), max_kg)
    m = build_packing(orders, capacity, n_trucks=len(ffd), max_kg=max_kg)
    pyo.SolverFactory("highs").solve(m)
    best = round(pyo.value(m.trucks))
    print(f"{max_kg:>6,} kg: weight alone needs {total_kg / max_kg:.2f}; first fit decreasing {len(ffd)}, "
          f"model {best} trailers (${best * cost:,} a day)")
    if max_kg == 16000:
        plan = trucks_used(m, orders)
print("the 16,000 kg plan:")
print(plan.to_string(index=False))
20,000 kg: weight alone needs 6.13; first fit decreasing 8, model 8 trailers ($5,200 a day)
18,000 kg: weight alone needs 6.81; first fit decreasing 8, model 8 trailers ($5,200 a day)
16,000 kg: weight alone needs 7.67; first fit decreasing 9, model 8 trailers ($5,200 a day)
15,000 kg: weight alone needs 8.18; first fit decreasing 9, model 9 trailers ($5,850 a day)
14,000 kg: weight alone needs 8.76; first fit decreasing 10, model 9 trailers ($5,850 a day)
the 16,000 kg plan:
 truck  orders  pallets    kg                  order_ids
     1       2       25 15310               TO-12, TO-16
     2       2       26 15440               TO-03, TO-22
     3       4       26 15100 TO-01, TO-05, TO-15, TO-21
     4       3       26 13500        TO-07, TO-09, TO-17
     5       3       26 15910        TO-02, TO-11, TO-23
     6       4       24 15630 TO-10, TO-13, TO-14, TO-24
     7       3       25 15940        TO-18, TO-19, TO-20
     8       3       22 15810        TO-04, TO-06, TO-08
  • Down to 18,000 kg nothing changes: pallets decide.
  • At 16,000 kg, FFD needs 9 trailers but 8 are enough: the model pairs heavy and light orders, which FFD (sorting by pallets only) never considers. The model saves a trailer, $650, every Tuesday of the thaw.
  • At 15,000 kg the 9th trailer can't be avoided: weight alone needs 8.18. At 14,000 kg FFD uses 10, the model 9.

Memo to transport planning: "During the thaw, plan loads with the model, not with first fit decreasing. At the expected 16,000 kg limit, Tuesday's orders fit on 8 trailers instead of 9."

Commit

git add .
git commit -m "Day 24: knapsack, bin packing, cutting stock"
git push

Day 24 checklist

  • I can write a knapsack, a bin-packing and a cutting-stock model.
  • I compared each with the rule of thumb a planner would use.
  • I compute a simple bound (pallets ÷ capacity) to know when a plan can't be beaten.
  • I know a second limit breaks simple ranking rules but not the model.
  • I know a pattern-based model can only choose the patterns it is given.
  • I can explain what column generation adds (math corner).