Prescriptive Analytics & Decision Intelligence
Overview / Module 5 / Day 49
Module 5 · Simulation and Monte Carlo · Day 49 of 80

Simulation-Optimization

Day 48 compared two options. Usually there are many: quantities for 240 store-days, shifts for a second driver, a forklift or not. Simulation-optimization searches over decisions with the simulator as the objective. It works when every option is run on the same random numbers, when the promise you must keep is a constraint the simulation estimates, and when the winner is checked on fresh runs. Today you search for croissant quantities and for the cheapest night-dock set-up that keeps the carriers' 30-minute promise (Day 47).

▶
Video for Day 49 coming soon

In this lesson

Today's 5-hour plan

LessonProjectBreakCommit
0:00–0:45
49.1 One decision: croissants for one store-day
0:45–1:45
49.2 A decision with a promise: a second driver for the busy hours
1:45–2:00
Break
2:00–2:45
49.3 Check the winner on fresh nights
2:45–3:45
A planted bug
3:45–4:00
Break
4:00–4:45
Mini-project: empty shelves on at most 10% of days
4:45–5:00
Commit with Git + checklist

49.1 One decision: croissants for one store-day

Day 45 used a formula, the critical ratio, for the best quantity. A simulator can find the same answer by trying every quantity, without the formula:

# ---------- 49.1 One decision: how many croissants for one store-day? ----------
print("--- one store")
price, cost = con.sql("SELECT transfer_price, ingredient_cost FROM bakery_range WHERE sku = 'BK-CR'").fetchall()[0]
means = store_day_means(con)
lam = means.query("store_id == 'S04' and day == 'Fri'")["mean"].item()
qs = np.arange(0, 21)
demand = np.random.default_rng(49).poisson(lam, 2_000)                    # 2,000 Fridays, the same for every q
crn = [(price * np.minimum(demand, q) - cost * q).mean() for q in qs]
fresh = [(lambda dd: (price * np.minimum(dd, q) - cost * q).mean())(np.random.default_rng(100 + q).poisson(lam, 2_000))
         for q in qs]
print(f"S04 on a Friday: Poisson demand, mean {lam:.2f}; formula (critical ratio {(price - cost) / price:.3f}): "
      f"{int(stats.poisson.ppf((price - cost) / price, lam))}")
print(pd.DataFrame({"croissants": qs, "same_days": np.round(crn, 2), "new_days_each_q": np.round(fresh, 2)})
      .iloc[6:16].to_string(index=False))
print(f"best by simulation: same days {qs[int(np.argmax(crn))]}, new days for each q {qs[int(np.argmax(fresh))]}")

# every store-day, the same way
best_sim, best_formula = [], []
rng = np.random.default_rng(491)
for mu in means["mean"]:
    dd = rng.poisson(mu, 2_000)
    profit = [(price * np.minimum(dd, q) - cost * q).mean() for q in range(0, 30)]
    best_sim.append(int(np.argmax(profit)))
    best_formula.append(int(stats.poisson.ppf((price - cost) / price, mu)))
gap = np.array(best_sim) - np.array(best_formula)
print(f"all 240 store-days: simulation = formula on {np.mean(gap == 0):.0%}, one croissant off on {np.mean(abs(gap) == 1):.0%}")
--- one store
S04 on a Friday: Poisson demand, mean 8.57; formula (critical ratio 0.714): 10
 croissants  same_days  new_days_each_q
          6      28.08            28.05
          7      31.30            31.57
          8      33.64            33.74
          9      34.98            35.53
         10      35.42            35.71
         11      35.07            35.14
         12      34.18            34.68
         13      32.89            32.63
         14      31.27            31.59
         15      29.45            29.43
best by simulation: same days 10, new days for each q 10
all 240 store-days: simulation = formula on 95%, one croissant off on 5%
  • With the same 2,000 Fridays for every quantity (CRN), the profit curve is smooth and its top is the formula's 10.
  • With new Fridays for each quantity, the curve is bumpy. Here it still peaks at 10, but the bumps could have moved the peak.
  • Over all 240 store-days the search matches the formula on 95% and is one croissant off on the rest. Those are near-ties, where the formula's own answer sits on a flat top.

The lesson: once a formula exists, use it. The simulator is for decisions where no formula exists, like the next one.

49.2 A decision with a promise: a second driver for the busy hours

