Prescriptive Analytics & Decision Intelligence
Overview / Module 1 / Day 2
Module 1 · Decision Modelling and Linear Programming · Day 2 of 80

Spreadsheet First: The Product Mix

Yesterday brute force found the best bake plan. Today you build the same model three ways: as a spreadsheet, by hand with algebra, and with a real solver. By the end you know what a solver does, and how to catch it when you have told it the wrong thing.

▶
Video for Day 2 coming soon

In this lesson

Today's 5-hour plan

LessonProjectBreakCommit
0:00–0:45
2.1 The model as a spreadsheet
0:45–1:45
2.2 Trial and error, and a greedy rule that fails
1:45–2:00
Break
2:00–2:45
2.3 By hand: which constraints are tight?
2:45–3:45
2.4 Your first solver, and a planted bug
3:45–4:00
Break
4:00–4:45
Mini-project: should the bakery add a rye loaf?
4:45–5:00
Commit with Git + checklist

2.1 The model as a spreadsheet

Planners have optimized with spreadsheets for decades. A spreadsheet model has three kinds of cells:

  • Decision cells: the numbers you change (batches of each product).
  • Formula cells: what follows from the decisions (hours used, profit).
  • Limit cells: what the formulas must not exceed (capacities, demand caps).

If you have Excel on Windows, you can build this in a sheet: decisions in B2:D2, the recipe in B5:D7, hours used in E5 as =SUMPRODUCT(B5:D5,$B$2:$D$2), and profit as =SUMPRODUCT(B3:D3,B2:D2). Excel's Solver add-in (Data → Solver) then changes the decision cells to maximize profit subject to E5:E7 <= F5:F7.

We build the same spreadsheet in pandas, so that it lives in Git and reads the course data. Create day02/product_mix.py:

import numpy as np
import pandas as pd
from scipy.optimize import linprog

products = pd.read_csv("data/bakery_products.csv").set_index("sku")
products["profit_per_batch"] = products.units_per_batch * (products.transfer_price - products.ingredient_cost)
recipe = pd.read_csv("data/bakery_recipe.csv").pivot(index="resource", columns="sku", values="use_per_batch").fillna(0)
capacity = pd.read_csv("data/bakery_resources.csv").set_index("resource")["weekly_capacity"]
demand = pd.read_csv("data/forecast_next_week.csv").set_index("sku")["demand_cap_batches"]

skus = list(products.index)          # BK-SD, BK-WW, BK-CR
recipe = recipe[skus]
print("Recipe (use per batch):")
print(recipe)
Recipe (use per batch):
sku                BK-SD  BK-WW  BK-CR
resource                              
baker_hours          1.0    1.0    1.5
oven_hours           2.0    1.0    1.5
sourdough_starter    1.0    0.0    0.0

pivot turns the long recipe file into a resource × product table. fillna(0) says whole-wheat and croissants use no starter. This table is the left-hand side of the constraints you wrote yesterday.

Now the spreadsheet itself, as a function:

def evaluate(plan):
    """The spreadsheet: decision cells in, used / slack / profit out."""
    x = pd.Series(plan, dtype=float)[skus]
    used = recipe @ x
    sheet = pd.DataFrame({"used": used, "capacity": capacity[used.index]})
    sheet["slack"] = sheet.capacity - sheet.used
    over_demand = (x - demand[skus]).clip(lower=0)
    feasible = bool((sheet.slack >= -1e-9).all() and (over_demand <= 1e-9).all() and (x >= 0).all())
    profit = float(products.profit_per_batch[skus] @ x)
    return sheet, profit, feasible


plan = {"BK-SD": 25, "BK-WW": 35, "BK-CR": 10}
sheet, profit, ok = evaluate(plan)
print("Current plan:", plan)
print(sheet)
print(f"profit ${profit:,.0f}, feasible: {ok}")
Current plan: {'BK-SD': 25, 'BK-WW': 35, 'BK-CR': 10}
                    used  capacity  slack
resource                                 
baker_hours         75.0        80    5.0
oven_hours         100.0       100    0.0
sourdough_starter   25.0        40   15.0
profit $17,000, feasible: True

recipe @ x is matrix multiplication: for every resource, the sum of use per batch × batches. It is SUMPRODUCT for all rows at once.

Slack is capacity left over. A constraint with zero slack is binding (or tight): it is what stops us earning more. In the current plan only the oven binds.

The 1e-9 tolerances matter: computers store 0.1 + 0.2 as 0.30000000000000004, so "exactly full" can look a hair over.

