Lab 13 Solutions: Decision Tree Calculator¶
These are the worked solutions, with outputs. Try the lab yourself first.
In the reading, decision analysis told Qahwa House’s owner not to buy a survey and showed how a risk-averse owner would choose a smaller kiosk. Now you build your own decision-tree calculator and use it on a bigger decision.
The question. Qahwa House can sell its cold brew in bottles in supermarkets. It can launch nationally, launch in Riyadh only, or not launch. First-year demand may be Strong, Moderate or Weak. Before deciding, it can run a pilot in 10 Riyadh stores for 40,000 SAR. Should it run the pilot, and what should it launch?
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)import numpy as np
import pandas as pd
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)
data = load("qahwa_kiosk_decision.csv")
brew = data[data["case"] == "cold_brew"]
brew| Column | Meaning |
|---|---|
case | which decision: kiosk (the reading) or cold_brew (the lab) |
alternative | an option the decision maker can choose |
state | a state of the world: what may happen, which nobody controls |
prior | the probability of the state, before any new information |
p_positive | the probability that a study (a survey or a pilot) gives a positive result if this state is the true one |
units, unit_margin_sar, fixed_cost_sar | how the profit is built: units sold × margin per unit − fixed cost |
profit_sar | the payoff: profit of the alternative in this state, in SAR |
Profits are for the first year. A national launch has large fixed costs (supermarket listing fees, national marketing and a co-packer’s minimum order: 1.1 million SAR), a Riyadh launch much smaller ones (300,000 SAR). The pilot’s record from similar products: it came out positive for 85% of products whose demand then proved strong, 50% of moderate ones and 15% of weak ones (p_positive).
Part A: The payoff table and simple criteria¶
A1. The payoff table¶
Pivot brew into payoff_table: one row per alternative (in the order ALTS), one column per state (in the order STATES), values profit_sar divided by 1,000 (thousand SAR).
ALTS = ["National", "Riyadh", "No launch"]
STATES = ["Strong", "Moderate", "Weak"]
payoff_table = (brew.pivot(index="alternative", columns="state", values="profit_sar")
.loc[ALTS, STATES] / 1000) # thousand SAR, rows ALTS, columns STATES
payoff_tablecheck("A1 shape and order", payoff_table.shape == (3, 3) and list(payoff_table.index) == ALTS and list(payoff_table.columns) == STATES)
check("A1 a national launch loses 500 thousand SAR if demand is weak", payoff_table.loc["National", "Weak"] == -500)✅ A1 shape and order
✅ A1 a national launch loses 500 thousand SAR if demand is weak
A2. Three rules without probabilities¶
Compute the regret table regret (best payoff in each state minus each payoff), then the alternative chosen by maximax, by maximin and by minimax regret, as labels in choice_maximax, choice_maximin and choice_regret.
regret = payoff_table.max() - payoff_table
choice_maximax = payoff_table.max(axis=1).idxmax()
choice_maximin = payoff_table.min(axis=1).idxmax()
choice_regret = regret.max(axis=1).idxmin()
print(regret, "\n")
print(choice_maximax, choice_maximin, choice_regret)state Strong Moderate Weak
alternative
National 0.0 0.0 500.0
Riyadh 550.0 100.0 100.0
No launch 900.0 250.0 0.0
National No launch National
check("A2 maximax", choice_maximax == "National")
check("A2 maximin", choice_maximin == "No launch")
check("A2 minimax regret", choice_regret == "National")✅ A2 maximax
✅ A2 maximin
✅ A2 minimax regret
A3. Expected monetary value¶
Store the prior probability of each state (in the order STATES) in a Series prior, the EMV of each alternative in emv, and the label of the best one in best_emv.
prior = brew.groupby("state")["prior"].first().loc[STATES]
emv = payoff_table @ prior
best_emv = emv.idxmax()
print(emv, "\nbest:", best_emv)alternative
National 187.5
Riyadh 125.0
No launch 0.0
dtype: float64
best: National
check("A3 the EMVs", np.allclose(emv.values, [187.5, 125.0, 0.0]))
check("A3 the EMV choice", best_emv == "National")✅ A3 the EMVs
✅ A3 the EMV choice
Part B: A decision tree calculator¶
A tree is built from three kinds of node, as nested dictionaries. Run the cell below: it defines them.
# Three kinds of node. A tree is nested dictionaries built from them.
def payoff(value):
return {"kind": "payoff", "value": value}
def chance(branches):
"""branches: a list of (label, probability, child node)."""
return {"kind": "chance", "branches": branches}
def decision(options):
"""options: a dict {label of the alternative: child node}."""
return {"kind": "decision", "options": options}B1. Folding back¶
Complete rollback(node): a chance node is worth the probability-weighted sum of its children’s values; a decision node is worth its best option, and stores that option’s label in node["best"]. The test tree compares a sure 50 with a coin flip for 120 or 0.
def rollback(node):
"""Fold the tree back: return the node's value and store the best option at each decision."""
if node["kind"] == "payoff":
return node["value"]
if node["kind"] == "chance":
return sum(p * rollback(child) for label, p, child in node["branches"])
values = {label: rollback(child) for label, child in node["options"].items()}
node["values"] = values
node["best"] = max(values, key=values.get)
return values[node["best"]]
# A small test: a sure 50, or a coin flip for 0 or 120
test = decision({"sure": payoff(50), "coin": chance([("heads", 0.5, payoff(120)), ("tails", 0.5, payoff(0))])})
print(rollback(test), test["best"])60.0 coin
check("B1 the coin flip is worth 60", rollback(test) == 60)
check("B1 and it is the better option", test["best"] == "coin")✅ B1 the coin flip is worth 60
✅ B1 and it is the better option
B2. The launch tree¶
Complete launch_choice(probs): a decision node whose options are the three alternatives, each followed by a chance node with one branch (state, probability, payoff(...)) per state. Fold it back: it must give the same answer as the EMV table.
def launch_choice(probs):
"""The launch decision, given probabilities for the three demand states (a Series indexed by STATES)."""
return decision({
alt: chance([(s, probs[s], payoff(payoff_table.loc[alt, s])) for s in STATES]) for alt in ALTS
})
tree = launch_choice(prior)
print(rollback(tree), tree["best"])187.5 National
check("B2 the tree's value is the best EMV", abs(rollback(tree) - 187.5) < 1e-9)
check("B2 the tree chooses a national launch", tree["best"] == "National")✅ B2 the tree's value is the best EMV
✅ B2 the tree chooses a national launch
Part C: Is the pilot worth 40,000 SAR?¶
C1. The value of perfect information¶
Compute ev_perfect, the expected value with a perfect forecast (the best payoff in each state, weighted by its prior), and evpi.
ev_perfect = (payoff_table.max() * prior).sum()
evpi = ev_perfect - emv.max()
print(ev_perfect, evpi)337.5 150.0
check("C1 EVPI", abs(evpi - 150) < 1e-9)
check("C1 so the pilot (40) is under the ceiling", evpi > 40)✅ C1 EVPI
✅ C1 so the pilot (40) is under the ceiling
C2. Bayes’ rule¶
Complete posterior(prior, likelihood): the joint probability of each state and the result, the probability of the result, and the updated probabilities. Then compute them for a positive and for a negative pilot.
hit = brew.groupby("state")["p_positive"].first().loc[STATES] # P(positive pilot | state)
def posterior(prior, likelihood):
"""Bayes' rule: return P(result) and P(state | result)."""
joint = prior * likelihood
p_result = joint.sum()
return p_result, joint / p_result
p_pos, post_pos = posterior(prior, hit)
p_neg, post_neg = posterior(prior, 1 - hit)
print(round(p_pos, 4), post_pos.round(4).to_dict(), post_neg.round(4).to_dict())0.4825 {'Strong': 0.4404, 'Moderate': 0.4663, 'Weak': 0.0933} {'Strong': 0.0725, 'Moderate': 0.4348, 'Weak': 0.4928}
check("C2 P(positive pilot)", abs(p_pos - 0.4825) < 1e-4)
check("C2 after a positive pilot, strong demand is much more likely", abs(post_pos["Strong"] - 0.4404) < 1e-4)
check("C2 after a negative pilot, weak demand is the most likely state", post_neg.idxmax() == "Weak")✅ C2 P(positive pilot)
✅ C2 after a positive pilot, strong demand is much more likely
✅ C2 after a negative pilot, weak demand is the most likely state
C3. The full tree¶
The function below returns a copy of a subtree with every payoff changed by an amount: use it to charge the pilot’s price. Build full: a decision between No pilot (launch_choice(prior)) and Pilot, a chance node with a positive and a negative branch, each followed by the launch decision with the updated probabilities. Fold it back, then compute evsi.
def shift(node, amount):
"""The same subtree with every payoff changed by amount (to charge the price of a study)."""
if node["kind"] == "payoff":
return payoff(node["value"] + amount)
if node["kind"] == "chance":
return chance([(s, p, shift(c, amount)) for s, p, c in node["branches"]])
return decision({k: shift(c, amount) for k, c in node["options"].items()})PILOT_COST = 40 # thousand SAR
full = decision({
"No pilot": launch_choice(prior),
"Pilot": chance([("positive", p_pos, shift(launch_choice(post_pos), -PILOT_COST)),
("negative", p_neg, shift(launch_choice(post_neg), -PILOT_COST))]),
})
rollback(full)
after_pos = full["options"]["Pilot"]["branches"][0][2]
after_neg = full["options"]["Pilot"]["branches"][1][2]
evsi = full["values"]["Pilot"] + PILOT_COST - emv.max()
print({k: round(float(v), 2) for k, v in full["values"].items()}, full["best"], after_pos["best"], after_neg["best"], round(evsi, 2)){'No pilot': 187.5, 'Pilot': 206.38} Pilot National Riyadh 58.88
check("C3 run the pilot", full["best"] == "Pilot")
check("C3 after a positive pilot: national; after a negative one: Riyadh", after_pos["best"] == "National" and after_neg["best"] == "Riyadh")
check("C3 EVSI", abs(evsi - 58.88) < 0.01)✅ C3 run the pilot
✅ C3 after a positive pilot: national; after a negative one: Riyadh
✅ C3 EVSI
C4. In the reading, the kiosk survey was not worth its price; here the pilot is. In one or two sentences, explain why, using EVSI, the price and what the study’s result changes in the decision.
The pilot is worth 58.9 thousand SAR (EVSI) and costs 40, so it adds about 18.9 in expectation; the kiosk survey was worth only 20.6 and cost 25. The pilot pays because its result changes a very large decision: after a negative pilot the company launches in Riyadh only instead of nationally, avoiding much of the national launch’s 500-thousand-SAR loss when demand is weak, and that loss is far bigger than anything at stake in the kiosk decision.
Part D: The owner’s risk attitude¶
D1. Certainty equivalents¶
The owner’s risk tolerance is = 400 thousand SAR. Complete certainty_equivalent(values, probs, R) for the exponential utility : compute the expected utility, then return .
def certainty_equivalent(values, probs, R):
"""CE of a gamble for exponential utility U(x) = 1 - exp(-x / R)."""
expected_utility = (probs * (1 - np.exp(-values / R))).sum()
return -R * np.log(1 - expected_utility)
R = 400
ce = pd.Series({a: certainty_equivalent(payoff_table.loc[a], prior, R) for a in ["National", "Riyadh"]}) # "No launch": 0 for sure
print(ce.round(1))National -109.3
Riyadh 89.9
dtype: float64
check("D1 the national launch's CE is negative", abs(ce["National"] - (-109.33)) < 0.01)
check("D1 the Riyadh launch's CE", abs(ce["Riyadh"] - 89.91) < 0.01)
check("D1 a risk-averse owner launches in Riyadh only", ce.idxmax() == "Riyadh")✅ D1 the national launch's CE is negative
✅ D1 the Riyadh launch's CE
✅ D1 a risk-averse owner launches in Riyadh only
D2. Your recommendation¶
Write three sentences for the owner: what the EMV analysis recommends, with its expected profit; whether to run the pilot and what to do after each result; and how the advice changes for an owner with a risk tolerance of 400 thousand SAR, with the certainty equivalents.
On expected value, Qahwa House should not launch blind but run the 40,000-SAR pilot: the pilot raises the expected first-year profit from 187.5 thousand SAR (a national launch straight away) to 206.4 thousand after its price. If the pilot is positive, launch nationally; if it is negative, launch in Riyadh only. An owner with a risk tolerance of 400 thousand SAR should however avoid the national launch without more evidence: its certainty equivalent is −109.3 thousand SAR against +89.9 for a Riyadh launch, because a weak market would cost the national launch 500 thousand.
★ Extended challenges¶
E1. How robust is the national launch? Keep the ratio of Strong to Moderate at 25 : 45 and let = P(Weak) vary from 0 to 0.8. Above which does a Riyadh launch have a higher EMV than a national one? Plot both EMVs against .
E2. How risk-tolerant must the owner be? Find the risk tolerance above which the national launch has a higher certainty equivalent than the Riyadh launch (no pilot).
E3. A worse pilot. Suppose the pilot comes out positive for 40% of weak products instead of 15% (the other hit rates unchanged). What is its EVSI now, and is it still worth 40,000 SAR?
# E1: EMV of each launch against P(Weak)
import matplotlib.pyplot as plt
def emv_at(p_weak):
probs = pd.Series({"Strong": (1 - p_weak) * 25 / 70, "Moderate": (1 - p_weak) * 45 / 70, "Weak": p_weak})
return payoff_table @ probs
grid = np.linspace(0, 0.8, 161)
curves = pd.DataFrame([emv_at(p) for p in grid], index=grid)
switch = grid[np.argmax(curves["Riyadh"].values > curves["National"].values)]
print(f"Riyadh beats National once P(Weak) is above about {switch:.3f}")
fig, ax = plt.subplots(figsize=(7, 3.2))
for alt, col in zip(ALTS, ["#D2691E", "#4C9BC9", "#888888"]):
ax.plot(grid, curves[alt], color=col, lw=2.5, label=alt)
ax.axvline(0.30, color="black", ls=":", lw=1)
ax.axvline(switch, color="black", ls="--", lw=1)
ax.set_xlabel("probability of weak demand")
ax.set_ylabel("EMV (thousand SAR)")
ax.legend()
plt.show()Riyadh beats National once P(Weak) is above about 0.395

