theme = Generators.observe(notify => {const read = () => {const css =getComputedStyle(document.body);const v = (name, fallback) => (css.getPropertyValue(name).trim() || fallback);return {dark:document.body.classList.contains("quarto-dark"),fg:v("--bs-body-color","#212529"),bg:v("--bs-body-bg","#ffffff"),muted:v("--bs-secondary-color","#6c757d"),grid:v("--bs-border-color","#dee2e6"),primary:v("--bs-link-color","#0d6efd"),accent:v("--bs-danger","#dc3545"),good:v("--bs-success","#198754") }; };// Quarto swaps stylesheets when the theme changes, and the new variables apply only once// the stylesheet has loaded; read them again shortly after, and keep the last reading.let last ="";const emit = () => {const t =read();const key =JSON.stringify(t);if (key !== last) { last = key;notify(t); } };const update = () => { emit();setTimeout(emit,100);setTimeout(emit,400); };update();const observer =newMutationObserver(update); observer.observe(document.body, {attributes:true,attributeFilter: ["class"]});return () => observer.disconnect();})
plotStyle = ({// "inherit" takes the page's text color directly, so axes and labels follow a theme// switch even before the plot redraws.color:"inherit",background:"transparent",fontSize:"13px",overflow:"visible"})
themedButton = (label, counterLabel =null) => {const button =html`<button type="button" class="btn btn-sm btn-outline-primary bisc-explorer-button">${label}</button>`;// The counter shows which run is on screen, so every press visibly does something and a// reader can tell runs apart. It reads 1 at page load and after Reset.const counter = counterLabel?html`<span class="bisc-run-counter" aria-live="polite"></span>`:null;const form =html`<form class="bisc-explorer-control">${button}${counter ||""}</form>`;const show = () => { if (counter) counter.textContent=`${counterLabel}${form.value+1}`; }; form.value=0;show(); button.onclick= () => { form.value+=1; form.dispatchEvent(newEvent("input", {bubbles:true})); };// Reset sets the value back to 0 and dispatches input; refresh the counter either way. form.addEventListener("input", show);return form;}
resetButton = (controls, label ="Reset to the starting values") => {// This runs once per page, because the cell that calls it depends on the controls// themselves (viewof), not on their values; so these are the values at page load.const start = controls.map(c => c.value);const button =html`<button type="button" class="btn btn-sm btn-outline-primary bisc-explorer-button">${label}</button>`; button.onclick= () => { controls.forEach((c, k) => { c.value= start[k]; c.dispatchEvent(newEvent("input", {bubbles:true})); }); };returnhtml`<div style="margin: 0.5rem 0">${button}</div>`;}
// A small seeded generator (mulberry32), so a run can be repeated.makeRandom = (seed) => {let a = seed >>>0;return () => { a = (a +0x6D2B79F5) >>>0;let t = a; t =Math.imul(t ^ (t >>>15), t |1); t ^= t +Math.imul(t ^ (t >>>7), t |61);return ((t ^ (t >>>14)) >>>0) /4294967296; };}
This page evaluates and optimizes an \((r, Q)\) policy for an item you describe, with the exact methods of Chapter 8. It is the general form of the transformer’s explorer, and it starts from the transformer’s values; Reset returns to them. Enter your item’s costs and its lead time demand, and the page finds the optimal policy by Algorithm Optimize_rq, checks it against the bounds that are known before solving, and evaluates any policy you choose beside it.
The page runs in your browser and records nothing. Its formulas are a restatement in JavaScript of the book’s code, and they are tested against that code on a range of items, from a slow mover with a lead time demand of a few units to a fast mover with a thousand.
What This Page Assumes
The page computes exactly, and it can do so only for the model below. Read these before you rely on a number from it.
The system. Continuous review, an \((r, Q)\) policy, demand that arrives one unit at a time, and unmet demand backordered. Orders are received in the sequence they were placed.
The costs. A fixed cost \(k\) per order, a holding cost \(h\) per unit per year, and a backorder cost \(b\) per unit per year owed. A cost \(\pi\) per unit short is a different model, and this page does not offer it.
Lead time demand. It is a discrete count, Poisson or negative binomial. The family follows the chapter’s rule on the variance to mean ratio. A ratio within 0.05 of one is Poisson at the mean, and the variance you entered is replaced by the mean. A larger ratio is negative binomial, matched to both moments. A ratio below one is refused, since neither family fits it.
The bounds. The mean lead time demand must lie between 0.1 and 5,000 units, and the variance to mean ratio must be at most 50. Outside them the tables the page builds become too long for a browser.
The service measure. The page reports the ready rate, not the fill rate. The two are equal when demand arrives one unit at a time in a Poisson process, as it does when you build the lead time demand from a demand rate and a lead time below. If you enter a variance from data whose demand arrives in bursts, the fill rate can be lower than the ready rate.
NoteFor anything else, use the software
Demand in lots, a gamma or another family, a service target, the classical approximation, or a cost per unit short are all in the code the chapter teaches, in Using the Software, and the chapter’s workbook covers the approximation and the service targets.
Your Item
viewof lambda = Inputs.number({value:45,label:"Demand rate, λ (units a year)"})viewof k = Inputs.number({value:220,label:"Ordering cost, k ($ an order)"})viewof h = Inputs.number({value:950,label:"Holding cost, h ($ a unit a year)"})viewof b = Inputs.number({value:8550,label:"Backorder cost, b ($ a unit a year)"})viewof how = Inputs.select(newMap([ ["From λ and the lead time","build"], ["Its mean and variance","direct"]]), {value:"build",label:"Lead time demand"})viewof unit = Inputs.select(newMap([["days",365], ["weeks",52], ["months",12], ["years",1]]), {value:12,label:"Lead time unit"})viewof meanL = Inputs.number({value:2,label:"Mean lead time"})viewof sdL = Inputs.number({value:0,label:"Standard deviation of the lead time"})viewof meanDL = Inputs.number({value:7.5,label:"Mean lead time demand, θ (units)"})viewof varDL = Inputs.number({value:7.5,label:"Variance of lead time demand"})viewof r = Inputs.number({value:9,step:1,label:"Reorder point, r"})viewof Q = Inputs.number([1,Infinity], {value:5,step:1,label:"Order quantity, Q"})useOptimum = {const button =html`<button type="button" class="btn btn-sm btn-outline-primary bisc-explorer-button">Use the optimal policy</button>`; button.onclick= () => {if (!result.ok) return;for (const [view, v] of [[viewof r, result.opt.r], [viewof Q, result.opt.Q]]) { view.value= v; view.dispatchEvent(newEvent("input", {bubbles:true})); } };returnhtml`<div style="margin: 0.5rem 0">${button}</div>`;}resetButton([viewof lambda, viewof k, viewof h, viewof b, viewof how, viewof unit, viewof meanL, viewof sdL, viewof meanDL, viewof varDL, viewof r, viewof Q])
import {matched} from"./explorers/lib/loss.js"import {cost, optimize, bounds} from"./explorers/lib/rq.js"costs = ({lambda, k, h, b})fmt = x =>String(Number(x.toPrecision(6)))moments = {if (how ==="direct") return {mean: meanDL,variance: varDL,note:""};// Case 3 of the chapter with Poisson demand: E[D] = Var[D] = lambda per year.const EL = meanL / unit, VL = (sdL / unit) **2;const mean = lambda * EL, variance = lambda * EL + lambda * lambda * VL;return {mean, variance,note:`With the lead time in years, E[L] = ${meanL}/${unit} = ${fmt(EL)} and Var[L] = (${sdL}/${unit})² = ${fmt(VL)}, so θ = λE[L] = ${fmt(mean)} units and Var[D(L)] = λE[L] + λ²Var[L] = ${fmt(variance)} units squared.`};}result = {const problems = [];if (!(lambda >0)) problems.push("The demand rate must be positive.");if (!(k >=0)) problems.push("The ordering cost cannot be negative.");if (!(h >0)) problems.push("The holding cost must be positive.");if (!(b >0)) problems.push("The backorder cost must be positive.");if (!Number.isInteger(r)) problems.push("The reorder point must be a whole number.");if (!(Number.isInteger(Q) && Q >=1)) problems.push("The order quantity must be a whole number, 1 or more.");const {mean, variance} = moments;if (!(mean >=0.1&& mean <=5000)) problems.push(`The mean lead time demand is ${mean.toPrecision(4)} units; this page needs it between 0.1 and 5,000.`);if (variance / mean >50) problems.push(`The variance to mean ratio is ${(variance / mean).toFixed(2)}; this page needs it at most 50.`);if (problems.length) return {ok:false, problems};try {const ltd =matched(mean, variance);const opt =optimize(ltd, costs);return {ok:true, ltd, opt,bd:bounds(ltd, costs),here:cost(ltd, r, Q, costs),best:cost(ltd, opt.r, opt.Q, costs)}; } catch (e) {return {ok:false,problems: [e.message.charAt(0).toUpperCase() + e.message.slice(1) +"."]}; }}
{if (!result.ok) {returnhtml`<div class="callout callout-style-simple callout-warning"><div class="callout-body"> <p><strong>The page cannot evaluate this item.</strong></p> <ul>${result.problems.map(p =>html`<li>${p}</li>`)}</ul> <p>For an item outside these limits, use the software of the chapter's Using the Software section.</p> </div></div>`; }const {ltd} = result;const fam = ltd.family==="Poisson"?`Poisson with mean ${fmt(ltd.mean)}`:`negative binomial with mean ${fmt(ltd.mean)} and variance ${fmt(ltd.variance)} (p = ${ltd.p.toFixed(4)}, size ${fmt(ltd.size)})`;const replaced = ltd.family==="Poisson"&&Math.abs(moments.variance- moments.mean) >1e-9* moments.mean?` The variance to mean ratio, ${(moments.variance/ moments.mean).toFixed(3)}, is within 0.05 of one, so the variance is taken equal to the mean.`:"";returnhtml`<p>${moments.note} The lead time demand is ${fam}.${replaced}</p>`;}
{if (!result.ok) returnhtml``;const {here, best, opt, bd} = result;const n = (x, d =4) => x.toFixed(d);const dollars = x =>"$"+ x.toLocaleString("en-US", {minimumFractionDigits:2,maximumFractionDigits:2});const rows = [ ["Expected backorders, B̄ (units)",n(here.B),n(best.B)], ["Ready rate",n(here.RR),n(best.RR)], ["Expected on hand, Ī (units)",n(here.I),n(best.I)], ["Orders a year, λ/Q",n(here.OF,2),n(best.OF,2)], ["Ordering, kλ/Q",dollars(here.ordering),dollars(best.ordering)], ["Holding, hĪ",dollars(here.holding),dollars(best.holding)], ["Backorders, bB̄",dollars(here.backorder),dollars(best.backorder)], ["Total cost a year",dollars(here.total),dollars(best.total)] ];const lo = r +1, hi = r + Q;const inBand = opt.r< opt.S&& opt.S<= opt.r+ opt.Q;const inBounds = bd.lower<= opt.cost+1e-6&& opt.cost<= bd.upper+1e-6;const extra =100* (here.total/ best.total-1);returnhtml` <table class="table table-sm" style="max-width: 42rem"> <thead><tr><th>Measure</th><th>Your policy (${r}, ${Q})</th><th>The optimum (${opt.r}, ${opt.Q})</th></tr></thead> <tbody>${rows.map(row =>html`<tr><td>${row[0]}</td><td>${row[1]}</td><td>${row[2]}</td></tr>`)}</tbody> </table> <p>Your policy costs ${extra <0.005?"the same as the optimum": extra.toFixed(1) +"% more than the optimum"}. Its positions run over ${lo} through ${hi}.</p> <p><strong>The checks.</strong> The optimal base-stock level is S* = ${opt.S}, and the optimal band,${opt.r+1} through ${opt.r+ opt.Q}, ${inBand ?"contains it, as it must":"does not contain it, which signals an error"}. The bounds known before solving are ${dollars(bd.lower)} ≤ C* ≤ ${dollars(bd.upper)}, and C* = ${dollars(opt.cost)}${inBounds ?"lies between them":"does not lie between them, which signals an error"}. The deterministic reference quantity is Q<sub>k</sub> = ${bd.Qk.toFixed(2)} units, against Q* = ${opt.Q}.</p>`;}
The first plot is the cost against the reorder point, with the order quantity held at your \(Q\). The red dot is your policy.
byR = {if (!result.ok) return [];const sd =Math.sqrt(result.ltd.variance);const span =Math.max(8,Math.ceil(3* sd));constfrom=Math.min(r, result.opt.r) - span, to =Math.max(r, result.opt.r) + span;const step =Math.max(1,Math.ceil((to -from) /400));const xs = d3.range(from, to +1, step);if (!xs.includes(r)) xs.push(r);return xs.sort((a, c) => a - c).map(x => ({r: x,...cost(result.ltd, x, Q, costs)}));}result.ok? Plot.plot({style: plotStyle,height:260,marginLeft:80,marginBottom:45,x: {label:"Reorder point, r",labelAnchor:"center",labelOffset:38,grid:true},y: {label:"Cost a year ($)",grid:true,domain: [0,2* d3.min(byR, d => d.total)]},marks: [ Plot.line(byR, {x:"r",y:"total",stroke: theme.primary,strokeWidth:1.5,clip:true}), Plot.dot([{r,total: result.here.total}], {x:"r",y:"total",r:6,fill: theme.accent,clip:true}) ],ariaLabel:"Cost a year against the reorder point at the chosen order quantity",ariaDescription:`At Q = ${Q} the least cost on the plotted range is $${d3.min(byR, d => d.total).toFixed(2)}. Your policy at r = ${r} costs $${result.here.total.toFixed(2)}.`}) :html``
The second plot is the ready rate against the reorder point at the same \(Q\), with your policy as the red dot.
result.ok? Plot.plot({style: plotStyle,height:240,marginLeft:80,marginBottom:45,x: {label:"Reorder point, r",labelAnchor:"center",labelOffset:38,grid:true},y: {label:"Ready rate",grid:true,domain: [0,1]},marks: [ Plot.line(byR, {x:"r",y:"RR",stroke: theme.primary,strokeWidth:1.5}), Plot.dot([{r,RR: result.here.RR}], {x:"r",y:"RR",r:6,fill: theme.accent}) ],ariaLabel:"Ready rate against the reorder point at the chosen order quantity",ariaDescription:`Your policy's ready rate is ${result.here.RR.toFixed(4)}.`}) :html``
The third plot is the least cost at each order quantity, from the steps of Algorithm Optimize_rq continued past the optimum. Each point is the best reorder point for that \(Q\). The red dot is your \(Q\).
byQ = {if (!result.ok) return [];const through =Math.max(2* result.opt.Q, Q +5,10);const path =optimize(result.ltd, costs, {through}).path;const step =Math.max(1,Math.ceil(path.length/400));return path.filter((p, i) => i % step ===0|| p.Q=== Q || p.Q=== result.opt.Q);}result.ok? Plot.plot({style: plotStyle,height:240,marginLeft:80,marginBottom:45,x: {label:"Order quantity, Q",labelAnchor:"center",labelOffset:38,grid:true},y: {label:"Least cost over r ($)",grid:true,domain: [0,2* result.opt.cost]},marks: [ Plot.line(byQ, {x:"Q",y:"cost",stroke: theme.muted,strokeWidth:1.5,clip:true}), Plot.dot(byQ.filter(p => p.Q=== Q), {x:"Q",y:"cost",r:6,fill: theme.accent,clip:true}) ],ariaLabel:"Least cost over the reorder point at each order quantity",ariaDescription:`The least cost is $${result.opt.cost.toFixed(2)} at Q = ${result.opt.Q}.`}) :html``
Things to Try
Leave the transformer’s values and press Use the optimal policy. The page finds \(r = 8\) and \(Q = 7\) at $7,225.15 a year, the answer of the chapter’s trace of Algorithm Optimize_rq, and the checks pass.
Set the standard deviation of the lead time to 1 month. The lead time demand becomes negative binomial with variance 21.5625, and the optimum moves to \(r = 10\) and \(Q = 8\) at $11,079.73.
Set the ordering cost to 0. The optimum is one for one, \(Q = 1\) with \(r = 10\), which is the base-stock level \(S^{*} = 11\).
Try a fast mover: \(\lambda = 6{,}000\) a year, \(k = \$27.50\), \(h = \$0.85\), \(b = \$8.50\), and a lead time of 2 weeks. The optimum orders 655 at a time, and the cost lies just inside its upper bound.
Enter a lead time demand directly with a variance below its mean. The page refuses it and says why.