Decision it supports: checking any plan a manager proposes, in seconds, before anyone bakes it.

Other decisions you can support the same way: checking a staff roster against hour limits · checking a truck load against weight and volume.

Try it 2.1

A manager proposes 20 sourdough, 40 whole-wheat and 15 croissant. Is it feasible? Which constraint fails, and by how much?

Solution
sheet, profit, ok = evaluate({"BK-SD": 20, "BK-WW": 40, "BK-CR": 15})
print(sheet); print(profit, ok)

Oven hours used = 2 × 20 + 40 + 1.5 × 15 = 102.5, slack −2.5, so it is infeasible: 2.5 oven hours over. Baker hours: 20 + 40 + 22.5 = 82.5, also 2.5 over. Profit would be $17,750, but the plan can't be baked.

2.2 Trial and error, and a greedy rule that fails

Try a few plans:

for plan in [{"BK-SD": 30, "BK-WW": 30, "BK-CR": 10},
             {"BK-SD": 20, "BK-WW": 45, "BK-CR": 10},
             {"BK-SD": 35, "BK-WW": 30, "BK-CR": 0}]:
    sheet, profit, ok = evaluate(plan)
    print(f"{plan}  profit ${profit:,.0f}  feasible {ok}  oven slack {sheet.slack['oven_hours']:.1f}  baker slack {sheet.slack['baker_hours']:.1f}")
{'BK-SD': 30, 'BK-WW': 30, 'BK-CR': 10}  profit $17,500  feasible False  oven slack -5.0  baker slack 5.0
{'BK-SD': 20, 'BK-WW': 45, 'BK-CR': 10}  profit $17,500  feasible True  oven slack 0.0  baker slack 0.0
{'BK-SD': 35, 'BK-WW': 30, 'BK-CR': 0}  profit $16,500  feasible True  oven slack 0.0  baker slack 15.0

The third plan is the "make the most profitable product first" rule: sourdough earns most per batch ($300), so make all 35, then fill with whole-wheat. It earns $16,500, less than the current plan.

A smarter-sounding rule: the oven is the bottleneck, so rank products by profit per oven hour and fill the oven in that order.

per_oven_hour = (products.profit_per_batch / recipe.loc["oven_hours"]).sort_values(ascending=False)
print("Profit per oven hour:")
print(per_oven_hour)
x = {s: 0.0 for s in skus}
for sku in per_oven_hour.index:
    # largest amount of this product that still fits every constraint
    room = [demand[sku]]
    used = recipe @ pd.Series(x)[skus]
    for r in recipe.index:
        if recipe.loc[r, sku] > 0:
            room.append((capacity[r] - used[r]) / recipe.loc[r, sku])
    x[sku] = max(0.0, min(room))
sheet, profit, ok = evaluate(x)
print("Greedy plan:", {k: round(float(v), 2) for k, v in x.items()}, f"profit ${profit:,.0f}")
Profit per oven hour:
sku
BK-WW    200.000000
BK-CR    166.666667
BK-SD    150.000000
dtype: float64
Greedy plan: {'BK-SD': 0.0, 'BK-WW': 45.0, 'BK-CR': 23.33} profit $14,833

$14,833: worse still. The rule looks only at the oven, but croissants use 1.5 baker hours each and run the bakers out first (45 + 1.5 × 23.33 = 80). With two or more binding constraints, no single ranking is right. Products compete for several resources at once, and the best mix balances them. That balancing is exactly what a solver does.

Try it 2.2

Rank by profit per baker hour instead and fill in that order. What profit do you get?

Solution

Per baker hour: sourdough $300, whole-wheat $200, croissant $166.67. Fill sourdough to its cap of 35 (70 oven hours, 35 baker hours). Whole-wheat then has room for 30 more oven hours, so 30 batches. The oven is now full: no croissants. Profit 300 × 35 + 200 × 30 = $16,500, the same plan as "most profitable first". Neither ranking finds $17,500.

2.3 By hand: which constraints are tight?

Brute force said the best plan uses the oven and the bakers fully, and whole-wheat sits at its demand cap of 45. If we guess those three constraints are binding, they become three equations in three unknowns:

