Lab 10 Solutions: What-If App over a Linear Program¶
These are the worked solutions, with outputs. Try the lab yourself first.
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": [c[r].pi for r in HOURS]}, index=HOURS) + 0.0,
"reduced_cost": pd.Series({p: x[p].dj for p in products.index}) + 0.0,
}
base = solve_mix(products, capacity)
print(base["status"], base["profit"])
base["resources"]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 53900.0
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))✅ A1 the base plan earns 53,900 SAR
✅ A1 shadow prices: roaster 390, oven 0, staff 175
✅ A1 reduced costs: House Blend +160, 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()
more["roast_h"] += 1
gain_roaster = solve_mix(products, more)["profit"] - base["profit"]
more = capacity.copy()
more["oven_h"] += 1
gain_oven = solve_mix(products, more)["profit"] - base["profit"]
print(gain_roaster, gain_oven)390.0 0.0
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)✅ A2 one more roaster hour adds 390 SAR
✅ A2 one more oven hour adds nothing
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?
A3. The best plan uses only 34 of the 40 oven hours, so the oven constraint has 6 hours of slack, and an extra hour would sit idle: a constraint with slack always has a shadow price of 0. Renting 10 more oven hours for 400 SAR a week therefore adds nothing to the profit at this plan; it can only lose 400 SAR, unless some other change makes the oven binding.
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": solve_mix(products, cap)["profit"]})
staff_sweep = pd.DataFrame(rows).set_index("labour_h")
staff_sweep["value of the last hour"] = staff_sweep["profit"].diff()
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))✅ B1 51 values, from 150 to 200 hours
✅ B1 each hour up to 172 is worth 175 SAR
✅ B1 from the 173rd hour an hour is worth 105 SAR
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 = 24 * base["resources"].loc["labour_h", "shadow_price"]
overtime_gain = staff_sweep.loc[184, "profit"] - base["profit"]
print(f"by the shadow price: {naive_gain:,.0f} SAR · re-solved: {overtime_gain:,.0f} SAR · cost: 3,120 SAR")by the shadow price: 4,200 SAR · re-solved: 3,360 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)✅ B3 the shadow price promises 4,200 SAR
✅ B3 the overtime really adds 3,360 SAR
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: staff_sweep.loc[160 + h, "profit"] - base["profit"] - 130 * h for h in range(0, 25)})
best_hours = net.idxmax()
best_net = net.max()
print(best_hours, best_net)12 540.0
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)✅ B4 buy 12 overtime hours
✅ B4 they add 540 SAR a week, net
✅ B4 all 24 hours add only 240 SAR, net
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)})B5. The shadow price of 175 SAR describes small changes only: each extra staff hour bakes a quarter batch more Date Maamoul, until at 172 hours the plan makes 20 batches and all 40 oven hours are used. From there the oven is a second bottleneck, and an extra staff hour can only shift baking from Date Maamoul to Saffron Cake, which is worth 105 SAR, less than the 130 SAR the overtime costs. So only the first 12 hours earn 175 SAR; “24 × 175” assumes the price holds beyond the end of its range.
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 = products[HOURS] @ prices
reduced = products["contribution_sar"] - hours_value
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"]))✅ C1 Saffron Cake's hours are worth 700 SAR
✅ C1 the products made between their limits break even
✅ C1 the differences match the solver's reduced costs
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()
cut.loc["Saffron Cake", "contribution_sar"] = 864 - 400
cut.loc["Saffron Cake", "max_batches"] = 40
after_cut = solve_mix(cut, capacity)
print(after_cut["profit"], after_cut["plan"]["Saffron Cake"])53900.0 0.0
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)✅ C2 the new contribution is 464 SAR
✅ C2 the profit does not change
✅ C2 still no Saffron Cake
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.
C3. Saffron Cake’s reduced cost is −140: its 4 staff hours are worth 700 SAR as Date Maamoul, and it brings only 560, so the plan makes none, and more demand for a product we do not make is worth nothing, while a lower price makes it even less attractive. It would enter the plan only with a contribution above 700 SAR, that is a price above 700 + 400 = 1,100 SAR a batch.
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"] = st.sidebar.slider("Oven hours", 0, 80, 40)
cap["labour_h"] = st.sidebar.slider("Staff hours", 0, 320, 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 += o["weekly_cost_sar"]
if o["adds_to"].startswith("max_batches:"):
prod.loc[o["adds_to"].split(":")[1], "max_batches"] += o["amount"]
else:
cap[o["adds_to"]] += o["amount"]
# 3. Solve with the offers, and show
profit, plan, prices = solve(prod, cap)
net = profit - without_offers - 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)Overwriting whatif_app.py
# 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")✅ D1 the app runs without an error
✅ D1 three sliders and four offers
✅ D1 this week's plan earns 53,900 SAR
overtime alone: +240
✅ D1 the overtime alone nets +240 SAR
roaster shift + overtime: +1,980
✅ D1 the roaster shift and the overtime together net +1,980 SAR
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.
Recommendation. Take the second roaster shift, the staff overtime and the House Blend campaign together: with them the best plan becomes 45, 6, 19 and 0 batches and earns 8,900 SAR a week more, a net gain of 2,180 SAR a week after their 6,720 SAR cost (the roaster shift and the overtime alone net 1,980 SAR); do not rent the oven, which adds nothing once the roaster shift is taken. On its own the overtime would net only 240 SAR, not the 1,080 SAR its shadow price suggests, because the 175 SAR an hour holds only up to 172 staff hours, where the oven fills up; the roaster shift moves that limit, since it takes staff hours away from Date Maamoul, so all 24 overtime hours become worth 175 SAR. Before signing I would check the campaign’s promise of 5 more batches of House Blend a week, since the campaign adds just 200 SAR a week and the plan depends on its demand limit.
★ 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.
def with_offers(chosen):
"""Copies of the model data with the chosen offers added."""
prod, cap = products.copy(), capacity.copy()
for _, o in chosen.iterrows():
if o["adds_to"].startswith("max_batches:"):
prod.loc[o["adds_to"].split(":")[1], "max_batches"] += o["amount"]
else:
cap[o["adds_to"]] += o["amount"]
return prod, cap
rows = []
for pick in itertools.product([False, True], repeat=len(options)):
chosen = options[list(pick)]
res = solve_mix(*with_offers(chosen))
rows.append({"offers": " + ".join(chosen["option"]) or "(none)", "gain": res["profit"] - base["profit"],
"cost": chosen["weekly_cost_sar"].sum()})
combos = pd.DataFrame(rows)
combos["net"] = combos["gain"] - combos["cost"]
combos.sort_values("net", ascending=False).head(6)E1. The best combination is the roaster shift + overtime + campaign, +2,180 SAR a week net. The roaster shift and the overtime are complements: alone they net +900 and +240, together +1,980. The roaster shift makes 4 more batches of Yemeni Haraz, which take 12 staff hours from Date Maamoul and free 6 oven hours; the staff’s 175 SAR price then holds up to 184 hours, so all 24 overtime hours earn it. The oven rental helps only without the roaster shift (overtime + oven nets +680, against +240 for the overtime alone); in every combination with the roaster shift it adds nothing and costs 400 SAR.
dual = pulp.LpProblem("rent_the_kitchen", pulp.LpMinimize)
p_hour = {r: dual.add_variable("price_" + r, lowBound=0) for r in HOURS}
p_dem = {q: dual.add_variable("demand_" + q.replace(" ", "_"), lowBound=0) for q in products.index}
dual += (pulp.lpSum(capacity[r] * p_hour[r] for r in HOURS)
+ pulp.lpSum(float(products.loc[q, "max_batches"]) * p_dem[q] for q in products.index))
for q in products.index:
dual += pulp.lpSum(products.loc[q, r] * p_hour[r] for r in HOURS) + p_dem[q] >= float(products.loc[q, "contribution_sar"]), q
res = dual.solve(pulp.HiGHS(msg=False))
print(res.status.name, pulp.value(dual.objective))
pd.Series({v.name: v.value() for v in dual.variables()})Optimal 53900.0
price_roast_h 390.0
price_oven_h 0.0
price_labour_h 175.0
demand_House_Blend 160.0
demand_Yemeni_Haraz 0.0
demand_Date_Maamoul 0.0
demand_Saffron_Cake 0.0
dtype: float64E2. The cheapest acceptable rent is 53,900 SAR, the best weekly profit (strong duality). Its prices are the shadow prices of Part A: 390 SAR per roaster hour, 0 per oven hour, 175 per staff hour, and 160 SAR per batch of House Blend demand (House Blend’s reduced cost); the other demand limits are worth 0 because they do not bind.
def solve_integer(products, capacity):
model = pulp.LpProblem("weekly_mix_int", pulp.LpMaximize)
x = {p: model.add_variable(p.replace(" ", "_"), lowBound=0, upBound=float(products.loc[p, "max_batches"]), cat="Integer")
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))
return pulp.value(model.objective), {p: x[p].value() + 0.0 for p in products.index}
best_offers = options[options["option"] != "Oven rental"]
for name, (prod, cap) in {"no offer": (products, capacity), "best combination": with_offers(best_offers)}.items():
print(name, solve_integer(prod, cap), "· LP:", solve_mix(prod, cap)["profit"])no offer (53900.0, {'House Blend': 40.0, 'Yemeni Haraz': 4.0, 'Date Maamoul': 17.0, 'Saffron Cake': 0.0}) · LP: 53900.0
best combination (62800.0, {'House Blend': 45.0, 'Yemeni Haraz': 6.0, 'Date Maamoul': 19.0, 'Saffron Cake': 0.0}) · LP: 62800.0
E3. With whole batches the best combination still earns 62,800 SAR a week (45, 6, 19 and 0 batches), exactly the LP value, and the base plan still earns 53,900: the LP plans are already whole numbers, so the recommendation does not change. That is luck, not a rule: in week 9’s E2 a single extra roaster hour was worth 390 SAR in the LP and nothing in whole batches.
# In the app, after the offers loop: value each offer alone against the scenario without offers.
def offer_table(products, cap, base_profit, prices):
rows = []
for _, o in options.iterrows():
prod2, cap2 = products.copy(), cap.copy()
if o["adds_to"].startswith("max_batches:"):
prod2.loc[o["adds_to"].split(":")[1], "max_batches"] += o["amount"]
estimate = None # the demand limit has no constraint price in this app
else:
cap2[o["adds_to"]] += o["amount"]
estimate = prices[o["adds_to"]] * o["amount"]
gain = solve_mix(prod2, cap2)["profit"] - base_profit
rows.append({"offer": o["option"], "shadow price × amount": estimate, "re-solved gain": gain,
"net": gain - o["weekly_cost_sar"]})
return pd.DataFrame(rows).set_index("offer")
# what st.dataframe(offer_table(...)) would show in the app, at this week's hours:
offer_table(products, capacity, base["profit"], base["resources"]["shadow_price"])E4. In the app, call st.dataframe(offer_table(products, cap_without_offers, without_offers, prices_without_offers)) (with the app’s own solve). The table shows at a glance that the overtime’s shadow-price estimate (4,200 SAR) is above its re-solved gain (3,360 SAR), the sign that the change leaves the range of its shadow price. The course version, week10/app/app.py, also values the campaign with House Blend’s reduced cost.