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

Monte Carlo of a Plan

With Day 42's inputs, today you simulate two whole plans: the bakery's week (Day 6) and the morning routes (Day 37). You report risk, not just averages (percentiles, the bad tail, the chance of a bad outcome), and learn how many runs a simulation needs before its numbers can be trusted.

▶
Video for Day 43 coming soon

In this lesson

Today's 5-hour plan

LessonProjectBreakCommit
0:00–0:45
43.1 The production plan
0:45–1:45
43.2 How many runs?
1:45–2:00
Break
2:00–2:45
43.3 The morning routes
2:45–3:45
Risk measures; a planted bug
3:45–4:00
Break
4:00–4:45
Mini-project: plan with a buffer
4:45–5:00
Commit with Git + checklist

43.1 The production plan

Create day43/plan_risk.py:

"""Day 43: Monte Carlo of two plans, the Day 6 production plan and the Day 37 morning routes.

Import it:  from plan_risk import demand_sampler, simulate_bakery, simulate_routes, risk_summary
"""
import numpy as np
import pandas as pd

from inputs import weekly_errors
from montecarlo import bakery_profit, drive_routes


def demand_sampler(con, rng):
    """One week of demand: each product's forecast times a forecast error drawn from history (a bootstrap):
    bread from BK-SD and BK-WW's errors, everything else from BK-CR's (no history of its own)."""
    e = weekly_errors(con)
    pools = {"bread": e[e.sku.isin(["BK-SD", "BK-WW"])].ratio.to_numpy(), "other": e[e.sku == "BK-CR"].ratio.to_numpy()}

    def week(cap, category):
        return {p: c * rng.choice(pools["bread" if category[p] == "bread" else "other"]) for p, c in cap.items()}
    return week


def simulate_bakery(make, cap, category, econ, sampler, runs):
    rows = []
    for _ in range(runs):
        demand = sampler(cap, category)
        profit = bakery_profit(make, demand, econ)
        unsold = sum(max(0.0, x - demand[p]) for p, x in make.items())
        short = sum(max(0.0, demand[p] - x) for p, x in make.items())     # products the plan makes
        rows.append((profit, unsold, short))
    return pd.DataFrame(rows, columns=["profit", "batches_unsold", "batches_short"])


def simulate_routes(plan, stops, ids, minutes, morning, runs):
    """morning() picks the weather and returns (weather, trip_factor). One row per simulated morning."""
    rows = []
    for _ in range(runs):
        weather, factor = morning()
        late = drive_routes(plan, stops, ids, minutes, factor)
        rows.append({"weather": weather, "late": sum(v > 0 for v in late.values()),
                     "late_minutes": sum(late.values()), **{s: v > 0 for s, v in late.items()}})
    return pd.DataFrame(rows)


def risk_summary(x, worst=0.05):
    """Mean, spread and the bad tail of a simulated result (bigger is better)."""
    x = np.sort(np.asarray(x))
    k = max(1, int(round(worst * len(x))))
    return {"mean": x.mean(), "sd": x.std(ddof=1), "p5": np.quantile(x, 0.05), "median": np.median(x),
            "p95": np.quantile(x, 0.95), "mean_of_worst_5pct": x[:k].mean()}

demand_sampler resamples the real forecast errors (Day 42): bread from sourdough and whole-wheat history, everything else from croissants. Then day43/run_monte_carlo.py:

# ---------- 43.1 The production plan ----------
d = load_data(con)
m = build_model(d)
solve(m)
make = {p: pyo.value(m.x[p]) for p in m.P if pyo.value(m.x[p]) > 1e-6}
econ = bakery_economics(con)
sims = simulate_bakery(make, d["cap"], d["category"], econ, demand_sampler(con, rng), 10_000)
print(f"Day 6 plan, 10,000 simulated weeks (the model promised $108,351.28):")
print(pd.Series(risk_summary(sims.profit)).map("${:,.2f}".format).to_string())
print(f"weeks below $100,000: {(sims.profit < 100_000).mean():.1%}; batches thrown away {sims.batches_unsold.mean():.1f} "
      f"and short {sims.batches_short.mean():.1f} a week on average")