Day 46 found a second night driver saves money. But the trucks come mostly between 23:00 and 02:00. Could a shorter shift do as well for less? dock_shift_options lists a second driver all night ($245), 4-hour shifts ($150) or 6-hour shifts ($200) starting at different times. Each can be combined with Day 48's faster forklift ($90). The carriers' promise: 90% of trucks start unloading within 30 minutes.

Drivers on shifts need a new SimPy trick. A driver who isn't on duty is held by a blocker process that has priority over the trucks. Create day49/shifts.py:

"""Day 49: the night dock with drivers on shifts. Each driver is available from `start` to `end` (minutes after 22:00;
end=None: until the last truck is unloaded), so a second driver can cover just the busy hours.

Import it:  from shifts import simulate_night_shifts, evaluate_option
"""
import numpy as np
import pandas as pd
import simpy


def simulate_night_shifts(rates, unload, doors, shifts, rng):
    """Like Day 46's simulate_night, but `shifts` lists (start, end) for each driver. A driver who isn't on shift is
    held by a 'blocker' with priority over the trucks; a driver whose shift ends finishes the truck in hand first."""
    env = simpy.Environment()
    dock_doors = simpy.Resource(env, capacity=doors)
    forklifts = simpy.PriorityResource(env, capacity=len(shifts))
    trucks = []

    def off_duty(start, end):
        if start > 0:
            with forklifts.request(priority=-1) as req:          # takes a driver before any truck can
                yield req
                yield env.timeout(start)                          # released when the shift starts
        if end is not None:
            yield env.timeout(end - env.now)
            req = forklifts.request(priority=-1)                  # the next free driver goes home
            yield req                                             # ... and is never released

    def truck(name, minutes):
        arrived = env.now
        with dock_doors.request() as door:
            yield door
            with forklifts.request(priority=0) as driver:
                yield driver
                start = env.now
                yield env.timeout(minutes)
        trucks.append((name, arrived, start, env.now))

    def arrivals():
        k = 0
        for hour, rate in enumerate(rates):                       # the same stream of draws as Day 46
            end = 60 * (hour + 1)
            while rate > 0:
                gap = rng.exponential(60 / rate)
                if env.now + gap >= end:
                    yield env.timeout(end - env.now)
                    break
                yield env.timeout(gap)
                k += 1
                env.process(truck(f"T{k}", unload()))
            else:
                yield env.timeout(end - env.now)

    for start, end in shifts:
        env.process(off_duty(start, end))
    env.process(arrivals())
    env.run()
    return pd.DataFrame(trucks, columns=["truck", "arrived", "start", "end"])


def evaluate_option(rates, unload_sampler, doors, shifts, nights, seed, free=60, per_hour=85.0, promise=30):
    """Simulate `nights` nights (the same nights for every option with the same seed: common random numbers).
    Returns one row per night: detention ($), the share of trucks that started within `promise` minutes, trucks."""
    rng = np.random.default_rng(seed)
    rows = []
    for _ in range(nights):
        t = simulate_night_shifts(rates, lambda: unload_sampler(rng), doors, shifts, rng)
        wait = (t.start - t.arrived).to_numpy()
        rows.append((float(np.maximum(wait - free, 0).sum() / 60 * per_hour), int((wait <= promise).sum()), len(t)))
    return pd.DataFrame(rows, columns=["detention", "on_time", "trucks"])

Then search all 20 options on the same 500 nights:

# ---------- 49.2 A decision with a promise: a second driver for the busy hours ----------
print("--- driver shifts")
log, settings = load_receiving(con)
rates, u = hourly_rates(log), log.unload_minutes.to_numpy()
options = con.sql("SELECT * FROM dock_shift_options").df()
FASTER, RENT = 0.85, 90.0                                                 # Day 48's faster forklift
kw = dict(free=settings["free_minutes_before_detention"], per_hour=settings["detention_per_hour"])


opt = options.set_index("option")


def shifts_for(name):
    """Driver 1 all night; driver 2 (if any) on the option's shift. A shift that runs to 06:00 stays until done."""
    o = opt.loc[name]
    if o.hours == 0:
        return [(0, None)]
    start, end = int(o.start_after_22h_minutes), int(o.start_after_22h_minutes + 60 * o.hours)
    return [(0, None), (start, None if end >= 480 else end)]


