Lab 9: Product Mix Model in PuLP¶
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 = ...
capacity = ...
capacitycheck("A1 four products", len(products) == 4)
check("A1 50 roaster hours, 40 oven hours, 160 staff hours", list(capacity) == [50, 40, 160])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).
Your answer here (double-click to edit).
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 += ..., "contribution" # the objective
roastery += ..., "roaster" # roaster hours
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))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)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"] = ...
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)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 = ...
per_roaster_hourcheck("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)B4. In two sentences: why does the best coffee plan make only 4 batches of Yemeni Haraz, the product with the highest margin?
Your answer here (double-click to edit).
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 += ..., "contribution"
for r in HOURS:
m += ... <= 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))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)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 = ...
usage = ...
print(plan.to_string())
usagecheck("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)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.
Your answer here (double-click to edit).
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_used = ...
print(manager_profit)
manager_usedcheck("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)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 = ...
gap_year = ...
print(f"{gap:,.0f} SAR a week, {gap_year:,.0f} 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)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 += ...
strict += ...
strict_status = ...
strict_statuscheck("D3 both promises cannot be kept", strict_status == "Infeasible")D4. In one sentence: which constraint makes the two promises impossible, and by how many hours?
Your answer here (double-click to edit).
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.
Write your recommendation here (double-click to edit).
★ 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?
# E1# E2# E3AI-use log (if you used an AI assistant)¶
What you asked, what you kept, what you changed.