Sensitivity Analysis: What Is One More Hour Worth?¶
Last week the solver found the best weekly plan of Qahwa House’s central kitchen: 40 batches of House Blend, 4 of Yemeni Haraz, 17 of Date Maamoul and no Saffron Cake, for 53,900 SAR a week. The roaster and the staff were binding; the oven had 6 hours to spare.
That plan rests on numbers that are estimates (contributions, demand) or that money can change (hours). A manager rarely asks only “what is the best plan?”. The next questions are: what would one more hour of the roaster be worth? How far can a price move before the plan changes? Which of the offers on my desk should I take? Answering them is sensitivity analysis, and an LP answers them almost for free.
This month the manager has four offers: a second roaster shift, staff overtime, hours on a neighbour’s oven, and a campaign to sell more House Blend. We will value each of them, and find that the most obvious way to do it ranks them wrongly.
After this reading you can:
define a shadow price and find it both by re-solving and from PuLP (
constraint.pi);explain why a constraint with slack has a shadow price of zero;
find the range over which a shadow price holds with a parameter sweep, and explain why it stops;
read reduced costs (
variable.dj) and price out a product against the shadow prices;find how far a contribution can move before the plan changes;
explain the dual: the shadow prices as a price list for the kitchen’s resources;
value a set of offers by re-solving the model, not by multiplying a shadow price.
Textbook: Albright & Winston, Business Analytics: Data Analysis and Decision Making, Chapter 13 (sensitivity analysis).
Setup¶
The first cell installs PuLP when you are in Colab; on your own computer, install it once with pip install "pulp[highs]>=4.3,<5". PuLP 4 needs a solver named explicitly; the course uses HiGHS (free, open source, installed by pulp[highs]), which also reports the shadow prices and reduced costs used here.
# 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") # this week's 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)
productsEach product’s contribution_sar per batch, the hours of the roaster, the oven and the staff one batch uses, and max_batches, the most the branches can sell in a week. The kitchen has 50 roaster hours, 40 oven hours and 160 staff hours a week.
1. The model as a function¶
We will solve the same model dozens of times with one number changed, so we wrap week 9’s model in a function. Besides the plan, it returns what the solver knows about each constraint and each variable once the LP is solved:
constraint.slack: the unused part of the resource;constraint.pi: the shadow price of the constraint (section 2);variable.dj: the reduced cost of the variable (section 4).
def solve_mix(products, capacity):
"""Solve the kitchen's weekly product-mix LP and return the plan and its sensitivity information."""
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,
"used": [capacity[r] - c[r].slack for r in HOURS],
"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}, name="reduced_cost") + 0.0,
}
base = solve_mix(products, capacity)
print(base["status"], f"· {base['profit']:,.0f} SAR a week")
print(base["plan"].to_string())
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 · 53,900 SAR a week
House Blend 40.0
Yemeni Haraz 4.0
Date Maamoul 17.0
Saffron Cake 0.0
The base plan is week 9’s: 40, 4, 17 and 0 batches, 53,900 SAR. The roaster and the staff have no slack; the oven has 6 hours. (The + 0.0 turns the solver’s “−0” into a plain 0.)
2. Shadow prices: what one more hour is worth¶
The simplest sensitivity question: what if we had one more hour? Give the kitchen one more hour of each resource in turn, re-solve, and compare the profit.
gain = {}
for r in HOURS:
more = capacity.copy()
more[r] += 1
gain[r] = solve_mix(products, more)["profit"] - base["profit"]
pd.DataFrame({"profit gain from one more hour": gain, "solver's shadow price": base["resources"]["shadow_price"]})One more roaster hour adds 390 SAR, one more staff hour 175 SAR, one more oven hour nothing. The solver reports the same numbers without re-solving: they are the constraints’ shadow prices (also called dual values or dual prices).
Shadow price of a constraint: the change in the optimal objective when the constraint’s right-hand side rises by one unit, all other numbers fixed.
It is the most a manager should pay for one more unit of the resource. A roaster hour that costs less than 390 SAR is worth buying; one that costs more is not.
Slack means a zero price. The oven already has 6 idle hours, so a seventh changes nothing. This is a general rule, called complementary slackness: a constraint with slack has a shadow price of 0, and a constraint with a positive shadow price is binding. Never pay for more of a resource you are not using up.
Where the 390 comes from¶
Why 390, when an hour of roaster earns 900 SAR on House Blend and 600 on Yemeni Haraz? Compare the two plans:
more = capacity.copy()
more["roast_h"] += 1
plus_one = solve_mix(products, more)
change = pd.DataFrame({"50 roaster hours": base["plan"], "51 roaster hours": plus_one["plan"]})
change["change"] = change["51 roaster hours"] - change["50 roaster hours"]
change["SAR"] = change["change"] * products["contribution_sar"]
change.round(2)House Blend is already at its demand limit, so the extra hour goes to Yemeni Haraz: +0.4 batch, worth +600 SAR. But 0.4 batch of Yemeni needs 1.2 staff hours, and the staff is fully used, so the solver takes them from Date Maamoul: −0.3 batch, −210 SAR. Net: 600 − 210 = 390 SAR.
A shadow price is not the profit of any single product: it includes every knock-on change the extra hour causes in the best plan. That is why only the model can compute it.
3. How far does a shadow price hold?¶
A shadow price is a rate, valid for small changes. If 1 roaster hour adds 390 SAR, do 30 hours add 30 × 390? Only if the plan keeps adjusting the same way. A parameter sweep answers it: solve the model for many values of one number and watch the profit.
def sweep(resource, values):
"""Re-solve the model for each value of one capacity; return the profit and the plan for each."""
rows = []
for v in values:
cap = capacity.copy()
cap[resource] = v
res = solve_mix(products, cap)
rows.append({resource: v, "profit": res["profit"], **res["plan"].round(2).to_dict()})
out = pd.DataFrame(rows).set_index(resource)
out["value of the last hour"] = out["profit"].diff() # profit(h) - profit(h - 1)
return out
staff = sweep("labour_h", range(80, 251))
roast = sweep("roast_h", range(30, 91))
staff.loc[[160, 170, 171, 172, 173, 174, 180, 232, 233]]Each extra staff hour is worth 175 SAR up to 172 hours. The 173rd is worth only 105 SAR. What happened at 172 hours? The extra staff hours were baking more Date Maamoul, 0.25 batch an hour, and at 172 hours the plan makes 20 batches, which need all 40 oven hours. The oven has become a second binding constraint. From then on an extra staff hour can only shift baking from Date Maamoul to Saffron Cake, which uses less oven time but earns less, so it is worth 105 SAR. Beyond 232 hours Saffron Cake reaches its demand limit of 30 batches and more staff is worth nothing.
fig, axes = plt.subplots(2, 2, figsize=(10, 6), sharex="col")
for col, (df, name, now) in enumerate([(staff, "staff hours", 160), (roast, "roaster hours", 50)]):
axes[0, col].plot(df.index, df["profit"] / 1000, color="C0", lw=2)
axes[0, col].axvline(now, color="grey", ls="--", lw=1)
axes[0, col].set_ylabel("best weekly profit (thousand SAR)")
axes[0, col].set_title(f"Re-solving for every number of {name}")
axes[1, col].step(df.index, df["value of the last hour"], where="pre", color="C3", lw=2)
axes[1, col].axvline(now, color="grey", ls="--", lw=1)
axes[1, col].set_ylabel("value of the last hour (SAR)")
axes[1, col].set_xlabel(f"{name} per week (dashed: this week)")
axes[1, 0].annotate("175 SAR up to 172 h:\nthe oven fills up", (172, 175), (182, 240), fontsize=9,
arrowprops=dict(arrowstyle="->", lw=0.8))
axes[1, 0].annotate("105 SAR", (200, 105), (205, 135), fontsize=9)
axes[1, 1].annotate("390 SAR from 40 to 80 h", (60, 390), (47, 480), fontsize=9)
axes[1, 0].set_ylim(-20, 420); axes[1, 1].set_ylim(-20, 760)
fig.tight_layout()
plt.show()
The profit is a piecewise linear curve of each capacity: straight while the same constraints bind, bending at each point where another constraint becomes binding or a variable reaches a limit. The shadow price is the slope of the current piece, so it drops in steps as the resource becomes less scarce. (Each kink is a degenerate point where the solver may report either neighbouring slope; between kinks the reported price is exact.)
The roaster’s price holds much longer: 390 SAR an hour from 40 to 80 hours. At 80 hours Yemeni Haraz reaches its demand limit of 16 batches and further roaster hours have nothing to roast. Below 40 hours House Blend can no longer fill its demand and each lost hour costs 690 SAR.
| Resource | Shadow price this week | Holds from | to | Why it stops |
|---|---|---|---|---|
| roaster | 390 SAR/h | 40 h | 80 h | below: House Blend leaves its limit; above: Yemeni Haraz reaches 16 |
| staff | 175 SAR/h | 92 h | 172 h | below: Date Maamoul reaches 0; above: the oven fills up |
| oven | 0 | 34 h | no limit | below 34 h the oven would bind |
Spreadsheet solvers print these ranges in a sensitivity report (“allowable increase” and “allowable decrease”). PuLP does not, but a sweep shows the same thing and also what happens beyond the range.
4. Reduced costs: pricing out the products¶
Shadow prices put a value on each hour. With them we can price out each product: what are the hours it uses worth in the best plan, and does its contribution cover them?
price = base["resources"]["shadow_price"]
pricing = pd.DataFrame({"contribution": products["contribution_sar"].astype(float),
"its hours, at shadow prices": products[HOURS] @ price})
pricing["difference"] = pricing["contribution"] - pricing["its hours, at shadow prices"]
pricing["solver's reduced cost"] = base["reduced_cost"]
pricing["batches"] = base["plan"]
pricingYemeni Haraz and Date Maamoul are made in between their limits, and their contribution exactly equals the value of their hours (2.5 × 390 + 3 × 175 = 1,500; 4 × 175 = 700). In an optimal plan, every product made “in between” breaks even at the shadow prices.
Saffron Cake uses 4 staff hours, which are worth 4 × 175 = 700 SAR as Date Maamoul, but it brings only 560. Its reduced cost is −140: each batch forced into the plan would cost 140 SAR of profit. It needs at least 140 SAR more contribution per batch, 700 SAR, to be worth making.
House Blend earns 160 SAR more than its hours are worth (reduced cost +160). It is held back only by its demand limit of 40 batches, so each extra batch the branches could sell would add 160 SAR.
The reduced cost (variable.dj) of a variable is this difference: how much the objective would change per unit if the variable were pushed away from its bound.
The branches’ proposal: cut the price of Saffron Cake¶
The branches suggest a 10% price cut on Saffron Cake (960 → 864 SAR a batch) so that they can sell 40 batches a week instead of 30. The reduced cost answers before we solve anything: Saffron Cake is already not worth making, and a lower price makes it worse; more demand for something we do not make is worth nothing. Let us confirm:
cut = products.copy()
cut.loc["Saffron Cake", "contribution_sar"] = 864 - 400 # new price minus the variable cost of 400 SAR
cut.loc["Saffron Cake", "max_batches"] = 40
after_cut = solve_mix(cut, capacity)
print(f"profit {after_cut['profit']:,.0f} SAR · Saffron Cake batches {after_cut['plan']['Saffron Cake']:.0f}")profit 53,900 SAR · Saffron Cake batches 0
Nothing changes: 53,900 SAR, still no Saffron Cake. Saffron Cake would enter the plan only if its contribution rose above 700 SAR, a price above 1,100 SAR a batch.
How far can a contribution move?¶
The same idea for every product: how far can its contribution move before the best plan changes? We sweep each contribution and keep the values for which this week’s plan (40, 4, 17 and 0) is still a best plan. At the edge of a range two plans tie for the best profit, and the solver may return either of them, so we do not ask which plan the solver returns: we ask whether this week’s plan still earns the best profit.
def plan_range(product, values):
"""The smallest and largest contribution in `values` for which this week's plan is still a best plan."""
same = []
for v in values:
changed = products.copy()
changed.loc[product, "contribution_sar"] = v
this_plan = (changed["contribution_sar"] * base["plan"]).sum() # this week's plan, at the new contribution
if np.isclose(this_plan, solve_mix(changed, capacity)["profit"]):
same.append(v)
return min(same), max(same)
grid = range(0, 2501, 5)
ranges = pd.DataFrame({p: plan_range(p, grid) for p in products.index}, index=["from", "to"]).T
ranges.insert(0, "now", products["contribution_sar"])
rangesRead the table with the grid in mind (0 to 2,500 SAR in steps of 5): an edge at 0 or 2,500 means “no limit in this direction”.
| Product | Now | This week’s plan stays a best plan for a contribution of | |
|---|---|---|---|
| House Blend | 900 | at least 740 | its hours are worth 390 + 2 × 175 = 740; above that, no limit: it is already at its demand |
| Yemeni Haraz | 1,500 | 525 to 1,900 | below 525 its 3 staff hours earn more as pastry; above 1,900 it displaces House Blend |
| Date Maamoul | 700 | 560 to 1,500 | below 560 Saffron Cake takes its place; above 1,500 it takes hours from House Blend |
| Saffron Cake | 560 | up to 700 | at 700 it ties with Date Maamoul and enters above it |
Inside its range a contribution can change and the plan stays the same, although the profit changes by (batches × change). A wide range means the plan is robust to errors in that estimate: Yemeni Haraz’s contribution could be off by several hundred riyals and the manager would still make 4 batches. A narrow range means the estimate deserves a second look.
5. The four offers¶
Now the manager’s question. Each offer adds hours (or demand) for a weekly cost:
options[["option", "adds_to", "amount", "unit", "cost_per_unit_sar", "weekly_cost_sar"]]The quick way to value an offer multiplies the shadow price by the amount. For the House Blend campaign the “shadow price” of its demand limit is House Blend’s reduced cost, 160 SAR a batch. The careful way re-solves the model with the offer included.
def apply(offers, products=products, capacity=capacity):
"""Copies of the model data with the chosen offers (rows of `options`) added."""
prod, cap = products.copy(), capacity.copy()
for _, o in offers.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
unit_value = {**base["resources"]["shadow_price"].to_dict(), "max_batches:House Blend": base["reduced_cost"]["House Blend"]}
value = options.set_index("option")[["amount", "weekly_cost_sar"]].copy()
value["shadow price × amount"] = [unit_value[o["adds_to"]] * o["amount"] for _, o in options.iterrows()]
value["re-solved gain"] = [solve_mix(*apply(options.iloc[[i]]))["profit"] - base["profit"] for i in range(len(options))]
value["net, by shadow price"] = value["shadow price × amount"] - value["weekly_cost_sar"]
value["net, re-solved"] = value["re-solved gain"] - value["weekly_cost_sar"]
valueBy the shadow price, staff overtime looks like the best offer: 24 hours × 175 SAR = 4,200 SAR for 3,120, a net +1,080 SAR a week. Re-solving says it earns only +240: the 175 SAR price holds for the first 12 hours (up to 172), and the other 12 are worth 105 SAR each, less than the 130 SAR they cost. The roaster shift (+900) stays inside its range (50 + 10 = 60 ≤ 80 hours), so for it the quick estimate is exact. The oven rental buys hours that nobody uses (−400 SAR). The campaign earns a modest +200.
fig, ax = plt.subplots(figsize=(8, 3.6))
y = np.arange(len(value))
ax.barh(y - 0.2, value["net, by shadow price"], height=0.38, color="C7", label="shadow price × amount − cost")
ax.barh(y + 0.2, value["net, re-solved"], height=0.38, color="C0", label="re-solved gain − cost")
for i, (a, b) in enumerate(zip(value["net, by shadow price"], value["net, re-solved"])):
ax.text(a + (30 if a >= 0 else -30), i - 0.2, f"{a:+,.0f}", va="center", ha="left" if a >= 0 else "right", fontsize=9)
ax.text(b + (30 if b >= 0 else -30), i + 0.2, f"{b:+,.0f}", va="center", ha="left" if b >= 0 else "right", fontsize=9)
ax.set_yticks(y, value.index)
ax.invert_yaxis()
ax.axvline(0, color="k", lw=0.8)
ax.set_xlim(-700, 1400)
ax.set_xlabel("net gain, SAR a week")
ax.set_title("Valuing each offer alone")
ax.legend(loc="lower right", fontsize=8)
fig.tight_layout()
plt.show()
How many overtime hours?¶
Overtime can be bought by the hour. Each hour inside the range earns 175 − 130 = 45 SAR; each hour beyond it loses 130 − 105 = 25 SAR. The sweep finds the best amount:
ot = pd.DataFrame({"hours": range(0, 25)})
ot["gain"] = [staff.loc[160 + h, "profit"] - base["profit"] for h in ot["hours"]]
ot["net"] = ot["gain"] - 130 * ot["hours"]
best = ot.loc[ot["net"].idxmax()]
print(f"best: {best['hours']:.0f} overtime hours, net {best['net']:+,.0f} SAR a week; all 24 hours: {ot['net'].iloc[-1]:+,.0f} SAR")best: 12 overtime hours, net +540 SAR a week; all 24 hours: +240 SAR
Alone, the kitchen should buy 12 overtime hours (+540 SAR a week), not 24.
6. Offers interact¶
A shadow price answers a question about one number with everything else fixed. When the manager takes two offers at once, the plan moves in two directions, and the ranges move too. With 4 offers there are 2⁴ = 16 combinations; the model is fast, so we try them all.
rows = []
for pick in itertools.product([False, True], repeat=len(options)):
chosen = options[list(pick)]
res = solve_mix(*apply(chosen))
rows.append({"offers": " + ".join(chosen["option"]) or "(none)",
"gain": res["profit"] - base["profit"],
"cost": chosen["weekly_cost_sar"].sum(),
"plan": ", ".join(f"{v:g}" for v in res["plan"].round(1))})
combos = pd.DataFrame(rows)
combos["net"] = combos["gain"] - combos["cost"]
combos.sort_values("net", ascending=False).reset_index(drop=True)The best combination is the roaster shift + overtime + campaign: +2,180 SAR a week. The roaster shift and the overtime together earn +1,980, much more than their separate gains (900 + 240 = 1,140). Why?
The roaster shift makes 4 more batches of Yemeni Haraz (8 instead of 4), which take 12 staff hours from Date Maamoul (14 batches instead of 17).
That frees 6 oven hours, so Date Maamoul can now grow by 6 batches before the oven fills. The staff’s 175 SAR range now runs up to 184 hours, and all 24 overtime hours earn 175 SAR.
The two offers are complements: each makes the other more valuable. A shadow price cannot see that; re-solving can. The oven rental helps in one case only: with the overtime and without the roaster shift, it lets the extra staff hours keep baking Date Maamoul (overtime + oven nets +680). Once the roaster shift is in, the oven has room again and the rental adds nothing.
7. The dual: a price list for the kitchen¶
Collect the shadow prices into a price list: roaster 390, oven 0, staff 175 SAR an hour, and 160 SAR for each batch of House Blend demand (its reduced cost; the other products’ demand limits are not binding, so they are worth 0). Now value everything the kitchen has at those prices:
resources_value = (capacity * price).sum()
demand_value = base["reduced_cost"].clip(lower=0) @ products["max_batches"].astype(float)
print(f"hours: {resources_value:,.0f} SAR + House Blend demand: {demand_value:,.0f} SAR = {resources_value + demand_value:,.0f} SAR")hours: 47,500 SAR + House Blend demand: 6,400 SAR = 53,900 SAR
50 × 390 + 40 × 0 + 160 × 175 + 40 × 160 = 53,900 SAR, exactly the best weekly profit. This is no coincidence. Imagine an outside company that wants to rent the whole kitchen for a week: every hour and every unit of demand. It must offer prices high enough that, for each product, the hours and demand that product uses are worth at least its contribution; otherwise the manager would rather make the product. The rent it pays is the price list times the quantities, and it looks for the cheapest acceptable price list. That is another LP, the dual of the kitchen’s LP:
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: # the hours and demand of each product must be worth at least its contribution
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, f"· cheapest rent: {pulp.value(dual.objective):,.0f} SAR")
pd.Series({v.name: v.value() for v in dual.variables()}).round(2)Optimal · cheapest rent: 53,900 SAR
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: float64The cheapest rent is 53,900 SAR, and the prices it sets are the shadow prices. Every LP has such a twin, its dual, and at the optimum the two objectives are equal (strong duality). The variables of the dual are the shadow prices of the original. You will rarely solve a dual by hand; the idea to keep is that shadow prices are the prices at which the kitchen’s resources are exactly worth what they earn.
8. Cautions¶
One number at a time, within its range. A shadow price or a reduced cost describes a small change of one number. For larger changes or several at once, re-solve (sections 3 and 6).
Linear programs only. Shadow prices come from the continuous LP. With whole batches (integer variables, week 12) there are no shadow prices; re-solving still works. Here, the whole-batch model happens to give the same values for these offers.
Degenerate points. Exactly at a kink, as at 172 staff hours, the solver may report either neighbouring price. If a shadow price matters to a decision, check it by re-solving with a little more and a little less.
The model’s own numbers are estimates. Sensitivity analysis tells you which estimates matter: those with narrow ranges. Simulation (week 14) lets them vary together.
Check your understanding¶
The oven’s shadow price is 0. Explain why, and what that says about the oven rental offer.
The roaster’s shadow price is 390 SAR an hour. How much would 20 more roaster hours add, and how do you know?
Saffron Cake’s reduced cost is −140. What does that mean for the branches’ price-cut proposal?
Why does the overtime look better than the roaster shift when valued by shadow prices, and worse when re-solved?
Why are the roaster shift and the overtime worth more together than separately?