def run(name, forklift, nights, seed):
    scale = FASTER if forklift else 1.0
    n = evaluate_option(rates, lambda g: scale * u[g.integers(len(u))], 3, shifts_for(name), nights, seed, **kw)
    n["cost"] = n.detention + opt.cost_per_night[name] + (RENT if forklift else 0.0)
    return n


rows = []
for name in opt.index:
    for forklift in (False, True):
        n = run(name, forklift, 500, seed=49)                             # the same 500 nights for all 20 options
        rows.append((name, "faster" if forklift else "today", opt.cost_per_night[name] + (RENT if forklift else 0),
                     round(n.detention.mean(), 2), round(n.cost.mean(), 2), round(n.on_time.sum() / n.trucks.sum(), 3)))
table = pd.DataFrame(rows, columns=["second_driver", "forklift", "fixed_cost", "detention", "cost_a_night", "within_30_min"])
table["promise_kept"] = table.within_30_min >= 0.90
print(table.sort_values("cost_a_night").to_string(index=False))
--- driver shifts
second_driver forklift  fixed_cost  detention  cost_a_night  within_30_min  promise_kept
   4h_from_00    today       150.0      18.53        168.53          0.850         False
   4h_from_23    today       150.0      31.02        181.02          0.864         False
   4h_from_01    today       150.0      34.11        184.11          0.774         False
   6h_from_23    today       200.0       7.55        207.55          0.918          True
   6h_from_00    today       200.0       9.22        209.22          0.893         False
   6h_from_22    today       200.0      13.67        213.67          0.891         False
   4h_from_22    today       150.0      67.89        217.89          0.820         False
   4h_from_02    today       150.0      84.37        234.37          0.655         False
   4h_from_00   faster       240.0       5.01        245.01          0.911          True
   4h_from_23   faster       240.0       7.43        247.43          0.917          True
    all_night    today       245.0       5.64        250.64          0.934          True
   4h_from_01   faster       240.0      12.14        252.14          0.851         False
   4h_from_22   faster       240.0      21.67        261.67          0.889         False
   4h_from_02   faster       240.0      40.17        280.17          0.740         False
         none   faster        90.0     200.28        290.28          0.600         False
   6h_from_23   faster       290.0       1.60        291.60          0.955          True
   6h_from_00   faster       290.0       2.18        292.18          0.940          True
   6h_from_22   faster       290.0       4.04        294.04          0.936          True
    all_night   faster       335.0       1.21        336.21          0.965          True
         none    today         0.0     405.43        405.43          0.481         False
  • The cheapest options (4-hour shifts, $169–$184 a night) break the promise: only 85–86% of trucks start within 30 minutes.
  • The cheapest option that keeps it is a second driver from 23:00 to 05:00 ($200), at $207.55 a night with 91.8% within 30 minutes. That is $43 a night cheaper than a second driver all night.
  • The faster forklift doesn't earn its place once there are two drivers: the second driver already removes most of the waiting.
  • Without the promise, the 4-hour shift from 00:00 would win at $169. The promise costs about $39 a night. That is worth knowing before agreeing to it.

49.3 Check the winner on fresh nights

# ---------- 49.3 Check the winners on fresh nights ----------
print("--- fresh nights")
top = table[table.promise_kept].nsmallest(3, "cost_a_night")
fresh = {}
for r in top.itertuples():
    n = fresh[(r.second_driver, r.forklift)] = run(r.second_driver, r.forklift == "faster", 2_000, seed=4_900)
    m, h = mean_ci(n.cost)
    print(f"{r.second_driver:>11} + {r.forklift:<6} forklift: search said ${r.cost_a_night:,.2f}, "
          f"2,000 fresh nights ${m:,.2f} +/- ${h:,.2f}; within 30 min {n.on_time.sum() / n.trucks.sum():.3f}")
(k1, n1), (k2, n2) = list(fresh.items())[:2]
d, h = paired_ci(n2.cost, n1.cost)
print(f"{k2[0]} + {k2[1]} forklift costs ${d:,.2f} +/- ${h:,.2f} a night more than {k1[0]} (same fresh nights)")
--- fresh nights
 6h_from_23 + today  forklift: search said $207.55, 2,000 fresh nights $205.48 +/- $1.66; within 30 min 0.917
 4h_from_00 + faster forklift: search said $245.01, 2,000 fresh nights $245.38 +/- $1.54; within 30 min 0.910
 4h_from_23 + faster forklift: search said $247.43, 2,000 fresh nights $248.38 +/- $2.12; within 30 min 0.919
