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

When Models Break: Infeasible and Unbounded

Marketing, sales and product development each add a rule to next week's plan. The solver answers: infeasible. Today you learn to find out why, and to report it in business terms ("the café contract and the forecast disagree", "the festival needs 12 more batches of starter than we have") rather than as a solver error. Then you meet the opposite failure: a plan that says profit is infinite.

▶
Video for Day 7 coming soon

In this lesson

Today's 5-hour plan

LessonProjectBreakCommit
0:00–0:45
7.1 Three new rules, one infeasible model
0:45–1:45
7.2 Cheap checks first; 7.3 an elastic model
1:45–2:00
Break
2:00–2:45
7.4 Finding the smallest set of rules that conflict
2:45–3:45
7.5 Unbounded models: the missing rule
3:45–4:00
Break
4:00–4:45
Mini-project: the sourdough festival memo
4:45–5:00
Commit with Git + checklist

7.1 Three new rules, one infeasible model

bakery_range_minimums.csv collects three new rules from three teams:

RuleFromWhat it says
Shelf presenceMarketingEvery product at least 2 batches, so it never disappears from the shelf
Café Laurier contractSalesAt least 50 batches of whole-wheat a week for a new café customer
Sourdough festivalProduct developmentAt least 18 batches of each of the 4 sourdough products

Several rules can set a minimum for the same product (whole-wheat has the shelf rule and the contract), so the largest counts. We add one constraint per product, xp≥min⁡px_p \ge \min_p. Create day07/diagnose.py:

import sys

import duckdb
import pyomo.environ as pyo

sys.path.insert(0, "day06")
from bakery import build_model, load_data

con = duckdb.connect("northbound.duckdb", read_only=True)
solver = pyo.SolverFactory("highs")


def status(m):
    return solver.solve(m, load_solutions=False).solver.termination_condition


def minimums(rules_sql="SELECT * FROM bakery_range_minimums"):
    """Several rules can set a minimum for the same product: the largest one counts."""
    return dict(con.sql(f"SELECT sku, max(min_batches) FROM ({rules_sql}) GROUP BY sku").fetchall())


def add_minimums(m, mins):
    m.min_batches = pyo.Param(m.P, initialize=mins, default=0)
    m.minimum = pyo.Constraint(m.P, rule=lambda m, p: m.x[p] >= m.min_batches[p])
    return m


# ---------- 7.1 The new rules make the model infeasible ----------
d = load_data(con)
m = add_minimums(build_model(d), minimums())
print("with all minimum rules:", status(m))
try:
    solver.solve(m)
except Exception as e:
    print(type(e).__name__, "-", str(e)[:70], "...")
with all minimum rules: infeasible
NoFeasibleSolutionError - A feasible solution was not found, so no solution can be loaded. Pleas ...

status() solves with load_solutions=False and returns only the termination condition. Without that option, Pyomo raises NoFeasibleSolutionError as soon as it tries to load a solution that does not exist. Either way: no plan satisfies all the rules.

The solver cannot tell you which rules to drop: that is a business decision. Your job is to find which rules conflict, and what each way out costs.

7.2 Cheap checks first

Most infeasibilities are simple, and SQL finds them in seconds. Two questions:

  1. Is any minimum above its own maximum?
  2. Do the minimums alone already need more of a resource than we have?
# ---------- 7.2 Cheap checks first: a minimum above its own maximum ----------
print(con.sql("""
    SELECT n.sku, n.min_batches, n.reason, f.demand_cap_batches
    FROM bakery_range_minimums n JOIN bakery_range_forecast f USING (sku)
    WHERE n.min_batches > f.demand_cap_batches"""))
print(con.sql("""
    SELECT r.resource, round(sum(u.use_per_batch * n.min_batches), 1) AS needed_by_minimums,
           any_value(r.weekly_capacity) AS capacity
    FROM (SELECT sku, max(min_batches) AS min_batches FROM bakery_range_minimums GROUP BY sku) n
    JOIN bakery_range_recipe u USING (sku) JOIN bakery_range_resources r USING (resource)
    GROUP BY r.resource ORDER BY r.resource"""))
┌─────────┬─────────────┬───────────────────────┬────────────────────┐
│   sku   │ min_batches │        reason         │ demand_cap_batches │
│ varchar │    int64    │        varchar        │       int64        │
├─────────┼─────────────┼───────────────────────┼────────────────────┤
│ BK-WW   │          50 │ Cafe Laurier contract │                 45 │
└─────────┴─────────────┴───────────────────────┴────────────────────┘

┌───────────────────┬────────────────────┬──────────┐
│     resource      │ needed_by_minimums │ capacity │
│      varchar      │       double       │  int64   │
├───────────────────┼────────────────────┼──────────┤
│ baker_hours       │              196.0 │      560 │
│ oven_hours        │              239.0 │      600 │
│ packing_hours     │              106.4 │      300 │
│ sourdough_starter │               72.0 │       60 │
└───────────────────┴────────────────────┴──────────┘