1.5C+2S+W=100(oven full)1.5C+S+W=80(bakers full)W=45(whole-wheat at its cap)\begin{aligned} 1.5C + 2S + W &= 100 && \text{(oven full)}\\ 1.5C + S + W &= 80 && \text{(bakers full)}\\ W &= 45 && \text{(whole-wheat at its cap)} \end{aligned}
A = np.array([[1.5, 2, 1], [1.5, 1, 1], [0, 0, 1]])
b = np.array([100, 80, 45])
cr, sd, ww = np.linalg.solve(A, b)
print(f"By hand: croissant {cr:g}, sourdough {sd:g}, whole-wheat {ww:g}")
sheet, profit, ok = evaluate({"BK-CR": cr, "BK-SD": sd, "BK-WW": ww})
print(f"profit ${profit:,.0f}, feasible {ok}")
By hand: croissant 10, sourdough 20, whole-wheat 45
profit $17,500, feasible True

Subtracting the second equation from the first gives S=20S = 20 straight away: each sourdough batch uses one more oven hour than baker hour, and the oven has 20 more hours than the bakers.

This is the key idea behind linear programming: the best plan sits where some set of constraints are all tight at once. A solver's job is to find the right set without guessing.

Try it 2.3

Guess a different set: oven full, bakers full, and croissants at their cap of 31. Solve it. Is the result feasible? Is it better?

Solution
A = np.array([[1.5, 2, 1], [1.5, 1, 1], [1, 0, 0]])
print(np.linalg.solve(A, [100, 80, 31]))
[31.  20.  13.5]

Croissant 31, sourdough 20, whole-wheat 13.5. Every constraint holds, so it is a feasible corner, but profit is 250 × 31 + 300 × 20 + 200 × 13.5 = $16,450. Feasible is not the same as best. (And a guess of "oven full, sourdough at 35, whole-wheat at 45" gives croissant = −10: a corner outside the feasible plans.)

2.4 Your first solver

scipy.optimize.linprog solves linear programs. With method="highs" (the default) it calls HiGHS, the same open-source solver we use through Pyomo from Day 4. It expects the problem in one fixed shape:

min⁡x  c⊤xs.t.Aub x≤bub,lower≤x≤upper\min_x\; c^\top x \quad \text{s.t.}\quad A_{ub}\,x \le b_{ub},\quad \text{lower} \le x \le \text{upper}

It minimizes. To maximize profit, minimize minus profit.

c = -products.profit_per_batch[skus].to_numpy()      # linprog minimises, so flip the sign
A_ub = recipe.to_numpy()
b_ub = capacity[recipe.index].to_numpy()
bounds = [(0, demand[s]) for s in skus]
res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds, method="highs")
print("linprog status:", res.message)
print("plan:", {s: round(float(v), 4) for s, v in zip(skus, res.x)})
print(f"profit ${-res.fun:,.2f}")
print("slack by resource:", {r: round(float(v), 4) for r, v in zip(recipe.index, res.slack)})
linprog status: Optimization terminated successfully. (HiGHS Status 7: Optimal)
plan: {'BK-SD': 20.0, 'BK-WW': 45.0, 'BK-CR': 10.0}
profit $17,500.00
slack by resource: {'baker_hours': 0.0, 'oven_hours': 0.0, 'sourdough_starter': 20.0}

Same answer as brute force and as the algebra, without trying 52,992 plans or guessing. The demand caps went in as bounds (upper limits on single variables), which solvers handle more cheaply than full constraints.

Three checks every time you run a solver:

  1. Status: "Optimal". Anything else (infeasible, unbounded, time limit) means the numbers are not an answer.
  2. Sign of the objective: res.fun is −17,500 because we minimized minus profit.
  3. Sense check: recompute profit and slack yourself (our evaluate function) and compare.

Decision it supports: the weekly bake plan, recomputed in milliseconds whenever the forecast or capacity changes.

Other decisions you can support the same way: a media mix across channels with budget and audience limits · a feed or fertilizer blend at least cost.

Try it 2.4: what is one more hour worth?

Re-solve with 110 oven hours, and separately with 81 baker hours. How much does profit change per extra hour?

Solution
for oven_h, baker_h in [(110, 80), (100, 81)]:
    r = linprog(c, A_ub=A_ub, b_ub=[baker_h, oven_h, 40], bounds=bounds, method="highs")
    print(oven_h, baker_h, r.x.round(4), -r.fun)

(The order of b_ub follows recipe.index: baker, oven, starter.)

110 80 [30.     45.      3.3333] 18833.333333333332
100 81 [19.     45.     11.3333] 17533.333333333332

