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

Fixed Costs and Big-M

Some costs come with doing something at all, whatever the amount: cleaning a line before a product runs, a truck that goes out half empty, a supplier's minimum order. They are fixed costs, and an LP can't see them: it would happily make 1.6 batches of a product and pay nothing extra. Today you add fixed costs and minimum runs to the bakery with a binary per product, and meet the big-M constraint that links them, and the trap of choosing M badly.

▶
Video for Day 22 coming soon

In this lesson

Today's 5-hour plan

LessonProjectBreakCommit
0:00–0:45
22.1 What the LP misses
0:45–1:45
22.2 Set-up costs and minimum runs
1:45–2:00
Break
2:00–2:45
22.3 How big should M be?
2:45–3:45
22.4 A planted bug: M too small
3:45–4:00
Break
4:00–4:45
Mini-project: the cost of keeping each product
4:45–5:00
Commit with Git + checklist

22.1 What the LP misses

bakery_range_setup gives each product a weekly set-up cost (cleaning and changeover, paid in any week the product is made) and a minimum run (the fewest batches worth starting). Start with Day 6's plan and pay its set-ups afterwards. Create day22/setups.py:

import sys

import duckdb
import pandas as pd
import pyomo.environ as pyo

sys.path.insert(0, "day06")
sys.path.insert(0, "day22")
from bakery import build_model, load_data, solve
from setup_model import build_with_setups

pd.set_option("display.width", 140)
con = duckdb.connect("northbound.duckdb", read_only=True)
d = load_data(con)
setup = con.sql("SELECT * FROM bakery_range_setup").df().set_index("sku")

# ---------- 22.1 The Day 6 plan, then pay its set-ups ----------
lp = build_model(d)
solve(lp)
made = [p for p in lp.P if pyo.value(lp.x[p]) > 1e-6]
too_small = [p for p in made if pyo.value(lp.x[p]) < setup.min_batches_if_made[p] - 1e-6]
lp_net = pyo.value(lp.total_profit) - setup.setup_cost_per_week[made].sum()
print(f"Day 6 plan: {len(made)} products made, profit ${pyo.value(lp.total_profit):,.2f}, "
      f"set-ups ${setup.setup_cost_per_week[made].sum():,.0f}, net ${lp_net:,.2f}")
print("made below their minimum run:", {p: round(pyo.value(lp.x[p]), 2) for p in too_small})
Day 6 plan: 22 products made, profit $108,351.28, set-ups $6,330, net $102,021.28
made below their minimum run: {'BK-26': 1.6}

The Day 6 plan makes 22 products and pays $6,330 of set-ups. Worse, it makes 1.6 batches of chocolate chip cookies, below the 4-batch minimum: the plan can't run as written.

22.2 Set-up costs and minimum runs

One binary per product, yp=1y_p = 1 if product pp is made this week, and two constraints:

xp≤Mp ypno batches unless madexp≥min runp ypif made, at least the minimum runnet profit=∑pprofitp xp−∑pset-upp yp\begin{aligned} x_p &\le M_p\, y_p && \text{no batches unless made} \\ x_p &\ge \text{min run}_p\, y_p && \text{if made, at least the minimum run} \\ \text{net profit} &= \sum_p \text{profit}_p\, x_p - \sum_p \text{set-up}_p\, y_p \end{aligned}

When yp=0y_p = 0 both constraints force xp=0x_p = 0. When yp=1y_p = 1 they say min runp≤xp≤Mp\text{min run}_p \le x_p \le M_p. MpM_p is a number big enough never to cut off a good plan: the big-M. A variable that is either 0 or between a minimum and a maximum is called semi-continuous: a pattern you will use again and again (minimum order sizes, minimum truck loads, minimum shift lengths). Create day22/setup_model.py:

"""Day 22: fixed costs. A product made in a week pays a set-up cost and must run at least a minimum number of batches.

Import it:  from setup_model import build_with_setups
"""
import sys

import pyomo.environ as pyo

sys.path.insert(0, "day06")
from bakery import build_model


