Inventory control¶
A company keeps stock in a central warehouse and in four shops. Every day each location checks its stock and decides whether to order: the warehouse from a supplier, the shops from the warehouse. Too much stock costs money to hold, too little loses sales. The question is the ordering rule of each location, and the rules depend on each other: a shop that orders more takes stock that another shop may need.
Each location follows an (s, S) policy, a common rule in practice. Every day it looks at its inventory position, the stock on hand plus the stock already on the way. When the position is at or below the reorder point s, it orders enough to bring it up to the level S. The instance:
- daily demand at the four shops is random (Poisson) with means 4, 6, 8 and 10 units,
- a customer who finds a shop empty buys elsewhere: the sale is lost, at a cost of 20 per unit,
- deliveries take 5 days from the supplier to the warehouse and 2 days from the warehouse to a shop,
- when the warehouse cannot fill all shop orders, it shares its stock in proportion to the orders,
- holding a unit costs 1 per day at every location (the money tied up is the same wherever the unit is), and stock on the way is not charged,
- an order costs 100 at the warehouse and 20 at a shop, whatever its size.
For a single location with backorders, the best (s, S) policy can be computed exactly by dynamic programming. With a warehouse that runs short, rationing and lost sales, no exact method exists, and practice falls back on simulation: run the system on random demand and measure the mean cost. Simulation also handles any rule you can write down, which formulas cannot.
There is no published optimum for this instance. The best known value comes from long searches, and every policy is also checked on fresh demand that the search has never seen (see below).
The model¶
The variables are the reorder point s and the order size Q = S - s at each of the five locations: two Integer vectors of 5 values, the warehouse first. Using Q instead of S means that every pair of values is a valid policy (S is always above s), so no constraint is needed.
The objective simulates the system for 100 days after a warm-up of 30 days, on 60 demand scenarios, and returns the mean cost per day. The scenarios are drawn once, from a fixed seed, and every policy faces exactly the same demand. These are common random numbers, and they matter a lot:
- the objective is deterministic, so the same policy always gets the same value, and an algorithm can compare two policies reliably,
- a difference between two policies comes from the policies, not from luck in the demand they happened to face.
With fresh random demand at each evaluation, the same policy would get a different cost each time: on 60 new scenarios it varies by about 0.75 per day (half a percent), more than most of the differences the search has to see near the end.
The simulation is vectorized: it runs a whole population of policies on all scenarios at once.
import numpy as np
import ypea
mean_demand = np.array([4.0, 6.0, 8.0, 10.0]) # units per day at each shop
warehouse_lead_time = 5 # days
shop_lead_time = 2
holding = 1.0 # per unit and day, at every location
warehouse_order_cost = 100.0
shop_order_cost = 20.0
lost_sale_cost = 20.0
warm_up = 30 # days before costs count
days = 100
# common random numbers: 60 demand scenarios, the same for every policy
rng = np.random.default_rng(2026)
demand = rng.poisson(mean_demand, (60, warm_up + days, 4)).astype(float)
def simulate(s, q, demand):
"""Mean cost per day of a batch of policies: s and q have shape (n, 5), warehouse first."""
n = len(s)
scenarios = len(demand)
s = s.astype(float)[:, None, :]
big_s = s + q[:, None, :] # order up to level S
warehouse = np.broadcast_to(big_s[:, :, 0], (n, scenarios)).copy() # stock on hand
shops = np.broadcast_to(big_s[:, :, 1:], (n, scenarios, 4)).copy()
warehouse_pipe = np.zeros((warehouse_lead_time, n, scenarios)) # stock on the way
shop_pipe = np.zeros((shop_lead_time, n, scenarios, 4))
cost = np.zeros((n, scenarios, 5)) # by location
for day in range(warm_up + days):
w = day % warehouse_lead_time
r = day % shop_lead_time
warehouse += warehouse_pipe[w] # deliveries arrive
warehouse_pipe[w] = 0
shops += shop_pipe[r]
shop_pipe[r] = 0
sold = np.minimum(shops, demand[:, day, :]) # the rest is lost
lost = demand[:, day, :] - sold
shops -= sold
position = shops + shop_pipe.sum(axis=0)
wanted = np.where(position <= s[:, :, 1:], big_s[:, :, 1:] - position, 0.0)
share = np.minimum(1.0, warehouse / np.maximum(wanted.sum(axis=2), 1.0)) # rationing
shipped = np.floor(wanted * share[:, :, None])
warehouse -= shipped.sum(axis=2)
shop_pipe[r] = shipped
position = warehouse + warehouse_pipe.sum(axis=0)
ordered = np.where(position <= s[:, :, 0], big_s[:, :, 0] - position, 0.0)
warehouse_pipe[w] = ordered
if day >= warm_up:
cost[:, :, 0] += holding * warehouse + warehouse_order_cost * (ordered > 0)
cost[:, :, 1:] += holding * shops + shop_order_cost * (shipped > 0) + lost_sale_cost * lost
return np.sum(cost.mean(axis=1) / days, axis=1)
def policy_cost(sol):
return simulate(sol.s, sol.q, demand)
problem = ypea.Problem(
[
ypea.Integer("s", lb=0, ub=[400, 80, 80, 80, 80]),
ypea.Integer("q", lb=1, ub=[400, 100, 100, 100, 100]),
],
policy_cost,
vectorized=True,
name="inventory",
)
result = ypea.CMAES(pop_size=50, max_nfe=10_000).solve(problem, seed=1)
print(result.summary())
best = result.best.solution
print("s =", best.s, " Q =", best.q)
# check the policy on 300 new scenarios that the search has never seen
fresh = np.random.default_rng(99).poisson(mean_demand, (300, warm_up + days, 4)).astype(float)
print(f"out of sample: {simulate(best.s[None], best.q[None], fresh)[0]:.2f} per day")
CMA-ES on inventory
best objective value: 131.159
feasible: True (violation 0)
evaluations: 10000, iterations: 200, time: 18.4 s, stopped by: max_nfe
s = [31 15 23 31 37] Q = [107 13 19 24 31]
out of sample: 131.62 per day
Differs from Python: MATLAB draws its own random numbers, so the demand scenarios and the results differ from Python's. Core MATLAB has no Poisson generator, so the block draws the demand by Knuth's method.
mean_demand = [4 6 8 10]; % units per day at each shop
setup = struct();
setup.warehouse_lead_time = 5; % days
setup.shop_lead_time = 2;
setup.holding = 1.0; % per unit and day, at every location
setup.warehouse_order_cost = 100.0;
setup.shop_order_cost = 20.0;
setup.lost_sale_cost = 20.0;
setup.warm_up = 30; % days before costs count
setup.days = 100;
n_days = setup.warm_up + setup.days;
% common random numbers: 60 demand scenarios, the same for every policy
demand = poisson_draws(ypea.Rng(2026), mean_demand, 60, n_days);
problem = ypea.Problem( ...
vars={
ypea.Integer("s", lb=0, ub=[400 80 80 80 80])
ypea.Integer("q", lb=1, ub=[400 100 100 100 100])
}, ...
objective=@(sol) simulate(sol.s, sol.q, demand, setup), ...
vectorized=true, ...
name="inventory");
result = ypea.CMAES(pop_size=50, max_nfe=10000).solve(problem, seed=1);
disp(result.summary())
best = result.best.solution;
fprintf("s = %s Q = %s\n", mat2str(best.s), mat2str(best.q))
% check the policy on 300 new scenarios that the search has never seen
fresh = poisson_draws(ypea.Rng(99), mean_demand, 300, n_days);
fprintf("out of sample: %.2f per day\n", simulate(best.s, best.q, fresh, setup))
function cost_per_day = simulate(s, q, demand, setup)
% Mean cost per day of a batch of policies: s and q have one row per policy, warehouse first.
n = size(s, 1);
scenarios = size(demand, 1);
s = reshape(s, n, 1, 5);
big_s = s + reshape(q, n, 1, 5); % order up to level S
warehouse = repmat(big_s(:, :, 1), 1, scenarios); % stock on hand: (policy, scenario)
shops = repmat(big_s(:, :, 2:5), 1, scenarios, 1); % (policy, scenario, shop)
warehouse_pipe = zeros(n, scenarios, setup.warehouse_lead_time); % stock on the way, one page per day
shop_pipe = zeros(n, scenarios, 4, setup.shop_lead_time);
cost = zeros(n, scenarios, 5); % by location
for day = 1:setup.warm_up + setup.days
w = mod(day - 1, setup.warehouse_lead_time) + 1;
r = mod(day - 1, setup.shop_lead_time) + 1;
warehouse = warehouse + warehouse_pipe(:, :, w); % deliveries arrive
warehouse_pipe(:, :, w) = 0;
shops = shops + shop_pipe(:, :, :, r);
shop_pipe(:, :, :, r) = 0;
today = reshape(demand(:, day, :), 1, scenarios, 4);
sold = min(shops, today); % the rest is lost
lost = today - sold;
shops = shops - sold;
position = shops + sum(shop_pipe, 4);
wanted = (big_s(:, :, 2:5) - position) .* (position <= s(:, :, 2:5));
share = min(1, warehouse ./ max(sum(wanted, 3), 1)); % rationing
shipped = floor(wanted .* share);
warehouse = warehouse - sum(shipped, 3);
shop_pipe(:, :, :, r) = shipped;
position = warehouse + sum(warehouse_pipe, 3);
ordered = (big_s(:, :, 1) - position) .* (position <= s(:, :, 1));
warehouse_pipe(:, :, w) = ordered;
if day > setup.warm_up
cost(:, :, 1) = cost(:, :, 1) + setup.holding * warehouse + setup.warehouse_order_cost * (ordered > 0);
cost(:, :, 2:5) = cost(:, :, 2:5) + setup.holding * shops + setup.shop_order_cost * (shipped > 0) ...
+ setup.lost_sale_cost * lost;
end
end
cost_per_day = sum(mean(cost, 2) / setup.days, 3);
end
function counts = poisson_draws(generator, mean_demand, n_scenarios, n_days)
% Poisson demands, (scenario, day, shop). Core MATLAB has no Poisson generator, so this
% multiplies uniform numbers until the product drops below exp(-mean) (Knuth's method).
limit = repmat(reshape(exp(-mean_demand), 1, 1, []), n_scenarios, n_days, 1);
counts = zeros(size(limit));
product = generator.random(size(limit));
active = product > limit;
while any(active(:))
counts(active) = counts(active) + 1;
product(active) = product(active) .* generator.random(nnz(active), 1);
active = product > limit;
end
end
CMA-ES on inventory
best objective value: 130.851
feasible: true (violation 0)
evaluations: 10000, iterations: 200, time: 13.3 s, stopped by: max_nfe
s = [35 18 27 35 42] Q = [104 11 14 19 26]
out of sample: 131.75 per day
The full script, examples/applications/inventory.py, has the same model and a plot of the cost of each location.
Results¶
The natural classical approach is to tune each location on its own: each shop by a full grid search over s and Q as if the warehouse never ran short, then the warehouse for those shops. A local search on the joint simulation can then improve it, one variable or one location at a time, until nothing changes. All of them use the same simulation and the same 60 scenarios. The last column is the cost of the final policy on 300 fresh scenarios:
| Method | Evaluations | Cost per day | Out of sample |
|---|---|---|---|
| Each location tuned alone | 14 701 | 141.45 | 142.63 |
| From it, one variable at a time | 4 576 more | 137.04 | 137.40 |
| From it, one location at a time (full grid of s and Q) | 117 004 more | 136.53 | 137.64 |
| CMA-ES (the run above) | 10 000 | 131.16 | 131.62 |
Tuning each location alone keeps a large stock at the warehouse, to protect shops that were tuned as if the warehouse never ran short. The best policies are different: a lean warehouse that orders large batches, and more stock in the shops, close to the customers. Moving one variable or one location at a time cannot get there, because every single step away from the old policy makes it worse. A local search from many random starts does find such policies, but slowly: with the same 10 000 evaluations as CMA-ES its runs average 138.1, and 10 starts with 88 460 evaluations in all reach 131.27, still above the worst of 10 CMA-ES runs below.
The best known value is 130.47, found by two long runs (L-SHADE and IPOP-CMA-ES, 100 000 evaluations each) that end at the same policy.
Five algorithms, each with 10 seeded runs of 10 000 evaluations. GA and SA use the native integer operators (space="native"). The gap is the distance of the best run from the best known value, and the out-of-sample cost is that of each run's best policy on 300 fresh scenarios.
| Algorithm | Best | Mean | Worst | Gap of best | Out of sample: best | Mean |
|---|---|---|---|---|---|---|
| CMA-ES | 130.47 | 130.81 | 131.15 | 0.0% | 131.66 | 131.90 |
| L-SHADE | 130.47 | 130.82 | 131.19 | 0.0% | 131.09 | 131.60 |
| DE | 131.22 | 131.42 | 131.80 | 0.6% | 131.39 | 131.59 |
| GA | 131.34 | 133.44 | 137.91 | 0.7% | 131.64 | 134.08 |
| SA | 131.73 | 133.50 | 138.44 | 1.0% | 132.02 | 134.07 |
CMA-ES (with a population of 50) and L-SHADE reach the best known value in their best run, and every one of their runs is within 0.6 percent of it. DE is almost as steady. GA and SA have a few poor runs, but even they beat the classical methods on average. Each run takes about half a minute.
On fresh demand, the policies of CMA-ES, L-SHADE and DE cost about the same, 131.6 to 131.9 per day on average. The best known policy itself costs 131.87 there, more than some policies that are worse in the search. In-sample differences of a few tenths are mostly the luck of the 60 scenarios, not real improvements. To separate policies that close, use more scenarios.
Try it on your own inventory¶
- Replace the demand with your own: a different distribution, a trend, seasons, or past sales replayed as scenarios. The simulation can hold any rule you can write as code: backorders, a truck capacity, a minimum order size, perishable stock.
- Use enough scenarios and days that the result holds on fresh demand. Always check the final policy out of sample: when it costs clearly more there than in the search, use more scenarios. Differences smaller than that gap are noise, not real improvements.
- Keep the same demand scenarios for the whole search (common random numbers). Draw new ones only to check the result.
- Choose variables that make every combination valid, such as the order size Q instead of the level S.