29.1 Rising costs: overtime tiers
overtime_tiers: the first 20 packing hours of overtime cost $60 an hour (the evening shift), the next 20 cost $95 (the night shift). Split overtime into one variable per tier, each up to its hours, and add them to the capacity. Create day29/piecewise.py:
d = load_data(con)
tiers = con.sql("SELECT * FROM overtime_tiers ORDER BY resource, tier").df()
print(tiers.to_string(index=False))
def with_overtime(d):
m = build_model(d)
m.T = pyo.Set(initialize=[(r.resource, r.tier) for r in tiers.itertuples()], dimen=2)
hours = {(r.resource, r.tier): r.hours for r in tiers.itertuples()}
m.rate = {(r.resource, r.tier): r.cost_per_hour for r in tiers.itertuples()}
m.ot = pyo.Var(m.T, bounds=lambda m, r, k: (0, hours[r, k])) # overtime hours in tier k
for r in m.R:
extra = sum(m.ot[t] for t in m.T if t[0] == r)
m.capacity_limit[r].set_value(sum(m.use[r, p] * m.x[p] for p in m.P) <= m.capacity[r] + extra)
m.overtime_cost = pyo.Expression(expr=sum(m.rate[t] * m.ot[t] for t in m.T))
m.total_profit.deactivate()
m.net = pyo.Objective(expr=m.total_profit.expr - m.overtime_cost, sense=pyo.maximize)
return m
for name, scale in [("a normal week", 1.0), ("a December week, demand +30%", 1.3)]:
week = {**d, "cap": {p: c * scale for p, c in d["cap"].items()}}
m = with_overtime(week)
solver.solve(m)
used = ", ".join(f"{r} tier {k} {pyo.value(m.ot[r, k]):.2f} h" for r, k in m.T if pyo.value(m.ot[r, k]) > 1e-6)
print(f"{name}: net ${pyo.value(m.net):,.2f}, overtime ${pyo.value(m.overtime_cost):,.2f}: {used}")
resource tier hours cost_per_hour
baker_hours 1 40 45
baker_hours 2 40 70
packing_hours 1 20 60
packing_hours 2 20 95
a normal week: net $108,837.29, overtime $1,059.88: packing_hours tier 1 17.66 h
a December week, demand +30%: net $113,520.31, overtime $2,146.67: packing_hours tier 1 20.00 h, packing_hours tier 2 9.96 h
There is no rule saying "use tier 1 before tier 2", and none is needed: tier 1 is cheaper, so the LP fills it first. In a normal week the bakery buys 17.66 evening hours (the same answer as Day 13's packing overtime); in December, all 20 evening hours and 9.96 night hours. This works because the cost rises with each extra hour: a convex cost, minimized (or a concave profit, maximized).
29.2 Falling costs: volume discounts
In December the bakery needs 55 t of bread flour a week. flour_discounts lists incremental discounts: each band of tonnes is paid at its own price (Prairie Hard Red: the first 10 t at $520, the next 10 at $495, the next 10 at $470).
supplier_id from_tonnes to_tonnes price_per_tonne
FL-DUR 0 10 590
FL-DUR 10 30 540
FL-OSW 0 15 410
FL-OSW 15 30 395
FL-PHR 0 10 520
FL-PHR 10 20 495
FL-PHR 20 30 470
FL-QCO 0 8 640
Now the later bands are cheaper. Split the tonnes into bands as in 29.1, and the LP would fill the cheap $470 band first, without buying the first 20 t at full price. A falling cost per unit is concave: to force the bands to fill in order, each band gets a binary, if band is reached:
where is the tonnes bought in band and its width. Band can only be used once band is full. Create day29/flour_costs.py, which builds Day 5's blend with several price rules:
"""Day 29: buying a week's bread flour when prices fall with volume.
Import it: from flour_costs import load_flour, build_flour
"""
import pyomo.environ as pyo
NEED = 40 # tonnes of bread flour a week (Day 5)
def load_flour(con):
flour = con.sql("SELECT * FROM flour_suppliers ORDER BY supplier_id").df().set_index("supplier_id")
spec = con.sql("SELECT * FROM flour_spec").df().set_index("property")
bands = con.sql("SELECT * FROM flour_discounts ORDER BY supplier_id, from_tonnes").df()
offer = con.sql("SELECT * FROM flour_all_units_offer ORDER BY from_tonnes").df()
delivery = con.sql("SELECT * FROM flour_delivery").df().set_index("supplier_id")
return flour, spec, bands, offer, delivery
def build_flour(flour, spec, bands, prices="list", offer=None, delivery=None, need=NEED):
"""t[s] = tonnes from supplier s, blended to the spec (Day 5). prices:
"list" one price per tonne (Day 5)
"incremental" each band of tonnes at its own price; binaries make the bands fill in order
"piecewise" the same cost curve with Pyomo's Piecewise component
"bands_lp" the bands without binaries (wrong for discounts: see the planted bug)
offer: an all-units offer (one supplier): every tonne at the price of the band the total falls in.
delivery: whole trucks per supplier, each with a cost."""
m = pyo.ConcreteModel(name="flour_purchase")
m.S = pyo.Set(initialize=flour.index.tolist())
m.t = pyo.Var(m.S, bounds=lambda m, s: (0, flour.max_tonnes_per_week[s]))
m.need = pyo.Constraint(expr=sum(m.t[s] for s in m.S) == need)
m.spec = pyo.ConstraintList()
for prop, row in spec.iterrows():
blend = sum(flour.loc[s, prop] * m.t[s] for s in m.S)
if row.min_value == row.min_value: # not NaN
m.spec.add(blend >= row.min_value * need)
if row.max_value == row.max_value:
m.spec.add(blend <= row.max_value * need)
offered = set() if offer is None else set(offer.supplier_id)
cost = {}
if prices == "list":
for s in m.S:
cost[s] = flour.price_per_tonne[s] * m.t[s]
elif prices in ("incremental", "bands_lp"):
idx = [(r.supplier_id, k) for k, r in bands.iterrows()]
m.B = pyo.Set(initialize=idx, dimen=2)
width = {(s, k): bands.to_tonnes[k] - bands.from_tonnes[k] for s, k in idx}
m.y = pyo.Var(m.B, bounds=lambda m, s, k: (0, width[s, k])) # tonnes bought in band k
m.split = pyo.Constraint(m.S, rule=lambda m, s: m.t[s] == sum(m.y[b] for b in m.B if b[0] == s))
if prices == "incremental":
m.reach = pyo.Var(m.B, within=pyo.Binary) # reach[s, k] = 1 if band k is used
m.only_if_reached = pyo.Constraint(m.B, rule=lambda m, s, k: m.y[s, k] <= width[s, k] * m.reach[s, k])
order = [(b, nxt) for b, nxt in zip(idx, idx[1:]) if b[0] == nxt[0]]
m.fill_in_order = pyo.Constraint(range(len(order)), # band k+1 only once band k is full
rule=lambda m, i: m.y[order[i][0]] >= width[order[i][0]] * m.reach[order[i][1]])
for s in m.S:
cost[s] = sum(bands.price_per_tonne[k] * m.y[s, k] for (s2, k) in idx if s2 == s)
elif prices == "piecewise":
m.c = pyo.Var(m.S)
m.curve = pyo.Block(m.S)
for s in m.S:
b = bands[bands.supplier_id == s]
points = [0.0] + [float(x) for x in b.to_tonnes]
values = [0.0]
for _, r in b.iterrows():
values.append(values[-1] + r.price_per_tonne * (r.to_tonnes - r.from_tonnes))
m.curve[s].pw = pyo.Piecewise(m.c[s], m.t[s], pw_pts=points, f_rule=values, pw_constr_type="EQ", pw_repn="INC")
cost[s] = m.c[s]
for s in offered: # all-units offer: replaces that supplier's prices
o = offer.reset_index(drop=True)
m.tier = pyo.Var(o.index.tolist(), within=pyo.Binary)
m.in_tier = pyo.Var(o.index.tolist(), within=pyo.NonNegativeReals)
m.one_tier = pyo.Constraint(expr=sum(m.tier[k] for k in o.index) == 1)
m.tier_lo = pyo.Constraint(o.index.tolist(), rule=lambda m, k: m.in_tier[k] >= o.from_tonnes[k] * m.tier[k])
m.tier_hi = pyo.Constraint(o.index.tolist(), rule=lambda m, k: m.in_tier[k] <= o.to_tonnes[k] * m.tier[k])
m.tier_total = pyo.Constraint(expr=m.t[s] == sum(m.in_tier[k] for k in o.index))
cost[s] = sum(o.price_per_tonne[k] * m.in_tier[k] for k in o.index)
m.flour_cost = pyo.Expression(expr=sum(cost[s] for s in m.S))
if delivery is not None:
m.trucks = pyo.Var(m.S, within=pyo.NonNegativeIntegers)
m.full = pyo.Constraint(m.S, rule=lambda m, s: m.t[s] <= delivery.tonnes_per_truck[s] * m.trucks[s])
m.delivery = pyo.Expression(expr=sum(delivery.cost_per_truck[s] * m.trucks[s] for s in m.S))
else:
m.delivery = pyo.Expression(expr=0)
m.cost = pyo.Objective(expr=m.flour_cost + m.delivery)
return m
def describe(m):
tonnes = ", ".join(f"{s} {pyo.value(m.t[s]):.2f} t" for s in m.S if pyo.value(m.t[s]) > 1e-6)
extra = f" + delivery ${pyo.value(m.delivery):,.2f}" if pyo.value(m.delivery) else ""
return f"${pyo.value(m.cost):,.2f} (flour ${pyo.value(m.flour_cost):,.2f}{extra}): {tonnes}"
# ---------- 29.2 Falling costs: incremental discounts ----------
flour, spec, bands, offer, delivery = load_flour(con)
NEED = 55 # tonnes a week in December
print(bands.to_string(index=False))
for prices in ("list", "incremental"):
f = build_flour(flour, spec, bands, prices=prices, need=NEED)
solver.solve(f)
print(f"{prices:<12}", describe(f))
list $25,931.82 (flour $25,931.82): FL-DUR 0.45 t, FL-OSW 24.55 t, FL-PHR 30.00 t
incremental $25,038.64 (flour $25,038.64): FL-DUR 0.45 t, FL-OSW 24.55 t, FL-PHR 30.00 t
With discounts the same tonnes cost $893 a week less ($25,038.64 instead of $25,931.82). The plan doesn't change: the flour spec, not the price, decides the blend here.
Decision it supports: how much to buy from each supplier when price depends on volume.
Other decisions you can support the same way: freight with rates by weight band · energy contracts with tiered tariffs · advertising bought in volume.
29.3 Pyomo's Piecewise
Pyomo builds these formulations for you from breakpoints: Piecewise(cost, tonnes, pw_pts=..., f_rule=...), with a choice of formulation (pw_repn). "INC" is the incremental formulation of 29.2; "SOS2" uses special ordered sets, which some solvers handle natively.
# ---------- 29.3 The same curve with Pyomo's Piecewise ----------
f = build_flour(flour, spec, bands, prices="piecewise", need=NEED)
solver.solve(f)
print(f"{'piecewise':<12}", describe(f))
piecewise $25,038.64 (flour $25,038.64): FL-DUR 0.45 t, FL-OSW 24.55 t, FL-PHR 30.00 t
Same answer. Write it by hand once to understand it; use Piecewise afterwards.
29.4 All-units discounts and delivery trucks
Ontario Soft White offers an all-units deal: the price of every tonne depends on the week's total, $392 a tonne from 15 t, $372 from 25 t. The cost jumps down at 15 t and 25 t: it is not even continuous. The model picks one tier with a binary, and the tonnes must fall inside it (tier, in_tier in flour_costs.py). Deliveries come in whole trucks (flour_delivery): a general integer per supplier, like Day 25's linehaul.
# ---------- 29.4 All-units discounts and delivery trucks ----------
print("--- Ontario Soft White's all-units offer")
print(offer.to_string(index=False))
print("--- delivery trucks")
print(delivery.to_string())
for name, kw in [("all-units offer", dict(offer=offer)), ("delivery trucks", dict(delivery=delivery)),
("offer and trucks", dict(offer=offer, delivery=delivery))]:
f = build_flour(flour, spec, bands, prices="incremental", need=NEED, **kw)
solver.solve(f)
print(f"{name:<17}", describe(f))
--- Ontario Soft White's all-units offer
supplier_id from_tonnes to_tonnes price_per_tonne
FL-OSW 0 15 410
FL-OSW 15 25 392
FL-OSW 25 30 372
--- delivery trucks
tonnes_per_truck cost_per_truck
supplier_id
FL-PHR 12 380
FL-OSW 12 220
FL-QCO 8 260
FL-DUR 12 450
all-units offer $24,450.00 (flour $24,450.00): FL-DUR 2.50 t, FL-OSW 25.00 t, FL-PHR 27.50 t
delivery trucks $27,035.00 (flour $25,195.00 + delivery $1,840.00): FL-OSW 24.00 t, FL-PHR 30.00 t, FL-QCO 1.00 t
offer and trucks $26,601.27 (flour $24,731.27 + delivery $1,870.00): FL-DUR 5.36 t, FL-OSW 25.64 t, FL-PHR 24.00 t
- The offer changes the plan: Ontario Soft White goes to exactly 25.00 t to reach the $372 tier, and durum makes up the protein. $24,450 a week, $589 less.
- Trucks change the plan too: 24 t of soft white (two full trucks) instead of 24.55, and 1 t from Quebec Organic instead of 0.45 t of durum: one Quebec truck ($260) costs less than one durum truck ($450).
- With both, the plan fills two Prairie trucks exactly (24.00 t) and puts 25.64 t on soft white.
Math corner (optional): when does a piecewise cost need binaries?
A function is convex if the segment between any two points of its graph lies on or above the graph: slopes rise. Minimizing a convex piecewise-linear cost is an LP, because the cheaper pieces are always used first (29.1). Concave costs (falling slopes: discounts, economies of scale) and discontinuous ones (all-units, fixed charges) make the feasible set non-convex, and linear programming can only describe convex sets. They need binaries (or SOS2 constraints), and the solver needs branch and bound. The same rule works for maximization with profits: concave profit is easy, convex profit isn't. Checking the direction of the slopes before modelling tells you whether a cost is an LP or a MIP.
The planted bug
day29/bug_discount_lp.py writes the discount bands without binaries: "the solver will fill them in order". Run it.
con = duckdb.connect("northbound.duckdb", read_only=True)
flour, spec, bands, offer, delivery = load_flour(con)
m = build_flour(flour, spec, bands, prices="bands_lp", need=55)
pyo.SolverFactory("highs").solve(m)
print("model says:", describe(m))
print("bands used:", {f"{s} {bands.from_tonnes[k]}-{bands.to_tonnes[k]} t": round(pyo.value(m.y[s, k]), 2)
for s, k in m.B if pyo.value(m.y[s, k]) > 1e-6})
check = build_flour(flour, spec, bands, prices="incremental", need=55) # what the same tonnes really cost
for s in check.S:
check.t[s].fix(pyo.value(m.t[s]))
pyo.SolverFactory("highs").solve(check)
print("the same tonnes at the supplier's real prices:", describe(check))
What happens, and why
model says: $24,897.73 (flour $24,897.73): FL-DUR 8.64 t, FL-OSW 26.36 t, FL-PHR 20.00 t
bands used: {'FL-DUR 10-30 t': 8.64, 'FL-OSW 0-15 t': 11.36, 'FL-OSW 15-30 t': 15.0, 'FL-PHR 10-20 t': 10.0, 'FL-PHR 20-30 t': 10.0}
the same tonnes at the supplier's real prices: $25,884.09 (flour $25,884.09): FL-DUR 8.64 t, FL-OSW 26.36 t, FL-PHR 20.00 t
The model claims $24,897.73, cheaper than the real best plan ($25,038.64). Look at the bands: 15 t of soft white at the $395 band and only 11.36 t at the $410 band; Prairie's $495 and $470 bands without its first, $520 band. The supplier would charge $25,884.09 for those tonnes: $845 a week more than the real best plan. Discounts are concave, and an LP fills cheap bands first. The model's cost is a fiction, and so is its plan. Check: the result is below a correctly priced plan, which can't happen.
Mini-project: should the bakery sign the offer?
The offer is for a year. Compare the weekly cost, with delivery trucks, with and without the offer, for needs of 40 t (a normal week) to 60 t (the busiest December week). How much does it save, and when does it change what the bakery buys?
Solution
"""Day 29 mini-project: should the bakery sign Ontario Soft White's all-units offer?
Weekly needs from 40 t (a normal week) to 60 t (the busiest December week), with delivery trucks.
Run from the repository root (after day06/load_tables.py): python day29/mini_project_offer.py
"""
import sys
import duckdb
import pandas as pd
import pyomo.environ as pyo
sys.path.insert(0, "day29")
from flour_costs import build_flour, load_flour
pd.set_option("display.width", 140)
con = duckdb.connect("northbound.duckdb", read_only=True)
flour, spec, bands, offer, delivery = load_flour(con)
rows = []
for need in (40, 45, 50, 55, 60):
out = [need]
for kw in ({}, {"offer": offer}):
m = build_flour(flour, spec, bands, prices="incremental", delivery=delivery, need=need, **kw)
pyo.SolverFactory("highs").solve(m)
out += [round(pyo.value(m.cost), 2), round(pyo.value(m.t["FL-OSW"]), 2)]
rows.append(out + [round(out[1] - out[3], 2)])
t = pd.DataFrame(rows, columns=["need_t", "cost_now", "osw_t_now", "cost_offer", "osw_t_offer", "saving"])
print(t.to_string(index=False))
need_t cost_now osw_t_now cost_offer osw_t_offer saving
40 19641.67 17.78 19363.33 17.78 278.34
45 22205.00 20.00 21920.00 20.00 285.00
50 24388.33 22.22 24096.67 22.22 291.66
55 27035.00 24.00 26601.27 25.64 433.73
60 29706.82 27.27 28854.55 27.27 852.27
- In a normal week (40 t), the offer saves $278: the same 17.78 t of soft white, at $392 instead of the incremental prices.
- The saving grows with volume, and at 55 t it changes the plan (25.64 t of soft white, to reach the $372 tier): $434. At 60 t: $852.
- An all-units offer can't cost more than the incremental prices here: in every band, the offer's price is at or below the incremental one. So the decision is whether the contract's other terms (exclusivity, minimum volumes) are worth about $280 to $850 a week.
Memo to purchasing: "Sign Ontario Soft White's offer if it carries no minimum volume: it saves $14,000 to $15,000 a year at normal volumes, more in December. The saving rises in weeks above 50 t, when buying 25 t from them reaches the lowest tier."
Commit
git add .
git commit -m "Day 29: piecewise-linear costs and discounts"
git push
Day 29 checklist
- I model rising piecewise costs with one variable per piece, without binaries.
- I model falling (incremental) discounts with binaries that fill bands in order.
- I can model an all-units discount and whole-truck delivery costs.
- I can use Pyomo's
Piecewise. - I check the slopes (convex or concave) before choosing LP or MIP.
- I know a cost below a correctly priced plan is a sign of a broken model.