def build_with_setups(d, setup, big_m=None, domain=pyo.Binary):
    """make[p] = 1 if product p is made this week.
    x[p] <= M[p] * make[p]: no batches unless made. By default M[p] is the product's demand cap, the smallest
    value that never cuts off a good plan. x[p] >= min_run[p] * make[p]: if made, at least the minimum run."""
    m = build_model(d)
    M = {p: (big_m if big_m is not None else d["cap"][p]) for p in d["products"]}
    m.make = pyo.Var(m.P, within=domain)
    m.only_if_made = pyo.Constraint(m.P, rule=lambda m, p: m.x[p] <= M[p] * m.make[p])
    m.min_run = pyo.Constraint(m.P, rule=lambda m, p: m.x[p] >= setup.min_batches_if_made[p] * m.make[p])
    m.setup_cost = pyo.Expression(expr=sum(setup.setup_cost_per_week[p] * m.make[p] for p in m.P))
    m.total_profit.deactivate()
    m.net_profit = pyo.Objective(expr=sum(m.profit[p] * m.x[p] for p in m.P) - m.setup_cost, sense=pyo.maximize)
    return m
# ---------- 22.2 Plan with the set-ups in the model ----------
m = build_with_setups(d, setup)
solve(m)
mip_made = [p for p in m.P if pyo.value(m.make[p]) > 0.5]
print(f"with set-ups: {len(mip_made)} products made, profit before set-ups "
      f"${pyo.value(m.net_profit + m.setup_cost):,.2f}, set-ups ${pyo.value(m.setup_cost):,.0f}, net ${pyo.value(m.net_profit):,.2f}")
changes = pd.DataFrame({
    "product": [d["name"][p] for p in m.P],
    "day6_batches": [round(pyo.value(lp.x[p]), 2) + 0.0 for p in m.P],
    "now": [round(pyo.value(m.x[p]), 2) + 0.0 for p in m.P],
    "setup_cost": [setup.setup_cost_per_week[p] for p in m.P],
    "min_run": [setup.min_batches_if_made[p] for p in m.P],
}, index=list(m.P))
print(changes[changes.day6_batches != changes.now].to_string())
with set-ups: 21 products made, profit before set-ups $108,262.38, set-ups $6,020, net $102,242.38
                              product  day6_batches    now  setup_cost  min_run
BK-18              Butter tart 6-pack          25.0  25.94       430.0        4
BK-26  Chocolate chip cookies 12-pack           1.6   0.00       310.0        4

The plan drops chocolate chip cookies (saving their $310 set-up) and uses the time on butter tarts: $102,242.38 net, $221 better than the Day 6 plan with its set-ups paid, and actually runnable. A small change here because the bakery already made few small products; in a range with more tail products, set-ups decide which products survive.

Decision it supports: which products to make this week, once each product costs something just to start.

Other decisions you can support the same way: which production lines to run · which suppliers to order from when each order has a delivery fee · which routes to drive when each truck has a fixed daily cost.

22.3 How big should M be?

Any MpM_p at least as large as the most product pp could ever make gives the same best plan. So why not just write 1,000,000? Because M changes the relaxation:

# ---------- 22.3 How big should M be? ----------
rows = []
for big_m in (None, 100, 10_000, 1_000_000):
    relaxed = build_with_setups(d, setup, big_m, domain=pyo.UnitInterval)
    solve(relaxed)
    exact = build_with_setups(d, setup, big_m)
    solve(exact)
    rows.append(("demand cap" if big_m is None else f"{big_m:,}", round(pyo.value(relaxed.net_profit), 2),
                 round(pyo.value(exact.net_profit), 2),
                 round((pyo.value(relaxed.net_profit) - pyo.value(exact.net_profit)) / pyo.value(exact.net_profit) * 100, 2)))
print(pd.DataFrame(rows, columns=["M", "relaxation_bound", "best_plan", "gap_pct"]).to_string(index=False))
         M  relaxation_bound  best_plan  gap_pct
demand cap         102372.08  102242.38     0.13
       100         107076.82  102242.38     4.73
    10,000         108338.54  102242.38     5.96
 1,000,000         108351.15  102242.38     5.97

Every M finds the same plan ($102,242.38). But the relaxation's bound weakens as M grows: from 0.13% above the best plan with M = demand cap, to 6% with M = 1,000,000. With a huge M, yp=0.000002y_p = 0.000002 allows 2 batches in the relaxation, so the set-up costs almost vanish and the bound says little. On this small model HiGHS finds the answer anyway; on a big one, a weak bound means a huge search tree and hours instead of seconds (Day 27 measures it).

The rule: M should be the smallest number that is always valid, usually a capacity or a demand cap you already have, per variable, not one number for the whole model. Very large values also invite numerical trouble (Day 9): with tolerances around 10−610^{-6}, M=109M = 10^9 lets "y=10−6y = 10^{-6}" pass for zero while allowing 1,000 batches.

