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

Mini-project: Blending and Meal Kits

Today is a project day. In the morning you blend flour from four suppliers to a quality specification at least cost. In the afternoon you design a Northbound Fresh meal kit: first the cheapest kit that meets the nutrition rules, then one that customers would actually buy. Both are classic blending problems: choose how much of each ingredient goes into a mix so that the mix's properties meet a spec.

▶
Video for Day 5 coming soon

In this lesson

Today's 5-hour plan

LessonProjectBreakCommit
0:00–0:45
5.1 Blending flour: shares of one tonne
0:45–1:45
5.2 A week of flour, with supplier limits
1:45–2:00
Break
2:00–2:45
5.3 The cheapest meal kit (the diet problem)
2:45–3:45
5.4 Rules that make a kit people would buy; a planted bug
3:45–4:00
Break
4:00–4:45
Mini-project: the kit memo and nutrition label
4:45–5:00
Commit with Git + checklist

Update the course data

The data script has grown. Open the Course data page, copy the new make_data.py over your old one, and rerun it:

python make_data.py
data/dcs.csv: 3 rows
data/stores.csv: 40 rows
data/bakery_products.csv: 3 rows
data/bakery_recipe.csv: 7 rows
data/bakery_resources.csv: 3 rows
data/bakery_current_plan.csv: 3 rows
data/bakery_sales_weekly.csv: 12,360 rows
data/flour_suppliers.csv: 4 rows
data/flour_spec.csv: 3 rows
data/mealkit_ingredients.csv: 13 rows
data/mealkit_rules.csv: 6 rows
data/bakery_range.csv: 30 rows
data/bakery_range_recipe.csv: 94 rows
data/bakery_range_resources.csv: 4 rows
data/bakery_range_forecast.csv: 30 rows
data/bakery_range_minimums.csv: 35 rows
data/plan_weeks.csv: 12 rows
data/plan_demand.csv: 360 rows
data/bakery_storage.csv: 4 rows
data/plan_settings.csv: 8 rows
data/places.csv: 17 rows
data/road_segments.csv: 28 rows
data/store_logistics.csv: 40 rows
data/dc_logistics.csv: 3 rows
data/dc_store_lanes.csv: 120 rows
data/driver_route_minutes.csv: 64 rows
data/chilled_nodes.csv: 47 rows
data/chilled_arcs.csv: 156 rows
data/store_pallets_history.csv: 2,120 rows
data/store_week_actual.csv: 160 rows
data/store_week_forecast.csv: 160 rows
data/dc_weeks.csv: 12 rows
data/distribution_costs.csv: 5 rows
data/bakery_investments.csv: 4 rows
data/bakery_range_setup.csv: 30 rows
data/candidate_sites.csv: 10 rows
data/site_store_lanes.csv: 400 rows
data/truck_spec.csv: 2 rows
data/rush_orders.csv: 16 rows
data/truck_orders.csv: 24 rows
data/christmas_orders.csv: 48 rows
data/cake_slab.csv: 1 rows
data/cake_bars.csv: 5 rows
data/crossdock_candidates.csv: 6 rows
data/crossdock_arcs.csv: 101 rows
data/christmas_week_orders.csv: 184 rows
data/flour_discounts.csv: 8 rows
data/flour_all_units_offer.csv: 3 rows
data/flour_delivery.csv: 4 rows
data/overtime_tiers.csv: 4 rows
data/network_options.csv: 3 rows
data/network_settings.csv: 7 rows
data/dc_staff.csv: 34 rows
data/dc_shifts.csv: 3 rows
data/dc_coverage.csv: 42 rows
data/dc_rules.csv: 8 rows
data/dc_last_sunday.csv: 34 rows
data/dc_current_roster.csv: 142 rows
data/staff_requests.csv: 47 rows
data/bakery_machines.csv: 8 rows
data/bakery_night_jobs.csv: 18 rows
data/bakery_operations.csv: 72 rows
data/bakery_rules.csv: 5 rows
data/delivery_stops.csv: 35 rows
data/delivery_matrix.csv: 1,225 rows
data/delivery_fleet.csv: 2 rows
data/forklift_certification.csv: 2 rows
data/delivery_days.csv: 6 rows
data/delivery_drivers.csv: 11 rows
data/driver_rules.csv: 5 rows
data/trip_log.csv: 1,872 rows
data/bakery_disruptions.csv: 2 rows
data/receiving_log.csv: 306 rows
data/receiving_settings.csv: 5 rows
data/dock_shift_options.csv: 10 rows
data/stress_scenarios.csv: 6 rows
data/yule_log_history.csv: 118 rows
data/yule_log_forecast.csv: 40 rows
data/yule_log_economics.csv: 5 rows
data/dc_items.csv: 6 rows
data/dc_suppliers.csv: 3 rows
data/dc_daily_demand.csv: 1,092 rows
data/purchase_orders.csv: 156 rows
data/inventory_settings.csv: 5 rows
data/dc_supplier_offers.csv: 2 rows
data/bakery_two_stage.csv: 4 rows
data/bakery_oven_log.csv: 780 rows
data/bakery_robust.csv: 1 rows
data/mdp_settings.csv: 3 rows
data/replenishment_scenarios.csv: 4 rows