Both checks fire:

  • The contract asks for 50 batches of whole-wheat, but the cap is 45. The cap is the stores' forecast. The café's 50 batches come on top of it, so the cap was wrong for this new kind of demand. This is a modelling mistake, not a capacity problem.
  • The festival needs 4 × 18 = 72 batches of starter; there are 60. This one is a real capacity conflict.

Decision it supports: which teams to call, and about what, before anyone touches the model.

Other decisions you can support the same way: checking a sales promise against capacity before signing · checking a staffing request against the budget.

7.3 An elastic model: how little must we break?

On bigger models, conflicts involve many constraints and no simple SQL finds them. A standard trick is the elastic model: give every rule a "bend" variable that lets it be broken, at a price, and minimize the total bending. The answer shows which rules must bend, and by how much, to make the plan possible.

# ---------- 7.3 An elastic model: how little must we break? ----------
def elastic(m):
    """Let every rule bend, at a price; minimize total bending instead of maximizing profit."""
    m.total_profit.deactivate()
    m.bend_min = pyo.Var(m.P, within=pyo.NonNegativeReals)
    m.bend_cap = pyo.Var(m.P, within=pyo.NonNegativeReals)
    m.bend_res = pyo.Var(m.R, within=pyo.NonNegativeReals)
    for p in m.P:
        m.minimum[p].set_value(m.x[p] + m.bend_min[p] >= m.min_batches[p])
        m.demand[p].set_value(m.x[p] <= m.cap[p] + m.bend_cap[p])
    for r in m.R:
        m.capacity_limit[r].set_value(sum(m.use[r, p] * m.x[p] for p in m.P) <= m.capacity[r] + m.bend_res[r])
    m.bending = pyo.Objective(expr=sum(m.bend_min[p] + m.bend_cap[p] for p in m.P) + sum(m.bend_res[r] for r in m.R))
    solver.solve(m)
    for v in (m.bend_min, m.bend_cap, m.bend_res):
        for k in v:
            if pyo.value(v[k]) > 1e-6:
                print(f"  {v.name}[{k}] = {pyo.value(v[k]):g}")


print("Elastic model:")
elastic(add_minimums(build_model(d), minimums()))
Elastic model:
  bend_min[BK-07] = 12
  bend_min[BK-WW] = 5

To get a plan, whole-wheat's minimum must bend by 5 batches (50 → 45) and some sourdough minimum by 12 batches. The total, 17, is the smallest total bending possible.

Note which sourdough product bends: olive sourdough, but any of the four would do, because each bends the starter use by the same amount. When several ways out are equally cheap, the solver picks one arbitrarily. If some rules matter more than others, give their bend variables bigger weights: that is your statement of priorities, and the business should set it.

set_value replaces a constraint's expression in place, so the same model can be turned into its elastic version.

Try it 7.1

The café contract is signed and must not bend. Give bend_min["BK-WW"] a weight of 10 in the objective (all others 1) and re-solve. What bends now?

Solution
w = {"BK-WW": 10}
m.bending = pyo.Objective(expr=sum(w.get(p, 1) * m.bend_min[p] + m.bend_cap[p] for p in m.P)
                          + sum(m.bend_res[r] for r in m.R))

(delete the old objective first with m.del_component(m.bending).) Now bend_cap[BK-WW] = 5 instead of bend_min[BK-WW] = 5: the model raises whole-wheat's forecast cap to 50 rather than cutting the contract. Same total, different story: with the weights, the elastic model points at the real fix for the contract (raise the cap by the café's volume).

7.4 The smallest set of rules that conflict

The elastic model says how much to bend. To say which rules are in conflict with each other, we want an irreducible infeasible set (IIS): a set of rules that cannot all hold, where dropping any single one of them makes the rest feasible.

The deletion filter finds one with nothing but repeated solves:

  1. Take every rule.
  2. For each rule in turn, switch it off and re-solve.
  3. If the model is still infeasible, that rule wasn't needed for the conflict: leave it off.
  4. If it becomes feasible, the rule is part of the conflict: switch it back on.
  5. The rules still on at the end are an IIS.
# ---------- 7.4 A deletion filter: the smallest set of rules that conflict ----------
def conflict_set(m):
    """Drop rules one at a time; keep a rule dropped if the model stays infeasible.
    What is left is an irreducible infeasible set (IIS): remove any one rule and it solves."""
    cons = [c for comp in (m.minimum, m.demand, m.capacity_limit) for c in comp.values()]
    for c in cons:
        c.deactivate()
        if status(m) != pyo.TerminationCondition.infeasible:
            c.activate()        # needed for the conflict: put it back
    return [c.name for c in cons if c.active]


