Lab 10: What-If App over a Linear Program¶
In this lab you take the weekly plan of Qahwa House’s central kitchen (week 9) and ask what it is worth to change it: one more hour, a lower price, an offer from a supplier. Then you package the model in a Streamlit app the manager can play with.
The question. Four offers are on the manager’s desk for next month: a second roaster shift, staff overtime, hours on a neighbour’s oven and a House Blend campaign. Which should the kitchen take? Valued with the shadow prices, the overtime looks like the best of the four. Is it?
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, plus your
whatif_app.py.
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), with the HiGHS solver.
import sys
if "google.colab" in sys.modules:
%pip install -q "pulp[highs]>=4.3,<5"import itertools
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") # week 9's model data
options = load("qahwa_roastery_options.csv") # the four offers
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)
options[["option", "adds_to", "amount", "unit", "cost_per_unit_sar", "weekly_cost_sar"]]products holds the four products (contribution per batch, hours of roaster, oven and staff per batch, max_batches the branches can sell); capacity the 50 roaster, 40 oven and 160 staff hours of a week. Each offer adds amount to a capacity (roast_h, oven_h, labour_h) or to the demand limit of House Blend, for weekly_cost_sar a week.
Part A: Shadow prices and reduced costs¶
A1. The model as a function¶
solve_mix builds and solves week 9’s model and returns the plan with its sensitivity information. Complete the two gaps: the shadow price of each resource constraint is c[r].pi, and the reduced cost of each variable is x[p].dj.
def solve_mix(products, capacity):
"""Solve the kitchen's weekly LP; return the profit, the plan, the resources table and the reduced costs."""
model = pulp.LpProblem("weekly_mix", pulp.LpMaximize)
x = {p: model.add_variable(p.replace(" ", "_"), lowBound=0, upBound=float(products.loc[p, "max_batches"]))
for p in products.index}
model += pulp.lpSum(float(products.loc[p, "contribution_sar"]) * x[p] for p in products.index)
for r in HOURS:
model += pulp.lpSum(products.loc[p, r] * x[p] for p in products.index) <= capacity[r], r
res = model.solve(pulp.HiGHS(msg=False))
c = {con.name: con for con in model.constraints()} # PuLP 4: constraints() is a list; index them by name
return {
"status": res.status.name,
"profit": pulp.value(model.objective),
"plan": pd.Series({p: x[p].value() for p in products.index}, name="batches"),
"resources": pd.DataFrame({"available": capacity,
"slack": [c[r].slack for r in HOURS],
"shadow_price": [... for r in HOURS]}, index=HOURS) + 0.0,
"reduced_cost": pd.Series({p: ... for p in products.index}) + 0.0,
}
base = solve_mix(products, capacity)
print(base["status"], base["profit"])
base["resources"]check("A1 the base plan earns 53,900 SAR", abs(base["profit"] - 53_900) < 1)
check("A1 shadow prices: roaster 390, oven 0, staff 175", np.allclose(base["resources"]["shadow_price"], [390, 0, 175]))
check("A1 reduced costs: House Blend +160, Saffron Cake -140",
np.isclose(base["reduced_cost"]["House Blend"], 160) and np.isclose(base["reduced_cost"]["Saffron Cake"], -140))A2. Check a shadow price by re-solving¶
A shadow price is a promise: one more hour adds this much to the best profit. Check two of them. Store in gain_roaster the profit with 51 roaster hours minus the base profit, and in gain_oven the same with 41 oven hours. (Copy capacity first: more = capacity.copy().)
more = capacity.copy()
...
gain_roaster = ...
more = capacity.copy()
...
gain_oven = ...
print(gain_roaster, gain_oven)check("A2 one more roaster hour adds 390 SAR", abs(gain_roaster - 390) < 1e-6)
check("A2 one more oven hour adds nothing", abs(gain_oven) < 1e-6)A3. In two sentences: why is the oven’s shadow price 0, and what does that tell you about the oven rental offer before you solve anything?
Your answer here (double-click to edit).
Part B: How far does a shadow price hold?¶
B1. Sweep the staff hours¶
Solve the model for every number of staff hours from 150 to 200. Store the results in a DataFrame staff_sweep, indexed by the hours, with a column profit. Then add a column value of the last hour: the profit minus the profit with one hour less (.diff()).
rows = []
for h in range(150, 201):
cap = capacity.copy()
cap["labour_h"] = h
rows.append({"labour_h": h, "profit": ...})
staff_sweep = pd.DataFrame(rows).set_index("labour_h")
staff_sweep["value of the last hour"] = ...
staff_sweep.loc[168:176]v = staff_sweep["value of the last hour"]
check("B1 51 values, from 150 to 200 hours", len(staff_sweep) == 51 and staff_sweep.index[0] == 150)
check("B1 each hour up to 172 is worth 175 SAR", np.allclose(v.loc[151:172], 175))
check("B1 from the 173rd hour an hour is worth 105 SAR", np.allclose(v.loc[173:200], 105))B2. See it¶
Run the cell: it draws the value of each extra staff hour.
fig, ax = plt.subplots(figsize=(7, 3.2))
ax.step(staff_sweep.index, staff_sweep["value of the last hour"], where="pre", color="C3", lw=2)
ax.axvline(160, color="grey", ls="--", lw=1)
ax.axhline(130, color="C0", ls=":", lw=1.5)
ax.text(186, 136, "overtime: 130 SAR/h", color="C0", fontsize=9)
ax.set_ylim(0, 220)
ax.set_xlabel("staff hours per week (dashed: this week)")
ax.set_ylabel("value of the last hour (SAR)")
ax.set_title("What each extra staff hour is worth")
plt.show()B3. The overtime offer¶
The overtime offer adds 24 staff hours for 130 SAR an hour (3,120 SAR a week). Store in naive_gain the gain you would expect from the shadow price (24 × the staff’s shadow price), and in overtime_gain the real gain: the profit with 184 staff hours minus the base profit (use staff_sweep).
naive_gain = ...
overtime_gain = ...
print(f"by the shadow price: {naive_gain:,.0f} SAR · re-solved: {overtime_gain:,.0f} SAR · cost: 3,120 SAR")check("B3 the shadow price promises 4,200 SAR", abs(naive_gain - 4_200) < 1e-6)
check("B3 the overtime really adds 3,360 SAR", abs(overtime_gain - 3_360) < 1e-6)B4. How many overtime hours?¶
Overtime can be bought by the hour. For each number of hours from 0 to 24, the net gain is the profit gain minus 130 SAR per hour. Store the best number of hours in best_hours and its net gain in best_net.
net = pd.Series({h: ... for h in range(0, 25)})
best_hours = ...
best_net = ...
print(best_hours, best_net)check("B4 buy 12 overtime hours", best_hours == 12)
check("B4 they add 540 SAR a week, net", abs(best_net - 540) < 1e-6)
check("B4 all 24 hours add only 240 SAR, net", abs(net[24] - 240) < 1e-6)B5. In two or three sentences: why does “24 × 175” overstate the value of the overtime? What happens in the kitchen at 172 staff hours? (Hint: look at the plan with 172 and with 173 staff hours.)
def with_staff(h):
cap = capacity.copy()
cap["labour_h"] = h
return cap
pd.DataFrame({f"{h} staff hours": solve_mix(products, with_staff(h))["plan"] for h in (160, 172, 173)})Your answer here (double-click to edit).
Part C: Reduced costs¶
C1. Price out the products¶
Value the hours each product uses at the shadow prices: hours_value is a Series (one value per product) equal to the product’s hours times the shadow prices, summed over the three resources (products[HOURS] @ prices). Then reduced = contribution − hours_value.
prices = base["resources"]["shadow_price"]
hours_value = ...
reduced = ...
pd.DataFrame({"contribution": products["contribution_sar"], "hours, at shadow prices": hours_value,
"difference": reduced, "solver's reduced cost": base["reduced_cost"], "batches": base["plan"]})check("C1 Saffron Cake's hours are worth 700 SAR", np.isclose(hours_value["Saffron Cake"], 700))
check("C1 the products made between their limits break even", np.allclose(reduced[["Yemeni Haraz", "Date Maamoul"]], 0))
check("C1 the differences match the solver's reduced costs", np.allclose(reduced, base["reduced_cost"]))C2. The branches’ proposal¶
The branches propose to cut the price of Saffron Cake by 10%, from 960 to 864 SAR a batch (its variable cost stays 400 SAR), so that they can sell 40 batches a week instead of 30. Make a copy cut of products with the new contribution and demand limit, solve it, and store the result in after_cut.
cut = products.copy()
...
...
after_cut = ...
print(after_cut["profit"], after_cut["plan"]["Saffron Cake"])check("C2 the new contribution is 464 SAR", cut.loc["Saffron Cake", "contribution_sar"] == 464)
check("C2 the profit does not change", abs(after_cut["profit"] - 53_900) < 1e-6)
check("C2 still no Saffron Cake", abs(after_cut["plan"]["Saffron Cake"]) < 1e-6)C3. In two sentences: use the reduced cost to explain the result of C2, and say from what price per batch Saffron Cake would be worth making.
Your answer here (double-click to edit).
Part D: The what-if app¶
D1. Fill in the app¶
The next cell writes a Streamlit app to whatif_app.py. The manager sets the hours of each resource and ticks the offers; the app re-solves the model and shows the plan, the shadow prices and the net gain of the offers: the profit with the offers, minus the profit without them, minus their cost. Fill in the five gaps marked ..., run the cell, then run the test cell under it.
%%writefile whatif_app.py
import pandas as pd
import pulp
import streamlit as st
URL = "https://chebil.github.io/BusinessDecision/data/"
HOURS = ["roast_h", "oven_h", "labour_h"]
@st.cache_data
def load(name):
try:
return pd.read_csv(URL + name)
except Exception:
return pd.read_csv("../data/" + name)
mix = load("qahwa_roastery_mix.csv")
options = load("qahwa_roastery_options.csv")
products = mix[mix["product"] != "capacity"].set_index("product")
capacity = mix.set_index("product").loc["capacity", HOURS].astype(float)
def solve(products, capacity):
model = pulp.LpProblem("weekly_mix", pulp.LpMaximize)
x = {p: model.add_variable(p.replace(" ", "_"), lowBound=0, upBound=float(products.loc[p, "max_batches"]))
for p in products.index}
model += pulp.lpSum(float(products.loc[p, "contribution_sar"]) * x[p] for p in products.index)
for r in HOURS:
model += pulp.lpSum(products.loc[p, r] * x[p] for p in products.index) <= capacity[r], r
res = model.solve(pulp.HiGHS(msg=False))
plan = pd.Series({p: x[p].value() for p in products.index}, name="batches")
prices = pd.Series({r: model.get_constraint_by_name(r).pi for r in HOURS}, name="shadow price (SAR/h)") + 0.0
return pulp.value(model.objective), plan, prices
st.title("Qahwa House · kitchen what-if")
# 1. The hours, in the sidebar
cap = capacity.copy()
cap["roast_h"] = st.sidebar.slider("Roaster hours", 0, 100, 50)
cap["oven_h"] = ... # a slider "Oven hours" from 0 to 80, default 40
cap["labour_h"] = ... # a slider "Staff hours" from 0 to 320, default 160
without_offers, _, _ = solve(products, cap)
# 2. The offers, as checkboxes
prod = products.copy()
cost = 0
for _, o in options.iterrows():
if st.sidebar.checkbox(o["option"]):
cost += ... # the offer's weekly cost
if o["adds_to"].startswith("max_batches:"):
prod.loc[o["adds_to"].split(":")[1], "max_batches"] += o["amount"]
else:
cap[o["adds_to"]] += ... # the offer's amount
# 3. Solve with the offers, and show
profit, plan, prices = solve(prod, cap)
net = ... # profit with the offers - without them - their cost
c1, c2 = st.columns(2)
c1.metric("Weekly contribution (SAR)", f"{profit:,.0f}")
c2.metric("Net gain of the offers (SAR)", f"{net:+,.0f}")
st.subheader("The plan")
st.dataframe(plan.round(1))
st.subheader("Shadow prices")
st.dataframe(prices)# Run the app in the notebook without a browser: Streamlit's AppTest executes it like a visitor would.
import importlib.util, subprocess, sys
if importlib.util.find_spec("streamlit") is None: # Colab does not ship Streamlit
subprocess.run([sys.executable, "-m", "pip", "install", "-q", "streamlit"], check=True)
import logging
from pathlib import Path
from streamlit.testing.v1 import AppTest
for name in ("streamlit", "streamlit.runtime.scriptrunner_utils.script_run_context"):
logging.getLogger(name).setLevel(logging.ERROR) # quiet "missing ScriptRunContext" notices
at = AppTest.from_file(str(Path("whatif_app.py").resolve()), default_timeout=90).run()
check("D1 the app runs without an error", not at.exception)
if at.exception:
print(at.exception[0].message)
else:
metric = lambda label: next(m.value for m in at.metric if m.label == label)
check("D1 three sliders and four offers", len(at.slider) == 3 and len(at.checkbox) == 4)
check("D1 this week's plan earns 53,900 SAR", metric("Weekly contribution (SAR)") == "53,900")
at.checkbox[1].check().run() # the overtime alone
print("overtime alone:", metric("Net gain of the offers (SAR)"))
check("D1 the overtime alone nets +240 SAR", metric("Net gain of the offers (SAR)") == "+240")
at.checkbox[0].check().run() # plus the roaster shift
print("roaster shift + overtime:", metric("Net gain of the offers (SAR)"))
check("D1 the roaster shift and the overtime together net +1,980 SAR", metric("Net gain of the offers (SAR)") == "+1,980")D2. See it in a browser¶
Colab cannot show a Streamlit page, so open it in GitHub Codespaces (free with GitHub Education) or on your own computer:
Put
whatif_app.pyin a folder, open a terminal there and runpip install streamlit pandas "pulp[highs]>=4.3,<5".Run
streamlit run whatif_app.py; a browser tab opens athttp://localhost:8501. (Away from the course repository, the app downloads the data from the course website.)To share it, push the file and a
requirements.txt(streamlit, pandas,pulp[highs]>=4.3,<5) to a GitHub repository and deploy it on Streamlit Community Cloud (share.streamlit.io).
The course’s finished version, with each offer valued alone, the contributions and demand limits, the reduced costs and a sweep chart of any resource, is week10/app/app.py in the course repository.
D3. Your recommendation¶
Use your app: tick the offers one at a time, then in combinations. Then write three sentences for the manager: which offers to take next month (with the net gain in SAR a week), why the overtime on its own is a weaker deal than its shadow price suggests, and one number in the model you would check before signing.
Write your recommendation here (double-click to edit).
★ Extended challenges¶
E1. Every combination. With 4 offers there are 16 combinations. Solve the model for each (itertools.product([False, True], repeat=4)) and rank them by net gain. Which combination is best, and which two offers are worth more together than apart?
E2. Rent the kitchen. Write and solve the dual LP: choose a price for each hour of the three resources and for each batch of demand of each product, to minimise the total value of the kitchen’s hours and demand limits, such that for every product the hours and the demand it uses are worth at least its contribution. Compare the optimal value and the prices with Part A.
E3. Whole batches. Solve the model for the best combination of E1 with every variable cat="Integer". Does the recommendation change?
E4. A better app. Add to your app a table with each offer valued alone (shadow price × amount, re-solved gain, net), as in section 5 of the reading.
# E1Your answer here (double-click to edit).
# E2Your answer here (double-click to edit).
# E3Your answer here (double-click to edit).
# E4Your answer here (double-click to edit).
AI-use log (if you used an AI assistant)¶
What you asked, what you kept, what you changed.