22.4 A planted bug: M too small

day22/bug_small_m.py sets one M for every product: 20 batches, "plenty, since most products sell fewer than 20". Run it.

con = duckdb.connect("northbound.duckdb", read_only=True)
d = load_data(con)
setup = con.sql("SELECT * FROM bakery_range_setup").df().set_index("sku")
m = build_with_setups(d, setup, big_m=20)
result = solve(m)
print(result.solver.termination_condition, f"net profit ${pyo.value(m.net_profit):,.2f}")
What happens, and why
optimal net profit $95,349.70

"Optimal", and $6,893 a week worse than the real best plan. M = 20 is a hidden capacity: every product whose demand cap is above 20 can now make at most 20 batches, however profitable it is. Too large an M weakens the relaxation; too small an M silently changes the problem. To catch it, list the variables sitting exactly at their M: any of them is a sign M is cutting off part of the plan.

Mini-project: the cost of keeping each product

The plan drops 9 products: 8 that Day 6 already dropped, plus chocolate chip cookies. Marketing wants to know what it would cost to keep each one on the shelf at its minimum run. Fix each dropped product's ypy_p to 1 in turn, re-solve, and rank them. What would it cost to keep all 30?

Solution
import sys

import duckdb
import pandas as pd
import pyomo.environ as pyo

sys.path.insert(0, "day06")
sys.path.insert(0, "day22")
from bakery import load_data, solve
from setup_model import build_with_setups

pd.set_option("display.width", 140)
con = duckdb.connect("northbound.duckdb", read_only=True)
d = load_data(con)
setup = con.sql("SELECT * FROM bakery_range_setup").df().set_index("sku")
best = build_with_setups(d, setup)
solve(best)
dropped = [p for p in best.P if pyo.value(best.make[p]) < 0.5]

rows = []
for p in dropped:
    m = build_with_setups(d, setup)
    m.make[p].fix(1)                         # keep this product on the shelf, at least its minimum run
    solve(m)
    rows.append((p, d["name"][p], d["category"][p], round(pyo.value(m.x[p]), 2),
                 round(pyo.value(best.net_profit) - pyo.value(m.net_profit), 2)))
keep = pd.DataFrame(rows, columns=["sku", "product", "category", "batches_if_kept", "cost_a_week"])
print(keep.sort_values("cost_a_week").to_string(index=False))

everything = build_with_setups(d, setup)
for p in everything.P:
    everything.make[p].fix(1)
solve(everything)
print(f"keep all 30 products: ${pyo.value(everything.net_profit):,.2f}, "
      f"${pyo.value(best.net_profit) - pyo.value(everything.net_profit):,.2f} a week less than the best plan")
  sku                        product     category  batches_if_kept  cost_a_week
BK-07                Olive sourdough        bread             3.00       108.61
BK-26 Chocolate chip cookies 12-pack       cookie             4.00       256.05
BK-22                     Cheesecake         cake             4.71       321.06
BK-24               Maple layer cake         cake             3.00       416.73
BK-08               Seeded sourdough        bread             4.00       422.71
BK-21              Black forest cake         cake             4.00       472.51
BK-15                  Danish 4-pack viennoiserie             5.00       505.88
BK-20                Lemon loaf cake         cake             4.00       714.96
BK-19                    Carrot cake         cake             4.00       745.76
keep all 30 products: $97,744.09, $4,498.29 a week less than the best plan

Keeping olive sourdough costs only $109 a week, chocolate chip cookies $256, cheesecake $321; carrot cake and lemon loaf cost over $700 each. Keeping all 30 products costs $4,498 a week. That is the number marketing must beat with the sales a full range brings (customers who leave when their cake is missing). The ranked list lets them choose: keep the cheap ones, drop the costly ones.

fix(1) on a binary is the MIP version of Day 7's "what does this rule cost?": force the decision, re-solve, compare. There are no reduced costs for binaries; forcing and re-solving is how you price a yes/no decision.

Commit

git add .
git commit -m "Day 22: set-up costs, minimum runs, big-M"
git push

Day 22 checklist

  • I can model a fixed cost with a binary and a big-M constraint.
  • I can model a minimum run (a semi-continuous variable).
  • I choose M as the smallest always-valid value, per variable.
  • I can show that a large M weakens the relaxation, and a small M changes the problem.
  • I check for variables sitting exactly at their M.
  • I priced each yes/no decision by fixing it and re-solving.