Modeling Patterns: Networks, Blends and Time¶
In Week 9 you built a first linear program, and in Week 10 you read what its constraints are worth. Real business models are larger, but most of them are assembled from a few patterns that come back again and again. This reading builds three of them for Qahwa House in PuLP: a network that moves coffee from two roasteries through a hub to six branches, a blend that mixes green beans to a taste specification, and a multiperiod plan that links the months through stock. One idea runs through all three: a balance constraint that says what comes in must go out, or stay.
After this reading you can:
formulate a transportation model from a table of lanes and solve it in PuLP;
add a transshipment node (a hub) with a flow-balance constraint and a capacity;
explain, with shadow prices, why the cheapest lane is not always in the cheapest plan;
write averages and percentages as linear constraints in a blending model;
link time periods with inventory-balance constraints.
Textbook: Albright & Winston, Chapter 14.
The first cell installs PuLP when you run the notebook in Colab (it takes a few seconds); on your own computer, install it once with pip install "pulp[highs]". PuLP 4 needs a solver named explicitly; the course uses HiGHS (free, open source, installed by pulp[highs]), which also reports shadow prices and reduced costs.
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"The decision¶
In January 2026 Qahwa House opens two branches, in Makkah and Madinah. Six branches now need roasted coffee every month, and it comes from two roasteries, in Riyadh and Dammam. Coffee travels either by van, straight from a roastery to a branch, or by full truck to a cross-dock in Jeddah, the hub, where vans take it on to the three western branches. A full truck costs much less per kilogram than a van, but the hub can handle at most 1,200 kg a month.
How much coffee should travel on each lane, so that every branch gets its coffee at the lowest freight cost?
import pandas as pd
import matplotlib.pyplot as plt
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")
lanes| Column | Meaning |
|---|---|
origin, destination | the two ends of the lane |
mode | van (loaded at the origin, driven to the destination) or truck (a full truck to the hub; the cost includes handling at the hub) |
km | road distance |
cost_sar_per_kg | freight cost of moving one kilogram on the lane (SAR) |
The lanes are the arcs of the network. The nodes have their own numbers: what each roastery can roast in a month, what each branch needs, and the hub’s capacity. We write them as dictionaries, and turn the lane table into a dictionary of costs keyed by (origin, destination).
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
print(f"supply {sum(supply.values()):,} kg demand {sum(demand.values()):,} kg lanes {len(cost)}")supply 4,000 kg demand 3,700 kg lanes 17
# Where the nodes sit: a sketch of the map, west on the left (spread out to be readable, not to scale)
POS = {"Madinah": (40.0, 25.3), "Jeddah hub": (40.8, 22.6), "Corniche": (39.0, 21.3), "Makkah": (41.8, 21.0),
"Riyadh roastery": (45.6, 24.4), "Olaya": (46.9, 23.2), "University": (45.2, 22.0),
"Dammam roastery": (49.4, 26.4), "Al Faisaliyah": (50.6, 24.6)}
def draw_network(flows=None, title=""):
"""Draw every lane in grey; with flows (kg by lane), draw the lanes in use, thicker for more coffee."""
fig, ax = plt.subplots(figsize=(8, 4.4))
for (a, b) in cost:
(x1, y1), (x2, y2) = POS[a], POS[b]
ax.plot([x1, x2], [y1, y2], color="#d5dde2", lw=1, zorder=1)
if flows is not None:
for (a, b), kg in flows.items():
if kg > 0.5:
(x1, y1), (x2, y2) = POS[a], POS[b]
ax.annotate("", xy=(x2, y2), xytext=(x1, y1), zorder=2,
arrowprops=dict(arrowstyle="-|>", color="#1f6f8b", lw=0.8 + kg / 300, shrinkA=10, shrinkB=10))
ax.text(x1 + 0.55 * (x2 - x1), y1 + 0.55 * (y2 - y1), f"{kg:,.0f}", fontsize=8, color="#1f6f8b",
ha="center", va="center", zorder=3,
bbox=dict(boxstyle="round,pad=0.2", fc="white", ec="#1f6f8b", lw=0.5))
for n, (x, y) in POS.items():
kind = "roastery" if n in supply else "hub" if n == HUB else "branch"
ax.scatter(x, y, s=170 if kind != "branch" else 90, zorder=4,
marker={"roastery": "s", "hub": "D", "branch": "o"}[kind],
color={"roastery": "#e07b39", "hub": "#7a5195", "branch": "#1f6f8b"}[kind])
if kind == "branch":
ax.text(x, y - 0.4, f"{n}\n{demand[n]:,} kg", fontsize=8, ha="center", va="top", zorder=5)
else:
cap = f"{supply[n]:,} kg" if kind == "roastery" else f"max {HUB_CAP:,} kg"
ax.text(x, y + 0.4, f"{n}\n{cap}", fontsize=8, ha="center", va="bottom", zorder=5, weight="bold")
ax.set_xlim(37.8, 51.8); ax.set_ylim(19.6, 27.8); ax.set_aspect("equal"); ax.axis("off")
ax.set_title(title, fontsize=11)
plt.show()
draw_network(title="The 2026 network: 2 roasteries (squares), the Jeddah hub (diamond), 6 branches (kg a month)")
The roasteries can roast 4,000 kg a month, and the branches need 3,700 kg, so there is enough coffee. The question is only where each kilogram goes. With 17 lanes, there are far too many plans to try by hand.
1. The transportation pattern¶
Start without the hub: vans only, from a roastery straight to a branch. This is the transportation pattern, one of the oldest linear programs:
sources with a capacity (the roasteries) and destinations with a demand (the branches);
one decision variable per lane: = kg sent from source to destination , with ;
minimise the total cost ;
each source ships at most its capacity: ;
each destination receives exactly its demand: .
In PuLP, the model’s add_variable_dicts creates one variable for every key of a list, here every lane. The constraints are written with a loop over the nodes, and each one sums the variables of the lanes that leave (or enter) the node.
direct = [lane for lane in cost if HUB not in lane] # the 12 van lanes from a roastery to a branch
m = pulp.LpProblem("transportation", pulp.LpMinimize)
ship = m.add_variable_dicts("ship", direct, lowBound=0) # kg on each lane
m += pulp.lpSum(cost[l] * ship[l] for l in direct) # objective: freight, SAR per month
for s in supply: # a roastery ships at most what it can roast
m += pulp.lpSum(ship[l] for l in direct if l[0] == s) <= supply[s]
for b in demand: # a branch receives exactly what it needs
m += pulp.lpSum(ship[l] for l in direct if l[1] == b) == demand[b]
result = m.solve(pulp.HiGHS(msg=False))
print(result.status.name, f"- freight {pulp.value(m.objective):,.0f} SAR per month")
plan = pd.Series({l: ship[l].varValue for l in direct}).unstack()[list(demand)]
plan.astype(int)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 - freight 6,795 SAR per month
The cheapest van-only plan costs 6,795 SAR a month. Riyadh roasts all it can (2,400 kg). The surprise is in the University column: the branch in Al-Kharj, 85 km from the Riyadh roastery, gets all its coffee from Dammam, 450 km away. And Madinah gets 200 kg from each roastery.
Why? Riyadh cannot serve every branch near it and in the west: that would take 3,000 kg, and it roasts 2,400. So 600 kg of those branches must come from Dammam. The useful question is not “which lane is cheapest?” but “where does it hurt least to use Dammam instead of Riyadh?”:
extra = pd.Series({b: cost[("Dammam roastery", b)] - cost[("Riyadh roastery", b)] for b in demand})
extra.sort_values().rename("extra SAR per kg if Dammam serves the branch")Al Faisaliyah -1.25
University 1.17
Madinah 1.22
Olaya 1.25
Corniche 1.28
Makkah 1.31
Name: extra SAR per kg if Dammam serves the branch, dtype: float64Al Faisaliyah is cheaper from Dammam anyway. Among the others, University is where Dammam costs the least extra (1.17 SAR per kg), then Madinah (1.22). The linear program gives Dammam exactly those 600 kg: all 400 of University and 200 of Madinah. A van from Dammam to Al-Kharj looks wasteful lane by lane, yet it is what lets Riyadh’s coffee go where it saves the most.
2. Network flow: a hub and its balance¶
Now add the Jeddah hub. The hub is a transshipment node: it neither roasts nor drinks coffee, it only passes it on. Its constraint is a flow balance:
and, because it can handle at most 1,200 kg a month, a capacity: coffee into the hub . Every node in a network gets a balance of this kind: at a roastery, what leaves is at most what it roasts; at a branch, what arrives is what it needs; at the hub, in equals out. That is the whole network flow pattern.
The function below builds the model for any hub capacity and any roastery capacities, so we can reuse it.
def solve_network(use_hub=True, hub_cap=HUB_CAP, supply=supply):
"""The cheapest delivery plan: returns the solved model, the solver's status and the kg on each lane."""
L = [l for l in cost if use_hub or HUB not in l]
m = pulp.LpProblem("delivery_plan", pulp.LpMinimize)
ship = m.add_variable_dicts("ship", L, lowBound=0)
m += pulp.lpSum(cost[l] * ship[l] for l in L)
for s in supply:
m += pulp.lpSum(ship[l] for l in L if l[0] == s) <= supply[s], "supply_" + s.split()[0]
for b in demand:
m += pulp.lpSum(ship[l] for l in L if l[1] == b) == demand[b], "demand_" + b.replace(" ", "_")
if use_hub:
into_hub = pulp.lpSum(ship[l] for l in L if l[1] == HUB)
out_of_hub = pulp.lpSum(ship[l] for l in L if l[0] == HUB)
m += into_hub == out_of_hub, "hub_balance" # the hub passes coffee on: in = out
m += into_hub <= hub_cap, "hub_capacity"
result = m.solve(pulp.HiGHS(msg=False))
return m, result.status.name, pd.Series({l: ship[l].varValue for l in L})
net, status, flows = solve_network()
print(status, f"- freight {pulp.value(net.objective):,.0f} SAR per month")
used = flows[flows > 0].rename("kg").to_frame()
used["SAR per kg"] = [cost[l] for l in used.index]
usedOptimal - freight 4,999 SAR per month
draw_network(flows, "The cheapest plan with the hub: 4,999 SAR a month")
With the hub, freight falls to 4,999 SAR a month, 1,796 SAR less than with vans only (26% less). Three things in this plan are worth a second look:
The hub is full: 1,200 kg go through it (600 from each roastery), and Makkah gets its last 100 kg by van straight from Riyadh.
Riyadh is full (2,400 kg) and Dammam has 300 kg to spare.
Dammam’s coffee drives 1,350 km to Jeddah, the longest lane on the map, although Riyadh is closer to Jeddah. And Madinah gets its coffee by van from Riyadh rather than through the hub: through the hub it would cost 1.68 + 1.56 = 3.24 SAR per kg, against 2.97 direct.
Why not just use the cheapest lanes?¶
A natural way to plan by hand is to take the cheapest route first: sort every route from a roastery to a branch (direct, or through the hub) by its cost per kg, and send as much as you can on each in turn, until the roasteries, the hub or the branches run out. Here it is in code:
def cheapest_route_first():
"""A hand planner's rule: fill the cheapest routes first, as far as the capacities allow."""
routes = []
for s in supply:
for b in demand:
routes.append((cost[(s, b)], s, b, False)) # by van
if (HUB, b) in cost:
routes.append((round(cost[(s, HUB)] + cost[(HUB, b)], 2), s, b, True)) # through the hub
left, need, hub_left, rows = dict(supply), dict(demand), HUB_CAP, []
for c, s, b, via_hub in sorted(routes, key=lambda r: r[0]):
kg = min(left[s], need[b], hub_left if via_hub else need[b])
if kg > 0:
left[s] -= kg; need[b] -= kg; hub_left -= kg if via_hub else 0
rows.append((s, "hub" if via_hub else "van", b, kg, c, kg * c))
return pd.DataFrame(rows, columns=["from", "via", "to", "kg", "SAR per kg", "SAR"])
greedy = cheapest_route_first()
print(f"cheapest route first: {greedy['SAR'].sum():,.0f} SAR linear program: {pulp.value(net.objective):,.0f} SAR")
greedycheapest route first: 5,338 SAR linear program: 4,999 SAR
The rule costs 5,338 SAR a month, 339 SAR (6.8%) more than the linear program, or about 4,000 SAR a year. It starts well, but it spends Riyadh’s last 300 kg on Makkah through the hub (2.20 SAR per kg, the cheapest route left at that moment) and is then stuck: Madinah’s 400 kg must come by van from Dammam at 4.19 SAR per kg. The linear program sees the whole network at once. It sends Riyadh’s coffee to Madinah (2.97) and lets Dammam fill the hub instead (2.24 + 0.30 to Corniche). What matters is not what a lane costs, but what using it frees up elsewhere.
What the constraints are worth¶
Week 10’s shadow prices put a number on “frees up”. PuLP stores them in each constraint’s .pi after the solve. For a minimisation, a negative shadow price on a capacity says how much the cost would fall with one more unit of it.
prices = pd.Series({c.name: c.pi for c in net.constraints()
if c.name.startswith(("supply", "hub_capacity"))})
(prices.round(2) + 0.0).rename("shadow price (SAR per kg)") # + 0.0 shows the solver's -0.0 as 0.0supply_Riyadh -0.56
supply_Dammam 0.00
hub_capacity -0.87
Name: shadow price (SAR per kg), dtype: float64One more kilogram of Riyadh capacity would save 0.56 SAR, and one more kilogram of hub capacity 0.87 SAR. Dammam’s capacity is worth nothing at the margin: it already has 300 kg to spare. A shadow price is only valid over a range, though. Re-solving for a range of hub capacities shows how far the 0.87 holds:
caps = list(range(0, 2101, 100))
freight = {}
for h in caps:
model, status, _ = solve_network(hub_cap=h) # keep the model while you read its results
freight[h] = pulp.value(model.objective)
freight = pd.Series(freight)
fig, ax = plt.subplots(figsize=(7, 3.2))
ax.plot(freight.index, freight.values, marker="o", ms=3, color="#1f6f8b")
ax.axvline(HUB_CAP, color="#e07b39", ls="--", lw=1)
ax.text(HUB_CAP + 30, 6400, "today: 1,200 kg", color="#e07b39", fontsize=9)
ax.set_xlabel("hub capacity (kg per month)"); ax.set_ylabel("freight (SAR per month)")
plt.show()
print(freight.loc[[0, 1200, 1300, 1500, 2100]].to_string())
0 6795.0
1200 4999.0
1300 4912.0
1500 4912.0
2100 4912.0
Without a hub (capacity 0) the freight is the van-only 6,795 SAR. Each step of hub capacity saves less than the one before, and above 1,300 kg nothing more is saved (4,912 SAR): the cheap trucks then carry everything they can usefully carry. So the shadow price of 0.87 SAR per kg holds for the next 100 kg only. If the hub’s operator offered 300 kg more capacity for 250 SAR a month, it would save 87 SAR, not 3 × 87: a bad deal.
3. The blending pattern¶
Qahwa House roasts one house blend, mixed from green beans of five origins. The blend must taste the same all year, so it has a specification, checked by cupping:
average acidity between 5.5 and 7.0, and average body at least 6.0 (both on a 0–10 scale);
average cup score at least 84 (on the 100-point specialty scale);
at least 5% Yemen Mocha, because the bag says “with Yemeni Mocha”.
beansThe decision variables are the proportions of each origin in one kilogram of blend, so . An average is a weighted sum: the blend’s acidity is . So “average acidity at least 5.5” is the linear constraint .
When the variables are quantities (kg) rather than proportions, the average is a ratio, , which is not linear. Multiply both sides by the total and it becomes linear again:
This is the one trick of the blending pattern. The function below uses this form, so it works for one kilogram and for a month’s purchase alike.
def solve_blend(total_kg=1, availability=False, yemen_min=0.05):
"""The cheapest blend of total_kg meeting the specification: returns the model, the status and the kg of each origin."""
b = beans.set_index("origin")
m = pulp.LpProblem("house_blend", pulp.LpMinimize)
kg = m.add_variable_dicts("kg", b.index, lowBound=0)
m += pulp.lpSum(b.price_sar_per_kg[o] * kg[o] for o in b.index) # cost of the green beans
m += pulp.lpSum(kg.values()) == total_kg, "total"
def at_least(col, level, name): # an average written linearly
m.addConstraint(pulp.lpSum((b[col][o] - level) * kg[o] for o in b.index) >= 0, name)
at_least("acidity", 5.5, "acidity_min")
m += pulp.lpSum((b.acidity[o] - 7.0) * kg[o] for o in b.index) <= 0, "acidity_max"
at_least("body", 6.0, "body_min")
at_least("cup_score", 84, "cup_min")
m += kg["Yemen Mocha"] >= yemen_min * total_kg, "yemen_min"
if availability:
for o in b.index:
m += kg[o] <= int(b.available_kg_month[o]), "available_" + o.split()[0] # int(): PuLP 4 wants plain Python numbers
result = m.solve(pulp.HiGHS(msg=False))
return m, result.status.name, pd.Series({o: kg[o].varValue for o in b.index})
bm, status, recipe = solve_blend()
print(status, f"- {pulp.value(bm.objective):.2f} SAR per kg of blend")
recipe.round(4).rename("share of the blend")Optimal - 32.06 SAR per kg of blend
Brazil Santos 0.61
Colombia Supremo 0.00
Ethiopia Yirgacheffe 0.34
Sumatra Mandheling 0.00
Yemen Mocha 0.05
Name: share of the blend, dtype: float64def profile(shares):
"""Average price and taste of a blend given as shares that sum to 1."""
b = beans.set_index("origin")
return pd.Series({c: (b[c] * shares).sum() for c in ["price_sar_per_kg", "acidity", "body", "cup_score"]}).round(3)
today = pd.Series({"Colombia Supremo": 0.95, "Yemen Mocha": 0.05}).reindex(beans.origin, fill_value=0)
pd.DataFrame({"cheapest blend": profile(recipe), "today's recipe": profile(today)})The cheapest blend is 61% Brazil, 34% Ethiopia and 5% Yemen Mocha, at 32.06 SAR per kg. Its cup score is exactly 84 and its Yemen share exactly 5%: those two constraints are binding; acidity and body have room to spare.
Today’s recipe, 95% Colombia with 5% Yemen Mocha, also meets the specification: Colombia is the all-rounder, good on every score. Yet it is not in the cheapest blend. Brazil is cheap but too flat and too low in cup score on its own; Ethiopia is dear but has acidity and cup score to give away. Together they meet the specification for 1.89 SAR per kg less than Colombia.
Now a month’s purchase: 3,700 kg of roasted coffee needs about 4,400 kg of green beans (roasting loses about 16% of the weight), and the importer can supply only so much of each origin.
bm2, status, buy = solve_blend(total_kg=4400, availability=True)
print(status, f"- {pulp.value(bm2.objective):,.0f} SAR per month ({pulp.value(bm2.objective) / 4400:.2f} SAR per kg)")
print(f"today's recipe: {4400 * profile(today)['price_sar_per_kg']:,.0f} SAR per month")
pd.DataFrame({"buy (kg)": buy, "available (kg)": beans.set_index("origin").available_kg_month})Optimal - 142,100 SAR per month (32.30 SAR per kg)
today's recipe: 149,380 SAR per month
Ethiopia is limited to 1,200 kg a month, less than the 34% the recipe wants (1,496 kg). So the model takes all 1,200 kg and brings in Colombia (740 kg) to fill the gap. The month costs 142,100 SAR, 7,280 SAR less than today’s recipe (149,380 SAR). The same constraints, one more line each for the availability, and the answer changes: that is why we write models rather than rules of thumb.
4. The multiperiod pattern¶
The last pattern links time periods. During Ramadan (from mid-February to mid-March in 2026) the branches sell more coffee. The two roasteries together roast at most 4,000 kg a month in normal shifts, at 6 SAR per kg, plus up to 400 kg of overtime at 9 SAR per kg. Roasted coffee can wait in stock, at 1.2 SAR per kg per month (storage and lost freshness). The plan starts with no stock.
months = ["Jan", "Feb", "Mar", "Apr"]
need = pd.Series([3700, 4300, 4600, 3500], index=months) # kg of roasted coffee for the six branches
REGULAR, OVERTIME = 4000, 400 # kg per month, at most
C_REG, C_OT, C_STOCK = 6.0, 9.0, 1.2 # SAR per kg
# Month by month, without stock: each month roasts what it needs, in overtime if it must
print((need - REGULAR).clip(lower=0).rename("overtime needed (kg)").to_string())Jan 0
Feb 300
Mar 600
Apr 0
Month by month, March needs 600 kg of overtime and only 400 kg are possible: living from month to month, March cannot be served. The months must be planned together. The link between them is an inventory balance, the flow balance of the network pattern with time as the network:
Coffee “flows” from one month to the next through the stock, exactly as it flowed through the hub.
mp = pulp.LpProblem("roasting_plan", pulp.LpMinimize)
reg = mp.add_variable_dicts("regular", months, lowBound=0, upBound=REGULAR)
ot = mp.add_variable_dicts("overtime", months, lowBound=0, upBound=OVERTIME)
stock = mp.add_variable_dicts("stock", months, lowBound=0) # kg in stock at the end of the month
mp += pulp.lpSum(C_REG * reg[t] + C_OT * ot[t] + C_STOCK * stock[t] for t in months)
for i, t in enumerate(months):
before = stock[months[i - 1]] if i > 0 else 0 # no stock at the start
mp += before + reg[t] + ot[t] - int(need[t]) == stock[t], "balance_" + t
result = mp.solve(pulp.HiGHS(msg=False))
print(result.status.name, f"- {pulp.value(mp.objective):,.0f} SAR for the four months")
roast = pd.DataFrame({"demand": need, "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]})
roast.astype(int)Optimal - 99,000 SAR for the four months
fig, ax = plt.subplots(figsize=(7, 3.2))
ax.bar(months, roast["regular"], color="#1f6f8b", label="regular")
ax.bar(months, roast["overtime"], bottom=roast["regular"], color="#e07b39", label="overtime")
for i, t in enumerate(months):
ax.plot([i - 0.42, i + 0.42], [need[t], need[t]], color="black", lw=2.5, label="demand" if i == 0 else None)
ax.set_ylim(3000, 5000); ax.set_ylabel("kg roasted"); ax.legend(loc="upper left", ncol=3, fontsize=8)
plt.show()
The plan costs 99,000 SAR. It roasts a full 4,000 kg in January and keeps the 300 kg it does not need for February. February runs 200 kg of overtime and keeps them for March, and March runs its full 400 kg of overtime. Holding a kilogram for a month (1.2 SAR) is cheaper than the overtime premium (3 SAR), so the model roasts ahead; the overtime it cannot avoid is pushed as late as possible.
Summary¶
| Pattern | Variables | The typical constraint |
|---|---|---|
| Transportation | kg on each lane | supply: out ≤ capacity; demand: in = need |
| Network flow | kg on each arc | balance at every transshipment node: in = out; capacities on nodes or arcs |
| Blending | kg (or share) of each input | an average as a linear constraint: |
| Multiperiod | production and stock in each period | inventory balance: stock before + produced − demand = stock after |
Build the model from the data: a variable per row of the lane table, a constraint per node, written with loops.
The cheapest lane is not always in the cheapest plan: a lane’s real cost is what it frees up elsewhere, which the shadow prices measure.
A shadow price holds over a range only: re-solve to see how far.
Next week: integer and nonlinear models: yes-or-no decisions, fixed costs, set covering and portfolio risk.