Lab 12 Solutions: Capital Budgeting and Facility Location¶
These are the worked solutions, with outputs. Try the lab yourself first.
The questions. Qahwa House has a capital budget of 1,000 k SAR for this year’s projects, and wants to open drive-through kiosks in north Riyadh. Which projects should it fund, and which kiosks should it open?
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.
# 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 no solver: the [highs] extra adds HiGHS, a free open-source solver.
# The first model you solve prints two lines about HiGHS (its version and licence): that is normal.
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)
projects = load("qahwa_projects.csv").fillna("")
sites = load("qahwa_sites.csv")
projects| File and column | Meaning |
|---|---|
| qahwa_projects.csv | one row per project |
project, name, area | the project |
cost_ksar | what it costs (k SAR) |
npv_ksar | its net present value over five years after paying for it (k SAR) |
requires | a project that must also be funded for this one to work (empty if none) |
excludes | a project that cannot be funded together with this one (empty if none) |
| qahwa_sites.csv | one row per (candidate kiosk site, district) pair |
site, yearly_cost_ksar, capacity_cups | the site, the yearly cost of a kiosk there (k SAR) and the most cups a day it can serve |
district, district_cups | the district and the cups a day its residents would buy at a kiosk within reach |
minutes | driving time between the district and the site |
The road and district names set the scene; the times, costs and demands are invented.
Part A: Capital budgeting¶
A1. More projects than money¶
Store the total cost of all ten projects in total_cost and their total NPV in total_npv (in k SAR). The Series cost and npv below are indexed by the project code.
cost = projects.set_index("project")["cost_ksar"]
npv = projects.set_index("project")["npv_ksar"]
total_cost = cost.sum()
total_npv = npv.sum()
total_cost, total_npv(np.int64(2600), np.int64(2790))check("A1 the ten projects cost 2,600 k SAR", total_cost == 2600)
check("A1 and would add 2,790 k SAR of NPV", total_npv == 2790)✅ A1 the ten projects cost 2,600 k SAR
✅ A1 and would add 2,790 k SAR of NPV
A2. A first binary model¶
Complete the model: one binary variable per project (already created), the objective (maximise the total NPV) and the budget constraint (total cost at most 1,000). Ignore the requires and excludes columns for now. Store the optimal NPV in npv_no_rules and the list of funded projects in funded_no_rules.
m = pulp.LpProblem("capital_budgeting", pulp.LpMaximize)
x = m.add_variable_dicts("fund", cost.index, cat="Binary")
m += pulp.lpSum(npv[p] * x[p] for p in cost.index) # the objective: total NPV
m += pulp.lpSum(cost[p] * x[p] for p in cost.index) <= 1000 # the budget constraint
res = m.solve(pulp.HiGHS(msg=False))
npv_no_rules = pulp.value(m.objective)
funded_no_rules = [p for p in cost.index if x[p].value() > 0.5]
print(res.status.name, npv_no_rules, funded_no_rules)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 1300.0 ['P2', 'P3', 'P5', 'P6']
check("A2 an NPV of 1,300 k SAR", round(npv_no_rules) == 1300)
check("A2 within the budget", cost[funded_no_rules].sum() <= 1000)
check("A2 it funds the app (P2) without the POS system it needs (P1)", "P2" in funded_no_rules and "P1" not in funded_no_rules)✅ A2 an NPV of 1,300 k SAR
✅ A2 within the budget
✅ A2 it funds the app (P2) without the POS system it needs (P1)
A3. Add the logical rules¶
Complete the function capital_budget(budget, cat). It must add, for every row of projects:
if
requiresis not empty: fund this project only if the required one is funded, ;if
excludesis not empty: not both, .
Then store the best NPV for a budget of 1,000 in npv_rules and the funded projects in plan.
def capital_budget(budget, cat="Binary"):
"""Best projects within the budget, with the rules. Returns (NPV, x as a Series)."""
m = pulp.LpProblem("capital_budgeting", pulp.LpMaximize)
x = m.add_variable_dicts("fund", cost.index, lowBound=0, upBound=1, cat=cat)
m += pulp.lpSum(npv[p] * x[p] for p in cost.index)
m += pulp.lpSum(cost[p] * x[p] for p in cost.index) <= float(budget) # float(): PuLP 4 refuses a NumPy integer after <= or >=
for _, row in projects.iterrows():
if row["requires"]:
m += x[row["project"]] <= x[row["requires"]]
if row["excludes"]:
m += x[row["project"]] + x[row["excludes"]] <= 1
res = m.solve(pulp.HiGHS(msg=False))
return pulp.value(m.objective), pd.Series({p: x[p].value() for p in cost.index})
npv_rules, x_rules = capital_budget(1000)
plan = list(x_rules[x_rules > 0.5].index)
print(npv_rules, plan, cost[plan].sum())1200.0 ['P1', 'P2', 'P3', 'P5', 'P10'] 1000
check("A3 the rules cost 100 k SAR of NPV: 1,200", round(npv_rules) == 1200)
check("A3 the POS system is funded with the app and the delivery link", {"P1", "P2", "P3"} <= set(plan))
check("A3 not both the roaster and the cold-brew line", not {"P4", "P5"} <= set(plan))
check("A3 the plan spends the whole budget", cost[plan].sum() == 1000)✅ A3 the rules cost 100 k SAR of NPV: 1,200
✅ A3 the POS system is funded with the app and the delivery link
✅ A3 not both the roaster and the cold-brew line
✅ A3 the plan spends the whole budget
Part B: Rounding and the budget¶
B1. The LP relaxation¶
Solve the same model with continuous variables between 0 and 1 (cat="Continuous"). Store the NPV in lp_npv and the variables in lp_x. How many projects are funded only partly?
lp_npv, lp_x = capital_budget(1000, cat="Continuous")
lp_x[lp_x > 1e-6].round(3)P1 0.741
P2 0.741
P3 0.741
P5 1.000
P6 1.000
dtype: float64check("B1 the LP is an upper bound on the integer plan", lp_npv >= npv_rules)
check("B1 three projects are funded only partly", ((lp_x > 1e-6) & (lp_x < 1 - 1e-6)).sum() == 3)✅ B1 the LP is an upper bound on the integer plan
✅ B1 three projects are funded only partly
B2. Round it¶
Round down: fund only the projects the LP funds fully. Round up: fund every project the LP funds at all. Store the NPV of the rounded-down plan in npv_down and the cost of the rounded-up plan in cost_up.
down = list(lp_x[lp_x > 1 - 1e-6].index)
up = list(lp_x[lp_x > 1e-6].index)
npv_down = npv[down].sum()
cost_up = cost[up].sum()
print(down, npv_down, "|", up, cost_up)['P5', 'P6'] 770 | ['P1', 'P2', 'P3', 'P5', 'P6'] 1140
check("B2 rounding down loses more than a third of the NPV", npv_down < 2 / 3 * npv_rules)
check("B2 rounding up breaks the budget", cost_up > 1000)✅ B2 rounding down loses more than a third of the NPV
✅ B2 rounding up breaks the budget
B3. One riyal less¶
Solve the integer model with a budget of 999.999 k SAR (one riyal less). Store the funded projects in plan_less and the NPV in npv_less.
npv_less, x_less = capital_budget(999.999)
plan_less = list(x_less[x_less > 0.5].index)
print(npv_less, plan_less)1170.0 ['P4', 'P6', 'P9']
check("B3 one riyal less costs only 30 k SAR of NPV", round(npv_rules - npv_less) == 30)
check("B3 but the two plans have no project in common", not set(plan) & set(plan_less))✅ B3 one riyal less costs only 30 k SAR of NPV
✅ B3 but the two plans have no project in common
B4. In two sentences: why can one riyal change the whole plan, and what does that mean for a manager who asks “what if the budget were a little smaller?”
Model answer. The best plan spent exactly 1,000 k SAR, so with one riyal less it is no longer affordable, and the next best combination of whole projects happens to be built from different pieces (with 0/1 decisions, plans do not shrink smoothly the way an LP solution does). So there is no shadow price to read off: to answer a “what if” about the budget, solve the model again for each budget, and look at how much NPV changes (only 30 k SAR here) as well as which projects.
Part C: Set covering¶
The promise to customers: a Qahwa House kiosk within 10 minutes’ drive of every district.
C1. The coverage matrix¶
The first lines below build minutes, a site × district table of driving times, and site_cost, the yearly cost of each site. Store in covers a table of the same shape that is True when the site reaches the district within 10 minutes.
minutes = sites.pivot(index="site", columns="district", values="minutes")
site_cost = sites.groupby("site")["yearly_cost_ksar"].first()
covers = minutes <= 10
covers.sum(axis=1).sort_values(ascending=False) # how many districts each site reachessite
Abu Bakr Rd 6
Anas Ibn Malik Rd 6
Northern Ring Rd 6
King Fahd Rd 5
Imam Saud Rd 3
Prince Turki Rd 2
King Salman Rd 1
Uthman Ibn Affan Rd 1
dtype: int64check("C1 eight sites and twelve districts", covers.shape == (8, 12))
check("C1 30 site-district pairs within 10 minutes", covers.values.sum() == 30)
check("C1 every district is reached by at least one site", covers.any(axis=0).all())✅ C1 eight sites and twelve districts
✅ C1 30 site-district pairs within 10 minutes
✅ C1 every district is reached by at least one site
C2. The cheapest cover¶
Complete the set-covering model: minimise the yearly cost of the open sites, with one constraint per district saying that at least one open site reaches it. Store the yearly cost in cover_cost and the open sites in cover_sites.
def cheapest_cover(covers, must_open=()):
m = pulp.LpProblem("set_covering", pulp.LpMinimize)
y = m.add_variable_dicts("open", covers.index, cat="Binary")
m += pulp.lpSum(site_cost[s] * y[s] for s in covers.index)
for d in covers.columns:
m += pulp.lpSum(y[s] for s in covers.index if covers.loc[s, d]) >= 1 # at least one open site reaches d
for s in must_open:
m += y[s] == 1
res = m.solve(pulp.HiGHS(msg=False))
return pulp.value(m.objective), [s for s in covers.index if y[s].value() > 0.5]
cover_cost, cover_sites = cheapest_cover(covers)
print(cover_cost, cover_sites)1870.0 ['Anas Ibn Malik Rd', 'Imam Saud Rd', 'King Fahd Rd']
check("C2 three kiosks", len(cover_sites) == 3)
check("C2 for 1,870 k SAR a year", round(cover_cost) == 1870)
check("C2 every district is reached", covers.loc[cover_sites].any(axis=0).all())✅ C2 three kiosks
✅ C2 for 1,870 k SAR a year
✅ C2 every district is reached
C3. Start with the busiest site?¶
The planning team wants to open Abu Bakr Rd first: it reaches six districts, as many as any site, and is the cheapest of those. Use the must_open argument to find the cheapest cover that includes it, and store its yearly cost in forced_cost.
forced_cost, forced_sites = cheapest_cover(covers, must_open=["Abu Bakr Rd"])
print(forced_cost, forced_sites, f"{forced_cost / cover_cost - 1:.0%} more")2340.0 ['Abu Bakr Rd', 'Anas Ibn Malik Rd', 'Imam Saud Rd', 'King Fahd Rd'] 25% more
check("C3 starting with Abu Bakr Rd needs four kiosks", len(forced_sites) == 4)
check("C3 and costs 470 k SAR a year more", round(forced_cost - cover_cost) == 470)✅ C3 starting with Abu Bakr Rd needs four kiosks
✅ C3 and costs 470 k SAR a year more
Part D: Fixed costs¶
Now the profit view. A kiosk earns about 6 SAR a cup, 360 days a year: each cup a day sold all year is worth MARGIN = 2.16 k SAR a year. An open kiosk costs its full yearly_cost_ksar (a fixed cost) and serves at most capacity_cups a day. Customers buy only at a kiosk within 10 minutes.
: open site ;
: cups a day that district buys at kiosk (only for pairs within 10 minutes);
maximise ;
demand: ; capacity and big-M link: .
D1. The most profitable kiosks¶
Complete the capacity-and-link constraint. Store the yearly profit in profit and the open sites in open_sites.
capacity = sites.groupby("site")["capacity_cups"].first()
demand = sites.groupby("district")["district_cups"].first()
MARGIN = 6 * 360 / 1000
def kiosk_plan(reach_all=False):
m = pulp.LpProblem("kiosks", pulp.LpMaximize)
y = m.add_variable_dicts("open", covers.index, cat="Binary")
pairs = [(s, d) for s in covers.index for d in covers.columns if covers.loc[s, d]]
x = m.add_variable_dicts("cups", pairs, lowBound=0)
m += MARGIN * pulp.lpSum(x.values()) - pulp.lpSum(site_cost[s] * y[s] for s in covers.index)
for d in covers.columns:
m += pulp.lpSum(x[s, d] for s in covers.index if (s, d) in x) <= float(demand[d])
for s in covers.index:
m += pulp.lpSum(x[s, d] for d in covers.columns if (s, d) in x) <= capacity[s] * y[s] # the big-M link
if reach_all:
for d in covers.columns:
m += pulp.lpSum(y[s] for s in covers.index if covers.loc[s, d]) >= 1
res = m.solve(pulp.HiGHS(msg=False))
served = pd.Series({d: sum(x[s, d].value() for s in covers.index if (s, d) in x) for d in covers.columns})
return pulp.value(m.objective), [s for s in covers.index if y[s].value() > 0.5], served
profit, open_sites, served = kiosk_plan()
print(round(profit, 1), open_sites)
served[served < demand] # districts not fully served2070.0 ['Abu Bakr Rd', 'Imam Saud Rd', 'King Fahd Rd']
Al Aqiq 40.0
Al Mursalat 0.0
Al Rabi 100.0
dtype: float64check("D1 a profit of 2,070 k SAR a year", round(profit, 1) == 2070.0)
check("D1 three kiosks, not the set-covering three", len(open_sites) == 3 and set(open_sites) != set(cover_sites))
check("D1 no open kiosk reaches Al Mursalat", served["Al Mursalat"] == 0 and not covers.loc[open_sites, "Al Mursalat"].any())✅ D1 a profit of 2,070 k SAR a year
✅ D1 three kiosks, not the set-covering three
✅ D1 no open kiosk reaches Al Mursalat
D2. The price of the promise¶
Solve the profit model again with the 10-minute promise (reach_all=True). Store the profit in profit_all and the drop in profit, the price of the promise, in price.
profit_all, open_all, served_all = kiosk_plan(reach_all=True)
price = profit - profit_all
print(round(profit_all, 1), open_all, round(price, 1))1850.4 ['Abu Bakr Rd', 'Anas Ibn Malik Rd', 'Imam Saud Rd', 'King Fahd Rd'] 219.6
check("D2 the promise needs a fourth kiosk", len(open_all) == 4)
check("D2 and costs 219.6 k SAR of profit a year", round(price, 1) == 219.6)✅ D2 the promise needs a fourth kiosk
✅ D2 and costs 219.6 k SAR of profit a year
D3. Your recommendation¶
Write three sentences for the board: which projects to fund (and why the obvious rules of thumb or rounding would get it wrong), which kiosks to open under each goal, and what the 10-minute promise costs, with numbers from Parts A to D.
Model recommendation. Fund the POS system, the loyalty app, the delivery-platform link, the cold-brew line and the barista academy: 1,200 k SAR of NPV for exactly the 1,000 k SAR budget, as a package, because the app and the delivery link need the POS system (rounding the LP would either waste a third of the value or break the budget, and if the budget falls even slightly, re-solve: the best plan then changes completely). For profit, open kiosks at King Fahd Rd, Abu Bakr Rd and Imam Saud Rd (2,070 k SAR a year), while the cheapest way to reach every district within 10 minutes is King Fahd Rd, Anas Ibn Malik Rd and Imam Saud Rd (1,870 k SAR a year in costs). Keeping the 10-minute promise inside the profit plan means a fourth kiosk and 219.6 k SAR less profit a year, all to serve Al Mursalat’s 80 cups a day, so the board should decide whether the promise is worth that before the sites are signed.
★ Extended challenges¶
E1. A different promise. Solve the set-covering model for promises of 8, 9, 11, 12 and 15 minutes. Which promises can be kept at all, and how does the cheapest cost change? (Check the status the solver returns, res.status.name, for infeasible models: change cheapest_cover to return the status too.)
E2. Spreading the cash reserve. Qahwa House holds 2 million SAR in reserve. Using the estimates of the reading (four funds; mu, vol and corr), find with scipy.optimize.minimize (method "SLSQP") the mix with the lowest volatility whose expected return is at least 7.5%. Compare its volatility with that of the real-estate fund alone (7.5% expected, 14% volatility).
E3. The budget staircase. Plot the best NPV for every budget from 600 to 1,400 k SAR in steps of 10. Between 950 and 1,080 k SAR (where every budget has a single best plan), at how many steps does the best plan change, and at how many does it change completely (no project in common with the plan one step before)?
# E1: the status tells us when a promise cannot be kept
def cheapest_cover_status(covers):
m = pulp.LpProblem("set_covering", pulp.LpMinimize)
y = m.add_variable_dicts("open", covers.index, cat="Binary")
m += pulp.lpSum(site_cost[s] * y[s] for s in covers.index)
for d in covers.columns:
m += pulp.lpSum(y[s] for s in covers.index if covers.loc[s, d]) >= 1
res = m.solve(pulp.HiGHS(msg=False))
return res.status.name, pulp.value(m.objective), [s for s in covers.index if y[s].value() > 0.5]
for t in [8, 9, 10, 11, 12, 15]:
status, c, s = cheapest_cover_status(minutes <= t)
print(f"{t:2d} minutes: {status:10s}" + (f" {c:,.0f} k SAR a year, {len(s)} kiosk(s)" if status == "Optimal" else "")) 8 minutes: Infeasible
9 minutes: Infeasible
10 minutes: Optimal 1,870 k SAR a year, 3 kiosk(s)
11 minutes: Optimal 1,810 k SAR a year, 3 kiosk(s)
12 minutes: Optimal 1,650 k SAR a year, 3 kiosk(s)
15 minutes: Optimal 690 k SAR a year, 1 kiosk(s)
An 8- or 9-minute promise cannot be kept: some district has no candidate site that close. From 10 minutes on, each extra minute makes the promise cheaper: 1,870 k SAR at 10 minutes, 1,650 at 12, and a single kiosk (Northern Ring Rd, 690 k SAR) reaches every district within 15 minutes. The marketing team’s “10 minutes” is a choice with a price, like any other constraint.
# E2: a nonlinear model, solved with SLSQP
from scipy.optimize import minimize
funds = ["Sukuk fund", "Saudi equity fund", "Real-estate fund", "Gold"]
mu = np.array([0.05, 0.10, 0.075, 0.06])
vol = np.array([0.02, 0.20, 0.14, 0.15])
corr = np.array([[1.0, 0.1, 0.2, 0.1], [0.1, 1.0, 0.6, 0.0], [0.2, 0.6, 1.0, 0.1], [0.1, 0.0, 0.1, 1.0]])
cov = np.outer(vol, vol) * corr
res = minimize(lambda w: w @ cov @ w, x0=np.full(4, 0.25), method="SLSQP", bounds=[(0, 1)] * 4,
constraints=[{"type": "eq", "fun": lambda w: w.sum() - 1},
{"type": "ineq", "fun": lambda w: w @ mu - 0.075}], options={"ftol": 1e-12})
print(f"volatility {np.sqrt(res.fun):.1%} against 14.0% for the real-estate fund alone")
pd.DataFrame({"weight": res.x.round(3), "SAR": (res.x * 2_000_000).round(-3).astype(int)}, index=funds)volatility 9.7% against 14.0% for the real-estate fund alone
The same 7.5% expected return with 9.7% volatility instead of 14%: about 30% less risk, because the four funds do not move together.
# E3: the staircase, and how often the plan changes
budgets = np.arange(600, 1401, 10)
results = [capital_budget(b) for b in budgets]
best = [r[0] for r in results]
plans = [frozenset(r[1][r[1] > 0.5].index) for r in results]
fig, ax = plt.subplots(figsize=(7, 3.2))
ax.step(budgets, best, where="post", color="#1f6f8b", lw=2.5)
ax.set_xlabel("capital budget (k SAR)")
ax.set_ylabel("best NPV (k SAR)")
plt.tight_layout()
plt.show()
window = [(b, plans[i - 1], plans[i]) for i, b in enumerate(budgets) if 950 < b <= 1080]
changes = sum(prev != cur for _, prev, cur in window)
complete = [b for b, prev, cur in window if not prev & cur]
print(f"from 950 to 1,080: the plan changes at {changes} of {len(window)} steps, completely at {len(complete)}: {complete}")
from 950 to 1,080: the plan changes at 5 of 13 steps, completely at 1: [np.int64(1000)]
The best NPV climbs in uneven steps of different sizes. Between 950 and 1,080 k SAR the plan changes at 5 of the 13 steps, and once (at 1,000) it changes completely. Outside this window, some budgets have two plans with the same best NPV (for example 940 and 1,090 to 1,110), and the solver may return either: another reason to report the NPV and the cost, not only the list of projects.