print("Conflict 1:", conflict_set(add_minimums(build_model(d), minimums())))

# Fix 1: the cafe contract comes on top of store demand, so it raises the cap too
d_fixed = dict(d, cap=dict(d["cap"], **{"BK-WW": d["cap"]["BK-WW"] + 50}))
m = add_minimums(build_model(d_fixed), minimums())
print("after fix 1:", status(m))
print("Conflict 2:", conflict_set(add_minimums(build_model(d_fixed), minimums())))

# Fix 2: the festival asks for 15 batches of each sourdough, not 18 (4 x 15 = 60 = starter capacity)
mins = minimums("""SELECT sku, CASE WHEN reason = 'sourdough festival' THEN 15 ELSE min_batches END AS min_batches
                   FROM bakery_range_minimums""")
m = add_minimums(build_model(d_fixed), mins)
print("after fix 2:", status(m))
solver.solve(m)
print(f"profit with all rules ${pyo.value(m.total_profit):,.2f}")
for p in ("BK-SD", "BK-03", "BK-07", "BK-08", "BK-WW"):
    print(f"  {p} {d['name'][p]:<18} {pyo.value(m.x[p]):g} batches")
Conflict 1: ['minimum[BK-WW]', 'demand[BK-WW]']
after fix 1: infeasible
Conflict 2: ['minimum[BK-03]', 'minimum[BK-07]', 'minimum[BK-08]', 'minimum[BK-SD]', 'capacity_limit[sourdough_starter]']
after fix 2: optimal
profit with all rules $108,825.58
  BK-SD Sourdough loaf     15 batches
  BK-03 Rye loaf           15 batches
  BK-07 Olive sourdough    15 batches
  BK-08 Seeded sourdough   15 batches
  BK-WW Whole-wheat loaf   95 batches

The filter needed about 65 solves of a 30-product model, a fraction of a second.

  • Conflict 1 is the whole-wheat minimum against its cap. Fix 1 adds the café's 50 batches to the stores' 45: cap 95.
  • The model is still infeasible: one IIS at a time. Conflict 2 is the four festival minimums against the starter. Fix 2, after talking to product development: 15 batches of each, which exactly fills the 60 batches of starter.

Then the plan is feasible, and every rule has a price:

# What does each rule cost? Solve with and without it.
m0 = build_model(d_fixed)
solver.solve(m0)
m1 = add_minimums(build_model(d_fixed), minimums("SELECT * FROM bakery_range_minimums WHERE reason = 'shelf presence'"))
solver.solve(m1)
print(f"no minimums ${pyo.value(m0.total_profit):,.2f}; shelf rule only ${pyo.value(m1.total_profit):,.2f}; all rules ${pyo.value(m.total_profit):,.2f}")
no minimums $110,936.85; shelf rule only $109,908.38; all rules $108,825.58

