Lab 15 Solutions: Choosing with Several Criteria (AHP and TOPSIS)¶
These are the worked solutions, with outputs. Try the lab yourself first.
The question. Qahwa House must choose one importer for the green coffee of its house blend (about 50 tonnes a year) for the next two years. Five importers are scored on cost, quality, reliability, sustainability and supply risk. Which one should the board sign with, and how sure can it be?
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.
Part E prepares your capstone defence: complete it with your team.
This lab is not graded (lab marks count the best 12 of Labs 1 to 14), but its last part is what you will be asked about at your defence.
# Run this cell once: it defines a small helper that checks your answers.
def check(label, condition):
print(("✅ " if condition else "❌ ") + label)import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
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)
suppliers = load("qahwa_supplier_criteria.csv")
suppliers| Column | Meaning | Better when |
|---|---|---|
supplier, origin | the importer and where its coffee comes from | |
cost_sar_kg | landed price of green coffee, SAR per kg | lower |
cupping_score | quality on the specialty-coffee cupping scale, 0–100 | higher |
on_time_pct | share of the last 24 months’ shipments that arrived on time (%) | higher |
sustainability_score | the purchasing team’s audit score, 0–100 | higher |
supply_risk | the purchasing team’s risk rating, 1 (low) to 10 (high) | lower |
The importers and their scores are invented for this course.
Part A: The decision matrix¶
The cell below builds the decision matrix X (one row per importer, one column per criterion, as floats) and the Series better, which says for each criterion whether a lower or a higher value is better.
crit = ["cost_sar_kg", "cupping_score", "on_time_pct", "sustainability_score", "supply_risk"]
better = pd.Series(["low", "high", "high", "high", "low"], index=crit)
X = suppliers.set_index("supplier")[crit].astype(float)
XA1. Cost alone¶
Store in cheapest the name of the cheapest importer, and in extra_red_sea how much more Red Sea Traders would cost per year than the cheapest, for 50 tonnes (50,000 kg), in SAR.
cheapest = X["cost_sar_kg"].idxmin()
extra_red_sea = (X.loc["Red Sea Traders", "cost_sar_kg"] - X["cost_sar_kg"].min()) * 50_000
cheapest, extra_red_sea('Santos Bulk', np.float64(250000.0))check("A1 cost alone picks Santos Bulk", cheapest == "Santos Bulk")
check("A1 Red Sea Traders costs 250,000 SAR a year more", round(extra_red_sea) == 250_000)✅ A1 cost alone picks Santos Bulk
✅ A1 Red Sea Traders costs 250,000 SAR a year more
A2. Dominated options¶
Option a dominates option b when a is at least as good as b on every criterion and strictly better on at least one. The table good flips the sign of the lower is better criteria, so that higher is better everywhere. Complete dominates(a, b), then store in dominated the list of importers dominated by at least one other.
good = X.copy()
good.loc[:, better == "low"] *= -1 # now higher is better on every criterion
def dominates(a, b):
"""True if importer a is at least as good as b on every criterion and better on at least one."""
return bool((good.loc[a] >= good.loc[b]).all() and (good.loc[a] > good.loc[b]).any())
dominated = [b for b in X.index if any(dominates(a, b) for a in X.index if a != b)]
dominated['Sidamo Link']check("A2 one importer is dominated: Sidamo Link", dominated == ["Sidamo Link"])
check("A2 Harar Direct dominates it", dominates("Harar Direct", "Sidamo Link"))
check("A2 Santos Bulk is not dominated (it is the cheapest)", "Santos Bulk" not in dominated)✅ A2 one importer is dominated: Sidamo Link
✅ A2 Harar Direct dominates it
✅ A2 Santos Bulk is not dominated (it is the cheapest)
From here on we work with the four importers that remain, X4.
X4 = X.drop(index=dominated)
X4Part B: Weights with AHP¶
The board compared the criteria two at a time on Saaty’s 1–9 scale (row against column; for example, cost is 4 times as important as sustainability):
| cost | quality | reliability | sustainability | risk | |
|---|---|---|---|---|---|
| cost | 1 | 1 | 2 | 4 | 2 |
| quality | 1 | 1 | 2 | 3 | 2 |
| reliability | 1/2 | 1/2 | 1 | 2 | 2 |
| sustainability | 1/4 | 1/3 | 1/2 | 1 | 1/2 |
| risk | 1/2 | 1/2 | 1/2 | 2 | 1 |
B1. The priority vector¶
The weights are the eigenvector of the largest eigenvalue of this matrix, scaled to add up to 1. Use np.linalg.eig(board): it returns the eigenvalues and a matrix whose columns are the eigenvectors (keep the real parts). Store the weights as a Series weights indexed by crit, and the largest eigenvalue in lam.
board = np.array([
[1, 1, 2, 4, 2 ],
[1, 1, 2, 3, 2 ],
[1/2, 1/2, 1, 2, 2 ],
[1/4, 1/3, 1/2, 1, 1/2],
[1/2, 1/2, 1/2, 2, 1 ],
])
eigvals, eigvecs = np.linalg.eig(board)
k = np.argmax(eigvals.real) # the position of the largest eigenvalue
lam = eigvals.real[k]
v = np.abs(eigvecs[:, k].real) # its eigenvector (real parts, made positive)
weights = pd.Series(v / v.sum(), index=crit)
weights.round(3)cost_sar_kg 0.308
cupping_score 0.292
on_time_pct 0.181
sustainability_score 0.082
supply_risk 0.136
dtype: float64check("B1 the weights add up to 1", abs(weights.sum() - 1) < 1e-9)
check("B1 cost weighs 30.8%", round(weights["cost_sar_kg"], 3) == 0.308)
check("B1 sustainability weighs least: 8.2%", weights.idxmin() == "sustainability_score" and round(weights.min(), 3) == 0.082)✅ B1 the weights add up to 1
✅ B1 cost weighs 30.8%
✅ B1 sustainability weighs least: 8.2%
B2. Consistency¶
Compute the consistency index and the consistency ratio , with the random index = 1.12 for = 5 criteria. Store them in CI and CR.
n = len(board)
CI = (lam - n) / (n - 1)
CR = CI / 1.12
print(f"lambda max = {lam:.3f}, CI = {CI:.4f}, CR = {CR:.3f}")lambda max = 5.069, CI = 0.0171, CR = 0.015
check("B2 CR = 0.015", round(CR, 3) == 0.015)
check("B2 below 0.10: the board's judgments are consistent enough", CR < 0.10)✅ B2 CR = 0.015
✅ B2 below 0.10: the board's judgments are consistent enough
B3. A second opinion¶
The finance manager filled in the same comparisons. Write a function ahp(matrix) that returns the weights (as a Series indexed by crit) and the CR, then apply it to finance. Store the results in w_fin and CR_fin.
finance = np.array([
[1, 3, 1/2, 5, 3 ],
[1/3, 1, 3, 2, 1 ],
[2, 1/3, 1, 3, 2 ],
[1/5, 1/2, 1/3, 1, 1/2],
[1/3, 1, 1/2, 2, 1 ],
])
def ahp(matrix):
"""The AHP weights (a Series indexed by crit) and the consistency ratio of a 5 x 5 comparison matrix."""
vals, vecs = np.linalg.eig(matrix)
k = np.argmax(vals.real)
v = np.abs(vecs[:, k].real)
n = len(matrix)
return pd.Series(v / v.sum(), index=crit), (vals.real[k] - n) / (n - 1) / 1.12
w_fin, CR_fin = ahp(finance)
print(w_fin.round(3), f"\nCR = {CR_fin:.3f}")cost_sar_kg 0.324
cupping_score 0.234
on_time_pct 0.248
sustainability_score 0.069
supply_risk 0.126
dtype: float64
CR = 0.173
check("B3 the function gives the board's weights back", np.allclose(ahp(board)[0], weights))
check("B3 the finance manager's CR is 0.173", round(CR_fin, 3) == 0.173)
check("B3 above 0.10: the judgments should be revisited", CR_fin > 0.10)✅ B3 the function gives the board's weights back
✅ B3 the finance manager's CR is 0.173
✅ B3 above 0.10: the judgments should be revisited
B4. Find the three judgments in finance that go round in a circle (A more important than B, B more important than C, but C more important than A). What would you say to the finance manager?
Answer. Cost is 3 times as important as quality (row 1, column 2), quality 3 times as important as reliability (row 2, column 3), but reliability is 2 times as important as cost (row 3, column 1). If the first two held, cost should be about 9 times as important as reliability, not half as important. Show the manager this circle and ask which of the three judgments to revise; recompute the CR afterwards.
Part C: Two ranking methods¶
C1. Min–max normalisation and the weighted sum¶
Complete minmax(X) so that every criterion is on a 0-to-1 scale among the importers, with 1 for the best and 0 for the worst: when higher is better, when lower is better. Then store the weighted-sum scores of X4 with the board’s weights in wsm.
def minmax(X):
lo, hi = X.min(), X.max()
R = (X - lo) / (hi - lo) # right for the "higher is better" criteria
low = better[better == "low"].index
R[low] = (hi[low] - X[low]) / (hi[low] - lo[low])
return R
wsm = (minmax(X4) * weights).sum(axis=1)
wsm.sort_values(ascending=False).round(3)supplier
Red Sea Traders 0.655
Jazan Highlands 0.619
Harar Direct 0.453
Santos Bulk 0.363
dtype: float64R = minmax(X4)
check("C1 the best importer on each criterion scores 1, the worst 0", (R.max() == 1).all() and (R.min() == 0).all())
check("C1 Santos Bulk scores 1 on cost", R.loc["Santos Bulk", "cost_sar_kg"] == 1)
check("C1 Red Sea Traders wins with 0.655", wsm.idxmax() == "Red Sea Traders" and round(wsm.max(), 3) == 0.655)
check("C1 Jazan Highlands is second with 0.619", wsm.sort_values().index[-2] == "Jazan Highlands" and round(wsm["Jazan Highlands"], 3) == 0.619)✅ C1 the best importer on each criterion scores 1, the worst 0
✅ C1 Santos Bulk scores 1 on cost
✅ C1 Red Sea Traders wins with 0.655
✅ C1 Jazan Highlands is second with 0.619
C2. TOPSIS¶
Complete topsis(X, weights), which returns the closeness of each importer:
divide each column by its length, , and multiply by the weights:
V;the ideal takes the best value of each column of
V(the largest if higher is better, the smallest otherwise), the anti-ideal the worst (given);the distances to both, and the closeness .
Store the closeness of X4 with the board’s weights in closeness.
def topsis(X, weights):
V = X / np.sqrt((X ** 2).sum()) * weights
ideal = pd.Series({c: V[c].max() if better[c] == "high" else V[c].min() for c in crit})
anti = pd.Series({c: V[c].min() if better[c] == "high" else V[c].max() for c in crit})
d_ideal = np.sqrt(((V - ideal) ** 2).sum(axis=1))
d_anti = np.sqrt(((V - anti) ** 2).sum(axis=1))
return d_anti / (d_ideal + d_anti)
closeness = topsis(X4, weights)
closeness.sort_values(ascending=False).round(3)supplier
Red Sea Traders 0.639
Jazan Highlands 0.554
Santos Bulk 0.507
Harar Direct 0.293
dtype: float64check("C2 closeness is between 0 and 1", closeness.between(0, 1).all())
check("C2 TOPSIS also picks Red Sea Traders (0.639)", closeness.idxmax() == "Red Sea Traders" and round(closeness.max(), 3) == 0.639)
check("C2 Harar Direct is last (0.293)", closeness.idxmin() == "Harar Direct" and round(closeness.min(), 3) == 0.293)✅ C2 closeness is between 0 and 1
✅ C2 TOPSIS also picks Red Sea Traders (0.639)
✅ C2 Harar Direct is last (0.293)
Part D: How sure is the answer?¶
with_weight(weights, criterion, value) sets one weight to value and scales the other four in proportion, so that the total stays 1.
D1. When does the winner change?¶
Using the grid grid (weights from 0 to 1 in steps of 0.001), store in flip_wsm the smallest sustainability weight above the board’s at which the weighted-sum winner is no longer Red Sea Traders, and in flip_topsis the same for TOPSIS.
def with_weight(weights, criterion, value):
w = weights * (1 - value) / (1 - weights[criterion])
w[criterion] = value
return w
def wsm_scores(w):
return (minmax(X4) * w).sum(axis=1)
grid = np.round(np.arange(0, 1.0005, 0.001), 3)
s = "sustainability_score"
flip_wsm = next(v for v in grid if v > weights[s] and wsm_scores(with_weight(weights, s, v)).idxmax() != "Red Sea Traders")
flip_topsis = next(v for v in grid if v > weights[s] and topsis(X4, with_weight(weights, s, v)).idxmax() != "Red Sea Traders")
print(flip_wsm, flip_topsis)0.132 0.141
check("D1 the weighted sum flips at a sustainability weight of 13.2%", round(flip_wsm, 3) == 0.132)
check("D1 TOPSIS flips at 14.1%", round(flip_topsis, 3) == 0.141)
check("D1 and the new winner is Jazan Highlands", wsm_scores(with_weight(weights, s, flip_wsm)).idxmax() == "Jazan Highlands")✅ D1 the weighted sum flips at a sustainability weight of 13.2%
✅ D1 TOPSIS flips at 14.1%
✅ D1 and the new winner is Jazan Highlands
D2. “Let’s keep it neutral: equal weights”¶
A board member proposes 20% for every criterion. Store the weighted-sum winner with equal weights in winner_equal.
equal = pd.Series(0.2, index=crit)
winner_equal = wsm_scores(equal).idxmax()
winner_equal, wsm_scores(equal).round(3).to_dict()('Jazan Highlands',
{'Red Sea Traders': 0.65,
'Harar Direct': 0.407,
'Santos Bulk': 0.272,
'Jazan Highlands': 0.733})check("D2 equal weights pick Jazan Highlands", winner_equal == "Jazan Highlands")
check("D2 and so does TOPSIS", topsis(X4, equal).idxmax() == "Jazan Highlands")✅ D2 equal weights pick Jazan Highlands
✅ D2 and so does TOPSIS
D3. Your recommendation¶
Write three sentences for the board: which importer to sign with (with its scores under both methods and the cost difference with the runner-up), how sure the answer is (the flip points), and why equal weights are not a neutral choice.
Model answer. Sign with Red Sea Traders: with the board’s AHP weights (consistent, CR = 0.015) it ranks first under both the weighted sum (0.655) and TOPSIS (0.639), ahead of Jazan Highlands (0.619 and 0.554), and it costs 350,000 SAR a year less than Jazan Highlands. The margin is thin: if sustainability weighed about 13 to 14% instead of 8% (or cost about 26% instead of 31%), Jazan Highlands would be the better choice, so the board should confirm these two weights before signing. Equal weights are not neutral: they more than double the weight of sustainability (20% instead of 8%) against the board’s judgment and pick Jazan Highlands, so any weights, equal or not, must be stated and justified.
Part E: Before your defence¶
In the student notebook, this part is a ten-line table each team completes for its own capstone (the checklist of the reading, Section 12), followed by one sentence on the input their recommendation is most sensitive to. For the importer decision, that sentence would be: “If the board weighed sustainability at 14% instead of 8%, we would recommend Jazan Highlands instead of Red Sea Traders.”
★ Extended challenges¶
★1. Who gets the voucher? Rebuild Week 7’s churn model (data qahwa_members_2025.csv; pd.get_dummies on branch with drop_first=True; train_test_split(..., test_size=0.3, random_state=631, stratify=y); LogisticRegression(max_iter=1000)) and the rule send a voucher when p > 1/6. For each branch, compute on the test set the share of members who get a voucher and the share of leavers who get one (recall). Then fit the model again without the branch columns. How do the gaps between branches and the test-set profit (+50 SAR per leaver reached, −10 SAR per voucher sent to a member who stays) change?
★2. Negotiate. The board likes Jazan Highlands’ sustainability. At what price per kg (in steps of 0.5 SAR) would Jazan Highlands become the board’s choice under both methods, with the board’s weights? How much would that cost per year compared with Red Sea Traders at 31 SAR/kg?
★3. Your own weights. Fill in your own pairwise comparisons of the five criteria. Is your CR below 0.10? Which importer wins with your weights, under each method?
# ★1: decisions and errors by branch, with and without the branch columns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
members = load("qahwa_members_2025.csv")
Xm = pd.get_dummies(members.drop(columns=["member_id", "churned"]), columns=["branch"], drop_first=True, dtype=int)
y = members["churned"]
X_train, X_test, y_train, y_test = train_test_split(Xm, y, test_size=0.3, random_state=631, stratify=y)
def by_branch(features):
model = LogisticRegression(max_iter=1000).fit(X_train[features], y_train)
send = model.predict_proba(X_test[features])[:, 1] > 1 / 6
t = pd.DataFrame({"branch": members.loc[X_test.index, "branch"], "churned": y_test, "send": send})
table = t.groupby("branch").apply(lambda d: pd.Series({
"voucher rate": d["send"].mean(), "recall": d.loc[d["churned"] == 1, "send"].mean()}), include_groups=False)
profit = 50 * (t["send"] & (t["churned"] == 1)).sum() - 10 * (t["send"] & (t["churned"] == 0)).sum()
return table, profit
with_b, profit_with = by_branch(list(Xm.columns))
without_b, profit_without = by_branch([c for c in Xm.columns if not c.startswith("branch_")])
print(f"profit with branch: {profit_with:,} SAR, without: {profit_without:,} SAR")
pd.concat({"with branch": with_b, "without branch": without_b}, axis=1).round(3)profit with branch: 10,050 SAR, without: 10,320 SAR
With the branch columns, the rule reaches 90.6% of University leavers but only 68.0% at Corniche: a gap of 22.6 points. Without them the gap narrows to 14.3 points (73.7% at Olaya to 88.0% at University) and the test-set profit is slightly higher (10,320 against 10,050 SAR). Here the fairer model costs nothing on this test set; check it with cross-validation before changing the rule, and remember that other columns can still carry the same information.
# ★2: the price at which Jazan Highlands wins under both methods
rows = []
for price in np.arange(38, 29.5, -0.5):
Xp = X4.copy()
Xp.loc["Jazan Highlands", "cost_sar_kg"] = price
w_win = (minmax(Xp) * weights).sum(axis=1).idxmax()
t_win = topsis(Xp, weights).idxmax()
rows.append({"Jazan price": price, "weighted sum": w_win, "TOPSIS": t_win})
prices = pd.DataFrame(rows)
best_price = prices.loc[(prices["weighted sum"] == "Jazan Highlands") & (prices["TOPSIS"] == "Jazan Highlands"), "Jazan price"].max()
print(f"Jazan Highlands wins under both methods from {best_price} SAR/kg: "
f"{(best_price - 31) * 50_000:,.0f} SAR a year more than Red Sea Traders")
prices.head(8)Jazan Highlands wins under both methods from 35.0 SAR/kg: 200,000 SAR a year more than Red Sea Traders
At 35 SAR/kg (3 SAR less than its offer), Jazan Highlands wins under both methods. It would still cost 200,000 SAR a year more than Red Sea Traders: with these weights, the board judges its extra quality, sustainability and low risk to be worth that much.
# ★3: one possible set of judgments (a board member who cares more about sustainability and risk)
mine = np.array([
[1, 1, 2, 1, 1 ],
[1, 1, 2, 2, 1 ],
[1/2, 1/2, 1, 1, 1/2],
[1, 1/2, 1, 1, 1 ],
[1, 1, 2, 1, 1 ],
])
w_mine, CR_mine = ahp(mine)
print(w_mine.round(3).to_dict(), f"CR = {CR_mine:.3f}")
print("weighted sum:", wsm_scores(w_mine).idxmax(), "| TOPSIS:", topsis(X4, w_mine).idxmax()){'cost_sar_kg': 0.222, 'cupping_score': 0.256, 'on_time_pct': 0.128, 'sustainability_score': 0.172, 'supply_risk': 0.222} CR = 0.017
weighted sum: Jazan Highlands | TOPSIS: Jazan Highlands
With these judgments (CR = 0.017) sustainability weighs about 17% and risk about 22%, and Jazan Highlands wins under both methods. Students’ answers will differ: what matters is that the CR is below 0.10 and that the winner is reported together with the weights.