Later lessons add files to the same script, so your list may be longer than the one above. The first seven files are byte-for-byte the same as before: new data uses its own random stream, so your Days 1–4 results do not change. Rerun python day01/ladder.py too: it rewrites data/forecast_next_week.csv, which Day 6 needs.

5.1 Blending flour: shares of one tonne

The bakery's bread flour must have at least 12.5% protein (for gluten), at most 0.60% ash (for a light crumb) and at most 14.0% moisture (for shelf life). Four suppliers each sell flour with different properties and prices:

                       supplier  price_per_tonne  protein_pct  ash_pct  moisture_pct  max_tonnes_per_week
supplier_id                                                                                              
FL-PHR         Prairie Hard Red              520         14.5     0.62          13.0                   30
FL-OSW       Ontario Soft White              410         10.0     0.48          14.2                   30
FL-QCO           Quebec Organic              640         13.0     0.55          13.5                    8
FL-DUR           Imported Durum              590         15.5     0.80          12.5                   30

No single flour works on its own: Prairie and Durum have too much ash, Ontario too little protein, Quebec is dear. A blend can do better. If fsf_s is the share of supplier ss in one tonne, the blend's protein is the weighted average ∑sproteinsfs\sum_s \text{protein}_s f_s, and so on for every property. That is linear in ff, so this is an LP:

min⁡∑sprices fss.t.∑sfs=1∑sproteins fs≥12.5,∑sashs fs≤0.60,∑smoistures fs≤14.00≤fs≤1\begin{aligned} \min\quad & \sum_s \text{price}_s \, f_s \\ \text{s.t.}\quad & \sum_s f_s = 1 \\ & \sum_s \text{protein}_s \, f_s \ge 12.5,\quad \sum_s \text{ash}_s \, f_s \le 0.60,\quad \sum_s \text{moisture}_s \, f_s \le 14.0 \\ & 0 \le f_s \le 1 \end{aligned}

Create day05/flour_blend.py:

import pandas as pd

import pyomo.environ as pyo

flour = pd.read_csv("data/flour_suppliers.csv").set_index("supplier_id")
spec = pd.read_csv("data/flour_spec.csv").set_index("property")
print(flour.drop(columns="province").to_string())
print(spec.to_string())
solver = pyo.SolverFactory("highs")


def spec_constraints(m, amount, total):
    """Blend quality = weighted average of supplier qualities, written without division."""
    m.spec = pyo.ConstraintList()
    for prop, row in spec.iterrows():
        blend = sum(flour.loc[s, prop] * amount[s] for s in m.S)
        if pd.notna(row.min_value):
            m.spec.add(blend >= row.min_value * total)
        if pd.notna(row.max_value):
            m.spec.add(blend <= row.max_value * total)


