Lab 12: Capital Budgeting and Facility Location¶
In this lab you build integer models in PuLP: a capital budget with logical rules, a set-covering model and a kiosk plan with fixed costs.
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.
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 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 = ...
total_npv = ...
total_cost, total_npvcheck("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)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 += ... # the objective: total NPV
m += ... # 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)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)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 += ...
if row["excludes"]:
m += ...
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())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)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 = ...
lp_x[lp_x > 1e-6].round(3)check("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)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 = ...
up = ...
npv_down = ...
cost_up = ...
print(down, npv_down, "|", up, cost_up)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)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 = ...
plan_less = ...
print(npv_less, plan_less)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))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?”
Your answer here (double-click to edit).
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 = ...
covers.sum(axis=1).sort_values(ascending=False) # how many districts each site reachescheck("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())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 += ... # at least one open site reaches district 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)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())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 = ...
print(forced_cost, forced_sites, f"{forced_cost / cover_cost - 1:.0%} 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)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 += ... # capacity, and no cups at all if the site is closed
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 servedcheck("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())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 = ...
price = ...
print(round(profit_all, 1), open_all, round(price, 1))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)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.
Write your recommendation here (double-click to edit).
★ 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# E2# E3AI-use log (if you used an AI assistant)¶
What you asked, what you kept, what you changed.