Prescriptive Analytics & Decision Intelligence
Overview / Module 2 / Day 12
Module 2 · Sensitivity, Duality and Network Flows · Day 12 of 80

Reduced Costs and Ranging

Yesterday's shadow prices valued the limits. Today's tools value the products and the plan's stability: reduced costs say how much more a product must earn before it is worth making, and ranging says how far any number can move before the plan changes. Together they answer the planner's most common question: "if this changes, do I need a new plan?"

▶
Video for Day 12 coming soon

In this lesson

Today's 5-hour plan

LessonProjectBreakCommit
0:00–0:45
12.1 Reduced costs: what an unbaked product is missing
0:45–1:45
12.2 Ranging with HiGHS
1:45–2:00
Break
2:00–2:45
12.3 Objective ranges: how stable is the plan?
2:45–3:45
12.4 Right-hand-side ranges: how far a shadow price holds
3:45–4:00
Break
4:00–4:45
Mini-project: which prices would change the plan?
4:45–5:00
Commit with Git + checklist

12.1 Reduced costs

On Day 6, eight products were not baked. Black forest cake earns $256 a batch, more than many baked products. Why not bake it, and how much would its profit need to rise?

The reduced cost of a product is its profit minus the value, at shadow prices, of everything one batch uses:

reduced costp=profitp−∑ruser,p yr\text{reduced cost}_p = \text{profit}_p - \sum_r \text{use}_{r,p}\, y_r

For a product that is baked (and below its cap), it is zero: it pays exactly for its resources (Day 11). For a product that is not baked, it is negative: the shortfall. Pyomo receives reduced costs through a suffix called rc. Create day12/reduced_costs.py:

import sys

import duckdb
import pandas as pd
import pyomo.environ as pyo

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

pd.set_option("display.width", 140)
con = duckdb.connect("northbound.duckdb", read_only=True)
d = load_data(con)
m = build_model(d)
m.dual = pyo.Suffix(direction=pyo.Suffix.IMPORT)
m.rc = pyo.Suffix(direction=pyo.Suffix.IMPORT)
solve(m)
base = pyo.value(m.total_profit)

# ---------- 12.1 Reduced costs: how far is each unbaked product from being worth baking? ----------
rows = []
for p in m.P:
    if pyo.value(m.x[p]) > 1e-6:
        continue
    resources = sum(d["use"].get((r, p), 0) * m.dual[m.capacity_limit[r]] for r in m.R)
    rows.append((p, d["name"][p], d["profit"][p], round(resources, 2), round(m.rc[m.x[p]], 2)))
rc = pd.DataFrame(rows, columns=["sku", "product", "profit_per_batch", "resources_at_shadow_prices", "reduced_cost"])
print(rc.sort_values("reduced_cost", ascending=False).to_string(index=False))
  sku           product  profit_per_batch  resources_at_shadow_prices  reduced_cost
BK-07   Olive sourdough             227.0                      229.97         -2.97
BK-22        Cheesecake             245.4                      253.89         -8.49
BK-15     Danish 4-pack             208.0                      225.07        -17.07
BK-21 Black forest cake             256.0                      273.27        -17.27
BK-08  Seeded sourdough             248.0                      299.51        -51.51
BK-24  Maple layer cake             193.8                      262.36        -68.56
BK-20   Lemon loaf cake             219.2                      313.50        -94.30
BK-19       Carrot cake             199.0                      322.94       -123.94

Black forest cake's oven and packing time is worth $273.27 at shadow prices; it earns $256, so it is $17.27 short. Olive sourdough is only $2.97 short: the slightest price rise or cost cut would bring it into the plan. Carrot cake is $123.94 short: no realistic price change will bake it.

Check one, the reduced cost of seeded sourdough ($51.51):

# Check one: give seeded sourdough just over its reduced cost, and it enters the plan
gap = -m.rc[m.x["BK-08"]]
for extra in (gap - 1, gap + 1):
    m2 = build_model(dict(d, profit=dict(d["profit"], **{"BK-08": d["profit"]["BK-08"] + extra})))
    solve(m2)
    print(f"BK-08 profit +${extra:.2f}: bakes {pyo.value(m2.x['BK-08']):.2f} batches")