# ---------- 5.1 Shares of one tonne ----------
m = pyo.ConcreteModel()
m.S = pyo.Set(initialize=flour.index.tolist())
m.share = pyo.Var(m.S, bounds=(0, 1))
m.one_tonne = pyo.Constraint(expr=sum(m.share[s] for s in m.S) == 1)
spec_constraints(m, m.share, 1)
m.cost = pyo.Objective(expr=sum(flour.loc[s, "price_per_tonne"] * m.share[s] for s in m.S))
print(solver.solve(m).solver.termination_condition)
print(f"cost per tonne ${pyo.value(m.cost):,.2f}")
for s in m.S:
    print(f"  {s} {flour.loc[s, 'supplier']:<20} {pyo.value(m.share[s]):.4f}")
for prop in spec.index:
    print(f"  blend {prop}: {sum(flour.loc[s, prop] * pyo.value(m.share[s]) for s in m.S):.3f}")
optimal
cost per tonne $471.11
  FL-PHR Prairie Hard Red     0.5556
  FL-OSW Ontario Soft White   0.4444
  FL-QCO Quebec Organic       0.0000
  FL-DUR Imported Durum       0.0000
  blend protein_pct: 12.500
  blend ash_pct: 0.558
  blend moisture_pct: 13.533

Five parts Prairie to four parts Ontario, at $471.11 a tonne: cheaper than any single flour that meets the spec (Quebec alone, at $640, is the only one). The protein rule binds at exactly 12.5%; ash and moisture have room to spare.

