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 21–23: bakery_investments (four options for the full bakery, each adding capacity at a weekly cost), bakery_range_setup (each product's weekly set-up cost and minimum run, Day 22), candidate_sites and site_store_lanes (three existing DCs and seven candidate sites, Day 23).
21.1 One yes/no decision
A binary variable takes the value 0 or 1. It turns a decision into a number the model can multiply: "lease two ovens" becomes , the oven capacity becomes , and the cost becomes . When nothing changes; when the bakery has 700 oven hours and pays $900 a week.
A model with binary (or integer) variables is a mixed-integer program (MIP): some variables must be whole numbers, others (the batches) may be fractions. In Pyomo the only change is the domain: within=pyo.Binary.
21.2 Four investments in one model
The plant manager's menu, bakery_investments:
resource extra_capacity cost_per_week
option
lease_ovens oven_hours 100 900
hire_baker baker_hours 40 1600
starter_tank sourdough_starter 12 250
packing_upgrade packing_hours 60 1400
On Day 13 you tried all 8 combinations of three options with a loop. With four options that is 16 solves; with 20 options a million. Instead, one model with one binary per option. Create day21/investments.py:
import itertools
import sys
import duckdb
import pandas as pd
import pyomo.environ as pyo
sys.path.insert(0, "day06")
from bakery import build_model, load_data, solve
def build_with_investments(d, menu, domain=pyo.Binary):
"""The Day 6 model plus one yes/no variable per investment: buy[o] = 1 adds its capacity and its cost."""
m = build_model(d)
m.O = pyo.Set(initialize=menu.index.tolist())
m.buy = pyo.Var(m.O, within=domain)
for r in m.R:
options = [o for o in m.O if menu.resource[o] == r]
m.capacity_limit[r].set_value(
sum(m.use[r, p] * m.x[p] for p in m.P) <= m.capacity[r] + sum(menu.extra_capacity[o] * m.buy[o] for o in options))
m.investment_cost = pyo.Expression(expr=sum(menu.cost_per_week[o] * m.buy[o] for o in m.O))
m.total_profit.deactivate()
m.net_profit = pyo.Objective(expr=sum(m.profit[p] * m.x[p] for p in m.P) - m.investment_cost, sense=pyo.maximize)
return m
def bought(m):
return [o for o in m.O if pyo.value(m.buy[o]) > 0.5]
Each capacity constraint gains the extra capacity of the options that add to it; the objective subtracts their cost. domain defaults to binary; we'll use other domains in a moment.
if __name__ == "__main__":
pd.set_option("display.width", 140)
con = duckdb.connect("northbound.duckdb", read_only=True)
d = load_data(con)
menu = con.sql("SELECT * FROM bakery_investments").df().set_index("option")
print(menu.to_string())
base = build_model(d)
solve(base)
print(f"no investments: ${pyo.value(base.total_profit):,.2f}")
# ---------- 21.2 All four options in one model ----------
m = build_with_investments(d, menu)
solve(m)
print(f"best: buy {bought(m)}; net profit ${pyo.value(m.net_profit):,.2f}")
# Check: try all 16 combinations, as on Day 13
best = None
for choice in itertools.product([0, 1], repeat=len(menu)):
e = build_with_investments(d, menu)
for o, c in zip(menu.index, choice):
e.buy[o].fix(c)
solve(e)
if best is None or pyo.value(e.net_profit) > best[0] + 1e-6:
best = (pyo.value(e.net_profit), choice)
print(f"enumeration of 16 combinations: best ${best[0]:,.2f} with {dict(zip(menu.index, best[1]))}")
no investments: $108,351.28
best: buy ['lease_ovens', 'hire_baker', 'starter_tank', 'packing_upgrade']; net profit $113,488.16
enumeration of 16 combinations: best $113,488.16 with {'lease_ovens': 1, 'hire_baker': 1, 'starter_tank': 1, 'packing_upgrade': 1}
Buy all four: the bakery earns $113,488.16 a week after paying for them, $5,136.88 more than today. The single MIP gives the same answer as trying all 16 combinations, in one solve.
Decision it supports: which of several investments to make, given that their values depend on each other.
Other decisions you can support the same way: which projects to fund · which machines to buy · which marketing campaigns to run.
21.3 Business rules as constraints
Binaries make logic expressible as linear constraints. With :
| Business rule | Constraint |
|---|---|
| A only if B | |
| Not both A and B | |
| At least one of A, B | |
| Exactly one of A, B, C | |
| At most k of the options | |
| A if and only if B | |
| A only if B is not chosen | |
| Budget |
Each row is worth checking with all four combinations of 0 and 1: the constraint must allow exactly the combinations the rule allows. Six rules, added one at a time:
# ---------- 21.3 Business rules as constraints on binaries ----------
b = lambda m, o: m.buy[o]
rules = {
"budget $2,500 a week": lambda m: m.investment_cost <= 2500,
"at most 2 options": lambda m: sum(m.buy[o] for o in m.O) <= 2,
"baker only with ovens": lambda m: b(m, "hire_baker") <= b(m, "lease_ovens"),
"ovens or packing, not both": lambda m: b(m, "lease_ovens") + b(m, "packing_upgrade") <= 1,
"exactly one option": lambda m: sum(m.buy[o] for o in m.O) == 1,
"packing only if no new baker": lambda m: b(m, "packing_upgrade") <= 1 - b(m, "hire_baker"),
}
rows = []
for name, rule in rules.items():
e = build_with_investments(d, menu)
e.rule = pyo.Constraint(expr=rule(e))
solve(e)
rows.append((name, ", ".join(bought(e)), round(pyo.value(e.net_profit), 2)))
print(pd.DataFrame(rows, columns=["rule", "buy", "net_profit"]).to_string(index=False))
rule buy net_profit
budget $2,500 a week lease_ovens, starter_tank 109623.37
at most 2 options lease_ovens, starter_tank 109623.37
baker only with ovens lease_ovens, hire_baker, starter_tank, packing_upgrade 113488.16
ovens or packing, not both lease_ovens, starter_tank 109623.37
exactly one option starter_tank 108706.52
packing only if no new baker lease_ovens, starter_tank, packing_upgrade 110918.02
- "Baker only with ovens" doesn't bind: the best plan buys both anyway.
- A $2,500 budget, "at most 2" and "ovens or packing, not both" all give the same answer: ovens and starter tank, $109,623.37.
- "Exactly one": the starter tank, the best single option.
- "Packing only if no new baker" gives up the baker and keeps the rest: $110,918.02.
Notice what didn't happen: nobody had to write "if this then that" code around the solver. The rules sit in the model, and the solver finds the best plan that obeys them all.
21.4 Relaxations and branch and bound
What if we let the binaries take any value between 0 and 1? That is the model's LP relaxation:
# The LP relaxation: let buy take any value between 0 and 1
r = build_with_investments(d, menu, domain=pyo.UnitInterval)
solve(r)
print(f"relaxation: ${pyo.value(r.net_profit):,.2f} with buy = {({o: round(pyo.value(r.buy[o]), 3) + 0.0 for o in r.O})}")
relaxation: $114,456.97 with buy = {'lease_ovens': 0.658, 'hire_baker': 1.0, 'starter_tank': 1.0, 'packing_upgrade': 0.528}
The relaxation leases 0.658 of the ovens and 0.528 of the packing upgrade: meaningless as a decision, but useful as a bound. Every yes/no plan is also a plan of the relaxation, so the relaxation's $114,456.97 is an upper limit on what any combination can earn. The best combination ($113,488.16) is within 0.85% of it.
Rounding the relaxation is not a method: here rounding up happens to give the right answer, but in general rounded solutions can be infeasible or far from the best. MIP solvers use branch and bound instead (Day 26 in detail): solve the relaxation; pick a fractional variable (say, ovens = 0.658); solve two new problems, one with ovens = 0 and one with ovens = 1; repeat on each, and drop any branch whose relaxation bound is worse than the best plan already found. The log shows it:
# ---------- 21.4 What the MIP solver does ----------
print("--- HiGHS log for the investment model")
pyo.SolverFactory("highs").solve(build_with_investments(d, menu), tee=True)
Nodes | B&B Tree | Objective Bounds | Dynamic Constraints | Work
Src Proc. InQueue | Leaves Expl. | BestBound BestSol Gap | Cuts InLp Confl. | LpIters Time
J 0 0 0 0.00% inf 112599.622222 Large 0 0 0 0 0.0s
S 0 0 0 0.00% 146199.2 113488.16 28.82% 0 0 0 0 0.0s
50.0% inactive integer columns, restarting
Model after restart has 4 rows, 32 cols (2 bin., 0 int., 0 impl., 30 cont., 0 dom.fix.), and 96 nonzeros
0 0 0 0.00% 114456.974667 113488.16 0.85% 0 0 0 5 0.0s
0 0 0 0.00% 114456.974667 113488.16 0.85% 0 0 0 5 0.0s
1 0 1 100.00% 113488.16 113488.16 0.00% 6 1 1 14 0.0s
Solving report
Status Optimal
Primal bound 113488.16
Dual bound 113488.16
Gap 0% (tolerance: 0.01%)
(Your log's times and thread counts will differ.) Read the columns BestBound (the best the relaxation says is possible) and BestSol (the best plan found so far). The solver found $113,488.16 almost immediately with a heuristic, then proved it optimal by raising the bound to meet it: gap 0%. On big models, the gap is what tells you how good the current plan is while the solver is still working.
The planted bug
day21/bug_bounds.py builds the investment model "with the right bounds". Run it.
con = duckdb.connect("northbound.duckdb", read_only=True)
d = load_data(con)
menu = con.sql("SELECT * FROM bakery_investments").df().set_index("option")
m = build_with_investments(d, menu, domain=pyo.NonNegativeReals)
for o in m.O:
m.buy[o].setub(1)
solve(m)
print(f"net profit ${pyo.value(m.net_profit):,.2f}")
print({o: round(pyo.value(m.buy[o]), 3) + 0.0 for o in m.O})
What happens, and why
net profit $114,456.97
{'lease_ovens': 0.658, 'hire_baker': 1.0, 'starter_tank': 1.0, 'packing_upgrade': 0.528}
within=NonNegativeReals with an upper bound of 1 is not binary: it is the relaxation. The model happily leases 0.658 of two ovens and reports a profit no real decision can earn. Bounds of 0 and 1 don't make a variable a yes/no decision; only the domain does. Whenever a model's "decisions" come out as fractions, check the domain first.
Mini-project: what each budget buys
Finance asks what each weekly investment budget from $0 to $5,000 would buy, in steps of $500. The plant manager adds a rule: no new baker unless the ovens are leased. Report each budget at which the best choice changes, with what it spends and what it gains.
Solution
import sys
import duckdb
import pyomo.environ as pyo
sys.path.insert(0, "day06")
sys.path.insert(0, "day21")
from bakery import build_model, load_data, solve
from investments import bought, build_with_investments
con = duckdb.connect("northbound.duckdb", read_only=True)
d = load_data(con)
menu = con.sql("SELECT * FROM bakery_investments").df().set_index("option")
base = build_model(d)
solve(base)
base_profit = pyo.value(base.total_profit)
previous = None
for budget in range(0, 5001, 500):
m = build_with_investments(d, menu)
m.budget = pyo.Constraint(expr=m.investment_cost <= budget)
m.baker_needs_ovens = pyo.Constraint(expr=m.buy["hire_baker"] <= m.buy["lease_ovens"])
solve(m)
choice = bought(m)
if choice != previous:
spent = pyo.value(m.investment_cost) + 0.0
gain = pyo.value(m.net_profit) - base_profit
print(f"budget ${budget:>5,}: buy {choice or 'nothing'}; spends ${spent:,.0f}, net gain ${gain:,.2f} a week")
previous = choice
budget $ 0: buy nothing; spends $0, net gain $0.00 a week
budget $ 500: buy ['starter_tank']; spends $250, net gain $355.24 a week
budget $1,500: buy ['lease_ovens', 'starter_tank']; spends $1,150, net gain $1,272.09 a week
budget $3,000: buy ['lease_ovens', 'starter_tank', 'packing_upgrade']; spends $2,550, net gain $2,566.74 a week
budget $4,000: buy ['lease_ovens', 'hire_baker', 'packing_upgrade']; spends $3,900, net gain $3,516.80 a week
budget $4,500: buy ['lease_ovens', 'hire_baker', 'starter_tank', 'packing_upgrade']; spends $4,150, net gain $5,136.88 a week
The best set does not simply grow with the budget. At $4,000 the plan drops the starter tank to afford the baker: ovens + baker + packing gain more than ovens + starter + packing, but the starter tank no longer fits. At $4,500 everything fits. This is why investment choices need a model: a ranking of options by return ("buy the best ones until the money runs out") misses combinations like this.
Memo to finance: "Each budget step buys something different. $1,150 a week (ovens and starter tank) returns $1,272; $2,550 returns $2,567; the full $4,150 returns $5,137. The baker only pays together with the ovens and the packing upgrade: approve all three or none of them."
Commit
git add .
git commit -m "Day 21: binary investments and business rules"
git push
Day 21 checklist
- I can model a yes/no decision with a binary variable that adds capacity and cost.
- One MIP gives the same answer as enumerating every combination.
- I can write "only if", "not both", "at least one", "at most k" and budget rules as linear constraints.
- I know the LP relaxation gives a bound, and why rounding it is not a method.
- I can read BestBound, BestSol and Gap in a MIP log.
- I know that bounds of 0 and 1 don't make a variable binary.