BK-08 profit +$50.51: bakes 0.00 batches
BK-08 profit +$52.51: bakes 6.67 batches

One dollar below its reduced cost, still not baked; one dollar above, and 6.67 batches enter the plan.

Decision it supports: which products are close to earning a place in the plan, and which are far away.

Other decisions you can support the same way: which suppliers are close to winning business · which routes or shifts are nearly worth adding.

12.2 Ranging with HiGHS

Reduced costs and shadow prices are values at the current plan. Ranging adds how far they hold:

  • Objective ranging, for each product: the lowest and highest profit per batch for which the current plan stays optimal (Day 3's "$200 to $400" for sourdough).
  • Right-hand-side ranging, for each limit: the range of capacity over which the shadow price stays the same.

HiGHS computes both, but Pyomo does not pass them back. So we write the model to an LP file, load it into HiGHS directly through its Python package highspy (installed with HiGHS on Day 1), and use Pyomo's symbol map to translate HiGHS's names (x(BK_03)) back to Pyomo's (x[BK-03]). Create day12/ranging.py:

"""Day 12: ranging with HiGHS. How far can a number move before the plan changes?

Pyomo does not pass ranging back, so we write the model as an LP file, load it into
HiGHS directly (highspy), and match HiGHS's names back to the Pyomo components.

Import it:  from ranging import ranging
"""
import os
import tempfile

import highspy
import pandas as pd


def ranging(m):
    """Return (costs, limits): ranging for every variable's objective coefficient
    and every constraint's right-hand side, as DataFrames indexed by Pyomo name."""
    path = os.path.join(tempfile.mkdtemp(), "model.lp")
    _, symbol_map_id = m.write(path, io_options={"symbolic_solver_labels": True})
    by_symbol = m.solutions.symbol_map[symbol_map_id].bySymbol

    h = highspy.Highs()
    h.setOptionValue("output_flag", False)
    h.readModel(path)
    h.run()
    status, r = h.getRanging()
    lp, sol = h.getLp(), h.getSolution()

    n = lp.num_col_
    costs = pd.DataFrame({
        "name": [by_symbol[c].name for c in lp.col_names_],
        "value": sol.col_value,
        "coefficient": lp.col_cost_,
        "lowest": r.col_cost_dn.value_[:n],
        "highest": r.col_cost_up.value_[:n],
    }).set_index("name")
    limits = pd.DataFrame({
        "name": [by_symbol[c].name for c in lp.row_names_],
        "activity": sol.row_value,
        "limit": lp.row_upper_,
        "shadow_price": sol.row_dual,
        "lowest": r.row_bound_dn.value_,
        "highest": r.row_bound_up.value_,
        "profit_at_lowest": r.row_bound_dn.objective_,
        "profit_at_highest": r.row_bound_up.objective_,
    }).set_index("name")
    # A limit with spare capacity can fall to what is used, or rise without end, and nothing changes.
    # (HiGHS reports a different quantity for such rows, so we state the simple answer ourselves.)
    spare = (limits.limit - limits.activity > 1e-7) & (limits.shadow_price.abs() < 1e-9)
    objective = h.getInfo().objective_function_value
    limits.loc[spare, ["lowest", "highest"]] = list(zip(limits.activity[spare], [float("inf")] * spare.sum()))
    limits.loc[spare, ["profit_at_lowest", "profit_at_highest"]] = objective
    return costs, limits

Two details:

  • getRanging() returns arrays for columns (variables) and rows (constraints). Each has a value_ (the limit of the range) and an objective_ (the profit at that limit).
  • For a constraint with spare capacity, the answer is simple and we state it ourselves: the limit can fall to what is used, or rise forever, and nothing changes.

12.3 Objective ranges: how stable is the plan?

# ---------- 12.2 Objective ranging: how far can each product's profit move? ----------
costs, limits = ranging(m)
costs = costs.rename(index=lambda n: n[2:-1])          # "x[BK-03]" -> "BK-03"
costs["product"] = [d["name"][p] for p in costs.index]
costs["batches"] = costs.value.round(2)
show = costs[["product", "batches", "coefficient", "lowest", "highest"]].round(2)
print(show.to_string())
                              product  batches  coefficient  lowest  highest
name
BK-03                        Rye loaf     25.0        267.0  229.97      inf
BK-04                 Multigrain loaf     18.0        294.0  186.79      inf
BK-05                 Baguette 2-pack      7.0        317.0  265.29      inf
BK-06              Country white loaf      8.0        246.0  175.40      inf
BK-07                 Olive sourdough      0.0        227.0    -inf   229.97
BK-08                Seeded sourdough      0.0        248.0    -inf   299.51
BK-09                 Ciabatta 4-pack      8.0        214.0  186.31      inf
BK-10                    Raisin bread     20.0        350.0  215.62      inf
BK-12         Pain au chocolat 4-pack     15.0        282.0  244.45      inf
BK-13         Almond croissant 4-pack     27.0        262.5  205.20      inf
BK-14            Cinnamon roll 4-pack     26.0        238.5  225.07      inf
BK-15                   Danish 4-pack      0.0        208.0    -inf   225.07
BK-16                    Brioche loaf      9.0        295.5  235.00      inf
BK-17           Apple turnover 4-pack      9.0        289.0  215.13      inf
BK-18              Butter tart 6-pack     25.0        235.0  224.38   238.30
BK-19                     Carrot cake      0.0        199.0    -inf   322.94
BK-20                 Lemon loaf cake      0.0        219.2    -inf   313.50
BK-21               Black forest cake      0.0        256.0    -inf   273.27
BK-22                      Cheesecake      0.0        245.4    -inf   253.89
BK-23                    Banana bread     20.0        285.6  263.83      inf
BK-24                Maple layer cake      0.0        193.8    -inf   262.36
BK-25         Oatmeal cookies 12-pack     16.0        196.2  174.42      inf
BK-26  Chocolate chip cookies 12-pack      1.6        193.8  189.73   208.36
BK-27             Nanaimo bars 6-pack     25.0        237.0  203.73      inf
BK-28             Date squares 6-pack     20.0        227.4  184.35      inf
BK-29              Shortbread 12-pack     19.0        177.0  164.97      inf
BK-30                 Brownies 6-pack     20.0        229.2  213.18      inf
BK-CR                Croissant 6-pack     31.0        250.0  205.69      inf
BK-SD                  Sourdough loaf     35.0        300.0  297.03   337.03
BK-WW                Whole-wheat loaf     45.0        200.0  146.57      inf

How to read a row: as long as raisin bread's profit stays between $215.62 and infinity, the bakery should keep baking its full 20 batches. For an unbaked product, the highest value is its profit plus its reduced cost (olive sourdough: $229.97).

The plan is robust for most products: their profit can fall $30 to $100 a batch before anything changes. Three are fragile:

  • Sourdough ($300; range $297.03 to $337.03): a $2.97 drop in profit per batch, 3 cents a loaf, changes the plan. The reason: olive sourdough, $2.97 short of entering, competes with it for starter. This is Day 6's and the capstone's sourdough surprise, now measured.
  • Butter tarts ($224.38 to $238.30) and chocolate chip cookies ($189.73 to $208.36): the two partial products, which move with any change.

Try it 12.1

In the 3-product bakery from Module 1, what is the range for each product's profit? Compare sourdough's range with Day 3's two-product answer ($200 to $400).

Solution
d = load_data(con, "module1_products", "bakery_recipe", "bakery_resources", "module1_forecast")
m = build_model(d)
solve(m)
costs, limits = ranging(m)
print(costs.round(2))
          value  coefficient  lowest  highest
name                                         
x[BK-CR]   10.0        250.0  225.00   300.00
x[BK-SD]   20.0        300.0  166.67   333.33
x[BK-WW]   45.0        200.0  166.67      inf

(Create the two module1_ views as in day11/shadow_prices.py.) With croissants in the model, sourdough's range is $166.67 to $333.33, not $200 to $400: a third product changes which corner neighbours the current one. Whole-wheat can rise without limit (it is already at its cap).

12.4 Right-hand-side ranges: how far a shadow price holds

# ---------- 12.3 Right-hand-side ranging: over what range does each shadow price hold? ----------
res = limits[limits.index.str.startswith("capacity")].round(2)
print(res[["activity", "limit", "shadow_price", "lowest", "highest", "profit_at_lowest", "profit_at_highest"]].to_string())

for oven in (589, 590, 600, 602, 603, 610):
    m3 = build_model(dict(d, capacity=dict(d["capacity"], oven_hours=oven)))
    solve(m3)
    predicted = base + 99.34 * (oven - 600)
    print(f"oven {oven}: re-solved ${pyo.value(m3.total_profit):,.2f}, shadow price predicts ${predicted:,.2f}")
                                   activity  limit  shadow_price  lowest  highest  profit_at_lowest  profit_at_highest
name
capacity_limit[baker_hours]          539.62  560.0          0.00  539.62      inf         108351.28          108351.28
capacity_limit[oven_hours]           600.00  600.0         99.34  589.43   602.29         107301.11          108578.34
capacity_limit[packing_hours]        300.00  300.0         94.46  299.06   304.35         108262.38          108762.46
capacity_limit[sourdough_starter]     60.00   60.0         54.09   57.09    60.00         108193.93          108351.28
oven 589: re-solved $107,257.32, shadow price predicts $107,258.54
oven 590: re-solved $107,357.88, shadow price predicts $107,357.88
oven 600: re-solved $108,351.28, shadow price predicts $108,351.28
oven 602: re-solved $108,549.96, shadow price predicts $108,549.96
oven 603: re-solved $108,642.02, shadow price predicts $108,649.30
oven 610: re-solved $109,182.01, shadow price predicts $109,344.68

Day 11's oven shadow price, $99.34, holds only between 589.43 and 602.29 oven hours. Inside that range, shadow price × change is exact (oven +2: $198.68 both ways). Outside it, the plan changes and the prediction drifts: at +10 hours the shadow price overstates the gain by $163.

The starter's range is 57.09 to 60.00: its price holds downward but not upward at all. Another degenerate corner (Day 11): one more batch of starter adds $51.12, not $54.09 (re-solve and see).

Ranges are narrow in a 30-product model: each extra hour shifts some product to its cap or off it, and the next hour is worth a little less. For anything bigger than a few hours, re-solve. Day 13 makes that cheap.

Mini-project: which prices would change the plan?

The pricing team reviews transfer prices next month. Before they do, tell them which products' plans would change with a small price move. For each product, convert the objective range into cents per loaf or pack (profit per batch ÷ units per batch), in both directions, and rank products by the smallest move that changes the plan, as a share of their price.

Solution
import sys

import duckdb
import pandas as pd

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

pd.set_option("display.width", 140)
con = duckdb.connect("northbound.duckdb", read_only=True)
d = load_data(con)
m = build_model(d)
solve(m)
costs, _ = ranging(m)
costs = costs.rename(index=lambda n: n[2:-1])

units = dict(con.sql("SELECT sku, units_per_batch FROM bakery_range").fetchall())
price = dict(con.sql("SELECT sku, transfer_price FROM bakery_range").fetchall())
t = pd.DataFrame({
    "product": [d["name"][p] for p in costs.index],
    "batches": costs.value.round(2),
    # how many cents per loaf or pack the price can fall, or must rise, before the plan changes
    "price_can_fall_cents": ((costs.coefficient - costs.lowest) / pd.Series(units) * 100).round(1),
    "price_must_rise_cents": ((costs.highest - costs.coefficient) / pd.Series(units) * 100).round(1),
    "price": pd.Series(price),
}, index=costs.index)
t["smallest_move_pct"] = (t[["price_can_fall_cents", "price_must_rise_cents"]].min(axis=1) / t.price).round(2)
print(t.sort_values("smallest_move_pct").head(8).to_string())
                              product  batches  price_can_fall_cents  price_must_rise_cents  price  smallest_move_pct
name
BK-SD                  Sourdough loaf     35.0                   3.0                   37.0   4.50               0.67
BK-07                 Olive sourdough      0.0                   inf                    3.0   3.55               0.85
BK-18              Butter tart 6-pack     25.0                  21.2                    6.6   6.95               0.95
BK-26  Chocolate chip cookies 12-pack      1.6                   6.8                   24.3   5.00               1.36
BK-22                      Cheesecake      0.0                   inf                   42.5  19.90               2.14
BK-14            Cinnamon roll 4-pack     26.0                  26.9                    inf   7.15               3.76
BK-21               Black forest cake      0.0                   inf                   86.4  21.05               4.10
BK-30                 Brownies 6-pack     20.0                  26.7                    inf   6.35               4.20

Memo to pricing: "Three price moves would change next week's bakery plan by themselves: sourdough down 3 cents a loaf (0.7%), olive sourdough up 3 cents (0.9%), butter tarts up 7 cents a pack (1%). Every other product's price can move several percent without changing the plan. Sourdough and olive sourdough compete for the same starter, so treat their prices together."

pd.Series(units) lines up the units per batch with the products by SKU; the division works product by product.

Tests for Days 11 and 12

Shadow prices, reduced costs and ranges are claims you can test against re-solving. Add "day12" to the folders in tests/conftest.py, then create tests/test_sensitivity.py:

"""Module 2, Days 11-12: shadow prices, reduced costs and ranging agree with re-solving."""
import pyomo.environ as pyo
import pytest
from bakery import build_model, load_data, solve
from ranging import ranging


@pytest.fixture(scope="module")
def full(con):
    d = load_data(con)
    m = build_model(d)
    m.dual = pyo.Suffix(direction=pyo.Suffix.IMPORT)
    m.rc = pyo.Suffix(direction=pyo.Suffix.IMPORT)
    solve(m)
    return d, m


def resolve(d, **capacity):
    m = build_model(dict(d, capacity=dict(d["capacity"], **capacity)))
    solve(m)
    return pyo.value(m.total_profit)


def test_shadow_price_matches_a_small_resolve(full):
    d, m = full
    base = pyo.value(m.total_profit)
    assert resolve(d, oven_hours=601) - base == pytest.approx(m.dual[m.capacity_limit["oven_hours"]], abs=1e-6)
    assert resolve(d, packing_hours=301) - base == pytest.approx(m.dual[m.capacity_limit["packing_hours"]], abs=1e-6)


def test_complementary_slackness(full):
    d, m = full
    for r in m.R:
        slack = d["capacity"][r] - pyo.value(m.capacity_limit[r].body)
        assert slack * m.dual[m.capacity_limit[r]] == pytest.approx(0, abs=1e-6)


def test_reduced_cost_is_profit_minus_resources_at_shadow_prices(full):
    d, m = full
    for p in m.P:
        if pyo.value(m.x[p]) < 1e-6:
            worth = sum(d["use"].get((r, p), 0) * m.dual[m.capacity_limit[r]] for r in m.R)
            assert m.rc[m.x[p]] == pytest.approx(d["profit"][p] - worth, abs=1e-6)


def test_oven_range_holds_inside_and_breaks_outside(full):
    d, m = full
    _, limits = ranging(m)
    oven = limits.loc["capacity_limit[oven_hours]"]
    price, base = oven.shadow_price, pyo.value(m.total_profit)
    inside = oven.highest - 0.5
    outside = oven.highest + 5
    assert resolve(d, oven_hours=inside) - base == pytest.approx(price * (inside - 600), abs=1e-4)
    assert resolve(d, oven_hours=outside) - base < price * (outside - 600) - 1
26 passed

Each test states a theorem from today and yesterday as a check on your data: a shadow price equals a small re-solve; slack times price is zero; a reduced cost is profit minus resources at shadow prices; a shadow price holds inside its range and fails outside it.

Commit

git add .
git commit -m "Day 12: reduced costs, ranging with highspy, price fragility"
git push

Day 12 checklist

  • I can get reduced costs from Pyomo with an rc suffix and explain them as profit minus resources at shadow prices.
  • I verified a reduced cost by re-solving just below and above it.
  • I can compute objective and right-hand-side ranges with HiGHS.
  • I know a shadow price holds only inside its range, and that ranges can be narrow.
  • I found the fragile products in the plan, and why sourdough is one of them.
  • I can translate a range into cents per loaf for the pricing team.