Update the course data
Copy the latest make_data.py from the Course data page and rebuild (python make_data.py, python day01/ladder.py, python day06/load_tables.py). New for Days 41–43: trip_log, six months of van trips with planned and actual minutes and the morning's weather (Day 42).
41.1 A production plan made for average demand
Monte Carlo simulation: replace an uncertain number with random draws, run the plan thousands of times, and look at the results. The tools are a random number generator (np.random.default_rng(seed): the seed makes runs repeatable) and a loop. Create day41/montecarlo.py:
"""Days 41-43: Monte Carlo helpers. A plan made with average numbers, played out against random ones.
Import it: from montecarlo import bakery_economics, bakery_profit, drive_routes, wait_in_line
"""
import numpy as np
def bakery_economics(con):
"""Per product: units per batch, price and ingredient cost per unit."""
df = con.sql("SELECT sku, units_per_batch, transfer_price, ingredient_cost FROM bakery_range ORDER BY sku").df()
return df.set_index("sku")
def bakery_profit(make, demand, econ):
"""One week's profit for batches made (dict) against batches demanded (dict): sell what is both made and
wanted; unsold bread is thrown away, so its ingredients are lost."""
total = 0.0
for p, x in make.items():
e = econ.loc[p]
sold = min(x, demand[p])
total += e.units_per_batch * (e.transfer_price * sold - e.ingredient_cost * x)
return total
def drive_routes(plan, stops, ids, minutes, trip_factor):
"""Drive the routes with random travel times: trip_factor() gives actual / planned minutes for one trip.
Leave when the dock opens, wait if early, unload, drive on. Returns {stop: minutes late (0 if on time)}."""
late = {}
for r in plan:
t, here = stops.window_open[ids[0]], 0
for node, _ in r["stops"]:
s = ids[node]
t += minutes[here][node] * trip_factor()
late[s] = max(0.0, t - stops.window_close[s])
t = max(t, stops.window_open[s]) + stops.service_minutes[s]
here = node
return late
def wait_in_line(arrival_gaps, service_times):
"""Waiting time of each truck at a single dock, first come first served (Lindley's recursion)."""
wait = np.zeros(len(service_times))
for k in range(1, len(service_times)):
wait[k] = max(0.0, wait[k - 1] + service_times[k - 1] - arrival_gaps[k])
return wait
Then day41/flaw.py. Day 6's plan makes 22 products at the forecast. Real demand is the forecast times an error, here a normal one with a standard deviation of 9% (BK-CR's history; Day 42 does better).
# ---------- 41.1 A production plan made for average demand ----------
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)
planned = bakery_profit(make, d["cap"], econ) # demand exactly as forecast
print(f"Day 6 plan: {len(make)} products, profit if demand is exactly the forecast: ${planned:,.2f}")
profits = []
for _ in range(RUNS): # demand = forecast x a random error, sd 9% (BK-CR's)
demand = {p: d["cap"][p] * rng.normal(1.0, 0.09) for p in make}
profits.append(bakery_profit(make, demand, econ))
profits = np.array(profits)
print(f"same plan, demand off by a typical forecast error: average ${profits.mean():,.2f} "
f"({profits.mean() - planned:+,.2f}); worst 5% of weeks below ${np.percentile(profits, 5):,.2f}")
Day 6 plan: 22 products, profit if demand is exactly the forecast: $108,351.28
same plan, demand off by a typical forecast error: average $102,741.89 (-5,609.39); worst 5% of weeks below $99,170.72
The model promised $108,351.28 a week. On average the same plan earns $102,741.89: $5,609 less. It's not bad luck. When demand is above the forecast, the bakery can't sell bread it didn't make; when demand is below, it throws bread away. Both errors cost money; neither earns any. Profit at average demand is not average profit.
41.2 Routes planned with average travel times
# ---------- 41.2 Routes planned with average travel times ----------
stops, ids, km, minutes = load_run(con)
fleet = load_fleet(con)
plan = solve_vrptw(stops, ids, km, minutes, fleet)
on_plan = drive_routes(plan, stops, ids, minutes, lambda: 1.0)
print(f"Day 37 routes at the planned travel times: {sum(v > 0 for v in on_plan.values())} late deliveries")
late_counts, any_late = [], 0
for _ in range(2_000): # each trip 0.85x to 1.4x the plan, typically 1.09x
late = drive_routes(plan, stops, ids, minutes, lambda: rng.lognormal(0.08, 0.12))
n = sum(v > 0 for v in late.values())
late_counts.append(n)
any_late += n > 0
print(f"with real travel times: {np.mean(late_counts):.2f} late deliveries a morning on average; "
f"at least one late on {any_late / 20:.1f}% of mornings")
Day 37 routes at the planned travel times: 0 late deliveries
with real travel times: 0.61 late deliveries a morning on average; at least one late on 60.8% of mornings
On paper, Day 37's routes are never late. With travel times that vary (each trip 0.85 to 1.4 times the plan), 6 mornings out of 10 have at least one late delivery. A plan that just meets a deadline at average speed misses it whenever traffic is slower than average, which is about half the time on each trip.
41.3 A dock that is busy exactly as often as it is free
Trucks arrive at the bakery's dock at random, and unloading takes 10 minutes on average, sometimes more, sometimes less. wait_in_line follows each truck through the line.
# ---------- 41.3 A dock that is busy exactly as often as it is free ----------
print("bakery dock, one truck unloaded at a time, average unloading 10 minutes, 200 arrivals:")
for every in (20.0, 12.5, 11.1, 10.5, 10.0):
waits = [wait_in_line(rng.exponential(every, 200), rng.exponential(10.0, 200)).mean() for _ in range(500)]
print(f" a truck every {every:4.1f} min on average (dock busy {10 / every:.0%}): average wait {np.mean(waits):5.1f} min")
bakery dock, one truck unloaded at a time, average unloading 10 minutes, 200 arrivals:
a truck every 20.0 min on average (dock busy 50%): average wait 9.8 min
a truck every 12.5 min on average (dock busy 80%): average wait 34.2 min
a truck every 11.1 min on average (dock busy 90%): average wait 61.1 min
a truck every 10.5 min on average (dock busy 95%): average wait 75.4 min
a truck every 10.0 min on average (dock busy 100%): average wait 93.5 min
"A truck every 10 minutes, 10 minutes each: the dock is exactly full" sounds fine with averages. In reality the line never clears: over 200 arrivals trucks wait 93 minutes on average, and the wait would keep growing on a longer day. Even at 80% busy, the wait is 34 minutes. Waiting grows much faster than the load (Day 47 gives the formula).
Decision it supports: whether a plan built on averages will actually work, and what it really earns.
Other decisions you can support the same way: project deadlines (the critical path at average task times is too short) · budgets built from average prices · staffing from average call volumes.
Why it happens (math corner, optional)
For a function and a random input , the average result equals the result at the average input only when is a straight line. Sales are : a bend, a concave function, so (Jensen's inequality). Lateness is , a convex function, so average lateness is more than the lateness at average times. Every plan has bends like these: capacity limits, deadlines, minimums. The flaw of averages is Jensen's inequality at work.
The planted bug
day41/bug_seed.py is a colleague's Monte Carlo of the Day 6 plan, "seeded so the results can be repeated". Run it.
profits = []
for run in range(10_000):
rng = np.random.default_rng(2041) # a fixed seed, so anyone gets the same answer
demand = {p: d["cap"][p] * rng.normal(1.0, 0.09) for p in make}
profits.append(bakery_profit(make, demand, econ))
What happens, and why
average $104,966.11, standard deviation $0.00, worst $104,966.11, best $104,966.11
10,000 runs, a standard deviation of zero, and an average that is simply one random week. The generator is created again inside the loop with the same seed, so every run draws the same numbers. Seed once, before the loop. A spread of exactly zero is a red flag in any simulation.
Mini-project: how many croissants?
The forecast for croissants (BK-CR) is 31 batches a week, and demand is off by about 9% either way. A batch of 50 sells for $7.00 a croissant and costs $2.00 in ingredients; unsold croissants are thrown away. Simulate the expected profit of making 26 to 36 batches. Is the forecast the best quantity?
Solution
"""Day 41 mini-project: how many batches of croissants (BK-CR) should the bakery make? The forecast is 31 batches,
and real demand is off by about 9% either way. Compare the expected profit of making 26 to 36 batches.
Run from the repository root (after day06/load_tables.py): python day41/mini_project_croissants.py
"""
import sys
import duckdb
import numpy as np
import pandas as pd
sys.path.insert(0, "day41")
from montecarlo import bakery_economics, bakery_profit
con = duckdb.connect("northbound.duckdb", read_only=True)
econ = bakery_economics(con)
forecast = con.sql("SELECT demand_cap_batches FROM bakery_range_forecast WHERE sku = 'BK-CR'").fetchall()[0][0]
e = econ.loc["BK-CR"]
print(f"BK-CR: {e.units_per_batch} croissants a batch, sold at ${e.transfer_price:.2f}, ingredients ${e.ingredient_cost:.2f}")
rng = np.random.default_rng(41)
demand = forecast * rng.normal(1.0, 0.09, 20_000) # the same 20,000 weeks for every choice
rows = []
for batches in range(26, 37):
profit = np.array([bakery_profit({"BK-CR": batches}, {"BK-CR": x}, econ) for x in demand])
unsold = np.maximum(batches - demand, 0).mean()
short = np.maximum(demand - batches, 0).mean()
rows.append((batches, round(profit.mean(), 2), round(unsold, 2), round(short, 2), round((demand > batches).mean(), 3)))
t = pd.DataFrame(rows, columns=["batches", "expected_profit", "batches_unsold", "batches_short", "chance_of_running_out"])
print(t.to_string(index=False))
best = t.loc[t.expected_profit.idxmax()]
print(f"best: {best.batches:.0f} batches, ${best.expected_profit:,.2f} a week "
f"(+${best.expected_profit - t.expected_profit[t.batches == forecast].iloc[0]:,.2f} against the forecast)")
BK-CR: 50.0 croissants a batch, sold at $7.00, ingredients $2.00
batches expected_profit batches_unsold batches_short chance_of_running_out
26 6486.17 0.04 5.04 0.965
27 6717.51 0.09 4.10 0.925
28 6930.53 0.20 3.20 0.858
29 7115.29 0.38 2.39 0.764
30 7260.96 0.68 1.69 0.637
31 7359.86 1.11 1.12 0.499
32 7409.98 1.69 0.69 0.361
33 7413.67 2.39 0.39 0.238
34 7379.39 3.20 0.20 0.142
35 7317.02 4.09 0.10 0.078
36 7236.65 5.04 0.04 0.038
best: 33 batches, $7,413.67 a week (+$53.81 against the forecast)
33 batches, two more than the forecast: $54 a week more. A batch short costs $250 of profit (a lost sale); a batch too many costs $100 of ingredients. Since running out costs more, it pays to bake a little extra. Every simulated quantity uses the same 20,000 weeks of demand, so the differences come from the choice, not from luck (Day 48).
This is the newsvendor problem, and Day 51 solves it with a formula: make the quantity that demand stays below with probability . Here that is batches.
Commit
git add .
git commit -m "Day 41: the flaw of averages"
git push
Day 41 checklist
- I can run a Monte Carlo simulation with a seeded generator and a loop.
- I showed that a plan's profit at average demand is not its average profit.
- I showed that deadlines met at average speed are missed often.
- I showed that a resource busy 100% of the time on average builds an endless line.
- I can explain the flaw with Jensen's inequality and the bends in a plan.
- I seed a generator once, outside the loop.