Lab 11: Logistics Network Model¶
In this lab you build the network model of Qahwa House’s coffee deliveries in PuLP, compare it with a hand planner’s rule, and then blend the house coffee at the lowest cost.
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.
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 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 = ...
len(direct)check("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))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 += ... # objective: total freight (SAR per month)
for s in supply:
m += ... # roastery s ships at most supply[s]
for b in demand:
m += ... # 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)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)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 = ...
univ_from_dammamcheck("A3 University gets all its coffee from Dammam", univ_from_dammam == 400)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?)
# A4Your answer here (double-click to edit).
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 = ...
out_of_hub = ...
m += ..., "hub_balance"
m += ..., "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]hub_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)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 = ...
dammam_to_hub = ...
saving = ...
hub_kg, dammam_to_hub, savingcheck("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)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 = ...
rule_costcheck("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)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?
Your answer here (double-click to edit).
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 = ...
hub_pricecheck("B5 one more kg of hub capacity would save 0.87 SAR", round(abs(hub_price), 2) == 0.87)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 += ... # objective: the cost of one kg of blend
blend += pulp.lpSum(x.values()) == 1 # the shares make one kg
blend += ... # acidity at least 5.5
blend += ... # acidity at most 7.0
blend += ... # body at least 6.0
blend += ... # cup score at least 84
blend += ... # 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)
sharescheck("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)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 += ... # objective: the cost of the beans
month += pulp.lpSum(kg.values()) == 4400
... # the four averages, written linearly
... # Yemen Mocha at least 5% of the 4,400 kg
... # each origin at most its availability (a loop)
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)
buycheck("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)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.
blend_saving = ...
blend_savingcheck("C3 the new purchase plan saves 7,280 SAR a month", round(blend_saving) == 7280)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).
Write your recommendation here (double-click to edit).
★ 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# E2# E3AI-use log (if you used an AI assistant)¶
What you asked, what you kept, what you changed.