9.1 Units: a forecast in loaves, a model in batches
The model works in batches (100 loaves). The forecast file from Day 1 has both forecast_units (loaves and packs) and demand_cap_batches. Pick the wrong column and nothing crashes. Create day09/units.py:
import sys
import duckdb
sys.path.insert(0, "day06")
from bakery import DataError, build_model, load_data, plan_table, solve
con = duckdb.connect() # in memory: copies of the tables we need
for t in ("bakery_products", "bakery_recipe", "bakery_resources", "forecast_next_week", "bakery_sales_weekly"):
con.sql(f"CREATE TABLE {t} AS SELECT * FROM 'data/{t}.csv'")
con.sql("CREATE VIEW products AS SELECT *, 'module 1' AS category FROM bakery_products")
# ---------- 9.1 The right forecast, and a forecast in the wrong unit ----------
con.sql("CREATE VIEW forecast_batches AS SELECT sku, demand_cap_batches FROM forecast_next_week")
con.sql("""CREATE VIEW forecast_loaves AS
SELECT sku, forecast_units AS demand_cap_batches FROM forecast_next_week""") # the mistake
for name in ("forecast_batches", "forecast_loaves"):
d = load_data(con, "products", "bakery_recipe", "bakery_resources", name)
m = build_model(d)
solve(m)
plan = plan_table(m, d)
print(name, dict(zip(plan.sku, plan.batches)), f"profit ${plan.profit.sum():,.2f}")
forecast_batches {'BK-CR': 10.0, 'BK-SD': 20.0, 'BK-WW': 45.0} profit $17,500.00
forecast_loaves {'BK-CR': 0.0, 'BK-SD': 20.0, 'BK-WW': 60.0} profit $18,000.00
With caps in loaves (3,500 instead of 35) the demand caps vanish in effect: the model bakes 60 batches of whole-wheat when the stores will take 45, and reports $500 more profit than is possible. The plan is wrong by 1,500 loaves a week, and every check from Day 6 passes: nothing is missing or negative.
Three habits prevent this:
- Put the unit in the name.
demand_cap_batches,use_per_batch,weekly_capacityin hours,holding_cost_per_batch_week. A column calledforecastinvites the mistake;forecast_unitsnext todemand_cap_batchesmakes it visible in the SQL. - Convert once, at the edge. Raw data arrive in whatever unit the source uses; one query converts to model units, and nothing else converts.
- Check against history. A forecast 100 times recent sales is a unit error until proven otherwise.
The third habit as code:
# ---------- 9.2 A plausibility check: is the forecast in line with history? ----------
def check_forecast_against_history(con, forecast, low=0.5, high=2.0):
"""Compare each product's forecast (in batches) with its average weekly sales over the last 8 weeks."""
rows = con.sql(f"""
WITH hist AS (
SELECT s.sku, sum(s.units_sold) / 8.0 / any_value(p.units_per_batch) AS avg_batches
FROM bakery_sales_weekly s JOIN bakery_products p USING (sku)
WHERE s.week_start > (SELECT max(week_start) FROM bakery_sales_weekly) - INTERVAL 8 WEEK
GROUP BY s.sku
)
SELECT f.sku, f.demand_cap_batches, round(h.avg_batches, 1) AS avg_batches,
round(f.demand_cap_batches / h.avg_batches, 2) AS ratio
FROM {forecast} f JOIN hist h USING (sku)
WHERE f.demand_cap_batches NOT BETWEEN {low} * h.avg_batches AND {high} * h.avg_batches
ORDER BY f.sku""").fetchall()
if rows:
raise DataError("; ".join(f"{s}: forecast {f} vs about {a} a week ({r}x)" for s, f, a, r in rows))
for name in ("forecast_batches", "forecast_loaves"):
try:
check_forecast_against_history(con, name)
print(name, "passes the history check")
except DataError as e:
print(name, "DataError:", e)
forecast_batches passes the history check
forecast_loaves DataError: BK-CR: forecast 1551 vs about 30.3 a week (51.2x); BK-SD: forecast 3500 vs about 34.2 a week (102.4x); BK-WW: forecast 4499 vs about 43.2 a week (104.04x)
A factor of 50 or 100 is the fingerprint of a unit error (50 packs or 100 loaves per batch). The band of 0.5 to 2 times history is a judgement: wide enough for Christmas, narrow enough to catch units. Put such checks in load_data, next to Day 6's.
Decision it supports: whether this week's inputs are in the units the model expects, before any plan leaves the building.
Other decisions you can support the same way: prices in cents versus dollars · capacities per day versus per week · kilograms versus tonnes.
9.2 Scaling: when the solver ignores your constraint
Northbound Fresh starts a carbon pilot: the three Module 1 products emit 40, 25 and 30 kg of CO2 per batch (ovens and delivery), and the bakery's budget is 1,900 kg a week. Add one constraint and write it in four units: kilograms, tonnes, megatonnes and gigatonnes. Mathematically all four are the same model. Create day09/scaling.py:
import pyomo.environ as pyo
CO2_KG = {"BK-SD": 40, "BK-WW": 25, "BK-CR": 30} # kg of CO2 per batch (ovens and delivery)
CO2_CAP_KG = 1900 # the pilot carbon budget, kg a week
UNITS = {"kg": 1, "tonnes": 1e-3, "megatonnes": 1e-9, "gigatonnes": 1e-12}
def bakery(scale):
m = pyo.ConcreteModel()
m.P = pyo.Set(initialize=["BK-SD", "BK-WW", "BK-CR"])
m.x = pyo.Var(m.P, bounds=lambda m, p: (0, {"BK-SD": 35, "BK-WW": 45, "BK-CR": 31}[p]))
m.oven = pyo.Constraint(expr=2 * m.x["BK-SD"] + m.x["BK-WW"] + 1.5 * m.x["BK-CR"] <= 100)
m.bakers = pyo.Constraint(expr=m.x["BK-SD"] + m.x["BK-WW"] + 1.5 * m.x["BK-CR"] <= 80)
m.carbon = pyo.Constraint(expr=sum(CO2_KG[p] * scale * m.x[p] for p in m.P) <= CO2_CAP_KG * scale)
m.profit = pyo.Objective(expr=300 * m.x["BK-SD"] + 200 * m.x["BK-WW"] + 250 * m.x["BK-CR"], sense=pyo.maximize)
return m
for unit, scale in UNITS.items():
m = bakery(scale)
tee = unit in ("megatonnes", "gigatonnes")
if tee:
print(f"--- HiGHS log with carbon in {unit}")
pyo.SolverFactory("highs").solve(m, tee=tee)
kg = sum(CO2_KG[p] * pyo.value(m.x[p]) for p in m.P)
plan = {p: round(pyo.value(m.x[p]), 2) for p in m.P}
flag = "" if kg <= CO2_CAP_KG + 1e-6 else " <-- OVER THE CARBON BUDGET"
print(f"{unit:>10}: plan {plan}, profit ${pyo.value(m.profit):,.2f}, CO2 {kg:,.1f} kg{flag}")
kg: plan {'BK-SD': 3.75, 'BK-WW': 45.0, 'BK-CR': 20.83}, profit $15,333.33, CO2 1,900.0 kg
tonnes: plan {'BK-SD': 3.75, 'BK-WW': 45.0, 'BK-CR': 20.83}, profit $15,333.33, CO2 1,900.0 kg
--- HiGHS log with carbon in megatonnes
Hessian has dimension 3 but no nonzeros, so is ignored
LP has 3 rows; 3 cols; 9 nonzeros
Coefficient ranges:
Matrix [3e-08, 2e+00]
Cost [2e+02, 3e+02]
Bound [3e+01, 4e+01]
RHS [2e-06, 1e+02]
WARNING: Problem has some excessively small bounds on constraints
…
Model status : Optimal
…
megatonnes: plan {'BK-SD': 3.75, 'BK-WW': 45.0, 'BK-CR': 20.83}, profit $15,333.33, CO2 1,900.0 kg
--- HiGHS log with carbon in gigatonnes
WARNING: HighsSparseMatrix local_ar_matrix matrix contains 3 |value| in [2.5e-11, 4e-11] at/below tolerance of 1e-09: ignored
Hessian has dimension 3 but no nonzeros, so is ignored
LP has 3 rows; 3 cols; 6 nonzeros
Coefficient ranges:
Matrix [1e+00, 2e+00]
Cost [2e+02, 3e+02]
Bound [3e+01, 4e+01]
RHS [2e-09, 1e+02]
WARNING: Problem has some excessively small bounds on constraints
…
Model status : Optimal
…
gigatonnes: plan {'BK-SD': 20.0, 'BK-WW': 45.0, 'BK-CR': 10.0}, profit $17,500.00, CO2 2,225.0 kg <-- OVER THE CARBON BUDGET
(… marks log lines left out.) In kilograms and tonnes the carbon budget binds: profit falls to $15,333.33 and emissions sit at exactly 1,900 kg. In megatonnes HiGHS warns but still gets it right. In gigatonnes the carbon coefficients (4 × 10⁻¹¹) are below HiGHS's tolerance of 10⁻⁹, and the solver drops them: "LP has 6 nonzeros", not 9. The carbon constraint becomes 0 ≤ 1.9 × 10⁻⁹, always true. The status is "Optimal", the plan emits 2,225 kg, and the only clue is a warning in a log nobody reads.
Why it happens: solvers work in floating point with absolute tolerances. A number below about 10⁻⁹ is treated as zero; two constraints that differ by less than 10⁻⁷ are treated as equal. Those tolerances only make sense if the model's numbers are of everyday size.
Rules of thumb:
- Choose units so that coefficients sit between about 10⁻³ and 10⁴. Batches, hours, kilograms, thousands of dollars are good; seconds, grams and cents in the same model are not.
- Read the "Coefficient ranges" lines of the solver log. Ranges wider than about 10⁶ deserve a second look.
- Recompute every constraint after solving, in real units, as
scaling.pydoes for CO2. The recheck is what flagged the gigatonne plan.
9.3 Known-answer tests with pytest
So far you checked models by running them and reading the output. Tests do the reading for you, every time, in a second. Add pytest to requirements.txt and install it:
echo "pytest==9.2.0" >> requirements.txt
pip install -r requirements.txt
A pytest test is a function whose name starts with test_, in a file whose name starts with test_, in a folder called tests. Inside, assert states what must be true. Create tests/conftest.py, which pytest reads first:
"""Shared test set-up: an in-memory database built from data/*.csv, and the model folders on the path."""
import glob
import os
import sys
import duckdb
import pytest
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
for folder in ("day06", "day08", "day09", "day10", "day12", "day14", "day15", "day16", "day18", "day19", "day20"):
sys.path.insert(0, os.path.join(ROOT, folder))
@pytest.fixture(scope="session")
def con():
"""A fresh in-memory copy of the course data, so tests never touch northbound.duckdb."""
db = duckdb.connect()
for path in sorted(glob.glob(os.path.join(ROOT, "data", "*.csv"))):
table = os.path.splitext(os.path.basename(path))[0]
db.sql(f"CREATE TABLE {table} AS SELECT * FROM read_csv('{path}')")
db.sql("CREATE VIEW module1_products AS SELECT *, 'module 1' AS category FROM bakery_products")
db.sql("CREATE VIEW module1_forecast AS SELECT sku, demand_cap_batches FROM forecast_next_week")
return db
A fixture is something tests ask for by name: any test with a con argument gets this database. scope="session" builds it once for the whole run. The tests use a fresh in-memory copy of data/, so they never depend on, or damage, northbound.duckdb. (They do need data/forecast_next_week.csv, written by day01/ladder.py.)
Now the tests for Day 6's model, tests/test_bakery.py:
"""Known-answer and property tests for the single-week bakery model (day06/bakery.py)."""
import pyomo.environ as pyo
import pytest
from bakery import DataError, build_model, load_data, plan_table, resource_table, solve
def small_data():
"""Day 3's two-product model, typed in: the answer is the corner (20, 60), $18,000."""
return {
"products": ["S", "W"], "resources": ["oven", "bakers", "starter"],
"name": {"S": "sourdough", "W": "whole-wheat"}, "category": {"S": "bread", "W": "bread"},
"profit": {"S": 300, "W": 200},
"capacity": {"oven": 100, "bakers": 80, "starter": 40},
"use": {("oven", "S"): 2, ("oven", "W"): 1, ("bakers", "S"): 1, ("bakers", "W"): 1, ("starter", "S"): 1},
"cap": {"S": 1000, "W": 1000},
}
def test_two_product_corner():
m = build_model(small_data())
solve(m)
assert pyo.value(m.x["S"]) == pytest.approx(20)
assert pyo.value(m.x["W"]) == pytest.approx(60)
assert pyo.value(m.total_profit) == pytest.approx(18_000)
def test_three_products_known_answer(con):
d = load_data(con, "module1_products", "bakery_recipe", "bakery_resources", "module1_forecast")
m = build_model(d)
solve(m)
plan = dict(zip(plan_table(m, d).sku, plan_table(m, d).batches))
assert plan == pytest.approx({"BK-SD": 20, "BK-WW": 45, "BK-CR": 10})
assert pyo.value(m.total_profit) == pytest.approx(17_500)
def test_full_range_known_answer(con):
d = load_data(con)
m = build_model(d)
solve(m)
assert pyo.value(m.total_profit) == pytest.approx(108_351.28, abs=0.01)
def test_plan_respects_every_limit(con):
d = load_data(con)
m = build_model(d)
solve(m)
assert (resource_table(m).slack >= -1e-6).all()
plan = plan_table(m, d)
assert (plan.batches >= -1e-6).all()
assert (plan.batches <= plan.demand_cap + 1e-6).all()
def test_missing_forecast_is_refused(con):
con.sql("CREATE OR REPLACE TEMP VIEW short_forecast AS SELECT * FROM bakery_range_forecast WHERE sku <> 'BK-04'")
with pytest.raises(DataError, match="BK-04 has no forecast"):
load_data(con, forecast="short_forecast")
def test_infeasible_model_raises():
m = build_model(small_data())
m.impossible = pyo.Constraint(expr=m.x["S"] >= 41) # the starter allows at most 40
with pytest.raises(RuntimeError, match="infeasible"):
solve(m)
Three kinds of test, each with a job:
| Kind | Example | What it protects |
|---|---|---|
| Known answer, worked by hand | Two products, corner (20, 60), $18,000 | The model's logic, on a case you can verify on paper (Day 3) |
| Known answer, from a trusted run | 3 products $17,500; 30 products $108,351.28 | Against any change that moves the answer (a regression test) |
| Behaviour | Missing forecast refused; infeasible model raises | The guard rails from Days 6 and 7 |
pytest.approx compares floating-point numbers with a tolerance: solver answers are rarely exactly 20, more often 19.999999999.
9.4 Property tests, and a bug caught
Known answers say what the answer is. Property tests say what must be true of any answer: stock balances, bread is never stored, limits hold. They keep working when the data change. tests/test_planner.py tests Day 8's planner:
"""Known-answer and property tests for the multi-week planner (day08/planner.py)."""
import pandas as pd
import pyomo.environ as pyo
import pytest
from bakery import build_model, load_data
from planner import build, load_plan_data, solve
TOL = 1e-6
def toy_data():
"""Day 8's toy: one product, two weeks, 10 batches a week, demand 5 then 15. Answer: $4,960."""
products = pd.DataFrame({"product_name": ["croissant"], "category": ["viennoiserie"],
"revenue_per_batch": [350.0], "ingredients_per_batch": [100.0],
"shelf_life_weeks": [3], "holding_cost_per_batch_week": [8.0],
"freezer_slots_per_batch": [1.0]}, index=pd.Index(["X"], name="sku"))
return {"products": products, "weeks": pd.DataFrame({"week": [1, 2], "capacity_factor": [1.0, 1.0]}),
"demand": {("X", 1): 5, ("X", 2): 15}, "use": {("oven_hours", "X"): 1.0},
"capacity": {("oven_hours", 1): 10, ("oven_hours", 2): 10}, "resources": ["oven_hours"],
"freezer_slots": 100.0}
@pytest.fixture(scope="module")
def six_weeks(con):
d = load_plan_data(con, weeks=6)
m = build(d)
solve(m)
return d, m
def test_toy_known_answer():
m = build(toy_data())
solve(m)
assert [pyo.value(m.make["X", t]) for t in (1, 2)] == pytest.approx([10, 10])
assert [pyo.value(m.keep["X", t]) for t in (1, 2)] == pytest.approx([5, 0])
assert pyo.value(m.profit) == pytest.approx(4_960)
def test_six_weeks_known_answer(six_weeks):
d, m = six_weeks
assert pyo.value(m.profit) == pytest.approx(597_870.27, abs=0.01)
def test_stock_balances_every_week(six_weeks):
d, m = six_weeks
for p in m.P:
before = 0
for t in m.T:
assert before + pyo.value(m.make[p, t]) == pytest.approx(pyo.value(m.sell[p, t]) + pyo.value(m.keep[p, t]), abs=TOL)
before = pyo.value(m.keep[p, t])
def test_bread_is_never_stored(six_weeks):
d, m = six_weeks
bread = d["products"].index[d["products"].category == "bread"]
assert max(pyo.value(m.keep[p, t]) for p in bread for t in m.T) <= TOL
def test_freezer_and_capacity_are_respected(six_weeks):
d, m = six_weeks
slots = d["products"].freezer_slots_per_batch
for t in m.T:
assert sum(slots[p] * pyo.value(m.keep[p, t]) for p in m.P) <= d["freezer_slots"] + TOL
for r in m.R:
assert pyo.value(m.capacity[r, t].body) <= pyo.value(m.cap[r, t]) + TOL
def test_storage_never_hurts(con, six_weeks):
d, m = six_weeks
no_storage = build(d, storage=False)
solve(no_storage)
assert pyo.value(m.profit) >= pyo.value(no_storage.profit) - TOL
def test_one_week_matches_the_single_week_model(con):
"""With one normal week and the Day 6 forecast as demand, the two models must agree."""
d = load_plan_data(con, weeks=1)
caps = dict(con.sql("SELECT sku, demand_cap_batches FROM bakery_range_forecast").fetchall())
d["demand"] = {(p, 1): caps[p] for p in d["products"].index}
m = build(d)
solve(m)
single = build_model(load_data(con))
solve(single)
assert pyo.value(m.profit) == pytest.approx(pyo.value(single.total_profit), abs=0.01)
The last test is a consistency test: with one normal week and Day 6's forecast as demand, the multi-week planner must give exactly the single-week answer, $108,351.28. Two models written on different days, by different reasoning, agreeing to the cent, is strong evidence both are right.
Run everything:
python -m pytest -v
tests/test_bakery.py::test_two_product_corner PASSED
tests/test_bakery.py::test_three_products_known_answer PASSED
tests/test_bakery.py::test_full_range_known_answer PASSED
tests/test_bakery.py::test_plan_respects_every_limit PASSED
tests/test_bakery.py::test_missing_forecast_is_refused PASSED
tests/test_bakery.py::test_infeasible_model_raises PASSED
tests/test_planner.py::test_toy_known_answer PASSED
tests/test_planner.py::test_six_weeks_known_answer PASSED
tests/test_planner.py::test_stock_balances_every_week PASSED
tests/test_planner.py::test_bread_is_never_stored PASSED
tests/test_planner.py::test_freezer_and_capacity_are_respected PASSED
tests/test_planner.py::test_storage_never_hurts PASSED
tests/test_planner.py::test_one_week_matches_the_single_week_model PASSED
13 passed
The planted bug
A colleague "fixes" the shelf-life rule in day08/planner.py so that it reads if t - L <= k <= t) instead of if t - L < k <= t). Make that change, run the tests, then undo it.
What the tests say
FAILED tests/test_planner.py::test_six_weeks_known_answer - assert 599469.586...
FAILED tests/test_planner.py::test_bread_is_never_stored - assert 52.0 <= 1e-06
2 failed, 11 passed
The known-answer test says something changed: profit rose by $1,599. The property test says what: bread is now kept in stock (52 batches). With <=, the window includes one extra week, so bread, with , may be kept for a week. Together the two failures point straight at the shelf-life rule.
This is why a suite needs both kinds of test. A known answer alone tells you the number moved; a property tells you which rule broke.
Decision it supports: whether a changed model may be used for next week's plan.
Other decisions you can support the same way: whether a new data feed can replace the old one · whether a solver upgrade changes any plan.
Mini-project: tests for the flour blend
Day 5's flour blend is a script with top-level code, which tests cannot call. Turn it into a function blend(flour, spec, min_share=None) in day09/flour.py that returns (status, cost_per_tonne, shares) and does not raise when the blend is impossible. Then write tests/test_flour.py with at least four tests:
- the known answer ($471.11; 5/9 Prairie, 4/9 Ontario);
- a property: the blend meets every spec and the shares add to 1;
- the Quebec label (Day 5, Try it 5.1) costs more, and its share is at least 20%;
- ash at 0.50% is infeasible.
Solution
"""Day 9 mini-project: the Day 5 flour blend as a function that tests can call.
Import it: from flour import blend
"""
import pandas as pd
import pyomo.environ as pyo
def blend(flour, spec, min_share=None):
"""Least-cost shares of one tonne. Returns (status, cost_per_tonne, shares) and never raises on infeasible."""
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)
m.spec = pyo.ConstraintList()
for prop, row in spec.iterrows():
quality = sum(flour.loc[s, prop] * m.share[s] for s in m.S)
if pd.notna(row.min_value):
m.spec.add(quality >= row.min_value)
if pd.notna(row.max_value):
m.spec.add(quality <= row.max_value)
for s, share in (min_share or {}).items():
m.spec.add(m.share[s] >= share)
m.cost = pyo.Objective(expr=sum(flour.loc[s, "price_per_tonne"] * m.share[s] for s in m.S))
result = pyo.SolverFactory("highs").solve(m, load_solutions=False)
status = str(result.solver.termination_condition)
if status != "optimal":
return status, None, None
m.solutions.load_from(result)
return status, pyo.value(m.cost), {s: pyo.value(m.share[s]) for s in m.S}
"""Day 9 mini-project: tests for the flour blend."""
import pytest
from flour import blend
@pytest.fixture(scope="module")
def flour(con):
return con.sql("SELECT * FROM flour_suppliers").df().set_index("supplier_id")
@pytest.fixture(scope="module")
def spec(con):
return con.sql("SELECT * FROM flour_spec").df().set_index("property")
def test_known_answer(flour, spec):
status, cost, shares = blend(flour, spec)
assert status == "optimal"
assert cost == pytest.approx(471.11, abs=0.01)
assert shares["FL-PHR"] == pytest.approx(5 / 9)
assert shares["FL-OSW"] == pytest.approx(4 / 9)
def test_blend_meets_every_spec(flour, spec):
_, _, shares = blend(flour, spec)
assert sum(shares.values()) == pytest.approx(1)
for prop, row in spec.iterrows():
quality = sum(flour.loc[s, prop] * x for s, x in shares.items())
if row.min_value == row.min_value: # not NaN
assert quality >= row.min_value - 1e-6
if row.max_value == row.max_value:
assert quality <= row.max_value + 1e-6
def test_quebec_label_costs_more(flour, spec):
_, base, _ = blend(flour, spec)
_, local, shares = blend(flour, spec, min_share={"FL-QCO": 0.2})
assert local == pytest.approx(502.44, abs=0.01)
assert local > base
assert shares["FL-QCO"] >= 0.2 - 1e-6
def test_ash_050_is_impossible(flour, spec):
tight = spec.copy()
tight.loc["ash_pct", "max_value"] = 0.50
status, cost, _ = blend(flour, tight)
assert status == "infeasible" and cost is None
row.min_value == row.min_value is a quick NaN test: NaN is the only value not equal to itself. With these, python -m pytest -q runs 17 tests.
Commit
git add .
git commit -m "Day 9: units, scaling, pytest suite"
git push
Day 9 checklist
- My column names carry their units, and I convert units in one place.
- I check forecasts against history to catch unit errors.
- I read the coefficient ranges in a solver log and keep coefficients of everyday size.
- I recompute constraints in real units after solving.
- I have known-answer, property and behaviour tests, and they run in about a second.
- I watched a test suite catch a one-character bug.