Lab 11 Solutions: Logistics Network Model¶
These are the worked solutions, with outputs. Try the lab yourself first.
The question. In January 2026 Qahwa House opens two branches, in Makkah and Madinah. Coffee for the six branches comes from the Riyadh and Dammam roasteries, by van straight to a branch or by full truck through a cross-dock in Jeddah. How much coffee should travel on each lane, what does the best plan save, and what is the cheapest house blend?
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)import sys
if "google.colab" in sys.modules: # Colab does not include PuLP: install it once per session, with the HiGHS solver
%pip install -q "pulp[highs]>=4.3,<5"import pandas as pd
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)
lanes = load("qahwa_network_lanes.csv")
beans = load("qahwa_blend_beans.csv")
supply = {"Riyadh roastery": 2400, "Dammam roastery": 1600} # kg roasted per month, at most
demand = {"Olaya": 900, "University": 400, "Al Faisaliyah": 700, # kg per month, exactly
"Corniche": 800, "Makkah": 500, "Madinah": 400}
HUB, HUB_CAP = "Jeddah hub", 1200 # the hub handles at most 1,200 kg a month
cost = {(r.origin, r.destination): r.cost_sar_per_kg for r in lanes.itertuples()} # SAR per kg, by lane
lanesEach row of lanes is one lane of the network: origin, destination, mode (van, or truck to the hub; the truck cost includes handling at the hub), km and cost_sar_per_kg, the freight cost of one kilogram. The dictionary cost gives the same costs keyed by (origin, destination), for example cost[("Riyadh roastery", "Olaya")].
The nodes are in the dictionaries supply (what each roastery can roast in a month), demand (what each branch needs) and HUB_CAP (what the Jeddah hub can handle).
A reminder of the PuLP you need (Week 9): model.add_variable_dicts("name", keys, lowBound=0) makes one variable per key in that model; model += expression sets the objective the first time, and adds a constraint when the expression contains <=, >= or ==; pulp.lpSum(...) adds many terms; after result = model.solve(pulp.HiGHS(msg=False)), result.status.name is the solver’s verdict ("Optimal"), pulp.value(model.objective) is the optimal cost and var.varValue a variable’s value.
Part A: Vans only (the transportation pattern)¶
First plan without the hub: every kilogram goes by van, straight from a roastery to a branch.
A1. The van lanes¶
Make a list direct of the lanes (the keys of cost) that do not touch the hub.
direct = [lane for lane in cost if HUB not in lane]
len(direct)12check("A1 twelve van lanes, two roasteries times six branches", len(direct) == 12)
check("A1 no lane touches the hub", all(HUB not in lane for lane in direct))✅ A1 twelve van lanes, two roasteries times six branches
✅ A1 no lane touches the hub
A2. Build and solve the model¶
Complete the model: the objective is the total freight; each roastery ships at most its supply; each branch receives exactly its demand. Store the optimal freight in vans_only.
m = pulp.LpProblem("vans_only", pulp.LpMinimize)
ship = m.add_variable_dicts("ship", direct, lowBound=0) # kg on each van lane
m += pulp.lpSum(cost[l] * ship[l] for l in direct) # objective: total freight (SAR per month)
for s in supply:
m += pulp.lpSum(ship[l] for l in direct if l[0] == s) <= supply[s] # roastery s ships at most supply[s]
for b in demand:
m += pulp.lpSum(ship[l] for l in direct if l[1] == b) == demand[b] # branch b receives exactly demand[b]
result = m.solve(pulp.HiGHS(msg=False))
vans_only = pulp.value(m.objective)
print(result.status.name, vans_only)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 6795.0
check("A2 the model is solved", result.status.name == "Optimal")
check("A2 the cheapest van-only plan costs 6,795 SAR a month", round(vans_only) == 6795)✅ A2 the model is solved
✅ A2 the cheapest van-only plan costs 6,795 SAR a month
A3. A surprising lane¶
Show the plan as a table, roasteries by branches (the cell does it for you). Then store in univ_from_dammam the kilograms that the University branch, in Al-Kharj, 85 km from the Riyadh roastery, receives from Dammam.
plan = pd.Series({l: ship[l].varValue for l in direct}).unstack()[list(demand)]
print(plan.astype(int))
univ_from_dammam = ship[("Dammam roastery", "University")].varValue
univ_from_dammam Olaya University Al Faisaliyah Corniche Makkah Madinah
Dammam roastery 0 400 700 0 0 200
Riyadh roastery 900 0 0 800 500 200
400.0check("A3 University gets all its coffee from Dammam", univ_from_dammam == 400)✅ A3 University gets all its coffee from Dammam
A4. Why does a branch 85 km from Riyadh get its coffee from 450 km away? Compute, for each branch, how much more a kilogram costs from Dammam than from Riyadh, then explain in two sentences. (Hint: can Riyadh serve all the branches near it and in the west?)
# A4
extra = pd.Series({b: cost[("Dammam roastery", b)] - cost[("Riyadh roastery", b)] for b in demand})
extra.sort_values()Al Faisaliyah -1.25
University 1.17
Madinah 1.22
Olaya 1.25
Corniche 1.28
Makkah 1.31
dtype: float64Riyadh would need 900 + 400 + 800 + 500 + 400 = 3,000 kg to serve every branch except Al Faisaliyah, and it roasts 2,400, so 600 kg must come from Dammam. Dammam costs the least extra at University (1.17 SAR per kg, then Madinah at 1.22), so the model gives Dammam all of University and 200 kg of Madinah: the long van to Al-Kharj frees Riyadh’s coffee for the west, where Dammam would cost more.
Part B: The network with the hub¶
The Jeddah hub is a transshipment node: coffee goes in by truck and out by van, and none stays there. Its constraints are a flow balance (coffee into the hub = coffee out of the hub) and a capacity (coffee into the hub ≤ HUB_CAP).
B1. The hub’s constraints¶
Complete the function: into_hub is the sum of the shipments on the lanes whose destination is the hub, out_of_hub the sum on the lanes whose origin is the hub. Then add the two constraints. Store the optimal freight in network_cost.
def solve_network(hub_cap=HUB_CAP):
m = pulp.LpProblem("network", pulp.LpMinimize)
ship = m.add_variable_dicts("ship", list(cost), lowBound=0)
m += pulp.lpSum(cost[l] * ship[l] for l in cost)
for s in supply:
m += pulp.lpSum(ship[l] for l in cost if l[0] == s) <= supply[s], "supply_" + s.split()[0]
for b in demand:
m += pulp.lpSum(ship[l] for l in cost if l[1] == b) == demand[b], "demand_" + b.replace(" ", "_")
into_hub = pulp.lpSum(ship[l] for l in cost if l[1] == HUB)
out_of_hub = pulp.lpSum(ship[l] for l in cost if l[0] == HUB)
m += into_hub == out_of_hub, "hub_balance"
m += into_hub <= hub_cap, "hub_capacity"
result = m.solve(pulp.HiGHS(msg=False))
return m, result.status.name, ship
net, status, ship = solve_network()
network_cost = pulp.value(net.objective)
print(status, network_cost)
used = pd.Series({l: ship[l].varValue for l in cost})
used[used > 0]Optimal 4999.0
Riyadh roastery Olaya 900.0
University 400.0
Makkah 100.0
Madinah 400.0
Jeddah hub 600.0
Dammam roastery Al Faisaliyah 700.0
Jeddah hub 600.0
Jeddah hub Corniche 800.0
Makkah 400.0
dtype: float64hub_in = sum(ship[l].varValue for l in cost if l[1] == HUB)
hub_out = sum(ship[l].varValue for l in cost if l[0] == HUB)
check("B1 the hub passes on all it receives", abs(hub_in - hub_out) < 1e-6)
check("B1 the hub is used, within its capacity", 0 < hub_in <= HUB_CAP + 1e-6)
check("B1 the cheapest plan with the hub costs 4,999 SAR a month", round(network_cost) == 4999)✅ B1 the hub passes on all it receives
✅ B1 the hub is used, within its capacity
✅ B1 the cheapest plan with the hub costs 4,999 SAR a month
B2. Read the plan¶
Store in hub_kg the coffee that goes through the hub, in dammam_to_hub the coffee that Dammam sends to the hub, and in saving how much less the network costs than the van-only plan of Part A (SAR per month).
hub_kg = sum(ship[l].varValue for l in cost if l[1] == HUB)
dammam_to_hub = ship[("Dammam roastery", HUB)].varValue
saving = vans_only - network_cost
hub_kg, dammam_to_hub, saving(1200.0, 600.0, 1796.0)check("B2 the hub is full", round(hub_kg) == HUB_CAP)
check("B2 half of the hub's coffee comes from Dammam, 1,350 km away", round(dammam_to_hub) == 600)
check("B2 the hub saves about a quarter of the freight", round(saving) == 1796)✅ B2 the hub is full
✅ B2 half of the hub's coffee comes from Dammam, 1,350 km away
✅ B2 the hub saves about a quarter of the freight
B3. A hand planner’s rule¶
A planner without a model would fill the cheapest routes first: sort the routes from a roastery to a branch (by van, or by truck and van through the hub) by their cost per kg, and send as much as possible on each in turn. That rule gives the plan below. Compute its freight and store it in rule_cost.
rule_plan = { # kg on each lane, from the "cheapest route first" rule
("Riyadh roastery", "Olaya"): 900, ("Dammam roastery", "Al Faisaliyah"): 700, ("Riyadh roastery", "University"): 400,
("Riyadh roastery", HUB): 1100, ("Dammam roastery", HUB): 100, (HUB, "Corniche"): 800, (HUB, "Makkah"): 400,
("Dammam roastery", "Madinah"): 400, ("Dammam roastery", "Makkah"): 100}
rule_cost = sum(cost[l] * kg for l, kg in rule_plan.items())
rule_cost5338.0check("B3 the rule's plan meets every demand",
all(sum(kg for l, kg in rule_plan.items() if l[1] == b) == demand[b] for b in demand))
check("B3 the rule's plan costs 5,338 SAR a month", round(rule_cost) == 5338)
check("B3 the linear program is cheaper", network_cost < rule_cost)✅ B3 the rule's plan meets every demand
✅ B3 the rule's plan costs 5,338 SAR a month
✅ B3 the linear program is cheaper
B4. Compare the two plans lane by lane. In two sentences: where does the rule go wrong, and why does the best plan send Dammam’s coffee 1,350 km to Jeddah although Riyadh is closer?
The rule spends Riyadh’s last kilograms on Makkah through the hub (2.20 SAR per kg, the cheapest route left at that moment) and then has to serve Madinah by van from Dammam at 4.19 SAR per kg. The linear program sends Riyadh’s coffee to Madinah directly (2.97) and lets Dammam fill the hub instead (2.24 + 0.30 to Corniche): a lane’s real cost is what it frees up elsewhere, and Riyadh’s capacity saves more in Madinah than in Jeddah, so the plan costs 339 SAR a month less.
B5. What the hub’s capacity is worth¶
After the solve, each constraint’s .pi is its shadow price (Week 10). Store the shadow price of the hub’s capacity in hub_price (look it up with net.get_constraint_by_name("hub_capacity")).
hub_price = net.get_constraint_by_name("hub_capacity").pi
round(hub_price, 2)-0.87check("B5 one more kg of hub capacity would save 0.87 SAR", round(abs(hub_price), 2) == 0.87)✅ B5 one more kg of hub capacity would save 0.87 SAR
Part C: The house blend (the blending pattern)¶
Qahwa House’s house blend mixes green beans from the five origins in beans. Its specification:
average acidity between 5.5 and 7.0, and average body at least 6.0;
average cup score at least 84;
at least 5% Yemen Mocha.
C1. One kilogram of blend¶
The variables are the shares of each origin in one kilogram, so they sum to 1, and each average is a weighted sum, for example the blend’s acidity is pulp.lpSum(b.acidity[o] * x[o] for o in b.index). Complete the model and store the cost of one kilogram in blend_cost.
b = beans.set_index("origin")
blend = pulp.LpProblem("house_blend", pulp.LpMinimize)
x = blend.add_variable_dicts("share", b.index, lowBound=0)
blend += pulp.lpSum(b.price_sar_per_kg[o] * x[o] for o in b.index) # objective: the cost of one kg of blend
blend += pulp.lpSum(x.values()) == 1 # the shares make one kg
blend += pulp.lpSum(b.acidity[o] * x[o] for o in b.index) >= 5.5 # acidity at least 5.5
blend += pulp.lpSum(b.acidity[o] * x[o] for o in b.index) <= 7.0 # acidity at most 7.0
blend += pulp.lpSum(b.body[o] * x[o] for o in b.index) >= 6.0 # body at least 6.0
blend += pulp.lpSum(b.cup_score[o] * x[o] for o in b.index) >= 84 # cup score at least 84
blend += x["Yemen Mocha"] >= 0.05 # Yemen Mocha at least 5%
result = blend.solve(pulp.HiGHS(msg=False))
blend_cost = pulp.value(blend.objective)
shares = pd.Series({o: x[o].varValue for o in b.index})
print(result.status.name, blend_cost)
sharesOptimal 32.06
Brazil Santos 0.61
Colombia Supremo 0.00
Ethiopia Yirgacheffe 0.34
Sumatra Mandheling 0.00
Yemen Mocha 0.05
dtype: float64check("C1 the cheapest blend costs 32.06 SAR per kg", round(blend_cost, 2) == 32.06)
check("C1 Colombia, the all-rounder, is not in it", shares["Colombia Supremo"] < 1e-6)
check("C1 Brazil and Ethiopia make up 95%", abs(shares["Brazil Santos"] + shares["Ethiopia Yirgacheffe"] - 0.95) < 1e-6)✅ C1 the cheapest blend costs 32.06 SAR per kg
✅ C1 Colombia, the all-rounder, is not in it
✅ C1 Brazil and Ethiopia make up 95%
C2. A month’s purchase¶
A month of roasting needs 4,400 kg of green beans, and the importer can supply at most available_kg_month of each origin. Now the variables are kilograms, so an average is a ratio. Write it linearly: “average acidity at least 5.5” becomes pulp.lpSum((b.acidity[o] - 5.5) * kg[o] for o in b.index) >= 0, and so on for the other averages. PuLP 4 wants plain Python numbers in a comparison, and pandas stores whole numbers as NumPy integers, so write the availability as kg[o] <= int(b.available_kg_month[o]). Store the month’s cost in month_cost.
month = pulp.LpProblem("monthly_purchase", pulp.LpMinimize)
kg = month.add_variable_dicts("kg", b.index, lowBound=0)
month += pulp.lpSum(b.price_sar_per_kg[o] * kg[o] for o in b.index) # objective: the cost of the beans
month += pulp.lpSum(kg.values()) == 4400
month += pulp.lpSum((b.acidity[o] - 5.5) * kg[o] for o in b.index) >= 0 # the four averages, written linearly
month += pulp.lpSum((b.acidity[o] - 7.0) * kg[o] for o in b.index) <= 0
month += pulp.lpSum((b.body[o] - 6.0) * kg[o] for o in b.index) >= 0
month += pulp.lpSum((b.cup_score[o] - 84) * kg[o] for o in b.index) >= 0
month += kg["Yemen Mocha"] >= 0.05 * 4400 # Yemen Mocha at least 5% of the 4,400 kg
for o in b.index: # each origin at most its availability
month += kg[o] <= int(b.available_kg_month[o])
result = month.solve(pulp.HiGHS(msg=False))
month_cost = pulp.value(month.objective)
buy = pd.Series({o: kg[o].varValue for o in b.index})
print(result.status.name, month_cost)
buyOptimal 142100.0
Brazil Santos 2240.0
Colombia Supremo 740.0
Ethiopia Yirgacheffe 1200.0
Sumatra Mandheling 0.0
Yemen Mocha 220.0
dtype: float64check("C2 the month's beans cost 142,100 SAR", round(month_cost) == 142100)
check("C2 all the Ethiopian beans available are bought", round(buy["Ethiopia Yirgacheffe"]) == 1200)
check("C2 so Colombia comes back into the blend", buy["Colombia Supremo"] > 0)✅ C2 the month's beans cost 142,100 SAR
✅ C2 all the Ethiopian beans available are bought
✅ C2 so Colombia comes back into the blend
C3. Today’s recipe is 95% Colombia and 5% Yemen Mocha. What does it cost for 4,400 kg, and how much does the new purchase plan save each month? Store the saving in blend_saving.
today_cost = 4400 * (0.95 * b.price_sar_per_kg["Colombia Supremo"] + 0.05 * b.price_sar_per_kg["Yemen Mocha"])
blend_saving = today_cost - month_cost
print(f"today's recipe: {today_cost:,.0f} SAR new plan: {month_cost:,.0f} SAR saving: {blend_saving:,.0f} SAR a month")today's recipe: 149,380 SAR new plan: 142,100 SAR saving: 7,280 SAR a month
check("C3 the new purchase plan saves 7,280 SAR a month", round(blend_saving) == 7280)✅ C3 the new purchase plan saves 7,280 SAR a month
Part D: Your recommendation¶
Write three sentences for the operations manager: how the coffee should travel in 2026 (with the plan’s monthly freight and what it saves compared with vans only and with the cheapest-route rule), which green beans to buy and what that saves, and one thing to check before relying on the model (an assumption or a number you would want confirmed).
Route 1,200 kg a month through the Jeddah hub, 600 kg from each roastery, serve Madinah and 100 kg of Makkah by van from Riyadh, and the rest by van from the nearest roastery: freight falls to 4,999 SAR a month, 1,796 SAR less than vans only and 339 SAR less than filling the cheapest routes first. For the house blend, buy 2,240 kg of Brazil, 1,200 kg of Ethiopia (all that is available), 740 kg of Colombia and 220 kg of Yemen Mocha a month: it meets the specification for 142,100 SAR, 7,280 SAR a month less than today’s Colombia recipe. Before relying on it, confirm the hub’s real capacity and the van rates, and run a cupping panel on the new blend, since the scores are averages of last year’s lots.
★ Extended challenges¶
E1. Ramadan. Demand for the four months January to April 2026 is 3,700, 4,300, 4,600 and 3,500 kg. The roasteries roast at most 4,000 kg a month in normal shifts (6 SAR per kg) plus up to 400 kg of overtime (9 SAR per kg); coffee kept in stock costs 1.2 SAR per kg per month, and there is no stock at the start. Show that planning month by month fails, then build a multiperiod model with an inventory balance (stock before + roasted − demand = stock after) and find the cheapest plan.
E2. More hub capacity. The hub’s operator offers 300 kg a month more capacity for 250 SAR a month. The shadow price from B5 says 300 × 0.87 = 261 SAR of savings. Re-solve with solve_network(hub_cap=1500): should Qahwa House accept? Why does the shadow price mislead here?
E3. More Yemeni coffee. Marketing wants 10% Yemen Mocha in the blend. What happens to the monthly purchase model of C2? What is the largest Yemen share the importer’s supply allows?
# E1
months = ["Jan", "Feb", "Mar", "Apr"]
need = pd.Series([3700, 4300, 4600, 3500], index=months)
print("overtime needed month by month:", (need - 4000).clip(lower=0).to_dict(), "- March needs 600 > 400: impossible")
mp = pulp.LpProblem("roasting_plan", pulp.LpMinimize)
reg = mp.add_variable_dicts("regular", months, lowBound=0, upBound=4000)
ot = mp.add_variable_dicts("overtime", months, lowBound=0, upBound=400)
stock = mp.add_variable_dicts("stock", months, lowBound=0)
mp += pulp.lpSum(6 * reg[t] + 9 * ot[t] + 1.2 * stock[t] for t in months)
for i, t in enumerate(months):
before = stock[months[i - 1]] if i > 0 else 0
mp += before + reg[t] + ot[t] - int(need[t]) == stock[t]
result = mp.solve(pulp.HiGHS(msg=False))
print(result.status.name, pulp.value(mp.objective))
pd.DataFrame({"regular": [reg[t].varValue for t in months], "overtime": [ot[t].varValue for t in months],
"end stock": [stock[t].varValue for t in months]}, index=months)overtime needed month by month: {'Jan': 0, 'Feb': 300, 'Mar': 600, 'Apr': 0} - March needs 600 > 400: impossible
Optimal 99000.0
Month by month, March would need 600 kg of overtime and only 400 kg are possible. Planned together, the four months cost 99,000 SAR: January roasts 300 kg ahead for February, February runs 200 kg of overtime for March, and March runs its full 400 kg of overtime. Holding coffee for a month (1.2 SAR) is cheaper than the overtime premium (3 SAR).
# E2
bigger, _, _ = solve_network(hub_cap=1500)
print(f"freight with 1,500 kg: {pulp.value(bigger.objective):,.0f} SAR; saving {network_cost - pulp.value(bigger.objective):,.0f} SAR a month")
for h in [1200, 1300, 1400, 1500]:
model, status, _ = solve_network(hub_cap=h) # keep the model while you read its results
print(h, pulp.value(model.objective))freight with 1,500 kg: 4,912 SAR; saving 87 SAR a month
1200 4999.0
1300 4912.0
1400 4912.0
1500 4912.0
No: 300 kg more capacity saves only 87 SAR a month, less than the 250 SAR it costs. The shadow price of 0.87 SAR per kg holds for the next 100 kg only; beyond 1,300 kg the extra capacity is not used, because the remaining branches are cheaper to serve another way. A shadow price is a slope at the current plan, valid over a range, not a price for any quantity.
# E3
def purchase(yemen_share):
"""Solve the monthly purchase of C2 with a given minimum share of Yemen Mocha; return the solver's status."""
mm = pulp.LpProblem("monthly_purchase", pulp.LpMinimize)
q = mm.add_variable_dicts("kg", b.index, lowBound=0)
mm += pulp.lpSum(b.price_sar_per_kg[o] * q[o] for o in b.index)
mm += pulp.lpSum(q.values()) == 4400
mm += pulp.lpSum((b.acidity[o] - 5.5) * q[o] for o in b.index) >= 0
mm += pulp.lpSum((b.acidity[o] - 7.0) * q[o] for o in b.index) <= 0
mm += pulp.lpSum((b.body[o] - 6.0) * q[o] for o in b.index) >= 0
mm += pulp.lpSum((b.cup_score[o] - 84) * q[o] for o in b.index) >= 0
mm += q["Yemen Mocha"] >= yemen_share * 4400
for o in b.index:
mm += q[o] <= int(b.available_kg_month[o])
return mm.solve(pulp.HiGHS(msg=False)).status.name
print("5% Yemen:", purchase(0.05), " 10% Yemen:", purchase(0.10))
print(f"largest Yemen share the supply allows: {b.available_kg_month['Yemen Mocha'] / 4400:.1%}")5% Yemen: Optimal 10% Yemen: Infeasible
largest Yemen share the supply allows: 6.8%
The model becomes infeasible: 10% of 4,400 kg is 440 kg and the importer supplies only 300 kg of Yemen Mocha. The largest share possible is 300 / 4,400 = 6.8%. Marketing must either accept that, find another supplier, or make less blend with the Yemeni claim.