Appendix G — Designing the Course Software
After reading this appendix you should be able to:
- explain why each class in the companion code exists and what it is responsible for
- carry a model from its requirements to its classes: the nouns of the domain, what each thing knows and does, and how the things collaborate
- check a design against the mathematics it implements
- extend a package without breaking the agreements its tests pin
Each chapter from Chapter 3 onward ends its main development with a section called Using the Software. That section shows what to type to reproduce the chapter’s examples, and it is all you need to run the code. This appendix holds the other half: why the code is shaped as it is.
The two halves are separated because they are read at different times. You use the software while you are learning a model, and the usage sections are written for that moment. You read a design when you want to change the code, extend it to a model the book does not cover, or judge whether a program of your own is organized well. That is a different question, and it is better asked once the model is familiar.
G.1 How to Read This Appendix
The appendix has one section per chapter, in the order of the chapters, and each section assumes the chapter it accompanies. Where a section says the chapter, it means that chapter, and the section’s opening line names it. Read a section after its chapter, not before.
Every section follows the same order, because the analysis always proceeds in that order:
- Requirements. What the software must do, each requirement traced to the place in the chapter that works it out.
- Nouns. The vocabulary of the domain, with the candidates that were rejected and why.
- Responsibilities. What each thing knows and what it does.
- Classes. How the things are related, drawn as a class diagram.
- Collaboration and checks. How the objects produce an answer, and how the answer is checked against the mathematics.
Section G.3 works through every step in full, and it is the place to start if you read only one section. The other sections take the steps in brief and spend their length on the decision that the chapter makes hard. That is, Section G.2 is about what may change and what must not, Section G.4 about three rules that are one rule, and Section G.7 about where a convention lives. The class diagrams use the notation of the Unified Modeling Language, and each one is walked through in the prose around it.
The code itself is in code/, the Gradle project described in Appendix F. Each package carries tests that pin the numbers the chapters print. Thus the tests, and not a reader, are the first check that a change has left the chapters’ examples intact.
G.2 Deterministic Lot Sizing
This section designs the software of Chapter 3. Where it says the chapter, it means Chapter 3. The code is in the package inventory.lotsizing, and Section 3.12 shows it in use.
Recall that Section 3.11.5 ended with three things a worksheet does not do. It evaluates and does not choose, it does not know its own assumptions, and it rounds after the fact. Those are reasons to write a program. They are not a design.
A worksheet argues for itself. The blocks sit in an order you can see, and a formula is a cell you can click on. A program’s structure is a set of decisions about which classes exist and what each class is responsible for, and a reader handed the finished code sees only the result. The decisions for the six models of the chapter come first, and Section 3.12 then shows what to type.
Four decisions carry most of the design, and each one is a question that returns in any model you write. We take them in turn.
G.2.1 What Changes, and What Must Not
A worksheet is a thing you edit. You change the ordering cost, the sheet recalculates, and you compare what you now see against the numbers from a minute ago. Both halves of that matter. The inputs have to be editable, and the answer you already took down has to stay where it was.
Those two requirements pull in opposite directions. We meet them with three types.
Figure G.1 illustrates the three answers to one question. CostParameters is the sheet. Every property can be assigned, and every property validates on assignment with the same predicate the constructor applies, so no invalid parameter set ever exists. ParameterSnapshot is the printout, unchangeable once taken. CostParametersIfc is the read-only view, and it is what every model, every cycle and every cost calculation depends on.
The read-only view is the decision doing the work. A model receives the interface, so a model cannot change the parameters it was given. Thus, the mutability is confined to the one place a reader utilizes it, and nothing below the input layer has to be written defensively.
The snapshot makes the arrangement safe.
val analysis = EconomicOrderQuantity.optimize(sheet) // sheet.orderCost is 20.0
sheet.orderCost = 40.0
analysis.parameters.orderCost // still 20.0Every result carries the values that produced it. Notice that the sweep in Section 3.12 assigns sheet.leadTime = lead inside a loop and keeps every analysis. That sweep is sound because each analysis froze its own inputs before the next assignment. Notice also that ParameterSnapshot is itself a CostParametersIfc, so a result can be re-analyzed from its own record.
You should take the general rule from this. When something must be editable and something must be stable, do not compromise between them on one type. Separate what can change from what has been recorded, and make the dependency run from the second to the first.
G.2.2 One Pipeline, Six Models
Section 3.4 derives one model and Section 3.5 obtains five more by imposing assumptions on it. The six therefore agree about almost everything. They agree about the geometry of Section 3.1, the cost assembly of Section 3.3, the reorder point of Section 3.6, and the service measures of Section 3.9. They disagree about one thing, the policy.
evaluate and optimize are final, and each model supplies a single method that chooses a policy. Notice that no arrow joins the six to one another, which is the point of the next paragraph.
Figure G.2 illustrates the arrangement. We write the shared part once and leave the varying part open.
abstract class AbstractLotSizingModel(override val name: String) : LotSizingModel {
/** The policy this model chooses for these parameters, and how it chose it. */
protected abstract fun choosePolicy(parameters: CostParametersIfc): ChosenPolicy
final override fun optimize(
parameters: CostParametersIfc,
rounding: QuantityRounding,
): InventoryPolicyAnalysisIfc {optimize and evaluate are final. That is, a model may decide what to order, and it may not decide what a cycle is, what it costs, or when to reorder. Those belong to the chapter and not to any one model, so a model that overrode them would contradict Section 3.1 instead of specializing it.
Table 3.1 obtains the classical economic order quantity from the general model as the replenishment rate and the backorder cost both grow without bound. The obvious move is to make EconomicOrderQuantity a subclass of GeneralBackorderModel. The code does not do so.
A subtype must be usable wherever its parent is, and the classical model is not. It has no backorder cost to be given, and handing it one is the case Section 3.5.2 warns about. What is true is a statement about numbers, that one model’s answer approaches another’s in a limit, and a statement about numbers belongs where numbers can be checked. Take the limit, watch the quantities converge, and the claim is settled. Thus, the relation between the six models is real, it is checkable, and it is not inheritance.
You should carry that distinction past the chapter. Before making B a subclass of A, ask whether every context that accepts an A would accept a B. In the mathematics, “B is a special case of A” is a different claim.
G.2.3 Sealed Types for Closed Sets
Four of the inputs are not numbers. Replenishment is instantaneous or at a rate. Shortages are forbidden or backordered. Holding cost is a charge on value or a rate. A schedule is flat, all-units or incremental. Each one is a small closed set of alternatives, and we write each as a sealed hierarchy.
Figure G.3 illustrates the four. Sealing buys one thing. The compiler knows the whole list, so it can check a decision over the kinds for completeness. That pays when something dispatches on the kind, and here something does. Table 3.1 says which model matches which assumptions, and the code is that table.
fun forParameters(parameters: CostParametersIfc): LotSizingModel {
val schedule = parameters.schedule
if (schedule is AllUnits) return AllUnitsDiscountModel
if (schedule is Incremental) return IncrementalDiscountModel
return when (parameters.replenishment) {
is Replenishment.Instantaneous -> when (parameters.shortages) {
is ShortagePolicy.NotPermitted -> EconomicOrderQuantity
is ShortagePolicy.Backordered -> PlannedBackorderModel
}
is Replenishment.AtRate -> when (parameters.shortages) {
is ShortagePolicy.NotPermitted -> EconomicProductionQuantity
is ShortagePolicy.Backordered -> GeneralBackorderModel
}
}
}There is no else, and the code will not compile if one is needed. For example, adding a third kind of replenishment stops the build at this function, the one place in the program that has to be revisited. The compiler enforces Table 3.1, and no comment asks anybody to remember it.
ShortagePolicy shows a second benefit. Recall from Section 3.5.2 that forbidding shortages is not the same as charging nothing for them, since a backorder cost of zero makes shortages free and sends the order quantity to infinity. A design with one nullable backorder cost would have to catch that at run time. Here NotPermitted and Backordered(b) are different things, and the constructor of the second requires a positive b. Thus, the mistake the callout warns about cannot be written down at all.
We apply one criterion, the closed set and not the tidiness. Section G.3.5 faces the same choice for the aggregate measures of Chapter 4 and answers it the other way, because nothing there dispatches on which measure it is holding and an organization may always find a fifth thing to run short of. You should seal when the mathematics closes the list and something must visit every case, and leave the hierarchy open otherwise.
G.2.4 An Answer That Carries Its Reasoning
We come to the last decision. It concerns what comes back, and an order quantity is a number that cannot be questioned. Three types let the caller question it.
A model asked to work outside its assumptions has three replies and not two.
sealed interface Applicability {
data object Applicable : Applicability
data class NotApplicable(val reason: String) : Applicability
data class Approximating(val ignored: List<String>) : Applicability
}The third reply is the interesting one. Notice that applying the order quantity to an item with a finite production rate is a deliberate approximation, which Exercise 3.4 asks you to make, so the model allows it and the discarded assumption rides on the result. Asking the planned backorder model for a policy when shortages are forbidden is refused outright, since nothing is left for it to compute. A boolean would treat those two alike.
Each model declares its assumptions once, and the verdict is derived from that declaration in the one place all six share. Stating an assumption in a declaration and then testing for it again by hand would write the same rule twice, in two forms free to disagree.
QuantityChoice records how the quantity was reached, and the routes differ. A closed form produced an interior optimum; or the stationary point lay outside the feasible region, so the answer sits on a boundary and carries a reason; or a candidate list was ranked and retained; or an unrounded optimum was rounded and both neighbors evaluated. Section 3.8 is where the record pays, since a discount answer that does not show its candidates cannot be checked against the worksheet that produced the same number.
Section 3.1.2 says the four durations account for the whole cycle, and advises checking it because the check catches most algebra errors immediately. We write the advice into the constructor.
checkClose(segments.total, length, "the segments sum to the cycle length")
checkClose(maxOnHand + maxBackorder, policy.orderQuantity * survivingFraction,
"the peaks account for the surviving part of the order")Those checks run whenever a cycle is built, so an identity the chapter states cannot quietly fail to hold in the program. The averages computed from the triangle areas are checked against the closed forms beside them.
The same discipline applies to arguments. Every constructor validates, and so does every function that could divide by a quantity somebody passed as zero. The failure a guard prevents is usually not a crash. A rounding rule asked for an interval of two to the seventieth base periods computes two to the sixth, because the shift that raises two to a power keeps only the low six bits of the exponent. It returns a plausible small number. A guard at the point of construction refuses the exponent.
We can now say what a seventh model would cost. It is one object with one choosePolicy, one assumptions declaration, and one branch that the compiler demands in forParameters. Nothing else in the package changes. Apply that test to any design and ask what the next requirement costs.
G.3 Multi-Item and Constrained Systems
This section designs the software of Chapter 4. Where it says the chapter, it means Chapter 4. The code is in the package inventory.multiitem, and Section 4.8 shows it in use.
In Section 4.7 we built each model as a worksheet. The layout of a worksheet is visible. A formula is a cell you can click on, a summary is a range you can highlight, and putting the multiplier in a single cell says that it belongs to the problem and not to any item.
A program shows none of that. Its structure is a set of decisions about which classes exist and what each class is responsible for, and those decisions leave no trace in the finished code. We therefore write them down first.
The analysis proceeds in the order such an analysis always does: what the software must do, what the domain calls things, what each thing knows and does, how the things are related, and how they collaborate to produce an answer. Code appears at the end of each step, by which point little is left to decide.
The effort pays off because the five models share more than they appear to. A programmer who writes the constrained problem, then the exchange curve, then joint replenishment, without pausing between them, will write Equation 4.5 three times. Thus, when the third one is wrong there are three places to correct.
G.3.1 What the Software Must Do
We begin with a list of requirements. Each entry names something a user would ask the software for, together with the section of the chapter that supplies the answer.
| # | The software must | Established in |
|---|---|---|
| R1 | compute each SKU’s order quantity ignoring any coupling | Chapter 3 |
| R2 | report an aggregate measure of a set of decisions | Section 4.1 |
| R3 | decide whether a stated limit on a measure binds | Section 4.2.1 |
| R4 | find the cheapest decisions meeting a limit, and report its shadow price | Section 4.2.2 |
| R5 | price a limit against having none | Section 4.3 |
| R6 | trace the frontier of achievable aggregate positions | Section 4.4 |
| R7 | schedule SKUs sharing one setup, under a stated ordering practice | Section 4.5 |
| R8 | restrict intervals to what an operation can run, and price the restriction | Section 4.5.3 |
| R9 | account for holding cost across locations without double counting | Section 4.6.1 |
| R10 | find reorder intervals across a chain or a distribution network | Section 4.6.2 |
Two features of Table G.1 matter more than the list itself.
Notice that R3, R4 and R5 do not mention a budget. They name a limit on a measure. Recall from Section 4.1 that an organization runs short of four different things, and that Section 4.2 then solved for one of them. A design that treats the budget as the problem, and the other three as variations on it, carries that assumption into every signature it writes.
A requirement is also not a class. R7 says to schedule SKUs sharing one setup. That sentence names two candidate things, a group of SKUs and a schedule, and it does not say whether either one is an object. For example, turning requirements straight into classes is how software acquires a ScheduleManager.
A requirement says what the software does. A scenario says who asks, and in what order.
| # | Scenario | The question behind it |
|---|---|---|
| S1 | solve under a limit | “Management will fund $10,000 of stock. What do I order?” |
| S2 | price the limit | “What is that ceiling costing me?” |
| S3 | trace the frontier | “If I want fewer orders, how much more stock is that?” |
| S4 | coordinate a supplier’s line | “These four come on one truck. How often do I order each?” |
| S5 | plan a network | “The depot feeds six branches. What interval does each run?” |
S1 and S3 of Table G.2 repay attention. “What do I order under a ten thousand dollar limit” and “if I want fewer orders, how much more stock is that” sound like two programs. Section 4.4 showed that they are one piece of mathematics asked from two ends. If the analysis is sound, the two will use the same objects and nearly the same messages, and we check that in Section G.3.8.
G.3.2 Finding the Nouns
The candidate classes are the nouns of the domain, and the test for keeping one is whether somebody who runs a stockroom would use the word. That test is not a matter of taste. A name taken from the domain survives changes in the mathematics, because the domain is what the mathematics describes. A name invented to suit an implementation has to be renamed every time the implementation moves.
| Term | What it means |
|---|---|
| SKU | a stock keeping unit: one item held at one location, and the thing that gets replenished |
| Portfolio | the SKUs that are decided together |
| Aggregate measure | a number computed over a whole plan: investment, space occupied, replenishment workload, relevant cost |
| Constraint | an aggregate measure together with the ceiling management has put on it |
| Replenishment plan | how much and how often, for every SKU in a portfolio |
| Order family | SKUs sharing a supplier, a truck or a machine setup, so that one order serves several |
| Interval rule | what intervals the operation can actually run |
| Supply network | SKUs that replenish one another, whether in a chain or from a center |
| Echelon holding rate | the value a location adds, as against the value accumulated through it |
Four other nouns suggest themselves. None of them survives the test.
The shadow price is a number that a solution reports. A class for it would know nothing beyond its own value and would do nothing, so it becomes a property of a replenishment plan. Recall from Section 4.3 that the price falls to zero exactly where the limit stops binding. Thus, the mathematics has no missing case and the property need not be nullable.
Echelon stock is defined in Section 4.6.1, and what it defines is a measure of a network. It belongs with investment and space, not with SKUs and plans.
Item and stage are one noun. A SKU already is an item at a location. Section 4.2 holds many SKUs at one location and Section 4.6 holds one item across many locations. That is, one entity under two topologies. Two classes would duplicate every field and force a conversion between the sections.
Shared resource is the instructive rejection, because Section 4.1 uses the phrase. A budget, a floor and a receiving dock are all things that several SKUs compete for. As a class name it fails the test. Nobody in a warehouse has a shared resource. They have a working capital account, a building with pallet positions, and a purchasing department that processes so many orders a week. The word that does pass is measure, since each of those is a number we can compute about a plan and put a ceiling on.
Figure G.4 illustrates the concepts and how they relate. Read it as sentences. A portfolio is one or more SKUs. A constraint limits a portfolio, an order family coordinates one, and a supply network sequences one. The dashed arrows say that all three produce a replenishment plan, and an aggregate measure measures that plan.
Figure G.4 carries no operations, no types and no direction of dependency. It is a conceptual model and not yet a design. Every argument in the rest of this section asks whether the code still says what this picture says.
G.3.3 What Each Thing Knows and Does
We describe each candidate class before drawing it. The traditional form is a class-responsibility-collaborator card, one index card per candidate, with three questions on it. What does it know? Who does it know? What does it do?
The size of the card does the work. A responsibility that will not fit on one card is usually two responsibilities, and a card with no collaborators is either a value or a mistake.
| Class | Knows | Knows about | Does |
|---|---|---|---|
SKU |
label, demand rate, unit value, order cost, holding rate | nobody | its economic order quantity; its cost at a quantity; the interval it would prefer |
Portfolio |
its SKUs, in a fixed order | SKU |
hands out its SKUs; builds a plan from one quantity each |
AggregateMeasure |
its name and unit | ReplenishmentPlan |
measure a plan |
ConstrainableMeasure |
whatever its kind knows | SKU |
its marginal at a SKU; the quantity a SKU takes at a price |
Constraint |
a measure, a ceiling | AggregateMeasure |
whether a plan meets it; the slack |
ReplenishmentPlan |
a quantity per SKU, and the price that produced it | SKU, AggregateMeasure |
report any measure of itself; compare itself with another plan |
ConstrainedLotSizing |
a portfolio, a constraint, a method | all three | the cheapest plan meeting the limit; whether it binds |
LotSizingMethod |
whatever its kind needs | Portfolio, Constraint |
produce that plan |
ExchangeCurve |
a portfolio | Portfolio, AggregateMeasure |
the plan at a price; the curve over prices; the variety index |
OrderFamily |
a portfolio, the major setup | Portfolio, IntervalRule |
a plan under a rule; what independent ordering would cost |
IntervalRule |
its base period | nobody | turn a preferred interval into one that can be run |
SupplyNetwork |
its SKUs, and who supplies whom | SKU, IntervalRule |
the echelon rate of a location; the plan |
Three rows of Table G.4 repay a second look.
SKU knows nobody. A SKU holding a reference to its portfolio could not be evaluated inside a sweep without the portfolio coming with it, and the exchange curve of Section 4.4 evaluates the same SKUs at a thousand prices. Notice also what a SKU does not know: its volume per unit. A SKU carrying a volume because a space limit exists would have to carry a weight when a weight limit arrives, so the class would grow once per constraint anybody writes.
IntervalRule knows nobody either. Given the interval a location would prefer, it returns one the operation can run, and it never asks which location. Thus, the same rule applies per SKU in an order family, per block in a serial chain, and per location in a distribution network.
The measure knows the plan and the plan knows the measure. Two rows pointing at each other should make us nervous. That is, they are one message seen from two sides. The measure owns the formula and the plan owns the data, so the measure is the receiver and plan.measuredBy(m) delegates to m.measure(plan). If both carried real implementations we would be starting on double dispatch, where adding a measure means editing every plan.
Reading the cards a second time, and asking who sends each message, finishes the analysis. One answer stands out. marginalAt is called by one kind of object, a lot sizing method, and by nothing that reports or displays. Thus, it belongs to the solving collaboration and not to the measure’s public face. We act on that in Section G.3.5.
G.3.4 The Classes
Figure G.5 illustrates the classes that carry an answer, and we take them in turn.
The SKU holds its own data and computes its own mathematics.
class SKU(
val label: String,
val demandRate: Double,
val orderCost: Double,
val holdingRate: Double,
val unitValue: Double = 0.0,
) {
/** @eq-multiitem-objective, this SKU alone, ignoring anything it shares. */
val economicOrderQuantity: Double
get() {
require(holdingRate > 0.0) {
"$label has no holding cost, so it has no unconstrained order quantity"
}
return sqrt(2.0 * orderCost * demandRate / holdingRate)
}
/** Ordering plus holding, per unit time, at a quantity someone else chose. */
fun costAt(orderQuantity: Double): Double {
require(orderQuantity > 0.0) { "An order quantity must be positive" }
return orderCost * demandRate / orderQuantity + holdingRate * orderQuantity / 2.0
}
/** The derivative of costAt, which is what a stationarity condition needs. */
fun marginalCostAt(orderQuantity: Double): Double =
-orderCost * demandRate / (orderQuantity * orderQuantity) + holdingRate / 2.0
}Notice that costAt takes a quantity instead of computing one. Every model in this chapter evaluates a SKU at a quantity chosen elsewhere, so a class that knew only its own optimum would be useless in four of the five. For example, the exchange curve evaluates every SKU at the quantity a price implies.
marginalCostAt looks like an implementation detail of economicOrderQuantity. It is in fact the piece every constrained model needs, because a stationarity condition is where a derivative is used.
One answer type serves all five models. The constrained problem and the exchange curve solve for quantities, and joint replenishment and both echelon structures solve for intervals. Recall that \(Q_j = \lambda_j T_j\), so an object holding one can report the other.
class ReplenishmentPlan(
val skus: List<SKU>,
private val quantities: List<Double>,
val shadowPrice: Double = 0.0,
) {
fun quantityOf(sku: SKU): Double = quantities[indexOf(sku)]
fun intervalOf(sku: SKU): Double = sku.intervalFor(quantityOf(sku))
/** Delegates to the measure, which owns the formula while this owns the data. */
fun measuredBy(measure: AggregateMeasure): Double = measure.measure(this)
}This is not unification for its own sake. The chapter claims that every model in it answers how much and how often. If that claim is true, then one answer type is the right number, and a sixth model whose answer did not fit here would be evidence against the claim.
A constraint is a measure together with a ceiling. “At most ten thousand dollars of average investment” is one sentence in the domain, so we make it one object. Keeping the measure separate from the ceiling lets the same measure serve the constrained problem, the exchange curve, and a management report that constrains nothing at all.
class Constraint(val measure: ConstrainableMeasure, val limit: Double) {
fun isMetBy(plan: ReplenishmentPlan): Boolean = measure.measure(plan) <= limit
/** Positive when there is room left, negative when the plan overshoots. */
fun slackIn(plan: ReplenishmentPlan): Double = limit - measure.measure(plan)
}Recall that the worksheet of Section 4.7.1 put the bind test in B11 and \(R(\theta)\) in B15. Those two cells are isMetBy and slackIn. Both implementations put them on the constraint, because the comparison needs the measure and the limit together and needs nothing else.
G.3.5 Measuring, and Limiting a Measure
This is where the analysis pays for itself, so we go slowly.
Figure G.6 illustrates two interfaces and four kinds. We take the split first.
Relevant cost is measured constantly and constrained never. Nobody puts a ceiling on the objective, because the objective is what everything else is traded against. Putting marginalAt on one interface with measure would force RelevantCost to implement a method that has no meaning for it, and a method implemented only to satisfy a compiler is a method somebody will eventually call. Thus, AggregateMeasure is what can be measured, and ConstrainableMeasure adds what a limit needs.
The marginal is the primitive and the quantity is derived from it. Recall from Section 4.2.2 that the stationarity condition for one SKU sets the derivative of the Lagrangian to zero.
- Let \(M\) represent any aggregate measure computed over a plan, so that \(\partial M/\partial Q_j\) is how much the measure changes per unit of order quantity at SKU \(j\).
With this notation the condition is
\[-\frac{k_j\lambda_j}{Q_j^{2}} + \frac{h_j}{2} + \theta\,\frac{\partial M}{\partial Q_j} = 0\]
which is Equation 4.5 before the algebra. Notice what the condition needs. It needs the SKU’s own cost derivative, supplied by SKU.marginalCostAt, and the measure’s marginal. Nothing else. Thus, any measure that can report a marginal can be solved numerically, and we write that once as a default implementation.
interface ConstrainableMeasure : AggregateMeasure {
/** How much this measure changes per unit of order quantity at one SKU. */
fun marginalAt(sku: SKU, orderQuantity: Double): Double
fun quantityAt(sku: SKU, shadowPrice: Double): Double {
val f = { q: Double -> sku.marginalCostAt(q) + shadowPrice * marginalAt(sku, q) }
// bisect f to zero, widening the bracket until it changes sign
}
}A measure whose stationarity condition has a closed form overrides quantityAt and skips the search. Both of the measures that the chapter solves by hand do so.
object AverageInvestment : ConstrainableMeasure {
override fun measure(plan: ReplenishmentPlan): Double =
plan.skus.sumOf { it.unitValue * plan.quantityOf(it) / 2.0 }
override fun marginalAt(sku: SKU, orderQuantity: Double): Double = sku.unitValue / 2.0
override fun quantityAt(sku: SKU, shadowPrice: Double): Double =
sqrt(2.0 * sku.orderCost * sku.demandRate / (sku.holdingRate + shadowPrice * sku.unitValue))
}That is Equation 4.5 with \(a_j = c_j/2\), and it is the only place in the program where the formula appears. The worksheet wrote it in column I of one sheet and again in the curve block of another, because a worksheet has no way to say the same thing once.
The third kind is the one that no coefficient can describe. A simpler interface suggests itself. Equation 4.2 writes every limit as \(\sum_j a_jQ_j \le A\), so a measure could report the single coefficient \(a_j\) and leave the rest to the solver. That interface serves a budget, where \(a_j = c_j/2\), and it serves a floor, where \(a_j = v_j\). Recall from Section 4.2.4 that a limit on replenishments is \(\sum_j \lambda_j/Q_j \le A\). Consumption falls as the quantities rise, so the marginal is negative and depends on the quantity, and the multiplier joins the ordering cost.
object ReplenishmentWorkload : ConstrainableMeasure {
override fun measure(plan: ReplenishmentPlan): Double =
plan.skus.sumOf { it.orderFrequencyAt(plan.quantityOf(it)) }
override fun marginalAt(sku: SKU, orderQuantity: Double): Double =
-sku.demandRate / (orderQuantity * orderQuantity)
override fun quantityAt(sku: SKU, shadowPrice: Double): Double =
sqrt(2.0 * (sku.orderCost + shadowPrice) * sku.demandRate / sku.holdingRate)
}No coefficient expresses that. An interface reporting only a coefficient would force every caller to ask which kind of resource it was holding, and that is the thing an interface exists to prevent. Thus, an abstraction drawn from two examples fits the third by luck or not at all, and the mathematics is what tells you which.
Why a hierarchy, and not one class holding two functions? In Kotlin we could write a single AggregateMeasure class with measure and marginalAt as function-valued properties, and the four kinds as four instances. That design would be better if the kinds differed only in a formula. They do not. SpaceOccupied knows a volume per unit, and a weight limit would know a weight per unit, while AverageInvestment reads the SKU’s own value and knows nothing extra. That is, the kinds differ in what they know, and holding state that varies by kind is what a subtype is for.
Notice also that this hierarchy is not sealed, while Section G.2.3 seals four hierarchies in Chapter 3. Sealing buys exhaustive checking, and exhaustive checking pays only when something dispatches on the kind and the mathematics closes the list. Both conditions hold in Chapter 3, where Table 3.1 is a table of four rows. Neither holds here. A solver asks a measure for a number and never asks which measure it is holding, and the list of scarce things in Section 4.1 is open. Thus, a new measure needs two methods and no edit anywhere else.
G.3.6 Alternatives Are Types, Settings Are Values
Figure G.7 illustrates two more hierarchies, and both exist because the domain offers alternatives.
Section 4.2.3 searches the multiplier until the measure meets its ceiling, which Goal Seek does on the worksheet and LagrangianSearch does here. Solver offers a second way, optimizing the quantities directly, which the code shown here does not implement. And Section 4.3 gives a third, a closed form under a budget when every SKU holds at \(h_j = ic_j\). Every quantity then shrinks by the same factor, so we can invert Equation 4.9.
class ProportionalScaling(private val carryingCharge: Double) : LotSizingMethod {
override fun solve(portfolio: Portfolio, constraint: Constraint): ReplenishmentPlan {
val free = AverageInvestment.measure(portfolio.freePlan())
val ratio = free / constraint.limit
val price = carryingCharge * (ratio * ratio - 1.0)
return portfolio.planAt(AverageInvestment, price)
}
}Notice that no search appears in it. It reproduces the multiplier of Section 4.2 to every digit the search finds, and it refuses to run when its preconditions fail. An interface with one implementation is speculation. The second implementation is what justifies this one.
Section 4.5.1 does not present one model with a setting. It presents four practices: order whenever you like, order everything on every cycle, order on whole multiples of a cycle, and order on powers of two. Each one answers the same question. Given the interval a location would prefer, what interval can the operation run?
interface IntervalRule {
val name: String
val basePeriod: Double
/** The runnable interval nearest the one this SKU or block would prefer. */
fun implementable(preferredInterval: Double): Double
fun multiplierFor(preferredInterval: Double): Int =
max(1, Math.round(implementable(preferredInterval) / basePeriod).toInt())
}
class PowerOfTwoMultiple(override val basePeriod: Double) : IntervalRule {
override fun implementable(preferredInterval: Double): Double =
(1L shl exponentFor(preferredInterval)) * basePeriod
}That question subsumes what look like two concepts. Coordinating a family and rounding an interval to a power of two appear to be different jobs, and they are one job with different answers. Thus, the arithmetic of Equation 4.31 is a function inside PowerOfTwoMultiple and not a class of its own, since it holds no state and there is only one way to do it. multiplierFor is written once on the interface, because under every rule the multiplier is the implementable interval divided by the base period.
We state the criterion behind both decisions once, since you will face the same question in every design you write.
Make a class when it holds state that varies independently of its arguments, or when it is one of several interchangeable ways of doing the same thing. A computation with neither property is a function.
Measured against that criterion, LotSizingMethod and IntervalRule are interfaces because they name interchangeable alternatives, SpaceOccupied is a class because it carries a volume map, and the power-of-two exponent is a function because it is neither.
G.3.7 Three Couplings and No Common Base
The temptation here is a Model interface with a solve() on it, so that all three couplings can be held in one list. Recall that Section 4.1 says these are three different kinds of interaction, and the mathematics agrees. One is a Lagrangian relaxation, one is a one-dimensional search over a base period, and one is a combinatorial partition. Figure G.8 shows what they do share, the SKU and the plan. A common supertype would assert a kinship the chapter denies, and every caller would then have to ask what it was really holding.
The two network topologies do share a supertype. They differ in the shape of one map, from a location to the location that supplies it. A chain points each location at the one above it, and a distribution network points every region at the center.
abstract class SupplyNetwork(
val skus: List<SKU>,
private val suppliedBy: Map<SKU, SKU>,
) {
/** @eq-echelon-holding: the value this location adds, not the value accumulated through it. */
fun echelonRate(sku: SKU): Double =
sku.holdingRate - (suppliedBy[sku]?.holdingRate ?: 0.0)
/** The intervals that solve the relaxed problem, before any rounding. */
abstract fun relaxedIntervals(): List<Double>
/** The relaxed intervals made runnable, one rule applied to every location. */
fun plan(rule: IntervalRule): List<Double> = relaxedIntervals().map { rule.implementable(it) }
}One expression serves both structures. It gives \(h_i - h_{i+1}\) down a chain and \(h_i - h_0\) across a distribution network, and it gives a location with no supplier its own rate, which Equation 4.34 states as a separate case. Notice that echelonRate sits on the network and not on the SKU. An echelon rate is a difference between neighbors, and a SKU that knew its neighbor would record the topology twice.
The two subclasses override the one thing that differs, the algorithm. SerialChain implements Algorithm 4.1 and DistributionNetwork implements the scan of Section 4.6.3. Section 4.7 built a worksheet for the second and not for the first, and the reason survives the change of language. The scan has a step count known in advance and the partition does not.
G.3.8 How the Objects Solve It
A class model says what exists. It does not say what happens, so we trace S1 of Table G.2 from the caller to the answer.
The four middle messages of Figure G.9 repeat until the bracket closes.
class LagrangianSearch(
private val precision: Double = 1.0E-12,
private val maximumIterations: Int = 400,
) : LotSizingMethod {
override fun solve(portfolio: Portfolio, constraint: Constraint): ReplenishmentPlan {
val measure = constraint.measure
var lo = 0.0
var hi = 1.0
while (constraint.slackIn(portfolio.planAt(measure, hi)) < 0.0) {
hi *= 2.0
check(hi < 1.0E12) {
"No price high enough to meet the ${measure.name} limit of ${constraint.limit}"
}
}
repeat(maximumIterations) {
val mid = 0.5 * (lo + hi)
if (hi - lo < precision) return@repeat
if (constraint.slackIn(portfolio.planAt(measure, mid)) < 0.0) lo = mid else hi = mid
}
return portfolio.planAt(measure, 0.5 * (lo + hi))
}
}Notice what the search does not know. It never writes Equation 4.5, never names a budget, and never asks what the measure is. It knows that raising the price lowers consumption, which Section 4.2.3 proves, and it relies on nothing else. Thus, one search serves a working capital account, a warehouse floor and a purchasing department, and quantityAt belongs on the measure.
Notice also the first two lines of the loop. The search widens its bracket until the slack changes sign. Section 4.7.1 observed that Goal Seek does not take that step, since it starts from whatever is already in the cell. Neither tool is safe on its own, and both rest on the same proof. They differ in how much of the search they arrange for you.
Section G.3.1 said that solving under a limit and tracing the frontier would turn out to be one thing. Compare the two.
fun at(shadowPrice: Double): ReplenishmentPlan {
val quantities = priced.skus.map { AverageInvestment.quantityAt(it, shadowPrice) }
return portfolio.planFor(quantities, shadowPrice)
}That is the body of the search’s inner step with the search removed, because the exchange curve is handed the price instead of finding it. Same objects, same message, one fewer participant. Had these two restated Equation 4.5 separately, the design would have failed at the exact place where Section 4.4 says the two problems meet.
One subtlety deserves a line. priced is the portfolio with every holding rate set to zero, because Section 4.4 has the multiplier replace the carrying charge instead of adding to it. Expressing that as a property of the SKUs keeps AverageInvestment.quantityAt the only place a quantity is computed.
A point on the curve is not a new kind of thing. at returns a ReplenishmentPlan, the type the constrained solve returns, because a point on the exchange curve is a portfolio evaluated at a price. It already has an investment and an ordering cost, the two axes of Figure 4.1. A CurvePoint class would add a noun the chapter never uses and force a conversion at every boundary. Before adding a type for a result, check whether the result is a familiar object under new conditions.
Two smaller decisions follow. The curve returns a Sequence and not a List, so a thousand-point sweep evaluates one point at a time and holds one. And the variety index \(J^{*}\) of Equation 4.21 is computed once on the curve, since it depends only on the items. Putting it on each point would compute the same number a thousand times and suggest that it varies along the curve.
G.3.9 Checking the Design Against the Mathematics
A design that cannot be checked is an opinion. Two things make this one checkable.
The first is Table G.5, in which every result of the chapter has one home in the code.
| The mathematics | Where it lives |
|---|---|
| Equation 3.17 | SKU.economicOrderQuantity |
| Equation 4.2 | AggregateMeasure.measure, Constraint.isMetBy |
| Equation 4.5 | ConstrainableMeasure.quantityAt |
| Equation 4.6 | LagrangianSearch, over Constraint.slackIn |
| Equation 4.9 | ProportionalScaling |
| Equation 4.15, Equation 4.21 | ExchangeCurve |
| Equation 4.25, Equation 4.27 | OrderFamily, IntegerMultiple |
| Equation 4.31, Equation 4.33 | PowerOfTwoMultiple |
| Equation 4.34 | SupplyNetwork.echelonRate |
| Algorithm 4.1 | SerialChain.blocks |
Read Table G.5 in both directions. Downward it says where to look when a number is wrong. Upward it tests the design, because every class in the package appears in the table or collaborates with something that does. A class in neither would be doing something the chapter never asked for.
The second is that every quantity the chapter reports can be recomputed a second way. Two of those second ways are worth carrying past the chapter.
Check a marginal against a numerical derivative. Each ConstrainableMeasure supplies both a measure and its marginal, and the marginal is where a sign slip hides. Such a slip still produces order quantities and still converges, so the answer looks like an answer. Comparing marginalAt against a numerical derivative of the measure beside it is what catches that, and nothing else will. For the same reason, each closed-form quantityAt is worth comparing against the general root finding default, which also demonstrates that a new measure really does need only two methods.
Check against an instance that can exhibit the thing being checked. A portfolio whose ordering costs are all equal cannot show the reallocation of Example 4.2, because a constant added to equal ordering costs changes them equally. A check written on such a portfolio agrees with the chapter and confirms nothing. Notice that it would look correct. Recall from Section 3.12 that this is not hypothetical: a ranking there came out identical under two different wrong objectives, and only a portfolio with unequal costs told them apart.
One question separates a design from an arrangement. What does the next requirement cost? A fifth measure, say a limit on handling hours, is a new class with two methods and no edit anywhere. A fifth ordering practice is a new IntervalRule. A third solution method is a new LotSizingMethod, and a third network topology is a subclass supplying one map and one algorithm. None of those changes an existing class.
G.4 Dynamic Lot Sizing
This section designs the software of Chapter 5. Where it says the chapter, it means Chapter 5. The code is in the package inventory.dynamiclotsizing, and Section 5.10 shows it in use.
Section 5.9 built the models as worksheets, where the structure is visible. A program has no such thing. Its structure is a set of decisions about which classes exist and what each one is responsible for, and none of those decisions leaves a mark in the finished code. So we make them first, in the order such an analysis proceeds: what the software must do, what the domain calls things, what each thing knows and does, and how they collaborate.
The chapter is a good one to design, because at first glance it is six unrelated recipes and at second glance it is one recipe with six settings. Getting that right in the code is what makes Table 5.15 a comparison.
G.4.1 What the Software Must Do
Reading back over the chapter, we find that the software has to
- hold a requirements schedule for one item, with costs that may vary by period,
- price any window \(w(t,u)\),
- evaluate a plan someone else chose, reporting setup, purchase and carrying separately,
- produce a plan under lot-for-lot, an adjusted economic order quantity, a periodic order quantity, Silver-Meal, least unit cost, part-period balancing, and Wagner-Whitin,
- report the penalty of one plan against another, and
- roll a horizon forward, committing part of each plan and discarding the rest.
Requirement 6 is the one Section 5.9 could not meet, and it is the reason for writing a program at all.
G.4.2 Finding the Nouns
Underline the nouns in the requirements, and three survive.
A requirements schedule is what the planner is handed. It is the item’s requirements and its costs over a horizon, and it is the only thing in the chapter that is data and not decision.
A plan is what the planner produces. It is an order quantity per period, and it knows what it costs.
A rule is how one becomes the other. Seven of them appear in the chapter, and Section 5.6 ranks them, which means the software has to be able to hold one without knowing which.
Two candidate nouns are instructive rejections.
Window looks like a class. It has a start, an end, a cost, and the chapter talks about it constantly. It fails because a window has no behavior of its own and no life of its own. It exists for the length of one comparison inside one rule, and \(w(t,u)\) is a function of the schedule and two integers. Thus, making it a class would put \(N^2/2\) objects on the heap to hold a number apiece.
Order also looks like a class, and it is a real thing in a warehouse. Here it is \(Q_t\), a number in a position. Every question the chapter asks about an order is a question about a plan: how many are there, what do they cost, and when do they fall.
Thus, the schedule owns the window cost. That is the decision the rest of the design rests on. Every rule in Table 5.15 prices the same windows, so computing them in one place means the heuristics and the algorithm are compared on identical numbers and not on two implementations of Equation 5.7.
G.4.3 What Each Thing Knows and Does
For each of the three we write a card, listing what it is responsible for and whom it needs in order to meet that responsibility.
| Class | Knows and does | Collaborates with |
|---|---|---|
RequirementsSchedule |
the requirements and the three cost streams; the requirement over a span; the unit cost held from one period to another; the window cost; the variability coefficient; the forced order period | LotSizingPlan |
LotSizingPlan |
the order quantities; ending inventory; setup, purchase and carrying; whether it orders only when empty; its penalty against another plan | RequirementsSchedule |
LotSizingRule |
how far a replenishment should reach | RequirementsSchedule, LotSizingPlan |
RollingHorizon |
the true schedule, the planning window, the frozen span; what the committed orders actually cost | all three |
Table G.6 illustrates one thing by leaving it out. A plan does not know its ending inventory as stored data. Equation 5.1 determines the inventory from the orders, so storing both would allow a plan to exist whose inventory no sequence of orders produces. The plan stores the quantities and computes the rest.
Notice also that the plan validates itself. A plan that runs short in some period violates assumption 6, and the constructor refuses it. That is not defensive programming for its own sake. Thus, every plan anywhere in the program is feasible, and no method downstream has to ask.
G.4.4 The Schedule
class RequirementsSchedule(
val label: String,
requirements: List<Double>,
orderCosts: List<Double>,
unitCosts: List<Double>,
holdingRates: List<Double>,
) {
/** The number of periods in the planning horizon, written N in the text. */
val horizon: Int get() = d.size
/** The periods, 1 through N, as a range to iterate over. */
val periods: IntRange get() = 1..horizon
/** The requirement of periods [from] through [through], written d[t,u]. */
fun requirementOver(from: Int, through: Int): Double {
requireWindow(from, through)
return (from..through).sumOf { d[it - 1] }
}
}Periods are numbered 1 through \(N\) on the outside and from zero on the inside, which is the ordinary arrangement. The alternative, exposing zero-based periods, would make every call site translate and every example in the chapter read differently from the text.
The costs arrive as four parallel lists instead of four scalars, so a period-varying instance needs no second class. For example, the constant-cost case that every worked example in the chapter utilizes is a factory method:
companion object {
/**
* The common case: one order cost, one unit cost and one carrying charge for the
* whole horizon, with h = ic as in @sec-costest-i.
*/
fun constantCosts(
label: String,
requirements: List<Double>,
orderCost: Double,
unitCost: Double,
carryingCharge: Double,
): RequirementsSchedule = RequirementsSchedule(
label = label,
requirements = requirements,
orderCosts = List(requirements.size) { orderCost },
unitCosts = List(requirements.size) { unitCost },
holdingRates = List(requirements.size) { carryingCharge * unitCost },
)
}The window cost is the schedule’s central method, and it is memoized, since every rule asks for the same \(N(N+1)/2\) values and Section 5.4.1 requires the arc costs to be settled before any decision is taken.
/**
* The window cost: order in [from] enough to cover the requirements of periods
* [from] through [through], and pay for the holding that implies.
*/
fun windowCost(from: Int, through: Int): Double {
requireWindow(from, through)
val key = (from - 1) * horizon + (through - 1)
cached[key]?.let { return it }
val value = k[from - 1] + (from..through).sumOf { unitCostHeld(from, it) * d[it - 1] }
cached[key] = value
return value
}
/**
* Setup plus carrying for a window. This is the cost the heuristics compare. The
* purchase term is excluded: it is the same under every plan while the
* unit cost is constant, and a criterion that divides by the length of the window
* would otherwise be dominated by it.
*/
fun relevantWindowCost(from: Int, through: Int): Double =
orderCostIn(from) + carryingCostOver(from, through)Two window costs, and the difference between them is not cosmetic. Equation 5.4 includes the purchase term and the recursion uses it, and that is right: adding the same constant to every plan changes no comparison. A heuristic that divides by the length of the window is a different matter. The purchase term grows with the window while the setup does not, so a cost-per-period built on Equation 5.4 falls simply because the window is longer, and Silver-Meal would extend to the end of the horizon on every instance. It has to divide the relevant cost, and relevantWindowCost supplies it.
G.4.5 Three Rules Are One Rule
Section 5.5.1 claims that Silver-Meal, least unit cost and part-period balancing are one procedure with three stopping rules. If that claim is true, the code should contain the procedure once.
interface LotSizingRule {
val name: String
fun plan(schedule: RequirementsSchedule): LotSizingPlan
}
abstract class WindowRule(override val name: String) : LotSizingRule {
/** The figure of merit for covering [from] through [through], or null to skip. */
protected abstract fun scoreOf(
schedule: RequirementsSchedule,
from: Int,
through: Int,
): Double?
final override fun plan(schedule: RequirementsSchedule): LotSizingPlan {
val orders = mutableListOf<Int>()
var from = schedule.nextRequirementFrom(1)
while (from <= schedule.horizon) {
orders.add(from)
from = schedule.nextRequirementFrom(1 + lastPeriodCovered(schedule, from))
}
return schedule.planFrom(orders)
}
/** How far a replenishment placed in [from] should reach. */
fun lastPeriodCovered(schedule: RequirementsSchedule, from: Int): Int {
var best = from
var previous: Double? = null
for (through in from..schedule.horizon) {
val score = scoreOf(schedule, from, through) ?: continue
if (previous != null && score > previous + TOLERANCE) break
previous = score
best = through
}
return best
}
}Notice that plan opens each window at nextRequirementFrom, the first period at or after the one given that requires something. An order placed in a period that needs nothing only carries stock across it, and the zero-inventory property of Section 5.3.1 says the optimal plan never places one, so no rule opens a window there.
Then two of the three rules are three lines apiece.
/** Silver-Meal: the least cost per period. */
object SilverMeal : WindowRule("Silver-Meal") {
override fun scoreOf(schedule: RequirementsSchedule, from: Int, through: Int): Double =
schedule.relevantWindowCost(from, through) / (through - from + 1)
}
/** Least unit cost: the least cost per unit. */
object LeastUnitCost : WindowRule("Least unit cost") {
override fun scoreOf(schedule: RequirementsSchedule, from: Int, through: Int): Double? {
val units = schedule.requirementOver(from, through)
return if (units <= 0.0) null else schedule.relevantWindowCost(from, through) / units
}
}That is Table 5.10, executable. The nullable return is the third column of that table’s one irregularity: a window covering no units has no cost per unit, so the rule steps over it instead of dividing by zero. Month 9 of the belt is such a period.
The third rule does not fit, and forcing it in would be the mistake.
/**
* Part-period balancing: extend until the carrying cost of the window is as close as
* it can get to the order cost.
*
* It does not fit WindowRule because it does not walk a score to a minimum. It walks
* a gap to its closest approach, and the period it keeps may be the one before the
* test failed and not the one that failed.
*/
object PartPeriodBalancing : LotSizingRule {
override val name: String = "Part-period balancing"
fun lastPeriodCovered(schedule: RequirementsSchedule, from: Int): Int {
val setup = schedule.orderCostIn(from)
var best = from
for (through in from + 1..schedule.horizon) {
val carried = schedule.carryingCostOver(from, through)
if (carried > setup) {
val below = schedule.carryingCostOver(from, through - 1)
return if (abs(carried - setup) < abs(below - setup)) through else through - 1
}
best = through
}
return best
}
}A template method earns its place when three things share a shape, and should be abandoned the moment a fourth thing only appears to. Part-period balancing can step back, and a stopping rule that returns “the one before the one that failed” cannot be expressed as a figure of merit walked to a minimum. Section 5.9.4 found the same boundary in the worksheet, where the two walking rules need a triangle of stopping tests and part-period balancing needs an ascending lookup. That two independent implementations drew the line in the same place is a sign the line is in the domain and not in either implementation.
G.4.6 The Algorithm Is Not a Heuristic
WagnerWhitin implements LotSizingRule and shares none of WindowRule. That is the arrangement Section 5.5 describes: an optimal algorithm and a stopping rule are different kinds of thing, and the interface says only that both answer the same question.
object WagnerWhitin : LotSizingRule {
override val name: String = "Wagner-Whitin"
/** The value function, the predecessor pointers, and the plan they trace out. */
fun solve(schedule: RequirementsSchedule): Solution {
val n = schedule.horizon
val value = DoubleArray(n + 1)
val from = IntArray(n + 1)
for (t in 1..n) {
var best = Double.MAX_VALUE
var argument = 1
for (s in 1..t) {
val candidate = value[s - 1] + arcCost(schedule, s, t)
// A tie keeps the earliest period achieving it, the same one that
// scanning s upward with a strict comparison keeps, and that MATCH
// finds on the worksheet. Both artifacts must report the same S(t).
if (candidate < best - TOLERANCE) {
best = candidate
argument = s
}
}
value[t] = best
from[t] = argument
}
...
}
private fun arcCost(schedule: RequirementsSchedule, s: Int, t: Int): Double =
if (schedule.requirementOver(s, t) == 0.0) 0.0 else schedule.windowCost(s, t)
}arcCost is the window cost, except that a window whose periods require nothing costs nothing, because it needs no order. When period 1 requires something, as Section 5.1 assumes, the exception changes no value: an empty window later in the horizon ties with extending the window before it, and the tie keeps the earlier period. It matters for a schedule that opens with empty periods, which the explorer accepts. Charging that empty window a setup would make the recursion order in period 1 and carry the stock across the empty periods, which is not optimal.
solve returns more than a plan. It returns \(V\) and \(S\), because Example 5.3 prints them and because a reader who wants to check the traceback needs the pointers. A method that returned only the plan would make Table 5.7 impossible to produce without solving the problem twice.
The two economic order quantity rules call into Chapter 3 instead of recomputing it.
class AdjustedEconomicOrderQuantity : LotSizingRule {
override fun plan(schedule: RequirementsSchedule): LotSizingPlan {
val quantity = EconomicOrderQuantity.orderQuantityFor(
orderCost = schedule.orderCostIn(1),
demandRate = schedule.averageRequirement,
holdingRate = schedule.holdingRateIn(1),
)
...
}
}This is the same EconomicOrderQuantity that Section G.2 built, used unchanged. Equation 3.17 appears once in this book’s code, so there is one place to correct when it is wrong.
G.4.7 How the Objects Solve It
Figure G.12 illustrates one call. The caller hands a rule a schedule and gets a plan.
The schedule sits in the middle of every collaboration. That follows from giving it the window cost. A rule never computes a cost; it decides which costs to ask for. That is what lets Section 5.6 rank the rules: they are being compared on their decisions and not on their arithmetic.
G.4.8 Rolling the Horizon
RollingHorizon is the class that exists because a worksheet cannot do this.
class RollingHorizon(
private val actual: RequirementsSchedule,
private val planningHorizon: Int,
private val freeze: Int = 1,
) {
/**
* Run [rule] on a window that advances by [freeze] periods at a time, implementing
* only the frozen orders, and report what the implemented orders actually cost.
*/
fun realizedPlan(rule: LotSizingRule): LotSizingPlan {
val n = actual.horizon
val placed = DoubleArray(n)
var period = 1
while (period <= n) {
val onHand = carriedInto(placed, period)
val committedTo = minOf(period + freeze - 1, n)
val net = netRequirements(period, minOf(period + planningHorizon - 1, n), onHand)
if (net != null) {
val plan = rule.plan(net.window)
for (t in period..committedTo) {
val offset = t - net.firstPlanned + 1
if (offset in 1..net.window.horizon) placed[t - 1] = plan.orderIn(offset)
}
}
period = committedTo + 1
}
return LotSizingPlan(actual, placed.toList())
}
}The subtle part is netRequirements. The planner at period \(t\) may be holding stock left over from an earlier order, and assumption 8 says a schedule starts empty. So the stock on hand is netted against the nearest requirements, as a requirements record nets it, and planning begins at the first period the stock does not cover. Getting this wrong produces a plan that orders on top of stock it already has, which every rule in the chapter is supposed to forbid.
Notice that realizedPlan returns a LotSizingPlan built against the true schedule and not against any of the windows. The plans the rule produced along the way were mostly discarded. What is reported is the cost of the orders that were actually placed, the only thing Table 5.17 could mean.
G.5 Material and Distribution Requirements Planning
This section designs the software of Chapter 6. Where it says the chapter, it means Chapter 6. The code is in the package inventory.requirementsplanning, and Section 6.10 shows it in use.
Section 6.9 built the models as worksheets, and a worksheet shows its own structure. A program does not, so the structure has to be decided and written down. In Section G.4 we did this for Chapter 5 and found that three heuristics were one procedure. The chapter’s design has a different shape, because most of what it needs already exists.
G.5.1 What the Software Must Do
- Hold a product structure, with quantities per, and assign low-level codes.
- Hold what the planner knows about an item that is not its requirements.
- Compute one item’s record: net, lot size, offset.
- Explode a master production schedule through the structure, in the right order.
- Do the same over a distribution network.
- Report what a plan costs, by item and in total.
Requirement 5 is the one to watch. It looks like a second feature and Section G.5.6 argues that it is not one.
G.5.2 Finding the Nouns
A planned item is what the item master holds: lead time, opening stock, what is on order, the costs, and the rule. Not its requirements, because for every item but an end item those are computed and change whenever the level above is replanned.
A bill of material is the structure. It owns the low-level codes, which are a property of the graph and not of any item in it. An item cannot answer “what is my low-level code” without seeing every path that reaches it, so the question belongs to the thing that holds the paths.
An MRP record is one item’s six rows over a horizon.
A requirements plan is every item’s record, and the order they were computed in.
A receipt policy is how much to have arrive, given what must arrive.
Level is the instructive rejection. It reads like a class and the chapter uses the word constantly. It fails because a level has no behavior: it is an integer attached to an item, and the only thing anyone does with it is sort by it.
Figure G.13 illustrates the five and how they stand to one another. Notice that the bill of material holds the low-level codes and the planned item does not.
G.5.3 The Join with Chapter 5
The design turns on one sentence: the net requirement stream is a Section 5.1.1 requirements schedule. Once that is said, none of Section 5.5 needs an MRP version.
/**
* The net requirements of this item, as a @sec-dynamiclotsizing requirements schedule.
*
* This is the join between the two chapters. @sec-dls-problem
* took a requirements schedule as given. @sec-mrpdrp computes one, for every item at
* every level, and hands it back to @sec-dls-heuristics unchanged.
*/
fun scheduleFor(netRequirements: List<Double>): RequirementsSchedule =
RequirementsSchedule.constantCosts(
label = label,
requirements = netRequirements,
orderCost = orderCost,
unitCost = unitCost,
carryingCharge = carryingCharge,
)The adapter that uses it is the whole of what Section 5.5 needed to be reused.
class PlanTheHorizon(private val rule: LotSizingRule) : ReceiptPolicy {
override fun receiptsFor(netRequirements: List<Double>, item: PlannedItem): List<Double> {
val first = netRequirements.indexOfFirst { it > 0.0 }
if (first < 0) return netRequirements.map { 0.0 }
val plan = rule.plan(item.scheduleFor(netRequirements.drop(first)))
return netRequirements.indices.map {
if (it < first) 0.0 else plan.orderIn(it - first + 1)
}
}
}The drop is part of the contract and not a convenience. Section 5.1.2 has inventory starting at zero and period 1 holding an order, so a rule handed a stream that opens with empty periods places a receipt in the first of them and carries it. The empty periods here are the lead-in of Section 6.3.4, and they are not part of the problem the rule is being asked to solve.
G.5.4 One Interface for Two Kinds of Rule
A fixed order quantity decides period by period and looks nowhere. Silver-Meal cannot decide anything until it has seen the whole horizon. They look as though they need two interfaces and they do not, because the net requirement stream is computed before any rule runs. That is what makes the whole of it available to a rule that needs the whole of it.
fun interface ReceiptPolicy {
/** Planned order receipts, one per period, covering [netRequirements]. */
fun receiptsFor(netRequirements: List<Double>, item: PlannedItem): List<Double>
}Figure G.14 illustrates what implements it. Two of the three are new, and the third is an adapter onto Chapter 5.
The fixed order quantity is the rule Section 5.2.2 had to exclude, and it is admissible here.
/**
* Order [quantity], or the period's net requirement when that is larger.
*
* @sec-dls-threeplans excluded this rule, because a quantity unrelated to the
* requirements cannot finish the horizon empty. Inside an MRP record it is
* admissible, and widely used, precisely because the record is not required to
* finish empty: what is left over is on hand at the start of the next planning
* cycle. That is what the projected-on-hand row is for.
*/
class FixedOrderQuantity(private val quantity: Double) : ReceiptPolicyG.5.5 Two Readings of “Net Requirement”
The record computes in two sweeps, one for each reading of Section 6.3.2, and this is the only place in the package where a name means two things. The first sweep produces the stream the policy is asked to cover; the second recomputes the row the record prints, after the policy’s receipts.
val netRequirementsBeforeLotSizing: List<Double> // what the policy is given
val netRequirements: List<Double> // what the record showsThus, the two names. One property meaning whichever the caller happened to need would put the package into a quiet disagreement with every worked example in the literature, and nothing in the arithmetic would say where the disagreement came from.
G.5.6 A Network Is a Bill of Material
Section 6.6.1 claimed that distribution requirements planning is the same calculation. The design’s job is to make that claim structural and not rhetorical, and the way it does so is by not writing a second class.
BillOfMaterial(
locations,
regions.map { BillOfMaterial.Usage(parent = it, child = "CW", quantity = 1.0) },
)That is the whole of the network’s definition. RequirementsPlan then assigns low-level codes, which puts the regions at 0 and the center at 1, plans them in that order, and computes the center’s gross requirements as the sum over its parents. Figure G.15 traces one item through that, and nothing in the trace would change if the graph were a network instead of a structure.
The temptation is a DistributionNetwork class with regions and center on it, reading more naturally at the call site. It would duplicate the low-level coding, the planning order and the explosion, and it would then be possible for the two to disagree about a network that is also a structure, and that is a real thing: a warehouse supplying both dealers and an assembly plant.
Section 4.6.3 does have a DistributionNetwork, and it is not this one. It solves a different problem, the power-of-two reorder intervals of Section 4.6.2, and it holds no time-phased anything. Two classes with the same name in one book is a fair criticism; two classes for two problems is not.
G.6 Single-Period Stochastic Inventory
This section designs the software of Chapter 7. Where it says the chapter, it means Chapter 7. The code is in the package inventory.newsvendor, and Section 7.14 shows it in use.
Section G.4 and Section G.5 each had an algorithm to organize. This chapter has a formula, so the design question is different and smaller: what are the pieces, and what keeps the two ways of computing the answer in agreement?
G.6.1 What the Software Must Do
Five requirements follow from the chapter, and each one names where in the chapter it comes from.
- Solve exactly, by Equation 7.11 for a continuous model and by Equation 7.13 for a discrete one, for any family with a quantile and a first order loss function.
- Evaluate any quantity and not only the best one, because Table 7.8, Table 7.6 and Table 7.9 all price a grid.
- Estimate the profit of a quantity by sampling, priced by the same cost function the exact route uses, Section 7.10.
- Refuse a problem with no finite, positive answer, Section 7.9.3.
- Take stock already on hand, Section 7.9.2.
G.6.2 Finding the Nouns
A demand model is a distribution with a quantile and a first order loss function. Notice that this is not a new class. It is LossFunctionDistributionIfc from Section D.3.10, which the KSL already provides for every family the chapter uses, and the design’s first decision is not to reimplement it.
A single-period cost structure is \(c_{o}\) and \(c_{u}\), together with the mapping from \(s\), \(c\), \(u\) and \(\pi\) that produces them. It owns Equation 7.5, it owns the critical ratio, and it owns the refusal of Section 7.9.3: a cost structure with a non-positive \(c_{o}\) or \(c_{u}\) is rejected at construction rather than allowed to return an absurd quantity later.
A solution pairs a quantity with what it implies: the expected shortage, the expected leftover, the expected cost, the expected profit. It is computed for any quantity and not only the optimal one, because the tables of the chapter all need a grid.
Newsvendor is the instructive rejection. It reads like the central class and the chapter is named after it. It fails because the cost structure and the demand model already do everything between them. Given both, the optimal quantity is one line, and a class whose only method is one line is a function wearing a costume.
G.6.3 The Classes
The code is in code/, package inventory.newsvendor, file SinglePeriod.kt. The cost structure is a data class.
data class SinglePeriodCosts(
val price: Double,
val cost: Double,
val salvage: Double,
val penalty: Double = 0.0,
) {
val overageCost: Double get() = cost - salvage
val underageCost: Double get() = price - cost + penalty
val criticalRatio: Double get() = underageCost / (underageCost + overageCost)
fun cost(q: Double, d: Double): Double =
overageCost * max(q - d, 0.0) + underageCost * max(d - q, 0.0)
fun profit(q: Double, d: Double): Double =
price * min(d, q) + salvage * max(q - d, 0.0) - cost * q - penalty * max(d - q, 0.0)
}The four constructor parameters are \(s\), \(c\), \(u\) and \(\pi\). overageCost and underageCost are Equation 7.5, criticalRatio is Equation 7.11, and cost and profit are Equation 7.3 and Equation 7.4 for one realized demand d, a value of \(X\). An init block, not shown, refuses a non-positive \(c_{o}\) or \(c_{u}\) with a message naming Section 7.9.3. Notice that price is the value of a unit at the moment it is needed. For the belt that is the selling price, and for the transformer of Example 7.3 it is the emergency purchase price, because that is what a missing unit costs to replace. A data class also gives copy, so a variation is one line. For the belt’s costs, copy(penalty = 40.0) is Section 7.9.1.
The exact route is two functions.
fun optimalLevel(costs: SinglePeriodCosts, demand: DistributionFunctionIfc): Double {
val ratio = costs.criticalRatio
if (demand !is DiscreteDistributionIfc) return demand.invCDF(ratio)
var x = max(floor(demand.invCDF(ratio)), 0.0)
while (x > 0.0 && demand.cdf(x - 1.0) >= ratio) x -= 1.0
while (demand.cdf(x) < ratio) x += 1.0
return x
}optimalLevel is Equation 7.11 when demand is continuous. When it is discrete, the two loops make the answer Equation 7.13 exactly, the smallest whole unit whose distribution function reaches the ratio, whatever convention the library’s quantile uses for a staircase. It takes any DistributionFunctionIfc, which is what lets Table 7.6 ask a lognormal and a gamma for a quantity without asking either for a loss function.
fun evaluate(costs: SinglePeriodCosts, demand: LossFunctionDistributionIfc,
level: Double, onHand: Double = 0.0): NewsvendorSolution {
val shortage = demand.firstOrderLossFunction(level)
val leftover = shortage + level - demand.mean()
val expectedCost = costs.overageCost * leftover + costs.underageCost * shortage
return NewsvendorSolution(costs, level, onHand, demand.cdf(level), shortage, leftover,
expectedCost, (costs.price - costs.cost) * demand.mean() - expectedCost)
}
fun solve(costs: SinglePeriodCosts, demand: LossFunctionDistributionIfc, onHand: Double = 0.0) =
evaluate(costs, demand, max(optimalLevel(costs, demand), onHand), onHand)evaluate prices any level, the stock available for the period, which is \(S\) of Section 7.9.2, and onHand is its \(I\). Its lines are Equation 7.7, Equation 7.8, Equation 7.9 and Equation 7.6, in that order. solve evaluates at the optimal level, and onHand carries Equation 7.15: the level does not depend on what is already there, and the order is the difference. When more than the level is already on hand, the level is what is on hand and nothing is ordered. NewsvendorSolution holds the eight values and computes orderQuantity as \((S - I)^{+}\).
The sampled route is one function.
fun estimate(demand: RVariableIfc, q: Double, replications: Int,
profit: (q: Double, d: Double) -> Double): Statistic {
val stat = Statistic("profit at %.2f".format(q))
demand.resetStartStream()
repeat(replications) { stat.collect(profit(q, demand.value)) }
return stat
}
fun estimate(costs: SinglePeriodCosts, demand: RVariableIfc, q: Double, replications: Int) =
estimate(demand, q, replications, costs::profit)This is the loop of Section 7.10 with its free variables given names. resetStartStream is there for the reason that section gives: every quantity estimated with the same demand faces the same demands. The second form passes costs::profit, the very function the cost structure defines. The first form takes any profit function, which is what Section 7.10.1 needs.
G.6.4 The Two Routes Must Agree
The design’s real content is the agreement Section 7.10 demonstrated. The same cost structure is evaluated two ways, exactly and by sampling, and the two must agree.
That agreement is not a convenience; it is what the design is for. A solver and an estimator that share a cost function can be checked against each other, and one that does not share it cannot. Both routes take their costs from SinglePeriodCosts. The exact route uses its overageCost and underageCost through the loss function in evaluate, and the sampled route calls its profit on each demand in estimate. The two are tied by Equation 7.6, which a test in the code checks.
Notice what that buys when the exact route stops applying. Under the nonlinear salvage rule of Section 7.10.1 the loss function integration is no longer valid, but the sampled evaluation still is. Only the profit function changes, and the machinery that samples and averages it is the machinery that was validated against the formula when the formula held. That is the whole argument for building it this way. Section 7.14 puts both routes to work on the belt.
G.7 Continuous Review Systems
This section designs the software of Chapter 8. Where it says the chapter, it means Chapter 8. The code is in the package inventory.continuousreview, and Section 8.13 shows it in use.
Section G.4 had six recipes to unify and Section G.6 had a formula to organize. The chapter has an algorithm, so the shape of the design is closer to the first. What makes it worth the walk is that the two hardest decisions here concern where a convention lives and how a fast search is kept exact, not which classes exist.
G.7.1 What the Software Must Do
Reading back over the chapter, we find that the software has to
- hold a lead time demand distribution and evaluate its loss functions to the third order, including at arguments below zero,
- evaluate any \((r,Q)\) policy, reporting the measures of Section 8.2 separately, and the spread of the backorder level alongside its mean,
- bound the answer before any search runs, as Section 8.7 does,
- return the optimal integer \((r,Q)\),
- do that in reasonable time on an item whose optimal batch is in the thousands, and
- accept a service target in place of a shortage cost.
Notice that requirement 1 reaches one order higher than the measures themselves do. Equation 8.20 needs \(G^{2}\) and Equation 8.23 needs \(G^{3}\), and the KSL supplies loss functions to the second order only, so the third is the one piece of distribution machinery the chapter has to build rather than borrow. Section D.3.7 gives the forms.
Requirement 5 is the one the worksheet of Section 8.12 cannot meet. That sheet unrolls one row per step of Algorithm 8.1, so it answers any item whose optimal batch fits in the rows laid down. An item whose batch is 2,842 does not fit, and that is the reason for writing a program at all.
G.7.2 Finding the Nouns
Underline the nouns in the requirements and four survive.
A lead time demand is a distribution with a quantile and two loss functions. Notice that this is not a new class but LossFunctionDistributionIfc of Section D.3.10, which the KSL already provides for every family Section 8.3 selects among, and the design’s first decision is not to reimplement it. What the library does not provide is the one thing requirement 1 names: \(G^{1}\) and \(G^{2}\) below zero. A wrapper adds those and nothing else.
An item is \(\lambda\), \(k\), \(h\), \(b\) and a lead time demand. It owns every formula in Section 8.2 and Section 8.5, which means it owns the cost of any policy, optimal or not. An item whose demand arrives in lots also carries its lot size distribution, which only the fill rate of Equation 9.23 reads.
A policy is a reorder point and an order quantity, and it is a pair of integers with a name.
An optimizer reads an item and returns a policy. It is the only thing in the chapter that searches.
Two candidate nouns fail, and each fails instructively.
Base-stock model looks like a class. Section 8.4 is a section of its own, it has its own cost function and its own optimality condition, and a reader who met it first would expect an object. It fails because Equation 8.28 makes it literal that the base-stock cost is the \((r,Q)\) cost at \(Q = 1\). In the code baseStockCost(s) is one line, and the line is the general window evaluated at a width of one unit. A second class would be a second implementation of an identity the chapter proves.
Service level also looks like a class, and it is the thing practitioners actually talk about. It fails for the reason Section 8.10.6 gives: a target is not an alternative to a shortage cost, it is a shortage cost stated without saying so. Thus, it belongs in the construction of an item, where Equation 8.47 converts it to a \(b\) that everything downstream can see and argue with. Making it a class would preserve the evasion the section exists to expose.
Figure G.16 illustrates the four and how they stand to one another.
G.7.3 The Window Is the Unit of Work
The design’s first real content is a decision about what a single step costs.
Equation 8.28 says a policy’s cost is \(k\lambda/Q\) plus the average of \(Q\) consecutive base-stock costs. Written that way it invites a loop, and a loop makes every policy cost \(Q\) evaluations of the lead time demand distribution. The search then costs \(Q\) times whatever it costs to walk, and the items that need a program are the items where \(Q\) is large.
Both sums have closed forms, and the chapter has already given them. Summing Equation 8.22 over the window is arithmetic, and summing Equation 8.20 telescopes by Equation D.10. Thus, one method replaces the loop:
fun windowTotal(r: Int, q: Int): Double {
requirePolicy(r, q)
val width = q.toDouble()
val shortage = leadTimeDemand.lossSecond(r.toDouble()) -
leadTimeDemand.lossSecond((r + q).toDouble())
return fixedCostRate +
holdingCost * width * (expectedPosition(r, q) - theta) +
(holdingCost + backorderCost) * shortage
}Notice that q appears in the arithmetic and not in a loop. A step of one thousand costs what a step of one costs, and that single fact is what makes the search of Section 8.8.3 worth writing. A step size that is free can double.
G.7.4 Two Searches, One Answer
The design’s second real content is that the optimizer exposes two methods and not one.
optimizeFromUnitBatch is Algorithm 8.1 as printed: start at \(Q = 1\), add the cheaper neighbor, stop when it is no longer below the average. It is exact by the argument of Section 8.8.1 and its loop runs \(Q^{*}\) times. optimize is the same algorithm warm started, searched in both directions, and stepped by doubling.
The doubling is fast and, on its own rather than exact. A step that commits on one edge of the window can build a window skewed to one side. It then carries \(Q\) past the optimum to a value that is still cheaper than where it started, and a search that only grows \(Q\) cannot walk back. optimize therefore finishes every doubling search with an exact per-unit search in both directions from wherever the doubling left it.
That is a claim, and a claim of that kind belongs in a test rather than a comment:
for ((name, model) in items()) {
val exact = RQOptimizer(model).optimizeFromUnitBatch()
val fast = RQOptimizer(model).optimize()
assertEquals(exact.orderQuantity, fast.orderQuantity, "$name: Q")
assertEquals(exact.reorderPoint, fast.reorderPoint, "$name: r")
assertEquals(exact.cost, fast.cost, 1e-6, "$name: cost")
}Keeping the slow method is the point. It is the thing the fast one is checked against, and a reader who distrusts the doubling can run it. On the items of Table G.7 the two agree everywhere, and the cost of agreeing is visible: 74 evaluations against 5,684 on an item whose optimal batch is 2,842.
| Item | \(r^{*}\) | \(Q^{*}\) | Algorithm 8.1 | Warm started |
|---|---|---|---|---|
| Transformer | 8 | 7 | 14 | 19 |
| Mid volume | 196 | 295 | 590 | 75 |
| High volume | 1,195 | 2,842 | 5,684 | 74 |
G.7.5 Where the Conventions Live
Two places in the chapter have a discrete form and a continuous one, and both are easy to write wrongly.
Equation 8.18 puts the inventory position on the integers \(r+1\) through \(r+Q\), whose mean is \(\tfrac{1}{2}(Q+1) + r\). A continuous family puts it on the interval, whose mean is \(Q/2 + r\). Likewise Equation D.10 defines \(G^{2}\) with \((X - b - 1)\) when \(X\) is discrete and with a square when it is continuous, so the two extensions below zero differ.
Each belongs in exactly one method. The position is one method that asks the distribution which kind it is; the loss function extension is one method that does the same. Everything else in the code, including the cost, the measures and both searches, calls those and never restates the rule. Write a convention out at each place it is used and one of those places will eventually disagree with the others. Half a unit of stock is \(h/2\) per unit time on every policy the software will ever report, and nothing about the answer looks wrong when it is missing.
G.8 Multi-Echelon Inventory Systems
This section designs the software of Chapter 10. Where it says the chapter, it means Chapter 10. Section 10.12 shows the code in use.
Section G.7 had an algorithm to organize and one convention to place. The chapter has more moving parts: two locations that must agree with one another, two models that share most of their arithmetic, and two searches only one of which may safely be run greedily. The package is inventory.multiechelon.
G.8.1 What the Software Must Do
Reading back over the chapter, the software has to
- hold a depot and the storerooms it supplies, and derive the rates of Equation 10.1 and Equation 10.2 from the network,
- evaluate the depot exactly, including the variance of its backorder level, which Equation 10.19 needs and which Section G.7 never had to produce,
- build a storeroom’s pipeline under either model, to one moment or to two,
- report the measures of Section 10.4 at every location,
- find the best split of a given number of units across the two levels, discarding the non-convex plans of Section 10.9.3, and
- spend a budget across items, returning the whole curve rather than one plan.
Requirements 5 and 6 are the ones the worksheet of Section 10.11 cannot meet, for the reason Section 10.11.6 gives. Requirement 2 is the one that looks hardest and turns out not to be.
G.8.2 Finding the Nouns
Underline the nouns in the requirements and four survive.
A storeroom is \(\lambda_j\), \(\phi_j\), \(T_j\) and \(O_j\). It owns Equation 10.1, and it owns the part of its own pipeline that Theorem 10.1 covers exactly, which is a property of the location and not of the system around it.
A depot item is one item’s stock at the depot together with the storerooms it supplies. It owns \(\lambda_0\), the shares \(f_j\) of Equation 10.16, and the depot’s own pipeline distribution.
A model is a set of depot items, and it is what a search is handed.
A search reads a model and a budget and returns stock levels. It is the only thing in the chapter that chooses anything.
Three candidate nouns fail, and each fails instructively.
Depot looks like a class, and in a diagram it is one. It fails because everything the depot is asked for is a property of a distribution: a backorder level, a variance, a delay that is the first divided by a rate. Giving it a class of its own would give it a home for behavior it does not have. The depot’s stock and its storerooms travel together, so they are one object.
METRIC and VARI-METRIC as two classes is the reading Section 10.8 almost invites, since they have separate names and separate sections. It fails on Equation 10.18. The two models agree on every mean in the chapter, and two classes would let them drift apart in a place where the chapter says they cannot.
A pipeline distribution of our own is the reflex, and it is wrong for the reason Section G.7.2 gives: the library already has one.
G.8.3 What Each Thing Knows and Does
| Class | Knows | Does |
|---|---|---|
BaseStockItem |
a stock level and a lead time demand distribution | the measures of Section 10.4, and the two moments of its backorder level |
VMBaseItem |
its failure rate, repair split, repair and ship times, and its depot | Equation 10.1; refits its own pipeline from Equation 10.18 and Equation 10.19 |
VMItem |
the depot’s stock and the storerooms beneath it | Equation 10.2 and Equation 10.12; tells every storeroom to refit when anything moves |
VariMetricModel |
a set of items | the totals of Equation 10.24 |
MAFItemData |
one item’s curve of backorders against units | builds the curve, takes the best split per total, and convexifies |
MarginalAnalysisAlgorithm |
a model and a budget | Algorithm 10.3: merges items by delta value until the money runs out |
LagrangeAlgorithm |
a model, a budget and an interval of multipliers | prices money and searches for the price that spends the budget |
Notice that neither METRIC nor VARI-METRIC is a class. VMBaseItem builds a pipeline under either, and which one is a flag rather than a type. That is Equation 10.18 expressed as a design decision.
G.8.4 The Classes
Read the composition and the dependency against each other. A VMItem owns its storerooms, and each storeroom holds a reference back. Setting a storeroom’s repair fraction recomputes \(\lambda_0\) by Equation 10.2, refits the depot’s Poisson, and then refits every storeroom. Setting the depot’s own stock level does the same thing from the other side:
override var stockLevel: Int
get() = super.stockLevel
set(value) {
super.stockLevel = value
updateBaseLeadTimeDemands()
}That mutual reference should not be designed away. Equation 10.18 says a storeroom cannot be described without asking the depot how long it makes people wait. A design in which a storeroom could be changed without the depot noticing would be modeling something the chapter denies.
Mutability also suits what Section 10.9 does with these objects. Algorithm 10.3 moves stock levels thousands of times while searching, and rebuilding the network on every move would be the wrong shape for that.
G.8.5 What the Library Already Supplies
Three pieces of distribution machinery the chapter appears to need turn out to be available already, and recognizing that is most of the design.
The loss functions. Every location holds a LossFunctionDistributionIfc and asks it for firstOrderLossFunction. The measures of Section 10.4 are then written once and answered by whichever family the fit chose, which is Equation 10.5 saying that only the distribution of \(X_j\) matters.
The second moment of a backorder level. Equation 10.20 walks \(E[B^{2}(s)]\) up one stock level at a time, and a worksheet needs that because it has rows and no second order loss function. A program has the reverse. We write the square as \((x-s)^{2} = (x-s)(x-s-1) + (x-s)\) and take expectations over \(x > s\), which gives
\[ E[B^{2}(s)] = 2\,G^{2}(s) + G^{1}(s) \tag{G.1}\]
so Equation 10.19 needs one line:
val varianceBackOrders: Double
get() {
val ebo = expectedBackOrders
val g2 = leadTimeDemand.secondOrderLossFunction(stockLevel.toDouble())
return 2.0 * g2 - ebo * (ebo - 1.0)
}Notice that this does not make Equation 10.20 wasted. The two forms agree at every stock level, and each suits the artifact that carries it. A worksheet has rows and no second order loss function, so it climbs. A program has the loss function and no need of the rows, so it evaluates.
A negative binomial with a fractional number of successes. Section 10.11.6 left the worksheet stuck on \(r = 14.3674\), because its own negative binomial function truncates that argument. The library takes it as a real number, so Equation 10.22 is a constructor call.
G.8.6 Choosing a Family
Equation 10.22 divides by \(1 - p\), and \(p \to 1\) as the variance approaches the mean. The original code answered that with a band, a Poisson for any ratio between 0.9 and 1.1, and Section 10.8.4 showed what the band costs. The port keys off the variance to mean ratio with no band:
val c = variance / mean
return when {
c > 1.0 + RATIO_TOLERANCE -> negativeBinomialOn(mean, variance)
c >= 1.0 - RATIO_TOLERANCE -> Poisson(mean)
else -> { val scale = variance / mean; Gamma(mean / scale, scale) }
}Notice that RATIO_TOLERANCE is \(10^{-9}\), which is rounding and not a model. At an empty depot the two moments of Equation 10.19 agree exactly, but the variance is reached by subtracting numbers in the hundreds, so it lands a few units in the last place away from the mean. The tolerance keeps that case a Poisson. Anything further from one is fitted as what it is.
The third branch is there for a reason. Section 10.8 records that neither Graves nor Sherbrooke could prove the variance always exceeds the mean, so a program that assumed it would be asserting what the literature declines to.
G.8.7 One Class, Two Models
METRIC and VARI-METRIC differ in one place. A VMItem carries a flag, and a storeroom consults it when it refits:
leadTimeDemand = if (depot.forcePoissonAtBases) {
Poisson(expectedNumInResupply)
} else {
fitTwoMoments(expectedNumInResupply, varianceNumInResupply)
}Everything above that line is shared, which is what makes Equation 10.18 structural rather than merely asserted: the two models cannot disagree about a mean, because one object computes it.
A location reports the variance of the distribution in use, not the variance that Equation 10.19 computed. Under METRIC those differ, and a report showing the second while using the first would describe a model nobody ran.
G.8.8 Two Searches, Only One of Them Greedy
Section 10.9 is two searches nested, and the difference between them is the whole of Section 10.9.3.
The inner search is greedy and exact. At a fixed depot stock the storerooms’ backorder functions are convex by Equation 10.10, so handing out units one at a time to whichever location gains most cannot be improved on. MAFItemData fills a table with one row per total and one column per depot level, spreading within a column that way.
The outer step is a minimum rather than a search. The best depot level for a given total is the row minimum, and taking minima across rows is exactly where convexity is lost.
The third step is convexification, and it is a lower convex hull reached by repeatedly jumping to whichever later total gives the steepest descent:
var slopeMax = 0.0
for (c in kIndex + 1 until maxRows) {
val s = slope(kIndex, c)
if (s >= slopeMax) { slopeMax = s; kLast = c }
}The totals it skips are the ones Table 10.8 strikes out, and Equation 10.25 is then computed across the jump, over however many units it spans.
neediestBase ranks storerooms by exactly Equation 10.10, the \(G^{0}(S_j) = P\{X_j > S_j\}\) of the next unit. The original code ranked by the stockout probability \(P\{X_j \ge S_j\}\), one index off; the two agree on identical storerooms and need not agree in general, and the port corrects it so that the sentence above stays true.
Notice what is absent. There is no fixed point, no convergence test and no iteration count anywhere in the evaluation. Algorithm 10.1 has no loop and neither does the code, which is Section 10.6.1 cashed in. A model that allowed batching could not say that.
G.8.9 Pricing the Budget Instead of Enforcing It
Section 10.9.7 derives the relaxation and compares it with marginal analysis on the two-item problem. In code it is LagrangeAlgorithm, which enumerates the depot over a window and reads Equation 10.27 off each storeroom at each trial level. Figure G.19 places it beside marginal analysis.
Notice that LagrangeAlgorithm is abstract and holds everything except how the multiplier is chosen, which is its one abstract method, search(). LagrangeEnumerationAlgorithm walks a grid of multipliers and keeps the smallest absolute budget gap, and LagrangeIterativeAlgorithm bisects on budgetGapAt. The figure shortens both names. That one method is the whole of the difference between them, and it is why Section 10.9.7 finds them stopping on different sides of the budget. Both families call VariMetricModel to evaluate a plan, so neither search is a different model; they differ only in how a plan is proposed.
G.9 Multi-Echelon Systems with Batch Ordering
This section designs the software of Chapter 11. Where it says the chapter, it means Chapter 11. Section 11.17 shows the code in use.
The package is inventory.multiechelon, extending what Chapter 10 built, with one addition to inventory.continuousreview.
G.9.1 What the Software Must Do
Reading back over the chapter, the software has to
- evaluate a two-level system exactly where Axsäter (1993) applies, for checking everything else against,
- build a hub’s lead time demand from other demand and storerooms that batch, exactly and by the recipe,
- give the wait at the hub as a distribution, for a customer and for a storeroom’s order, at a constant or a random lead time,
- turn a wait into a storeroom’s lead time demand by any of the three routes, and
- run the iteration by either route and price its answer exactly.
G.9.2 The Classes
| Class | Knows | Does |
|---|---|---|
OneForOneTwoLevel |
the rates, lead times and three cost rates | Equation 11.5; the stock levels by linearity |
AxsaterBatchOrdering |
a one-for-one system and the two batches | Equation 11.7, Equation 11.8 and his equation (6), and his three approximations |
OrderCountLaw |
a storeroom’s rate and batch | Equation 11.9, at a random moment and seen from an order |
BatchedHub |
the other demand, the storerooms and the hub’s policy | Equation 11.10, Equation 11.12, the shortcut, Equation 11.14, and the hub’s measures over its positions |
HubDelay |
a hub, and whose wait | Equation 11.3 and Equation 11.13, their moments, and a midpoint grid |
MixedWait |
waits at several lead times | Equation 11.15 |
StoreroomWithDelay |
a storeroom’s rate, its transit and a wait | the three routes of Section 11.6.4 |
TwoLevelIteration |
a problem and the two routes | Algorithm 11.1, and the exact price of any policy |
TwoLevelLedger |
two policies and a script of demands | posts the ledgers of Section 11.3, checking the positions on every row |
Notice that no class is a “storeroom” in the sense of Chapter 10. A storeroom here is a demand stream as the hub sees it, StoreStream, and a lead time demand as the storeroom sees it, StoreroomWithDelay; what it is to itself is Chapter 8’s RQModel. LeadTimeDemand gains two factories, tabulated and mixture, since a convolution and a mixture are distributions no family describes.
G.10 Simulating Inventory Systems
This section designs the software of Chapter 12. Where it says the chapter, it means Chapter 12. Section 12.10 shows the code in use.
The package is inventory.simulation. Its core is the event model of the \((r, Q)\) policy in Rossetti (2026), copied into the companion code and adapted: the names follow this book’s notation, the reorder decision orders as many batches as it takes to clear the reorder point, and the model gains the options the chapter’s examples need. Every other package in the companion code computes; this one is the first that runs a model through time, and it is built on the KSL’s ModelElement rather than on its distributions alone.
G.10.1 What the Software Must Do
Reading back over the examples, the software has to
- run one stock point under \((r, Q)\), \((s, S)\) or \((R, s, S)\), which includes \((R, S)\) as \(s = S - 1\), with demand either backordered or lost,
- accept demand in lots of a stated distribution, filling a lot partly when the shelf holds part of it and owing the rest first come first served,
- draw each lead time from any distribution, deliver orders either independently or in one supply line, and record when an order overtakes another,
- be driven by a script of demand times as well as by a sampled demand process, so that Example 12.1 is a test and not only an illustration,
- collect the time-persistent measures of Equation 12.2 and the observation-based measures of Section 12.4.4, together with the undershoot, the order sizes, the waits and the cost terms of Equation 8.1, or a cost per unit lost under lost sales,
- let one stock point be another’s supplier over a transit time, filling the lower location’s orders first come first served and shipping part of an order when it holds only part of it, and let a lower location send some of its requests elsewhere, as a storeroom with its own repair shop does, and
- report each measure as an interval and compare it, field by field, with the exact model of the same policy.
G.10.2 The Nouns
Three nouns become classes: the stock point, the policy it runs, and the supplier that fills its orders. Several others do not, and the reasons are the design.
The event is not a class. A demand and a receipt are methods of the stock point, scheduled on the KSL’s calendar. Table 12.1 lists two events and one decision, and the code has two event methods and one decision method in the same places.
Lost sales is not a subclass. Whether an unmet demand waits or departs is a property of the demand, not a different kind of stock point, so it is a flag on the stock point. Every policy runs under either setting without being written twice.
Periodic review is a policy, not a stock point. It is the one policy that owns an event of its own, the review, which it schedules on the calendar when the replication starts. A demand under periodic review takes no decision, so the stock point’s decision method simply does nothing for it.
A two-level system is not a class. The KSL book’s model gives a stock point one way to obtain stock: it asks an InventoryFillerIfc to fill an order. A supplier with a lead time is one kind of filler, and so is another stock point. Thus a storeroom supplied by a hub is a stock point whose filler is the hub, seen through a transit link that adds \(O_j\), and a storeroom that rebuilds some of its failures is a stock point whose filler sends each request one way or the other. The two-level examples of Section 12.8 are assembled from the same three classes as the single location of Example 12.2. Notice that this is the coupling Chapter 10 and Chapter 11 worked so hard to approximate: here it is simply the order of the calls.
G.10.3 The Classes
| Class | Knows | Does |
|---|---|---|
InventoryFillerIfc |
nothing | accepts a request for a quantity; the one thing a supplier must do |
SimInventory |
\(I\), \(\mathit{IO}\) and \(B\) as time-weighted responses, the backorder queue, the lost-sales flag, the cost rates | the demand and receipt events of Table 12.1; Equation 12.1, through TWResponse; the unit fill rate, lot fill rate and ready rate; the cost terms at the end of each replication; fills a lower location’s orders as an InventoryFillerIfc |
RQSimInventory |
\(r\) and \(Q\) | the decision of Table 12.1, ordering \(\lfloor (r - \mathit{IP})/Q \rfloor + 1\) batches |
SSSimInventory |
\(s\) and \(S\) | orders \(S - \mathit{IP}\), and records the undershoot of Equation 9.25 |
PeriodicSimInventory |
\(R\), \(s\) and \(S\) | schedules the review; counts reviews and orders separately, as Equation 9.5 requires; records the undershoot |
LeadTimeSupplier |
a lead time distribution, and whether orders queue | fills after \(L\), or at the later of \(t + L\) and the previous receipt; records crossings and the time each order is outstanding |
TransitLink |
a stock point and a transit time | makes a stock point a supplier, adding \(O_j\) after it ships, and records each request’s wait |
RoutingFiller |
several fillers and the probability of each | sends each request to one of them, as the storeroom’s own shop and the depot of Example 12.10 share its failures |
CustomerDemand |
a stock point, a time between demands, and a lot size distribution | generates the demands, each scheduling its successor, on its own random number streams |
ScriptedDemand |
a stock point and a list of demand times | replays a hand ledger one unit at a time, as Example 12.1 does |
Estimate |
an average, a half-width and a count | whether the interval covers a value |
SimulatedPerformance |
an Estimate for each measure |
compares itself with Chapter 8’s RQPerformance or Chapter 9’s RSPerformance, measure by measure |
Notice what is missing: a class for the two-level system, for the hub, or for the depot. A hub is SimInventory running \((r, Q)\) with a LeadTimeSupplier behind it and TransitLinks in front of it. The depot of Example 12.10 is the same thing running \((S_0 - 1, 1)\), since a one-for-one stock point replenished after a constant repair time behaves exactly as one replenished by a supplier with that lead time.
G.10.4 The Two Routes Must Agree
Recall from Section G.6.4 that two routes sharing one cost structure can be checked against each other. Here the exact route is the code of Chapter 8 to Chapter 11 and the simulated route is this package, and the check is the chapter’s thesis written as tests.
There is one test for every example that has an exact column, and each test asserts the agreement the example states. The ledger test of Example 12.1 asserts equality, row by row, since nothing in it is random. Every other test asserts that each interval covers the exact value: Table 12.5, Table 12.10, the costs and service measures of Table 12.7, the order rates and undershoots of the periodic examples, the four exact rows of Table 12.14, and Table 12.15. The tests run at a fixed seed, so a test that passes once passes every time.
One detail of the tests deserves stating, because a test written naively would fail a correct model. A test that checks eleven measures from the same runs, each at 95%, will find a miss among them about four times in ten, which is too often for a test that should fail only on a defect. Each test therefore builds its intervals at the Bonferroni level for the number of measures it checks, \(1 - 0.05/k\) for \(k\) measures, so that a correct model passes the whole family at 95%. The chapter prints ordinary 95% intervals, and Example 12.2 said what one miss among them does and does not mean.
The tests do not pin the simulated figures the chapter prints. Those figures are reported with their half-widths, at the seed and the KSL version stated with each run, and a later version of the library may move a printed digit within its half-width. What the tests guarantee is the thing that matters: that every interval still covers the exact value it was printed beside.