Day 6 plan, 10,000 simulated weeks (the model promised $108,351.28):
mean                  $105,821.95
sd                      $1,510.53
p5                    $102,804.44
median                $106,275.20
p95                   $107,478.84
mean_of_worst_5pct    $101,648.78
weeks below $100,000: 0.4%; batches thrown away 6.6 and short 20.9 a week on average

With the errors the bakery really has, the plan earns $105,822 a week on average, $2,529 less than promised (less than Day 41's guess, because bread errors are only 4–5%). One week in twenty earns less than $102,804, and those bad weeks average $101,649. Report a plan with its spread and its bad tail, not with one number:

MeasureWhat it answers
MeanWhat we earn over many weeks
Standard deviationHow much one week moves around the mean
5th and 95th percentilesA bad week and a good week
Mean of the worst 5% (CVaR)How bad the bad weeks are on average (Day 58)
P(profit < target)How often we miss a target

43.2 How many runs?

A simulated average is itself random. Its standard error is the standard deviation of one run divided by n\sqrt{n}, and a 95% confidence interval is the average ± 1.96 standard errors.

# ---------- 43.2 How many runs? ----------
print("one simulated week's profit varies by about ${:,.0f} (sd); the average of n weeks by sd / sqrt(n):".format(sims.profit.std()))
for runs in (100, 1_000, 10_000, 100_000):
    x = simulate_bakery(make, d["cap"], d["category"], econ, demand_sampler(con, np.random.default_rng(runs)), runs).profit
    half = 1.96 * x.std(ddof=1) / np.sqrt(runs)
    print(f"{runs:>7,} runs: average ${x.mean():,.2f} +/- ${half:,.2f} (95% confidence)")
one simulated week's profit varies by about $1,511 (sd); the average of n weeks by sd / sqrt(n):
    100 runs: average $105,794.26 +/- $302.70 (95% confidence)
  1,000 runs: average $105,724.40 +/- $98.45 (95% confidence)
 10,000 runs: average $105,800.05 +/- $30.46 (95% confidence)
100,000 runs: average $105,789.19 +/- $9.58 (95% confidence)

Ten times more runs buys only 10≈3\sqrt{10} \approx 3 times more precision. 10,000 runs pin the average to ±$30, plenty to tell this plan from one that differs by $100; 100 runs (±$300) don't. Choose the number of runs from the precision the decision needs, and always print the interval.

43.3 The morning routes

Each simulated morning draws the weather from the log's mix, then every trip's actual / planned ratio from that weather's trips.

# ---------- 43.3 The morning routes ----------
stops, ids, km, minutes = load_run(con)
plan = solve_vrptw(stops, ids, km, minutes, load_fleet(con))
trips, _ = clean_trips(load_trips(con))
mornings = simulate_routes(plan, stops, ids, minutes, travel_sampler(trips, rng), 5_000)
print(f"Day 37 routes, 5,000 simulated mornings: {mornings.late.mean():.2f} late deliveries on average; "
      f"at least one late on {(mornings.late > 0).mean():.1%} of mornings")
print(mornings.groupby("weather").agg(mornings=("late", "size"), late_per_morning=("late", "mean"),
                                      any_late=("late", lambda x: (x > 0).mean()),
                                      late_minutes=("late_minutes", "mean")).round(3).to_string())
by_stop = mornings[[s for s in ids[1:]]].mean().sort_values(ascending=False)
print("most often late:", ", ".join(f"{s} {p:.1%} ({stops.name[s]}, closes {int(stops.window_close[s]) // 60:02d}:"
                                    f"{int(stops.window_close[s]) % 60:02d})" for s, p in by_stop.head(5).items()))
Day 37 routes, 5,000 simulated mornings: 0.91 late deliveries on average; at least one late on 69.4% of mornings
         mornings  late_per_morning  any_late  late_minutes
weather
clear        3636             0.741     0.602         8.246
rain         1243             1.208     0.932        16.365
snow          121             2.909     1.000        58.637
most often late: C18 64.7% (Cafe partner 18, closes 06:45), S34 7.6% (Northbound Laval 1, closes 07:00), C20 5.8% (Cafe partner 20, closes 06:15), C24 2.0% (Cafe partner 24, closes 06:45), C19 1.7% (Cafe partner 19, closes 07:15)
  • 0.91 late deliveries a morning; at least one on 69% of mornings. In snow, every morning has late deliveries.
  • One café, C18, is late on 65% of mornings. The route planner fitted it in just before its window closes, at the planned speed; at real speeds it's usually late. Simulation finds the fragile part of a plan, not just its average.

Decision it supports: how risky a plan is, and which parts of it fail first.

Other decisions you can support the same way: a budget's chance of overrunning · a project's chance of finishing on time · an investment's downside.

The planted bug

day43/bug_confidence.py compares the Day 6 plan with a plan that makes 5% more of everything, with 200 simulated weeks each. Run it.

for name, make, seed in [("Day 6 plan", base, 1), ("5% more of everything", {p: 1.05 * x for p, x in base.items()}, 2)]:
    x = simulate_bakery(make, d["cap"], d["category"], econ, demand_sampler(con, np.random.default_rng(seed)), 200).profit
    half = 1.96 * x.std() / len(x)                            # the 95% margin of the average
    print(f"{name:<22} ${x.mean():,.2f} +/- ${half:,.2f}")
What happens, and why
Day 6 plan             $105,642.61 +/- $16.44
5% more of everything  $105,287.28 +/- $18.49

The margins (±$16 and ±$18) are far too small: the code divides by nn instead of n\sqrt{n}. With 200≈14\sqrt{200} \approx 14 the margins are about ±$210: the two intervals overlap, and 200 runs can't tell these plans apart reliably. An overconfident simulation is worse than none: it settles decisions on noise. (Day 48 shows how to compare two plans with far fewer runs.)

Mini-project: plan with a buffer

Re-plan the morning routes (Day 37's model) with the matrix minutes multiplied by 1.00, 1.05, 1.10, 1.15 and 1.20. Simulate each plan on the same 2,000 mornings (same seed). What does each buffer cost a day, and what does it save in late deliveries?

Solution
"""Day 43 mini-project: plan the morning routes with padded travel times. Re-plan with the matrix minutes x 1.00,
1.05, 1.10, 1.15, 1.20, then simulate each plan on the same 2,000 mornings. What does each buffer cost a day,
and how many late deliveries does it save?

Run from the repository root (after day06/load_tables.py):  python day43/mini_project_buffer.py   (about 2 minutes)
"""
import sys

import duckdb
import numpy as np
import pandas as pd

for folder in ("day36", "day37", "day41", "day42", "day43"):
    sys.path.insert(0, folder)
from inputs import clean_trips, load_trips, travel_sampler
from plan_risk import simulate_routes
from routing import load_run
from vrptw import load_fleet, simulate, solve_vrptw

pd.set_option("display.width", 160)
con = duckdb.connect("northbound.duckdb", read_only=True)
stops, ids, km, minutes = load_run(con)
fleet = load_fleet(con)
trips, _ = clean_trips(load_trips(con))
rows = []
for buffer in (1.00, 1.05, 1.10, 1.15, 1.20):
    padded = np.ceil(minutes * buffer)
    plan = solve_vrptw(stops, ids, km, padded, fleet)
    cost, total_km, _ = simulate(plan, stops, ids, km, padded, fleet)
    # the same 2,000 mornings for every plan: same seed, same weather and trip draws in the same order
    sims = simulate_routes(plan, stops, ids, minutes, travel_sampler(trips, np.random.default_rng(7)), 2_000)
    types = pd.Series([r["type"] for r in plan]).value_counts().to_dict()
    rows.append((f"x{buffer:.2f}", f"{types.get('van', 0)} vans, {types.get('truck', 0)} trucks", round(cost, 2),
                 round(sims.late.mean(), 3), round((sims.late > 0).mean(), 3), round(sims.late_minutes.mean(), 1)))
t = pd.DataFrame(rows, columns=["buffer", "vehicles", "cost_per_day", "late_per_morning", "mornings_with_late",
                                "late_minutes"])
print(t.to_string(index=False))
buffer         vehicles  cost_per_day  late_per_morning  mornings_with_late  late_minutes
 x1.00 5 vans, 2 trucks        864.50             0.960               0.717          12.1
 x1.05 5 vans, 2 trucks        860.22             0.250               0.172           4.4
 x1.10 3 vans, 3 trucks        839.09             0.392               0.248           6.0
 x1.15 4 vans, 3 trucks        926.10             0.266               0.199           6.3
 x1.20 5 vans, 2 trucks        876.53             0.200               0.150           3.6
  • Any buffer helps a lot, and costs little: with ×1.05 the late deliveries fall from 0.96 to 0.25 a morning, and mornings with a late delivery from 72% to 17%, at about the same cost.
  • The numbers don't fall smoothly. Each buffer gives a different heuristic plan (Day 37's noise): ×1.10 is cheaper but later than ×1.05, ×1.15 uses an extra vehicle. Read the trend, not each row.
  • Every plan was simulated on the same mornings, so the differences come from the plans, not from different random weather (Day 48 makes this precise).

Memo to transport: "Plan the morning routes with travel times 5% above the matrix. It costs nothing measurable and cuts late café deliveries by about three quarters. Update the matrix itself from the trip log (Day 42) so that planned times match real ones."

Commit

git add .
git commit -m "Day 43: Monte Carlo of the production plan and the routes"
git push

Then run the tests: tests/test_simulation.py checks Days 41–43 (the plan's profit at the forecast, known queue and route answers, the cleaning rule, the error sizes, the risk summary). Add "day41", "day42", "day43" to the folders in conftest.py.

"""Module 5, Days 41-43: Monte Carlo building blocks."""
import numpy as np
import pandas as pd
import pyomo.environ as pyo
import pytest
from bakery import build_model, load_data, solve
from inputs import clean_trips, demand_error_sd, load_trips
from montecarlo import bakery_economics, bakery_profit, drive_routes, wait_in_line
from plan_risk import risk_summary


def test_profit_at_the_forecast_is_the_model_profit(con):
    d = load_data(con)
    m = build_model(d)
    solve(m)
    make = {p: pyo.value(m.x[p]) for p in m.P}
    assert bakery_profit(make, d["cap"], bakery_economics(con)) == pytest.approx(108_351.28, abs=0.01)


def test_queue_and_routes_known_answers():
    # trucks every 5 minutes, 10 minutes each: every truck waits 5 minutes longer than the one before
    assert list(wait_in_line(np.full(4, 5.0), np.full(4, 10.0))) == [0, 5, 10, 15]
    stops = pd.DataFrame({"window_open": [0, 0], "window_close": [100, 10], "service_minutes": [0, 2]}, index=["D", "A"])
    plan = [{"stops": [(1, 0)]}]
    assert drive_routes(plan, stops, ["D", "A"], [[0, 8], [8, 0]], lambda: 1.0) == {"A": 0.0}
    assert drive_routes(plan, stops, ["D", "A"], [[0, 8], [8, 0]], lambda: 1.5) == {"A": 2.0}


def test_cleaning_and_errors(con):
    clean, bad = clean_trips(load_trips(con))
    assert sorted(bad.trip_id) == ["T00041", "T00312", "T00903", "T01456"]
    sd = demand_error_sd(con)
    assert 0.03 < sd["bread"] < sd["viennoiserie"] < 0.12


def test_risk_summary():
    r = risk_summary(np.arange(1, 101))
    assert r["mean"] == 50.5 and r["mean_of_worst_5pct"] == 3.0
65 passed

Day 43 checklist

  • I can simulate a plan thousands of times with inputs resampled from data.
  • I report mean, spread, percentiles, the bad tail and the chance of missing a target.
  • I compute a confidence interval with the standard error (divide by n\sqrt{n}).
  • I choose the number of runs from the precision the decision needs.
  • I use simulation to find the fragile parts of a plan.
  • I compare plans on the same random numbers.