4h_from_00 + faster forklift costs $39.91 +/- $1.07 a night more than 6h_from_23 (same fresh nights)

The winner holds up on 2,000 new nights: $205.48 ± $1.66 a night, with 91.7% of trucks within 30 minutes. The runner-up costs $40 a night more, with an interval of ±$1. Here the optimizer's curse is mild, because 500 nights of CRN separate the options well. It is never zero, so always re-check.

Decision it supports: choosing among many options when each can only be evaluated by simulation, including under a service promise.

Other decisions you can support the same way: staffing levels by hour in a call centre · reorder points and quantities (Module 6) · the number of checkouts open by hour · buffer sizes on a production line.

The planted bug

day49/bug_new_seeds.py is a colleague's version of the search: a new seed for every option ("more randomness is more realistic") and 100 nights each. Run it.

def search(base, common, nights=100):
    rows = []
    for k, o in enumerate(options.itertuples()):
        start, end = o.start_after_22h_minutes, o.start_after_22h_minutes + 60 * o.hours
        shifts = [(0, None)] + ([] if o.hours == 0 else [(start, None if end >= 480 else end)])
        seed = base if common else base + k                                    # the bug: a new seed for each option
        n = evaluate_option(rates, lambda g: u[g.integers(len(u))], 3, shifts, nights, seed=seed)
        rows.append((o.option, round(n.detention.mean() + o.cost_per_night, 2), round(n.on_time.sum() / n.trucks.sum(), 3)))
    t = pd.DataFrame(rows, columns=["second_driver", "cost_a_night", "within_30_min"])
    kept = t[t.within_30_min >= 0.90]
    return t, (kept.nsmallest(1, "cost_a_night").iloc[0] if len(kept) else pd.Series({"second_driver": "no option"}))


t, best = search(490, common=False)
print(t.sort_values("cost_a_night").to_string(index=False))
print(f"choose {best.second_driver}: ${best.cost_a_night:,.2f} a night, promise kept ({best.within_30_min:.3f})")
print("--- the same search, 20 starting seeds")
for label, common, nights in [("new seed for each option, 100 nights", False, 100),
                              ("same seed for every option, 100 nights", True, 100),
                              ("same seed for every option, 500 nights", True, 500)]:
    picks = pd.Series([search(1_000 * b, common, nights)[1].second_driver for b in range(1, 21)]).value_counts()
    print(f"{label:>39}: " + ", ".join(f"{name} {k}x" for name, k in picks.items()))
What happens, and why
second_driver  cost_a_night  within_30_min
   4h_from_00        161.24          0.848
   4h_from_23        175.02          0.846
   4h_from_01        183.83          0.794
   4h_from_22        196.73          0.843
   6h_from_23        206.80          0.925
   6h_from_00        208.82          0.903
   4h_from_02        209.06          0.662
   6h_from_22        209.86          0.904
    all_night        247.91          0.944
         none        339.67          0.508
choose 6h_from_23: $206.80 a night, promise kept (0.925)
--- the same search, 20 starting seeds
   new seed for each option, 100 nights: 6h_from_23 10x, 6h_from_00 7x, 6h_from_22 2x, all_night 1x
 same seed for every option, 100 nights: 6h_from_23 13x, 6h_from_00 3x, all_night 3x, no option 1x
 same seed for every option, 500 nights: 6h_from_23 16x, 6h_from_00 4x

This time it happens to pick the right option. But run the same search from 20 starting seeds and it picks the 23:00 shift only half the time. The rest of the time it picks the 00:00 shift, which breaks the promise in the 500-night search (89.3%), or a dearer option. With a new seed for each option, the comparison mixes the options' differences with the nights' differences.

Common random numbers help (13 of 20), and CRN with 500 nights helps more (16 of 20). The remaining picks of the 00:00 shift happen because it sits right at the 90% line: no amount of simulation makes a near-tie decisive. Fixes: use the same random numbers for every option; run enough nights for the promise, not just the cost; re-check the top few on fresh runs; and when two options are this close, choose the one with a safety margin.

Mini-project: empty shelves on at most 10% of days

Store Operations wants empty croissant shelves on at most 10% of store-days, chain-wide, while making as much profit as possible. Day 45's rules give 22% (critical ratio) or 3.5% (95% in stock at every store-day). Search between them.

