Lab 9 Solutions: Product Mix Model in PuLP¶
These are the worked solutions, with outputs. Try the lab yourself first.
In this lab you build the weekly production plan of Qahwa House’s central kitchen as a linear program in PuLP, and compare it with the plan the manager would make by instinct.
The question. How many batches of each product should the kitchen make this week? The manager’s instinct: as much as possible of the product with the highest margin, Yemeni Haraz.
How this lab works
Run the cells from top to bottom with Shift + Enter. Replace every
...with your code, then run the check cell under it.Extended track: after Part D, try the ★ challenges.
Submit before the next lab session: File → Download → Download .ipynb.
You may use an AI assistant for code. If you do, add a short note at the end: what you asked, what you kept and what you changed.
# Run this cell once: it defines a small helper that checks your answers.
def check(label, condition):
print(("✅ " if condition else "❌ ") + label)# 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).
Part A: The roastery model¶
A1. Products and capacities¶
Split the table: products holds the four product rows with product as the index, and capacity holds the three hours available (the capacity row, columns HOURS, as floats).
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: float64check("A1 four products", len(products) == 4)
check("A1 50 roaster hours, 40 oven hours, 160 staff hours", list(capacity) == [50, 40, 160])✅ A1 four products
✅ A1 50 roaster hours, 40 oven hours, 160 staff hours
A2. The model in words¶
This week the oven is being serviced: the kitchen makes coffee only, House Blend ( batches) and Yemeni Haraz ( batches). In three short lines, write the decision variables, the objective and the constraints (with their numbers, from the table).
Decision variables: and , the batches of House Blend and Yemeni Haraz made this week.
Objective: maximise the contribution (SAR).
Constraints: roaster hours; staff hours; demand , ; and .
A3. Solve it with PuLP¶
Complete the model: the objective and the roaster constraint. The bounds of the variables hold the demand limits. The first solve of a session also prints two lines with HiGHS’s name and licence; you can ignore them.
roastery = pulp.LpProblem("roastery", pulp.LpMaximize)
H = roastery.add_variable("house_blend", lowBound=0, upBound=40)
Y = roastery.add_variable("yemeni_haraz", lowBound=0, upBound=16)
roastery += 900 * H + 1500 * Y, "contribution"
roastery += 1.0 * H + 2.5 * Y <= 50, "roaster"
roastery += 2.0 * H + 3.0 * Y <= 160, "labour"
result = roastery.solve(pulp.HiGHS(msg=False))
print(result.status.name, H.value(), Y.value(), 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 40.0 4.0 42000.0
check("A3 the status is Optimal", result.status.name == "Optimal")
check("A3 the roaster constraint is in the model", "roaster" in [c.name for c in roastery.constraints()])
check("A3 the best coffee plan earns 42,000 SAR", abs(pulp.value(roastery.objective) - 42_000) < 1)✅ A3 the status is Optimal
✅ A3 the roaster constraint is in the model
✅ A3 the best coffee plan earns 42,000 SAR
Part B: The picture behind the answer¶
B1. The corners¶
The feasible region of the roastery model has five corners: , , , and . Add a column contribution to the DataFrame corners with the contribution of each corner.
corners = pd.DataFrame({"H": [0, 40, 40, 10, 0], "Y": [0, 0, 4, 16, 16]})
corners["contribution"] = 900 * corners["H"] + 1500 * corners["Y"]
cornerscheck("B1 five corners", len(corners) == 5)
check("B1 the best corner is (40, 4), as PuLP found", corners.loc[corners["contribution"].idxmax(), ["H", "Y"]].tolist() == [40, 4])
check("B1 the 'Yemeni first' corner (10, 16) earns 33,000 SAR", corners.query("H == 10 and Y == 16")["contribution"].item() == 33_000)✅ B1 five corners
✅ B1 the best corner is (40, 4), as PuLP found
✅ B1 the 'Yemeni first' corner (10, 16) earns 33,000 SAR
B2. The graph¶
Run the cell: it draws the feasible region, the roaster line, the two demand limits and three iso-profit lines.
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()
B3. Per roaster hour¶
Compute each coffee’s contribution per roaster hour and store it in a Series per_roaster_hour, indexed by product (House Blend and Yemeni Haraz only).
coffee = products.loc[["House Blend", "Yemeni Haraz"]]
per_roaster_hour = coffee["contribution_sar"] / coffee["roast_h"]
per_roaster_hourproduct
House Blend 900.0
Yemeni Haraz 600.0
dtype: float64check("B3 House Blend: 900 SAR per roaster hour", per_roaster_hour["House Blend"] == 900)
check("B3 Yemeni Haraz: 600 SAR per roaster hour", per_roaster_hour["Yemeni Haraz"] == 600)✅ B3 House Blend: 900 SAR per roaster hour
✅ B3 Yemeni Haraz: 600 SAR per roaster hour
B4. In two sentences: why does the best coffee plan make only 4 batches of Yemeni Haraz, the product with the highest margin?
B4. The roaster is the scarce resource, and an hour of it earns 900 SAR on House Blend but only 600 SAR on Yemeni Haraz. So House Blend gets the roaster first, up to its demand of 40 batches, and the 10 hours left make 4 batches of Yemeni Haraz.
Part C: The whole kitchen¶
C1. The full model¶
The oven is back. Build the model with all four products and the three resources, reading every number from products and capacity. Complete the objective and the constraint inside the loop with pulp.lpSum. The code builds the model inside a function, build_mix, that returns the model and its variables, so you can build it again in D3.
def build_mix(products, capacity):
"""Build the weekly model; return it with its variables."""
m = pulp.LpProblem("weekly_mix", pulp.LpMaximize)
x = {p: m.add_variable(p.replace(" ", "_"), lowBound=0, upBound=products.loc[p, "max_batches"])
for p in products.index}
m += pulp.lpSum(products.loc[p, "contribution_sar"] * x[p] for p in products.index), "contribution"
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, pulp.value(model.objective))Optimal 53900.0
check("C1 the status is Optimal", result.status.name == "Optimal")
check("C1 three resource constraints", len(model.constraints()) == 3)
check("C1 the best plan earns 53,900 SAR a week", abs(pulp.value(model.objective) - 53_900) < 1)✅ C1 the status is Optimal
✅ C1 three resource constraints
✅ C1 the best plan earns 53,900 SAR a week
C2. The plan and the hours¶
Store the plan in a Series plan (batches, indexed by product). Then build a DataFrame usage indexed by resource with three columns: used, available and slack.
plan = pd.Series({p: x[p].value() for p in products.index})
used = pd.Series({r: (products[r] * plan).sum() for r in HOURS})
usage = pd.DataFrame({"used": used, "available": capacity, "slack": capacity - used})
print(plan.to_string())
usageHouse Blend 40.0
Yemeni Haraz 4.0
Date Maamoul 17.0
Saffron Cake 0.0
check("C2 40 House Blend, 4 Yemeni Haraz, 17 Date Maamoul, 0 Saffron Cake", plan.round(6).tolist() == [40, 4, 17, 0])
check("C2 the roaster and the staff are binding", abs(usage.loc["roast_h", "slack"]) < 1e-6 and abs(usage.loc["labour_h", "slack"]) < 1e-6)
check("C2 the oven has 6 hours to spare", abs(usage.loc["oven_h", "slack"] - 6) < 1e-6)✅ C2 40 House Blend, 4 Yemeni Haraz, 17 Date Maamoul, 0 Saffron Cake
✅ C2 the roaster and the staff are binding
✅ C2 the oven has 6 hours to spare
C3. The branches would buy 30 batches of Saffron Cake a week, yet the plan makes none. In two sentences, explain why, using the resource table.
C3. Staff time is binding, and both pastries need 4 staff hours a batch, so each staff hour earns 175 SAR on Date Maamoul (700 / 4) but only 140 SAR on Saffron Cake (560 / 4). The oven, where Saffron Cake would do better, has 6 hours of slack, so it does not limit the plan: every staff hour left after the coffee goes to Date Maamoul.
Part D: The manager’s plan¶
D1. Highest margin first¶
The manager’s plan fills the demand of the product with the highest margin first: 16 batches of Yemeni Haraz, then 10 of House Blend (the roaster hours left), then 20 of Date Maamoul (the oven is then full), and no Saffron Cake. Compute its weekly contribution manager_profit, and the hours it uses in a Series manager_used (indexed by resource).
manager = pd.Series({"House Blend": 10, "Yemeni Haraz": 16, "Date Maamoul": 20, "Saffron Cake": 0})
manager_profit = (manager * products["contribution_sar"]).sum()
manager_used = pd.Series({r: (products[r] * manager).sum() for r in HOURS})
print(manager_profit)
manager_used47000.0
roast_h 50.0
oven_h 40.0
labour_h 148.0
dtype: float64check("D1 the manager's plan is feasible", (manager_used <= capacity + 1e-9).all())
check("D1 it earns 47,000 SAR a week", manager_profit == 47_000)
check("D1 it leaves 12 staff hours idle", capacity["labour_h"] - manager_used["labour_h"] == 12)✅ D1 the manager's plan is feasible
✅ D1 it earns 47,000 SAR a week
✅ D1 it leaves 12 staff hours idle
D2. The gap¶
Store in gap how much more the LP plan earns per week, and in gap_year the same over 52 weeks.
gap = pulp.value(model.objective) - manager_profit
gap_year = 52 * gap
print(f"{gap:,.0f} SAR a week, {gap_year:,.0f} SAR a year")6,900 SAR a week, 358,800 SAR a year
check("D2 6,900 SAR a week", abs(gap - 6_900) < 1)
check("D2 358,800 SAR a year", abs(gap_year - 358_800) < 1)✅ D2 6,900 SAR a week
✅ D2 358,800 SAR a year
D3. Two promises¶
The branches insist on at least 30 batches of House Blend, and the manager has promised a hotel at least 10 batches of Yemeni Haraz. Build a fresh model with strict, xs = build_mix(products, capacity) (a variable belongs to one model, so we build a new one rather than copy it), add both promises as constraints on its variables xs, solve it, and store its status (a string such as "Optimal") in strict_status.
strict, xs = build_mix(products, capacity)
strict += xs["House Blend"] >= 30, "min_house"
strict += xs["Yemeni Haraz"] >= 10, "min_yemeni"
strict_status = strict.solve(pulp.HiGHS(msg=False)).status.name
strict_status'Infeasible'check("D3 both promises cannot be kept", strict_status == "Infeasible")✅ D3 both promises cannot be kept
D4. In one sentence: which constraint makes the two promises impossible, and by how many hours?
D4. The roaster: 30 batches of House Blend and 10 of Yemeni Haraz need roaster hours, 5 more than the 50 available.
D5. Your recommendation¶
Write three sentences for the manager: the plan to follow this week (with numbers), what it earns compared with the “highest margin first” plan, and one assumption of the model that you would check before following it.
Recommendation. Make 40 batches of House Blend, 4 of Yemeni Haraz and 17 of Date Maamoul this week, and no Saffron Cake. This plan earns 53,900 SAR of contribution, 6,900 SAR a week (about 359,000 SAR a year) more than filling the Yemeni Haraz demand first, because it gives the scarce roaster hours to House Blend (900 SAR per roaster hour against 600) and leaves no staff hour idle. The plan assumes the contributions, the hours per batch and the demand limits are right and that a batch always takes the same time; if the demand for House Blend were overestimated, the plan would change, so the forecast should be checked first.
★ Extended challenges¶
E1. One more roaster hour. Re-solve the full model with 51 roaster hours instead of 50. How much does the contribution rise, and what happens to the plan?
E2. Whole batches. Pastries come in whole trays. Solve the 51-hour model again with every variable cat="Integer". Compare with E1: what is the extra roaster hour worth now?
E3. A better Saffron Cake. Raise the contribution of Saffron Cake step by step (600, 650, 700, 720 SAR) and re-solve. From which contribution does the plan start making it, and what does it stop making instead?
def solve_mix(products, capacity, cat="Continuous"):
"""Build and solve the weekly model; return the plan and the contribution."""
m = pulp.LpProblem("mix", pulp.LpMaximize)
v = {p: m.add_variable(p.replace(" ", "_"), lowBound=0, upBound=products.loc[p, "max_batches"], cat=cat)
for p in products.index}
m += pulp.lpSum(products.loc[p, "contribution_sar"] * v[p] for p in products.index)
for r in HOURS:
m += pulp.lpSum(products.loc[p, r] * v[p] for p in products.index) <= capacity[r], r
m.solve(pulp.HiGHS(msg=False))
return pd.Series({p: v[p].value() for p in products.index}) + 0.0, pulp.value(m.objective) # + 0.0 turns -0.0 into 0.0
more = capacity.copy()
more["roast_h"] = 51
plan51, profit51 = solve_mix(products, more)
print(plan51.round(2).to_string())
best = (plan * products["contribution_sar"]).sum() # the 50-hour plan of C2 (53,900 SAR)
print(f"contribution {profit51:,.0f} SAR, +{profit51 - best:,.0f} SAR")House Blend 40.0
Yemeni Haraz 4.4
Date Maamoul 16.7
Saffron Cake 0.0
contribution 54,290 SAR, +390 SAR
E1. One more roaster hour raises the contribution by 390 SAR, to 54,290 SAR. The extra hour makes 0.4 more batches of Yemeni Haraz (+600 SAR), which take 1.2 staff hours away from Date Maamoul (0.3 batches, −210 SAR). That 390 SAR is the roaster’s shadow price, next week’s main idea.
plan51i, profit51i = solve_mix(products, more, cat="Integer")
print(plan51i.to_string())
print(f"contribution {profit51i:,.0f} SAR")House Blend 40.0
Yemeni Haraz 4.0
Date Maamoul 17.0
Saffron Cake 0.0
contribution 53,900 SAR
E2. With whole batches the plan stays 40, 4, 17 and 0, and the contribution stays 53,900 SAR: one extra hour cannot make a whole extra batch of Yemeni Haraz (2.5 hours), so in whole batches it is worth nothing. Divisibility matters when a resource comes in small amounts; integer models are the topic of week 12.
for c in [600, 650, 700, 720]:
better = products.copy()
better.loc["Saffron Cake", "contribution_sar"] = c
plan_c, profit_c = solve_mix(better, capacity)
print(c, plan_c.round(1).tolist(), f"{profit_c:,.0f}")600 [40.0, 4.0, 17.0, 0.0] 53,900
650 [40.0, 4.0, 17.0, 0.0] 53,900
700 [40.0, 4.0, 17.0, 0.0] 53,900
720 [40.0, 4.0, 0.0, 17.0] 54,240
E3. Below 700 SAR the plan does not change. At exactly 700 SAR a Saffron Cake batch earns as much per staff hour as Date Maamoul (175 SAR), so both plans earn 53,900 SAR and the solver may return either (HiGHS keeps Date Maamoul); above 700 SAR the plan swaps all 17 batches of Date Maamoul for 17 of Saffron Cake. Saffron Cake’s contribution must rise by 140 SAR before it enters the plan: its reduced cost, another idea of next week.