(All three include the café's 50 batches.) The shelf-presence rule costs $1,028.47 a week; the festival at 15 batches costs another $1,082.80. Marketing can now weigh those numbers against the sales the rules bring. That conversation is the point of the whole exercise.

Commercial solvers can compute an IIS directly (Gurobi's computeIIS is the best known). The deletion filter is worth knowing because it works with any solver and you can explain it to anyone.

Decision it supports: which business rules to renegotiate, in which order, with what each costs.

Other decisions you can support the same way: service-level promises that can't all be kept · a timetable where some requests must be refused.

7.5 Unbounded: the missing rule

Product development adds focaccia to the product list ($280 profit a batch), but the recipe and forecast files have not been updated yet. A model built without Day 6's checks:

# ---------- 7.5 Unbounded: a product with no recipe and no forecast ----------
# Focaccia: 100 loaves a batch, $4.20 price, $1.40 ingredients -> $280 a batch.
# Someone added it to the product list, but not yet to the recipe or the forecast.
d2 = dict(d)
d2["products"] = d["products"] + ["BK-31"]
d2["profit"] = dict(d["profit"], **{"BK-31": 280.0})
d2["name"] = dict(d["name"], **{"BK-31": "Focaccia"})
m = pyo.ConcreteModel()
m.P = pyo.Set(initialize=d2["products"])
m.x = pyo.Var(m.P, bounds=lambda m, p: (0, d2["cap"].get(p)))
m.c = pyo.Constraint(d2["resources"], rule=lambda m, r: sum(d2["use"].get((r, p), 0) * m.x[p] for p in m.P) <= d2["capacity"][r])
m.obj = pyo.Objective(expr=sum(d2["profit"][p] * m.x[p] for p in m.P), sense=pyo.maximize)
print("Focaccia added without recipe or forecast:", status(m))

# Find the culprit: give every variable a huge bound and see which ones reach it
for p in m.P:
    if m.x[p].ub is None:
        m.x[p].setub(1e6)
solver.solve(m)
print("variables at the 1,000,000 bound:", [p for p in m.P if pyo.value(m.x[p]) > 1e6 - 1])
Focaccia added without recipe or forecast: unbounded
variables at the 1,000,000 bound: ['BK-31']

With no recipe rows, focaccia uses no oven, bakers or packing; with no forecast, it has no cap. Every batch earns $280 and costs nothing, so profit can grow forever: unbounded.

Real businesses are never unbounded. An unbounded model always means a missing rule or a missing number. To find it, give every variable a huge bound (here a million batches) and solve: the variables that reach the bound point at the gap. load_data would have refused the data outright ("BK-31 has no forecast; BK-31 has no recipe rows").

StatusWhat it meansFirst check
InfeasibleNo plan satisfies every ruleMinimums above maximums; minimums alone above capacity; then an elastic model or a deletion filter
UnboundedProfit can grow foreverA variable with no cap, a product with no resource use, a wrong sign; then big bounds
Optimal but wrongThe model solved, but not the model you meantpprint, the LP file, data checks, recomputing the objective

Mini-project: the sourdough festival memo

Product development insists on 18 batches of each sourdough product. The starter culture can be expanded to 72 batches a week (one more starter tank). Compare four options, with the café contract fixed as in 7.4:

  • A: no festival (shelf rule and café only)
  • B: festival at 15 batches each, 60 starter batches
  • C: festival at 18 batches each, 72 starter batches
  • D: festival at 18 batches each, 60 starter batches

Write day07/festival_memo.md: the profit of each option, what the extra starter capacity is worth per week, and a recommendation in three sentences.

Solution
import sys

import duckdb
import pyomo.environ as pyo

sys.path.insert(0, "day06")
from bakery import build_model, load_data

con = duckdb.connect("northbound.duckdb", read_only=True)
solver = pyo.SolverFactory("highs")
d = load_data(con)
d = dict(d, cap=dict(d["cap"], **{"BK-WW": d["cap"]["BK-WW"] + 50}))   # the cafe contract on top of store demand


def plan(festival_min, starter_capacity):
    rules = con.sql(f"""
        SELECT sku, max(CASE WHEN reason = 'sourdough festival' THEN {festival_min} ELSE min_batches END)
        FROM bakery_range_minimums GROUP BY sku""").fetchall()
    dd = dict(d, capacity=dict(d["capacity"], sourdough_starter=starter_capacity))
    m = build_model(dd)
    m.minimum = pyo.Constraint(m.P, rule=lambda m, p: m.x[p] >= dict(rules).get(p, 0))
    result = solver.solve(m, load_solutions=False)
    if result.solver.termination_condition != pyo.TerminationCondition.optimal:
        return None
    m.solutions.load_from(result)
    return pyo.value(m.total_profit)


options = {
    "A: no festival (shelf rule and cafe only)": plan(0, 60),
    "B: festival at 15 batches each": plan(15, 60),
    "C: festival at 18 batches, 72 starter batches": plan(18, 72),
    "D: festival at 18 batches, 60 starter batches": plan(18, 60),
}
for name, profit in options.items():
    print(f"{name:<48} {'infeasible' if profit is None else f'${profit:,.2f}'}")
gain = options["C: festival at 18 batches, 72 starter batches"] - options["B: festival at 15 batches each"]
print(f"12 extra starter batches are worth ${gain:,.2f} a week, ${gain / 12:,.2f} per batch")
A: no festival (shelf rule and cafe only)        $109,908.38
B: festival at 15 batches each                   $108,825.58
C: festival at 18 batches, 72 starter batches    $109,278.60
D: festival at 18 batches, 60 starter batches    infeasible
12 extra starter batches are worth $453.02 a week, $37.75 per batch

Memo: "The festival as proposed (18 batches of each sourdough) is impossible with today's starter: it needs 72 batches and we have 60. At 15 batches each it fits and costs $1,082.80 a week in profit against no festival; at 18 batches with a second starter tank it costs $629.78. The second tank is worth $453 a week, so it pays for itself if it costs less than about $23,500 a year; otherwise run the festival at 15 batches."

Every number in the memo comes from a solve, and option D is reported as what it is: not a worse plan, but no plan at all.

Commit

git add .
git commit -m "Day 7: infeasible and unbounded models, elastic model, deletion filter"
git push

Day 7 checklist

  • I check the status with load_solutions=False before loading a solution.
  • I run cheap SQL checks (minimum above maximum, minimums above capacity) first.
  • I can build an elastic model and read which rules must bend, and by how much.
  • I can find an irreducible infeasible set with a deletion filter.
  • I can find the missing rule behind an unbounded model.
  • I report infeasibility as a business conflict with a price on each way out.