Prescriptive Analytics & Decision Intelligence
Overview / Module 6 / Day 53
Module 6 · Optimization under Uncertainty · Day 53 of 80

Two-Stage Stochastic Programming

The newsvendor has one product and no second chance. The bakery has 30 products sharing ovens, bakers, packing and starter. It also has a second chance: a mid-week top-up bake in 40 overtime oven hours ($55 an hour extra), once early-week sales show where demand is.

▶
Video for Day 53 coming soon

In this lesson

Today's 5-hour plan

LessonProjectBreakCommit
0:00–0:45
53.1 One product: the newsvendor as a scenario LP
0:45–1:45
53.2 The extensive form: 30 products, 103 weeks
1:45–2:00
Break
2:00–2:45
53.3 The stochastic plan against the Day 6 plan
2:45–3:45
53.4 What an oven hour is worth now; a planted bug
3:45–4:00
Break
4:00–4:45
Mini-project: lease ovens for December?
4:45–5:00
Commit with Git + checklist

A two-stage stochastic program plans for that:

  • Stage 1 decides now (the week's plan).
  • Stage 2 decides later, differently in every scenario (the top-up, what sells, what goes to the day-old shelf).
  • The objective is the expected profit over the scenarios.

Today you build it with 103 historical weeks as scenarios and compare its plan with Day 6's.

53.1 One product: the newsvendor as a scenario LP

Write the scenarios out. With xx the first-stage plan, and yw,swy_w, s_w the top-up and sales in scenario ww (probability πw\pi_w):

max⁡  ∑wπw[ p sw−c (x+yw)+v (x+yw−sw)−h yw]\max\; \sum_w \pi_w \Big[\, p\,s_w - c\,(x + y_w) + v\,(x + y_w - s_w) - h\,y_w \Big]

s.t.sw≤x+yw,sw≤Dw,capacity on x and on yw\text{s.t.}\quad s_w \le x + y_w,\quad s_w \le D_w,\quad \text{capacity on } x \text{ and on } y_w

Here pp is the price, cc the ingredient cost, vv the salvage value on the day-old shelf, and hh the top-up's extra oven cost. Each scenario gets its own copy of the second-stage variables. This is the extensive form. Create day53/two_stage.py:

"""Day 53: two-stage stochastic programming for the bakery's week.
Stage 1 (now): how many batches to plan for the week, within the ovens, bakers, packing and starter.
Stage 2 (once demand is known, a different answer in every scenario): top up with a mid-week bake in overtime
oven hours, sell what is wanted, put leftovers on the day-old shelf.

Import it:  from two_stage import load_two_stage, build_two_stage, scenario_profits
"""
import numpy as np
import pandas as pd
import pyomo.environ as pyo

from bakery import load_data
from correlated import error_table


def load_two_stage(con, december_only=False):
    """The Day 6 data, per-batch economics, the day-old shelf and top-up settings, and the scenarios:
    every historical week's forecast errors applied to this week's forecast (Day 44: products move together)."""
    d = load_data(con)
    e = con.sql("SELECT sku, units_per_batch, transfer_price, ingredient_cost FROM bakery_range").df().set_index("sku")
    st = dict(con.sql("SELECT * FROM bakery_two_stage").fetchall())
    econ = pd.DataFrame({"price": e.units_per_batch * e.transfer_price, "cost": e.units_per_batch * e.ingredient_cost})
    econ["salvage"] = econ.price * st["day_old_price_share"] * st["day_old_sell_share"]
    err = error_table(con)
    if december_only:
        err = err[[w.month == 12 for w in pd.to_datetime(err.index)]]
    bread, other = ((err["BK-SD"] + err["BK-WW"]) / 2).to_numpy(), err["BK-CR"].to_numpy()
    demand = {(p, w): d["cap"][p] * (bread[w] if d["category"][p] == "bread" else other[w])
              for p in d["products"] for w in range(len(err))}
    return d, econ, st, demand, list(err.index.astype(str))


def build_two_stage(d, econ, st, demand, weeks, plan=None, anticipate=False, lease=None):
    """The extensive form: one copy of the second stage per scenario, all equally likely.
    plan: fix the first stage (to evaluate a given plan). anticipate=True: the planted bug (Day 53).
    lease: (extra oven hours, cost a week) to offer as a yes/no first-stage choice (the mini-project)."""
    m = pyo.ConcreteModel(name="two_stage_bakery")
    m.P, m.R, m.W = pyo.Set(initialize=d["products"]), pyo.Set(initialize=d["resources"]), pyo.Set(initialize=range(len(weeks)))
    use = lambda r, p: d["use"].get((r, p), 0.0)
    # stage 1
    if anticipate:
        m.x = pyo.Var(m.P, m.W, within=pyo.NonNegativeReals)              # a plan for each scenario: the bug
        x = lambda p, w: m.x[p, w]
    else:
        m.x = pyo.Var(m.P, within=pyo.NonNegativeReals)
        x = lambda p, w: m.x[p]
    m.lease = pyo.Var(within=pyo.Binary) if lease else pyo.Param(initialize=0, mutable=False)
    extra = lambda r: (lease[0] * m.lease if lease and r == "oven_hours" else 0)
    if anticipate:
        m.capacity = pyo.Constraint(m.R, m.W, rule=lambda m, r, w: sum(use(r, p) * m.x[p, w] for p in m.P) <= d["capacity"][r])
    else:
        m.capacity = pyo.Constraint(m.R, rule=lambda m, r: sum(use(r, p) * m.x[p] for p in m.P) <= d["capacity"][r] + extra(r))
    if plan is not None:
        for p in m.P:
            m.x[p].fix(plan.get(p, 0.0))
    # stage 2, scenario by scenario
    m.y = pyo.Var(m.P, m.W, within=pyo.NonNegativeReals)                  # top-up batches
    m.s = pyo.Var(m.P, m.W, within=pyo.NonNegativeReals)                  # batches sold
    m.topup = pyo.Constraint(m.W, rule=lambda m, w: sum(use("oven_hours", p) * m.y[p, w] for p in m.P) <= st["topup_oven_hours"])
    m.sell_made = pyo.Constraint(m.P, m.W, rule=lambda m, p, w: m.s[p, w] <= x(p, w) + m.y[p, w])
    m.sell_wanted = pyo.Constraint(m.P, m.W, rule=lambda m, p, w: m.s[p, w] <= demand[p, w])

    def week_profit(m, w):
        return sum(econ.price[p] * m.s[p, w] - econ.cost[p] * (x(p, w) + m.y[p, w])
                   + econ.salvage[p] * (x(p, w) + m.y[p, w] - m.s[p, w])
                   - st["topup_cost_per_oven_hour"] * use("oven_hours", p) * m.y[p, w] for p in m.P)
    m.week_profit = pyo.Expression(m.W, rule=week_profit)
    lease_cost = lease[1] * m.lease if lease else 0
    m.expected_profit = pyo.Objective(expr=sum(m.week_profit[w] for w in m.W) / len(weeks) - lease_cost,
                                      sense=pyo.maximize)
    return m


def scenario_profits(m):
    return np.array([pyo.value(m.week_profit[w]) for w in m.W])

The scenarios are Day 44's whole historical weeks: each week's forecast errors applied to this week's forecast, so products move together as they did. First the check, one product with no top-up and no capacity limit:

# ---------- 53.1 One product: the newsvendor as a scenario LP ----------
print("--- one product")
cr = {"products": ["BK-CR"], "resources": ["oven_hours"], "use": {("oven_hours", "BK-CR"): d["use"]["oven_hours", "BK-CR"]},
      "capacity": {"oven_hours": 1e9}, "cap": {"BK-CR": d["cap"]["BK-CR"]}}             # no capacity limit, no top-up
m = build_two_stage(cr, econ, {**st, "topup_oven_hours": 0}, demand, weeks)
solve(m)
e = econ.loc["BK-CR"]
hist = [demand["BK-CR", w] for w in range(W)]
print(f"scenario LP: {pyo.value(m.x['BK-CR']):.2f} batches; Day 51's formula with the day-old shelf: "
      f"{q_empirical(hist, critical_ratio(e.price, e.cost, e.salvage)):.2f}")
--- one product
scenario LP: 31.81 batches; Day 51's formula with the day-old shelf: 31.81

The LP finds Day 51's empirical newsvendor quantity exactly. A two-stage program is a newsvendor when there is one product and nothing else. Its power is everything else: shared capacity, a second chance, many products at once.

53.2 The extensive form: 30 products, 103 weeks

# ---------- 53.2 The extensive form: 30 products, 103 weeks ----------
print("--- extensive form")
sp = build_two_stage(d, econ, st, demand, weeks)
solve(sp)
print(f"{sp.nvariables():,} variables, {sp.nconstraints():,} constraints")
print(f"stochastic plan: expected profit ${pyo.value(sp.expected_profit):,.2f} a week")
--- extensive form
6,210 variables, 6,287 constraints
stochastic plan: expected profit $112,600.11 a week

The model has about 6,200 variables, 200 times Day 6's, and HiGHS solves it in about a second. The size grows with the number of scenarios. Day 54 asks how many scenarios are enough.

53.3 The stochastic plan against the Day 6 plan

Evaluate both plans the same way: fix the first stage, and let the second stage do its best in each of the 103 weeks.

# ---------- 53.3 The stochastic plan against the Day 6 plan ----------
print("--- plans compared")
det = build_model(d)
solve(det)
day6 = {p: pyo.value(det.x[p]) for p in d["products"]}
stoch = {p: pyo.value(sp.x[p]) for p in d["products"]}
rows, topups = [], {}
for name, plan in [("Day 6 plan (the forecast)", day6), ("stochastic plan", stoch)]:
    ev = build_two_stage(d, econ, st, demand, weeks, plan=plan)
    solve(ev)
    prof = scenario_profits(ev)
    topups[name] = pd.Series({p: np.mean([pyo.value(ev.y[p, w]) for w in ev.W]) for p in ev.P})
    y = sum(pyo.value(ev.y[p, w]) for p in ev.P for w in ev.W) / W
    left = sum(pyo.value(plan[p] + ev.y[p, w] - ev.s[p, w]) for p in ev.P for w in ev.W) / W
    rows.append((name, round(sum(plan.values()), 1), round(prof.mean(), 2), round(np.quantile(prof, 0.05), 2),
                 round(prof.min(), 2), round(y, 1), round(left, 1)))
print(pd.DataFrame(rows, columns=["plan", "batches", "expected_profit", "p5", "worst_week", "topup_batches",
                                  "leftover_batches"]).to_string(index=False))
diff = pd.DataFrame({"category": pd.Series(d["category"]), "forecast": pd.Series(d["cap"]), "day6": pd.Series(day6),
                     "stochastic": pd.Series(stoch)}).round(2)
diff["change"] = (diff.stochastic - diff.day6).round(2)
diff["topup_day6"] = topups["Day 6 plan (the forecast)"].round(2)
diff["topup_stochastic"] = topups["stochastic plan"].round(2)
print("largest changes:")
print(diff[diff.change.abs() > 0.5].sort_values("change").to_string())
--- plans compared
                     plan  batches  expected_profit        p5  worst_week  topup_batches  leftover_batches
Day 6 plan (the forecast)    429.6        111778.48 109095.30    73974.37           34.7               6.1
          stochastic plan    429.2        112600.11 111994.46    79042.69           34.6               2.5
largest changes:
           category  forecast  day6  stochastic  change  topup_day6  topup_stochastic
BK-30        cookie        20  20.0       13.15   -6.85        0.32              6.64
BK-SD         bread        35  35.0       30.84   -4.16        0.00              0.08
BK-03         bread        25  25.0       21.37   -3.63        0.33              3.69
BK-27        cookie        25  25.0       23.74   -1.26        0.56              1.43
BK-14  viennoiserie        26  26.0       24.86   -1.14        0.00              0.00
BK-28        cookie        20  20.0       18.99   -1.01        0.45              1.23
BK-25        cookie        16  16.0       14.99   -1.01        0.36              1.18
BK-29        cookie        19  19.0       18.08   -0.92        0.26              0.90
BK-WW         bread        45  45.0       44.11   -0.89        0.47              0.99
BK-CR  viennoiserie        31  31.0       30.11   -0.89        0.00              0.00
BK-23          cake        20  20.0       19.14   -0.86        0.00              0.00
BK-13  viennoiserie        27  27.0       26.40   -0.60        0.00              0.00
BK-18  viennoiserie        30  25.0       28.40    3.40        0.00              0.00
BK-26        cookie         9   1.6        7.72    6.12        7.16              1.22
BK-22          cake         9   0.0        7.40    7.40        0.08              0.02
BK-07         bread        29   0.0        7.79    7.79       24.04             15.83
  • The stochastic plan earns $822 a week more on average ($42,700 a year), and its bad weeks are much better: the 5th percentile is $2,900 higher.
  • It bakes almost the same total, but a different mix. The Day 6 plan leaves BK-07 out, then spends 24 batches of top-up on it in nearly every week: the top-up becomes a costly second shift for a product it could have planned.
  • The stochastic plan puts BK-07, BK-22 and BK-26 into the plan. It holds back on products whose demand is uncertain and can be baked mid-week, such as cookies (BK-30) and rye (BK-03), and tops them up only in the weeks they sell. It plans less sourdough than the forecast (30.8 instead of 35), freeing starter for other products.
  • The deterministic model can't see any of this, because it doesn't know there will be a second chance.

53.4 What an oven hour is worth now

# ---------- 53.4 What an oven hour is worth now ----------
print("--- capacity values")
sp.dual = pyo.Suffix(direction=pyo.Suffix.IMPORT)
solve(sp)
det.dual = pyo.Suffix(direction=pyo.Suffix.IMPORT)
solve(det)
for r in d["resources"]:
    print(f"{r:>18}: Day 6 (forecast) ${det.dual[det.capacity_limit[r]]:7.2f}   stochastic (expected) ${sp.dual[sp.capacity[r]]:7.2f}")
--- capacity values
       baker_hours: Day 6 (forecast) $   0.00   stochastic (expected) $   0.00
        oven_hours: Day 6 (forecast) $  99.34   stochastic (expected) $  94.77
     packing_hours: Day 6 (forecast) $  94.46   stochastic (expected) $  86.02
 sourdough_starter: Day 6 (forecast) $  54.09   stochastic (expected) $  56.34

In a two-stage program the first-stage duals are expected shadow prices, averaged over the scenarios. An oven hour is worth $94.77 rather than $99.34, and a packing hour $86 rather than $94. Part of their value at the forecast came from demand that may not be there, and the top-up can cover some of the rest. Capacity decisions taken on deterministic duals overvalue capacity a little here. The mini-project makes such a decision properly.

Decision it supports: a plan committed before uncertainty resolves, when there are ways to adjust afterwards.

Other decisions you can support the same way: staffing a week before its calls arrive (overtime as recourse) · buying energy a day ahead (the spot market as recourse) · pre-positioning stock before a storm · capacity bought now, used later.

The planted bug

day53/bug_anticipate.py gives every scenario its own plan, "so the plan fits each week". Run it.

m = build_two_stage(d, econ, st, demand, weeks, anticipate=True)
solve(m)
print(f"expected profit ${pyo.value(m.expected_profit):,.2f} a week")
for week in ("2024-12-16", "2025-01-06", "2025-06-30"):
    w = weeks.index(week)
    print(f"week like {week}: plan {sum(pyo.value(m.x[p, w]) for p in m.P):.1f} batches, "
          f"sourdough {pyo.value(m.x['BK-SD', w]):.2f}, croissants {pyo.value(m.x['BK-CR', w]):.2f}")
What happens, and why
expected profit $113,648.14 a week
week like 2024-12-16: plan 435.7 batches, sourdough 23.70, croissants 46.24
week like 2025-01-06: plan 388.8 batches, sourdough 29.92, croissants 19.34
week like 2025-06-30: plan 427.3 batches, sourdough 35.46, croissants 29.10

The expected profit is $113,648, about $1,050 more than the stochastic plan, and the plan bakes 46 batches of croissants for a week like Christmas and 19 for a week like early January. Nice, if you know which week is coming. But the plan must be made before demand is known. Letting the first stage depend on the scenario breaks non-anticipativity: the model peeks at the future.

What it computes has a name, the wait-and-see value. The gap to the real stochastic plan is the value of perfect information, which Day 55 uses. In a stochastic program, every first-stage variable has no scenario index.

Mini-project: lease ovens for December?

The lease from Day 21 adds 100 oven hours for $900 a week, and must be signed before the week's demand is known. Make it a yes/no first-stage variable. Decide it with all 103 historical weeks, then with December's weeks only, and compare with the decision on the forecast.

Solution
"""Day 53 mini-project: lease extra ovens for a December week? The lease (Day 21) adds 100 oven hours for $900 and
must be signed before the week's demand is known. Decide it inside the two-stage model (a yes/no first-stage
variable), with December's historical weeks as scenarios, and with all weeks. Compare with the decision made on the
forecast alone.

Run from the repository root (after day06/load_tables.py):  python day53/mini_project_lease.py
"""
import sys

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

for folder in ("day06", "day42", "day44", "day53"):
    sys.path.insert(0, folder)
from bakery import build_model, solve
from two_stage import build_two_stage, load_two_stage

pd.set_option("display.width", 160)
con = duckdb.connect("northbound.duckdb", read_only=True)
hours, cost = con.sql("SELECT extra_capacity, cost_per_week FROM bakery_investments WHERE option = 'lease_ovens'").fetchall()[0]

d, *_ = load_two_stage(con)
gain_forecast = []
for extra in (0, hours):
    m = build_model({**d, "capacity": {**d["capacity"], "oven_hours": d["capacity"]["oven_hours"] + extra}})
    solve(m)
    gain_forecast.append(pyo.value(m.total_profit))
print(f"on the forecast: the lease adds ${gain_forecast[1] - gain_forecast[0]:,.2f} a week for ${cost:,.0f}: "
      f"net ${gain_forecast[1] - gain_forecast[0] - cost:+,.2f}")

rows = []
for label, dec in [("all 103 weeks", False), ("December weeks", True)]:
    d, econ, st, demand, weeks = load_two_stage(con, december_only=dec)
    value = {}
    for lease in (0, 1):
        m = build_two_stage(d, econ, st, demand, weeks, lease=(hours, cost))
        m.lease.fix(lease)
        solve(m)
        value[lease] = pyo.value(m.expected_profit)
    m = build_two_stage(d, econ, st, demand, weeks, lease=(hours, cost))
    solve(m)
    rows.append((label, len(weeks), round(value[0], 2), round(value[1], 2), round(value[1] - value[0], 2),
                 "lease" if pyo.value(m.lease) > 0.5 else "don't lease"))
print(pd.DataFrame(rows, columns=["scenarios", "weeks", "no_lease", "lease", "net_gain_of_lease", "model_decides"])
      .to_string(index=False))
on the forecast: the lease adds $1,083.62 a week for $900: net $+183.62
     scenarios  weeks  no_lease     lease  net_gain_of_lease model_decides
 all 103 weeks    103 112600.11 113084.92             484.82         lease
December weeks     10 113773.36 114314.08             540.72         lease
  • On the forecast, the lease pays only $184 a week net, a close call.
  • In the two-stage model it pays $485 a week (all weeks) and $541 (December). Extra oven hours let the plan include more products and keep top-up room for the weeks demand runs high. The forecast can't see that second use.
  • The model decides the lease and the plan together, and the lease is a binary, so this is a small stochastic MIP. HiGHS solves it in seconds.

Memo: "Lease the extra ovens for December: in December-like weeks they add about $540 a week after the $900 lease, three times what the forecast suggests, because they also give room to bake more when demand runs high."

Commit

git add .
git commit -m "Day 53: two-stage stochastic programming"
git push

Then run the tests: tests/test_uncertainty.py checks Days 51–53. It covers the critical ratio, the normal expected-profit formula against simulation, EOQ and lead-time spread, a policy with no uncertainty that never runs out, the scenario LP equal to the newsvendor, and the anticipative model never below the stochastic one. Add "day51", "day52" and "day53" to the folders in conftest.py.

"""Known answers for Days 51-53: the newsvendor, inventory policies, the two-stage model."""
import numpy as np
import pyomo.environ as pyo
import pytest

from bakery import solve
from inventory import eoq, sigma_lead_time, simulate_policy
from newsvendor import critical_ratio, expected_profit, normal_expected_profit, q_empirical
from two_stage import build_two_stage, load_two_stage


def test_newsvendor_formulas():
    assert critical_ratio(7.0, 2.0) == pytest.approx(5 / 7)
    assert critical_ratio(7.0, 2.0, salvage=1.0, penalty=1.0) == pytest.approx(6 / 7)
    assert q_empirical(range(1, 11), 0.7) == 7
    demand = np.random.default_rng(0).normal(100, 20, 400_000)
    assert expected_profit(110, demand, 7, 2) == pytest.approx(normal_expected_profit(110, 100, 20, 7, 2), rel=1e-3)


def test_inventory_formulas():
    assert eoq(1_000, 50, 2.5) == pytest.approx(200)
    assert sigma_lead_time(10, 3, 4, 0) == pytest.approx(6)              # sqrt(4) x 3 when the lead time is fixed


def test_policy_without_uncertainty():
    """Constant demand of 10 a day, a 2-day lead time: a reorder point of 30 never runs out."""
    r = simulate_policy(np.array([10]), np.array([2]), np.random.default_rng(1), 200, reorder_point=30, order_qty=50)
    assert r["fill_rate"] == 1.0
    assert r["orders"] == pytest.approx(200 * 10 / 50, abs=1)


def test_scenario_lp_is_the_newsvendor(con):
    d, econ, st, demand, weeks = load_two_stage(con)
    one = {"products": ["BK-CR"], "resources": ["oven_hours"], "use": {("oven_hours", "BK-CR"): 1.5},
           "capacity": {"oven_hours": 1e9}, "cap": {"BK-CR": d["cap"]["BK-CR"]}}
    m = build_two_stage(one, econ, {**st, "topup_oven_hours": 0}, demand, weeks)
    solve(m)
    e = econ.loc["BK-CR"]
    q = q_empirical([demand["BK-CR", w] for w in range(len(weeks))], critical_ratio(e.price, e.cost, e.salvage))
    assert pyo.value(m.x["BK-CR"]) == pytest.approx(q, abs=1e-6)


def test_knowing_the_future_is_worth_something(con):
    d, econ, st, demand, weeks = load_two_stage(con)
    values = []
    for anticipate in (False, True):
        m = build_two_stage(d, econ, st, demand, weeks, anticipate=anticipate)
        solve(m)
        values.append(pyo.value(m.expected_profit))
    assert values[1] >= values[0] - 1e-6
80 passed

Day 53 checklist

  • I can write a two-stage stochastic program in extensive form.
  • I can build scenarios from history that keep products moving together.
  • I evaluate any plan by fixing the first stage and solving the second.
  • I can explain how a stochastic plan differs from a deterministic one, and why.
  • My first-stage variables never depend on the scenario (non-anticipativity).