Ten more oven hours add $1,333.33: $133.33 per oven hour. One more baker hour adds $33.33. If an oven hour of overtime costs less than $133, it pays; a baker hour pays only if it costs under $33. These numbers are shadow prices, and the solver can report them without re-solving. That is Day 11.

The planted bug

Open day02/bug_sign.py. Before running it, read it and predict what it will print.

from scipy.optimize import linprog

profit = [300, 200, 250]                 # sourdough, whole-wheat, croissant
A_ub = [[2.0, 1.0, 1.5],                 # oven hours
        [1.0, 1.0, 1.5],                 # baker hours
        [1.0, 0.0, 0.0]]                 # sourdough starter
b_ub = [100, 80, 40]
bounds = [(0, 35), (0, 45), (0, 31)]

res = linprog(profit, A_ub=A_ub, b_ub=b_ub, bounds=bounds, method="highs")
print(res.message)
print("plan:", [round(float(v), 4) for v in res.x], "objective:", res.fun)
What happens, and the fix
Optimization terminated successfully. (HiGHS Status 7: Optimal)
plan: [0.0, 0.0, 0.0] objective: 0.0

The solver reports success and recommends baking nothing. It did exactly what it was told: minimize profit, and the least profit is zero. The fix is linprog([-p for p in profit], ...), then report -res.fun.

The lesson: an "Optimal" status means the solver solved your model, not that your model is right. Always run the sense check.

Mini-project: should the bakery add a rye loaf?

Product development proposes a rye loaf: 100 loaves per batch, transfer price $4.00, ingredients $1.60 per loaf, 1.5 oven hours and 1 baker hour per batch, and half a batch of sourdough starter. Marketing expects to sell at most 15 batches a week.

  1. Compute the rye profit per batch. Is it more or less than whole-wheat?
  2. Solve the four-product model with linprog in day02/mini_project_rye.py.
  3. How much does rye add to weekly profit? What does the bakery make less of?
  4. Write two sentences for the planner: add rye or not?
Solution
from scipy.optimize import linprog

skus = ["BK-SD", "BK-WW", "BK-CR", "BK-RY"]
profit = [300, 200, 250, 100 * (4.00 - 1.60)]          # rye: 100 loaves, $4.00 price, $1.60 ingredients
oven = [2.0, 1.0, 1.5, 1.5]
baker = [1.0, 1.0, 1.5, 1.0]
starter = [1.0, 0.0, 0.0, 0.5]                          # rye uses half a batch of starter
demand = [35, 45, 31, 15]

res = linprog([-p for p in profit], A_ub=[oven, baker, starter], b_ub=[100, 80, 40],
              bounds=[(0, d) for d in demand], method="highs")
print(res.message)
for s, x in zip(skus, res.x):
    print(f"  {s}: {x:g} batches")
print(f"profit ${-res.fun:,.2f}  (was $17,500.00 without rye)")
print("slack oven, baker, starter:", [round(float(v), 4) for v in res.slack])
Optimization terminated successfully. (HiGHS Status 7: Optimal)
  BK-SD: 12.5 batches
  BK-WW: 45 batches
  BK-CR: 5 batches
  BK-RY: 15 batches
profit $17,600.00  (was $17,500.00 without rye)
slack oven, baker, starter: [0.0, 0.0, 20.0]
  1. Rye earns 100 × ($4.00 − $1.60) = $240 a batch, more than whole-wheat ($200).
  2. The solver bakes all 15 rye batches, cutting sourdough from 20 to 12.5 and croissants from 10 to 5.
  3. Profit rises by only $100 a week. Rye's $240 is mostly paid for with oven and baker hours taken from sourdough and croissants.
  4. Memo: "Rye adds about $100 a week ($5,200 a year) with current ovens and bakers, because it takes capacity from sourdough and croissants. Add it only if the launch costs less than that, or together with extra oven hours, which are worth $133 each."

Notice the plan has half a batch of sourdough. Real batches are whole; Module 3 adds integer variables.

Commit

git add .
git commit -m "Day 2: spreadsheet model, greedy rules, by-hand solution, linprog"
git push

Day 2 checklist

  • I can build a plan checker that reports used, capacity and slack for each resource.
  • I can explain why ranking products by profit per batch, or per hour of one resource, misses the best plan.
  • I can find a corner by guessing which constraints are binding and solving the equations.
  • I solved the product mix with linprog and got $17,500.
  • I always check status, objective sign and a recomputed profit.
  • I know what an extra oven hour ($133.33) and an extra baker hour ($33.33) are worth.