Optimization Modeling: The Best Product Mix¶
Until now the course has described data and predicted outcomes. This week we prescribe: we let the computer search through every possible plan and return the best one. The tool is the linear program (LP), the workhorse of operations in airlines, refineries, factories and supply chains.
Qahwa House’s central kitchen in Al-Kharj roasts the coffee and bakes the pastries for all four branches. Every week the manager decides how many batches of four products to make. The roaster, the oven and the staff have only so many hours, and the branches can only sell so much. Which plan earns the most?
The manager’s instinct is to make as much as possible of the product with the highest margin. We will see why that instinct leaves money on the table.
After this reading you can:
name the three parts of an optimization model: decision variables, objective and constraints;
write a small product-mix model in words and in algebra;
draw the feasible region of a two-variable LP and find its best corner with iso-profit lines;
solve an LP with PuLP and read the status, the plan, the objective and the slack of each constraint;
build a larger model from a table with
lpSumand loops;recognise an infeasible and an unbounded model, and state the assumptions of a linear model.
Textbook: Albright & Winston, Business Analytics: Data Analysis and Decision Making, Chapter 13.
Setup¶
The first cell installs PuLP, with the HiGHS solver, when you are in Colab; on your own computer, install it once with pip install "pulp[highs]>=4.3,<5".
# Colab does not include PuLP: install it once per session (a few seconds).
# PuLP 4 ships without a solver: the [highs] extra installs HiGHS, the free solver this course uses.
import sys
if "google.colab" in sys.modules:
%pip install -q "pulp[highs]>=4.3,<5"import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import pulp
BASE = "https://chebil.github.io/BusinessDecision/data/"
def load(name):
"""Read a course dataset from the website, or from a local copy of the repository."""
try:
return pd.read_csv(BASE + name)
except Exception: # offline, or working from a copy of the course repository
return pd.read_csv("../data/" + name)
mix = load("qahwa_roastery_mix.csv")
mix| Column | Meaning |
|---|---|
product, kind, batch | what is made, and what one batch is |
price_sar | what the branches pay the kitchen for one batch (SAR) |
variable_cost_sar | beans, flour, dates, saffron and packaging for one batch (SAR) |
contribution_sar | price minus variable cost: what one more batch adds to the week’s profit |
roast_h, oven_h, labour_h | hours of the roaster, the oven and the kitchen staff one batch uses |
max_batches | the most batches the branches can sell in a week |
The last row, capacity, holds the hours available each week: 50 roaster hours, 40 oven hours and 160 staff hours (four people, 40 hours each).
1. Three ingredients¶
Every optimization model has three parts. Write them in words before you write any code.
| Part | Question | The kitchen |
|---|---|---|
| Decision variables | What do we choose? | the number of batches of each product this week |
| Objective | What do we maximise or minimise? | the week’s total contribution (SAR) |
| Constraints | What limits the choice? | roaster, oven and staff hours; what the branches can sell; no negative batches |
A plan that meets every constraint is feasible. The best feasible plan is optimal. Regression (weeks 6 and 7) gave us numbers to expect; an LP gives us the numbers to choose.
We split the table into the products and the capacities:
HOURS = ["roast_h", "oven_h", "labour_h"]
products = mix[mix["product"] != "capacity"].set_index("product")
capacity = mix.set_index("product").loc["capacity", HOURS].astype(float)
capacityroast_h 50.0
oven_h 40.0
labour_h 160.0
Name: capacity, dtype: float642. Two products: the roastery alone¶
Start small. Suppose that this week the oven is being serviced, so the kitchen makes coffee only. Two decisions:
= batches of House Blend, = batches of Yemeni Haraz.
Every expression is linear: each batch adds the same contribution and uses the same hours, whatever the others do.
With two variables we can draw every feasible plan. Each constraint keeps the points on one side of a line; the points that satisfy all of them form the feasible region. The staff constraint never binds here: even 40 and 16 batches would need only of the 160 hours, so its line lies outside the picture.
fig, ax = plt.subplots(figsize=(7, 5.2))
h = np.linspace(0, 55, 200)
ax.fill([0, 40, 40, 10, 0], [0, 0, 4, 16, 16], color="C0", alpha=0.18, label="feasible plans")
ax.plot(h, (50 - h) / 2.5, color="C3", lw=2.2, label="roaster: H + 2.5 Y = 50")
ax.axvline(40, color="C1", lw=2.2, label="House Blend demand: H = 40")
ax.axhline(16, color="C2", lw=2.2, label="Yemeni demand: Y = 16")
for k, profit in enumerate((24_000, 33_000, 42_000)): # iso-profit lines: 900 H + 1500 Y = profit
ax.plot(h, (profit - 900 * h) / 1500, color="grey", ls="--", lw=1,
label="iso-profit: 24,000, 33,000, 42,000 SAR" if k == 0 else None)
ax.scatter([40], [4], s=70, color="C3", zorder=5)
ax.annotate("best plan (40, 4)\n42,000 SAR", (40, 4), (41.5, 7), fontsize=9)
ax.scatter([10], [16], s=70, color="k", zorder=5)
ax.annotate("highest margin first (10, 16)\n33,000 SAR", (10, 16), (17, 18.4), fontsize=9,
arrowprops=dict(arrowstyle="->", color="k", lw=0.8))
ax.set_xlim(0, 55); ax.set_ylim(0, 22)
ax.set_xlabel("H: batches of House Blend")
ax.set_ylabel("Y: batches of Yemeni Haraz")
ax.set_title("The roastery's feasible plans and three iso-profit lines")
ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.16), ncol=2, fontsize=8)
plt.show()
The dashed lines are iso-profit lines: every plan on one line earns the same contribution. Moving the line up and to the right raises the profit. The best plan is the last feasible point the line touches as it moves outward, here the corner .
This is the key fact of linear programming: if an LP has an optimal plan, then one of the corners of the feasible region is optimal. A two-variable model can be solved by checking the corners:
corners = pd.DataFrame({"H": [0, 40, 40, 10, 0], "Y": [0, 0, 4, 16, 16]})
corners["roaster_h"] = 1.0 * corners["H"] + 2.5 * corners["Y"]
corners["contribution"] = 900 * corners["H"] + 1500 * corners["Y"]
cornersThe best corner earns 42,000 SAR: 40 batches of House Blend and 4 of Yemeni Haraz. The manager’s instinct, Yemeni Haraz first because it earns 1,500 SAR a batch, fills the demand of 16 batches, which takes 40 of the 50 roaster hours and leaves room for only 10 batches of House Blend: 33,000 SAR, 9,000 less.
Why? The roaster is the scarce resource, so what matters is the contribution per roaster hour, not per batch:
coffee = products.loc[["House Blend", "Yemeni Haraz"]]
(coffee["contribution_sar"] / coffee["roast_h"]).rename("SAR per roaster hour")product
House Blend 900.0
Yemeni Haraz 600.0
Name: SAR per roaster hour, dtype: float64An hour of roaster time spent on House Blend earns 900 SAR; on Yemeni Haraz, only 600. So House Blend gets the roaster first, up to its demand of 40 batches (40 hours), and the 10 hours left go to Yemeni Haraz: 4 batches.
3. Solving it with PuLP¶
Drawing works for two variables. For more, we hand the model to a solver. PuLP is a Python library in which you write the model almost as you would on paper; it then calls a solver to find the optimum. PuLP 4 needs a solver named explicitly; the course uses HiGHS (free, open source, installed by pulp[highs]), and it also reports shadow prices and reduced costs, which we use next week.
Create the problem with
pulp.LpProblem(name, pulp.LpMaximize).Create one variable per decision with
problem.add_variable(name, lowBound=..., upBound=...). A variable belongs to the problem that created it.Add the objective with
+=, then each constraint with+=and a name.Call
problem.solve(pulp.HiGHS(msg=False)). It returns a result: read itsstatusfirst, then the variable values and the objective.
roastery = pulp.LpProblem("roastery", pulp.LpMaximize)
H = roastery.add_variable("house_blend", lowBound=0, upBound=40) # batches of House Blend (demand: at most 40)
Y = roastery.add_variable("yemeni_haraz", lowBound=0, upBound=16) # batches of Yemeni Haraz (demand: at most 16)
roastery += 900 * H + 1500 * Y, "contribution" # the first expression added is the objective
roastery += 1.0 * H + 2.5 * Y <= 50, "roaster" # then each constraint, with a name
roastery += 2.0 * H + 3.0 * Y <= 160, "labour"
result = roastery.solve(pulp.HiGHS(msg=False)) # HiGHS: a free, open-source solver
print(result.status.name)
print("House Blend:", H.value(), " Yemeni Haraz:", Y.value(), " contribution:", pulp.value(roastery.objective))Running HiGHS 1.16.0 (git hash: f3f113d): Copyright (c) 2026 under MIT licence terms
Includes third-party software components, see THIRD_PARTY_NOTICES.md for full details
Optimal
House Blend: 40.0 Yemeni Haraz: 4.0 contribution: 42000.0
The status is Optimal, and PuLP finds the corner we found on the graph: 40 and 4, for 42,000 SAR. The first solve of a session also prints two lines with HiGHS’s name and licence; you can ignore them.
Always read the status first. A number printed after an Infeasible status is meaningless.
Next, the constraints. A constraint is binding when the plan uses all of its resource (its slack is zero); otherwise it has slack, spare capacity:
cons = roastery.constraints() # the list of constraints, each with its name
pd.DataFrame({"used": {c.name: c.value() - c.constant for c in cons},
"available": {c.name: -c.constant for c in cons},
"slack": {c.name: c.slack for c in cons}}).round(1) + 0.0The roaster is binding: all 50 hours are used. Staff time is not: 68 of the 160 hours are free. Only the binding constraints shape the optimum. If the roaster had more hours, the profit would rise; extra staff hours would add nothing this week. How much one more roaster hour is worth is the subject of next week.
4. The whole kitchen: four products, three resources¶
Now the oven is back. The full weekly model has four decision variables, one per product, and three resource constraints. In general form, with the batches of product , its contribution, the hours of resource one batch uses, the hours available and the demand:
We no longer type the numbers into the model: we read them from the table. pulp.lpSum adds up a list of terms, and a loop writes one constraint per resource. The same code would solve a model with 400 products. We write the steps as a function, build_mix, that returns the model and its variables, so that we can build variants of it later (section 6).
def build_mix(products, capacity):
"""Build the weekly model from the two tables; return it with its variables."""
m = pulp.LpProblem("weekly_mix", pulp.LpMaximize)
# one decision variable per product, between 0 and what the branches can sell
x = {p: m.add_variable(p.replace(" ", "_"), lowBound=0, upBound=products.loc[p, "max_batches"])
for p in products.index}
# objective: the week's total contribution
m += pulp.lpSum(products.loc[p, "contribution_sar"] * x[p] for p in products.index), "contribution"
# one constraint per resource: hours used <= hours available
for r in HOURS:
m += pulp.lpSum(products.loc[p, r] * x[p] for p in products.index) <= capacity[r], r
return m, x
model, x = build_mix(products, capacity)
result = model.solve(pulp.HiGHS(msg=False))
print(result.status.name, "·", f"{pulp.value(model.objective):,.0f} SAR a week")Optimal · 53,900 SAR a week
plan = pd.Series({p: x[p].value() for p in products.index}, name="batches")
used = pd.Series({r: (products[r] * plan).sum() for r in HOURS})
print(plan.to_string(), "\n")
pd.DataFrame({"used": used, "available": capacity, "slack": capacity - used})House Blend 40.0
Yemeni Haraz 4.0
Date Maamoul 17.0
Saffron Cake 0.0
The best weekly plan: 40 batches of House Blend, 4 of Yemeni Haraz, 17 of Date Maamoul and no Saffron Cake, for 53,900 SAR a week.
Read it with the resource table. The roaster (50 of 50 hours) and the staff (160 of 160) are binding; the oven has 6 hours to spare. So the plan follows the two scarce resources:
House Blend earns the most per roaster hour, so it fills its demand (40 batches, 40 roaster hours, 80 staff hours);
the 10 roaster hours left make 4 batches of Yemeni Haraz (12 staff hours);
the 68 staff hours left go to pastries. Both pastries need 4 staff hours a batch, and Date Maamoul earns 700 SAR against Saffron Cake’s 560, so all 68 hours make 17 batches of Date Maamoul, which need 34 of the 40 oven hours.
Saffron Cake is not made at all, although the branches would sell 30 batches: its staff hours earn more as Date Maamoul.
5. The intuitive plan¶
How good is the instinct “highest margin first”? The function below makes as much as possible of the product with the highest contribution per batch, then the next one with the hours left, and so on.
def highest_margin_first(products, capacity):
"""Make as much as possible of the product with the highest contribution per batch, then the next, and so on."""
left = capacity.copy()
plan = {}
for p in products.sort_values("contribution_sar", ascending=False).index:
need = products.loc[p, HOURS].astype(float)
room = min(left[r] / need[r] for r in HOURS if need[r] > 0) # batches the hours still allow
plan[p] = min(products.loc[p, "max_batches"], room)
left = left - plan[p] * need
return pd.Series(plan).reindex(products.index)
intuitive = highest_margin_first(products, capacity)
intuitive_profit = (intuitive * products["contribution_sar"]).sum()
pd.DataFrame({"intuitive plan": intuitive, "LP plan": plan})used_int = pd.Series({r: (products[r] * intuitive).sum() for r in HOURS})
print(f"intuitive plan: {intuitive_profit:,.0f} SAR · LP plan: {pulp.value(model.objective):,.0f} SAR · "
f"gap: {pulp.value(model.objective) - intuitive_profit:,.0f} SAR a week")
pd.DataFrame({"used": used_int, "available": capacity, "slack": capacity - used_int})intuitive plan: 47,000 SAR · LP plan: 53,900 SAR · gap: 6,900 SAR a week
The intuitive plan earns 47,000 SAR a week, 6,900 SAR less than the LP: about 359,000 SAR over a year of 52 weeks, from the same kitchen and staff. It fills the 16 batches of Yemeni Haraz first, which eats 40 roaster hours and leaves room for only 10 batches of House Blend. It then fills the oven with Date Maamoul (20 batches), and leaves 12 staff hours idle.
The ratios explain it. Each product’s contribution per hour of each resource:
ratios = pd.DataFrame({r: products["contribution_sar"] / products[r].replace(0, np.nan) for r in HOURS})
ratios.round(0)Ranked per batch, Yemeni Haraz wins. Per roaster hour, House Blend wins. Per staff hour, Yemeni Haraz is ahead of House Blend again, and per oven hour Saffron Cake beats Date Maamoul. Each ranking gives a different plan, and the right one depends on which resources are scarce, which we only know once the plan is chosen. A simple ranking works when a single resource binds; with two or more, the LP weighs them all at once. That is what a solver is for.
6. When a model breaks¶
Two things can go wrong before any optimum exists.
Infeasible: no plan meets every constraint. Suppose the branches insist on at least 30 batches of House Blend and the manager promises a hotel at least 10 batches of Yemeni Haraz. Those two alone need roaster hours, and there are 50. We build a fresh model with build_mix (a variable belongs to one model, so we do not copy the old one) and add the two promises:
strict, xs = build_mix(products, capacity)
strict += xs["House Blend"] >= 30, "min_house"
strict += xs["Yemeni Haraz"] >= 10, "min_yemeni"
strict.solve(pulp.HiGHS(msg=False)).status.name'Infeasible'An infeasible model is a message to the manager, not a bug: the promises cannot all be kept. Either find 5 more roaster hours or renegotiate one of the two commitments.
Unbounded: the objective can grow without limit. This happens when a constraint is missing. Keep only the roaster constraint and forget the demand limits: pastries do not use the roaster, so nothing stops the model from baking an infinite number of them.
loose = pulp.LpProblem("loose", pulp.LpMaximize)
y = {p: loose.add_variable("loose_" + p.replace(" ", "_"), lowBound=0) for p in products.index}
loose += pulp.lpSum(products.loc[p, "contribution_sar"] * y[p] for p in products.index)
loose += pulp.lpSum(products.loc[p, "roast_h"] * y[p] for p in products.index) <= capacity["roast_h"], "roaster"
loose.solve(pulp.HiGHS(msg=False)).status.name'Unbounded'No real business has unlimited profit. An unbounded model always means that something real (a capacity, a demand, a budget) was left out.
7. What “linear” assumes¶
An LP is only as good as four assumptions. Check them before you trust a plan.
| Assumption | Meaning | In the kitchen |
|---|---|---|
| Proportionality | twice the batches, twice the contribution and twice the hours | no volume discounts on green beans, no set-up time per run |
| Additivity | the totals are sums over the products | roasting House Blend does not slow down Yemeni Haraz |
| Divisibility | variables may take fractional values | 4.4 batches makes sense for beans (kg), less so for trays; whole numbers come in week 12 |
| Certainty | every number in the table is known | demand and prices are estimates; next week we ask how much they can change before the plan does |
When an assumption fails badly, the model is changed (integer variables, fixed costs, nonlinear terms; weeks 11 and 12) or tested (sensitivity analysis, week 10; simulation, week 14).
Check your understanding¶
Name the decision variables, the objective and the constraints of the kitchen model in one sentence each.
Why is the optimal plan of a two-variable LP at a corner of the feasible region?
The roaster has no slack and the oven has 6 hours of slack. Which of the two would you try to expand first, and why?
Why does “highest contribution per batch first” fail here, and when would a ranking by contribution per hour be enough?
A model returns the status Unbounded. What do you check first?
Summary¶
An optimization model has decision variables, an objective and constraints; write them in words first.
The feasible region of an LP is bounded by straight lines; if there is an optimum, a corner is optimal, and iso-profit lines show which.
In PuLP:
LpProblem, variables with bounds fromadd_variable, the objective and constraints added with+=,lpSumand loops to build from a table, thensolve(pulp.HiGHS(msg=False))and read the status first.Binding constraints have zero slack and shape the plan; the others do not matter at the optimum.
The best plan (53,900 SAR) beats the “highest margin first” plan (47,000 SAR) because two resources are scarce at once, and only the LP weighs them together.
Infeasible means the promises conflict; unbounded means a real limit is missing.
Next week: how much is one more roaster hour worth, and how far can a price move before the plan changes? Sensitivity analysis and duality.