46.1 What the log says
receiving_log: 306 trucks over 24 nights (22:00 to 06:00), with the arrival time and how long each took to unload. receiving_settings: 3 doors, 1 night forklift driver (Day 32's coverage), detention of $85 an hour after the first hour. Create day46/dock.py:
"""Day 46: the night receiving dock at DC-MTL as a discrete-event simulation with SimPy.
A truck needs a free door and a free forklift driver to unload.
Import it: from dock import load_receiving, hourly_rates, simulate_night, simulate_nights
"""
import numpy as np
import pandas as pd
import simpy
START = 22 * 60 # 22:00, in minutes after midnight
def load_receiving(con):
log = con.sql("SELECT * FROM receiving_log ORDER BY night_of, arrival_minute").df()
log["minute_of_night"] = (log.arrival_minute - START) % 1440 # minutes after 22:00
settings = dict(con.sql("SELECT * FROM receiving_settings").fetchall())
return log, settings
def hourly_rates(log):
"""Trucks an hour, by hour of the night, averaged over the nights in the log."""
nights = log.night_of.nunique()
hour = (log.minute_of_night // 60).astype(int)
return (hour.value_counts().sort_index() / nights).reindex(range(8), fill_value=0.0).to_numpy()
def simulate_night(rates, unload, doors, drivers, rng, trace=None):
"""One night. rates: trucks an hour for each hour from 22:00; unload(): one unloading time in minutes.
Returns one row per truck: arrival, start of unloading, end (minutes after 22:00)."""
env = simpy.Environment()
dock_doors = simpy.Resource(env, capacity=doors)
forklifts = simpy.Resource(env, capacity=drivers)
trucks = []
def truck(name, minutes):
arrived = env.now
with dock_doors.request() as door:
yield door # wait for a door
with forklifts.request() as driver:
yield driver # then for a driver
start = env.now
if trace is not None:
trace.append(f"{env.now:6.1f} {name} starts unloading ({minutes:.0f} min)")
yield env.timeout(minutes)
trucks.append((name, arrived, start, env.now))
def arrivals():
k = 0
for hour, rate in enumerate(rates): # a Poisson process, rate changing each hour
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
if trace is not None:
trace.append(f"{env.now:6.1f} T{k} arrives")
env.process(truck(f"T{k}", unload()))
else:
yield env.timeout(end - env.now)
env.process(arrivals())
env.run() # until every truck is unloaded
return pd.DataFrame(trucks, columns=["truck", "arrived", "start", "end"])
def simulate_nights(rates, unload_sampler, doors, drivers, nights, seed, free=60, per_hour=85.0):
"""Many independent nights. Detention: carriers charge per_hour for waiting beyond `free` minutes."""
rng = np.random.default_rng(seed)
rows = []
for _ in range(nights):
t = simulate_night(rates, lambda: unload_sampler(rng), doors, drivers, rng)
wait = t.start - t.arrived
rows.append({"trucks": len(t), "mean_wait": wait.mean() if len(t) else 0.0, "max_wait": wait.max() if len(t) else 0.0,
"waited_over_free": int((wait > free).sum()),
"detention": float(np.maximum(wait - free, 0).sum() / 60 * per_hour),
"last_done": t.end.max() if len(t) else 0.0})
return pd.DataFrame(rows)
Then day46/run_dock.py:
# ---------- 46.1 What the log says ----------
per_night = log.groupby("night_of").size()
print(f"{len(log)} trucks over {log.night_of.nunique()} nights: {per_night.mean():.2f} a night "
f"(variance {per_night.var():.2f}; Poisson would give variance = mean)")
rates = hourly_rates(log)
print("trucks an hour:", " ".join(f"{22 + h if 22 + h < 24 else h - 2:02d}h {r:.2f}" for h, r in enumerate(rates)))
u = log.unload_minutes.to_numpy()
shape, _, scale = stats.gamma.fit(u, floc=0)
print(f"unloading: mean {u.mean():.2f} min, sd {u.std(ddof=1):.2f} (coefficient of variation {u.std(ddof=1) / u.mean():.2f}); "
f"gamma fit shape {shape:.2f}, scale {scale:.2f}")
print(f"settings: {settings}")
306 trucks over 24 nights: 12.75 a night (variance 9.67; Poisson would give variance = mean)
trucks an hour: 22h 0.92 23h 1.75 00h 2.67 01h 2.92 02h 0.92 03h 1.12 04h 1.58 05h 0.88
unloading: mean 29.75 min, sd 15.03 (coefficient of variation 0.51); gamma fit shape 4.01, scale 7.42
settings: {'doors': 3, 'night_forklift_drivers': 1, 'free_minutes_before_detention': 60, 'detention_per_hour': 85, 'extra_driver_cost_per_night': 245}
- About 13 trucks a night, Poisson-like (the variance is close to the mean).
- But not evenly: almost 3 an hour between midnight and 02:00, under 1 an hour at either end of the night. Each truck takes about 30 minutes to unload (variable: a coefficient of variation of 0.5), so one driver can handle 2 an hour.
46.2 SimPy: processes, resources, events
Four ideas are all of SimPy:
- An
Environmentkeeps the simulation clock; nothing happens between events. - A process is a Python generator:
truck()is one truck's life, andarrivals()creates trucks. yield env.timeout(minutes)lets time pass for that process (unloading, the gap to the next arrival).- A
Resource(doors, drivers) has a capacity;with resource.request() as req: yield reqwaits in line until one is free, and releases it at the end of thewithblock.
# ---------- 46.2 SimPy in one night ----------
trace = []
night = simulate_night(rates, lambda: 30.0, int(settings["doors"]), int(settings["night_forklift_drivers"]),
np.random.default_rng(3), trace=trace)
print("the first events of one night (minutes after 22:00):")
for line in trace[:8]:
print(" ", line)
print(night.head(5).round(1).to_string(index=False))
the first events of one night (minutes after 22:00):
7.2 T1 arrives
7.2 T1 starts unloading (30 min)
32.7 T2 arrives
37.2 T2 starts unloading (30 min)
127.7 T3 arrives
127.7 T3 starts unloading (30 min)
133.5 T4 arrives
143.3 T5 arrives
truck arrived start end
T1 7.2 7.2 37.2
T2 32.7 37.2 67.2
T3 127.7 127.7 157.7
T4 133.5 157.7 187.7
T5 143.3 187.7 217.7
Read the trace: T2 arrives at 32.7 but starts at 37.2, when T1 finishes; T4 and T5 queue behind T3. The table is the same night, one row per truck.
46.3 Five hundred nights
# ---------- 46.3 Five hundred nights ----------
unload = lambda rng: u[rng.integers(len(u))] # resample the logged unloading times
nights = simulate_nights(rates, unload, int(settings["doors"]), int(settings["night_forklift_drivers"]), 500, seed=46,
free=settings["free_minutes_before_detention"], per_hour=settings["detention_per_hour"])
print(nights.describe().loc[["mean", "50%", "max"]].round(2).to_string())
print(f"nights with more than $800 of detention: {(nights.detention > 800).mean():.1%}; "
f"last truck done after 06:00 (480 min) on {(nights.last_done > 480).mean():.1%} of nights")
trucks mean_wait max_wait waited_over_free detention last_done
mean 12.97 47.95 108.99 4.64 417.05 510.96
50% 13.00 36.20 92.27 3.00 83.85 500.56
max 24.00 225.84 400.84 21.00 4313.81 817.55
nights with more than $800 of detention: 17.2%; last truck done after 06:00 (480 min) on 65.8% of nights
With one driver, trucks wait 48 minutes on average, and the dock pays $417 of detention a night on average (but $84 on a typical night: a few bad nights, with a peak-hour pile-up, cost thousands). On two nights in three the last truck isn't unloaded until after 06:00. Average figures are dominated by the bad nights: report the distribution.
Decision it supports: how many doors, people or machines a process needs, when arrivals and work times vary.
Other decisions you can support the same way: checkout lanes · hospital beds and nurses · call-centre agents · machines in a factory.
The planted bug
day46/bug_driver.py is a colleague's version of the truck: "request a door and a driver, then unload". Run it.
def truck(minutes):
arrived = env.now
with doors.request() as door:
yield door
driver = drivers.request() # ask for the forklift driver
waits.append(env.now - arrived)
yield env.timeout(minutes)
drivers.release(driver)
What happens, and why
average wait 0.98 min; trucks waiting over an hour: 0.0%
An average wait of one minute, and no truck ever waits an hour: the dock looks fine. drivers.request() is created but never yielded, so the truck doesn't wait for the driver: it starts unloading at once, and up to three trucks "share" the one driver. In SimPy, a request only holds the process back when you yield it; use with ... as req: yield req, which also releases it. Check a simulation against a case you can work out by hand (Day 47 does it with formulas).
Mini-project: a second night driver?
A second night forklift driver costs $245 a night. Would that pay for itself in detention? Would a fourth door help instead? Compare 3 doors with 1, 2 and 3 drivers, and 4 doors with 1 driver, on the same 500 nights.
Solution
"""Day 46 mini-project: hire a second night forklift driver ($245 a night) to cut detention charges?
And would a fourth door help instead?
Run from the repository root (after day06/load_tables.py): python day46/mini_project_driver.py
"""
import sys
import duckdb
import pandas as pd
sys.path.insert(0, "day46")
from dock import hourly_rates, load_receiving, simulate_nights
pd.set_option("display.width", 160)
con = duckdb.connect("northbound.duckdb", read_only=True)
log, settings = load_receiving(con)
rates, u = hourly_rates(log), log.unload_minutes.to_numpy()
rows = []
for doors, drivers in [(3, 1), (4, 1), (2, 2), (3, 2), (3, 3)]:
n = simulate_nights(rates, lambda rng: u[rng.integers(len(u))], doors, drivers, 500, seed=46, # same 500 nights
free=settings["free_minutes_before_detention"], per_hour=settings["detention_per_hour"])
extra = (drivers - 1) * settings["extra_driver_cost_per_night"]
rows.append((doors, drivers, round(n.mean_wait.mean(), 2), round(n.max_wait.mean(), 1), round(n.waited_over_free.mean(), 2),
round(n.detention.mean(), 2), extra, round(n.detention.mean() + extra, 2)))
t = pd.DataFrame(rows, columns=["doors", "drivers", "mean_wait", "longest_wait", "trucks_over_an_hour", "detention",
"extra_drivers", "cost_a_night"])
print(t.to_string(index=False))
doors drivers mean_wait longest_wait trucks_over_an_hour detention extra_drivers cost_a_night
3 1 47.95 109.0 4.64 417.05 0 417.05
4 1 47.95 109.0 4.64 417.05 0 417.05
2 2 5.22 23.1 0.18 3.09 245 248.09
3 2 5.22 23.1 0.18 3.09 245 248.09
3 3 0.90 6.0 0.00 0.00 490 490.00
- A second driver pays: detention falls from $417 to $3 a night, so the dock costs $248 a night instead of $417: about $169 a night saved ($53,000 a year over 312 nights), and trucks wait 5 minutes instead of 48.
- A fourth door changes nothing: the driver is the bottleneck, not the doors. Two doors would be enough with two drivers.
- A third driver isn't worth it: it saves the last $3 of detention for $245.
Memo to the DC manager: "Add a second forklift driver on the night shift ($245 a night). It cuts carriers' detention charges by about $414 a night and gets every truck unloaded by 06:00 on most nights. Don't build a fourth door. The roster change goes into the Day 32 coverage table (night forklift: 2)."
Commit
git add .
git commit -m "Day 46: discrete-event simulation of the receiving dock"
git push
Day 46 checklist
- I can write a SimPy model with processes, timeouts and resources.
- I can model a task that needs two resources at once.
- I can replicate a simulation over many nights and report the distribution.
- I
yieldevery resource request (or usewith). - I found the bottleneck and priced the fix.