- States: what you know now.
- Actions: what you can do.
- Transitions: what happens next, with probabilities.
- Costs: what each step costs.
Dynamic programming solves an MDP exactly when the model is known. Reinforcement learning learns a policy from experience when it isn't. Today you do both for olive oil at DC-MTL, and see why a known model beats learning when you have one.
59.1 The MDP
mdp_settings: olive oil (AM-04) can also be bought from an overnight wholesaler. The DC orders in the evening and the cases arrive before the next day's demand, so the lead time doesn't need a place in the state.
| Element | Here |
|---|---|
| State | cases on hand in the evening, 0 to 600 |
| Action | cases to order tonight |
| Transition | tomorrow evening: , with drawn from the 182 days of history |
| Cost of a day | $150 if it orders, $15.10 per case short (lost margin), $0.0345 per case left over (holding) |
The Bellman equation for the average cost per day and the relative values :
The value of being at is the best action's cost today plus the value of where it leads. Create day59/mdp.py:
"""Day 59: an inventory Markov decision process for one DC item. Each evening the DC sees its stock x and orders a
cases from an overnight wholesaler; they arrive before the next day's demand. Unmet demand is lost.
Cost of a day: K if it orders + lost margin m per case short + holding h per case left at the end of the day.
Import it: from mdp import load_mdp, value_iteration, policy_cost, q_learning
"""
import numpy as np
def load_mdp(con):
s = dict(con.sql("SELECT * FROM mdp_settings").fetchall())
item, cap = s["item_id"], int(s["max_stock_cases"])
i = con.sql(f"SELECT cost_per_case, margin_per_case FROM dc_items WHERE item_id = '{item}'").fetchall()[0]
st = dict(con.sql("SELECT * FROM inventory_settings").fetchall())
hist = con.sql(f"SELECT cases FROM dc_daily_demand WHERE item_id = '{item}'").df().cases.to_numpy()
pmf = np.bincount(hist) / len(hist) # demand distribution: the history itself
return {"item": item, "cap": cap, "step": int(s["order_step_cases"]), "pmf": pmf, "history": hist,
"K": float(st["order_cost_per_po"]), "m": float(i[1]),
"h": float(i[0]) * float(st["holding_rate_per_year"]) / float(st["days_per_year"])}
def day_cost_and_next(p, pmf=None):
"""For every stock level y after delivery (0..cap): the expected cost of the day (lost margin + holding) and the
transition matrix to the next evening's stock max(y - D, 0)."""
pmf = p["pmf"] if pmf is None else pmf
n, dem = p["cap"] + 1, np.arange(len(pmf))
cost, trans = np.zeros(n), np.zeros((n, n))
for y in range(n):
short, left = np.maximum(dem - y, 0), np.maximum(y - dem, 0)
cost[y] = pmf @ (p["m"] * short + p["h"] * left)
np.add.at(trans[y], left, pmf)
return cost, trans
def value_iteration(p, tol=1e-6, max_iter=20_000, pmf=None):
"""Relative value iteration for the average cost a day. Returns the order-up-to level for each stock x
(the policy), the average cost a day, and the number of iterations."""
cost, trans = day_cost_and_next(p, pmf)
n = p["cap"] + 1
v = np.zeros(n)
for it in range(max_iter):
g = cost + trans @ v # value of starting the day at level y
best_up = np.minimum.accumulate(g[::-1])[::-1] # the best y >= x
arg_up = np.array([x + int(np.argmin(g[x:])) for x in range(n)])
new = np.minimum(g, p["K"] + best_up) # don't order, or order up to the best level
avg = new[0] - v[0]
new -= new[0]
if np.max(np.abs(new - v)) < tol:
v = new
break
v = new
order_up = np.where(p["K"] + best_up < g - 1e-9, arg_up, np.arange(n))
return order_up, avg, it + 1
def policy_cost(p, order_up, pmf=None):
"""Exact average cost a day of a stationary policy (order up to order_up[x] at stock x): the Markov chain's
stationary distribution. Also: orders a year and fill rate."""
pmf = p["pmf"] if pmf is None else pmf
cost, trans = day_cost_and_next(p, pmf)
n = p["cap"] + 1
y = np.asarray(order_up)
chain = trans[y] # evening x -> next evening, via y = order_up[x]
vals, vecs = np.linalg.eig(chain.T)
pi = np.real(vecs[:, np.argmin(np.abs(vals - 1))])
pi = pi / pi.sum()
orders = pi @ (y > np.arange(n))
dem = np.arange(len(pmf))
short = np.array([pmf @ np.maximum(dem - yy, 0) for yy in y])
return {"cost_a_day": float(pi @ (cost[y] + p["K"] * (y > np.arange(n)))), "orders_a_year": float(orders * 365),
"fill_rate": float(1 - (pi @ short) / (pmf @ dem)), "avg_stock": float(pi @ y)}
def q_learning(p, episodes, rng, days=365, gamma=0.999, alpha=0.05, eps=0.1, check_every=None):
"""Tabular Q-learning from simulated days (demand resampled from history). States are stock levels in buckets
of `step` cases; actions: order 0, step, 2 step, ... cases. It learns costs to go (minimize), with exploration
and learning rates that shrink as experience grows. Returns the greedy policy (order-up-to level for every
stock level) and a learning curve: the exact cost a day of the greedy policy every `check_every` years."""
step = p["step"]
buckets = p["cap"] // step + 1
actions = np.arange(buckets) * step
q = np.zeros((buckets, len(actions)))
allowed = np.array([[b * step + a <= p["cap"] for a in actions] for b in range(buckets)])
q[~allowed] = np.inf
curve, x = [], 0
for ep in range(episodes):
explore, rate = max(0.01, eps * (1 - ep / episodes)), alpha / (1 + ep / 50)
for _ in range(days):
b = x // step
ok = np.flatnonzero(allowed[b])
k = rng.choice(ok) if rng.random() < explore else ok[np.argmin(q[b, ok])]
y = x + actions[k]
d = p["history"][rng.integers(len(p["history"]))]
nxt = max(y - d, 0)
c = (p["K"] if k > 0 else 0.0) + p["m"] * max(d - y, 0) + p["h"] * nxt
q[b, k] += rate * (c + gamma * q[nxt // step].min() - q[b, k])
x = nxt
if check_every and (ep + 1) % check_every == 0:
curve.append((ep + 1, policy_cost(p, greedy(q, actions, p))["cost_a_day"]))
return greedy(q, actions, p), curve
def greedy(q, actions, p):
up = []
for x in range(p["cap"] + 1):
a = actions[int(np.argmin(q[x // p["step"]]))]
up.append(x + a if x + a <= p["cap"] else x)
return np.array(up)
Then day59/run_mdp.py:
# ---------- 59.1 The MDP ----------
print("--- the mdp")
mean, sd = p["history"].mean(), p["history"].std(ddof=1)
print(f"{p['item']}: demand {mean:.2f} +/- {sd:.2f} cases a day (0 to {p['history'].max()}); states 0..{p['cap']} cases; "
f"K ${p['K']:.0f} an order, lost margin ${p['m']:.2f} a case, holding ${p['h']:.4f} a case a day")
--- the mdp
AM-04: demand 17.74 +/- 8.72 cases a day (0 to 53); states 0..600 cases; K $150 an order, lost margin $15.10 a case, holding $0.0345 a case a day
59.2 Value iteration
Relative value iteration applies the Bellman equation repeatedly, from any starting values, until the values stop changing. For each level after delivery it computes : the day's expected cost plus the expected value of tomorrow. Then at each stock level it chooses between ordering nothing () and paying to reach the best level above .
# ---------- 59.2 Value iteration ----------
print("--- value iteration")
order_up, avg, iters = value_iteration(p)
orders_at = np.flatnonzero(order_up > np.arange(len(order_up)))
s_star, S_star = orders_at.max(), int(order_up[0])
print(f"converged in {iters} iterations; average cost ${avg:,.2f} a day")
print(f"the optimal policy: when stock is {s_star} or less, order up to {S_star}; otherwise order nothing "
f"(an (s, S) policy, s = {s_star}, S = {S_star})")
print("order-up-to level by evening stock: " + ", ".join(f"{x}->{order_up[x]}" for x in (0, 10, 20, s_star, s_star + 1, 60)))
--- value iteration
converged in 1572 iterations; average cost $14.09 a day
the optimal policy: when stock is 27 or less, order up to 415; otherwise order nothing (an (s, S) policy, s = 27, S = 415)
order-up-to level by evening stock: 0->415, 10->415, 20->415, 27->415, 28->28, 60->60
Nobody told the algorithm what shape the policy should have, yet it found an (s, S) policy: when stock falls to 27 cases or fewer, order up to 415; otherwise order nothing. Scarf proved in 1960 that with a fixed order cost, (s, S) is optimal for problems like this. Dynamic programming finds the right and without a formula.
59.3 Against the formulas
# ---------- 59.3 Against the formulas ----------
print("--- policies compared")
n = p["cap"] + 1
q_eoq = int(round(eoq(mean * 365, p["K"], p["h"] * 365)))
z = stats.norm.ppf(0.98)
policies = {
"optimal (s, S) by DP": order_up,
f"EOQ: s = 98% of a day's demand, Q = {q_eoq}": None,
"order up to the 98% quantile every day": np.maximum(np.arange(n), int(np.quantile(p["history"], 0.98))),
"order up to the average every day": np.maximum(np.arange(n), int(round(mean))),
}
s_eoq = int(round(mean + z * sd))
policies[f"EOQ: s = 98% of a day's demand, Q = {q_eoq}"] = np.where(np.arange(n) <= s_eoq,
np.minimum(np.arange(n) + q_eoq, p["cap"]), np.arange(n))
rows = []
for name, pol in policies.items():
r = policy_cost(p, pol)
rows.append((name, round(r["cost_a_day"], 2), round(r["orders_a_year"], 1), round(r["fill_rate"], 4), round(r["avg_stock"], 1)))
print(pd.DataFrame(rows, columns=["policy", "cost_a_day", "orders_a_year", "fill_rate", "avg_stock_after_delivery"])
.to_string(index=False))
--- policies compared
policy cost_a_day orders_a_year fill_rate avg_stock_after_delivery
optimal (s, S) by DP 14.09 16.2 0.9993 226.7
EOQ: s = 98% of a day's demand, Q = 393 14.24 16.5 0.9999 233.0
order up to the 98% quantile every day 152.65 365.0 0.9929 39.0
order up to the average every day 199.24 365.0 0.8166 18.0
- The EOQ policy from Day 52 costs $14.24 a day, only 1% above the optimum: the classic formulas are excellent here. Dynamic programming earns its keep where formulas don't exist, such as perishable stock, capacity limits or prices that change.
- Ordering every day costs ten times as much, because the order cost is paid 365 times a year. Ordering only up to the average every day is worse still: it pays the order cost daily and runs short (fill rate 82%).
59.4 Reinforcement learning: Q-learning
Suppose nobody knew the demand distribution, only how to act and see what happens. Q-learning learns , the cost to go after taking action in state , from experience. After each simulated day:
It explores (a random action 10% of the time at first) and acts greedily otherwise. Stock is grouped in buckets of 20 cases, and orders are multiples of 20, so the table stays small.
# ---------- 59.4 Reinforcement learning: Q-learning ----------
print("--- q-learning")
rng = np.random.default_rng(59)
learned, curve = q_learning(p, 1_000, rng, check_every=50)
c = np.array(curve)
for ep, cost in curve[1::2]:
print(f" after {ep:>4} simulated years: greedy policy costs ${cost:,.2f} a day")
print(f"DP optimum ${avg:,.2f}; Q-learning's greedy policy over the last 500 years: median ${np.median(c[10:, 1]):,.2f}, "
f"best ${c[:, 1].min():,.2f}, worst ${c[10:, 1].max():,.2f}")
print(f"its final policy: orders when stock <= {np.flatnonzero(learned > np.arange(n)).max()}, "
f"up to {int(learned[0])} from empty")
fig, ax = plt.subplots(figsize=(7, 3.6))
ax.plot(c[:, 0], c[:, 1], "o-", color="#3b82f6", label="Q-learning's greedy policy")
ax.axhline(avg, ls="--", color="#e5484d", label="dynamic programming (optimal)")
ax.set(xlabel="simulated years of experience", ylabel="average cost a day ($)", yscale="log",
title="Q-learning learns from experience, unevenly")
ax.set_yticks([15, 20, 30, 50, 100, 150], ["15", "20", "30", "50", "100", "150"])
ax.yaxis.set_minor_locator(matplotlib.ticker.NullLocator())
ax.spines[["top", "right"]].set_visible(False)
ax.legend(frameon=False, loc="upper left")
fig.tight_layout()
fig.savefig("figures/day59_qlearning.png", dpi=150)
print("saved figures/day59_qlearning.png")
--- q-learning
after 100 simulated years: greedy policy costs $14.36 a day
after 200 simulated years: greedy policy costs $14.63 a day
after 300 simulated years: greedy policy costs $18.73 a day
after 400 simulated years: greedy policy costs $15.18 a day
after 500 simulated years: greedy policy costs $142.79 a day
after 600 simulated years: greedy policy costs $22.65 a day
after 700 simulated years: greedy policy costs $34.69 a day
after 800 simulated years: greedy policy costs $16.40 a day
after 900 simulated years: greedy policy costs $17.46 a day
after 1000 simulated years: greedy policy costs $43.98 a day
DP optimum $14.09; Q-learning's greedy policy over the last 500 years: median $22.09, best $14.36, worst $142.79
its final policy: orders when stock <= 99, up to 580 from empty
saved figures/day59_qlearning.png

- After 100 simulated years, the greedy policy costs $14.36 a day, close to the optimal $14.09.
- But it doesn't stay there. A few states that are rarely visited keep wrong values, and when the greedy choice flips in one of them (say, order nothing when empty), the policy costs $143 a day. Over the last 500 years the median is $22.
- Dynamic programming used the model and solved it exactly in seconds. Q-learning needed a thousand simulated years and still isn't reliable.
- When you can write down the model, solve it. Reinforcement learning is for problems whose model is unknown or far too large: then the noise, the tuning and the need for a simulator are the price of having no model. Even then, test the learned policy, as here, before trusting it.
Decision it supports: a decision repeated over time, where each choice shapes the next situation.
Other decisions you can support the same way: when to replace a machine or a truck · pricing perishable goods as the sell-by date nears · admitting patients or bookings with limited capacity · when to rebalance a portfolio.
The planted bug
day59/bug_mean_demand.py runs value iteration with the average daily demand, "because the whole distribution is too slow". Run it.
mean = int(round(p["history"].mean()))
certain = np.zeros(mean + 1)
certain[mean] = 1.0 # every day sells exactly the average
order_up, avg, _ = value_iteration(p, pmf=certain)
s = np.flatnonzero(order_up > np.arange(len(order_up))).max()
print(f"policy: when stock is {s} or less, order up to {order_up[0]}; the model says ${avg:,.2f} a day")
r = policy_cost(p, order_up) # judged with the real demand distribution
print(f"with real demand: ${r['cost_a_day']:,.2f} a day, fill rate {r['fill_rate']:.4f}")
What happens, and why
policy: when stock is 17 or less, order up to 396; the model says $13.67 a day
with real demand: $14.51 a day, fill rate 0.9964
The model promises $13.67 a day, less than the true optimum ($14.09). Its policy, judged on real demand, costs $14.51. With demand certain, the model sees no reason for safety stock, so it reorders at 17 cases instead of 27 and runs short on bad days. This is Day 41's flaw of averages, inside a dynamic program. A DP is exactly as good as its transition probabilities; replacing them with averages throws away what the method is for.
Mini-project: what is the order cost worth?
The $150 cost of placing an order drives the policy. Purchasing could combine olive oil with coffee (same supplier) in one order, roughly halving the order cost per item, or automate ordering. Re-solve the DP for order costs of $0, $25, $75, $150 and $300. How do and move, and what is each reduction worth a year?
Solution
"""Day 59 mini-project: the cost of placing an order ($150) drives olive oil's policy. Purchasing could combine
olive oil with coffee (same supplier) in one order, roughly halving the order cost per item, or automate ordering.
Re-solve the DP for an order cost of $0, $25, $75, $150 and $300. How do s and S move, and what is each
reduction worth a year?
Run from the repository root (after day06/load_tables.py): python day59/mini_project_order_cost.py
"""
import sys
import duckdb
import numpy as np
import pandas as pd
sys.path.insert(0, "day59")
from mdp import load_mdp, policy_cost, value_iteration
pd.set_option("display.width", 160)
con = duckdb.connect("northbound.duckdb", read_only=True)
p = load_mdp(con)
rows = []
for k in (0, 25, 75, 150, 300):
q = {**p, "K": float(k)}
order_up, avg, _ = value_iteration(q)
orders = np.flatnonzero(order_up > np.arange(len(order_up)))
r = policy_cost(q, order_up)
rows.append((k, int(orders.max()), int(order_up[0]), round(avg, 2), round(r["orders_a_year"], 1),
round(r["avg_stock"], 1), round(r["fill_rate"], 4)))
t = pd.DataFrame(rows, columns=["order_cost", "s", "S", "cost_a_day", "orders_a_year", "avg_stock", "fill_rate"])
t["saving_a_year_vs_150"] = ((t.cost_a_day[t.order_cost == 150].item() - t.cost_a_day) * 365).round(0)
print(t.to_string(index=False))
order_cost s S cost_a_day orders_a_year avg_stock fill_rate saving_a_year_vs_150
0 52 53 1.22 365.0 53.0 1.0000 4698.0
25 32 187 6.23 39.1 115.0 0.9993 2869.0
75 29 302 10.19 22.8 171.1 0.9993 1424.0
150 27 415 14.09 16.2 226.7 0.9993 0.0
300 25 575 19.63 11.5 305.7 0.9993 -2022.0
- S moves with the order cost (53 → 575 cases), roughly like EOQ's . s barely moves (52 → 25): the reorder point protects against demand, and demand doesn't change.
- Halving the order cost to $75 (joint ordering with coffee) saves about $1,400 a year for olive oil alone, with the same service. Automating to $25 saves $2,900.
- With a free order, the DP orders every day up to 53 cases (a base-stock policy) and never runs short.
Note to Purchasing: "Ordering olive oil with coffee in one purchase order would save about $1,400 a year on this item alone; across the six items, Day 60 finds more."
Commit
git add .
git commit -m "Day 59: MDPs, dynamic programming and Q-learning"
git push
Day 59 checklist
- I can define states, actions, transitions and costs of an MDP, and write its Bellman equation.
- I can solve an MDP with (relative) value iteration and read the policy's structure.
- I can evaluate a policy exactly through its stationary distribution.
- I can train a tabular Q-learning agent, and judge it against the exact solution.
- I know when to use dynamic programming and when reinforcement learning is worth its cost.