The national launch keeps the higher EMV only while weak demand is less likely than about 0.395; the team’s estimate is 0.30. Like the kiosk, the choice is not very robust, which is another argument for the pilot: it is exactly the probability of a weak market that the pilot helps to pin down.
# E2: the risk tolerance at which the national launch overtakes Riyadh
from scipy.optimize import brentq
gap = lambda r: certainty_equivalent(payoff_table.loc["National"], prior, r) - certainty_equivalent(payoff_table.loc["Riyadh"], prior, r)
R_switch = brentq(gap, 100, 10_000)
print(f"National needs a risk tolerance above about {R_switch:.0f} thousand SAR")National needs a risk tolerance above about 1932 thousand SAR
About 1,932 thousand SAR, nearly five times the owner’s 400. Only a decision maker who would accept a 50-50 gamble to win about 1.9 million or lose about 1 million SAR would launch nationally without a pilot.
# E3: a pilot that is fooled more often by weak products
hit2 = hit.copy()
hit2["Weak"] = 0.40
p_pos2, post_pos2 = posterior(prior, hit2)
p_neg2, post_neg2 = posterior(prior, 1 - hit2)
v_pos = rollback(launch_choice(post_pos2))
v_neg = rollback(launch_choice(post_neg2))
evsi2 = p_pos2 * v_pos + p_neg2 * v_neg - emv.max()
print(f"EVSI with the worse pilot: {evsi2:.1f} thousand SAR (price {PILOT_COST})")EVSI with the worse pilot: 28.9 thousand SAR (price 40)
The EVSI falls to about 28.9 thousand SAR, below the 40-thousand price: the worse pilot is no longer worth running. Raising its false positives on weak products from 15% to 40% takes away about half of the pilot’s value, because a false positive leads to a national launch in a weak market, the one outcome the pilot exists to prevent.