Hint: start from the critical-ratio quantities. Repeatedly add one croissant where it buys the most in-stock days per dollar of profit lost, until the chain reaches 10%. Do the search on 1,000 simulated weeks, then check it on 1,000 fresh ones.

Solution
"""Day 49 mini-project: Store Operations wants empty croissant shelves on at most 10% of store-days (chain-wide).
Find the most profitable quantities that keep that promise. Search on 1,000 simulated weeks: start from the
critical-ratio quantities (Day 45) and add one croissant at a time where it buys the most in-stock days per dollar
of profit lost. Then check the plan on fresh weeks.

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

import duckdb
import numpy as np
import pandas as pd
from scipy import stats

sys.path.insert(0, "day45")
from stockouts import simulate_store_days, store_day_means

pd.set_option("display.width", 160)
con = duckdb.connect("northbound.duckdb", read_only=True)
price, cost = con.sql("SELECT transfer_price, ingredient_cost FROM bakery_range WHERE sku = 'BK-CR'").fetchall()[0]
means = store_day_means(con)
demand, _, _ = simulate_store_days(means, np.zeros(len(means), dtype=int), np.random.default_rng(49), weeks=1_000)


def score(q, demand):
    sold = np.minimum(demand, q)
    return (price * sold - cost * q).sum() / len(demand), (demand > q).mean()     # profit a week, share of days out


q = stats.poisson.ppf((price - cost) / price, means["mean"]).astype(int)
profit, out = score(q, demand)
steps = 0
while out > 0.10:
    # for each store-day: one more croissant gains in-stock days (P(demand = q)) and costs profit
    gain = (demand == q).mean(axis=0)
    lost = cost - price * (demand > q).mean(axis=0)
    k = int(np.argmax(gain / np.maximum(lost, 1e-9)))
    q[k] += 1
    profit, out = score(q, demand)
    steps += 1
print(f"{steps} croissants added to the critical-ratio plan; search weeks: profit ${profit:,.2f} a week, days out {out:.3f}")

fresh, _, _ = simulate_store_days(means, np.zeros(len(means), dtype=int), np.random.default_rng(4_900), weeks=1_000)
rows = []
for name, quantity in [("today: the average", np.round(means["mean"]).astype(int).to_numpy()),
                       ("critical ratio (Day 45)", stats.poisson.ppf((price - cost) / price, means["mean"]).astype(int)),
                       ("at most 10% of days out", q),
                       ("each store-day 90% in stock", stats.poisson.ppf(0.90, means["mean"]).astype(int))]:
    p, o = score(quantity, fresh)
    rows.append((name, int(quantity.sum()), round(o, 3), round(p, 2)))
print("fresh weeks:")
print(pd.DataFrame(rows, columns=["rule", "croissants_a_week", "days_out", "profit_a_week"]).to_string(index=False))
342 croissants added to the critical-ratio plan; search weeks: profit $5,678.10 a week, days out 0.100
fresh weeks:
                       rule  croissants_a_week  days_out  profit_a_week
         today: the average               1463     0.392        5690.99
    critical ratio (Day 45)               1774     0.222        5884.21
    at most 10% of days out               2116     0.100        5679.57
each store-day 90% in stock               2234     0.074        5542.87
  • The search adds 342 croissants a week. On fresh weeks the chain is out on 10.0% of store-days, and profit is $5,680 a week: about $205 a week less than the critical-ratio rule, and the same as today's profit with a quarter of the empty shelves.
  • The obvious alternative, 90% in stock at every store-day, sends 118 more croissants and earns $137 a week less than the search. The search puts the extra croissants where they are cheapest: at stores where one more croissant often prevents an empty shelf.

Memo: "A 10% limit on empty shelves costs about $205 a week against the most profitable rule ($10,700 a year). The cheapest way to meet it is to send extra croissants to the stores where they do the most good, not the same service level everywhere."

Commit

git add .
git commit -m "Day 49: simulation-optimization"
git push

Day 49 checklist

  • I can search a decision with a simulator as the objective, using the same random numbers for every option.
  • I can model resources that change over time in SimPy (blockers with priority).
  • I handle a promise as a constraint the simulation estimates, and I know what it costs.
  • I re-check the winner on fresh runs.
  • I can run a greedy search on sample paths when there are too many options to try them all.