4.1 Why a modelling language
Look back at Day 2's linprog call: c, A_ub, b_ub, bounds. Which row of A_ub is the oven? Which column is croissants? You had to remember, and on Day 2 the order of b_ub was baker, oven, starter only because pivot sorted the resources alphabetically. With 30 products and 4 resources, that bookkeeping is where errors hide.
A modelling language lets you write the model with names, the way you write it on paper. It then builds the matrices and passes them to a solver. Pyomo is the open-source modelling language for Python; it talks to HiGHS, Gurobi, CPLEX and others, so the same model runs on any of them.
| Paper | Pyomo |
|---|---|
| Decision variables | pyo.Var |
| Objective | pyo.Objective |
| Constraints | pyo.Constraint |
| Index sets (products, resources) | pyo.Set |
| Data (profit, capacity) | pyo.Param |
Create day04/first_model.py. First, the model exactly as on Day 1, one variable per product:
import pyomo.environ as pyo
# ---------- 4.1 One variable per product, written out by hand ----------
m = pyo.ConcreteModel(name="bakery_scalar")
m.S = pyo.Var(within=pyo.NonNegativeReals, bounds=(0, 35)) # sourdough batches
m.W = pyo.Var(within=pyo.NonNegativeReals, bounds=(0, 45)) # whole-wheat batches
m.C = pyo.Var(within=pyo.NonNegativeReals, bounds=(0, 31)) # croissant batches
m.profit = pyo.Objective(expr=300 * m.S + 200 * m.W + 250 * m.C, sense=pyo.maximize)
m.oven = pyo.Constraint(expr=2 * m.S + 1 * m.W + 1.5 * m.C <= 100)
m.bakers = pyo.Constraint(expr=1 * m.S + 1 * m.W + 1.5 * m.C <= 80)
m.starter = pyo.Constraint(expr=m.S <= 40)
solver = pyo.SolverFactory("highs")
result = solver.solve(m)
print("termination:", result.solver.termination_condition)
print(f"S = {pyo.value(m.S):g}, W = {pyo.value(m.W):g}, C = {pyo.value(m.C):g}")
print(f"profit = ${pyo.value(m.profit):,.2f}")
termination: optimal
S = 20, W = 45, C = 10
profit = $17,500.00
The same $17,500 plan, and every line reads like the paper model. Things to notice:
bounds=(0, 35)puts the demand cap straight on the variable.sense=pyo.maximize: no more flipping signs as withlinprog.pyo.value(m.S)reads a value after solving.m.Son its own is the variable object, not a number.result.solver.termination_conditionis the status. Check it every time.
Decision it supports: the weekly bake plan, in a form a colleague can read and check line by line.
Other decisions you can support the same way: any small model you need to explain to a manager · a quick check of a model someone built in a spreadsheet.
4.2 Sets, parameters and indexed constraints
Writing one variable per product does not scale. The real bakery has 30 products. We write the model once over sets, and feed the data separately:
is the set of products, the set of resources. The model has one capacity constraint per resource and one demand constraint per product, however many there are.
# ---------- 4.2 Sets and parameters: one model for any list of products ----------
products = ["BK-SD", "BK-WW", "BK-CR"]
resources = ["oven_hours", "baker_hours", "sourdough_starter"]
profit = {"BK-SD": 300, "BK-WW": 200, "BK-CR": 250}
cap = {"BK-SD": 35, "BK-WW": 45, "BK-CR": 31}
capacity = {"oven_hours": 100, "baker_hours": 80, "sourdough_starter": 40}
use = {("oven_hours", "BK-SD"): 2.0, ("oven_hours", "BK-WW"): 1.0, ("oven_hours", "BK-CR"): 1.5,
("baker_hours", "BK-SD"): 1.0, ("baker_hours", "BK-WW"): 1.0, ("baker_hours", "BK-CR"): 1.5,
("sourdough_starter", "BK-SD"): 1.0}
m = pyo.ConcreteModel(name="bakery")
m.P = pyo.Set(initialize=products) # products
m.R = pyo.Set(initialize=resources) # resources
m.profit = pyo.Param(m.P, initialize=profit) # $ per batch
m.cap = pyo.Param(m.P, initialize=cap) # demand cap, batches
m.capacity = pyo.Param(m.R, initialize=capacity) # per week
m.use = pyo.Param(m.R, m.P, initialize=use, default=0) # use per batch; missing = 0
m.x = pyo.Var(m.P, within=pyo.NonNegativeReals) # batches to bake
def demand_rule(m, p):
return m.x[p] <= m.cap[p]
def capacity_rule(m, r):
return sum(m.use[r, p] * m.x[p] for p in m.P) <= m.capacity[r]
m.demand = pyo.Constraint(m.P, rule=demand_rule)
m.capacity_limit = pyo.Constraint(m.R, rule=capacity_rule)
m.total_profit = pyo.Objective(expr=sum(m.profit[p] * m.x[p] for p in m.P), sense=pyo.maximize)
m.capacity_limit.pprint()
result = solver.solve(m)
print("termination:", result.solver.termination_condition)
for p in m.P:
print(f" {p}: {pyo.value(m.x[p]):g} batches")
print(f"profit = ${pyo.value(m.total_profit):,.2f}")
capacity_limit : Size=3, Index=R, Active=True
Key : Lower : Body : Upper : Active
baker_hours : -Inf : x[BK-SD] + x[BK-WW] + 1.5*x[BK-CR] : 80.0 : True
oven_hours : -Inf : 2.0*x[BK-SD] + x[BK-WW] + 1.5*x[BK-CR] : 100.0 : True
sourdough_starter : -Inf : x[BK-SD] + 0*x[BK-WW] + 0*x[BK-CR] : 40.0 : True
termination: optimal
BK-SD: 20 batches
BK-WW: 45 batches
BK-CR: 10 batches
profit = $17,500.00
How it works:
pyo.Param(m.R, m.P, initialize=use, default=0): the recipe is a dictionary keyed by (resource, product). Combinations not listed, like starter for whole-wheat, take the default 0. This mirrors the long recipe file from Day 1.- A rule is a function that returns one constraint for one index. Pyomo calls
capacity_rule(m, r)once for each resource and stores the results inm.capacity_limit, indexed by resource. m.capacity_limit.pprint()prints every constraint Pyomo built. Read it. It is the fastest way to catch a wrong coefficient. Here each row matches the recipe.
Decision it supports: the same plan, from a model that does not change when products are added.
Other decisions you can support the same way: a staffing plan over a set of shifts · a media plan over a set of channels.
Try it 4.1
Packing becomes a fourth resource: sourdough uses 0.5 packing hours a batch, whole-wheat 0.5, croissants 0.6, and the packing line has 35 hours next week. Add it by changing only the data (resources, capacity, use). What is the new plan?
Solution
resources = ["oven_hours", "baker_hours", "sourdough_starter", "packing_hours"]
capacity["packing_hours"] = 35
use.update({("packing_hours", "BK-SD"): 0.5, ("packing_hours", "BK-WW"): 0.5, ("packing_hours", "BK-CR"): 0.6})
The model code does not change. The new plan is sourdough 30, whole-wheat 40, croissant 0: $17,000. Packing (0.5 × 30 + 0.5 × 40 = 35 hours) and the oven are now full, and croissants drop out altogether. A new limit can change the whole mix, not just shave it.
4.3 What the solver receives, and what it says
Two ways to see what is going on between Pyomo and HiGHS.
# ---------- 4.3 What the solver receives, and what it says ----------
print("--- HiGHS log ---")
pyo.SolverFactory("highs").solve(m, tee=True) # a new solver object, so it starts from scratch
m.write("day04/bakery.lp", io_options={"symbolic_solver_labels": True})
print(open("day04/bakery.lp").read())
First, tee=True prints the solver's log:
--- HiGHS log ---
Hessian has dimension 3 but no nonzeros, so is ignored
LP has 6 rows; 3 cols; 10 nonzeros
Coefficient ranges:
Matrix [1e+00, 2e+00]
Cost [2e+02, 3e+02]
Bound [0e+00, 0e+00]
RHS [3e+01, 1e+02]
Presolving model
6 rows, 3 cols, 10 nonzeros 0s
Initial sweep identifies 0 + 4 + 0 = 4 / 6 empty + singleton + redundant rows
2 rows, 3 cols, 6 nonzeros 0s
2 rows, 3 cols, 6 nonzeros 0s
Presolve reductions: rows 2(-4); columns 3(-0); nonzeros 6(-4)
Solving the presolved LP
Choosing to use dual simplex solver
Using dual simplex solver
Iteration Objective Infeasibilities num(sum)
0 0.0000000000e+00 Ph1: 0(0) 0.0s
2 -1.7500000000e+04 Pr: 0(0) 0.0s
Performed postsolve
Solving the original LP from the solution after postsolve
Model status : Optimal
Simplex iterations: 2
Objective value : 1.7500000000e+04
P-D objective error : 0.0000000000e+00
HiGHS run time : 0.00
Read it top to bottom:
- 6 rows, 3 cols: 6 constraints (3 demand + 3 capacity), 3 variables.
- Coefficient ranges: the smallest and largest numbers in the model. When these span many powers of ten (say 1e-4 to 1e+7), solvers struggle; Day 9 is about scaling.
- Presolve removed 4 of the 6 rows: the 3 single-variable demand rows became bounds, and the starter row (S ≤ 40) is implied by the cap S ≤ 35. Real solvers simplify your model before solving it.
- Dual simplex, 2 iterations: the solver walked across 2 corners (Day 3) to the best one. The objective shows as −17,500 because HiGHS minimizes internally.
- Model status: Optimal. This is the line that matters.
Second, m.write("day04/bakery.lp") saves the model in LP format, the plain-text form solvers read:
\* Source Pyomo model name=bakery *\
max
total_profit:
+300 x(BK_SD)
+200 x(BK_WW)
+250 x(BK_CR)
s.t.
c_u_demand(BK_SD)_:
+1 x(BK_SD)
<= 35
c_u_demand(BK_WW)_:
+1 x(BK_WW)
<= 45
c_u_demand(BK_CR)_:
+1 x(BK_CR)
<= 31
c_u_capacity_limit(oven_hours)_:
+2.0 x(BK_SD)
+1 x(BK_WW)
+1.5 x(BK_CR)
<= 100
c_u_capacity_limit(baker_hours)_:
+1 x(BK_SD)
+1 x(BK_WW)
+1.5 x(BK_CR)
<= 80
c_u_capacity_limit(sourdough_starter)_:
+1 x(BK_SD)
<= 40
bounds
0 <= x(BK_SD) <= +inf
0 <= x(BK_WW) <= +inf
0 <= x(BK_CR) <= +inf
end
This file is the model with no Python in the way. Commit it: when someone changes the model, git diff day04/bakery.lp shows exactly which coefficient moved. You can also send it to a colleague who uses another solver.
Try it 4.2: change a number, re-solve
Rebuilding a model for every what-if is slow on big models. Declare the capacity as mutable=True, then change it and re-solve. Run day04/oven_sweep.py:
m.capacity = pyo.Param(m.R, initialize={"oven_hours": 100, "baker_hours": 80, "sourdough_starter": 40}, mutable=True)
and later:
solver = pyo.SolverFactory("highs")
for hours in (100, 105, 110, 115, 120, 130):
m.capacity["oven_hours"] = hours
solver.solve(m)
plan = [round(pyo.value(m.x[p]), 2) + 0.0 for p in m.P]
print(f"oven {hours:>3} h: profit ${pyo.value(m.total_profit):>10,.2f} plan {plan}")
What happens to profit as oven hours go from 100 to 130? Where does extra oven time stop paying?
Solution
oven 100 h: profit $ 17,500.00 plan [20.0, 45.0, 10.0]
oven 105 h: profit $ 18,166.67 plan [25.0, 45.0, 6.67]
oven 110 h: profit $ 18,833.33 plan [30.0, 45.0, 3.33]
oven 115 h: profit $ 19,500.00 plan [35.0, 45.0, 0.0]
oven 120 h: profit $ 19,500.00 plan [35.0, 45.0, 0.0]
oven 130 h: profit $ 19,500.00 plan [35.0, 45.0, 0.0]
Each extra oven hour is worth $133.33 (Day 2's number) up to 115 hours, where sourdough reaches its demand cap of 35. Beyond that, extra oven time is worth nothing. A shadow price holds only over a range: Day 12 gets that range straight from the solver. (+ 0.0 turns −0.0 into 0.0 in the printout.)
4.4 A report you can trust
A solver answer is only useful with three checks: the status, the slack of every resource, and the objective recomputed from the plan. Put them in one function you reuse:
# ---------- 4.4 A report you can trust ----------
def report(m, result):
tc = result.solver.termination_condition
if tc != pyo.TerminationCondition.optimal:
print("NOT OPTIMAL:", tc)
return
print(f"{'resource':<18}{'used':>8}{'capacity':>10}{'slack':>8}")
for r in m.R:
used = pyo.value(m.capacity_limit[r].body)
print(f"{r:<18}{used:>8.2f}{pyo.value(m.capacity[r]):>10.2f}{pyo.value(m.capacity[r]) - used:>8.2f}")
recomputed = sum(pyo.value(m.profit[p]) * pyo.value(m.x[p]) for p in m.P)
print(f"objective ${pyo.value(m.total_profit):,.2f}, recomputed ${recomputed:,.2f}")
report(m, result)
resource used capacity slack
oven_hours 100.00 100.00 0.00
baker_hours 80.00 80.00 0.00
sourdough_starter 20.00 40.00 20.00
objective $17,500.00, recomputed $17,500.00
m.capacity_limit[r].body is the left-hand side of the constraint; pyo.value evaluates it at the solution. Recomputing the objective by hand looks redundant until the day the objective expression has a bug.
Decision it supports: handing a plan to the bakery manager with the evidence that it fits.
Other decisions you can support the same way: any model output that leaves your laptop.
The planted bug
day04/bug_typo.py solves without error and returns a plausible plan. Before reading the solution, run it, compare with yesterday's answer, and find the problem using pprint.
import pyomo.environ as pyo
m = pyo.ConcreteModel()
m.P = pyo.Set(initialize=["BK-SD", "BK-WW", "BK-CR"])
m.R = pyo.Set(initialize=["oven_hours", "baker_hours", "sourdough_starter"])
m.profit = pyo.Param(m.P, initialize={"BK-SD": 300, "BK-WW": 200, "BK-CR": 250})
m.capacity = pyo.Param(m.R, initialize={"oven_hours": 100, "baker_hours": 80, "sourdough_starter": 40})
m.use = pyo.Param(m.R, m.P, default=0, initialize={
("oven_hours", "BK-SD"): 2.0, ("oven_hours", "BK-WW"): 1.0, ("oven_hours", "BK-CR"): 15,
("baker_hours", "BK-SD"): 1.0, ("baker_hours", "BK-WW"): 1.0, ("baker_hours", "BK-CR"): 1.5,
("sourdough_starter", "BK-SD"): 1.0})
m.x = pyo.Var(m.P, bounds=lambda m, p: (0, {"BK-SD": 35, "BK-WW": 45, "BK-CR": 31}[p]))
m.capacity_limit = pyo.Constraint(m.R, rule=lambda m, r: sum(m.use[r, p] * m.x[p] for p in m.P) <= m.capacity[r])
m.total_profit = pyo.Objective(expr=sum(m.profit[p] * m.x[p] for p in m.P), sense=pyo.maximize)
result = pyo.SolverFactory("highs").solve(m)
print(result.solver.termination_condition)
for p in m.P:
print(f" {p}: {pyo.value(m.x[p]):g}")
print(f"profit ${pyo.value(m.total_profit):,.2f}")
What happens, and how to find it
optimal
BK-SD: 27.5
BK-WW: 45
BK-CR: 0
profit $17,250.00
Optimal, plausible, and wrong: croissants disappear and profit is $250 lower than yesterday. Add m.capacity_limit.pprint() and the oven row reads 2.0*x[BK-SD] + x[BK-WW] + 15*x[BK-CR]: someone typed 15 oven hours for croissants instead of 1.5. At 15 hours a batch, croissants are hopeless, so the solver drops them.
No solver can catch a data typo. Your defences: print the model, check that the plan's product mix makes sense, and (Day 6) validate data before it reaches the model.
Mini-project: the rye loaf in Pyomo
Rewrite Day 2's rye mini-project in Pyomo, in day04/rye_pyomo.py, with:
- all data in one dictionary
data(profit, caps, capacities, recipe); - a function
build(data)that returns the model, with no numbers inside it; - the same answer as Day 2.
Then add rye to the data, not to the code.
Solution
"""Day 4 mini-project: the four-product bakery (with rye) in Pyomo, from dictionaries.
Run from the repository root: python day04/rye_pyomo.py
"""
import pyomo.environ as pyo
data = {
"profit": {"BK-SD": 300, "BK-WW": 200, "BK-CR": 250, "BK-RY": 240},
"cap": {"BK-SD": 35, "BK-WW": 45, "BK-CR": 31, "BK-RY": 15},
"capacity": {"oven_hours": 100, "baker_hours": 80, "sourdough_starter": 40},
"use": {("oven_hours", "BK-SD"): 2.0, ("oven_hours", "BK-WW"): 1.0, ("oven_hours", "BK-CR"): 1.5, ("oven_hours", "BK-RY"): 1.5,
("baker_hours", "BK-SD"): 1.0, ("baker_hours", "BK-WW"): 1.0, ("baker_hours", "BK-CR"): 1.5, ("baker_hours", "BK-RY"): 1.0,
("sourdough_starter", "BK-SD"): 1.0, ("sourdough_starter", "BK-RY"): 0.5},
}
def build(data):
m = pyo.ConcreteModel()
m.P = pyo.Set(initialize=list(data["profit"]))
m.R = pyo.Set(initialize=list(data["capacity"]))
m.profit = pyo.Param(m.P, initialize=data["profit"])
m.capacity = pyo.Param(m.R, initialize=data["capacity"])
m.use = pyo.Param(m.R, m.P, initialize=data["use"], default=0)
m.x = pyo.Var(m.P, bounds=lambda m, p: (0, data["cap"][p]))
m.capacity_limit = pyo.Constraint(m.R, rule=lambda m, r: sum(m.use[r, p] * m.x[p] for p in m.P) <= m.capacity[r])
m.total_profit = pyo.Objective(expr=sum(m.profit[p] * m.x[p] for p in m.P), sense=pyo.maximize)
return m
m = build(data)
result = pyo.SolverFactory("highs").solve(m)
print(result.solver.termination_condition)
for p in m.P:
print(f" {p}: {pyo.value(m.x[p]):g}")
print(f"profit ${pyo.value(m.total_profit):,.2f}")
optimal
BK-SD: 12.5
BK-WW: 45
BK-CR: 5
BK-RY: 15
profit $17,600.00
The same $17,600 as Day 2. bounds=lambda m, p: (0, data["cap"][p]) sets each variable's bounds from the data. Because build contains no numbers, adding a fifth product is a data change only. Day 6 takes this one step further and reads data from DuckDB.
Commit
git add .
git commit -m "Day 4: first Pyomo models, solver log, LP file, report"
git push
Day 4 checklist
- I can write a linear program in Pyomo with
Var,ObjectiveandConstraint. - I can index a model over sets and feed it data through
Param, with defaults for missing combinations. - I check the termination condition before reading any value.
- I can read a HiGHS log and an LP file.
- I can change a mutable parameter and re-solve.
- I found a data typo with
pprint.