6-inv-2.jl, runnable Julia extracted from the lecture’s code blocks.
1. From one-time to periodic
Lecture 6.1 (Sec. 4) set one-time safety stock beside periodic safety stock and dealt with the one-time case, in which nothing left over can be carried to the next demand. The periodic case is taken up here, in which it can. Periodic safety stock is in some sense the easier problem, since there is not just one shot at it. What drove the one-time case is that whatever was left over was disposed of as essentially worthless, but for most products that is the exception rather than the rule. Where the one-time trade-off was between lost profit and disposal cost, the periodic trade-off is again with lost profit or, in this case, a backorder. A backorder makes little sense in a one-time situation, which almost by definition assumes that demand cannot be backordered, but in the periodic case a customer can be told that the product will be available in a day or two. Whether the customer will wait depends on the product. A customer who walks into a store and does not find it on the shelf is probably not going to make another trip a day or two later, while a customer told that a delivery to the home is delayed a day or two is unlikely to cancel the order unless it is critical, so backordering is a lot more doable there. Lost profit, the revenue side, is one side of the trade-off. The other is the cost of carrying inventory, which exists here just as it does for working and economic stock (Lecture 6.1, Secs. 2 and 3). A periodic safety stock problem is to find the best trade-off between the two.
Lost sales and backorders
A stockout, a demand that cannot be satisfied, is dealt with in one of two ways. In a lost sale, a customer not served because there is no product is simply lost, and with it whatever revenue would have been received from that customer. In a backorder, a demand that could not be satisfied, because the product ran out that day, waits: the customer is willing to wait a day or two to receive the product. A backorder needs a product that is not obsolete at the end of the day; it has to have a longer life, as the more common products that do not expire in one period do.
At first glance a backorder might not seem costly. A customer who walks into a store charging $100 for a unit, finds it unavailable and agrees to wait a week for it does not expect the price to be lowered to $90, or any discount at all. So is there really no cost to a backorder, and no reason to carry safety stock, if customers do not seem to mind coming back the next week? There has to be some cost. Of those who say they will be back in a week, perhaps half will not actually show up, which makes a backorder something like half of a lost sale. The penalty for a backorder is not necessarily a monetary one; it is what is called the loss of goodwill of the customer, and it is a real thing: a customer who finds a store out of stock half the time will eventually find somewhere else to shop. The difficulty is putting a dollar figure on it.
Sometimes the cost is spelled out. Under vendor-managed inventory, in which the stock at a location is managed by the company that supplies it rather than the one that uses it, a supplier may hold the stock that feeds an automobile assembly plant, with the one requirement that whenever a bumper is needed to put on a vehicle, it is there. If it is not, the car cannot be made, and it is not a lost sale; the plant has to wait for a backorder. Such agreements, service level agreements, typically carry well-defined penalties: if the bumper is not available within 15 minutes of when it is needed on the line, a penalty of something like $500 starts, and beyond an hour it rises to something like three or four thousand dollars. The vendor can take the service level agreement and plug it into its model to determine how much inventory to carry to avoid those costs.
The cost of an underage is thus split between two possibilities. A lost sale costs the profit the unit would have made, p - c, the underage cost c_{\text{under}} of Lecture 6.1 (Eq. 15 in Lecture 6.1). A backorder has obvious direct costs, such as expediting the replacement or drop shipping it from the supplier straight to the customer; it has the indirect cost of the goodwill lost; and in some cases a contract with the customer sets an explicit cost for each unit backordered, and sometimes for each sale lost, as a service guarantee. The cost of a backorder is often taken to be a fixed penalty for each unit backordered. Here it is taken instead as a delay discount, the share of the unit profit lost for each period the customer waits, the way Lecture 6.3 evaluates the wait for a make-to-stock product, one made ahead of demand and sold from stock rather than made to order.2
Base stock and reorder point
Two periodic safety stock models will now be considered, base stock and the reorder point, and Table 1 sets them beside the one-time model.
Table 1: Safety stock models: the one-time model of Lecture 6.1 and the two periodic models taken up here, what each determines and the trade-off it makes.
Model
Decision scope
Primary trade-off
Decision variables
One‑time
One period, before demand is known
Underage (lost sales only) vs Overage (unsold)
Order quantity q
Base‑stock
One-for-one replenishment to a fixed level
Service (lost sale or backorder) vs Holding (average on hand)
Maximum level q_{\max}
Reorder‑point
Periodic replenishment in batches once stock hits reorder level
Service (lost sale or backorder) vs Holding and Ordering (setup)
Reorder point q_{\min}, order quantity q_o
The one-time problem already considered is a single period, and the decision has to be made before the demand is known, which is why order information or other data correlated with demand can help forecast it. Of the two periodic models, the first, the base stock model, is the easiest: like the one-time model, it is pure safety stock, with units ordered one at a time, a replacement ordered as soon as each unit is demanded. With the second, the reorder point, nothing is ordered until the inventory falls to a threshold level, and then a batch of several units is ordered. This is like truckload shipping: ordering part of a truckload rather than one item at a time is more economic, since putting more product on the truck spreads the fixed cost of operating it over more units and lowers the transport cost per unit. The reorder point is a combination of safety stock and the economic stock already seen in Lecture 6.1.
Base stock fits when a supplier makes deliveries almost daily or weekly and can simply be told to add another unit to the next delivery. When an order goes overseas in a shipping container, a container is not ordered for every item demanded; the order waits until an entire container of product is needed, and the reorder point is more appropriate. Base stock’s single decision variable is q_{\max}, the order-up-to level at which inventory is kept. Keeping just one unit means stocking out quite a bit; keeping more units makes a stockout less likely, but the inventory carrying cost rises, and that is base stock’s trade-off. The reorder point adds a fixed cost each time an order is placed, the cost of the shipping container, which is the same whether the container holds one unit or is filled to its capacity.
All of this looks at a single stocking location. In a supply chain with stock held at several locations, as in Sec. 4, lost sales cannot simply be assumed at every level: they make sense only at the level facing the customer. A supplier does not just say that it is out of stock and forget about the order; it almost always backorders it, so backordering is more prevalent in multi-echelon situations, those with stock at more than one level, or echelon, of a supply chain. Secs. 2 and 3 take lost sales first, because they are easier to talk about, and then backorders.
Stockout probability and average inventory
The performance measures used to determine the best policy are two. One is the out-of-stock percentage. The other is the average inventory level.
The out-of-stock percentage is written \pi_0, the probability of being out of stock: the probability that a demand finds no units on hand, which is the fraction of demands that become lost sales or backorders, not in general the fraction of the time with none on hand (Sec. 2). The average inventory level, \bar q, is the average number of units on hand over time. Both depend on the levels a policy keeps, and base stock and the reorder point both need them. How each is calculated, for Poisson demand or by simulation, is taken up in Sec. 2, once the two base stock models are stated.
2. Base stock
The first of the two periodic models of Table 1 is base stock, in which each unit is replaced as soon as it is demanded.
After its control logic and its two models, one with lost sales and one with backorders, base stock’s two measures are found in three ways, in this order. Simulation measures both, for any demand (Ex. 1). Poisson demand, Average on hand for any demand and Clock and customers then find them by formula from the demand during a lead time: the average on hand for any distribution of that demand, and the fraction of demands out of stock only for Poisson demand, whose distribution can be calculated by hand (Ex. 2); Ex. 3 determines the best level from the formulas and checks the simulation against them. Bootstrapping returns to the simulation for demand that is not Poisson, running it on a record of the data, sampled at random with replacement, in place of Poisson draws (Ex. 4, 5), and comes last because its results are compared against the Poisson’s.
Control logic
Base stock is pure safety stock. The seller makes one decision, the maximum finished goods inventory level. The control logic for the seller is to start with inventory at the max level and to order a replacement after each (unit) customer sale. In the customer fulfillment process, if there is a demand and the inventory level is greater than 0, a sale is made; otherwise, it is a lost sale. With backorders, otherwise, the customer waits for a replacement, getting a discount in price based on the wait. The performance measures are the out-of-stock percentage and the average inventory level.
Fig. 1 draws the control logic as a flowchart, one flow for each of the two events, a demand and the arrival of a replacement, with the steps taken only with backorders in purple, and writes q for the units on hand and b for the backorders waiting:
Show the code that draws this figure
# Code block 1: base stock's control logic as a flowchartbluec = colorant"#1f6fb5"# a determined series, as in 6.1grayc = colorant"#7f7f7f"# a neutral stepboc = colorant"#6a3d9a"# backorders# Every symbol in the font of the lecture's equations: italic for a# letter, upright for its digits and operatorsmi = Makie.MathTeXEngine.texfont(:italic)mr = Makie.MathTeXEngine.texfont(:math)it(s) =rich(s; font = mi) # a symbol, in italicsup(s) =rich(s; font = mr) # digits and operatorssub(b, k) =rich(it(b), subscript(up(k))) # a symbol, its subscriptfunctionrrect(x, y, w, h, r) # a rounded box's outline c = ((x + w/2- r, y + h/2- r, 0), (x - w/2+ r, y + h/2- r, 90), (x - w/2+ r, y - h/2+ r, 180), (x + w/2- r, y - h/2+ r, 270)) pts = [Point2f(cx +r*cosd(a), cy +r*sind(a)) for (cx, cy, a0) in c for a inrange(a0, a0 +90; length =7)]return ptsendfunctionlabel!(ax, x, y, s; color =:black, bold =false) ls = s isa Vector ? s : [s] # one line, or severalfor (i, l) inenumerate(ls)text!(ax, x, y +0.21*(length(ls) +1-2i); text = l, color, fontsize =13, align = (:center, :center), font = bold ? :bold ::regular)endreturnnothingendfunctionstep!(ax, x, y, s; w =3.0, h =1.0, c = bluec) # an actionpoly!(ax, rrect(x, y, w, h, 0.15); color =:white, strokecolor = c, strokewidth =2)returnlabel!(ax, x, y, s)endfunctionevent!(ax, x, y, s; w =3.6, h =0.7) # an eventpoly!(ax, rrect(x, y, w, h, h/2); color = bluec)returnlabel!(ax, x, y, s; color =:white, bold =true)endfunctionpause!(ax, x, y, s; w =3.6, h =0.7) # a resting statepoly!(ax, rrect(x, y, w, h, min(h/2, 0.35)); color = (grayc, 0.15), strokecolor = grayc, strokewidth =2)returnlabel!(ax, x, y, s)endfunctionask!(ax, x, y, s; w =3.4, h =1.5, c = grayc) # a decisionpoly!(ax, Point2f[(x - w/2, y), (x, y + h/2), (x + w/2, y), (x, y - h/2)]; color =:white, strokecolor = c, strokewidth =2)returnlabel!(ax, x, y, s)endfunctionflow!(ax, pts...; c = grayc, s ="", at =1, al = (:left, :bottom), off = (8, 3), tip =true) xs, ys = [p[1] for p in pts], [p[2] for p in pts] # a path, an arrow n = tip ? length(pts) -1:length(pts) n >1&&lines!(ax, xs[1:n], ys[1:n]; color = c, linewidth =2) tip &&arrows2d!(ax, [xs[end-1]], [ys[end-1]], [xs[end] - xs[end-1]], [ys[end] - ys[end-1]]; color = c, shaftwidth =2, tipwidth =10, tiplength =10)isempty(s) &&returnnothing# a label beside the path, if anytext!(ax, pts[at][1], pts[at][2]; text = s, color = c, fontsize =13, align = al, offset = off)returnnothingendfunctionchart(x1, y0, y1) # a blank canvas, 40 px a unit fig =Figure(size = (round(Int, 40x1), round(Int, 40(y1 - y0))), figure_padding =2) ax =Axis(fig[1, 1]; aspect =DataAspect())hidedecorations!(ax)hidespines!(ax)limits!(ax, 0, x1, y0, y1)return fig, axendfig, ax =chart(15.6, 1.65, 9.8)xl, xr, xo =2.7, 11.0, 7.0# demand, replacement, stockoutflow!(ax, (5.4, 8.99), (5.4, 8.7), (xl, 8.7), (xl, 8.35))flow!(ax, (10.2, 8.99), (10.2, 8.7), (xr, 8.7), (xr, 8.35))pause!(ax, 7.8, 9.35, rich("Start: ", it("q"), up(" = "),sub("q", "max"), " on hand, ", it("b"),up(" = 0"), " backorders"); w =7.2, h =0.72)flow!(ax, (xl, 7.65), (xl, 7.3)) # a demand arrivesflow!(ax, (xl, 5.8), (xl, 5.45); s ="yes", at =2)flow!(ax, (xl, 4.45), (xl, 3.9))flow!(ax, (xl, 3.1), (xl, 2.45))flow!(ax, (xl +1.7, 6.55), (xo, 6.55), (xo, 5.45); s ="no")flow!(ax, (xo +0.9, 4.45), (xo +0.9, 2.1), (xl +2.2, 2.1); c = bluec, s ="lost sales", al = (:left, :top), off = (6, -3))flow!(ax, (xo -0.9, 4.45), (xo -0.9, 3.5), (xl +1.95, 3.5); c = boc, s ="backorders", al = (:right, :top), off = (-6, -3))event!(ax, xl, 8.0, "A demand arrives"; w =3.7)ask!(ax, xl, 6.55, ["On hand?", L"q > 0"])step!(ax, xl, 4.95, ["Sell a unit", L"q - 1"])step!(ax, xl, 3.5, "Order a replacement"; w =3.9, h =0.8)pause!(ax, xl, 2.1, "Wait for the next event"; w =4.4)step!(ax, xo, 4.95, ["Out of stock: a lost sale,",rich("or a backorder, ", it("b"), up(" + 1"))]; w =4.4, c = grayc)flow!(ax, (xr, 7.65), (xr, 7.3)) # a replacement arrivesflow!(ax, (xr, 5.8), (xr, 5.45); c = boc, s ="yes", at =2)flow!(ax, (xr +1.7, 6.55), (14.0, 6.55), (14.0, 5.45); s ="no")flow!(ax, (xr, 4.45), (xr, 3.85))flow!(ax, (14.0, 4.45), (14.0, 3.5), (xr +2.2, 3.5))event!(ax, xr, 8.0, "A replacement arrives"; w =4.4)ask!(ax, xr, 6.55, ["Waiting?", L"b > 0"]; c = boc)step!(ax, xr, 4.95, ["Fill a backorder", L"b - 1"]; w =3.1, c = boc)step!(ax, 14.0, 4.95, ["Put on hand", L"q + 1"]; w =2.6)pause!(ax, xr, 3.5, "Wait for the next event"; w =4.4)fig
Figure 1: Base stock’s control logic. A demand that finds a unit on hand is a sale, and its replacement is ordered. Otherwise it is a lost sale, or, with backorders, the customer waits and the replacement is ordered all the same. A replacement that arrives fills a waiting backorder first.
Customer sales are assumed to be one unit at a time, since demand is typically taken to be a Poisson process, in which every arrival is independent; modeling the variability in the size of each customer’s order is set aside here; with orders of several units, the fraction of customers out and the fraction of units short differ. With a maximum level of ten units, say, however that is determined, and a replacement ordered on the spot after every sale, why would the seller ever be out of stock rather than staying at ten all the time? The reason is the lead time of a replacement. If it takes a week to get an order in, the first sale at the beginning of the week puts an order in, and if ten sales occur during the week, the seller is out of stock by the time the order for that first sale arrives. Whatever the lead time of the replenishment, the question is how much inventory is needed on hand for the probability of having that many sales within it to be at whatever level is wanted. Every time the guess is wrong, and customers walk in before the first replenishment has arrived, there is a lost sale, and estimating that over some period of time gives the out-of-stock percentage. And because sales keep taking from inventory before some of the replenishments arrive, the average inventory level is not ten, the maximum: the level moves around a lot, and its average is the other performance measure.
Base stock is also realistic for production on a line. In a Kanban or just-in-time system, whenever a unit is short, a ticket goes back and starts production of a replacement unit, so just-in-time and Kanban systems can be thought of as base stock inventory, the form Lecture 6.3 uses for make-to-stock production. The only situation where base stock would not be used is when there is a batching cost, such as a very significant setup of the production system whenever a particular product is produced; a reorder point policy, Sec. 3, would then be used instead.
Two models
Base stock is stated as two models, Model 1 taking a stockout as a lost sale and Model 2 as a backorder. They differ in one assumption, (c), what becomes of a demand that finds no units on hand. Model 1 is the periodic counterpart of Lecture 6.1’s one-time safety stock model (Model 2 in Lecture 6.1), not a special case of it: a unit left over is carried to the next demand, at a carrying cost, instead of being disposed of.
maximize: total profit per period of a seller who starts with its inventory at a maximum level and orders a replacement after each unit sold, the profit on units sold less the cost of carrying the units on hand
solve for:
(a) maximum inventory level, a whole number of units.
subject to: none
assumptions:
(a) demand arrives one unit at a time;
(b) each order is received a lead time after it is placed;
(c) demand that finds no units on hand is lost.
Model 1: Base stock with lost sales
Model 1 formulation: Base stock with lost sales
The maximum inventory level is the one that solves, with TP the total profit ($/period),
\max_{q_{\max}} \; TP = ( p - c ) \bigl( 1 - \pi_{0}\mkern-1.5mu( q_{\max} ) \bigr) \, r_{a} - c \, h \, \bar{q} ( q_{\max} )
\tag{1}
where
q_{\max}
=maximum inventory level (units)
p
=unit price ($/unit)
c
=unit cost ($/unit)
\pi_{0}\mkern-1.5mu( q_{\max} )
=probability out of stock, the fraction of demand lost
r_{a}
=demand arrival rate (units/period)
h
=inventory carrying rate (1/period)
\bar{q} ( q_{\max} )
=average inventory level (units).
\pi_0 and \bar q are the two performance measures of Sec. 1, each a function of q_{\max}. How they are calculated, for Poisson demand or by simulation, follows the two models.
Eq. 1 is the overall problem, and it is not that different from the one-time case of Lecture 6.1, which also maximized profit with one knob, the quantity to order. Here the one knob being tuned is the value of q_{\max} that maximizes total profit. Set beside the operating profit of Lecture 6.1, \pi(q, d_i) = p \min\{q, d_i\} - c q (Eq. 11 in Lecture 6.1), the first term of Eq. 1 is the same unit profit p - c made on the demand that is satisfied, (1 - \pi_0) r_a units a period, since each unit sold is replaced at cost c. The second term takes the place of the cost of the units over: a unit not sold is no longer lost but carried, at a cost of c h for each period it is on hand.
A backorder is modeled by a delay discount, as Lecture 6.3 does for make-to-stock production. Some procurement contracts charge a penalty for each day of delay. Model 2 is base stock with backorders, with what changes from Model 1 shown against it:
maximize: total profit per period of a seller who starts with its inventory at a maximum level and orders a replacement after each unit solddemanded, the profit on units sold, reduced by the cost of the backorders, a delay discount on each unit backordered, less the cost of carrying the units on hand
solve for:
(a) maximum inventory level, a whole number of units.
subject to: none
assumptions:
(a) demand arrives one unit at a time;
(b) each order is received a lead time after it is placed;
(c) demand that finds no units on hand is lostbackordered, filled when a replacement arrives.
The maximum inventory level is the one that solves
\max_{q_{\max}} \; TP = ( p - c ) \bigl( 1 - \pi_{0}\mkern-1.5mu( q_{\max} ) \, g \, t_{e} \bigr) \, r_{a} - c \, h \, \bar{q} ( q_{\max} )
\tag{2}
with the other symbols as in Model 1’s formulation, and
\pi_{0}\mkern-1.5mu( q_{\max} )
=probability out of stock, the fraction of demand backordered
g
=delay discount factor (1/period)
t_{e}
=lead time, taken as the time a backordered demand waits (period).
The delay discount is the cost of a backorder: the share g of the unit profit is lost for each period a demand waits, so a backorder waiting a lead time costs (p - c) \, g \, t_e. The other common cost of a backorder is a fixed penalty for each unit backordered, which would take the place of (p - c) \, g \, t_e in Eq. 2. How g is estimated for a product is taken up in Lecture 6.3, where the same delay discount evaluates the wait of a make-to-stock producer’s backorders.
In total profit, the probability of being out of stock, \pi_0, is then the fraction of customers who have to backorder, and on those units the unit profit is reduced by the delay discount. The rest of the time, a fraction 1 - \pi_0, the unit profit is made in full from inventory. Set side by side, Eq. 1 and Eq. 2 differ only in their first term, the cost of a stockout. With a lost sale, a stockout costs the whole unit profit p - c; with a backorder, its cost is the delay discount, the share g \, t_e of the unit profit. At g \, t_e = 1 the two objectives are the same, and at g \, t_e = 1/2 a backorder is the half of a lost sale of Sec. 1.
Simulation
Lecture 6.1 assumed nothing about the demand: it found its best quantity on the demand history itself, by brute force or with an optimizer, without fitting a distribution to the data (Lecture 6.1, Sec. 4). That worked because nothing over is carried from one demand to the next, assumption (c) of 6.1’s one-time model, so each demand in the history could be evaluated on its own. Here stock carries over, so how a demand is satisfied depends on the demands before it and on the orders still in transit: a policy has to be run through time, which is a simulation, and the data enter it by bootstrapping (Bootstrapping, at the end of this section, once the Poisson formulas have given results to compare it with).
With Julia available, simulation is the better method, and it comes first here. The Poisson formulas, taken up after it, are used because they are what a spreadsheet can do, and this course is not limited to spreadsheets. The formulas do allow some calculation by hand, and they are conceptually clear. Other analytical methods exist, but they rest on assumptions of their own, typically a normal distribution of demand where the Poisson cannot be assumed, and whole courses were once taught on their formulas.
The Poisson formulas of base stock, and of the reorder point in Sec. 3, are about as much as can be done without simulation, and two assumptions make them possible at all: Poisson demand and a constant lead time. The reason for the first is the Poisson arrivals see time averages (PASTA) property, which lets the fraction of the time with none on hand stand for the fraction of demands out of stock (Clock and customers). The problem with assuming Poisson arrivals is that the assumption is great for a perfectly steady state in which nothing changes, but no supply chain sees the same demand rate every day of the year: demand rises in some months, such as the summer, and is higher on weekends than during the week, and a Poisson process with one rate for all time does not account for these variations. A simulation handles them in one of two ways. One is a negative binomial distribution, a two-parameter extension of the Poisson that models lumpier demand, periods with a lot of demand followed by periods with less. The approach more typically used in simulation is a different arrival rate for each day, or even each hour: demand might be low at the start of the day, peak at lunchtime, and drop again toward the end of the day, with each hour’s arrivals a Poisson process at that hour’s rate. This is called a nonhomogeneous Poisson process, as in Lecture 1.3 (Sec. 8), and it keeps the best of the Poisson while allowing the demand rate to vary.
In a simulation, a backordered unit would probably not just go through the normal channels; it would be expedited in some way. It is not difficult to include an additional event for it, a delivery directly from the supplier to the customer that may bypass the stocking location. The nice thing about simulation is that such more realistic effects can be added.
By simulation, the two measures of either the lost sales or backorder models are counted over a long stretch of simulated time, each stated in words over its formula:
\hphantom{\underset{\displaystyle \bar{q} ( q_{\max} )}{\pi_{0}\mkern-1.5mu( q_{\max} )}}\mathllap{\pi_{0}\mkern-1.5mu( q_{\max} )} = \mathrlap{\left\{ \begin{array}{l} \text{fraction of the simulated demands} \\ \text{that find no unit on hand} \\[4pt] n_{\text{out}} / n_{d} \end{array} \right.}\hphantom{\underset{\displaystyle \left\{ \begin{array}{l} \text{time average of the units on hand} \\ \text{over the time simulated} \\[4pt] A / T , \quad A = \sum_{k = 1}^{n} q_{k - 1} \, ( t_{k} - t_{k - 1} ) \end{array} \right.}{\left\{ \begin{array}{l} \text{fraction of the simulated demands} \\ \text{that find no unit on hand} \\[4pt] n_{\text{out}} / n_{d} \end{array} \right.}} \tag{3}
\hphantom{\underset{\displaystyle \bar{q} ( q_{\max} )}{\pi_{0}\mkern-1.5mu( q_{\max} )}}\mathllap{\bar{q} ( q_{\max} )} = \mathrlap{\left\{ \begin{array}{l} \text{time average of the units on hand} \\ \text{over the time simulated} \\[4pt] A / T , \quad A = \sum_{k = 1}^{n} q_{k - 1} \, ( t_{k} - t_{k - 1} ) \end{array} \right.}\hphantom{\underset{\displaystyle \left\{ \begin{array}{l} \text{time average of the units on hand} \\ \text{over the time simulated} \\[4pt] A / T , \quad A = \sum_{k = 1}^{n} q_{k - 1} \, ( t_{k} - t_{k - 1} ) \end{array} \right.}{\left\{ \begin{array}{l} \text{fraction of the simulated demands} \\ \text{that find no unit on hand} \\[4pt] n_{\text{out}} / n_{d} \end{array} \right.}} \tag{4}
where
n_d
=number of demands simulated
n_{\text{out}}
=demands that find no unit on hand
n
=number of events simulated
t_k
=time of the kth event (periods), from t_0 = 0 to t_n = T
q_k
=units on hand just after the kth event (units), from q_0 = q_{\max}
A
=area under the units on hand, summed over the events (unit-periods)
T
=time simulated (periods).
The units on hand change only when an event occurs, so the area A is a sum over the events: at each event, the units on hand since the last event times the time since it. The longer the stretch simulated, the closer both measures come to their exact values, for any demand and any lead time. The two are taken two ways: \pi_0 is counted only as each demand arrives, what the customers see, and \bar q over every moment, what a clock sees (Clock and customers, below). Two schedulers drive the simulation, generating the times at which the next events occur. Given the time at which a demand occurs, the first determines when the next demand will occur. The second gives the time at which an order arrives, here deterministic, with no variability, as with a milk run (Lecture 5.3), a truck arriving every 1/8 of a period, so that the demand is the single source of randomness. The event queue, the event calendar E, is where the real work gets done: whenever an event is put into it, it keeps the sorted order, so the earliest event can always be taken from it. It starts with an initial demand at time zero, and the inventory starts at q_{\max}; the inventory is the state of the system, like the memory of what is happening in it, adjusted at every event. The simulation loop continues as long as the calendar is not empty. Each pass first takes the earliest event from the calendar, which returns the type of event and the time it occurs and removes it from the calendar. If that time is greater than the stopping time, the simulation stops. Otherwise the event is processed. For a demand, the next demand is scheduled at once: the sequence of demands is not known at the start, and each demand generates the next, so the simulation hopscotches through time, adding one demand at a time. Then, if inventory is positive, one unit is taken from it and, since this is base stock, its replenishment is ordered at once, the second scheduler adding the lead time to the current time to give the time it arrives. With lost sales, a demand that finds zero inventory orders nothing, since only a sale orders a replacement, and counting the demands that found zero inventory gives the estimate of the out-of-stock percentage. For an order arriving, all that is done is to add one to the stock.
Fig. 2 draws the simulation as the managing of its event calendar E. Each pass takes the earliest event out of the calendar, adds the area since the last event to A, moves the clock t to the event, and processes it by the control logic of Fig. 1. A demand adds to the counts n_d and n_{\text{out}}; at the stopping time T the counts and the area give Eq. 3 and Eq. 4:
Show the code that draws this figure
# Code block 2: the simulation loop around its event calendarfig, ax =chart(15.6, 1.2, 9.85)xm, xc =4.3, 13.6# main column, the calendarflow!(ax, (xm, 8.825), (xm, 8.35))flow!(ax, (xm, 7.05), (xm, 6.65))flow!(ax, (xm +1.4, 6.05), (7.7, 6.05); s ="yes")flow!(ax, (xm, 5.45), (xm, 5.05); s ="no", at =2)flow!(ax, (xm, 3.55), (xm, 2.95); s ="demand", at =2)flow!(ax, (xm +1.8, 4.3), (7.9, 4.3); s ="arrival")flow!(ax, (xm -3.3, 2.25), (0.3, 2.25); tip =false) # back to the topflow!(ax, (9.6, 3.8), (9.6, 1.35), (0.3, 1.35), (0.3, 7.7), (1.1, 7.7))flow!(ax, (xm +3.3, 2.25), (xc, 2.25), (xc, 4.25); c = bluec, s ="new events in", at =2, al = (:right, :bottom), off = (-8, 3))flow!(ax, (xc -1.65, 7.7), (xm +3.2, 7.7); c = bluec, s ="earliest out", al = (:right, :bottom), off = (-8, 3))pause!(ax, xm, 9.3, [rich("Start: clock ", it("t"), up(" = 0"), ", ",it("q"), up(" = "), sub("q", "max")," on hand,"),rich("the first demand in the calendar ", it("E"))]; w =7.6, h =0.95)step!(ax, xm, 7.7, [rich("Take the earliest event out of ", it("E")),rich("add ", it("q"), up(" × "), "(its time ",up("−"), " ", it("t"), ") to ", it("A")),rich("clock ", it("t"), " to its time")]; w =6.4, h =1.3)ask!(ax, xm, 6.05, L"t > T\,?"; w =2.8, h =1.2)stop = L"\pi_0 = n_{\mathrm{out}} / n_{\mathrm{d}}, \; \bar{q} = A / T"step!(ax, 9.6, 6.05, ["Stop", stop]; w =3.8, c = grayc)ask!(ax, xm, 4.3, ["Demand or", "arrival?"]; w =3.6, h =1.5)step!(ax, xm, 2.25, [rich(sub("n", "d"), up(" + 1"),", the next demand into ", it("E"), ","),"then the control logic for a demand,",rich("a stockout adding 1 to ", sub("n", "out"))]; w =6.6, h =1.4)step!(ax, 9.6, 4.3, ["Control logic", "for an arrival"]; w =3.4)poly!(ax, rrect(xc, 6.1, 3.3, 3.7, 0.15); color = (bluec, 0.08), strokecolor = bluec, strokewidth =2) # the calendartext!(ax, xc, 7.65; text =rich("Event calendar ", it("E")), fontsize =13, font =:bold, color = bluec, align = (:center, :center))for (i, (k, s)) inenumerate([("1", "demand"), ("2", "arrival"), ("3", "arrival"), ("4", "arrival")]) y =7.65-0.62ilines!(ax, [xc -1.45, xc +1.45], [y +0.31, y +0.31]; color = bluec, linewidth =1)text!(ax, xc, y; text =rich(sub("t", k), " ", s), fontsize =13, align = (:center, :center))endtext!(ax, xc, 4.55; text ="earliest first", fontsize =13, color = bluec, align = (:center, :center))fig
Figure 2: Simulation as the managing of an event calendar. The calendar E holds the events scheduled so far, earliest first. Each pass takes the earliest out, adds the units on hand times the time since the last event to the area A, moves the clock t to the event, and processes it by the control logic of Fig. 1; a demand puts new events into the calendar.
How the event calendar is kept matters. A priority queue, which in Julia comes from the DataStructures package rather than base Julia, keeps its values in sorted order as each one is put in, so the earliest event can always be taken from it, a very efficient way of doing it. With the events in a plain array instead, events being added and taken out all the time, every time the earliest was wanted the entire array would have to be searched. A priority queue finds the earliest in about \log n steps, and for really big numbers \log n is a lot smaller than n, which allows the number of events to run into the millions and still be computed very effectively.
Efficient data structures are an important feature of Julia, and one reason for using it. MATLAB, for example, did not allow them, which made simulation impossible in the basic language: specialized toolboxes had to be used, with the data structure capability it was missing. The calendar here, E, is kept with base Julia alone, as a vector of events in time order. The earliest event is always the first, taken out by popfirst! with no search at all, and schedule! finds the place of a new event by a binary search, searchsortedfirst, which compares the new event with the middle of the part of the calendar still in question and halves that part each time, in about \log_2 n comparisons rather than n. Putting the event in place still moves the later ones along, but the calendar never holds more than a few events at once, the next demand and the replacements on order, so the sorted vector does the work of a priority queue here without a package. The implementation follows Fig. 2, with the names of Eq. 3 and Eq. 4: the calendar E, the units on hand q and the backorders waiting b, the area A, the clock t₀, and the counts nd and nout. The two schedulers are sch[1], for the next demand, and sch[2], for the arrival of a replacement, and the keyword backorder chooses between the two models, the two ways out of a stockout in Fig. 1:
Model 1 implementation: Simulation
# Model: base stock with lost sales or backorders, by simulation# Event by event: fraction out of stock per demand, average on hand,# and fraction of the time with none on handschedule!(E, t, evt) =# put an event into E, in time orderinsert!(E, searchsortedfirst(E, (t, evt)), (t, evt))functionbase_stock(qmax, sch, t_stop; backorder =false) E = [(0.0, :demand)] # event calendar (time, kind) q, b = qmax, 0# state: units on hand, backorders t₀, A, A0 =0.0, 0.0, 0.0# clock, area under q(t), time at 0 nd, nout =0, 0# demands, and those out of stockwhile !isempty(E) t, evt =popfirst!(E) # the earliest event, out of E A +=q*(min(t, t_stop) - t₀) # units on hand × time since last A0 += (q ==0)*(min(t, t_stop) - t₀) # time with none t > t_stop &&break# stop the simulation at T = t_stop t₀ = t # the clock to the event's timeif evt ==:demand nd +=1schedule!(E, sch[1](t), :demand)if q >0# a sale, and its replacement ordered q -=1schedule!(E, sch[2](t), :arrival)else# out of stock nout +=1if backorder b +=1schedule!(E, sch[2](t), :arrival)end# otherwise a lost saleendelseif b >0# a replacement fills a backorder b -=1else# a replacement goes on hand q +=1endend# per demand, over time, and over the time with none on handreturn (π₀ = nout/nd, q̄ = A/t_stop, none = A0/t_stop)end
1
sch[1] gives the time of the next demand and sch[2] the time a replacement arrives, so any demand and any lead time are a change to the schedule alone, never to the simulation.
2
The time with none on hand is summed the way the area is, so none is the fraction of the time with none on hand, the clock’s stockout probability of Table 3, beside \pi_0, the customers’.
3
With backorders, a demand that finds none on hand waits and its replacement is ordered at once, and the next replacement to arrive fills it instead of going on hand; with lost sales nothing is ordered. Either way the demand is counted out of stock, so \pi_0 is the fraction backordered or the fraction lost.
base_stock (generic function with 1 method)
Searching the levels for the best one, as Ex. 1(b) does by simulation and Ex. 3(b) with the Poisson formulas, needs a range to search. The upper bound taken for q_{\max} is twice the demand rate. The search is then literally brute force, starting from zero and going up to the bound, determining the total profit of each level and saving the largest.
Twice is not always enough. Start with twice, and if the best level found is right at the upper bound, the bound is not high enough: make it four times, and keep doubling until the best level found is below the bound. A best level at the bound, or at a lower bound, says only that the bound is too restrictive, an artifact of how much was searched, since it is not a real bound on anything in the system. The range of maximum levels searched, which every search of this lecture uses, is therefore
with the demand arrival rate r_a, in units a period, rounded to a whole number, and the bound doubled whenever the best level found is the bound itself, as it is likely to be for a lead time of more than two periods, whose mean demand, r_a t_e, is then more than 2 r_a.
Example 1: Base stock by simulation
An item sells for p = \$6 a unit and costs c = \$3, and its inventory carrying rate is h = 0.3 per period. Demand for it arrives as a Poisson process at a rate of r_a = 6 units a period, and each replacement is received exactly t_e = 1/8 period after it is ordered. Two cases are considered, each on its own. In the first, demand that finds no unit on hand is lost, as in Model 1. In the second, it is backordered, as in Model 2, the cost of a backorder a delay discount at a factor of g = 4 per period, so that a backorder waiting a lead time loses g \, t_e = 0.5 of the unit profit. Simulate the item with both models, and determine the best maximum inventory level of each.
Example 1(a): One level
Simulate the policy at q_{\max} = 3 with lost sales and with backorders, and measure the fraction out of stock and the average on hand of each.
The next demand is drawn as in Lecture 1.3 (Sec. 7), the time since the last one an exponential, -\ln(U)/r_a for U uniform, and each replacement arrives exactly t_e later. Code block 3 sets the item’s data and the two schedulers:
# Code block 3: the item's data and the two schedulersusingLogjam# for prt, a labeled tableusingRandomra =6# units/period, demand arrival ratete =1/8# period, lead timep =6# $/unit, unit pricec =3# $/unit, unit costh =0.3# 1/period, inventory carrying rateg =4# 1/period, delay discount factorRandom.seed!(1234) # reproducible drawsdemand(t) = t -log(rand())/ra # time of the next demandarrival(t) = t + te # time a replacement arrivessch = [demand, arrival]
2-element Vector{Function}:
demand (generic function with 1 method)
arrival (generic function with 1 method)
To see the calendar at work, Code block 4 records the first events of a run with lost sales, up to time 0.6, and Table 2 lists them, each row with the units on hand, q, and on order, o, after its event, and the calendar it leaves:
Show the code that records the first events
# Code block 4: the first events, and the calendar after eachfunctionbase_stock_log(qmax, sch, t_stop) # base_stock, recorded E = [(0.0, :demand)] # event calendar (time, kind) q, o = qmax, 0# units on hand, units on order rec = [] # (time, kind, lost, q, o, calendar)while !isempty(E) t, evt =popfirst!(E) # the earliest event, out of E t > t_stop &&break# stop the simulation at t_stop lost =false# a demand that finds none on handif evt ==:demandschedule!(E, sch[1](t), :demand)if q >0# a sale, and its replacement ordered q, o = q -1, o +1schedule!(E, sch[2](t), :arrival)else# a lost sale lost =trueendelse# a replacement arrives q, o = q +1, o -1endpush!(rec, (; t, evt, lost, q, o, E =copy(E)))endreturn recendt3(t) =rpad(round(t, digits =3), 5, "0") # a time to 3 decimalscal(E) =join([(k ==:demand ? "d ":"a ") *t3(t) for (t, k) in E],", ") # the calendar, earliest firstRandom.seed!(1234) # the draws of Code block 3rec =base_stock_log(3, sch, 0.6) # every event up to time 0.6kind = [r.lost ? "demand, lost":string(r.evt) for r in rec]prt(DataFrame(time =t3.(getfield.(rec, :t)), event = kind, q =getfield.(rec, :q), o =getfield.(rec, :o), calendar =cal.(getfield.(rec, :E))))
Table 2: The first events of the simulation with lost sales at q_{\max} = 3, up to time 0.6: the time and kind of each event, the units on hand, q, and on order, o, after it, and the calendar it leaves, d for a demand and a for an arrival, earliest first.
time event q o calendar
─────────────────────────────────────────────────
0.000 demand 2 1 a 0.125, d 0.187
0.125 arrival 3 0 d 0.187
0.187 demand 2 1 d 0.287, a 0.312
0.287 demand 1 2 a 0.312, a 0.412, d 0.540
0.312 arrival 2 1 a 0.412, d 0.540
0.412 arrival 3 0 d 0.540
0.540 demand 2 1 d 0.559, a 0.665
0.559 demand 1 2 a 0.665, a 0.684, d 0.732
Each row of Table 2 is the earliest event in the calendar the row before it left. Each demand puts the next demand into the calendar, and each demand that finds a unit on hand also puts in the arrival of its replacement, a lead time of t_e = 0.125 later; an arrival puts in nothing. Code block 5 then runs the simulation for 100,000 periods with lost sales, and again with backorders on the same stream of demands:
# Code block 5: the simulation at q_max = 3, both modelst_stop =100_000.0# periods simulated, TRandom.seed!(1234) # the draws of Code block 3, anewpi0sim, qbarsim, nonesim =base_stock(3, sch, t_stop)TPsim = (p - c)*(1- pi0sim)*ra - c*h*qbarsimRandom.seed!(1234) # the same demands, now backorderedpi0bo, qbarbo, nonebo =base_stock(3, sch, t_stop; backorder =true)TPbosim = (p - c)*(1- pi0bo*g*te)*ra - c*h*qbarboprt(DataFrame(stockout = ["lost sale", "backorder"], pi0 = [pi0sim, pi0bo], none = [nonesim, nonebo], qbar = [qbarsim, qbarbo], TP = [TPsim, TPbosim]))
stockout pi0 none qbar TP
────────────────────────────────────────
lost sale 0.0336 0.0336 2.27 15.35
backorder 0.0405 0.0407 2.26 15.60
The simulation also measures the clock’s stockout probability, the fraction of the time with none on hand: 0.0336 with lost sales and 0.0407 with backorders, each the fraction of demands out of stock to within the sampling error, as PASTA has it for Poisson demand (Table 3), a Triangulate check of Lecture 1.2.
With lost sales, every unit sold is replaced, so the units on hand and the units on order add up to q_{\max} at every moment. In the roles of Lecture 6.1 (Table 1 in Lecture 6.1), the units on hand are safety stock and the units on order are working stock, whose average is the throughput times the time each spends in transit by Little’s Law, q_I = n q t, the number of shipments n times their size q times the time t in transit (Eq. 5 in Lecture 6.1), here the rate at which units are sold times the lead time. Their sum is a Balance check of Lecture 1.2:
# Code block 6: units on hand and on order add up to q_maxonorder = (1- pi0sim)*ra*te # units, throughput × lead timeqbarsim + onorder # units
2.9986636916770233
As for inventory turns in Lecture 6.1 (Ex. 1), the throughput over the average on hand is 2.55 turns a period. Fig. 3 draws the units on hand and on order over one period of the simulation, from time 2 to time 3, a period with a lost sale in it, with the given maximum level in red and the units on hand and on order the simulation determines in blue and orange:
Show the code that draws this figure
# Code block 7: units on hand and on order over one periodgivc = colorant"#d21f26"# a given series, as in 6.1ordc = colorant"#e08a1e"# units on orderRandom.seed!(1234) # the draws of Code block 3rec =base_stock_log(3, sch, 3.0) # Code block 4's recorderts = [getfield.(rec, :t); 3.0] # event times, held to time 3qs = [getfield.(rec, :q); rec[end].q] # units on handos = [getfield.(rec, :o); rec[end].o] # units on orderlost = [r.t for r in rec if r.lost] # times of lost salesfig =Figure(size = (600, 330))ax =Axis(fig[2, 1]; xlabel ="Time (periods)", ylabel ="Units", xlabelsize =15, ylabelsize =15, xticklabelsize =13, yticklabelsize =13, yticks =0:3)h_ord =stairs!(ax, ts, os; step =:post, color = ordc, linewidth =2.5)h_on =stairs!(ax, ts, qs; step =:post, color = bluec, linewidth =2.5)h_max =hlines!(ax, [3]; color = givc, linestyle =:dash, linewidth =2)h_lost =scatter!(ax, lost, zeros(length(lost)); marker =:xcross, color =:black, markersize =14)xlims!(ax, 2, 3)ylims!(ax, -0.25, 3.25)Legend(fig[1, 1], [h_on, h_ord, h_max, h_lost], ["On hand", "On order", "Maximum level, 3", "Lost sale"]; orientation =:horizontal, framevisible =false, labelsize =13, padding = (0, 0, 0, 0))fig
Figure 3: Units on hand, in blue, and units on order, in orange, both determined by the simulation, under base stock at the maximum level of 3, given, in red, simulated from time 2 to time 3, with a lost sale where a demand finds none on hand. On hand and on order always add up to 3.
Simulated at q_{\max} = 3: with lost sales, \pi_0 = 0.0336 and \bar q = 2.2739 units; with backorders, \pi_0 = 0.0405 and \bar q = 2.2572 units
Example 1(b): Every level and the best
Determine the best maximum inventory level of each model by simulation.
Every level tried in the search uses the same random numbers, what simulation calls common random numbers. It compares apples with apples: if anything odd happens in the random numbers, some levels might escape it and look better than they actually are, so having every level see the same random set of demands is a fairer comparison. To verify the best level, the seed can be changed, or several seeds tried in a loop, but in simulation optimization, choosing the best of several alternatives by simulating each, every alternative is almost always looked at with the same randomness. That is also the reason for two different random number streams: with a random lead time, the demands and the lead times each have their own, which controls the correlation between them and gives more pointed results in the optimization.
Code block 8 searches every level up to the bound of Eq. 5 by simulation. A single source of randomness, as in Code blocks 3 to 7, needs only Random.seed!, as in the lectures before this one; here there are two, so the demands come from a stream of their own, rng1, and the lead times from another, rng2, each with its own seed. The time of the next demand, the lead time, and whether a stockout is backordered are keyword arguments, each the example’s unless another is given, as Ex. 5 gives others:
# Code block 8: the best level by simulation, on one stream of demandsUBqmax =2round(Int, ra) # units, the upper bound on q_maxqmax =0:UBqmax # units, maximum levels triedfunctionsimTP(q; leadtime = r -> te, # simulated TP at level q demand = (t, r) -> t -log(rand(r))/ra, backorder =false) rng1 =Xoshiro(1234) # same demands at each level rng2 =Xoshiro(5678) # and the same lead times sch = [t ->demand(t, rng1), t -> t +leadtime(rng2)] π₀, q̄ =base_stock(q, sch, t_stop; backorder) lost = backorder ? π₀*g*te : π₀ # share of profit lost on demandreturn (p - c)*(1- lost)*ra - c*h*q̄endTPᵒsim, qmaxᵒsim =maximum((simTP(q), q) for q in qmax)TPᵒbosim, qmaxᵒbosim =maximum((simTP(q; backorder =true), q)for q in qmax)
1
Xoshiro(1234) creates a random number generator of its own, a stream of random numbers started from the seed 1234, apart from the one Random.seed! starts. Each call starts both streams from the same seeds, so every level sees the same customers and the same lead times, and a difference between two levels is the policy’s, not the draw’s.
(15.604061648969843, 3)
The best level is 3 with lost sales and 3 with backorders, below the upper bound of 12, so the bound did not cut the search short.
Best level by simulation 3 units with lost sales, at a total profit of $15.35 per period, and 3 units with backorders, at $15.60
Poisson demand
Poisson demand gives the simulation’s measures without running it, because one number, its mean during a lead time, gives the whole distribution of the demand during a lead time, small enough to calculate by hand. The simulation, above, handles everything the Poisson does not, such as lumpy or seasonal demand and a variable lead time. The Poisson formulas also validate the simulation: with backorders they are exact, so a simulation of Poisson demand has to reproduce them, the check Ex. 3(a) makes of Ex. 1(a).
For a constant lead time t_e, both measures of either the lost sales or backorder models depend on the demand during a lead time, D_L. The average inventory depends on the distribution of D_L and on nothing else, Poisson or not (Average on hand for any demand, below). The fraction of demands that find none on hand also depends on the demand being Poisson (Clock and customers, below).
That restriction gives up less than it may seem: for a great many arrival processes the Poisson process is a good model, not merely an approximation, and Lecture 1.3 (Sec. 4) set out why. When each short time interval carries the same small, independent chance of an arrival, the process appears completely random. For arrivals at an average rate r_a, the time between successive arrivals then follows the exponential distribution, whose mean is 1/r_a: at r_a = 5 customers per hour, an average gap of 12 minutes. The exponential is memoryless: however long it has been since the last arrival, the time remaining until the next one keeps the same distribution. Lecture 1.3 derives this for the customers of a barber shop in a city of 10,000 people (Eq. 3 in Lecture 1.3). This memoryless, totally random pattern is the Poisson process, the c^2 = 1 reference on Lecture 1.3’s scale of variability (Eq. 2 in Lecture 1.3), c^2 the squared coefficient of variation, the variance over the square of the mean.
One of the first demonstrations that the Poisson process corresponds to things in the real world was a study of the Prussian cavalry, which published each year how many of its soldiers had been killed by a kick from a horse while caring for, grooming, or feeding the horses. The number was not large, a handful in each of 20 or 30 years out of a very large number of soldiers, and it followed a Poisson process almost perfectly. The Poisson models cases with a very large population of candidates: each soldier had a fair number of opportunities every day to be kicked, but perhaps a one-in-a-million chance each time, so out of perhaps a billion opportunities in a year only five or six came up. The arrivals at a fast-food restaurant in a particular hour are modeled the same way. The restaurant has a market area with a population of perhaps 10,000 who might go there, and if each goes about once a month, each has a 1 in 30 chance of going on any one day; counted over any day or hour, the arrivals match a Poisson process nicely.
The cavalry study is Ladislaus von Bortkiewicz’s, whose 1898 book The Law of Small Numbers made the Prussian horse-kick data famous: the number of soldiers killed by a horse’s kick each year in each of 14 cavalry corps over 20 years, numbers he showed followed a Poisson distribution.3
Demand during a lead time
The demand during a lead time, D_L, is then a Poisson count with mean \mu = r_a t_e. The probability of exactly j demands during a lead time, and of j or fewer, are
Demand for an item arrives as a Poisson process at a rate of r_a = 6 units a period, and each order for the item is received a constant t_e = 1/8 period after it is placed. Determine the probability of exactly 0, 1, 2, and 3 demands during a lead time, and of that many or fewer.
With demand a Poisson process, its rate is the arrival rate r_a, and the lead time t_e is, in the terms of Lecture 1.3, an effective process time: the period over which arrivals are counted. The lead time of Ex. 2, t_e = 1/8 of a period, which the examples after it keep, is not arbitrary. The lead time of a reorder can be thought of as the time it takes to produce a restocked item, its effective process time, and one over the effective process time of a single machine is its effective capacity, here 8 units a period. For the reorders not to back up, that capacity has to be greater than the arrival rate of r_a = 6 units a period: a lead time of 1/6 would correspond to 100% utilization, while a capacity of 8 a period gives a utilization of 6/8, or 75%.
Example 2(a): By hand
Compute the probabilities with Eq. 6 and Eq. 7, one term at a time.
The mean demand during a lead time is the arrival rate times the lead time. Its units, units a period times periods, are units, a Units check of Lecture 1.2:
The probability of j or fewer demands, F(j; \mu) of Eq. 7, is the running sum of the terms, each value the one before it plus the next term, Eq. 9. The probability of none is the first term, F(0; 0.75) = 0.47237, and the probability of at most one adds the second:
F(1; 0.75) = 0.47237 + 0.35427 = 0.82664
The probability of at most two adds the third,
F(2; 0.75) = 0.82664 + 0.13285 = 0.95949
and the probability of at most three adds the fourth:
F(3; 0.75) = 0.95949 + 0.03321 = 0.99270
Without rounding the terms before adding them, the last is 0.99271.
\mu = 0.75 units; F(j; 0.75) = 0.47237, 0.82664, 0.95949, 0.99271 for j = 0 to 3
Example 2(b): In code
Compute the same probabilities in Julia and compare them with Ex. 2(a).
The cumulative distribution function of Eq. 7 is written as a function of j and \mu, summing the same terms one at a time as Ex. 2(a) did, each probability from the one before it by Eq. 8 and the running sum by Eq. 9, and is used again in Secs. 2 to 4. Computed this way, no factorial is ever formed, which for 21 or more demands would be too large for Julia’s whole numbers:
# Code block 9: F(j; μ), the probability of j or fewer, Poisson mean μfunctionpoissoncdf(j, μ) pℓ =exp(-μ) # Pr(D_L = 0) F = pℓ # F(0; μ)for ℓ in1:j pℓ *= μ/ℓ # Pr(D_L = ℓ), from Pr(D_L = ℓ - 1) F += pℓ # F(ℓ; μ), from F(ℓ - 1; μ)endreturn Fend
poissoncdf (generic function with 1 method)
Code block 10 sets the example’s arrival rate and lead time and tabulates, for up to three demands during a lead time, the probability of each and F(j; \mu):
# Code block 10: demand during a lead timera =6# units/period, demand arrival ratete =1/8# period, lead timeμ = ra*te # units, mean demand during a lead timej =0:3# demands during a lead timepj =exp(-μ) .* μ.^j ./factorial.(j) # Pr(D_L = j)F =poissoncdf.(j, μ) # F(j; μ)prt([pj F]; rows = j, cols = ["pj", "F"], row_title ="j", fracdig =5, allfrac =5)
The code reproduces Ex. 2(a) to five places, and its F(3; 0.75), carrying every digit, is 0.99271. Fig. 4 draws the probabilities for up to six demands during a lead time: no demand at all is the most likely, and the running sum is all but 1 by three demands.
Show the code that draws this figure
# Code block 11: Pr(D_L = j) and F(j; μ) for up to six demandscdfc = colorant"#1e8a3c"# a cumulative probabilityjj =0:6# demands during a lead timepj =exp(-μ) .* μ.^jj ./factorial.(jj) # Pr(D_L = j)fig =Figure(size = (600, 300))ax =Axis(fig[1, 1]; xlabel = L"\text{Demands during a lead time, } j", ylabel ="Probability", xlabelsize =15, ylabelsize =15, xticklabelsize =13, yticklabelsize =13, xticks = jj)barplot!(ax, jj, pj; color = bluec, label = L"\Pr(D_L = j)")scatterlines!(ax, jj, poissoncdf.(jj, μ); color = cdfc, markersize =8, label = L"F(j;\,\mu)")lbl =string.(round.(pj[1:4], digits =3))text!(ax, jj[1:3], pj[1:3]; text = lbl[1:3], color =:white, align = (:center, :top), offset = (0, -4), fontsize =13)text!(ax, jj[4], pj[4]; text = lbl[4], align = (:center, :bottom), offset = (0, 3), fontsize =13)ylims!(ax, 0, 1.12)axislegend(ax; position =:rc, labelsize =13)fig
Figure 4: The probability of exactly j demands during a lead time, with the four of Ex. 2(a) labeled, and of j or fewer, F(j; \mu), for a Poisson mean of 0.75.
\mu = 0.75 units; F(j; \mu) = 0.47237, 0.82664, 0.95949, 0.99271 for j = 0 to 3
Average on hand for any demand
Base stock is one-for-one replenishment, with a maximum level q_{\max}, a constant lead time t_e, and a demand rate r_a. Every sale triggers an order, so the units missing from the shelf are exactly the orders still in transit: with backorders, where every demand orders its replacement, the demand D_L over the most recent lead time. The units on hand are therefore q = (q_{\max} - D_L)^{+}, its positive part, the larger of q_{\max} - D_L and 0. Let F be the cumulative distribution function of D_L, whatever the distribution of the demand: nothing in this subsection assumes it is Poisson, which is needed only for the fraction of demands out of stock (Clock and customers, below).
Average inventory = \sum_j \Pr(\text{unit } j \text{ is on the shelf}), for any demand.
Number the q_{\max} units in the order they will be used. Unit j is still on the shelf exactly when fewer than j units were demanded during the lead time, so \Pr(\text{unit } j \text{ on the shelf}) = \Pr(D_L \le j - 1) = F(j - 1). Inventory is a count of units present, and the average of a count is the sum of each unit’s probability of being present:
\bar{q} ( q_{\max} ) = \left\{ \begin{array}{l} \text{expected units of } q_{\max} \text{ left after} \\ \text{the demand during a lead time} \\[4pt] \mathbb{E}[ ( q_{\max} - D_{L} ) ^{+} ] = \sum_{j = 0}^{q_{\max} - 1} F ( j ) \end{array} \right.
\tag{10}
F(j)
=probability of j or fewer demands during a lead time, \Pr(D_L \le j), for any distribution of D_L; for Poisson demand, F(j; \mu) of Eq. 7
\mathbb{E}[\,\cdot\,]
=expected value, the average over the distribution of D_L
(x)^{+}
=positive part of x
=\max\{x, 0\}.
This replaces “how many are there on average?” (an expectation of a max) with “how likely is each unit to be there?” (a lookup of the cumulative distribution function).
The fraction of the time with none on hand is one minus the cumulative distribution function of D_L, for the Poisson available as a function, a built-in function in a spreadsheet and poissoncdf of Code block 9 here. It is evaluated not at q_{\max} but at q_{\max} - 1, since that is what gives the probability of actually stocking out. Demand comes in whole units, so no unit is on hand when the demand during the lead time has used up all q_{\max}, that is, when D_L \ge q_{\max}, which for whole units is D_L > q_{\max} - 1:
Evaluated at q_{\max} instead, 1 - F(q_{\max}; \mu) = \Pr(D_L > q_{\max}) would leave out D_L = q_{\max}, and understate the fraction of the time out of stock by \Pr(D_L = q_{\max}).Fig. 5 draws both measures for q_{\max} = 3 at the mean of Ex. 2, \mu = 0.75, one row for each unit and one column for each number of demands during a lead time, as wide as its probability:
Show the code that draws this figure
# Code block 12: the units on hand, unit by unit and outcome by outcomeqm =3# units, the maximum level of Ex. 3(a)ds =0:qm-1# demands during a lead time, below qmpd = [exp(-μ)*μ^d/factorial(d) for d in ds] # Pr(D_L = d)pd = [pd; 1-sum(pd)] # and Pr(D_L ≥ qm), the last columnx0 = [0; cumsum(pd)] # each column's left edgeFj =poissoncdf.(0:qm-1, μ) # Pr(unit j on hand) = F(j - 1)units = ["Unit 1, sold first"; ["Unit $j" for j in2:qm-1];"Unit $qm, sold last"]fig =Figure(size = (620, 330))ax =Axis(fig[1, 1]; yreversed =true, xlabelsize =15, xlabel = L"\text{Demand during a lead time, } D_L", xticks = ((x0[1:end-1] .+ x0[2:end])./2, [string.(ds); "$(qm)+"]), yticks = (1:qm, units), xticklabelsize =13, yticklabelsize =13, xgridvisible =false, ygridvisible =false, xticksvisible =false, yticksvisible =false)hidespines!(ax)for j in1:qm, d in0:qm # unit j is on hand when D_L ≤ j - 1 on = d ≤ j -1poly!(ax, Rect(x0[d+1], j -0.42, pd[d+1], 0.84); color = on ? (bluec, 0.35) ::white, strokecolor = on ? bluec : (grayc, 0.6), strokewidth =1)endxr =1.40# the right edge of the additionfor j in1:qm # each row's shaded length, F(j - 1) Fs =round(Fj[j], digits =4) op = j ==1 ? "":"+\\;"text!(ax, xr, j; text = L"%$op F(%$(j-1)) = %$Fs", align = (:right, :center), fontsize =13)lines!(ax, [1.01, 1.09], [j, j]; color = grayc, linestyle =:dot)endinkc = colorant"#252525"# the rule under the additionlines!(ax, [1.10, xr], fill(qm +0.5, 2); color = inkc, linewidth =1)qb =round(sum(Fj), digits =4) # the shaded area, the rows added uptext!(ax, xr, qm +0.82; align = (:right, :center), fontsize =13, color = bluec, text = L"\text{sum} = \bar{q}(%$qm) = %$qb")pq =round(pd[end], digits =4) # none on hand, the last row's endtext!(ax, 1, qm +0.6; align = (:right, :center), fontsize =13, text = L"\Pr(D_L \geq %$qm) = %$pq")xlims!(ax, 0, 1.42)ylims!(ax, qm +1.05, 0.5)fig
Figure 5: The units on hand at a maximum level of 3 and the mean demand during a lead time of Ex. 2, 0.75. Each column is a number of demands during a lead time, as wide as its probability; each row is a unit, in the order the units are sold, shaded in blue where it is on hand, the probabilities determined from Ex. 2’s mean. Read by rows, the shaded area is the sum of Eq. 10, added up at the right; read by columns, it is the expected units left. Either way it is the average on hand, and the unshaded end of the last row is the fraction of the time with none on hand.
Sliced vertically, by outcome, each column contributes \Pr(D_L = d)\,(q_{\max} - d), giving the textbook \mathbb{E}[(q_{\max} - D_L)^{+}]. Sliced horizontally, by unit, each row’s shaded length is F(j - 1), giving the sum of the cumulative distribution function. Same area, so same answer. The right edge of the staircase of shaded rows is the cumulative distribution function laid on its side.
The first unit sits less than half the time on the shelf and the last unit almost always does, which makes safety stock visible. In Fig. 5, unit 1 is on hand 0.4724 of the time and unit 3 0.9595. Raising q_{\max} by one adds a new bottom row of length F(q_{\max}): the new unit sits idle with probability F(q_{\max}), at a cost of c \, h \, F(q_{\max}), the carrying cost Ex. 3(c) sets against the stockouts the unit saves.
This result does not need Poisson. Nothing in the staircase argument used the Poisson formula; Poisson only set the column widths. The identity holds for any integer-valued lead-time demand with backorders (for continuous demand, the sum becomes \int_0^{q_{\max}} F(x)\,dx), and so does the fraction of the time with none on hand, the end of the last row. Check with deterministic demand D_L = 2 and q_{\max} = 4: inventory is 2, and F(0) + F(1) + F(2) + F(3) = 0 + 0 + 1 + 1 = 2, a Landmark check of Lecture 1.2.
Clock and customers
The fraction of the time with none on hand and the fraction of demands that find none on hand are two different averages, taken by two different observers, and a riddle sets the two observers apart:
Riddle. A person has been in only one restaurant where they ever saw it empty of customers. Why?
Answer. It is the one restaurant where they worked. As an employee, their presence had nothing to do with whether customers were there, so their shifts sampled the restaurant like a clock. In every other restaurant they were a customer, and a customer’s presence makes the restaurant non-empty by definition.
“The clock” means the time average, what an observer sees at a moment chosen purely by time, independent of customer arrivals (the employee in the riddle). “The customer view” means the average over arrival instants, what customers see just before they arrive.
The simulation of Ex. 1 is both observers. Its area over the time simulated, Eq. 4, and its fraction of the time with none on hand, the none of Code block 5, watch the shelf at every moment, as the employee does: they are the clock. Its count of the demands that find none on hand, Eq. 3, looks at the shelf only as each demand arrives: it is the customer view.
There are two different stockout probabilities:
Table 3: The average inventory and the two stockout probabilities, and which of them needs Poisson demand. The formulas are exact with backorders (Model 2) and approximations with lost sales (Model 1), where the units on order are not D_L.
Measure
Formula
Needs Poisson?
Average inventory
\sum_{j=0}^{q_{\max}-1} F(j)
No
Fraction of time with none
\Pr(D_L \ge q_{\max}) = 1 - F(q_{\max} - 1)
No
Fraction of customers out
1 - F(q_{\max} - 1)
Yes (PASTA)
The time fraction is the unshaded part of the bottom row in Fig. 5. The customer fraction equals it only when arriving customers see the time average, which is what PASTA (Poisson Arrivals See Time Averages) guarantees. With unit demands, the fill rate, 1 - \pi_0, is then F(q_{\max} - 1), the same cumulative distribution function that built the staircase.
For Poisson demand, then, the fraction of demands out of stock is
\pi_{0}\mkern-1.5mu( q_{\max} ) = \left\{ \begin{array}{l} \text{probability that a demand finds no unit on} \\ \text{hand, by PASTA the fraction of the time} \\ \text{with none on hand} \\[4pt] \Pr ( D_{L} \geq q_{\max} ) = 1 - F ( q_{\max} - 1 ; \mu ) \end{array} \right.
\tag{11}
Both formulas, Eq. 10 and Eq. 11 above, are exact when demand that finds no units on hand is backordered, as in Model 2, and an approximation with the lost sales of Model 1. Poisson demand is the critical assumption of Eq. 11, because of a property called Poisson arrivals see time averages (PASTA): it holds for Poisson arrivals because they are memoryless, and not in general for other arrival processes. With another demand process, 1 - F(q_{\max} - 1) of its D_L is still the fraction of the time with none on hand, but no longer the fraction of demands out of stock (Fig. 6).
Show the code that draws this figure
# Code block 13: units on hand with a demand exactly every 1/6 periodevenly(t) = t +1/ra # the next demand, 1/6 period laterreg =base_stock_log(1, [evenly, arrival], 1.0) # demands, no drawstr = [getfield.(reg, :t); 1.0] # event times, held to time 1qr = [getfield.(reg, :q); reg[end].q] # units on handsales = [r.t for r in reg if r.evt ==:demand] # every demand a salenone = [(tr[i], tr[i+1]) for i in1:length(qr)-1 if qr[i] ==0]fr =base_stock(1, [evenly, arrival], t_stop) # over T = t_stoppn =round(Int, 100fr.none) # %, of the time with none on handpc =round(Int, 100fr.π₀) # %, of the demands that find nonefig =Figure(size = (600, 270))ax =Axis(fig[2, 1]; xlabel ="Time (periods)", ylabel ="Units", xlabelsize =15, ylabelsize =15, xticklabelsize =13, yticklabelsize =13, yticks =0:1)h_none =vspan!(ax, first.(none), last.(none); color = (grayc, 0.25))h_on =stairs!(ax, tr, qr; step =:post, color = bluec, linewidth =2.5)h_dem =scatter!(ax, sales, fill(-0.12, length(sales)); marker =:utriangle, color = givc, markersize =12)xlims!(ax, -0.03, 1.03)ylims!(ax, -0.3, 1.25)Legend(fig[1, 1], [h_on, h_none, h_dem], ["On hand", "None on hand, $pn% of the time","Demand, $pc% find none"]; orientation =:horizontal, framevisible =false, labelsize =13, padding = (0, 0, 0, 0))fig
Figure 6: Units on hand, determined by the simulation, in blue, with a demand exactly every 1/6 period, given, in red, at a maximum level of 1 and the lead time of 1/8, over the first period. None is on hand, shaded, three quarters of the time, yet every demand finds a unit; the two fractions in the legend are the simulation’s over the whole time simulated.
For Poisson demand the two agree, which is PASTA: in Ex. 1(a), 0.0336 of the demands are lost and none is on hand 0.0336 of the time. That is why, for Poisson demand, the customers’ stockout probability can be read off the clock, Eq. 11 from the end of the last row of Fig. 5, without following the customers at all. For other demand the two part. With a demand exactly every 1/6 period, evenly spaced, the extreme of arrivals smoother than Poisson, the shelf of Fig. 6 is empty 75% of the time, yet no demand finds it empty; with demand burstier than Poisson, such as the bakery’s of Lecture 6.1, customers see more stockouts than the clock (Ex. 5(b)). On Lecture 1.3’s scale of variability these are c^2 < 1,c^2 = 1 and c^2 > 1 (Eq. 2 in Lecture 1.3), and Poisson is the dividing line.
No Logjam function computes either the lost sales or backorder models, so their implementations for Poisson demand are written out here, with poissoncdf of Code block 9 as F(j; \mu):
Model 1 implementation: Poisson demand
# Model: base stock with lost sales, Poisson demand, constant lead time# Fraction out of stock, average on hand, total profit, best levelpi0(qmax, μ) = qmax ==0 ? 1.0:1-poissoncdf(qmax -1, μ)qbar(qmax, μ) =sum(poissoncdf(j, μ) for j in0:qmax-1; init =0.0)TP(qmax; h = h, ra = ra, μ = μ) = (p - c)*(1-pi0(qmax, μ))*ra -c*h*qbar(qmax, μ)maxTP(qmaxs; h = h, ra = ra, μ = μ) =maximum((TP(q; h, ra, μ), q) for q in qmaxs)
1
With q_{\max} = 0 nothing is ever on hand, so every demand is out of stock and \pi_0 = 1, set directly since F(-1; \mu) is not defined.
2
The carrying rate, arrival rate and mean demand during a lead time are keyword arguments, each the example’s value unless another is given, as Ex. 8 gives another arrival rate.
3
Each level is tried in turn and the one with the largest total profit is kept, the brute force of Lecture 6.1’s one-time model (Model 2 in Lecture 6.1).
maxTP (generic function with 1 method)
Model 2 implementation: Poisson demand
# Model: base stock with backorders, Poisson demand, constant lead time# Total profit with the delay discount on the fraction backorderedTPbo(qmax; g = g, h = h, ra = ra, μ = μ) = (p - c)*(1-pi0(qmax, μ)*g*te)*ra -c*h*qbar(qmax, μ)
1
pi0 and qbar are those of Model 1’s implementation for Poisson demand, exact here, since every stockout is backordered. The delay discount factor is a keyword argument, the example’s unless another is given, as Ex. 3(c) gives others, and so are the carrying rate, arrival rate and mean demand during a lead time, as in TP.
TPbo (generic function with 1 method)
Example 3: Base stock with Poisson demand
The item of Ex. 2 sells for p = \$6 a unit and costs c = \$3, and its inventory carrying rate is h = 0.3 per period. Demand arrives as in Ex. 2, a Poisson process at r_a = 6 units a period, and each replacement is received t_e = 1/8 period after it is ordered. Two cases are considered, each on its own. In the first, demand that finds no unit on hand is lost, as in Model 1. In the second, it is backordered, as in Model 2, the cost of a backorder a delay discount at a factor of g = 4 per period, so that a backorder waiting a lead time loses g \, t_e = 0.5 of the unit profit, the half of a lost sale of Sec. 1. Determine the maximum inventory level that maximizes total profit in each case.
Example 3(a): Total profit at one level by hand
Determine the total profit of a maximum level of q_{\max} = 3 with lost sales and with backorders, with Eq. 11 and Eq. 10 and the values of Ex. 2.
The probability of being out of stock is one minus the cumulative distribution function at q_{\max} - 1 = 2, from Ex. 2(a):
The carrying cost is the cost of a unit times the carrying rate times the average on hand:
c \, h \, \bar q = 3(0.3)(2.25850) = 2.03265 \ \$/\text{period}
Total profit with lost sales, Eq. 1, is the difference:
TP(3) = 17.27082 - 2.03265 = \$15.23817 \text{ per period}
With backorders, every unit of demand is sold, and the unit profit on the fraction backordered is reduced by the delay discount, g \, t_e = 4(0.125) = 0.5:
The carrying cost is the same, so total profit with backorders, Eq. 2, is
TP(3) = 17.63541 - 2.03265 = \$15.60276 \text{ per period}
Its units, dollars a unit times units a period, less dollars a unit times one per period times units, are dollars a period, a Units check of Lecture 1.2.
TP(3) = \$15.23817 per period with lost sales and $15.60276 with backorders, with \pi_0 = 0.04051 and \bar q = 2.25850 units
Example 3(b): Every level and the best
Determine the total profit of each maximum level from 0 to the upper bound of Eq. 5 with lost sales and with backorders, and the level that maximizes each.
The levels tried run from 0 to the upper bound of Eq. 5, at the example’s arrival rate
q_{\max} \le 2 \, r_a = 2(6) = 12 \text{ units}
Code block 14 sets the example’s unit price, unit cost, carrying rate, and delay discount factor beside the arrival rate, lead time, and mean demand during a lead time of Code block 10, and evaluates both models at each level, one row a level, with F(q_{\max}; \mu),\pi_0,\bar q, and the total profit with lost sales, TP, and with backorders, TP_{bo}, as its columns:
# Code block 14: total profit at each maximum level, both modelsp =6# $/unit, unit pricec =3# $/unit, unit costh =0.3# 1/period, inventory carrying rateg =4# 1/period, delay discount factorUBqmax =2round(Int, ra) # units, the upper bound on q_maxqmax =0:UBqmax # units, maximum levels triedprt(hcat(poissoncdf.(qmax, μ), pi0.(qmax, μ), qbar.(qmax, μ),TP.(qmax), TPbo.(qmax)); rows = qmax, cols = ["F", "pi0", "qbar", "TP", "TPbo"], row_title ="qmax", fracdig =5, allfrac =5)
The simulation of Ex. 1(a) and these formulas are two methods for the same quantities, a Triangulate check of Lecture 1.2. With backorders they agree: the simulated fraction out of stock, 0.0405, and average on hand, 2.2572, are the formulas’ 0.0405 and 2.2585 to within the sampling error of the simulation. With lost sales they do not: the simulated fraction lost, 0.0336, is below 0.0405, and the simulated average on hand, 2.2739, is a little above 2.2585. With backorders, every demand orders a replacement, so the units on order are the demand during a lead time, D_L, a Poisson count with mean \mu, and a demand is out of stock exactly when D_L \ge q_{\max}, as Eq. 11 has it. With lost sales, a demand that finds none on hand orders nothing, so the units on order never exceed q_{\max}, and all q_{\max} of them are on order less often. The best level is 3 either way (Ex. 1(b)).
Row 4, q_{\max} = 3, is Ex. 3(a)’s calculation; without rounding \pi_0 to 0.04051 before multiplying, its total profit is $15.23825, not the $15.23817 by hand. No level can make more than (p - c) r_a, the profit of selling every unit of demand with none held, which is Lecture 6.1’s total operating profit of perfect prediction (Eq. 16 in Lecture 6.1) per period, and Code block 15 compares the best level of each model with it:
# Code block 15: the best levels, and their shares of perfect predictionTPᵒ, qmaxᵒ =maxTP(qmax) # lost salesTPboᵒ, qmaxboᵒ =maximum((TPbo(q), q) for q in qmax) # backordersTPub = (p - c)*ra # $/period, all demand sold, none heldTPᵒ/TPub, TPboᵒ/TPub
(0.8465694312405372, 0.8668221511129443)
The best level is q_{\max} = 3 either way, below the upper bound of 12, so the bound did not cut the search short, and the same best levels as the simulation of Ex. 1(b), a Triangulate check of Lecture 1.2 on the decision. With lost sales it reaches 84.7% of the $18 bound, and with backorders 86.7%, a Bounds check of Lecture 1.2. Fig. 7 shows where the rest goes with lost sales: at every level, total profit, lost profit, and carrying cost add to the bound, and raising the level trades lost profit for carrying cost. Total profit with backorders lies above it at every level, since a stockout then costs half the unit profit instead of all of it, and the two meet as the level rises and stockouts become rare.
Show the code that draws this figure
# Code block 16: total profit, lost profit and carrying cost against q_maxoptc = colorant"#b23a48"# an optimum, as in Lecture 6.1tpbc = colorant"#e08a1e"# total profit with backordersdcc = colorant"#1e8a3c"# carrying costLP(q) = (p - c)*pi0(q, μ)*ra # $/period, lost profitCC(q) =c*h*qbar(q, μ) # $/period, carrying costfig =Figure(size = (600, 390))ax =Axis(fig[1, 1]; xlabel ="Maximum inventory level (units)", ylabel ="\$ per period", xlabelsize =15, ylabelsize =15, xticklabelsize =13, yticklabelsize =13)scatterlines!(ax, qmax, TPbo.(qmax); color = tpbc, marker =:diamond, label ="Total profit, backorders")scatterlines!(ax, qmax, TP.(qmax); color = bluec, label ="Total profit, lost sales")scatterlines!(ax, qmax, LP.(qmax); color = grayc, marker =:utriangle, linestyle =:dash, label ="Lost profit")scatterlines!(ax, qmax, CC.(qmax); color = dcc, marker =:rect, linestyle =:dash, label ="Carrying cost")scatter!(ax, [qmaxᵒ, qmaxboᵒ], [TPᵒ, TPboᵒ]; color = optc, markersize =16, strokecolor =:white, strokewidth =1.5)Legend(fig[2, 1], ax; orientation =:horizontal, nbanks =2, labelsize =13, framevisible =false) # below, clear of the linesfig
Figure 7: Total profit with lost sales and with backorders, lost profit and carrying cost per period against the maximum inventory level, with the maximum total profit of each in maroon. At each level total profit with lost sales, lost profit and carrying cost add to the profit of selling every unit of demand with none held.
q_{\max}^{*} = 3 units with lost sales, at a total profit of $15.24 per period, and 3 units with backorders, at $15.60
Example 3(c): A cheaper backorder
Determine how small the delay discount factor, and with it the cost of a backorder, can get before the best level with backorders falls from 3 to 2.
The best level should fall as a backorder gets cheaper, and how far the delay discount has to move before it does is a Nudge check of Lecture 1.2. With backorders, going from 2 to 3 units saves the delay discount on the demand the third unit keeps from being backordered and costs the carrying of that unit:
TP(3) - TP(2) = (p - c) \, r_a \, g \, t_e \bigl[\pi_0\mkern-1.5mu(2) - \pi_0\mkern-1.5mu(3)\bigr] - c \, h \bigl[\bar q(3) - \bar q(2)\bigr]
Both differences can be read off Fig. 5. The third unit adds its row to the average on hand, \bar q(3) - \bar q(2) = F(2; 0.75) = 0.95949, and takes the column D_L = 2 out of the stockouts, \pi_0\mkern-1.5mu(2) - \pi_0\mkern-1.5mu(3) = \Pr(D_L = 2) = 0.13285, both from Ex. 2(a), so the difference is zero at
a delay discount factor of g = 0.36112 / 0.125 = 2.88896 per period. Code block 17 computes the same factor from the functions of the two implementations, and finds the best level with backorders just below and just above it:
# Code block 17: the delay discount at which the best level falls to 2dTP = (p - c)*ra*te*(pi0(2, μ) -pi0(3, μ)) # $/period per unit of gdCC =c*h*(qbar(3, μ) -qbar(2, μ)) # $/period, carrying a 3rdgstar = dCC/dTP # 1/period(maximum((TPbo(q; g =2.8), q) for q in qmax),maximum((TPbo(q; g =3.0), q) for q in qmax))
At g = 3 the best level with backorders is still 3, and at g = 2.8 it is 2. The delay discount factor has to fall to 2.88889 a period, against the 2.88896 found by hand from terms rounded to five places, before the decision changes: for the third unit to pay, a backorder has to cost at least 36% of the unit profit, where the example’s costs half.
Best level with backorders 3 for g above 2.889 per period, 2 below it
Bootstrapping
Bootstrapping is random sampling, with replacement, from a finite population of data, every data item equally likely to be drawn each time. With replacement is the critical part: an item drawn is put back and can be drawn again, and drawn many times, the samples show the averages and correlations that are in the data.
For demand that is not Poisson, the fraction out of stock has no formula here (Clock and customers), so the simulation of Ex. 1 is run instead on the data themselves, by the bootstrapping set aside at the start of Simulation. Bootstrapping is a technique that many students do not realize is very effective with a small amount of data. In the bakery case of Lecture 6.1, 13 days of demand may be all there is, as for a lot of real-world problems. The nice thing about bootstrapping is that an actual data set has all of its embedded correlations already in it. With a set of 1,000 orders, for example, random sets of orders are created by sampling randomly from the thousand, and the key is that the sampling is with replacement: each value drawn is put right back, so every value in the data set appears in the samples, on average, in the same proportion as in the data. In the simulation of Ex. 1, the place to bootstrap is where the synthetic values are generated, in the scheduler demand of Code block 3, whose -log(rand())/ra is a random draw from the exponential distribution: that draw is replaced by a sample with replacement from the actual data set, as Ex. 5(b) does for the demand through the keyword demand of simTP (Code block 8), and Ex. 5(a) for the lead time through leadtime. The simulation does not care where the data come from, since all it does is call the schedule for the time of the next event, whatever value it is given.
Code block 18 is the bootstrap itself, a function that, given the data, returns a sampler drawing one item of it at a time:
# Code block 18: the bootstrap, a draw from the data with replacementfunctionbootstrap(x) # a sampler for the data x n =length(x) # items in the datareturn r -> x[rand(r, 1:n)] # one item, each equally likelyend
1
The sampler takes a stream of random numbers r and draws one item: rand(r, 1:n) picks a position from 1 to n, every one equally likely, and nothing is taken out of x, so the item drawn is in effect put back and can be drawn again. Taking a stream r, as the lead time of simTP does (Code block 8), is what lets it plug into the simulation as it is.
bootstrap (generic function with 1 method)
Code block 19 uses it on the bakery’s 13 days of demand of Lecture 6.1 (Ex. 6 in Lecture 6.1), drawing 100,000 days:
# Code block 19: the bootstrap on the bakery's 13 daysusingStatisticsd = [237, 214, 161, 146, 331, 159, 423, 332, 139, 327, 152, 98,116] # loaves/day, Lecture 6.1's 13 daysday =bootstrap(d) # a day's loaves, drawn from the 13rng =Xoshiro(1234) # its own stream of random numbersmany = [day(rng) for _ in1:100_000] # 100,000 days drawnshare = [count(==(dᵢ), many) for dᵢ in d]/length(many)prt([d fill(1/13, 13) share; NaNmean(d) mean(many)]; fracdig =4, rows = [string.(1:13); "Average loaves"], row_title ="Day", cols = ["Loaves", "Share of the 13", "Share of the draws"])
1
==(dᵢ) is a function that tests whether its argument equals day i’s loaves, dᵢ, and count counts the draws for which it is true; divided by the number of draws, each count is that day’s share of them.
Day Loaves Share of the 13 Share of the draws
───────────────────────────────────────────────────────────
1 237 0.0769 0.0761
2 214 0.0769 0.0760
3 161 0.0769 0.0760
4 146 0.0769 0.0764
5 331 0.0769 0.0775
6 159 0.0769 0.0772
7 423 0.0769 0.0782
8 332 0.0769 0.0777
9 139 0.0769 0.0778
10 327 0.0769 0.0783
11 152 0.0769 0.0768
12 98 0.0769 0.0759
13 116 0.0769 0.0762
Average loaves 218.0769 218.8497
Every day is drawn about 1/13 = 0.0769 of the time, every day equally likely, so the draws have the data’s average, 218.85 loaves a day against the 13 days’ 218.08. The bottom row weights each day’s loaves by its share: 1/13 each for the 13 days, and the share it was drawn for the draws.
Example 4: Lee’s new recipe
Lee, the baker of Lecture 6.1 (Ex. 6 in Lecture 6.1), has developed a new recipe for his bread with which it keeps: a loaf can be sold on the days after it is baked, its price falling each day it is kept by 10% of what it was on its first day: $4.50 on its second day, $4.00 on its third, and so on. The downside of the new recipe is that each loaf takes a day to produce, so the loaves sold on any day were started the day before. With 6.1’s price of $5 and cost of $1 a loaf, demand not satisfied lost, and only its 13 days of demand to go on, determine the best base stock level of Model 1, with the fall in price as its carrying rate, whether the new recipe is worth adopting, and what assuming Poisson demand would cost.
Example 4(a): The best base stock level
Determine the best base stock level, simulated on the 13 days bootstrapped, and whether the new recipe makes more than the old.
The fall in price enters Model 1 as a carrying rate, determined as Lecture 3.3 determines one (Eq. 12 in Lecture 3.3), the sum of interest, warehousing and obsolescence. Held a day at a time, a loaf’s interest and warehousing are negligible, about (0.05 + 0.06)/365 = 0.0003 a day, so its carrying rate is its obsolescence alone, which the percent-reduction interval of Eq. 13 in Lecture 3.3 determines from the value it loses, x_h = 0.1 of its price in t_h = 1 day:
What a loaf loses with age is its price, not its cost, so its carrying cost is on the price, $5 times 0.1, or $0.50 for each day it is kept, and the total profit of Eq. 1 becomes
TP = (p - c)(1 - \pi_0)\, r_a - p\, h\, \bar q
A loaf’s fall in price is p h times the days it was kept, and the days all the loaves are kept add up to the area under the units on hand that base_stock already sums, so p h \bar q is the price lost to age, whichever loaves the customers take: the simulation carries the fall in price without a change.
The rest is Model 1 as it stands: a lead time of a day, demand not satisfied lost, and a schedule of demands. Code block 20 makes the schedule from the 13 days bootstrapped. Each day’s demand is drawn by day of Code block 19, and since the record gives each day’s total, not the time of each sale, its loaves are demanded at random times within the day:
# Code block 20: Lee's days bootstrapped into a schedule of demandsN =2_000# days simulatedrng =Xoshiro(1234) # its own stream of random numbersn = [day(rng) for _ in1:N +1] # each day's demand, one of the 13T =sort!([k +rand(rng) for k in0:N for _ in1:n[k +1]])lee(t) = T[searchsortedlast(T, t) +1] # next demand after t
1
Day k, counted from 0, runs from time k to k + 1, and each of its n[k + 1] demands is put at k + rand(rng), a time drawn at random within it; sort! puts the demands of all the days in time order.
2
searchsortedlast(T, t) is the position in T of the last demand at or before time t, so the next demand is the one after it. lee is the first of base_stock’s two schedulers, sch[1], in place of Code block 3’s demand.
lee (generic function with 1 method)
Code block 21 searches the levels with base_stock as it stands, its schedulers lee and the lead time, and the total profit above, up to the bound of Eq. 5, twice a day’s mean demand. Beside it is the old recipe on the same days, 6.1’s answer baked each morning and the rest given away:
# Code block 21: the best level, by base_stock on Lee's dayspL, cL =5, 1# $/loaf, price and cost (Lecture 6.1)xh, th =0.1, 1# price lost, a tenth in a dayhL = xh/th # 1/day, carrying rate, obsolescencelead =1# day, to produce a loafrL =mean(d) # loaves/day, demand arrival ratefunctionTPlee(S, sch) # $/day, total profit at level S π₀, q̄ =base_stock(S, sch, N) # Model 1's simulation, as it standsreturn (pL - cL)*(1- π₀)*rL - pL*hL*q̄ # carrying cost on priceendSlev =0:10:2round(Int, rL) # loaves, the levels triedTPrec = [TPlee(S, [lee, t -> t + lead]) for S in Slev]TPᵒrec, Sᵒrec =maximum(zip(TPrec, Slev))q61 =331# loaves a morning, 6.1 Ex. 6(c)TPold =mean(pL*min(q61, x) - cL*q61 for x in n[1:N]) # $/day(S = Sᵒrec, TP =round(TPᵒrec, digits =2), TP_old =round(TPold, digits =2))
(S = 350, TP = 776.22, TP_old = 730.76)
The best level is 350 loaves, at a total profit of $776.22 a day. On the same days the old recipe makes $730.76, so the new recipe is worth $45.46 a day more, even with each loaf taking a day to produce: Lee should adopt it. Neither recipe can make more than (p - c) r_a, every loaf demanded sold with none held, $872.31 a day, a Bounds check of Lecture 1.2.
Best level 350 loaves, at a total profit of $776.22 a day against $730.76 with the old recipe: adopt the new recipe
Example 4(b): Assuming Poisson demand
Determine the level a Poisson of the same mean would choose, and its actual total profit on Lee’s days.
The 13 days have a standard deviation of 103.0 loaves a day, where a Poisson count of the same mean has one of 14.8. Code block 22 repeats the search with Poisson demand of the bakery’s mean, drawn from exponential gaps as Code block 3 draws the item’s, through the same base_stock, so that the demand is the one difference, and reads the level it chooses off Code block 21’s search on Lee’s days:
# Code block 22: the same search with Poisson demand of the same meanfunctionTPleeP(S) # $/day at level S, Poisson demand r =Xoshiro(1234) # the same demands at every levelreturnTPlee(S, [t -> t -log(rand(r))/rL, t -> t + lead])endTPrecP = [TPleeP(S) for S in Slev] # $/day, Poisson demandTPᵒrecP, SᵒrecP =maximum(zip(TPrecP, Slev))TPP = TPrec[findfirst(==(SᵒrecP), Slev)] # $/day, on Lee's days(S = SᵒrecP, predicted =round(TPᵒrecP, digits =2), actual =round(TPP, digits =2))
# Code block 23: total profit against the level, Poisson and Lee's dayslumpc = colorant"#e08a1e"# Lee's days, bootstrappedfig =Figure(size = (600, 330))ax =Axis(fig[1, 1]; xlabel ="Base stock level (loaves)", ylabel ="Total profit (\$ per day)", xlabelsize =15, ylabelsize =15, xticklabelsize =13, yticklabelsize =13)hlines!(ax, [TPold]; color =:gray50, linestyle =:dot, linewidth =1.5, label ="Old recipe")lines!(ax, Slev, TPrecP; color = bluec, linewidth =2, label ="Poisson demand")lines!(ax, Slev, TPrec; color = lumpc, linewidth =2, label ="Lee's days, bootstrapped")scatter!(ax, [SᵒrecP, Sᵒrec], [TPᵒrecP, TPᵒrec]; color = optc, markersize =13)scatter!(ax, [SᵒrecP], [TPP]; color =:white, strokecolor = optc, strokewidth =2, markersize =13)lines!(ax, [SᵒrecP, SᵒrecP], [TPP, TPᵒrecP]; color = optc, linestyle =:dash)text!(ax, SᵒrecP, TPᵒrecP; text ="\$$(round(TPᵒrecP, digits =2))", align = (:right, :bottom), offset = (-6, 4), fontsize =13, color = bluec)text!(ax, Sᵒrec, TPᵒrec; text ="\$$(round(TPᵒrec, digits =2))", align = (:left, :top), offset = (8, -6), fontsize =13, color = lumpc)text!(ax, SᵒrecP, TPP; text ="\$$(rpad(round(TPP, digits =2), 6, "0"))", align = (:left, :top), offset = (8, -4), fontsize =13, color = optc)xlims!(ax, 145, 445)ylims!(ax, 540, 900)axislegend(ax; position =:rb, labelsize =13)fig
Figure 8: Total profit per day against the base stock level, simulated by base_stock with Poisson demand of the bakery’s mean, in blue, and on Lee’s 13 days bootstrapped, in orange, both determined, each with its best level in maroon; the open circle is the Poisson’s best level on Lee’s days, and the dotted line the old recipe on the same days.
With Poisson demand the best level is 250 loaves, promising $853.57 a day. On Lee’s days that level’s actual total profit is $701.40: $74.82 a day less than the bootstrap’s level of 350, $152.17 less than it promised, the dashed drop of Fig. 8, and less than the old recipe’s $730.76. Assuming Poisson demand, Lee would adopt the new recipe expecting it to pay, and its actual total profit would be less than before. With only 13 days of demand, and nothing like a Poisson in them, bootstrapping them into base_stock is how the new recipe can be evaluated on the demand Lee actually has.
A Poisson’s level of 250 loaves has an actual total profit of $701.40 a day on Lee’s days, against $776.22 at the bootstrap’s 350 and $730.76 with the old recipe
Ex. 5 bootstraps two records from Lecture 6.1 into the simulation of Model 1, one of lead times and one of demand:
Example 5: Bootstrapped lead times and demand
The item of Ex. 3 is simulated with lost sales, as in Model 1, first with its lead time drawn from a record, with backorders as well, and then with its demand drawn from one. Determine the best maximum inventory level in each case.
Example 5(a): Uncertain lead time
Determine the best level when each replacement’s lead time is uncertain, with the same mean of 1/8 period: drawn from the record of 12 transit times of Lecture 6.1 (Ex. 7 in Lecture 6.1),
19, 17, 20, 35, 18, 16, 18, 28, 19, 17, 31, 14
days, scaled to that mean, or drawn from an exponential distribution.
The other critical assumption of the model is that the lead time is constant. The model could be built on to allow a variable lead time, and that would not be a killer, since much of it could be kept; but in a simulation a variable lead time is trivial: each lead time simply comes from whatever distribution is wanted, an exponential, say, as variable as desired. What is amazing is that, for a base stock policy, the difference between a constant and a highly variable lead time is almost nothing. It can look as if something is wrong with the simulation, since the variability goes way up and the base stock does not, but the simulation is doing what it should, modeling the process. The best explanation, from experimenting with the simulation, is that under base stock every reorder is for the same item. Even with variability in how long each replenishment takes, a quick one is balanced by a long one, followed by another early one, so the replenishments do not arrive first in, first out: some ordered later arrive sooner than ones ordered earlier. Nor would anyone keep them first in, first out, holding back a delivery that has arrived because one ordered before it is stuck in a port. It is a really good property: the variability of the lead time is not that critical.
Code block 24 repeats Code block 8’s search with each lead time drawn from its own stream of random numbers, the record bootstrapped by Code block 18’s bootstrap:
# Code block 24: the best level with each lead time, both modelsx = [19, 17, 20, 35, 18, 16, 18, 28, 19, 17, 31, 14] # days, 6.1 Ex. 7cases = ["constant"=> r -> te,"record, scaled"=>bootstrap(te*x/mean(x)),"exponential"=> r ->-te*log(rand(r))]best = [maximum((simTP(q; leadtime), q) for q in qmax) for (_, leadtime) in cases] # lost salesbestbo = [maximum((simTP(q; leadtime, backorder =true), q) for q in qmax) for (_, leadtime) in cases] # backordersprt(DataFrame(lead_time =first.(cases), qmax =last.(best), TP =first.(best), qmax_bo =last.(bestbo), TP_bo =first.(bestbo)))
1
Each case is a Pair, written =>, of its name and its lead time. The lead time is a function written with ->, read “maps to”, which Lecture 1.2 (Sec. 1.7) calls an anonymous function, defined without a name: r -> te takes the case’s stream of random numbers, r, and returns its lead time, here always t_e. The search takes each function back out of its pair as leadtime, and first.(cases) the names for the table.
2
Each lead time is one of 6.1’s 12 transit times, drawn with replacement and scaled so that their mean is t_e, the record scaled first and then handed to bootstrap: only the record’s variability carries over, not its days.
The best level is 3 with every lead time, and total profit differs by 0.5 cents a period: the almost nothing described above, a Triangulate check of Lecture 1.2 between the three. In Lecture 6.1 (Ex. 7 in Lecture 6.1), the same record’s delays changed which supplier to use; for base stock with lost sales they change nothing. With backorders the best level is again 3 with every lead time, at total profits within 0.4 cents a period of each other, and with backorders the nothing is exact rather than almost, apart from the sampling error.
By Palm’s theorem, with Poisson demand and lead times that are independent and identically distributed and independent of demand, the units on order are a Poisson count with mean r_a times the mean lead time whatever the lead-time distribution, so lead-time variability drops out entirely. It is why the three lead times of Code block 24 give one best level.
Best level 3 units with a constant, a bootstrapped, and an exponential lead time, with lost sales and with backorders alike
Example 5(b): Demand as lumpy as the bakery’s
Determine the best level when the demand is as lumpy as the bakery’s of Lecture 6.1 (Ex. 6 in Lecture 6.1), its 13 days bootstrapped: each period’s demand is one of the 13 days, drawn with replacement and scaled to the mean of 6 units a period.
The 13 days are bootstrapped with Code block 18’s bootstrap, scaled to the item’s mean of 6 units a period: each period’s demand is one of the days, drawn with replacement. The record gives each day’s total, not the time of each sale, so each unit demanded in a period is put at a random time within it, the one assumption the simulation adds to the data:
# Code block 25: each period's demand, one of the bakery's 13 daysP =ceil(Int, t_stop) +1# periods simulateddI =round.(Int, ra*d/mean(d)) # units/period, the days at a mean of 6period =bootstrap(dI) # a period's demand, one of the daysrng =Xoshiro(1234) # its own stream of random numbersn = [period(rng) for _ in1:P] # each period's demandT =sort!([k +rand(rng) for k in0:P-1 for _ in1:n[k +1]])next_demand(t, r) = T[searchsortedlast(T, t) +1]
1
period(rng) draws one of the 13 days for each of the P periods, with replacement, by Code block 18’s bootstrap: this line is the bootstrap. The days are first scaled by ra/mean(d) and rounded, so that each is a whole number of units and together they average r_a.
2
Period k, counted from 0, runs from time k to k + 1, and each of its n[k + 1] units is demanded at k + rand(rng), a time drawn at random within it; sort! puts the demands of all the periods in time order.
3
searchsortedlast(T, t) is the position in T of the last demand at or before time t, so the next demand is the one after it. simTP passes next_demand a stream of random numbers r, as it does the Poisson demand of Code block 8, but none is needed: the demands were all drawn in advance, in T, so every level sees the same ones.
next_demand (generic function with 1 method)
Scaled, the 13 days are 7, 6, 4, 4, 9, 4, 12, 9, 4, 9, 4, 3, 3 units a period, whose mean is 6.0, the example’s r_a.
Code block 26 repeats Code block 8’s search with next_demand as the time of the next demand, beside the search with Poisson demand:
# Code block 26: total profit at each level, Poisson and bakery demandTPpois = [simTP(q) for q in qmax] # $/periodTPbake = [simTP(q; demand = next_demand) for q in qmax] # $/periodTPᵒbake, qmaxᵒbake =maximum(zip(TPbake, qmax))prt([TPpois TPbake]; rows = qmax, cols = ["Poisson", "bakery"], row_title ="qmax")
Code block 27 runs the simulation of Model 1 at q_{\max} = 3 on the same demands:
# Code block 27: the fraction lost, the time with none and the average# on hand at q_max = 3schb = [t ->next_demand(t, nothing), t -> t + te] # no stream neededpi0bake, qbarbake, nonebake =base_stock(3, schb, t_stop)(pi0 = pi0bake, none = nonebake, qbar = qbarbake)
# Code block 28: total profit against q_max, Poisson and bakery demandlumpc = colorant"#e08a1e"# demand as lumpy as the bakery'sfig =Figure(size = (600, 320))ax =Axis(fig[1, 1]; xlabel ="Maximum inventory level (units)", ylabel ="Total profit (\$ per period)", xlabelsize =15, ylabelsize =15, xticklabelsize =13, yticklabelsize =13, xticks = qmax)scatterlines!(ax, qmax, TPpois; color = bluec, markersize =8, label ="Poisson demand")scatterlines!(ax, qmax, TPbake; color = lumpc, markersize =8, label ="Bakery's demand, bootstrapped")scatter!(ax, [qmaxᵒsim, qmaxᵒbake], [TPᵒsim, TPᵒbake]; color = optc, markersize =13)text!(ax, qmaxᵒsim, TPᵒsim; text ="\$$(round(TPᵒsim, digits =2))", align = (:center, :bottom), offset = (0, 8), fontsize =13, color = bluec)text!(ax, qmaxᵒbake, TPᵒbake; text ="\$$(rpad(round(TPᵒbake, digits =2), 5, "0"))", align = (:left, :top), offset = (4, -8), fontsize =13, color = lumpc)ylims!(ax, -0.5, 18)axislegend(ax; position =:rb, labelsize =13)fig
Figure 9: Total profit per period against the maximum inventory level, simulated with Poisson demand and with the bakery’s demand of Lecture 6.1 bootstrapped, both determined, each with its best level in maroon and the total profit there.
With the bakery’s demand the best level is still 3, but at q_{\max} = 3 the fraction of demand lost rises from 0.0336 to 0.0414, total profit falls from $15.35 to $15.20 a period, and a level of 4 is nearly as good, at $14.91. It is an Assumptions check of Lecture 1.2 on the Poisson demand of Model 1: for this item, assuming Poisson demand when the demand is as lumpy as the bakery’s would leave the decision unchanged but overstate the profit. Its customers also find the shelf empty more often than the clock does: 0.0414 of the demands are lost, while none is on hand 0.0358 of the time, where with Poisson demand the two were the same (Ex. 1(a)). The bakery’s demand is burstier than Poisson (Clock and customers), and its customers see more stockouts than the clock.
Whether the demand of Lecture 6.1’s bakery (Ex. 6 in Lecture 6.1) could have been taken as Poisson is an Assumptions check of Lecture 1.2, made on 6.1’s own data. The variance of a Poisson count equals its mean, as the customer demand of Sec. 4 shows, so its standard deviation is the square root of its mean. Code block 29 compares the two on 6.1’s 13 days of demand, in loaves and at the item’s mean of 6 units a period:
# Code block 29: the bakery's demand against a Poisson of the same meanm =mean(d) # loaves/day, mean demands =std(d) # loaves/day, standard deviationsP =sqrt(m) # loaves/day, a Poisson's std. deviationm6, s6 =mean(dI), std(dI) # units/period, the days at a mean of 6sP6 =sqrt(m6) # units/period, a Poisson's std. deviationprt([m s sP s^2/m; m6 s6 sP6 s6^2/m6]; rows = ["loaves", "units"], row_title ="scale", cols = ["mean", "std", "Poisson std", "var/mean"])
scale mean std Poisson std var/mean
─────────────────────────────────────────────
loaves 218.08 103.02 14.77 48.67
units 6.00 2.92 2.45 1.42
The bakery’s standard deviation, 103.0 loaves a day, is about 7 times a Poisson’s 14.8, and its variance 48.7 times its mean: the lumpy demand described above, for which the Poisson does not apply, so Lecture 6.1 solved on the data. Ex. 5(b) simulates the days at the item’s mean of 6, though, and there the variance is only 1.42 times the mean: a Poisson’s standard deviation grows only as the square root of its mean, so the same days are much closer to Poisson at the smaller scale, which is why bootstrapping them left the best level unchanged and lowered the total profit by only 15 cents a period. Fig. 10 draws the 13 days at the item’s scale against the band within which a Poisson of the same mean would put nearly every day, its mean plus or minus two standard deviations, with the given days in red and the Poisson determined from them in blue.
Show the code that draws this figure
# Code block 30: the bakery's demand against a Poisson of the same meanfig =Figure(size = (600, 300))ax =Axis(fig[1, 1]; xlabel ="Day", ylabel ="Units", xlabelsize =15, ylabelsize =15, xticklabelsize =13, yticklabelsize =13, xticks =1:13)band!(ax, [0.5, 13.5], fill(m6 -2sP6, 2), fill(m6 +2sP6, 2); color = (bluec, 0.25), label ="Poisson, mean ± 2 std. dev.")hlines!(ax, [m6]; color = bluec, linewidth =1.5, label ="Mean")scatterlines!(ax, 1:13, dI; color = givc, markersize =8, label ="Demand")ylims!(ax, 0, 16)axislegend(ax; position =:lt, labelsize =13, orientation =:horizontal)fig
Figure 10: Lecture 6.1’s 13 days of bakery demand, scaled to the item’s mean of 6 units a period, given, in red, against a Poisson of the same mean, determined from it, in blue: the mean, and the band of the mean plus or minus two standard deviations.
Best level 3 units with the bakery’s demand bootstrapped, at a total profit of $15.20 per period, against $15.35 with Poisson demand
3. Reorder point
The second periodic model of Table 1, the reorder point, orders a batch rather than a single unit, for when each order carries a fixed cost.
Control logic
The reorder point is safety and cycle stock, cycle stock the economic stock of ordering in batches (Lecture 6.1, Sec. 3). The seller makes two decisions, the fixed order quantity and the order point (minimum inventory level). The control logic for the seller is to start with inventory at the max level, the order point plus the order quantity, and to order when the inventory position, the units on hand plus the units on order, less any backorders, falls to the minimum level. In the customer fulfillment process, if there is a demand and the inventory level is greater than 0, a sale is made; otherwise, it is a lost sale. With backorders, otherwise, the customer waits for the next order to arrive, getting a discount in price based on the wait. The performance measures are the out-of-stock percentage, the average inventory level and the average number of orders.
Fig. 11 draws the control logic as base stock’s was drawn in Fig. 1, with q again the units on hand and b the backorders waiting, and it differs in three ways. It keeps the inventory position, which a sale or a backorder lowers by one. It orders only when the position falls to the order point q_{\min}, instead of at every demand. And it orders and receives q_o units at a time instead of one: an order raises the position by q_o, and an arrival fills up to q_o waiting backorders and puts the rest on hand.
Show the code that draws this figure
# Code block 31: the reorder point's control logic as a flowchartqmn, qo_ =sub("q", "min"), sub("q", "o") # the order point and quantityfig, ax =chart(15.6, -0.1, 9.8)xl, xr, xo =2.7, 11.4, 7.0# demand, order, stockoutflow!(ax, (5.4, 8.99), (5.4, 8.7), (xl, 8.7), (xl, 8.35))flow!(ax, (10.8, 8.99), (10.8, 8.7), (xr, 8.7), (xr, 8.35))pause!(ax, 8.1, 9.35, rich("Start: ", it("q"), up(" = "), qmn, up(" + "), qo_, " on hand and position, ", it("b"),up(" = 0")); w =7.6, h =0.72)flow!(ax, (xl, 7.65), (xl, 7.3)) # a demand arrivesflow!(ax, (xl, 5.8), (xl, 5.45); s ="yes", at =2)flow!(ax, (xl, 4.45), (xl, 4.05))flow!(ax, (xl, 2.55), (xl, 2.2); s ="yes", at =2)flow!(ax, (xl, 1.2), (xl, 0.7))flow!(ax, (xl +1.7, 3.3), (5.3, 3.3), (5.3, 0.35), (xl +2.2, 0.35); s ="no")flow!(ax, (xl +1.7, 6.55), (xo, 6.55), (xo, 5.675); s ="no")flow!(ax, (xo +1.0, 4.225), (xo +1.0, 0.35), (5.3, 0.35); c = bluec, s ="lost sales", al = (:left, :top), off = (6, -3), tip =false)flow!(ax, (xo -1.2, 4.225), (xo -1.2, 3.95), (xl +0.7, 3.95), (xl +0.7, 3.74); c = boc, s ="backorders", al = (:left, :top), off = (6, -3))event!(ax, xl, 8.0, "A demand arrives"; w =3.7)ask!(ax, xl, 6.55, ["On hand?", L"q > 0"])step!(ax, xl, 4.95, ["Sell a unit", rich(it("q"), up(" − 1"),", position ", up("− 1"))]; w =3.6)ask!(ax, xl, 3.3, ["Position", rich("at ", qmn, "?")])step!(ax, xl, 1.7, ["Order", rich(qo_, " units, position ", up("+ "), qo_)]; w =3.6)pause!(ax, xl, 0.35, "Wait for the next event"; w =4.4)step!(ax, xo, 4.95, ["Out of stock: a lost sale,",rich("or a backorder: ", it("b"), up(" + 1"), ","),rich("position ", up("− 1"))]; w =4.4, h =1.45, c = grayc)flow!(ax, (xr, 7.65), (xr, 7.3)) # an order arrivesflow!(ax, (xr, 5.8), (xr, 5.45); c = boc, s ="yes", at =2)flow!(ax, (xr +1.7, 6.55), (14.4, 6.55), (14.4, 5.45); s ="no")flow!(ax, (xr, 4.45), (xr, 3.65))flow!(ax, (14.4, 4.45), (14.4, 3.3), (xr +2.2, 3.3))event!(ax, xr, 8.0, rich("An order of ", qo_, " arrives"); w =4.4)ask!(ax, xr, 6.55, ["Waiting?", L"b > 0"]; c = boc)step!(ax, xr, 4.95, [rich("Fill up to ", qo_, " of them,"),"the rest on hand"]; w =3.4, c = boc)step!(ax, 14.4, 4.95, ["Put on hand", rich(it("q"), up(" + "), qo_)]; w =2.3)pause!(ax, xr, 3.3, "Wait for the next event"; w =4.4)fig
Figure 11: The reorder point’s control logic, which differs from base stock’s in Fig. 1 in the inventory position it keeps, the check of the position against the order point, and orders and arrivals of q_o units instead of one. A demand that finds a unit on hand is a sale; otherwise it is a lost sale, or, with backorders, the customer waits. A sale or a backorder lowers the inventory position, and when the position falls to the order point an order of q_o units is placed. An order that arrives fills the waiting backorders first, the rest going on hand.
The reorder point follows the same logic as base stock, with a few things added. The fixed order quantity is one value picked and used for every order going forward rather than adjusted each time. The order point is a threshold: as long as demand leaves the inventory above it, nothing is ordered, and only once the inventory drops to it is an order placed, for the fixed order quantity. There is one additional performance measure: the average number of orders, the average order rate.
Two models
The reorder point is stated as two models, as base stock was, Model 3 with lost sales and Model 4 with backorders, differing in the same assumption, (c), and in the same term of the objective. Model 3 is built on base stock with lost sales, Model 1, with what changes shown against it:
maximize: total profit per period of a seller who starts with its inventory at a maximum level and orders a replacement after each unit soldorders a fixed quantity whenever its inventory position falls to a minimum level, the profit on units sold less the cost of carrying the units on handand the fixed cost of the orders
solve for:
(a) maximum inventory level, a whole number of unitsorder quantity, a positive whole number of units, the same for every order; (b) order point, the minimum inventory position, a whole number of units.
subject to: none; (a) Largest order quantity: order quantity at most a multiple, from 2 to 4, of the economic order quantity of Lecture 6.1 (Sec. 3).
assumptions:
(a) demand arrives one unit at a time;
(b) each order is received a lead time after it is placed;
(c) demand that finds no units on hand is lost.
=probability out of stock, the fraction of demand lost
r_{a}
=demand arrival rate (units/period)
h
=inventory carrying rate (1/period)
\bar{q}
=average inventory level (units)
c_{o}
=fixed cost per order ($/order)
r_{o}
=average order rate (orders/period)
q_{o , \max}
=largest order quantity, a multiple \beta, from 2 to 4, of the economic order quantity \sqrt{2 c_o r_a / (c h)}, rounded up (units).
\pi_0 and \bar q are the measures of Sec. 1, now functions of both q_o and q_{\min}. How they are calculated, for Poisson demand or by simulation, follows the two models.
Model 4 is the reorder point with backorders, with what changes from Model 3 shown against it:
maximize: total profit per period of a seller who orders a fixed quantity whenever its inventory position falls to a minimum level, the profit on units sold, reduced by the cost of the backorders, a delay discount on each unit backordered, less the cost of carrying the units on hand and the fixed cost of the orders
solve for:
(a) order quantity, a positive whole number of units, the same for every order;
(b) order point, the minimum inventory position, a whole number of units.
subject to:
(a) Largest order quantity: order quantity at most a multiple, from 2 to 4, of the economic order quantity.
assumptions:
(a) demand arrives one unit at a time;
(b) each order is received a lead time after it is placed;
(c) demand that finds no units on hand is lostbackordered, filled when an order arrives.
where every demand is sold in the end, so that the order rate is the demand arrival rate divided by the order quantity,
r_o\mkern-1.5mu(q_o) = \frac{r_a}{q_o}
with the other symbols as in Model 3’s formulation, and
\pi_{0}\mkern-1.5mu( q_{o} , q_{\min} )
=probability out of stock, the fraction of demand backordered
g
=delay discount factor (1/period)
t_{e}
=lead time, taken as the time a backordered demand waits (period).
As for base stock, Eq. 12 and Eq. 13 differ in the cost of a stockout: the whole unit profit with a lost sale, and with a backorder the delay discount, the share g \, t_e of it (Model 2). Constraint (a) of each bounds the search, as Eq. 5 does for base stock, not anything in the system: a best order quantity at q_{o,\max} says only that \beta is too small, and \beta is raised.
Simulation
By simulation, the two measures of either the lost sales or backorder models are counted as for base stock, now at a policy of an order quantity and an order point, each stated in words over its formula:
\hphantom{\underset{\displaystyle \bar{q} ( q_{o} , q_{\min} )}{\pi_{0}\mkern-1.5mu( q_{o} , q_{\min} )}}\mathllap{\pi_{0}\mkern-1.5mu( q_{o} , q_{\min} )} = \mathrlap{\left\{ \begin{array}{l} \text{fraction of the simulated demands} \\ \text{that find no unit on hand} \\[4pt] n_{\text{out}} / n_{d} \end{array} \right.}\hphantom{\underset{\displaystyle \left\{ \begin{array}{l} \text{time average of the units on hand} \\ \text{over the time simulated} \\[4pt] A / T , \quad A = \sum_{k = 1}^{n} q_{k - 1} \, ( t_{k} - t_{k - 1} ) \end{array} \right.}{\left\{ \begin{array}{l} \text{fraction of the simulated demands} \\ \text{that find no unit on hand} \\[4pt] n_{\text{out}} / n_{d} \end{array} \right.}} \tag{14}
\hphantom{\underset{\displaystyle \bar{q} ( q_{o} , q_{\min} )}{\pi_{0}\mkern-1.5mu( q_{o} , q_{\min} )}}\mathllap{\bar{q} ( q_{o} , q_{\min} )} = \mathrlap{\left\{ \begin{array}{l} \text{time average of the units on hand} \\ \text{over the time simulated} \\[4pt] A / T , \quad A = \sum_{k = 1}^{n} q_{k - 1} \, ( t_{k} - t_{k - 1} ) \end{array} \right.}\hphantom{\underset{\displaystyle \left\{ \begin{array}{l} \text{time average of the units on hand} \\ \text{over the time simulated} \\[4pt] A / T , \quad A = \sum_{k = 1}^{n} q_{k - 1} \, ( t_{k} - t_{k - 1} ) \end{array} \right.}{\left\{ \begin{array}{l} \text{fraction of the simulated demands} \\ \text{that find no unit on hand} \\[4pt] n_{\text{out}} / n_{d} \end{array} \right.}} \tag{15}
with n_d,n_{\text{out}},n,t_k,q_k,A, and T as in Eq. 3 and Eq. 4. The simulation is the loop of Fig. 2 around its event calendar, with the control logic of Fig. 11 in place of base stock’s. Its implementation returns Eq. 14 and Eq. 15, and adds the inventory position, pos, to the state of base stock’s simulation:
Model 3 implementation: Simulation
# Model: reorder point with lost sales or backorders, by simulation# Event by event: fraction out of stock per demand, average on handfunctionreorder_point(qo, qmin, sch, t_stop; backorder =false) E = [(0.0, :demand)] # event calendar (time, kind) q = qmin + qo # state: units on hand, at the maximum pos, b = q, 0# inventory position, backorders t₀, A =0.0, 0.0# clock, area under q(t) nd, nout =0, 0# demands, and those out of stockwhile !isempty(E) t, evt =popfirst!(E) # the earliest event, out of E A +=q*(min(t, t_stop) - t₀) # units on hand × time since last t > t_stop &&break# stop the simulation at T = t_stop t₀ = t # the clock to the event's timeif evt ==:demand nd +=1schedule!(E, sch[1](t), :demand)if q >0# a sale q -=1elseif backorder # out of stock: a backorder waits nout +=1 b +=1else# out of stock: a lost sale nout +=1continue# the position is left as it wasend pos -=1# a sale or a backorder lowers itif pos == qmin # the position falls to the order point pos += qoschedule!(E, sch[2](t), :arrival)endelse# an order of q_o arrives f =min(b, qo) # the backorders it fills b -= f q += qo - f # the rest goes on handendendreturn (π₀ = nout/nd, q̄ = A/t_stop) # per demand, over timeend
1
A demand that finds a unit on hand is a sale; one that finds none is a backorder, with backorders, or otherwise a lost sale, which goes on to the next event and leaves the position as it was. A sale and a backorder each lower the position by one, as in Fig. 11.
reorder_point (generic function with 1 method)
Example 6: Reorder point by simulation
The item of Ex. 1 now has a fixed cost of c_o = \$2 for each order placed, whatever its size. As in Ex. 1, two cases are considered, each on its own. In the first, demand that finds no unit on hand is lost, as in Model 3. In the second, it is backordered, as in Model 4, the cost of a backorder the delay discount of Ex. 1. Demand is a Poisson process and each order is received exactly t_e = 1/8 period after it is placed. Determine the order quantity and order point that maximize total profit in each case, by simulation.
Example 6(a): Largest order quantity to try
Determine the largest order quantity to try, with \beta = 2.
The bound on the order quantity is a multiple of the economic order quantity of Lecture 6.1 (Eq. 10 in Lecture 6.1):
q^{*} = \sqrt{\frac{2 f \, c_o}{v \, h}}
\tag{16}
Here the demand rate f of Eq. 16 is the arrival rate r_a and the unit value v is the unit cost c, so the economic order quantity is
Simulate the policy of ordering q_o = 5 units whenever the inventory position falls to q_{\min} = 2, with lost sales and with backorders, and measure its fraction out of stock and total profit.
The demand and the lead time are drawn with the schedulers of Ex. 1, and the backorders are simulated on the same stream of demands, with the fixed cost per order set in Code block 32:
# Code block 32: the simulation at q_o = 5, q_min = 2, both modelsco =2# $/order, fixed cost per orderRandom.seed!(1234) # the draws of Code block 3, anewpi0sim, qbarsim =reorder_point(5, 2, sch, t_stop)rosim = (1- pi0sim)*ra/5# orders/periodTPsim = (p - c)*(1- pi0sim)*ra - c*h*qbarsim - co*rosimRandom.seed!(1234) # the same demands, now backorderedpi0rpbo, qbarrpbo =reorder_point(5, 2, sch, t_stop; backorder =true)TPrpbosim = (p - c)*(1- pi0rpbo*g*te)*ra - c*h*qbarrpbo - co*ra/5prt(DataFrame(stockout = ["lost sale", "backorder"], pi0 = [pi0sim, pi0rpbo], qbar = [qbarsim, qbarrpbo], TP = [TPsim, TPrpbosim]))
stockout pi0 qbar TP
────────────────────────────────
lost sale 0.0097 4.25 11.62
backorder 0.0098 4.25 11.69
Fig. 12 draws the units on hand and the inventory position over the first four periods of the simulation, with the given order point in red and the units on hand the simulation determines in blue:
Show the code that draws this figure
# Code block 33: units on hand and the inventory position, four periods# reorder_point, recording (time, on hand, position)functionreorder_point_path(qo, qmin, sch, t_stop) E = [(0.0, :demand)] # event calendar (time, kind) q = pos = qmin + qo # units on hand, and the position path = [(0.0, q, pos)]while !isempty(E) t, evt =popfirst!(E) # the earliest event, out of E t > t_stop &&break# stop the simulation at t_stopif evt ==:demandschedule!(E, sch[1](t), :demand)if q >0# a sale lowers on hand and position q, pos = q -1, pos -1if pos == qmin # the position falls to the order point pos += qoschedule!(E, sch[2](t), :arrival)endendelse# an order of q_o arrives q += qoendpush!(path, (t, q, pos))endreturn pathendRandom.seed!(1234) # the draws of Code block 32path =reorder_point_path(5, 2, sch, 4.0)ts =first.(path) # event timesfig =Figure(size = (600, 300))ax =Axis(fig[1, 1]; xlabel ="Time (periods)", ylabel ="Units", xlabelsize =15, ylabelsize =15, xticklabelsize =13, yticklabelsize =13, yticks =0:7)band!(ax, [0, 4], [2.5, 2.5], [7.5, 7.5]; color = (grayc, 0.15))stairs!(ax, ts, getindex.(path, 3); step =:post, color = grayc, linewidth =2, label ="Inventory position")stairs!(ax, ts, getindex.(path, 2); step =:post, color = bluec, linewidth =2, label ="On hand")hlines!(ax, [2]; color = givc, linestyle =:dash, label = L"\text{Order point } q_{\min}")xlims!(ax, 0, 4)ylims!(ax, -0.3, 9.5)axislegend(ax; position =:lt, labelsize =13, orientation =:horizontal)fig
Figure 12: Units on hand, determined by the simulation, in blue, and the inventory position, in gray, under the reorder point with an order quantity of 5 and an order point of 2, given, in red, simulated over the first four periods. The shaded band holds the levels 3 to 7, from the order point plus 1 to the order point plus the order quantity.
Simulated at q_o = 5,q_{\min} = 2: with lost sales, \pi_0 = 0.0097 and total profit $11.62 per period; with backorders, \pi_0 = 0.0098 and $11.69
Example 6(c): Every policy and the best
Determine the policy of each model that maximizes total profit by simulation, over the order quantities from 1 to Ex. 6(a)’s bound and the order points from 0 to one less than the upper bound of Eq. 5.
Code block 34 simulates every policy on the same stream of demands, as Code block 8 did every level of base stock, with whether a stockout is backordered a keyword argument:
# Code block 34: the best policy by simulation, on one stream of demandsqomax =ceil(Int, 2sqrt(2ra*co/(c*h))) # units, Ex. 6(a)'s boundqos, qmins =1:qomax, 0:UBqmax-1# order quantities and points triedfunctionsimTPrp(qo, qmin; backorder =false) # simulated TP of a policyRandom.seed!(1234) # the same demands for every policy sch = [t -> t -log(rand())/ra, t -> t + te] π₀, q̄ =reorder_point(qo, qmin, sch, t_stop; backorder) backorder ||return (p - c)*(1- π₀)*ra - c*h*q̄ -co*(1- π₀)*ra/qoreturn (p - c)*(1- π₀*g*te)*ra - c*h*q̄ - co*ra/qoendTPᵒrpsim, qoᵒsim, qminᵒsim =maximum((simTPrp(qo, qmin), qo, qmin) for qo in qos, qmin in qmins)TPᵒrpbosim, qoᵒbosim, qminᵒbosim =maximum((simTPrp(qo, qmin; backorder =true), qo, qmin)for qo in qos, qmin in qmins)
(12.35654981925875, 7, 0)
Neither best policy makes more than (p - c) r_a, every unit demanded sold with none held and no order placed, $18 a period, a Bounds check of Lecture 1.2, and Ex. 7(b) checks both against the formulas for Poisson demand.
Best policy by simulation with lost sales q_o^{*} = 6 units and q_{\min}^{*} = 1, at a total profit of $11.98 per period; with backorders 7 and 0 units, at $12.36
Poisson demand
As for base stock, Poisson demand gives the simulation’s measures without running it, because its measures have simple formulas; the simulation before it handles any other demand or lead time. For Poisson demand and a constant lead time, both measures of either the lost sales or backorder models are base stock’s, Eq. 11 and Eq. 10, averaged over the q_o levels, q_{\min} + 1 to q_{\min} + q_o, that the inventory position passes through, each stated in words over its formula:
with F and \mu as in Eq. 11 and Eq. 10. With backorders, each unit of demand lowers the inventory position by one, and each order placed at q_{\min} raises it by q_o, to q_{\min} + q_o. Between orders, then, the position spends one demand at each of the levels q_{\min} + q_o down to q_{\min} + 1, each equally often, and at each level the reorder point is base stock at that level: the units on hand when a demand arrives are the position a lead time earlier, y, less the demand during the lead time, so the demand finds none on hand when D_L \ge y, with probability 1 - F(y - 1; \mu), base stock’s Eq. 11 at q_{\max} = y. Each level then accounts for the same share of the demands, 1/q_o, so the reorder point’s measures are base stock’s averaged over the q_o levels, y = q_{\min} + \ell for \ell = 1 to q_o, the sums over \ell in Eq. 17 and Eq. 18: by hand, the average of q_o rows of Ex. 3’s table. With lost sales a lost demand leaves the position as it was, so the averages are an approximation, as base stock’s formulas are.
NoteCounted cycle by cycle
Counted cycle by cycle, from one order to the next, the measures for Poisson demand and a constant lead time are
TP ( q_{o} , q_{\min} ) = ( p - c ) ( 1 - \pi_{0} ) r_{a} - c \, h \, \bar{q} - c_{o} \, r_{o}
The assumptions are the same as those of the base stock model for Poisson demand and constant lead time.
The set up of Eq. 12 is similar to base stock, with two control knobs for total profit instead of one, and the additional term for ordering. The sum of cumulative probabilities is identical to base stock’s, but where for base stock it was the whole average inventory, since that was purely a safety stock problem, for the reorder point the same formula is labeled the safety stock component, Eq. 20. The average inventory level takes it and adds half the order quantity, which should look familiar from the truckload example of Lecture 3.3: once an order of q_o is received the inventory is at q_o above the safety stock, and just before the next one it is at none, so on average it is at half, an \alpha of one half in the cycle stock \alpha q of Lecture 6.1 (Eq. 5 in Lecture 6.1). Unlike trucking, where inventory could be counted at both the origin and the destination, here only the destination is looked at; the supplier’s decision is not modeled. Together, the safety stock and the cycle stock are the average inventory level. The other new quantity is the average order rate, Eq. 22, the arrival rate times one minus the fraction lost, divided by the quantity ordered each time: the number of orders placed per unit of time. With two decisions the problem is two-dimensional, the order points in the rows and the order quantities in the columns, and how many columns are needed is not obvious. A good heuristic is the economic order quantity (EOQ), the square root formula for the optimal truckload with \alpha equal to one half, which puts a 2 in the numerator: the square root of two times the order cost times the arrival rate over the carrying cost. The factor \beta of Eq. 23 goes beyond the EOQ because there is no logic saying that it would be optimal: profit is being maximized, not cost minimized.
There is no reason to stick to the economic order quantity itself, so some multiple of it is used, most often a \beta between 2 and 4. Using 2, and extending the range if profit is largest at its edge, keeps the search no bigger than it needs to be; that gives the maximum order quantity. All of the assumptions of the base stock model hold.
Eq. 19 is the probability that one cycle runs out before its order arrives. Set in total profit as if it were the fraction of all demand lost, it overstates the lost sales, and at q_o = 1, where the reorder point should be base stock at q_{\max} = q_{\min} + 1,Eq. 21 does not give base stock’s average on hand. That is why Model 3 takes the averages of Eq. 17 and Eq. 18 instead. At q_o = 1 these are base stock’s exactly, and with no fixed cost per order, c_o = 0,Model 3 is Model 1: the reorder point generalizes base stock. The first term of the sum in Eq. 17 is Eq. 19, the probability of running out at the lowest of the levels.
NoteBase stock and the reorder point, side by side
Basically the same model as base stock, with some things added for the reorder feature, the reorder point is best thought of as an incremental extension of base stock. Service is controlled in base stock by q_{\max} and in the reorder point by q_{\min}, two different sides of the equation for the probability of a lost sale, a customer whose demand is not satisfied: one minus the cumulative distribution function at q_{\min} for the reorder point, against one minus it at q_{\max} - 1 for base stock. The average on hand is calculated two different ways, base stock’s directly as the sum of cumulative probabilities and the reorder point’s as safety stock plus cycle stock, and the average order rates differ too. One thing base stock leaves off the table is the cost of ordering, assumed to be zero since it entered no calculation. If ordering one unit at a time cost enough, it could wipe out the profit, and to be exact it could be added to base stock’s total profit. In most cases it changes nothing, since orders are taken to be delivered all the time, so it is effectively zero and left off, but this is how it would be included.
The reorder-point cases below are the cycle forms of Eq. 19 and Eq. 21; Model 3 evaluates them as the averages of Eq. 17 and Eq. 18, which at q_o = 1 are the base-stock cases. Service is controlled by q_{\max} (base-stock) or q_{\min} (reorder-point) via the tail of D_{L} through the cumulative distribution function:
The implementations for Poisson demand average the functions of Model 1’s implementation over the levels:
Model 3 implementation: Poisson demand
# Model: reorder point with lost sales, Poisson demand, constant lead time# Fraction lost and average on hand, averaged over the q_o levelspi0rp(qo, qmin, μ) =sum(pi0(qmin + ℓ, μ) for ℓ in1:qo)/qoqbarrp(qo, qmin, μ) =sum(qbar(qmin + ℓ, μ) for ℓ in1:qo)/qoro(qo, qmin; ra = ra, μ = μ) = (1-pi0rp(qo, qmin, μ))*ra/qoTPrp(qo, qmin; co = co, h = h, ra = ra, μ = μ) = (p - c)*(1-pi0rp(qo, qmin, μ))*ra -c*h*qbarrp(qo, qmin, μ) -co*ro(qo, qmin; ra, μ)maxTPrp(qos, qmins) =maximum((TPrp(qo, qmin), qo, qmin) for qo in qos, qmin in qmins)
1
Base stock’s measure at each level q_{\min} + \ell the position passes through, averaged over the q_o levels, Eq. 17; Eq. 18 likewise.
2
The fixed cost per order is a keyword argument, as are the carrying rate, arrival rate and mean demand during a lead time, as in TP, each the example’s unless another is given.
3
Every pair of an order quantity and an order point is tried in turn, and the one with the largest total profit is kept.
maxTPrp (generic function with 1 method)
Model 4 implementation: Poisson demand
# Model: reorder point with backorders, Poisson demand, constant lead time# Total profit with the delay discount on the fraction backorderedTPrpbo(qo, qmin; co = co, h = h, ra = ra, μ = μ) = (p - c)*(1-pi0rp(qo, qmin, μ)*g*te)*ra -c*h*qbarrp(qo, qmin, μ) - co*ra/qo
1
pi0rp and qbarrp are those of Model 3’s implementation for Poisson demand, exact here, since every stockout is backordered. Every demand is sold in the end, so orders are placed at r_a / q_o a period. The keyword arguments are those of TPrp.
TPrpbo (generic function with 1 method)
Example 7: Reorder point with Poisson demand
The item of Ex. 3 now has a fixed cost of c_o = \$2 for each order placed, whatever its size. As in Ex. 3, two cases are considered, each on its own. In the first, demand that finds no unit on hand is lost, as in Model 3. In the second, it is backordered, as in Model 4, the cost of a backorder the delay discount of Ex. 3. Determine the order quantity and order point that maximize total profit in each case.
Example 7(a): Total profit of one policy by hand
Determine the total profit of ordering q_o = 5 units whenever the inventory position falls to q_{\min} = 2, with lost sales and with backorders, with Eq. 17 and Eq. 18, from the values of Ex. 3.
The position passes through the levels 3 to 7, and the fraction of demand lost is base stock’s at those levels, from Ex. 3’s table, averaged; at 7 it is 1 - F(6; 0.75) = 0.00001:
With backorders, every demand is sold, the unit profit on the fraction backordered reduced by the delay discount, g \, t_e = 0.5, and orders are placed at 6/5 = 1.2 a period, so total profit, Eq. 13, is
TP(5, 2) = \$11.62034 per period with lost sales by the averaged forms, against $11.54893 by the cycle forms, and $11.68502 with backorders
Example 7(b): Every policy and the best
Determine the total profit of every order quantity from 1 to q_{o,\max} and order point from 0 to one less than the upper bound of Eq. 5 with lost sales, and the policy that maximizes it with lost sales and with backorders.
The fixed cost per order joins the data of Code blocks 10 and 14, and Ex. 6(a)’s bound is computed from them:
# Code block 35: the fixed cost per order and the largest q_o to tryco =2# $/order, fixed cost per orderqomax =ceil(Int, 2sqrt(2ra*co/(c*h))) # units, β = 2 times the EOQ
11
The order point takes the place base stock’s maximum level less one has in the probability of a stockout, so it is searched up to one less than the bound of Eq. 5, at q_o = 1 the policies tried being base stock’s up to its bound:
Code block 36 evaluates Model 3 at every policy, the order points in the rows and the order quantities in the columns:
# Code block 36: total profit of every policyqos, qmins =1:qomax, 0:UBqmax-1# order quantities and points triedTPgrid = [TPrp(qo, qmin) for qmin in qmins, qo in qos]prt(TPgrid; rows = qmins, cols = qos, row_title ="qmin") # q_o across
With lost sales, the simulated fraction lost of Ex. 6(b), 0.0097, and total profit, $11.62, agree with these averaged forms, 0.0098 and $11.62, and not with the cycle forms, 0.0405 and $11.55: a Triangulate check of Lecture 1.2 that determines which of the two is right. With backorders, the simulated fraction backordered, 0.0098, and total profit, $11.69, are the averaged forms’ 0.0098 and $11.69 to within the sampling error of the simulation, the averaged forms being exact with backorders.
Row 3, q_{\min} = 2, column 5 is Ex. 7(a)’s calculation with lost sales. Code block 37 finds the best policy of each model:
# Code block 37: the best policy, lost sales and backordersTPᵒrp, qoᵒ, qminᵒ =maxTPrp(qos, qmins) # lost salesTPᵒrpbo, qoᵒbo, qminᵒbo =# backordersmaximum((TPrpbo(qo, qmin), qo, qmin) for qo in qos, qmin in qmins)(qoᵒsim, qminᵒsim) == (qoᵒ, qminᵒ), # the best policies of Ex. 6(c)(qoᵒbosim, qminᵒbosim) == (qoᵒbo, qminᵒbo)
(true, true)
These are the best policies the simulation of Ex. 6(c) found: with lost sales, at a total profit of $11.98 a period against the formulas’ $12.02, and with backorders, at $12.36 against $12.36. It is a Triangulate check of Lecture 1.2 on the decision.
Fig. 13 draws each row of the table. The best policy of each model is below Ex. 6(a)’s bound of 11 on the order quantity and the bound of 11 on the order point, so neither bound cut the search short.
Show the code that draws this figure
# Code block 38: total profit against q_o for each q_minfig =Figure(size = (600, 340))ax =Axis(fig[1, 1]; xlabel ="Order quantity (units)", ylabel ="Total profit (\$ per period)", xlabelsize =15, ylabelsize =15, xticklabelsize =13, yticklabelsize =13, xticks = qos)pal =cgrad(:Blues, length(qmins) +2; categorical =true)[3:end] # one step a q_min, light to darkfor (i, qmin) inenumerate(qmins)scatterlines!(ax, qos, TPgrid[i, :]; label = L"q_{\min} = %$qmin", color = pal[i], markersize =6)endscatter!(ax, [qoᵒ], [TPᵒrp]; color = optc, markersize =13)Legend(fig[1, 2], ax; labelsize =13, framevisible =false)fig
Figure 13: Total profit per period against the order quantity, one line for each order point, with the best policy of Code block 37 in maroon.
With lost sales, q_o^{*} = 6 units and q_{\min}^{*} = 1, at a total profit of $12.02 per period; with backorders, 7 and 0 units, at $12.36
Example 7(c): Base stock as a landmark
Check that each model with q_o = 1 and no fixed cost per order is base stock with the same stockout.
The reorder point should then be base stock at q_{\max} = q_{\min} + 1,Model 3 that of Model 1 and Model 4 that of Model 2, a Landmark check of Lecture 1.2:
# Code block 39: q_o = 1 and c_o = 0 is base stock at q_max = q_min + 1lostsales = [TPrp(1, qmin; co =0) for qmin in0:5] ≈ [TP(qmin +1) for qmin in0:5]backorders = [TPrpbo(1, qmin; co =0) for qmin in0:5] ≈ [TPbo(qmin +1) for qmin in0:5]lostsales, backorders
(true, true)
With q_o = 1 and c_o = 0, each model is base stock at every level
4. Multi-echelon inventory
Base stock and the reorder point hold inventory at a single location. A supply chain holds it at several, each level supplying the next, and the two possibilities of Sec. 1 for a stockout, a lost sale and a backorder, are not open at every level. A lost sale is possible only at the last level, the one facing the customers, where a stockout may be either. Further up, a stockout is almost always backordered.
Fig. 14 draws four levels of a supply chain, the four roles of the beer game of Sec. 5, a game in which a player runs each level, the retailer facing the customers at the right:
Show the code that draws this figure
# Code block 40: four levels of a supply chainshipc = colorant"#d21f26"# shipments of productinfoc = colorant"#0f9ad6"# demands and ordersnodec = colorant"#2e8b57"# stocking locationsnamec = colorant"#7a1f7a"# who is at each placeevtc = colorant"#4f8f2a"# what each arrow carrieslane!(ax, a, b, color) =# an arrow from a to b, as [x, y]arrows2d!(ax, [a[1]], [a[2]], [b[1] - a[1]], [b[2] - a[2]]; color, shaftwidth =2, tipwidth =10, tiplength =11)note!(ax, x, y, s; al = (:center, :top), size =13) =text!(ax, x, y; text = s, color = evtc, fontsize = size, align = al)# The four roles, upstream at the left, drawn over x0 to 15 across and# y0 to y1 up; returns the figure, its axis and where things arefunctionchain(x0, y0, y1) rn, lo, y =0.5, 0.24, 2.0# node radius, lane offset, center xs = [3.0, 5.9, 8.8, 11.7] # node centers yo, ys = y + lo, y - lo # orders above, shipments below rim =sqrt(rn^2- lo^2) # where a lane meets a node's edge cx =12.95# where the customers are w =600# pixels across h =round(Int, w*(y1 - y0)/(15- x0)) fig =Figure(size = (w +20, h +20), figure_padding =10) ax =Axis(fig[1, 1]; aspect =DataAspect())hidedecorations!(ax)hidespines!(ax)limits!(ax, x0, 15, y0, y1)for i in1:3# role i + 1 orders from role ilane!(ax, [xs[i+1] - rim, yo], [xs[i] + rim, yo], infoc)lane!(ax, [xs[i] + rim, ys], [xs[i+1] - rim, ys], shipc)endlane!(ax, [cx -0.1, yo], [xs[4] + rim, yo], infoc) # demandlane!(ax, [xs[4] + rim, ys], [cx -0.1, ys], shipc) who = ["Factory", "Distributor", "Wholesaler", "Retailer"]for (x, s) inzip(xs, who)poly!(ax, Circle(Point2f(x, y), rn); color =:white, strokecolor = nodec, strokewidth =2.5)text!(ax, x, y + rn +0.08; text = s, color = namec, fontsize =15, font =:bold, align = (:center, :bottom))endtext!(ax, cx, y; text ="Customers", color = namec, fontsize =15, font =:bold, align = (:left, :center))return fig, ax, (; xs, y, rn, yo, ys, rim, cx)endfig, ax, g =chain(1.9, 0.55, 3.1)for x in g.xs[1:3]note!(ax, x, g.y - g.rn -0.08, "stockout:\nbackorder")endnote!(ax, g.xs[4], g.y - g.rn -0.08,"stockout: lost\nsale or backorder")xm = (g.xs[1] + g.xs[2])/2# between factory and distributornote!(ax, xm, g.yo +0.07, "orders"; al = (:center, :bottom))note!(ax, xm, g.ys -0.07, "shipments")fig
Figure 14: Four levels of a supply chain, the retailer facing the customers at the right. A stockout at the retailer is a lost sale or a backorder; upstream it is a backorder. Orders run upstream in blue and shipments downstream in red.
Last echelon
Only the last level (or echelon) of a multi-echelon system holds finished goods inventory and is customer facing. Stockouts at this level impact revenue through lost sales and/or backorder costs. At the other levels, raw material and work-in-process inventory is held to support the last level, and stockouts at these levels are (typically) backordered, with (usually) no notion of lost sales.
At the retail level, a customer either walks in or goes to the website, and if the product is not available, the assumption is that the customer is not willing to wait for it to be backordered, either to come back to the store to pick it up or to have it shipped at a later date: it is just a lost sale. Whether people are willing to wait or just walk away depends on the product. A highly unique product, one of a kind, available nowhere else, is waited for, a week or two if need be. A commodity is not: a customer who finds the bag of Cheetos out of stock walks across the street to the 7-Eleven, which probably has exactly the same bag on its shelf, and the sale is lost. Every product falls somewhere in that spectrum.
Further back up the chain, when the wholesaler or distribution warehouse that supplies convenience stores is out of stock, the retailer does not say “forget it” and go get the product somewhere else. The distribution centers are sometimes owned by the same company, as 7-Eleven owns its own, and a one-of-a-kind store probably gets its product from a wholesaler that has distribution centers, but in either case it is an ongoing relationship: a store is not stocked by walking around picking suppliers at random every week. So other than at the last echelon, everything in Fig. 14 would be backordered. For a backorder to make sense in a model, there has to be some negative cost associated with it: a supplier that is out of stock half the time, or that makes every order wait a week, has some cost, and the problem in modeling it is how to actually come up with that cost. Supply chain management commonly does not even try to put a dollar figure on having to backorder, and uses service levels instead: a distribution center wants to be able to supply its customers with the product 98% or 95% of the time. Picking such a number in effect picks the percentile of the Poisson cumulative distribution to reach, and from it the probabilities follow and the model works. But a consultant who opens by asking a client what service level the client wants is not asking a meaningful question, and an honest client would answer that the consultant should determine it and deliver it as the recommendation: the service level that maximizes profit. Analyses done by just picking a 98% service level, asked how the 95% or 98% was picked, answer surprisingly often that it is just common in industry, sweeping an interesting question under the rug. A number should be traced down to how it would actually be determined.
Fig. 15 is a two-echelon supply chain, a supplier shipping to a distribution center (DC) that supplies two retailers, each facing its own customers:
Show the code that draws this figure
# Code block 41: the two-echelon supply chainshipc = colorant"#d21f26"# shipments of productinfoc = colorant"#0f9ad6"# demands and ordersnodec = colorant"#2e8b57"# stocking locationsnamec = colorant"#7a1f7a"# who is at each endevtc = colorant"#4f8f2a"# what each arrow carriesrn =0.42# node radius, data units# Centers of the DC and the two retailers, and the chain's two endsdc, r1, r2 = [4.0, 2.0], [7.6, 3.3], [7.6, 0.7]sup, cus1, cus2 = [1.3, 2.0], [10.1, 3.3], [10.1, 0.7]fig =Figure(size = (620, 220))ax =Axis(fig[1, 1]; aspect =DataAspect())hidedecorations!(ax)hidespines!(ax)limits!(ax, -0.9, 12.3, 0.05, 4.25)functionarrow!(a, b, color; off =0.0) # a to b, moved off sideways u = (b .- a) ./sqrt(sum(abs2, b .- a)) n = [-u[2], u[1]] # unit normal, to the left a, b = a .+ off .* n, b .+ off .* nreturnarrows2d!(ax, [a[1]], [a[2]], [b[1] - a[1]], [b[2] - a[2]]; color, shaftwidth =2, tipwidth =10, tiplength =11)endrim(p, q) = p .+ rn .* (q .- p) ./sqrt(sum(abs2, q .- p)) # p's edgearrow!(sup, rim(dc, sup), shipc)for r in (r1, r2)arrow!(rim(dc, r), rim(r, dc), shipc; off =-0.11)arrow!(rim(r, dc), rim(dc, r), infoc; off =-0.11)endlines!(ax, [sup[1], 4.3], [1.25, 1.25]; color = shipc, linewidth =2)arrow!([4.3, 1.25], rim(r2, [4.3, 1.25]), shipc)arrow!(cus1 .- [0.15, 0], rim(r1, cus1), infoc)arrow!(cus2 .- [0.15, 0], rim(r2, cus2), infoc)for (p, s) in ((dc, "DC"), (r1, "1"), (r2, "2"))poly!(ax, Circle(Point2f(p...), rn); color =:white, strokecolor = nodec, strokewidth =2.5)text!(ax, p...; text = s, color = namec, fontsize =16, font =:bold, align = (:center, :center))endname!(x, y, s, al) =text!(ax, x, y; text = s, color = namec, fontsize =16, font =:bold, align = al)name!(sup[1] -0.1, sup[2], "Supplier", (:right, :center))name!(cus1[1] +0.05, cus1[2], "Customer", (:left, :center))name!(cus2[1] +0.05, cus2[2], "Customer", (:left, :center))name!(r1[1], r1[2] +0.5, "Retailer", (:center, :bottom))θ =atan(r1[2] - dc[2], r1[1] - dc[1]) # slope of the DC-retailer linesevt!(x, y, s; rot =0.0, al = (:center, :bottom)) =text!(ax, x, y; text = s, color = evtc, fontsize =13, rotation = rot, align = al)evt!(2.55, 2.15, "sup2dc_ship")evt!(5.67, 2.81, "ret2dc_order"; rot = θ)evt!(5.95, 2.42, "dc2ret_ship"; rot = θ, al = (:center, :top))evt!(2.6, 1.15, "sup2dc2ret_ship"; al = (:center, :top))evt!(8.9, 3.38, "demand")fig
Figure 15: A two-echelon supply chain. Red arrows are shipments of product, blue arrows are demands and orders, and each green label names what its arrow carries.
In Fig. 15 the red lines represent actual shipments of product to a location and the blue lines the flow of information, the demands and the orders. Each green label is the name of the event on its arrow in a simulation of the chain, read from where to where, so that ret2dc_order is an order from a retailer to the DC. Each of the two retailers sees demand from its own customers, demand, and, with base stock, once a demand at a retailer occurs, the retailer sends an order to the DC, labeled ret2dc_order, the retailer-to-DC order. If there is inventory at the DC, a DC-to-retailer shipment, dc2ret_ship, follows. Both the order and the shipment are drawn, since stocking occurs at the DC as well. The arrow from the supplier through the DC, sup2dc2ret_ship, drawn to retailer 2 though it applies to retailer 1 as well, handles the need to backorder. When an order is placed on the DC and the DC is at zero inventory, the DC backorders it. It immediately sends an order to the supplier to cover the backorder, and, separately from the normal replenishment, the supplier-to-DC shipment, sup2dc_ship, the supplier ships through the DC directly to the retailer. The product does not go into storage at the DC: the backorder is cross-docked, as in Lecture 3.4. Its time is whatever the supplier-to-DC time is plus the DC-to-retailer time, with the cross-docking taken as instantaneous; a delay of a day or so could be added to be a bit more accurate.
Each echelon keeps its own stock by the bookkeeping of the reorder point (Sec. 3), with more of its units on their way to it, and the beer game of Sec. 5 uses these terms throughout:
Upstream and downstream: toward the supplier and toward the customers; orders travel upstream and shipments downstream, as in Fig. 14
Lead time: time from placing an order to receiving it, at an echelon the time the order takes to reach the supplier plus the time the shipment takes to come back
Backlog: units an echelon owes its customers and has not yet shipped, its backorders; above the last echelon every stockout becomes backlog
On order: units an echelon has ordered and not yet received, its orders on their way upstream, the backlog its supplier owes it, and the shipments on their way down
Inventory position: units on hand plus units on order, less the backlog, as in Sec. 3 (Fig. 11); an echelon’s order is judged against its position, not against its stock on hand
Key concepts
Three fundamental concepts are associated with managing inventory across multiple levels of a supply chain:
Risk pooling: aggregating uncertain demand across locations or products lowers total variability, reducing the overall safety stock required
Bullwhip effect: demand variability increasingly amplifies as orders move upstream in a supply chain, causing inefficiencies
Information sharing: providing upstream visibility to downstream data (like actual sales) dampens the bullwhip effect by allowing planning based on the true demand signal
To do any type of analysis of a multi-echelon system, simulation is really needed: not much can be done straight from formulas, since the calculations of Secs. 2 and 3 do not scale terribly well. So the focus is instead on the three key concepts.
Risk pooling
Risk pooling aggregates uncertainty: it combines demand variability across multiple locations or products. It reduces total variability: the aggregated demand is less volatile than the sum of individual demands, as highs and lows partially cancel out. And it lowers safety stock: it enables the supply chain to achieve the same service level with significantly less overall inventory compared to decentralized systems.
It makes sense: with lots of stocking points, duplicating one another, more inventory tends to be carried, since each wants stock on hand to use while its demand is much less, split among multiple locations, so centralizing means carrying less inventory on average. Ex. 8 illustrates it with the same problem as base stock’s Ex. 3, set up as the same operation at nine decentralized warehouses all over the country, against the alternative of one centralized warehouse.
Example 8: Risk pooling
Using the same base stock example of Ex. 3 and Model 1, compare the total profit and the inventory of 9 regional (decentralized) warehouses, each facing the demand of Ex. 3, vs. 1 centralized warehouse facing the demand of all nine regions, with the same lead time.
Example 8(a): Nine regional warehouses by hand
Determine the total profit and the average inventory of the nine regional warehouses together, from Ex. 3.
Each regional warehouse is Ex. 3’s: its best maximum level is q_{\max} = 3, at a total profit of $15.23817 per period with an average of 2.25850 units on hand (Ex. 3(a)). With TP^{(n)} and \bar q^{(n)} the total profit and the average inventory of n warehouses together, the nine make nine times the profit of one:
TP^{(9)} = 9 \times 15.23817 = \$137.14353 \text{ per period}
Each holds at most 3 units, so the nine together hold at most 27. One warehouse facing all of their demand should need far fewer, a Prior check of Lecture 1.2 that Ex. 8(b) answers.
TP^{(9)} = \$137.14353 per period, \bar q^{(9)} = 20.32650 units
Example 8(b): One central warehouse
Determine the maximum level that maximizes the central warehouse’s total profit, and its total profit and average inventory at that level.
The central warehouse faces the demand of all nine regions, nine times the arrival rate of one, with the same lead time, so its mean demand during a lead time is nine times as large:
# Code block 42: one central warehouse, the nine regions' demand pooledrapool =9ra # units/period, pooled arrival rateμpool = rapool*te # units, mean demand in a lead timeUBpool =2round(Int, rapool) # units, the upper bound on q_maxTPpool, qmaxpool =maxTP(0:UBpool; ra = rapool, μ = μpool)qbarpool =qbar(qmaxpool, μpool) # units, average on hand at the best(TP = TPpool, qmax = qmaxpool, qbar = qbarpool)
Fig. 16 draws the central warehouse’s total profit at the levels tried from 0 to 20, around its best, beside the total profit of the nine regional warehouses at their best from Ex. 8(a).
Show the code that draws this figure
# Code block 43: the central warehouse's total profit against q_maxqpool =0:20# units, the levels around the bestTPnine =round(9TPᵒ, digits =2) # $/period, Ex. 8(a)'s totalfig =Figure(size = (600, 320))ax =Axis(fig[1, 1]; xlabel ="Maximum inventory level (units)", ylabel ="Total profit (\$ per period)", xlabelsize =15, ylabelsize =15, xticklabelsize =13, yticklabelsize =13)scatterlines!(ax, qpool, TP.(qpool; ra = rapool, μ = μpool); color = bluec, label ="One central warehouse")hlines!(ax, [9TPᵒ]; color = grayc, linestyle =:dash, label ="Nine regional warehouses, \$$TPnine")scatter!(ax, [qmaxpool], [TPpool]; color = optc, markersize =13)text!(ax, qmaxpool, TPpool; text ="\$$(round(TPpool, digits =2))", align = (:center, :bottom), offset = (0, 8), fontsize =13)ylims!(ax, -5, 180)axislegend(ax; position =:rb, labelsize =13)fig
Figure 16: Total profit per period of one central warehouse against its maximum inventory level, with its best level in maroon, and the total profit of nine regional warehouses at their best levels, dashed.
q_{\max}^{*} = 14 units, at a total profit of $153.91 per period, with 7.26 units on hand on average
The best level, 14 units, is far below the 27 the nine regional warehouses hold at most, as the Prior check of Ex. 8(a) expected.
Example 8(c): Comparison by hand
Determine how much less inventory the central warehouse holds than the nine regional warehouses, and how much more profit it makes.
The central warehouse holds 7.25685 units on average, from Ex. 8(b), against the 20.32650 of the nine regional warehouses, from Ex. 8(a), a fraction less of
About 64% less inventory (0.64299) and 12.2% more profit (0.12225) with one central warehouse
Example 8(d): Comparison in code
Compute the comparison of Ex. 8(a) to 8(c), and compare it with the values by hand.
Code block 44 sets the two side by side, the nine regional warehouses at Ex. 3’s best level of Code block 15, each warehouse’s level and fraction lost, and the nine’s inventory and profit together:
# Code block 44: nine regional warehouses against one central warehouseTP9 =9TPᵒ # $/period, nine times Ex. 3's bestqbar9 =9qbar(qmaxᵒ, μ) # units, nine times its average on handprt(DataFrame(warehouses = ["nine regional", "one central"], qmax = [qmaxᵒ, qmaxpool], pi0 = [pi0(qmaxᵒ, μ), pi0(qmaxpool, μpool)], qbar = [qbar9, qbarpool], TP = [TP9, TPpool]))
warehouses qmax pi0 qbar TP
────────────────────────────────────────────
nine regional 3 0.0405 20.33 137.14
one central 14 0.0096 7.26 153.91
Code block 45 computes the two fractions of Ex. 8(c):
# Code block 45: less inventory and more profit, as fractions(less_inventory =1- qbarpool/qbar9, more_profit = TPpool/TP9 -1)
The code’s 64.3% less inventory and 12.2% more profit agree with Ex. 8(c), and the central warehouse also loses less of its demand, 0.96% against 4.05%. A version of this example from an earlier offering of the course gives the central warehouse’s inventory as 5.82 units, where its own calculation gives 7.26, and the 64% less inventory it reports beside it is 1 - 7.26/20.33: the 5.82 is a slip, which a Source check of Lecture 1.2 finds.
One central warehouse: 64.3% less inventory and 12.2% more profit than nine regional warehouses
What is the tradeoff with using a centralized warehouse? Transport costs can be much higher. Is centralizing, then, always a good thing? From an inventory perspective, yes: risk pooling by centralizing will probably always reduce the amount of inventory. But like everything in supply chains, it is a tradeoff. By centralizing, transportation costs are probably going to be a lot higher if the same lead times are wanted. Nine distribution centers distributed all over the country are probably within one day of every customer, whereas one centralized distribution center, to be within one day, has to ship expedited, overnight, to make it from Missouri to North Carolina. So either the lead time is longer or some type of expedited shipping is used, and there is always a cost associated with it. Ex. 8 is not a complete analysis: its profit went up because it ignored any potential increase in transport cost. An analysis of the increase in transport cost of centralizing might find that it more than offsets the increase in profit. Risk pooling is not always a win, but it is a way of helping the inventory side of the equation.
Bullwhip effect
The bullwhip effect amplifies variability: small changes in end-customer demand create increasingly larger swings in orders placed further upstream in the supply chain. It is caused by local reactions, driven by factors like batch ordering, individual forecast updates, fluctuations in the price, and shortage gaming at each echelon. And it creates inefficiencies: it results in excessive inventory, stockouts, poor capacity utilization, and higher costs throughout the supply chain. In shortage gaming, a supplier limits the quantity it ships to a percentage of each order. Its buyers, knowing it, place larger orders in the hope of getting closer to the quantity they actually want. The ordering information the supplier receives is then inconsistent, which may feed into the bullwhip effect.4
At the first level, one option is the reorder point and another is base stock, which places an order every time there is a demand, and if base stock is done all the way through the supply chain, the bullwhip effect is not a problem. The problem arises with batching, as in the reorder point of Sec. 3, where a fixed cost is associated with placing an order: ordering one unit at a time is not wanted, and orders are batched to spread that fixed cost. Then the level upstream does not see individual customer orders. All it sees is nothing, and then all of a sudden an order for ten units of something, then nothing again, then ten units. As in the discussion of cycle time in Lecture 1.3, the batching can make a big increase in the squared coefficient of variation (Eq. 2 in Lecture 1.3), a much more variable system at the next level up. Visually it looks like a bullwhip, its amplitude increasing up the supply chain, which is where the term comes from. The main cause of the bullwhip effect is probably batch ordering.
A sale, the one time the price is low, makes a sudden big spike in the demand for a product, and with no information sharing the upstream supplier does not know that it was a one-time thing, because the product was on sale that month, with perhaps another sale, and another increase, in three or four months. The supplier might forecast that the demand for the product is actually increasing and, to account for it, increase the amount it orders and carry more safety stock. So without information sharing, at every level up the supply chain this can result in big increases in the amount of inventory. Ex. 9 looks at the bullwhip effect from the factory physics point of view of Lecture 1.3, in terms of the squared coefficient of variation. One of the main takeaways of factory physics is that whenever variability increases, things do not work out well: it causes all kinds of difficulties, and that is the main takeaway of the bullwhip effect.
Example 9: Bullwhip from batching
The item of Ex. 6 is sold from a warehouse that orders q_o = 5 units from its factory whenever its inventory position falls to q_{\min} = 2. Determine how variable the units the warehouse orders from the factory each period are, against the units its customers demand each period.
Example 9(a): Customer demand by hand
Determine the mean, variance and squared coefficient of variation of the units the customers demand each period.
The units demanded in a period are a Poisson count, as the demand during a lead time is (Eq. 6), with mean r_a = 6 for a period of length one, and the variance of a Poisson count equals its mean:
\sigma^2_{\text{customer}} = r_a = 6
Its squared coefficient of variation (SCV) of Lecture 1.3 (Eq. 2 in Lecture 1.3), with the mean r_a in the place of t, is
Simulate the warehouse with lost sales for 100,000 periods, and determine the mean, variance and squared coefficient of variation of the units demanded and of the units ordered each period.
Code block 46 defines two helpers: the squared coefficient of variation of a series, and the units in each period, counted from the times at which they occur:
# Code block 46: the SCV of a series, and units per period from timesscv(x) =var(x)/mean(x)^2# squared coefficient of variationfunctionperperiod(t, P) # units in each of periods 1 to P n =zeros(Int, P)for tᵢ in t # a unit at time tᵢ is in period ⌊tᵢ⌋ + 1 n[floor(Int, tᵢ) +1] +=1endreturn nend
perperiod (generic function with 1 method)
Code block 47 extends reorder_point, the simulation implementation of Model 3 with lost sales, to record the time of each demand, each sale, and each unit ordered, an order of q_o being q_o units ordered at the same time:
# Code block 47: the times of demands, sales and units orderedfunctiondemand_and_orders(qo, qmin, sch, t_stop) E = [(0.0, :demand)] # event calendar (time, kind) q = qmin + qo # state: units on hand, at the maximum pos = q # inventory position: on hand + on order tdem, tsold, tplaced =Float64[], Float64[], Float64[]while !isempty(E) t, evt =popfirst!(E) # the earliest event, out of E t > t_stop &&break# stop the simulation at t_stopif evt ==:demandpush!(tdem, t)schedule!(E, sch[1](t), :demand)if q >0# a sale lowers on hand and position q -=1 pos -=1push!(tsold, t)if pos == qmin # q_o units ordered from the factory pos += qoappend!(tplaced, fill(t, qo))schedule!(E, sch[2](t), :arrival)endendelse# an order of q_o arrives q += qoendendreturn tdem, tsold, tplacedend
demand_and_orders (generic function with 1 method)
Code block 48 runs it at the policy of Ex. 7(a) for the 100000 periods of Code block 5, with the time between units, the measure Lecture 1.3 uses for arrivals, as a last column:
# Code block 48: units demanded and ordered at q_o = 5, q_min = 2Random.seed!(1234) # the draws of Code block 3tdem, tsold, tplaced =demand_and_orders(5, 2, [demand, arrival], t_stop)P =floor(Int, t_stop) # periods simulatedn =perperiod.([tdem, tplaced], P) # units demanded, ordered, by periodprt([mean.(n) var.(n) scv.(n) scv.(diff.([tdem, tplaced]))]; rows = ["demanded", "ordered"], row_title ="units", cols = ["mean", "var", "scv", "scv_between"], fracdig =3)
units mean var scv scv_between
───────────────────────────────────────────
demanded 6.011 6.060 0.1677 1.003
ordered 5.953 9.662 0.2727 4.962
The simulated demand, a mean of 6.01 units a period with a variance of 6.06 and an SCV of 0.168, agrees with Ex. 9(a), a Triangulate check of Lecture 1.2. The units ordered have nearly the same mean, less the few sales lost, but a variance 1.59 times the demand’s. Fig. 17 draws the first 40 periods, the demand given to the retailer in red and the orders its policy determines in blue: the orders come five units at a time, and swing further than the demand.
Show the code that draws this figure
# Code block 49: units demanded and ordered in the first 40 periodsper =1:40# periods drawnvd, vo =round.(var.(n), digits =2)fig =Figure(size = (600, 300))ax =Axis(fig[1, 1]; xlabel ="Period", ylabel ="Units", xlabelsize =15, ylabelsize =15, xticklabelsize =13, yticklabelsize =13)scatterlines!(ax, per, n[1][per]; color = givc, markersize =6, label ="Demanded, variance $vd")scatterlines!(ax, per, n[2][per]; color = bluec, markersize =6, label ="Ordered, variance $vo")ylims!(ax, -0.5, maximum(n[2][per]) +6)axislegend(ax; position =:lt, labelsize =13, orientation =:horizontal)fig
Figure 17: Units demanded by the customers, given, in red, and units ordered from the factory, determined by the policy, in blue, in each of the first 40 periods of Code block 48’s simulation, each with its variance over all the periods.
Which measure the bullwhip is read on matters. Counted per period, or per unit as Lecture 1.3 counts arrivals, batching raises it: the factory sees units in lumps. Counted per order, batching lowers it, since a batch is placed every fifth sale, more regularly than the sales arrive; that measure counts orders, not units. A version of this example from an earlier offering of the course treats the orders as a Poisson process of batches of five, at an order rate of 1.15 a period, which gives the units ordered a variance of 1.15 \times 5^2 = 28.75, nearly five times the customers’. The simulated orders are placed every fifth sale, not at random, so they are more regular than that, and their variance, 9.66, is 1.59 times the customers’: the batching amplifies the variability, by less than the earlier version found, which a Source check of Lecture 1.2 shows.
Units ordered: variance 9.66 a period, 1.59 times the customers’
Example 9(c): Base stock as a landmark
Check that with one unit ordered at a time, the warehouse passes the units it sells to the factory unchanged.
With q_o = 1 and q_{\min} = 2 the reorder point is base stock at q_{\max} = 3 (Ex. 7(c)): each sale orders one unit, so the units ordered should be exactly the units sold, a Landmark check of Lecture 1.2:
# Code block 50: q_o = 1, base stock, orders exactly the units soldRandom.seed!(1234) # the draws of Code block 3_, tsold1, tplaced1 =demand_and_orders(1, 2, [demand, arrival], t_stop)tplaced1 == tsold1 # the same units, at the same times
true
Units ordered from the factory each period at q_o = 5,q_{\min} = 2: variance 9.66, 1.59 times the customers’ 6.06; at q_o = 1, base stock, the units ordered are the units sold
Information sharing
Information sharing provides visibility: it gives upstream partners (e.g., factories) access to downstream data like real-time customer sales or inventory levels. It dampens the bullwhip effect: it allows upstream planning based on the less volatile, true end-customer demand signal, rather than amplified order patterns. And it improves coordination: it enables better synchronization between echelons, leading to reduced overall inventory and improved efficiency.
The problem is that when the next level up in the supply chain is a completely separate company, information is not always wanted to be shared; it might be viewed as somehow proprietary. Sharing, perhaps not everything but limited information about a product, helps the upstream supplier better forecast when it needs to make shipments to satisfy the demand. Companies like Walmart have been sharing information with their suppliers for probably 30 years. A supplier of Cheetos to Walmart’s distribution centers probably gets information daily on the demand at each Walmart store for each particular type of Cheetos product, in real time, every time a sale is made, and uses it to figure out how much it should be shipping to the distribution center and ultimately onward to the individual stores. Walmart does not do it out of the goodness of its heart: it gives the supplier the information, but it also pays less per bag of Cheetos, since the supplier has to carry less safety stock now that information is shared. It is part of an ongoing negotiation.
5. Beer game
Classic beer game
Instead of trying to come up with some type of analytical model, one way to illustrate the bullwhip effect is to play a game that has been around for a long time, called the beer game. Before it was played on a computer, it was played on the floor, with boards and cards. Above the customers, the players are the retailer, the wholesaler and, as players three and four, the distributor and the factory. The classic beer game is set up with essentially zero information sharing: all the wholesaler sees is the orders from the retailer, and the retailer is the only part of the supply chain that actually sees the customers’ demand.
Beer flows downstream and orders flow upstream. Each week a player receives an incoming shipment from upstream, beer ordered four weeks before, and with actual game boards and moving pieces, managing all of this by hand, things got messed up. Each player ships beer to fill the orders it has, and a player without enough inventory creates a backlog that must be filled later, in effect a backorder: everything is backordered. The critical decision is how much to order from the supplier. The game is rigged a little. In the first couple of periods demand is fairly constant, and then there is a big spike, two or three times as much demand for one order period. That one spike at the customer level propagates up the supply chain. The next level up sees the single increase and, depending on how it was managing its inventory, may not have enough, so the spike forces it into a backorder. Out of stock, the player at that level bumps up how much it orders, not realizing that it was a one-time spike, and there is always a two-week delay going up the supply chain. When the game is done, the actual demand can be plotted. In a game played for an entire year with weekly ordering, the customer demand was perfectly flat except in the third week, when one little blip was three times higher than normal. In the inventory profiles all the way upstream, that one blip leaves some players, months into the year, holding six months’ worth of inventory, which is where the bullwhip aspect comes from: crazy big increases.
Another version of the game records its metrics. In it, the actual customer demand is four units a week until, from the fourth to the fifth week, it goes up to eight units, and it stays at eight units the rest of the year. The retailer does not know what the future holds, so every week it increases the amount it orders, until by week seven it realizes that demand is not actually increasing but steady again, and levels off; by the end of the year it is almost back to matching customer demand, but it takes 16 weeks to get back to where it was. At the factory, the little change from week 4 to week 5 translated, about three months later, into a super high inventory level. This has been recorded everywhere, and even today, with information sharing, it is still an issue. The game is evaluated by its costs, calculated weekly. A player is charged $0.50 for each unit that remains in its inventory at the end of the week and $1.00 for each unit backlogged at the end of the week.5
Playing the game
Two teams each play the retailer and the wholesaler. The distributor and the factory follow base stock (Ex. 10), ordering exactly what reaches them. The class plays 12 weeks. A role sees only its own stock on hand, its own backlog, the shipment that reaches it and the order that reaches it; only the retailer sees what the customers order. The one decision a role makes each week is how much to order from its supplier, and at the factory how much to brew.
Each week runs in five steps, the five of the algorithm beergame in Ex. 10(b), and every role takes each step at the same time:
Receive. Add the shipment arriving this week to the stock on hand. At the factory, this is the beer that finishes brewing.
Read the order. Read the order arriving this week: at the retailer, the customers’ order; at every other role, the order its customer placed two weeks before.
Ship. Ship the order arriving plus any backlog, as far as the stock on hand allows. What cannot be shipped is added to the backlog and shipped in a later week; no sale is lost.
Count the cost. At the end of the week, each unit on hand costs $0.50 and each unit backlogged $1.00.
Order. Determine how much to order from the supplier. The order reaches the supplier two weeks later, and what the supplier ships reaches the role two weeks after that. At the factory the order is a brewing request, ready three weeks later.
Two quantities do the bookkeeping. What is shipped is limited by what is on hand,
with on order and backlog as Sec. 4 defines them. Every role starts at base stock’s position for customers ordering 4 units a week, 28 units, and the factory at 24 (Ex. 10(a)); ordering each week exactly what arrived keeps the position there, which is base stock (Ex. 10(b)).
Table 4 is the record each role keeps, one row a week, its columns in the order of the five steps:
Table 4: The record each role keeps, one row a week
Week
Received
Order arrived
Shipped
On hand
Backlog
Cost
Ordered
1
2
3
The game is evaluated by the total cost of the whole chain, the four roles’ weekly costs added up over the weeks played, not by any one role’s cost. After the last week, the orders each role placed are set beside the orders it received, as in Fig. 20: a role whose orders placed vary more than the orders it received, the larger variance of Ex. 9, has amplified the variability passed to it, the bullwhip effect.
Example 10: Beer game under two policies
A retailer, a wholesaler, a distributor, and a factory play the beer game of Table 5 for 20 weeks, while customer demand steps from 4 units a week to 8 in week 5. Determine the orders each role places when every role follows base stock at the position the game starts it in, and when every role follows a reorder point that orders batches of q_o = 12 units whenever its position is at or below q_{\min} = 24 units.
Fig. 18 sets the game out on the chain of Fig. 14, as it stands at the start:
Show the code that draws this figure
# Code block 51: the beer game at the start# One panel of the chain, drawn the same here and in Code block 55: role k# at xs[k], upstream at the left, over 0 to w across in px pixelsbp = (; xs = [2.4, 4.8, 7.2, 9.6], y =1.0, rn =0.48, lo =0.26, w =12.45, px =632)ppu = bp.px/bp.w # pixels per unit, every panelfunctionnum!(ax, x, y, new, old; c = namec) # old struck, beside new wn, wo =0.18length(new), 0.15length(old) # widths, data units xn =new== old ? x : x + (wo +0.08)/2# the pair centered on xifnew!= old xo = xn - (wn + wo)/2-0.08text!(ax, xo, y; text = old, color = grayc, fontsize =13, align = (:center, :center))poly!(ax, Rect2f(xo - wo/2, y -0.015, wo, 0.03); color = grayc)endtext!(ax, xn, y; text =new, color = c, fontsize =15, font =:bold, align = (:center, :center))returnnothingendbox!(ax, x, y, v, c) =# one week of a delay (scatter!(ax, [x], [y]; marker =:rect, markersize =32, color =:white, strokecolor = c, strokewidth =1.2);text!(ax, x, y; text =string(v), color = c, fontsize =13, align = (:center, :center)))functionbeer_axis(pos, lo, hi) # a panel's axis, lo to hi up ax =Axis(pos; aspect =DataAspect())hidedecorations!(ax)hidespines!(ax)limits!(ax, 0, bp.w, lo, hi)return axend# held: each role's (new, old), factory first; ords and ships: each lane's# boxes, left then right; prod: production, the next to arrive firstfunctionbeer_panel!(ax, held, ords, ships, prod, dem; label ="", names =false) (; xs, y, rn, lo) = bp yo, ys, rim = y + lo, y - lo, sqrt(rn^2- lo^2) cx = xs[4] + rim +0.75# where the customers arefor k in1:3# role 5 - k supplies role 4 - klane!(ax, [xs[k+1] - rim, yo], [xs[k] + rim, yo], infoc)lane!(ax, [xs[k] + rim, ys], [xs[k+1] - rim, ys], shipc) m = (xs[k] + xs[k+1])/2for j in1:2# the left box, then the rightbox!(ax, m +0.24(2j -3), yo, ords[k][j], infoc)box!(ax, m +0.24(2j -3), ys, ships[k][j], shipc)endendlane!(ax, [cx -0.1, yo], [xs[4] + rim, yo], infoc) # demandlane!(ax, [xs[4] + rim, ys], [cx -0.1, ys], shipc)lane!(ax, [xs[1] -2.25, ys], [xs[1] - rim, ys], shipc) # brewedfor (j, v) inenumerate(prod)box!(ax, xs[1] -0.9-0.48(j -1), ys, v, shipc)endfor k in1:4poly!(ax, Circle(Point2f(xs[k], y), rn); color =:white, strokecolor = nodec, strokewidth =2)num!(ax, xs[k], y, held[k]...)endnum!(ax, cx +0.45, yo, dem...; c = infoc) # customer demandtext!(ax, xs[1] -2.35, y +0.42; text = label, fontsize =15, font =:bold, align = (:left, :center)) names ||returnnothing who = ["Factory", "Distributor", "Wholesaler", "Retailer"]for (x, s) inzip(xs, who)text!(ax, x, y + rn +0.06; text = s, color = namec, fontsize =15, font =:bold, align = (:center, :bottom))endtext!(ax, cx +0.05, y + rn +0.06; text ="Customers", color = namec, fontsize =15, font =:bold, align = (:left, :bottom))returnnothingendfig =Figure(size = (bp.px +8, round(Int, ppu*1.73) +8), figure_padding =4)ax =beer_axis(fig[1, 1], 0.2, 1.93)four =fill((4, 4), 3) # each lane's two weeks, 4 unitsbeer_panel!(ax, fill(("12", "12"), 4), four, four, fill(4, 3), ("4", "4"); names =true)x1, ys, yo = bp.xs[1], bp.y - bp.lo, bp.y + bp.lolane!(ax, [x1 -0.4, yo], [x1 -2.25, yo], infoc) # to brewtext!(ax, x1 -2.35, bp.y + bp.rn +0.06; text ="Brewery", color = namec, fontsize =15, font =:bold, align = (:left, :bottom))note!(ax, x1 -1.38, ys -0.24, "3 weeks"; size =13)note!(ax, bp.xs[4] +1.6, ys -0.2, "8 from week 5"; size =13)fig
Figure 18: The beer game’s chain of Fig. 14 at the start of the game: each role holds 12 units, each week of a delay holds 4, two weeks of orders on each blue arrow and two of shipments on each red one, three weeks of production from the brewery into the factory, and the customers’ demand is 4 units a week, 8 from week 5.
Table 5 sets out the rules, with the name each has in the code that plays the game.
Table 5: Rules of the beer game
Rule
Value
Name in code
Roles, from the customer up
retailer, wholesaler, distributor, factory
roles 1 to 4
Order delay, to supplier
2 weeks
tord
Shipping delay, to role
2 weeks
tship
Production delay, factory
3 weeks
tprod
On hand at start, each role
12 units
I0
Each delay week at start
4 units
q0
Holding cost
$0.50 a unit on hand, week’s end
chold
Backlog cost
$1.00 a unit backlogged, week’s end
cback
Customer demand
4 units a week, 8 from week 5
weekly
Example 10(a): Starting position by hand
Determine the inventory position each role starts the game in.
Each role starts with 12 units on hand, and the game starts steady, with 4 units in each week of every delay. For the retailer, the wholesaler and the distributor, the units on order are 2 weeks of orders on their way to the supplier and 2 weeks of shipments on their way back, the rate times the time by Little’s Law, as for the working stock of Lecture 6.1 (Eq. 5 in Lecture 6.1). The inventory position, the units on hand plus the units on order of Sec. 4, is
q_{\max} = 12 + 4(2 + 2) = 28 \text{ units}
The factory’s units on order are its 3 weeks of production:
q_{\max} = 12 + 4(3) = 24 \text{ units}
These are base stock’s maximum levels for a demand of 4 units a week, as Ex. 1(a)’s Balance check has the units on hand and on order adding up to q_{\max}.
Starting position 28 units for the retailer, the wholesaler and the distributor, 24 for the factory
Example 10(b): Base stock in simulation
Simulate the 20 weeks with every role following base stock, and determine the orders each role places.
The game is played one week at a time, in five steps, as the algorithm beergame sets out, with d_t the customer demand in week t,T the number of weeks played, q_0 the units in each week of a delay at the start, I_0 each role’s units on hand at the start, and, for role i,I_i and B_i its units on hand and backlogged, a_i the order that arrives, x_i the units it ships, p_i its inventory position, and q_i the order it places; each shipment and order arrives after its delay in the rules table:
algorithm beergame;{ input: each week's customer demand; the roles, retailer to }{ factory; the delays, starting stock and costs of the }{ rules table; and a policy that sets each order }{ output: each role's units received, shipped, on hand, }{ backlogged and ordered, and its cost, each week }begin put q₀ units in each week of every delay; Iᵢ := I₀ and Bᵢ := 0 for each role i; for t := 1 to T do begin { 1. each role receives the shipment due } for each role i do Iᵢ := Iᵢ + the shipment due at i; { 2. the orders due arrive } a₁ := dₜ; for i := 2 to 4 do aᵢ := the order due from role i − 1; { 3. each role ships what it can, backlogs the rest } for each role i do begin xᵢ := min{Iᵢ, aᵢ + Bᵢ}; Bᵢ := aᵢ + Bᵢ − xᵢ and Iᵢ := Iᵢ − xᵢ; if i > 1 then send xᵢ to role i − 1; end; { 4. the week's cost } for each role i do cᵢₜ := 0.50 Iᵢ + 1.00 Bᵢ; { 5. each role orders, by its policy } for each role i do begin pᵢ := Iᵢ + units on order for i − Bᵢ; qᵢ := policy(i, t, aᵢ, pᵢ); if i < 4 then send qᵢ to role i + 1 else start qᵢ in production; end; end;end;
Code block 52 is beergame in Julia, step for step. At the retailer the order that arrives is the customer demand, and the order a role places is determined by a policy, from the role, the week, the order that arrived, and the role’s inventory position:
# Code block 52: the beer game, one week at a timefunctionbeergame(order, d; tord =2, tship =2, tprod =3, I0 =12, q0 =4, chold =0.50, cback =1.00) T, n =length(d), 4# weeks, roles# shipments on their way to each role and orders on their way from# each role to its supplier, one slot a week, q0 in each at the start inship = [fill(q0, i < n ? tship : tprod) for i in1:n] inord = [fill(q0, tord) for i in1:n-1] onhand, backlog =fill(I0, n), zeros(Int, n)# by week and role: units received, orders arrived, units shipped,# on hand, backlogged, the position, units ordered, and the cost R, A, X, I, B, P, Q = (zeros(Int, T, n) for _ in1:7) C =zeros(T, n)for t in1:Tfor i in1:n # 1. receive a shipment R[t, i] =popfirst!(inship[i])push!(inship[i], 0) onhand[i] += R[t, i]end A[t, 1] = d[t] # 2. an order arrivesfor i in2:n A[t, i] =popfirst!(inord[i-1])push!(inord[i-1], 0)endfor i in1:n # 3. ship what can be shipped due = A[t, i] + backlog[i] X[t, i] =min(onhand[i], due) onhand[i] -= X[t, i] backlog[i] = due - X[t, i]if i >1# on its way to role i - 1 inship[i-1][end] = X[t, i]endend I[t, :] = onhand # 4. record, and the cost B[t, :] = backlog C[t, :] = chold*onhand + cback*backlogfor i in1:n # 5. place an order onorder =sum(inship[i]) + (i < n ? sum(inord[i]) + backlog[i+1] :0) P[t, i] = onhand[i] + onorder - backlog[i] Q[t, i] =order(i, t, A[t, i], P[t, i])if i < n inord[i][end] = Q[t, i]else# a production request inship[n][end] = Q[t, i]endendendreturn (; R, A, X, I, B, P, Q, C)end
1
A role’s units on order are those on their way to it and, for all but the factory, its orders still on their way to the supplier and the units its supplier has backlogged for it; the position is Sec. 4’s, on hand plus on order, less what the role itself owes.
beergame (generic function with 1 method)
Code block 53 sets the customer demand, the roles and the two policies. Base stock replaces each unit ordered from a role, so it orders what was ordered; the reorder point orders whole batches of q_o:
# Code block 53: customer demand, the roles and the two policiesweekly(T; d1 =4, d2 =8, tstep =5) = [t < tstep ? d1 : d2 for t in1:T]roles = ["Retailer", "Wholesaler", "Distributor", "Factory"]basestock_policy(i, t, a, p) = a # order what was orderedreorder_policy(qmin, qo) = (i, t, a, p) -> p ≤ qmin ? qo*(fld(qmin - p, qo) +1) :0
1
Whole batches of q_o until the position p is above q_{\min},fld(qmin - p, qo) + 1 of them, since one week’s orders can take the position more than one batch below it.
reorder_policy (generic function with 1 method)
Code block 54 plays base stock. Each role’s position after its first order is Ex. 10(a)’s:
# Code block 54: base stock, 20 weeksdw =weekly(20) # units/week, customer demandbs =beergame(basestock_policy, dw)bs.P[1, :] + bs.Q[1, :] # each role's position, after ordering
4-element Vector{Int64}:
28
28
28
24
Fig. 19 shows the game in play under base stock, the chain at the end of each week from week 4, still as it started, to week 8, as the customer demand steps up from 4 to 8 in week 5:
Show the code that draws this figure
# Code block 55: the chain at the end of each week, base stockwv(M, t, i) = t ≥1 ? M[t, i] :4# a week's value, 4 beforeheld(g, t, i) = t ≥1&& g.B[t, i] >0 ? "−$(g.B[t, i])":string(t ≥1 ? g.I[t, i] :12) # on hand, or −backlogfunctionbeer_week!(ax, g, t, d; names =false) # g, Code block 52'sbeer_panel!(ax, [(held(g, t, 5- k), held(g, t -1, 5- k)) for k in1:4], [(wv(g.Q, t -1, 4- k), wv(g.Q, t, 4- k)) for k in1:3], [(wv(g.X, t, 5- k), wv(g.X, t -1, 5- k)) for k in1:3], [wv(g.Q, s, 4) for s in t-2:t], # 3 weeks of production (string(d[t]), string(d[max(t -1, 1)])); label ="Week $t", names)returnnothingendfunctionbeer_weeks(g, weeks, d) # one panel a week, top to bottom his = [r ==1 ? 1.93:1.6 for r ineachindex(weeks)] # panel tops hs =round.(Int, ppu .* (his .-0.47)) # panel heights, pixels fig =Figure(size = (bp.px +8, sum(hs) +12(length(weeks) -1) +8), figure_padding =4)for (r, t) inenumerate(weeks) ax =beer_axis(fig[r, 1], 0.47, his[r])beer_week!(ax, g, t, d; names = r ==1)rowsize!(fig.layout, r, Fixed(hs[r]))endrowgap!(fig.layout, 12)return figendbeer_weeks(bs, 4:8, dw)
Figure 19: The beer game in play under base stock: the chain of Fig. 18 at the end of each week from week 4 to week 8, the customer demand stepping from 4 to 8 in week 5. The number in each role is its units on hand, with a minus sign when it is a backlog instead, and a value that changed during the week is shown struck through beside its new one. Each blue box is a week of orders on its way up to the supplier, the right-hand one placed this week; each red box is a week of shipments on its way down, the left-hand one shipped this week; at the left are the factory’s 3 weeks of production.
Table 6 is the retailer’s record in the columns of Table 4, over the first 10 weeks of the game Code block 54 plays:
Table 6: The retailer’s record of Table 4 under base stock, the first 10 weeks: the units received, the customers’ order arrived, the units shipped, on hand and backlogged at the end of the week, the week’s cost, and the units ordered.
In week 5 the retailer ships the 8 units its customers order, out of its 12 on hand, and orders 8, which take 2 weeks to reach the wholesaler. Its shipments still come in at the old rate of 4, so its stock falls by 4 a week, to 0 by week 7. In week 7 the wholesaler receives the first order of 8, ships it, and orders 8 in turn: the step has moved one role up the chain in 2 weeks. In week 8 the retailer receives only 4 units against a demand of 8 and backlogs the other 4, its first stockout; the first 8 reaches it in week 9, 4 weeks after the step, 2 for the order to go up and 2 for the shipment to come back. Base stock orders only what is ordered and never raises its position for the higher demand, so the retailer’s backlog grows, to 12 units by week 20.
Fig. 20 draws the orders each role receives and places, the orders given to a role, by the customers or by the role below it, in red and the orders its policy determines in blue:
Show the code that draws this figure
# Code block 57: orders received and placed by each role, base stockfunctionorders_by_role(g) # g, a game Code block 52 returns fig =Figure(size = (600, 460)) wk =1:size(g.Q, 1) # weeksfor i in1:4 ax =Axis(fig[i, 1]; ylabel = roles[i], ylabelsize =15, xticklabelsize =13, yticklabelsize =13, xticks =2:2:20, yticks =0:4:12)stairs!(ax, wk, g.A[:, i]; step =:center, color = givc, linestyle =:dash, linewidth =2, label ="Orders received")stairs!(ax, wk, g.Q[:, i]; step =:center, color = bluec, linewidth =2, label ="Orders placed") vr =round(var(g.A[:, i]), digits =2) vp =round(var(g.Q[:, i]), digits =2)text!(ax, 20.4, 16.5; text ="variance $vr received, $vp placed", align = (:right, :top), fontsize =13)ylims!(ax, -1, 17)if i ==1Legend(fig[0, 1], ax; orientation =:horizontal, labelsize =13, framevisible =false)endif i <4hidexdecorations!(ax; grid =false)else ax.xlabel ="Week" ax.xlabelsize =15endendrowgap!(fig.layout, 6)return figendorders_by_role(bs)
Figure 20: Orders each role receives, given to it by the customers or by the role below, in red, and places, determined by base stock, in blue, week by week, with the variance of each over the 20 weeks. Base stock places exactly what it receives, so the two lines coincide.
Every role orders exactly what was ordered from it, so the step in customer demand moves up the chain unchanged, 2 weeks later at each role. Code block 58 checks that role i’s order in week t is the customer demand of week t - 2(i - 1), an Assumptions check of Lecture 1.2 on base stock passing orders on unchanged:
# Code block 58: base stock passes each order up, 2 weeks a rolelag(i, t) = t >2(i -1) ? dw[t -2(i -1)] :4# 4 before the gameall(bs.Q[t, i] ==lag(i, t) for i in1:4, t in1:20)
true
Under base stock, role i orders the customer demand of 2(i - 1) weeks earlier: true
Example 10(c): Reorder point in simulation
Simulate the 20 weeks with every role following the reorder point, determine the orders each role places, and compare their variance with the variance of the orders it receives.
Code block 59 plays the reorder point and sets the variance of the orders each role receives and places beside base stock’s:
Fig. 21 draws them week by week, the orders given to each role in red and those its policy determines in blue:
Show the code that draws this figure
# Code block 60: orders received and placed by each role, reorder pointorders_by_role(rp)
Figure 21: Orders each role receives, given to it by the customers or by the role below, in red, and places, determined by the reorder point with an order point of 24 and an order quantity of 12, in blue, week by week, with the variance of each over the 20 weeks. Above the retailer, a role places what it receives in every week after week 2, and the blue line covers the red there.
Fig. 22 shows the same weeks of the game under the reorder point:
Show the code that draws this figure
# Code block 61: the chain at the end of each week, reorder pointbeer_weeks(rp, 4:8, dw)
Figure 22: The beer game in play under the reorder point, with an order point of 24 and an order quantity of 12: the chain at the end of each week from week 4 to week 8, read as Fig. 19.
The boxes on the blue arrows of orders now hold 0 or a batch of 12: a role orders only in a week its position falls to 24 or below, so the orders each supplier sees jump between nothing and a batch while the customers order a steady 4, then 8 a week. That is the batching Sec. 4 found to be the main cause of the bullwhip effect.
Every unit the factory requests enters the chain and every unit the retailer ships to a customer leaves it, so the units on hand, in transit and in production at the end are the units at the start plus the requests less the shipments, a Balance check of Lecture 1.2:
# Code block 62: units in the chain at the end, a Balance checkwk =length(dw) # the last weektransit =sum(rp.X[wk-1:wk, 2:4]) # shipped in the last 2 weeksmaking =sum(rp.Q[wk-2:wk, 4]) # requested in the last 3 weeksstart =4*12+3*2*4+3*4# on hand, in transit, in productionsum(rp.I[wk, :]) + transit + making == start +sum(rp.Q[:, 4]) -sum(rp.X[:, 1])
true
Under base stock the variances differ from role to role only because the step reaches each role 2 weeks later within the same 20 weeks. Under the reorder point the retailer’s orders have a variance of 36.38, 13.5 times the customer demand’s 2.69, and each role above, ordering in the same batches, passes that on almost unchanged, to 37.52 at the factory.
Variance of the orders placed, retailer to factory: base stock 2.69, 3.54, 4.04, 4.21, each the variance of the orders received; reorder point 36.38, 36.38, 36.38, 37.52, against the customer demand’s 2.69
The delay discount is a form of the backorder cost of the base stock model in the literature, which charges a backorder for the time it waits, the cost to carry one unit of backorder for a year, beside the cost to carry one unit of inventory for a year. W. J. Hopp and M. L. Spearman, Factory Physics, 3rd ed. (Long Grove, IL: Waveland Press, 2011), sec. 2.4.2, 71–78; P. H. Zipkin, Foundations of Inventory Management (New York: McGraw-Hill, 2000), chap. 6; “Base stock model,” Wikipedia, accessed November 13, 2026, https://en.wikipedia.org/wiki/Base_stock_model.↩︎
Ladislaus von Bortkiewicz, Das Gesetz der kleinen Zahlen [The law of small numbers] (Leipzig: B. G. Teubner, 1898), 23–25; “Ladislaus Bortkiewicz,” Wikipedia, accessed November 11, 2026, https://en.wikipedia.org/wiki/Ladislaus_Bortkiewicz.↩︎
Janice H. Hammond, “The Beer Game: Description of Exercise,” Harvard Business School note 9-694-104 (rev. February 24, 1997), 1, based on the work of the Systems Dynamics Group, Sloan School of Management, Massachusetts Institute of Technology; see also John D. Sterman, “Modeling Managerial Behavior: Misperceptions of Feedback in a Dynamic Decision Making Experiment,” Management Science 35, no. 3 (March 1989).↩︎