Lab 13: Decision Tree Calculator¶
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 = ... # 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)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 = ...
choice_maximax = ...
choice_maximin = ...
choice_regret = ...
print(choice_maximax, choice_maximin, choice_regret)check("A2 maximax", choice_maximax == "National")
check("A2 maximin", choice_maximin == "No launch")
check("A2 minimax regret", choice_regret == "National")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 = ...
emv = ...
best_emv = ...
print(emv, "\nbest:", best_emv)check("A3 the EMVs", np.allclose(emv.values, [187.5, 125.0, 0.0]))
check("A3 the EMV choice", best_emv == "National")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 ... # the expected value of the children
values = {label: rollback(child) for label, child in node["options"].items()}
node["values"] = values
node["best"] = ... # the label with the largest value
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"])check("B1 the coin flip is worth 60", rollback(test) == 60)
check("B1 and it is the better option", test["best"] == "coin")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: ... for alt in ALTS # a chance node with one branch per state, each ending in a payoff
})
tree = launch_choice(prior)
print(rollback(tree), tree["best"])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")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 = ...
evpi = ...
print(ev_perfect, evpi)check("C1 EVPI", abs(evpi - 150) < 1e-9)
check("C1 so the pilot (40) is under the ceiling", evpi > 40)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 = ...
p_result = ...
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())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")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": ..., # a chance node: positive / negative, each followed by launch_choice(...) shifted by -PILOT_COST
})
rollback(full)
after_pos = full["options"]["Pilot"]["branches"][0][2]
after_neg = full["options"]["Pilot"]["branches"][1][2]
evsi = ... # (value of the Pilot option + PILOT_COST) - best EMV without the pilot
print({k: round(float(v), 2) for k, v in full["values"].items()}, full["best"], after_pos["best"], after_neg["best"], round(evsi, 2))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)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.
Your answer here (double-click to edit).
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 = ...
return ...
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))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")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.
Write your recommendation here (double-click to edit).
★ 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# E2# E3AI-use log (if you used an AI assistant)¶
What you asked, what you kept, what you changed.