Two habits in spec_constraints:

  • The spec is data (flour_spec.csv), so the quality team can change a limit without touching code.
  • Each rule is written as blend >= min * total, never blend / total >= min. With shares, total is 1; in 5.2 it is a variable, and dividing by a variable makes the model nonlinear (you'll hit this in 5.4).

Decision it supports: which suppliers to buy flour from, and in what proportions.

Other decisions you can support the same way: animal feed, fertilizer, fuel or coffee blends · a portfolio with limits on average risk.

Try it 5.1

Marketing wants to print "made with Quebec flour" on the bags, which requires at least 20% Quebec Organic. What does the label cost per tonne? And what happens if the quality team tightens ash to 0.55%, or to 0.50%?

Solution

Add m.local = pyo.Constraint(expr=m.share["FL-QCO"] >= 0.2) and re-solve; for ash, change 0.6 to 0.55 in flour_spec.csv (or in a copy of the spec in your script).

  • 20% Quebec: $502.44 a tonne (Prairie 0.4222, Ontario 0.3778, Quebec 0.2). The label costs $31.33 a tonne.
  • Ash ≤ 0.55%: $523.33 a tonne, one third from each of Prairie, Ontario and Quebec. Ash and protein now both bind.
  • Ash ≤ 0.50%: infeasible. Only Ontario flour is below 0.50% ash, and it has 10% protein; no blend meets both rules. Day 7 is about finding out which rules conflict.

5.2 A week of flour, with supplier limits

Next week the bakery needs 40 tonnes, and Quebec Organic can deliver at most 8. Now the decision is tonnes per supplier, and the spec applies to the average over the total:

# ---------- 5.2 Tonnes for a week, with supplier limits ----------
NEED = 40   # tonnes of bread flour next week
m = pyo.ConcreteModel()
m.S = pyo.Set(initialize=flour.index.tolist())
m.t = pyo.Var(m.S, bounds=lambda m, s: (0, flour.loc[s, "max_tonnes_per_week"]))
total = sum(m.t[s] for s in m.S)
m.need = pyo.Constraint(expr=total == NEED)
spec_constraints(m, m.t, total)
m.cost = pyo.Objective(expr=sum(flour.loc[s, "price_per_tonne"] * m.t[s] for s in m.S))
print(solver.solve(m).solver.termination_condition)
print(f"weekly flour cost ${pyo.value(m.cost):,.2f} for {NEED} t")
for s in m.S:
    print(f"  {s}: {pyo.value(m.t[s]):.3f} t")
optimal
weekly flour cost $18,844.44 for 40 t
  FL-PHR: 22.222 t
  FL-OSW: 17.778 t
  FL-QCO: 0.000 t
  FL-DUR: 0.000 t

The same 5 : 4 blend, 40 × $471.11 = $18,844.44. Here total is an expression in the variables, and blend >= 12.5 * total stays linear. The supplier limits don't bind this week; they will when Prairie has a bad harvest (try setting its limit to 15).

5.3 The cheapest meal kit: the diet problem

Northbound Fresh wants to sell a Family Meal Kit: ingredients for 4 servings in one box. The nutrition team set rules per kit:

nutrient,min_per_kit,max_per_kit
kcal,2400,3200
protein_g,120,
fat_g,,110
fibre_g,40,
sodium_mg,,2400
weight_g,1800,2600

mealkit_ingredients.csv has 13 ingredients, each with a food group, cost per 100 g, nutrients per 100 g (approximate values) and the most that fits in a box. The decision is grams of each ingredient, gig_i; every nutrient is ∑inutrienti gi/100\sum_i \text{nutrient}_i \, g_i / 100.

This is the diet problem, one of the first problems linear programming was tested on: George Stigler posed it in 1945 for a cheapest healthy diet, and it was solved with the simplex method in 1947.

We will build several versions of the kit today, so the model goes in a small module, day05/kit_model.py:

"""Day 5: the meal kit model, shared by mealkit.py and price_rules.py."""
import pandas as pd
import pyomo.environ as pyo

food = pd.read_csv("data/mealkit_ingredients.csv").set_index("ingredient")
rules = pd.read_csv("data/mealkit_rules.csv").set_index("nutrient")
NUTRIENTS = ["kcal", "protein_g", "fat_g", "fibre_g", "sodium_mg"]
solver = pyo.SolverFactory("highs")


def build():
    m = pyo.ConcreteModel()
    m.I = pyo.Set(initialize=food.index.tolist())
    m.g = pyo.Var(m.I, bounds=lambda m, i: (0, food.loc[i, "max_g"]))    # grams per kit
    m.weight = pyo.Expression(expr=sum(m.g[i] for i in m.I))
    m.amount = pyo.Expression(NUTRIENTS, rule=lambda m, n: sum(food.loc[i, n] * m.g[i] / 100 for i in m.I))
    m.rules = pyo.ConstraintList()
    for n, row in rules.iterrows():
        e = m.weight if n == "weight_g" else m.amount[n]
        if pd.notna(row.min_per_kit):
            m.rules.add(e >= row.min_per_kit)
        if pd.notna(row.max_per_kit):
            m.rules.add(e <= row.max_per_kit)
    m.cost = pyo.Objective(expr=sum(food.loc[i, "cost_per_100g"] * m.g[i] / 100 for i in m.I))
    return m


def show(m, title):
    print(f"--- {title}: ${pyo.value(m.cost):.2f} per kit, {pyo.value(m.weight):,.0f} g")
    for i in m.I:
        if pyo.value(m.g[i]) > 1e-6:
            print(f"  {i:<18} {pyo.value(m.g[i]):7.1f} g")
    print("  " + ", ".join(f"{n} {pyo.value(m.amount[n]):,.1f}" for n in NUTRIENTS))

Then day05/mealkit.py uses it:

import sys

import pyomo.environ as pyo

sys.path.insert(0, "day05")
from kit_model import build, food, show, solver

# ---------- 5.3 The cheapest kit that meets the nutrition rules ----------
m = build()
print(solver.solve(m).solver.termination_condition)
show(m, "Cheapest kit")
optimal
--- Cheapest kit: $6.23 per kit, 1,800 g
  Brown rice           110.3 g
  Dry lentils          298.0 g
  Canned chickpeas     391.7 g
  Carrots              600.0 g
  Onions               400.0 g
  kcal 2,400.0, protein_g 120.0, fat_g 18.0, fibre_g 83.7, sodium_mg 1,393.4

pyo.Expression names a piece of the model (the kit's weight, each nutrient amount) so constraints and reports can reuse it.

$6.23 for four servings, nutritionally fine, and nobody would buy it: rice, lentils, chickpeas, carrots and onions, no sauce, no meat. Stigler's 1945 diet was mostly flour, cabbage and dried beans for the same reason. The model only knows the rules you give it. A cheap, strange answer means rules are missing, not that the model is wrong.

Try it 5.2

Which nutrition rules bind in the cheapest kit? Which ingredients sit at their box limit?

Solution

Energy is at its minimum (2,400 kcal), protein at its minimum (120 g) and weight at its minimum (1,800 g). Fat (18 g of 110), fibre (83.7 of 40 minimum) and sodium have slack. Carrots (600 g) and onions (400 g) are at their box limits: they are the cheapest grams of weight. So the cheapest kit is driven by three things: hit the calories, hit the protein, fill the box cheaply.

5.4 Rules that make a kit people would buy

The product team describes the kit they want: a whole-wheat pasta kit, with a real tomato sauce, meat, plenty of vegetables, and no single ingredient dominating. Each wish becomes a linear rule:

WishRule
A pasta kit350 g ≤ pasta ≤ 500 g, no rice
A real saucetomato sauce ≥ 400 g
Meat in itbeef + chicken ≥ 400 g
Plenty of vegetablesvegetables ≥ 35% of the kit's weight
Nothing dominateseach ingredient ≤ 30% of the weight

The share rules are ratios ("35% of the weight"), and we write them without division: vegetables ≥ 0.35 × weight.

# ---------- 5.4 Rules that make it a pasta kit people would buy ----------
m = build()
veg = [i for i in m.I if food.loc[i, "food_group"] == "vegetable"]
m.pasta = pyo.Constraint(expr=pyo.inequality(350, m.g["Whole-wheat pasta"], 500))
m.sauce = pyo.Constraint(expr=m.g["Tomato sauce"] >= 400)
m.meat = pyo.Constraint(expr=m.g["Lean ground beef"] + m.g["Chicken thigh"] >= 400)
m.no_rice = pyo.Constraint(expr=m.g["Brown rice"] == 0)
m.veg_share = pyo.Constraint(expr=sum(m.g[i] for i in veg) >= 0.35 * m.weight)
m.max_share = pyo.Constraint(m.I, rule=lambda m, i: m.g[i] <= 0.30 * m.weight)
print(solver.solve(m).solver.termination_condition)
show(m, "Pasta kit")
optimal
--- Pasta kit: $10.30 per kit, 1,800 g
  Whole-wheat pasta    373.5 g
  Chicken thigh        400.0 g
  Tomato sauce         400.0 g
  Carrots              226.5 g
  Onions               400.0 g
  kcal 2,400.0, protein_g 138.2, fat_g 55.0, fibre_g 52.8, sodium_mg 2,251.0

pyo.inequality(350, x, 500) is a two-sided rule in one line. The kit now costs $10.30, and every extra dollar over $6.23 buys something the customer asked for. The model picked chicken over beef (cheaper per gram of protein) and carrots and onions as vegetables (cheapest), with the sauce counting as a vegetable too.

Decision it supports: a meal kit recipe at the lowest cost that meets nutrition and product rules.

Other decisions you can support the same way: hospital or school menus · pet food formulas · a fleet's fuel mix with emission limits.

Try it 5.3

Customers expect something green. Require at least 150 g of spinach or broccoli in total. What does it cost? Then require the meat to be beef (≥ 400 g of beef): what now?

Solution
m.green = pyo.Constraint(expr=m.g["Spinach"] + m.g["Broccoli"] >= 150)
--- Pasta kit with greens: $10.91 per kit, 1,800 g
  Whole-wheat pasta    376.9 g
  Chicken thigh        400.0 g
  Tomato sauce         400.0 g
  Broccoli             150.0 g
  Carrots               73.1 g
  Onions               400.0 g
  kcal 2,400.0, protein_g 141.5, fat_g 55.4, fibre_g 52.7, sodium_mg 2,194.8

Greens add $0.61 a kit (broccoli, the cheaper green, replaces carrots). Adding m.beef = pyo.Constraint(expr=m.g["Lean ground beef"] >= 400) gives $12.03: a beef kit costs $1.12 more than a chicken one.

The planted bug

day05/bug_ratio.py writes the vegetable share the way you would say it, "vegetables divided by weight is at least 35%":

veg = [i for i in m.I if food.loc[i, "food_group"] == "vegetable"]
m.veg_share = pyo.Constraint(expr=sum(m.g[i] for i in veg) / weight >= 0.35)

Run it.

What happens, and the fix
pyomo.contrib.solver.common.util.IncompatibleModelError: Highs interface does not support expressions of degree None

Dividing by weight, which contains variables, makes the constraint nonlinear ("degree None" means "not a polynomial"). HiGHS solves linear and quadratic models only, so it refuses. The fix is to multiply both sides by the weight, which is positive:

m.veg_share = pyo.Constraint(expr=sum(m.g[i] for i in veg) >= 0.35 * weight)

Every "share of a total" rule can be linearized this way, as long as the total cannot be negative.

Mini-project: the kit memo

Northbound Fresh plans to sell the kit at $24.99. Using your pasta kit with greens (Try it 5.3), write day05/mealkit_memo.md for the category manager:

  1. The recipe in grams, and the ingredient cost per kit and per serving.
  2. A nutrition label per serving (one quarter of the kit): kcal, protein, fat, fibre, sodium.
  3. The margin per kit before packing and labour.
  4. Which two rules cost the most, and what dropping each would save (re-solve without it).
  5. One sentence on what the model does not know (taste, supply, food safety).
Model answer

1. Pasta 376.9 g, chicken thigh 400 g, tomato sauce 400 g, broccoli 150 g, carrots 73.1 g, onions 400 g; $10.91 a kit, $2.73 a serving.

2. Per serving: 600 kcal, 35.4 g protein, 13.9 g fat, 13.2 g fibre, 549 mg sodium.

3. $24.99 − $10.91 = $14.08 before packing and labour.

4. Drop one rule at a time and re-solve (day05/price_rules.py, a loop over the rules):

def kit(drop=None):
    m = build()
    veg = [i for i in m.I if food.loc[i, "food_group"] == "vegetable"]
    product_rules = {
        "pasta 350-500 g": lambda: pyo.Constraint(expr=pyo.inequality(350, m.g["Whole-wheat pasta"], 500)),
        "sauce >= 400 g": lambda: pyo.Constraint(expr=m.g["Tomato sauce"] >= 400),
        "meat >= 400 g": lambda: pyo.Constraint(expr=m.g["Lean ground beef"] + m.g["Chicken thigh"] >= 400),
        "no rice": lambda: pyo.Constraint(expr=m.g["Brown rice"] == 0),
        "vegetables >= 35%": lambda: pyo.Constraint(expr=sum(m.g[i] for i in veg) >= 0.35 * m.weight),
        "each <= 30%": lambda: pyo.Constraint(m.I, rule=lambda m, i: m.g[i] <= 0.30 * m.weight),
        "greens >= 150 g": lambda: pyo.Constraint(expr=m.g["Spinach"] + m.g["Broccoli"] >= 150),
    }
    for k, (name, make) in enumerate(product_rules.items()):
        if name != drop:
            setattr(m, f"rule_{k}", make())
    solver.solve(m)
    return pyo.value(m.cost), list(product_rules)


base, names = kit()
print(f"all rules: ${base:.2f}")
for name in names:
    cost, _ = kit(drop=name)
    print(f"  without {name:<18} ${cost:5.2f}  saves ${base - cost:.2f}")
all rules: $10.91
  without pasta 350-500 g    $10.91  saves $0.00
  without sauce >= 400 g     $10.47  saves $0.44
  without meat >= 400 g      $ 7.25  saves $3.66
  without no rice            $10.88  saves $0.03
  without vegetables >= 35%  $10.91  saves $0.00
  without each <= 30%        $10.91  saves $0.00
  without greens >= 150 g    $10.30  saves $0.61

The meat rule costs $3.66 a kit, a third of the ingredient cost; greens cost $0.61 and the sauce $0.44. Rules that save $0.00 are not binding: the kit already meets them, so dropping them changes nothing.

5. "The model meets the nutrition and product rules at least cost; it does not know whether the kit tastes good, so the test kitchen must approve the recipe before launch."

Commit

git add .
git commit -m "Day 5: flour blending and meal kit models"
git push

Day 5 checklist

  • I can model a blend whose properties are weighted averages of its ingredients.
  • I write share rules as "part ≥ share × total", never with division.
  • I keep specs and rules in data files, not in code.
  • I know why the cheapest diet is strange, and fix it with rules, not by hand.
  • I can price a business rule by solving with and without it.
  • I can read the error HiGHS gives for a nonlinear constraint.