3.1 Plans as points, constraints as lines
Next week the croissant line is down for maintenance, so the bakery makes only sourdough () and whole-wheat (). We start without demand caps, to see the shape clearly:
Each plan is a point. Each constraint, with replaced by , is a straight line; the plans that satisfy it lie on one side. The oven line runs from to : all oven hours on whole-wheat, or all on sourdough.
The plans that satisfy every constraint form the feasible region. Because every constraint is a straight line, the region is a polygon with straight sides and no dents (it is convex).
Create day03/geometry.py. We write each constraint as three numbers meaning ; the non-negativity rules become and .
import itertools
import os
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import linprog
os.makedirs("figures", exist_ok=True)
# Every constraint written as a_S * S + a_W * W <= b
BASE = {
"oven: 2S + W <= 100": (2, 1, 100),
"bakers: S + W <= 80": (1, 1, 80),
"starter: S <= 40": (1, 0, 40),
"S >= 0": (-1, 0, 0),
"W >= 0": (0, -1, 0),
}
3.2 Corner points and iso-profit lines
A corner (vertex) is where two constraint lines cross and every other constraint still holds. We find them all: intersect every pair of lines, keep the points that are feasible.
def corners(cons):
"""Intersect every pair of constraint lines; keep the points that satisfy all constraints."""
pts = []
for (n1, (a1, b1, c1)), (n2, (a2, b2, c2)) in itertools.combinations(cons.items(), 2):
M = np.array([[a1, b1], [a2, b2]], dtype=float)
if abs(np.linalg.det(M)) < 1e-12:
continue # parallel lines never meet
s, w = np.linalg.solve(M, [c1, c2])
if all(a * s + b * w <= c + 1e-9 for a, b, c in cons.values()):
pts.append((round(s, 6) + 0.0, round(w, 6) + 0.0))
return sorted(set(pts))
(+ 0.0 turns a "negative zero" −0.0 into 0.0, so the same corner isn't kept twice.)
The drawing function plots each line, shades the region, labels every corner with its profit, and draws a dashed iso-profit line through the best corner: all the plans that earn the same profit.
def order_polygon(pts):
"""Sort corner points around their centre so they draw as a polygon."""
cx, cy = np.mean(pts, axis=0)
return sorted(pts, key=lambda p: np.arctan2(p[1] - cy, p[0] - cx))
def draw(ax, cons, profit, title, lim=(0, 100), unbounded=False):
pts = corners(cons)
xs = np.linspace(*lim, 200)
lines = [(n, abc) for n, abc in cons.items() if not n.endswith(">= 0")]
for i, (name, (a, b, c)) in enumerate(lines):
color = f"C{i}"
if b == 0:
ax.axvline(c / a, lw=1.2, color=color, label=name)
else:
ax.plot(xs, (c - a * xs) / b, lw=1.2, color=color, label=name)
if unbounded:
# the region runs off the top of the chart: profit can grow forever
ax.fill([0, 40, 40, 0], [0, 0, lim[1], lim[1]], alpha=0.18, color="tab:green", label="feasible region (never ends)")
ax.annotate("", xy=(30, 98), xytext=(30, 60), arrowprops=dict(arrowstyle="->", lw=2))
ax.text(31, 75, "more W is always\nallowed and earns more", fontsize=8)
pts = []
elif not pts:
ax.text(5, 5, "no point satisfies every constraint", fontsize=9)
if len(pts) >= 3:
poly = order_polygon(pts)
ax.fill(*zip(*poly), alpha=0.18, color="tab:green", label="feasible region")
best = None
for s, w in pts:
v = profit[0] * s + profit[1] * w
ax.plot(s, w, "ko", ms=4)
ax.annotate(f"({s:g}, {w:g})\n${v:,.0f}", (s, w), textcoords="offset points", xytext=(5, 5), fontsize=8)
if best is None or v > best[2]:
best = (s, w, v)
if best:
# iso-profit line through the best corner
ax.plot(xs, (best[2] - profit[0] * xs) / profit[1], "k--", lw=1, label=f"profit = ${best[2]:,.0f}")
ax.plot(best[0], best[1], "r*", ms=14)
ax.set_xlim(*lim)
ax.set_ylim(*lim)
ax.set_xlabel("S: sourdough batches")
ax.set_ylabel("W: whole-wheat batches")
ax.set_title(title, fontsize=10)
ax.legend(fontsize=7, loc="upper right")
return pts, best
profit = (300, 200)
fig, ax = plt.subplots(figsize=(6, 6))
pts, best = draw(ax, BASE, profit, "Sourdough and whole-wheat: profit 300 S + 200 W")
fig.tight_layout()
fig.savefig("figures/day03_feasible_region.png", dpi=120)
print("Corner points and their profit:")
for s, w in pts:
print(f" S = {s:>5g}, W = {w:>5g}: ${profit[0] * s + profit[1] * w:>8,.0f}")
print(f"Best corner: S = {best[0]:g}, W = {best[1]:g}, profit ${best[2]:,.0f}")
res = linprog([-300, -200], A_ub=[[2, 1], [1, 1], [1, 0]], b_ub=[100, 80, 40], method="highs")
print(f"linprog agrees: S = {res.x[0]:g}, W = {res.x[1]:g}, profit ${-res.fun:,.0f}")
Corner points and their profit:
S = 0, W = 0: $ 0
S = 0, W = 80: $ 16,000
S = 20, W = 60: $ 18,000
S = 40, W = 0: $ 12,000
S = 40, W = 20: $ 16,000
Best corner: S = 20, W = 60, profit $18,000
linprog agrees: S = 20, W = 60, profit $18,000

Read the picture:
- The green polygon holds every plan the bakery can bake. It has 5 corners.
- The dashed line is every plan earning $18,000. Lines for other profits are parallel to it: lower profits sit closer to the origin, higher ones further out.
- Slide the dashed line outward as far as it goes while still touching the region. It last touches at (20, 60), where the oven and baker lines cross.
That is why the best plan of a linear program is always at a corner (or along an edge between two equally good corners): the iso-profit line leaves the region last at a corner. The simplex method, the classic LP algorithm, walks from corner to corner along the edges, improving profit at each step, and stops when no neighbouring corner is better.
Decision it supports: seeing, not just being told, why the best plan uses the oven and bakers fully and leaves starter spare.
Other decisions you can support the same way: explaining a two-product trade-off to a manager with one chart · checking a solver's answer on a small version of a big model.
Math corner (optional): why a corner?
Profit is linear, so along any straight segment between two plans it changes at a constant rate. Take any plan inside the region and move in the direction that raises profit: profit keeps rising until you hit a constraint line. Then move along that line in the direction that raises profit, until you hit another. In two dimensions you are now at a corner. If profit is exactly flat along the line you are on, every point of that edge is equally good, including both its end corners. So some corner is always among the best plans, provided the region is not empty and profit cannot grow forever. Those two exceptions are 3.4.
3.3 Adding the demand caps; how far can a price move?
Add the Day 1 demand caps, and :
DEMAND = dict(BASE)
DEMAND["demand: S <= 35"] = (1, 0, 35)
DEMAND["demand: W <= 45"] = (0, 1, 45)
fig, ax = plt.subplots(figsize=(6, 6))
pts, best = draw(ax, DEMAND, profit, "With demand caps S <= 35, W <= 45")
fig.tight_layout()
fig.savefig("figures/day03_with_demand.png", dpi=120)
print(f"With demand caps the best corner is S = {best[0]:g}, W = {best[1]:g}, profit ${best[2]:,.0f}")
With demand caps the best corner is S = 27.5, W = 45, profit $17,250

The whole-wheat cap cuts off the old corner (20, 60). The new best corner is where the oven line meets : , so . The bakers now have 7.5 hours spare. Note the half batch: linear programs happily return fractions. Rounding down to 27 costs $150; Module 3 handles whole batches properly.
How far can a price move before the plan changes?
Go back to the model without demand caps. The best corner (20, 60) stays best as long as the dashed iso-profit line is steeper than the baker line and flatter than the oven line. The baker line has slope ratio 1 : 1 and the oven line 2 : 1, so (20, 60) stays best while sourdough profit ÷ whole-wheat profit is between 1 and 2. With whole-wheat at $200, that is sourdough between $200 and $400.
for p_s in (150, 199, 201, 300, 399, 401, 450):
r = linprog([-p_s, -200], A_ub=[[2, 1], [1, 1], [1, 0]], b_ub=[100, 80, 40], method="highs")
print(f" ${p_s}: S = {r.x[0]:g}, W = {r.x[1]:g}, profit ${-r.fun:,.0f}")
$150: S = 0, W = 80, profit $16,000
$199: S = 0, W = 80, profit $16,000
$201: S = 20, W = 60, profit $16,020
$300: S = 20, W = 60, profit $18,000
$399: S = 20, W = 60, profit $19,980
$401: S = 40, W = 20, profit $20,040
$450: S = 40, W = 20, profit $22,000
Between $201 and $399 the plan does not change, only its profit. Below $200 the bakery should stop sourdough altogether; above $400 it should bake sourdough up to the starter limit. Planners love this: a price can move a long way before the plan needs to change. Module 2 gets these ranges straight from the solver (Day 12).
Try it 3.1
Keep sourdough at $300. For what range of whole-wheat profit per batch does (20, 60) stay the best plan? Check three values with linprog.
Solution
We need 1 ≤ 300 ÷ ≤ 2, so between $150 and $300.
for p_w in (149, 151, 200, 299, 301):
r = linprog([-300, -p_w], A_ub=[[2, 1], [1, 1], [1, 0]], b_ub=[100, 80, 40], method="highs")
print(p_w, r.x, -r.fun)
149 [40. 20.] 14980.0
151 [20. 60.] 15060.0
200 [20. 60.] 18000.0
299 [20. 60.] 23940.0
301 [ 0. 80.] 24080.0
3.4 Four special cases
A model can fail to have one clean best corner in four ways. Each has a picture and a solver message you must recognise.
cases = {
"Infeasible: contract needs W >= 85": ({**BASE, "contract: W >= 85": (0, -1, -85)}, (300, 200)),
"Unbounded: oven and bakers forgotten": ({k: v for k, v in BASE.items() if k.startswith(("starter", "S >=", "W >="))}, (300, 200)),
"Many optima: sourdough profit $400": (BASE, (400, 200)),
"Degenerate: three lines meet at one corner": ({**BASE, "demand: W <= 60": (0, 1, 60)}, (300, 200)),
}
fig, axes = plt.subplots(2, 2, figsize=(11, 11))
for ax, (title, (cons, prof)) in zip(axes.ravel(), cases.items()):
draw(ax, cons, prof, title, unbounded=title.startswith("Unbounded"))
A = [[a, b] for a, b, c in cons.values()]
b = [c for a, b, c in cons.values()]
r = linprog([-prof[0], -prof[1]], A_ub=A, b_ub=b, bounds=[(None, None)] * 2, method="highs")
answer = f"S = {r.x[0]:g}, W = {r.x[1]:g}, profit ${-r.fun:,.0f}" if r.status == 0 else ""
print(f"{title}\n linprog status {r.status}: {r.message} {answer}")
fig.tight_layout()
fig.savefig("figures/day03_special_cases.png", dpi=110)
Infeasible: contract needs W >= 85
linprog status 2: The problem is infeasible. (HiGHS Status 8: model_status is Infeasible; primal_status is None)
Unbounded: oven and bakers forgotten
linprog status 3: The problem is unbounded. (HiGHS Status 10: model_status is Unbounded; primal_status is Feasible)
Many optima: sourdough profit $400
linprog status 0: Optimization terminated successfully. (HiGHS Status 7: Optimal) S = 40, W = 20, profit $20,000
Degenerate: three lines meet at one corner
linprog status 0: Optimization terminated successfully. (HiGHS Status 7: Optimal) S = 20, W = 60, profit $18,000

The non-negativity rules are in the constraint list here, so we pass bounds=[(None, None)] * 2 to stop linprog adding its own.
| Case | What you see | What it means in the business | What to do |
|---|---|---|---|
| Infeasible | No green region: no plan satisfies every rule | A sales contract promised 85 whole-wheat batches; the bakers can make at most 80 | Find the conflicting rules (Day 7); relax one (overtime) or renegotiate |
| Unbounded | The region runs off the chart; profit grows forever | Almost always a missing constraint, here the oven and bakers | Look for the forgotten limit; real businesses are never unbounded |
| Many optima | The iso-profit line lies along an edge | At $400, sourdough and whole-wheat earn the same per oven hour, so every plan from (20, 60) to (40, 20) earns $20,000 | The solver returns one; pick among them on a second goal (Module 7) |
| Degenerate | Three lines pass through the best corner | Whole-wheat cap of 60 is exactly met by the plan that fills oven and bakers | Harmless for the answer, but shadow prices become ambiguous (Day 11) |
Decision it supports: telling a manager why there is no plan, or several, instead of reporting a solver error.
Other decisions you can support the same way: spotting an impossible promise in a service-level agreement · finding a missing rule in a model a colleague wrote.
Try it 3.2
Yesterday's three-product answer baked 10 croissants. Fix croissants at 10: they use 15 oven hours and 15 baker hours, leaving and . Add the demand caps , . Draw it with draw and solve with linprog. What special case do you see?
Solution
FIXED = {
"oven: 2S + W <= 85": (2, 1, 85),
"bakers: S + W <= 65": (1, 1, 65),
"demand: S <= 35": (1, 0, 35),
"demand: W <= 45": (0, 1, 45),
"S >= 0": (-1, 0, 0),
"W >= 0": (0, -1, 0),
}
fig, ax = plt.subplots(figsize=(6, 6))
draw(ax, FIXED, (300, 200), "Croissants fixed at 10")
fig.savefig("figures/day03_try_fixed_croissants.png", dpi=120)
r = linprog([-300, -200], A_ub=[[2, 1], [1, 1]], b_ub=[85, 65], bounds=[(0, 35), (0, 45)], method="highs")
print(r.x, -r.fun)
[20. 45.] 15000.0
The best corner (20, 45) lies on three lines at once: oven, bakers and the whole-wheat cap. In two dimensions a corner needs only two, so it is degenerate. Add the croissants' $2,500 and you get yesterday's $17,500.
Yesterday's three-product corner had the same three tight constraints, but with three variables a corner needs three, so it was not degenerate. Fixing croissants removed a variable without removing a constraint.
Mini-project: a December week with overtime
In December, demand for whole-wheat rises to 60 batches (sourdough stays capped at 35, croissants are still down for maintenance). The bakery can run the ovens 20 extra hours, for 120 in total, at a cost of $60 per extra oven hour. Bakers stay at 80 hours, starter at 40.
- Draw the region with 100 oven hours and with 120, and find the best corner of each.
- Is the overtime worth it? How many hours should the bakery book?
- Which constraints bind with overtime? What would you look at next?
Solution
for oven_h in (100, 120):
r = linprog([-300, -200], A_ub=[[2, 1], [1, 1], [1, 0]], b_ub=[oven_h, 80, 40],
bounds=[(0, 35), (0, 60)], method="highs")
print(oven_h, r.x, -r.fun)
100 [20. 60.] 18000.0
120 [35. 45.] 19500.0
1. With 100 oven hours the best corner is (20, 60), $18,000: oven and bakers full, whole-wheat at its new cap of 60 (a degenerate corner, like the fourth special case). With 120 hours it moves to (35, 45), $19,500: sourdough at its cap, bakers full.
2. All 20 hours add $1,500 for 20 × $60 = $1,200: worth it, by $300 a week. But look closer. Each extra oven hour lets the bakery swap one whole-wheat batch for one sourdough batch, worth $100, until sourdough reaches its cap of 35 at 115 hours:
for oven_h in (105, 114, 115, 116):
r = linprog([-300, -200], A_ub=[[2, 1], [1, 1], [1, 0]], b_ub=[oven_h, 80, 40],
bounds=[(0, 35), (0, 60)], method="highs")
print(oven_h, r.x, -r.fun)
105 [25. 55.] 18500.0
114 [34. 46.] 19400.0
115 [35. 45.] 19500.0
116 [35. 45.] 19500.0
The last 5 overtime hours earn nothing. Book 15 hours, not 20: +$1,500 − $900 = +$600 a week. 3. At (35, 45) the bakers and the sourdough cap bind, and oven hours beyond 115 go unused. The next things to price are an extra baker hour, or a promotion that lifts sourdough demand.
Commit
git add .
git commit -m "Day 3: LP geometry, corners, price ranges, special cases"
git push
Day 3 checklist
- I can draw the feasible region of a two-variable LP and list its corners.
- I can explain with the iso-profit line why the optimum is at a corner.
- I found the price range ($200 to $400 for sourdough) over which the best plan does not change.
- I can recognise infeasible, unbounded, many-optima and degenerate models from a picture and from the solver status.
- I know that an "Optimal" status means the model was solved, not that the model is right.
- I priced overtime with the model before recommending it.