@mark1russell7/stack-endurance 0.8.9 → 0.8.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -48,6 +48,8 @@ With a base stack, a cut also stops each part that cannot work without the cut p
48
48
 
49
49
  With the option `horizon` of `h` days, the shortfall counts only the first `h` days of each cut: `E[max(0, min(D, h) - T)] * users`. A draw that holds `h` days has no shortfall. Thus a buy plan can aim at a target, for example 14 days and then 90 days.
50
50
 
51
+ The option `share` of `yearShortfall` sets the share of the stores in each case. The default `take` uses `enduranceOf`. With `best`, the query uses `bestEndurance`, and the horizon of the shortfall is the horizon of the share. Thus a draw at the horizon keeps back only `h` times its demand, and the lower levels get the rest.
52
+
51
53
  A draw that only the parts of `down` stop has no curve of its duration. The query puts it in `unread`, and its shortfall is not in the sum. A gate shows it as no read, not as a pass.
52
54
 
53
55
  A cut can have no `duration`, as before a source gives its curve. Then each draw whose stop the cut can be part of goes in `unread`. A draw whose minimal stop sets do not have the cut keeps its curves. When the query has no minimal sets, it cannot tell, so the draw goes in `unread`. The gate gives the warning `endurance-cut-no-curve` for each such cut.
@@ -136,6 +138,24 @@ const best = bestEndurance(layer, dry, { at: "2026-12-01" });
136
138
 
137
139
  The take order gives the water to `a` first, so `b` gets 0 days. The best share gives the juice to `a` and the water to `b`.
138
140
 
141
+ ### A horizon
142
+
143
+ With the option `horizon` of `h` days, each draw holds `h` days at most. A draw at the horizon keeps back only `h` times its demand. The rest of the stores goes to the lower levels.
144
+
145
+ - A draw at the horizon has `days: h` and `atHorizon: true`. It can hold more days.
146
+ - A draw with no end also gets `h` days.
147
+ - With no horizon, the result is the same as before the option.
148
+
149
+ An example: the stores have 10 L of water. The drink at the level `life` takes 1 L each day. The food at the level `health` is rice, cooked with 2 L of water for each pot.
150
+
151
+ ```ts
152
+ const best = bestEndurance(layer, dry, { at: "2026-12-01", horizon: 5 });
153
+ // best.needs.drink is { days: 5, binding: ["water"], takes: { water: 5 }, atHorizon: true }.
154
+ // best.needs.food.days is 2.5: the other 5 L cook 2.5 pots.
155
+ ```
156
+
157
+ With no horizon, the drink takes all the water for 10 days, and the food gets 0 days.
158
+
139
159
  ## The entries
140
160
 
141
161
  | Entry | What it has |
package/build/add-on.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { u as EnduranceLayer } from "./layer-BwbOgVFi.js";
1
+ import { u as EnduranceLayer } from "./layer-BdgJSBND.js";
2
2
  import { StackJoiner } from "@mark1russell7/system-stack";
3
3
  /**
4
4
  * This function gives the endurance add-on.
package/build/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as DirectUse, c as ENDURANCE_SCHEMA, d as Gift, f as IsoDate, g as Survival, h as Store, i as CutBound, l as Endurance, m as Resource, n as Converter, o as Draw, p as Prior, r as Cut, s as DrawEndurance, t as CaseCuts, u as EnduranceLayer } from "./layer-BwbOgVFi.js";
1
+ import { a as DirectUse, c as ENDURANCE_SCHEMA, d as Gift, f as IsoDate, g as Survival, h as Store, i as CutBound, l as Endurance, m as Resource, n as Converter, o as Draw, p as Prior, r as Cut, s as DrawEndurance, t as CaseCuts, u as EnduranceLayer } from "./layer-BdgJSBND.js";
2
2
  import { CutBound as CutBound$1, Fault, LayerParse, LayerPiece, PathOptions, Stack, curveFault, survivalAt } from "@mark1russell7/system-stack";
3
3
  /** The options of the queries of a case. */
4
4
  export interface CaseOptions {
@@ -122,6 +122,15 @@ export interface JointDays {
122
122
  * @throws {RangeError} A code of `needs` is not the need of a draw of the layer, or a date is not `YYYY-MM-DD`.
123
123
  */
124
124
  export declare function jointDays(layer: EnduranceLayer, caseCuts: CaseCuts, options: CaseOptions, needs: readonly string[]): JointDays;
125
+ /** The options of `bestEndurance`: the options of a case, and a horizon. */
126
+ export interface BestOptions extends CaseOptions {
127
+ /**
128
+ * The horizon in days, more than 0. The default is no horizon. A draw holds the horizon at most, thus it keeps back
129
+ * only the horizon times its demand. The rest of the stores goes to the lower levels. Use the target of a plan, for
130
+ * example 14 days, to ask if each draw holds the target.
131
+ */
132
+ readonly horizon?: number | undefined;
133
+ }
125
134
  /**
126
135
  * This function gives the days that each draw holds when a case stops its supply. The stores and the devices have their best share.
127
136
  * The result has the form of `enduranceOf`, so `caseShortfall` takes it.
@@ -142,17 +151,20 @@ export declare function jointDays(layer: EnduranceLayer, caseCuts: CaseCuts, opt
142
151
  * - At the end, a program takes the smallest sum of the shares of the stocks, each over its stock, then the fewest device-days.
143
152
  * These are the takes of the result. A resource in `binding` has no stock left at this point.
144
153
  * - A draw in `capped` used a device with no device-days left at the step that fixed it.
154
+ * - With a horizon, the floor of each step is the horizon at most. A step whose floor is the horizon fixes each of its
155
+ * open draws at the horizon, with `atHorizon`. Such a draw takes only the horizon times its demand. A draw with no
156
+ * end also holds the horizon. With no horizon, the result is the same as before the option.
145
157
  *
146
158
  * The programs use exact rationals, so the result has no error of the method. Only the change back to a number rounds.
147
159
  * The fewest days of the first level are the joint days (`jointDays`) of the draws of that level.
148
160
  *
149
161
  * @param layer - The endurance layer
150
162
  * @param caseCuts - The case
151
- * @param options - The date, and the stack or the parts that are also down
163
+ * @param options - The date, the stack or the parts that are also down, and the horizon
152
164
  * @returns The endurance of each draw whose supply stops
153
- * @throws {RangeError} A date is not `YYYY-MM-DD`.
165
+ * @throws {RangeError} A date is not `YYYY-MM-DD`, or the horizon is not more than 0.
154
166
  */
155
- export declare function bestEndurance(layer: EnduranceLayer, caseCuts: CaseCuts, options: CaseOptions): Endurance;
167
+ export declare function bestEndurance(layer: EnduranceLayer, caseCuts: CaseCuts, options: BestOptions): Endurance;
156
168
  /**
157
169
  * This function gives the expected days of a cut after a time, up to a horizon: `E[max(0, min(D, to) - from)]`.
158
170
  * It is the area under the curve from `from` to `to`. The curve is linear between its points, so the area is exact.
@@ -344,6 +356,22 @@ export interface Shortfall {
344
356
  * @throws RangeError when the horizon is not a number more than 0, or `maxSets` is not a whole number from 1
345
357
  */
346
358
  export declare function caseShortfall(layer: EnduranceLayer, caseCuts: CaseCuts, endurance: Endurance, options?: ShortfallOptions): Shortfall;
359
+ /**
360
+ * The share of the stores in a case. `take` is the take order of `enduranceOf`. `best` is the leximin share of
361
+ * `bestEndurance`, level by level.
362
+ */
363
+ export type Share = "take" | "best";
364
+ /** The shares, with the default first. */
365
+ export declare const SHARES: readonly Share[];
366
+ /** The options of `yearShortfall`: the date, the stack or the parts that are also down, the horizon and the share. */
367
+ export interface YearShortfallOptions extends CaseOptions, ShortfallOptions {
368
+ /**
369
+ * The share of the stores in each case. The default `take` gives the endurance from `enduranceOf`. With `best`,
370
+ * the endurance comes from `bestEndurance`, and the horizon of the shortfall is the horizon of the share. Thus a
371
+ * draw at the horizon keeps back only the horizon times its demand, and the lower levels get the rest.
372
+ */
373
+ readonly share?: Share | undefined;
374
+ }
347
375
  /** The shortfall of one year at one place, with the part of each case. */
348
376
  export interface YearShortfall extends Shortfall {
349
377
  readonly place: string;
@@ -366,10 +394,12 @@ export interface YearShortfall extends Shortfall {
366
394
  *
367
395
  * @param layer - The endurance layer, with its cases and priors
368
396
  * @param place - The place of the priors
369
- * @param options - The date, the stack or the parts that are also down, and the horizon
370
- * @throws RangeError for a bad date, horizon or `maxSets`: refer to `caseShortfall` and `enduranceOf`
397
+ * - With `share: "best"`, the endurance of each case comes from `bestEndurance` with the horizon of the shortfall.
398
+ *
399
+ * @param options - The date, the stack or the parts that are also down, the horizon and the share
400
+ * @throws RangeError for a bad date, horizon, `maxSets` or share: refer to `caseShortfall` and `enduranceOf`
371
401
  */
372
- export declare function yearShortfall(layer: EnduranceLayer, place: string, options: CaseOptions & ShortfallOptions): YearShortfall;
402
+ export declare function yearShortfall(layer: EnduranceLayer, place: string, options: YearShortfallOptions): YearShortfall;
373
403
  /**
374
404
  * These are the codes of the gate. Each code is an error, except `endurance-device-mix`, `endurance-no-way` and `endurance-cut-no-curve`, which are warnings.
375
405
  *
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":["CutBound"],"sources":["../src/endurance.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A6BG,gBAAgB,iBAAiB,YAAY,kDAAkD,mBAAyC;;;;;iBAiKvI;WACN,OAAO;;WAEP,aAAa;WACb,OAAO;;;;;WAKP;;WAEA;;;;;;WAMA,OAAOA;;;;;;;;;;;;;;;;wBAmEF,WAAW,UAAU,UAAU,MAAM,MAAM,UAAS,mBAAwB;;iBAM3E;;;;;WAKN,QAAQ,SAAS;;WAEjB,aAAa,SAAS;;WAEtB,OAAO,SAAS;;;;;WAKhB;;WAEA;;WAEA;;;;;;;;;WASA,OAAOA;;;;;;;;;;;;wBAiBF,cAAc,OAAO,gBAAgB,UAAU,UAAU,WAAW,WAAW,UAAS,mBAAwB;;iBA8B/G,sBAAsB;WAC5B;;WAEA;aAA2B;aAAuB;aAAuB,WAAW;aAAoB,WAAW;;;;;;;;;;;;;;;;;wBAiB9G,cAAc,OAAO,gBAAgB,eAAe,SAAS,cAAc,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;qBCrjBjG;;YAmCD,wBAAwB;;iBAGnB,uBAAuB;WAC7B,MAAM;;;;;;;;;;;wBAcD,eAAe,OAAO,gBAAgB,QAAQ,QAAQ;;wBAiJtD,kBAAkB,iBAAiB;;;;;;;;;;;;;;;;;wBC7MnC,cAAc,iBAAiB,WAAW,oBAAoB,WAAW;;qBCf5E,wBAAwB;;;;;;;;;qBAkBxB,kBAAkB"}
1
+ {"version":3,"file":"index.d.ts","names":["CutBound"],"sources":["../src/endurance.ts","../src/joint.ts","../src/best.ts","../src/shortfall.ts","../src/check.ts","../src/join.ts","../src/sample.ts"],"mappings":";;;iBAUiB;;WAEN,IAAI;;WAEJ,QAAQ;;WAER;;;;;;wBAOK,YAAY,UAAU,UAAU,SAAS,KAAK,iCAAiC;;;;;;;wBAoB/E,aAAa,OAAO,gBAAgB,IAAI,SAAS,eAAc,sBAAkC;;wBAYjG,WAAW,MAAM,MAAM,UAAU;;;;;wBAQjC,UAAU,OAAO,gBAAgB,UAAU,UAAU,cAAc,sBAAsB;;wBAWzF,SAAS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;;;;;;;WASA,OAAOA;;;;;;;;;;;;wBAiBF,cAAc,OAAO,gBAAgB,UAAU,UAAU,WAAW,WAAW,UAAS,mBAAwB;;;;;YAiCpH;;qBAGC,iBAAiB;;iBAGb,6BAA6B,aAAa;;;;;;WAMhD,QAAQ;;;iBAIF,sBAAsB;WAC5B;;WAEA;aAA2B;aAAuB;aAAuB,WAAW;aAAoB,WAAW;;;;;;;;;;;;;;;;;;;wBAmB9G,cAAc,OAAO,gBAAgB,eAAe,SAAS,uBAAuB;;;;;;;;;;;;;;;;;;;;;;;qBC3kBvF;;YAmCD,wBAAwB;;iBAGnB,uBAAuB;WAC7B,MAAM;;;;;;;;;;;wBAcD,eAAe,OAAO,gBAAgB,QAAQ,QAAQ;;wBAiJtD,kBAAkB,iBAAiB;;;;;;;;;;;;;;;;;wBC7MnC,cAAc,iBAAiB,WAAW,oBAAoB,WAAW;;qBCf5E,wBAAwB;;;;;;;;;qBAkBxB,kBAAkB"}
package/build/index.js CHANGED
@@ -131,6 +131,12 @@ function jointDays(layer, caseCuts, options, needs) {
131
131
  };
132
132
  }
133
133
  // src/best.ts
134
+ /** This function gives the horizon as a rational, or undefined for no horizon. It throws a `RangeError` for a horizon that is not more than 0. */
135
+ function horizonOf$1(horizon) {
136
+ if (horizon === void 0 || horizon === 1e400) return void 0;
137
+ if (!(horizon > 0) || !Number.isFinite(horizon)) throw new RangeError(`The horizon ${String(horizon)} is not a number of days more than 0.`);
138
+ return exact(horizon);
139
+ }
134
140
  /**
135
141
  * This function gives the days that each draw holds when a case stops its supply. The stores and the devices have their best share.
136
142
  * The result has the form of `enduranceOf`, so `caseShortfall` takes it.
@@ -151,17 +157,21 @@ function jointDays(layer, caseCuts, options, needs) {
151
157
  * - At the end, a program takes the smallest sum of the shares of the stocks, each over its stock, then the fewest device-days.
152
158
  * These are the takes of the result. A resource in `binding` has no stock left at this point.
153
159
  * - A draw in `capped` used a device with no device-days left at the step that fixed it.
160
+ * - With a horizon, the floor of each step is the horizon at most. A step whose floor is the horizon fixes each of its
161
+ * open draws at the horizon, with `atHorizon`. Such a draw takes only the horizon times its demand. A draw with no
162
+ * end also holds the horizon. With no horizon, the result is the same as before the option.
154
163
  *
155
164
  * The programs use exact rationals, so the result has no error of the method. Only the change back to a number rounds.
156
165
  * The fewest days of the first level are the joint days (`jointDays`) of the draws of that level.
157
166
  *
158
167
  * @param layer - The endurance layer
159
168
  * @param caseCuts - The case
160
- * @param options - The date, and the stack or the parts that are also down
169
+ * @param options - The date, the stack or the parts that are also down, and the horizon
161
170
  * @returns The endurance of each draw whose supply stops
162
- * @throws {RangeError} A date is not `YYYY-MM-DD`.
171
+ * @throws {RangeError} A date is not `YYYY-MM-DD`, or the horizon is not more than 0.
163
172
  */
164
173
  function bestEndurance(layer, caseCuts, options) {
174
+ const horizon = horizonOf$1(options.horizon);
165
175
  const stoppedParts = caseStopped(caseCuts, options);
166
176
  const stock = storeAmounts(layer, options.at, stoppedParts);
167
177
  const draws = caseDraws(layer, caseCuts, stoppedParts);
@@ -171,7 +181,7 @@ function bestEndurance(layer, caseCuts, options) {
171
181
  for (const level of levelGroups(layer, draws)) {
172
182
  let open = level;
173
183
  while (open.length > 0) {
174
- const step = buildStep(parts, caseCuts, draws, fixed, open, devices, "span");
184
+ const step = buildStep(parts, caseCuts, draws, fixed, open, devices, "span", horizon);
175
185
  const solved = solveLexicographic(step.program.constraints(), [{
176
186
  sense: "max",
177
187
  coefficients: dense(/* @__PURE__ */ new Map([[step.floor, ONE]]), step.program.count)
@@ -187,7 +197,8 @@ function bestEndurance(layer, caseCuts, options) {
187
197
  const floor = solved.values[0] ?? ZERO;
188
198
  const first = solved.stages[0]?.result;
189
199
  const dual = first?.status === "optimal" ? first.dual : [];
190
- let done = open.filter((draw) => sign(dual[step.floors.get(draw.need)] ?? ZERO) !== 0);
200
+ const atHorizon = horizon !== void 0 && equals(floor, horizon);
201
+ let done = atHorizon ? open : open.filter((draw) => sign(dual[step.floors.get(draw.need)] ?? ZERO) !== 0);
191
202
  if (done.length === 0) done = open;
192
203
  const full = new Set([...step.shared].filter(([, limit]) => equals(valueAt(limit.row, solved.x), mul(limit.room, floor))).map(([key]) => key));
193
204
  for (const draw of done) {
@@ -200,7 +211,8 @@ function bestEndurance(layer, caseCuts, options) {
200
211
  span: floor,
201
212
  endless: false,
202
213
  keep,
203
- capped
214
+ capped,
215
+ atHorizon
204
216
  });
205
217
  }
206
218
  const fixedNow = new Set(done.map((draw) => draw.need));
@@ -247,16 +259,12 @@ function bestEndurance(layer, caseCuts, options) {
247
259
  }, ZERO);
248
260
  return equals(taken, exact(stock.get(resource) ?? 0));
249
261
  }).sort();
250
- const days = toNumber(fix.span);
251
- needs[need] = fix.capped.length === 0 ? {
252
- days,
253
- binding,
254
- takes
255
- } : {
256
- days,
262
+ needs[need] = {
263
+ days: toNumber(fix.span),
257
264
  binding,
258
265
  takes,
259
- capped: fix.capped
266
+ ...fix.capped.length === 0 ? {} : { capped: fix.capped },
267
+ ...fix.atHorizon ? { atHorizon: true } : {}
260
268
  };
261
269
  }
262
270
  return {
@@ -286,10 +294,12 @@ function levelGroups(layer, draws) {
286
294
  * - With `"span"`, each open draw has a column of its days, not less than the floor. Its runs share the device-days that the fixed draws leave, for the floor.
287
295
  * The device-days of each day are the runs over the span. A span not less than the floor uses fewer of them, so this is the safe side.
288
296
  * - With `"day"`, each open draw has a span of one day and takes no stock. Its runs share the device-days of one day.
297
+ * - With a horizon, the floor is the horizon at most.
289
298
  */
290
- function buildStep(parts, caseCuts, draws, fixed, open, devices, mode) {
299
+ function buildStep(parts, caseCuts, draws, fixed, open, devices, mode, horizon) {
291
300
  const program = new Program();
292
301
  const floor = program.next();
302
+ if (horizon !== void 0) program.push(/* @__PURE__ */ new Map([[floor, ONE]]), "<=", horizon);
293
303
  const opened = new Set(open.map((draw) => draw.need));
294
304
  const blocks = [];
295
305
  const floors = /* @__PURE__ */ new Map();
@@ -376,7 +386,8 @@ function fixEndless(parts, caseCuts, draws, fixed, open, devices) {
376
386
  span: ONE,
377
387
  endless: true,
378
388
  keep,
379
- capped: []
389
+ capped: [],
390
+ atHorizon: false
380
391
  });
381
392
  }
382
393
  }
@@ -882,6 +893,8 @@ function caseShortfall(layer, caseCuts, endurance, options = {}) {
882
893
  bound: weakestBound(bounds)
883
894
  };
884
895
  }
896
+ /** The shares, with the default first. */
897
+ const SHARES = ["take", "best"];
885
898
  /**
886
899
  * This function gives the shortfall of one year at one place.
887
900
  * It is the sum over the cases of the layer of the expected count of the events of each case times its shortfall.
@@ -893,12 +906,16 @@ function caseShortfall(layer, caseCuts, endurance, options = {}) {
893
906
  *
894
907
  * @param layer - The endurance layer, with its cases and priors
895
908
  * @param place - The place of the priors
896
- * @param options - The date, the stack or the parts that are also down, and the horizon
897
- * @throws RangeError for a bad date, horizon or `maxSets`: refer to `caseShortfall` and `enduranceOf`
909
+ * - With `share: "best"`, the endurance of each case comes from `bestEndurance` with the horizon of the shortfall.
910
+ *
911
+ * @param options - The date, the stack or the parts that are also down, the horizon and the share
912
+ * @throws RangeError for a bad date, horizon, `maxSets` or share: refer to `caseShortfall` and `enduranceOf`
898
913
  */
899
914
  function yearShortfall(layer, place, options) {
900
915
  horizonOf(options);
901
916
  budgetsOf(options);
917
+ const share = options.share ?? "take";
918
+ if (!SHARES.includes(share)) throw new RangeError(`The share ${String(options.share)} is not ${SHARES.join(" or ")}.`);
902
919
  const levels = zeroLevels(layer);
903
920
  const independent = zeroLevels(layer);
904
921
  const upper = zeroLevels(layer);
@@ -911,7 +928,7 @@ function yearShortfall(layer, place, options) {
911
928
  const prior = (layer.priors ?? []).find((item) => item.case === caseCuts.case && item.place === place);
912
929
  if (prior === void 0) continue;
913
930
  const rate = yearRate(prior);
914
- const endurance = enduranceOf(layer, caseCuts, options);
931
+ const endurance = share === "best" ? bestEndurance(layer, caseCuts, options) : enduranceOf(layer, caseCuts, options);
915
932
  const shortfall = caseShortfall(layer, caseCuts, endurance, options);
916
933
  for (const [level, days] of Object.entries(shortfall.levels)) levels[level] = (levels[level] ?? 0) + rate * days;
917
934
  for (const [level, days] of Object.entries(shortfall.independent)) independent[level] = (independent[level] ?? 0) + rate * days;
@@ -1163,6 +1180,6 @@ const SAMPLE_ENDURANCE = {
1163
1180
  asOf: "2025-12-01"
1164
1181
  }]
1165
1182
  };
1166
- export { ENDURANCE_CODES, ENDURANCE_SCHEMA, INDEPENDENT_MAX_WORK, INDEPENDENT_TOLERANCE, MINIMAL_STOP_CUTS, SAMPLE_ENDURANCE, SAMPLE_ENDURANCE_STACK, bestEndurance, caseDraws, caseShortfall, caseStopped, checkEndurance, curveFault, drawDemand, enduranceOf, eventStop, giftNeed, giftResource, hasEnduranceError, independentStop, joinEndurance, jointDays, longestStop, minimalStops, stopCurves, storeAmounts, survivalAt, survivalQuantile, tailDays, upperStop, yearChance, yearRate, yearShortfall };
1183
+ export { ENDURANCE_CODES, ENDURANCE_SCHEMA, INDEPENDENT_MAX_WORK, INDEPENDENT_TOLERANCE, MINIMAL_STOP_CUTS, SAMPLE_ENDURANCE, SAMPLE_ENDURANCE_STACK, SHARES, bestEndurance, caseDraws, caseShortfall, caseStopped, checkEndurance, curveFault, drawDemand, enduranceOf, eventStop, giftNeed, giftResource, hasEnduranceError, independentStop, joinEndurance, jointDays, longestStop, minimalStops, stopCurves, storeAmounts, survivalAt, survivalQuantile, tailDays, upperStop, yearChance, yearRate, yearShortfall };
1167
1184
 
1168
1185
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/joint.ts","../src/best.ts","../src/stops.ts","../src/shortfall.ts","../src/sample.ts"],"sourcesContent":["import { type Objective, solveLexicographic } from \"@mark1russell7/linear\";\nimport { add, div, equals, mul, neg, ONE, type Rational, sign, toNumber, ZERO } from \"@mark1russell7/rational\";\nimport { type CaseOptions, caseDraws, caseStopped, drawDemand, storeAmounts } from \"./endurance.ts\";\nimport type { CaseCuts, Converter, EnduranceLayer, IsoDate } from \"./layer.ts\";\nimport { caseParts, deviceUse, drawBlock, fewestRow, Program, reachOf, valueAt } from \"./program.ts\";\nimport { addTo, dense, exact, type Row } from \"./rows.ts\";\n\n// The joint days: the largest count of days that a set of draws holds together, with the best share of the stores.\n// The query is a linear program over the totals of the span, with exact rationals (@mark1russell7/linear).\n\n/** The joint days of a set of draws in a case, with the share of the stores at the optimum. */\nexport interface JointDays {\n readonly case: string;\n readonly at: IsoDate;\n /**\n * The largest count of days that each draw of `plan` holds at the same time. It is `Infinity` when `plan` is empty,\n * or when the stores give each draw of `plan` without end.\n */\n readonly days: number;\n /** The needs of the set that take from the stores: the case stops their supply, and their demand is more than 0. The order is the order of `caseDraws`. */\n readonly plan: readonly string[];\n /** The needs of the set that take nothing from the stores, in the order of their codes. The case does not stop their supply, or their demand is 0. */\n readonly holds: readonly string[];\n /**\n * The amount of each resource that each draw of `plan` takes from the stores in `days`. The keys are the code of the need, then the code of the resource.\n * A take through a converter that makes a resource counts the inputs of the converter. A resource with no take is not in the record.\n * The record is empty when `days` is `Infinity`.\n */\n readonly takes: Readonly<Record<string, Readonly<Record<string, number>>>>;\n /**\n * The resources that limit `days`, in the order of their codes. Each one has a store in the layer, is an input of `plan` through each chain,\n * and has no stock left at the optimum. The list is empty when `days` is `Infinity`.\n */\n readonly binding: readonly string[];\n /** The count of runs of each converter at the optimum, by the `id` of the converter. A converter with no run is not in the record. */\n readonly runs: Readonly<Record<string, number>>;\n /**\n * The converters of the plan whose limit `perDay` stops more runs at the optimum, in the order of their `id`. A converter of the plan\n * gives a need of the plan, or makes an input of the plan through each chain.\n * The list is empty when `days` is `Infinity` or 0. Else it has each converter of the plan with a limit of 0.\n */\n readonly capped: readonly string[];\n}\n\n/**\n * This function gives the joint days of a set of draws. These are the largest count of days `d` at which each draw holds `d` days.\n * The draws hold at the same time, with the best share of the stores and of the runs of the converters.\n *\n * - The function solves a linear program over the totals of the span. Its variables are `d`, the take of each direct use,\n * the runs of each converter, and the share of each stock.\n * - Each draw of the plan gets `d` times its demand (`drawDemand`) from its direct uses and from the converters that give its need.\n * - The takes of each resource are not more than its stock (`storeAmounts` at `at`) plus the gifts of the converters that make it.\n * - A converter whose device stops gives nothing, and a store whose part stops gives nothing, as in `enduranceOf`.\n * - The runs of a converter with a limit `perDay` are not more than `perDay` times `devices` times `d`. The converters of one device share it, as in `enduranceOf`.\n * - A store counts with all of its amount when its due date is after `at`, as in `enduranceOf`. A due date in the span has no effect.\n * - After the largest `d`, a second objective takes the smallest sum of the shares of the stocks. Thus the takes have no waste.\n * - A third objective takes the fewest device-days of the converters. Thus the runs are not more than the plan uses.\n * - The draws that are not in the set are outside this plan. They take nothing in the program.\n * - A need of the set whose supply works, or whose demand is 0, holds without end. It goes in `holds`, as `enduranceOf` leaves it out.\n *\n * The take order of `enduranceOf` gives the stores to a higher draw first. This function gives one share for the whole set.\n * Thus a draw of the set can get fewer days here than alone, and a lower draw can get more.\n *\n * The program uses exact rationals, so the result has no error of the method. Only the change back to a number rounds.\n *\n * @param layer - The endurance layer\n * @param caseCuts - The case\n * @param options - The date, and the stack or the parts that are also down\n * @param needs - The codes of the needs of the draws of the set\n * @returns The joint days, the takes of each draw, the binding resources and the runs of each converter\n * @throws {RangeError} A code of `needs` is not the need of a draw of the layer, or a date is not `YYYY-MM-DD`.\n */\nexport function jointDays(layer: EnduranceLayer, caseCuts: CaseCuts, options: CaseOptions, needs: readonly string[]): JointDays {\n const known = new Set(layer.draws.map((draw) => draw.need));\n const unknown = needs.filter((need) => !known.has(need));\n if (unknown.length > 0) throw new RangeError(`The needs ${unknown.map((need) => `\"${need}\"`).join(\", \")} are not the needs of draws of the layer.`);\n const stoppedParts = caseStopped(caseCuts, options);\n const stock = storeAmounts(layer, options.at, stoppedParts);\n const wanted = new Set(needs);\n const plan = caseDraws(layer, caseCuts, stoppedParts).filter((draw) => wanted.has(draw.need));\n const planned = new Set(plan.map((draw) => draw.need));\n const base = { case: caseCuts.case, at: options.at, plan: plan.map((draw) => draw.need), holds: [...wanted].filter((need) => !planned.has(need)).sort() };\n const endless: JointDays = { ...base, days: Infinity, takes: {}, binding: [], runs: {}, capped: [] };\n if (plan.length === 0) return endless;\n\n const parts = caseParts(layer, stoppedParts, stock, planned);\n const program = new Program();\n const days = program.next();\n const blocks = plan.map((draw) => {\n const block = drawBlock(program, parts, draw);\n // The need of the draw: its gifts are not less than its demand times the days.\n const need: Row = new Map(block.gifts);\n addTo(need, days, neg(exact(drawDemand(draw, caseCuts))));\n program.push(need, \">=\", ZERO);\n return block;\n });\n // The limit of each device: the runs use `devices` times `d` device-days or less. A limit of 0 stops the converter.\n const runCols = blocks.flatMap((block) => [...block.runs]);\n const { limits, stopped } = deviceUse(runCols);\n for (const index of stopped) program.push(new Map([[index, ONE]]), \"<=\", ZERO);\n for (const limit of limits.values()) {\n const row: Row = new Map(limit.row);\n addTo(row, days, neg(exact(limit.devices)));\n program.push(row, \"<=\", ZERO);\n }\n // The shares of each stock are not more than the stock.\n for (const resource of parts.stocked) {\n const row: Row = new Map();\n for (const block of blocks) addTo(row, block.shares.get(resource) as number, ONE);\n program.push(row, \"<=\", exact(stock.get(resource) ?? 0));\n }\n\n const most: Row = new Map([[days, ONE]]);\n const least: Row = new Map();\n for (const block of blocks) for (const [resource, index] of block.shares) addTo(least, index, div(ONE, exact(stock.get(resource) ?? 1)));\n // The third objective takes the fewest device-days. Thus a converter whose inputs cost no stock does not give more runs than the plan uses,\n // and `runs` and `capped` have one value.\n const objectives: Objective[] = [\n { sense: \"max\", coefficients: dense(most, program.count) },\n { sense: \"min\", coefficients: dense(least, program.count) },\n { sense: \"min\", coefficients: dense(fewestRow(runCols), program.count) },\n ];\n const solved = solveLexicographic(program.constraints(), objectives);\n // The point 0 is feasible and the later objectives are not less than 0. So only an unbounded first stage has no optimum.\n if (solved.status !== \"optimal\") return endless;\n\n const x = solved.x;\n const takes: Record<string, Record<string, number>> = {};\n for (const block of blocks) {\n const record: Record<string, number> = {};\n for (const [resource, index] of block.shares) if (sign(x[index] ?? ZERO) > 0) record[resource] = toNumber(x[index] ?? ZERO);\n takes[block.draw.need] = record;\n }\n // A converter gives a need or a resource, so it is a cook or a maker, not the two.\n const total = new Map<Converter, Rational>();\n for (const [converter, index] of runCols) total.set(converter, add(total.get(converter) ?? ZERO, x[index] ?? ZERO));\n const runs: Record<string, number> = {};\n for (const [converter, value] of total) if (sign(value) > 0) runs[converter.id] = toNumber(value);\n\n const withStore = new Set(layer.stores.map((store) => store.resource));\n // The converters that the plan can use: the converters that give a need of the plan, and the makers of the resources of the closure.\n const { closure, reach } = reachOf(parts, planned);\n const binding = [...closure]\n .filter((resource) => withStore.has(resource))\n .filter((resource) => {\n // A resource with no live stock has no share, so its take is 0 and it is used up.\n const taken = blocks.reduce((sum, block) => {\n const index = block.shares.get(resource);\n return index === undefined ? sum : add(sum, x[index] ?? ZERO);\n }, ZERO);\n return equals(taken, exact(stock.get(resource) ?? 0));\n })\n .sort();\n const best = solved.values[0] ?? ZERO;\n const capped = sign(best) > 0\n ? [\n ...[...total.keys()].filter((converter) => converter.perDay !== undefined && !(converter.perDay > 0)),\n ...[...limits.values()].filter((limit) => equals(valueAt(limit.row, x), mul(exact(limit.devices), best))).flatMap((limit) => limit.converters),\n ]\n .filter((converter) => reach.has(converter))\n .map((converter) => converter.id)\n .sort()\n : [];\n return { ...base, days: toNumber(best), takes, binding, runs, capped };\n}\n","import { type Objective, solveLexicographic } from \"@mark1russell7/linear\";\nimport { add, div, equals, mul, neg, ONE, type Rational, sign, sub, toNumber, ZERO } from \"@mark1russell7/rational\";\nimport { type CaseOptions, caseDraws, caseStopped, drawDemand, storeAmounts } from \"./endurance.ts\";\nimport type { CaseCuts, Converter, Draw, DrawEndurance, Endurance, EnduranceLayer } from \"./layer.ts\";\nimport { type CaseParts, caseParts, deviceUse, drawBlock, type DrawBlock, fewestRow, Program, reachOf, valueAt } from \"./program.ts\";\nimport { addTo, dense, exact, type Row } from \"./rows.ts\";\n\n// The best endurance: the days of each draw with the best share of the stores, the most important level first.\n// Each step is a linear program over the totals of the spans, with exact rationals (@mark1russell7/linear).\n\n/** A draw whose days are fixed. */\ninterface Fixed {\n /** The span of the draw in the programs: its days, or 1 for a draw with no end. */\n readonly span: Rational;\n /** True for a draw that holds without end. It takes no stock, and its span is one day. */\n readonly endless: boolean;\n /** The device-days of each day that the draw keeps, by the key of the device. */\n readonly keep: ReadonlyMap<string, Rational>;\n /** The `id` of each converter whose limit stops more runs at the step that fixes the draw. */\n readonly capped: readonly string[];\n}\n\n/** A program of one step, with the indexes of its parts. */\ninterface Step {\n readonly program: Program;\n readonly blocks: readonly DrawBlock[];\n /** The column of the common days of the open draws. */\n readonly floor: number;\n /** The row `days - floor >= 0` of each open draw, by the code of its need. */\n readonly floors: ReadonlyMap<string, number>;\n /** The run columns of the open draws. */\n readonly openRuns: readonly (readonly [Converter, number])[];\n /** The device-days of the open draws for each device, with the device-days of each day that the fixed draws leave. */\n readonly shared: ReadonlyMap<string, { readonly row: Row; readonly room: Rational; readonly converters: readonly Converter[] }>;\n}\n\n/**\n * This function gives the days that each draw holds when a case stops its supply. The stores and the devices have their best share.\n * The result has the form of `enduranceOf`, so `caseShortfall` takes it.\n *\n * The share is lexicographic. The draws of the first level get their best days, then the draws of the next level get theirs, and so on.\n * In one level, the share is the best for the draw with the fewest days, then for the next draw, and so on (the leximin share).\n * Thus a draw of a level cannot take a store that another draw of the level needs more.\n *\n * - The function solves a sequence of linear programs over the totals of the spans. Each program has the days of the open draws\n * and their common floor. For each draw, it has the take of each direct use, the runs of each converter and the share of each stock.\n * - Each step takes the largest floor. A draw whose floor row has a dual value that is not 0 cannot get more days. The step fixes its days.\n * The dual values of the floor rows add to 1, so each step fixes one draw or more.\n * - A fixed draw keeps its days in each later step. Its share of the stocks can change, so a later draw can get a store that it does not need.\n * - The stores, the direct uses, the converters and the devices follow the rules of `jointDays`. A store counts with all of its amount when its due date is after `at`.\n * - A fixed draw keeps the device-days of each day that it uses at its step, for all the days of the later draws. This is the safe side, as in `enduranceOf`.\n * The exact share of a device between two spans is not a linear program: the device-days of a day are the runs over the span.\n * - A step with no largest floor gives the open draws no end. Each of them takes no stock, and keeps the fewest device-days of each day.\n * - At the end, a program takes the smallest sum of the shares of the stocks, each over its stock, then the fewest device-days.\n * These are the takes of the result. A resource in `binding` has no stock left at this point.\n * - A draw in `capped` used a device with no device-days left at the step that fixed it.\n *\n * The programs use exact rationals, so the result has no error of the method. Only the change back to a number rounds.\n * The fewest days of the first level are the joint days (`jointDays`) of the draws of that level.\n *\n * @param layer - The endurance layer\n * @param caseCuts - The case\n * @param options - The date, and the stack or the parts that are also down\n * @returns The endurance of each draw whose supply stops\n * @throws {RangeError} A date is not `YYYY-MM-DD`.\n */\nexport function bestEndurance(layer: EnduranceLayer, caseCuts: CaseCuts, options: CaseOptions): Endurance {\n const stoppedParts = caseStopped(caseCuts, options);\n const stock = storeAmounts(layer, options.at, stoppedParts);\n const draws = caseDraws(layer, caseCuts, stoppedParts);\n const parts = caseParts(layer, stoppedParts, stock, new Set(draws.map((draw) => draw.need)));\n // The count of devices of each key. The gate refuses two counts for one device.\n const devices = new Map([...deviceUse([...parts.cooks, ...parts.makers].map((converter) => [converter, 0] as const)).limits].map(([key, limit]) => [key, limit.devices] as const));\n const fixed = new Map<string, Fixed>();\n\n for (const level of levelGroups(layer, draws)) {\n let open = level;\n while (open.length > 0) {\n const step = buildStep(parts, caseCuts, draws, fixed, open, devices, \"span\");\n const solved = solveLexicographic(step.program.constraints(), [\n { sense: \"max\", coefficients: dense(new Map([[step.floor, ONE]]), step.program.count) },\n { sense: \"min\", coefficients: dense(fewestRow(step.openRuns), step.program.count) },\n ]);\n if (solved.status !== \"optimal\") {\n if (solved.status === \"infeasible\") throw new Error(\"The step of the best endurance has no point. The point of the last step is a point of it.\");\n fixEndless(parts, caseCuts, draws, fixed, open, devices);\n break;\n }\n const floor = solved.values[0] ?? ZERO;\n const first = solved.stages[0]?.result;\n const dual = first?.status === \"optimal\" ? first.dual : [];\n let done = open.filter((draw) => sign(dual[step.floors.get(draw.need) as number] ?? ZERO) !== 0);\n // The dual values of the floor rows add to 1. Thus `done` is not empty. The fallback fixes each open draw at the floor.\n if (done.length === 0) done = open;\n const full = new Set([...step.shared].filter(([, limit]) => equals(valueAt(limit.row, solved.x), mul(limit.room, floor))).map(([key]) => key));\n for (const draw of done) {\n const block = step.blocks.find((item) => item.draw.need === draw.need) as DrawBlock;\n const keep = new Map<string, Rational>();\n for (const [key, limit] of deviceUse(block.runs).limits) keep.set(key, sign(floor) > 0 ? div(valueAt(limit.row, solved.x), floor) : ZERO);\n const { reach } = reachOf(parts, new Set([draw.need]));\n const capped = sign(floor) > 0\n ? [...reach]\n .filter((converter) => converter.perDay !== undefined && (!(converter.perDay > 0) || [...full].some((key) => step.shared.get(key)?.converters.includes(converter))))\n .map((converter) => converter.id)\n .sort()\n : [];\n fixed.set(draw.need, { span: floor, endless: false, keep, capped });\n }\n const fixedNow = new Set(done.map((draw) => draw.need));\n open = open.filter((draw) => !fixedNow.has(draw.need));\n }\n }\n\n const needs: Record<string, DrawEndurance> = {};\n if (draws.length === 0) return { case: caseCuts.case, at: options.at, needs };\n const last = buildStep(parts, caseCuts, draws, fixed, [], devices, \"span\");\n const least: Row = new Map();\n for (const block of last.blocks) for (const [resource, index] of block.shares) addTo(least, index, div(ONE, exact(stock.get(resource) ?? 1)));\n const objectives: Objective[] = [\n { sense: \"min\", coefficients: dense(least, last.program.count) },\n { sense: \"min\", coefficients: dense(fewestRow(last.blocks.flatMap((block) => [...block.runs])), last.program.count) },\n ];\n const solved = solveLexicographic(last.program.constraints(), objectives);\n if (solved.status !== \"optimal\") throw new Error(\"The last program of the best endurance has no optimum. The point of the last step is a point of it.\");\n const withStore = new Set(layer.stores.map((store) => store.resource));\n for (const block of last.blocks) {\n const need = block.draw.need;\n const fix = fixed.get(need) as Fixed;\n if (fix.endless) {\n needs[need] = { days: Infinity, binding: [], takes: {} };\n continue;\n }\n const takes: Record<string, number> = {};\n for (const [resource, index] of block.shares) if (sign(solved.x[index] ?? ZERO) > 0) takes[resource] = toNumber(solved.x[index] ?? ZERO);\n const { closure } = reachOf(parts, new Set([need]));\n const binding = [...closure]\n .filter((resource) => withStore.has(resource))\n .filter((resource) => {\n // A resource with no live stock has no share, so its take is 0 and it is used up.\n const taken = last.blocks.reduce((sum, item) => {\n const index = item.shares.get(resource);\n return index === undefined ? sum : add(sum, solved.x[index] ?? ZERO);\n }, ZERO);\n return equals(taken, exact(stock.get(resource) ?? 0));\n })\n .sort();\n const days = toNumber(fix.span);\n needs[need] = fix.capped.length === 0 ? { days, binding, takes } : { days, binding, takes, capped: fix.capped };\n }\n return { case: caseCuts.case, at: options.at, needs };\n}\n\n/** This function gives the draws of each level, in the order of `levels`. The draws of a level that is not in `levels` come last, together. */\nfunction levelGroups(layer: EnduranceLayer, draws: readonly Draw[]): Draw[][] {\n const rank = (draw: Draw): number => {\n const index = layer.levels.indexOf(draw.level);\n return index < 0 ? layer.levels.length : index;\n };\n const out: Draw[][] = [];\n let previous = -1;\n for (const draw of draws) {\n if (rank(draw) !== previous) out.push([]);\n previous = rank(draw);\n out[out.length - 1]?.push(draw);\n }\n return out;\n}\n\n/**\n * This function gives the program of one step. The fixed draws keep their spans and their device-days. The open draws have a common floor.\n *\n * - With `\"span\"`, each open draw has a column of its days, not less than the floor. Its runs share the device-days that the fixed draws leave, for the floor.\n * The device-days of each day are the runs over the span. A span not less than the floor uses fewer of them, so this is the safe side.\n * - With `\"day\"`, each open draw has a span of one day and takes no stock. Its runs share the device-days of one day.\n */\nfunction buildStep(\n parts: CaseParts,\n caseCuts: CaseCuts,\n draws: readonly Draw[],\n fixed: ReadonlyMap<string, Fixed>,\n open: readonly Draw[],\n devices: ReadonlyMap<string, number>,\n mode: \"span\" | \"day\",\n): Step {\n const program = new Program();\n const floor = program.next();\n const opened = new Set(open.map((draw) => draw.need));\n const blocks: DrawBlock[] = [];\n const floors = new Map<string, number>();\n const openRuns: (readonly [Converter, number])[] = [];\n const kept = new Map<string, Rational>();\n for (const draw of draws) {\n const fix = fixed.get(draw.need);\n if (fix === undefined && !opened.has(draw.need)) continue;\n const endless = fix?.endless ?? mode === \"day\";\n const block = drawBlock(program, parts, draw, !endless);\n blocks.push(block);\n const demand = exact(drawDemand(draw, caseCuts));\n const need: Row = new Map(block.gifts);\n if (fix !== undefined) {\n program.push(need, \">=\", mul(demand, fix.span));\n const { limits, stopped } = deviceUse(block.runs);\n for (const index of stopped) program.push(new Map([[index, ONE]]), \"<=\", ZERO);\n for (const [key, limit] of limits) program.push(limit.row, \"<=\", mul(fix.keep.get(key) ?? ZERO, fix.span));\n for (const [key, value] of fix.keep) kept.set(key, add(kept.get(key) ?? ZERO, value));\n continue;\n }\n openRuns.push(...block.runs);\n if (mode === \"day\") {\n program.push(need, \">=\", demand);\n continue;\n }\n const days = program.next();\n addTo(need, days, neg(demand));\n program.push(need, \">=\", ZERO);\n floors.set(draw.need, program.push(new Map([[days, ONE], [floor, neg(ONE)]]), \">=\", ZERO));\n }\n const shared = new Map<string, { row: Row; room: Rational; converters: readonly Converter[] }>();\n const { limits, stopped } = deviceUse(openRuns);\n for (const index of stopped) program.push(new Map([[index, ONE]]), \"<=\", ZERO);\n for (const [key, limit] of limits) {\n const left = sub(exact(devices.get(key) ?? limit.devices), kept.get(key) ?? ZERO);\n const room = sign(left) > 0 ? left : ZERO;\n shared.set(key, { row: limit.row, room, converters: limit.converters });\n if (mode === \"day\") {\n program.push(limit.row, \"<=\", room);\n continue;\n }\n const row: Row = new Map(limit.row);\n addTo(row, floor, neg(room));\n program.push(row, \"<=\", ZERO);\n }\n for (const resource of parts.stocked) {\n const row: Row = new Map();\n for (const block of blocks) {\n const index = block.shares.get(resource);\n if (index !== undefined) addTo(row, index, ONE);\n }\n if (row.size > 0) program.push(row, \"<=\", exact(parts.stock.get(resource) ?? 0));\n }\n return { program, blocks, floor, floors, openRuns, shared };\n}\n\n/**\n * This function fixes the open draws with no end. Each open draw takes no stock, and keeps the fewest device-days of each day.\n * A step with no largest floor has a direction with no take of a stock, so this program has a point.\n */\nfunction fixEndless(parts: CaseParts, caseCuts: CaseCuts, draws: readonly Draw[], fixed: Map<string, Fixed>, open: readonly Draw[], devices: ReadonlyMap<string, number>): void {\n const step = buildStep(parts, caseCuts, draws, fixed, open, devices, \"day\");\n const solved = solveLexicographic(step.program.constraints(), [{ sense: \"min\", coefficients: dense(fewestRow(step.openRuns), step.program.count) }]);\n if (solved.status !== \"optimal\") throw new Error(\"The draws with no end of the best endurance have no point of one day.\");\n for (const draw of open) {\n const block = step.blocks.find((item) => item.draw.need === draw.need) as DrawBlock;\n const keep = new Map<string, Rational>();\n for (const [key, limit] of deviceUse(block.runs).limits) keep.set(key, valueAt(limit.row, solved.x));\n fixed.set(draw.need, { span: ONE, endless: true, keep, capped: [] });\n }\n}\n","import { DEFAULT_MAX_SETS, stopSets, type Stack } from \"@mark1russell7/system-stack\";\n\n// The minimal stop sets of a supply from the structure of the needs. The index does not give this entry: `stopCurves` uses it.\n\n/**\n * This function gives the minimal sets of cuts that stop a supply, from the paths of the needs of the stack (`stopSets` of the core).\n * A set is a list of indexes of `parts`, from the smallest set. Two sets of one size are in the order of `minimalStops`.\n *\n * - `parts` has the part of each cut that counts. Two cuts of one part are two cuts: each one stops what the part stops.\n * - A cut of the supply stops it alone. The other sets come from `stopSets` with the cut parts as `among`, so no other part can fail.\n * - The parts of `down` are down for the full event. The caller makes sure that they do not stop the supply with no cut.\n * - The result is `undefined` when the search passes its budget, or when the sets of cuts are more than `maxSets`.\n *\n * @param stack - The base stack\n * @param supply - The part of the supply of a draw\n * @param parts - The part of each cut that counts\n * @param down - The parts that are down for the full event\n * @param maxSets - The largest count of sets in one step of the search, and of the sets of cuts (`maxSets` of `stopSets`)\n */\nexport function stackStops(stack: Stack, supply: string, parts: readonly string[], down: readonly string[] = [], maxSets: number = DEFAULT_MAX_SETS): number[][] | undefined {\n const cutsOf = new Map<string, number[]>();\n for (const [index, part] of parts.entries()) cutsOf.set(part, [...(cutsOf.get(part) ?? []), index]);\n const own = (cutsOf.get(supply) ?? []).map((index) => [index]);\n const among = [...cutsOf.keys()].filter((part) => part !== supply);\n const found = stopSets(stack, supply, { down, among, size: among.length, maxSets });\n if (found.kind === \"budget\") return undefined;\n // The empty set: the supply is not in the stack, or it does not work in the base stack.\n // In both, `stopped` of the core does not count it as stopped, so only a cut of the supply stops it.\n if (found.sets.some((set) => set.length === 0)) return own;\n const out = [...own];\n for (const set of found.sets) {\n // Each choice of one cut for each part of the set is a minimal set of cuts.\n let choices: number[][] = [[]];\n for (const part of set) {\n const cuts = cutsOf.get(part) ?? [];\n if (choices.length * cuts.length + out.length > maxSets) return undefined;\n choices = choices.flatMap((choice) => cuts.map((cut) => [...choice, cut]));\n }\n out.push(...choices.map((choice) => choice.sort((x, y) => x - y)));\n }\n return out.sort(byMask);\n}\n\n/** The order of `minimalStops`: the smaller set first, then the set whose largest different index is smaller. */\nfunction byMask(a: readonly number[], b: readonly number[]): number {\n if (a.length !== b.length) return a.length - b.length;\n for (let index = a.length - 1; index >= 0; index -= 1) {\n const difference = (a[index] ?? 0) - (b[index] ?? 0);\n if (difference !== 0) return difference;\n }\n return 0;\n}\n","import { type OrderedRing, pathSetReliability, stronglyConnectedComponents } from \"@mark1russell7/collections/graph\";\nimport { DEFAULT_MAX_SETS, neededParts, survivalAt, weakestBound, type CutBound, type PathOptions } from \"@mark1russell7/system-stack\";\nimport { caseDraws, caseStopped, enduranceOf, type CaseOptions } from \"./endurance.ts\";\nimport type { CaseCuts, Draw, Endurance, EnduranceLayer, Prior, Survival } from \"./layer.ts\";\nimport { stackStops } from \"./stops.ts\";\n\n// The shortfall: the user-days in which a draw does not get its need, for one case and for one year.\n\n/** The read of a curve at a time is in the core since system-stack 0.1.13. This package gives it again, so its API does not change. */\nexport { survivalAt };\n\n/**\n * This function gives the expected days of a cut after a time, up to a horizon: `E[max(0, min(D, to) - from)]`.\n * It is the area under the curve from `from` to `to`. The curve is linear between its points, so the area is exact.\n * With no horizon, the area goes to the end of the curve.\n */\nexport function tailDays(curve: Survival, from: number, to: number = Infinity): number {\n let area = 0;\n for (let index = 1; index < curve.length; index += 1) {\n const [t0] = curve[index - 1] ?? [0, 1];\n const [t1] = curve[index] ?? [0, 0];\n const start = Math.max(t0, from);\n const end = Math.min(t1, to);\n if (start < end) area += ((survivalAt(curve, start) + survivalAt(curve, end)) / 2) * (end - start);\n }\n return area;\n}\n\n/**\n * The options of a shortfall: the stack or the parts that are also down, as for `enduranceOf`, and a horizon.\n * With a horizon of `h` days, the shortfall counts only the first `h` days of each cut. A draw that holds `h` days has no shortfall.\n * Thus a plan can aim at a target, for example 14 days and then 90 days.\n */\n/**\n * The options of `stopCurves`. With a stack, `maxSets` is the budget of the search of the needs (`stopSets` of the core).\n * When the search passes it, `minimalStops` gives the sets.\n */\nexport interface StopCurveOptions extends Pick<CaseOptions, \"stack\" | \"down\">, Pick<PathOptions, \"maxSets\"> {\n /** The budget of `independentStop` for the curve of each draw, a whole number from 1. The default is `INDEPENDENT_MAX_WORK`. */\n readonly maxWork?: number | undefined;\n}\n\nexport interface ShortfallOptions extends StopCurveOptions {\n /** The horizon in days, more than 0. The default is no horizon. */\n readonly horizon?: number | undefined;\n}\n\nfunction horizonOf(options: ShortfallOptions): number {\n const horizon = options.horizon ?? Infinity;\n if (!(horizon > 0)) throw new RangeError(`The horizon ${String(options.horizon)} is not a number of days more than 0.`);\n return horizon;\n}\n\nfunction budgetsOf(options: StopCurveOptions): { readonly maxSets: number; readonly maxWork: number } {\n const maxSets = options.maxSets ?? DEFAULT_MAX_SETS;\n if (!Number.isInteger(maxSets) || maxSets < 1) throw new RangeError(`The option maxSets is ${String(options.maxSets)}: it is not a whole number from 1.`);\n const maxWork = options.maxWork ?? INDEPENDENT_MAX_WORK;\n if (!Number.isInteger(maxWork) || maxWork < 1) throw new RangeError(`The option maxWork is ${String(options.maxWork)}: it is not a whole number from 1.`);\n return { maxSets, maxWork };\n}\n\n/**\n * This function gives the days at which the chance of the curve falls to `chance`. With `0.1`, it is the 90th percentile of the duration.\n * When the curve does not fall to `chance`, the result is `Infinity`.\n */\nexport function survivalQuantile(curve: Survival, chance: number): number {\n for (let index = 1; index < curve.length; index += 1) {\n const [t0, p0] = curve[index - 1] ?? [0, 1];\n const [t1, p1] = curve[index] ?? [0, 0];\n if (p0 <= chance) return t0;\n if (p1 <= chance) return t0 + ((p0 - chance) * (t1 - t0)) / (p0 - p1);\n }\n return Infinity;\n}\n\n/** This function gives the chance that a case reaches its place one or more times in one year: `1 - exp(-perYear * reach)`. */\nexport function yearChance(prior: Prior): number {\n return 1 - Math.exp(-prior.perYear * prior.reach);\n}\n\n/** This function gives the expected count of the events of a case at its place in one year: `perYear * reach`. */\nexport function yearRate(prior: Prior): number {\n return prior.perYear * prior.reach;\n}\n\n/** This function gives the times at which a curve of the result can bend: each point of each curve, and each crossing of two curves. */\nfunction bendTimes(curves: readonly Survival[]): number[] {\n const times = [...new Set(curves.flatMap((curve) => curve.map(([days]) => days)))].sort((x, y) => x - y);\n const out = new Set(times);\n for (let index = 1; index < times.length; index += 1) {\n const t0 = times[index - 1] ?? 0;\n const t1 = times[index] ?? 0;\n for (const [i, a] of curves.entries()) {\n for (const b of curves.slice(i + 1)) {\n const d0 = survivalAt(a, t0) - survivalAt(b, t0);\n const d1 = survivalAt(a, t1) - survivalAt(b, t1);\n if (d0 * d1 < 0) out.add(t0 + ((t1 - t0) * d0) / (d0 - d1));\n }\n }\n }\n return [...out].sort((x, y) => x - y);\n}\n\n/**\n * This function makes a survival curve from a chance at each time. It stops at the first chance of 0, and it removes an increase of rounding.\n *\n * @throws RangeError when the chance at the last time is more than 0, as for curves that do not end at a chance of 0\n */\nfunction curveFrom(times: readonly number[], chanceAt: (days: number) => number): Survival {\n const out: [number, number][] = [];\n for (const days of times) {\n const chance = Math.min(out[out.length - 1]?.[1] ?? 1, chanceAt(days));\n out.push([days, chance]);\n if (chance === 0) return out;\n }\n throw new RangeError(\"The curves do not fall to a chance of 0 at their last point.\");\n}\n\n/**\n * This function gives the curve of a stop of some cuts when one event makes each cut longer together.\n * At each time, the chance is the largest `s` at which the cuts with a chance of `s` or more stop the supply.\n *\n * - When any one cut stops the supply, the result is the largest chance of the curves (`longestStop`).\n * - When the supply needs `any` of two parts, the stop ends with the shorter of the two cuts.\n * - Between two times of `bendTimes` the order of the curves does not change. So the result is linear between its points.\n * - When no set of cuts stops the supply, the result is `[[0, 0]]`. This curve does not start at `[0, 1]`, so `checkEndurance` refuses it.\n *\n * The result is not a limit. When the cuts are independent, a stop of two cuts in series can be longer. A stop through a need of `any` can be shorter.\n *\n * @param curves - The curves of the cuts, each one good for `checkEndurance`\n * @param stops - This function tells if the cuts of a list of indexes stop the supply. A larger list stops it when a smaller list does.\n * @throws RangeError when a curve does not end at a chance of 0\n */\nexport function eventStop(curves: readonly Survival[], stops: (cuts: readonly number[]) => boolean): Survival {\n return curveFrom(bendTimes(curves), (days) => {\n const chances = curves.map((curve) => survivalAt(curve, days));\n for (const level of [...new Set(chances)].sort((x, y) => y - x)) {\n if (stops(chances.flatMap((chance, index) => (chance >= level ? [index] : [])))) return level;\n }\n return 0;\n });\n}\n\n/**\n * This function gives the curve of the longest of some stops: at each time, the largest chance of the curves.\n * It is `eventStop` when any one cut stops the supply.\n *\n * @param curves - The curves, each one good for `checkEndurance`\n * @throws RangeError when there is no curve, or when a curve does not end at a chance of 0\n */\nexport function longestStop(curves: readonly Survival[]): Survival {\n const first = curves[0];\n if (first === undefined) throw new RangeError(\"longestStop needs one or more curves.\");\n return curves.length === 1 ? first : eventStop(curves, (cuts) => cuts.length > 0);\n}\n\n/**\n * The largest count of cuts for which `minimalStops` examines each set, and for which `independentStop` adds the chance of each state.\n * With a stack, `stopCurves` finds the minimal sets from the needs, so a larger count of cuts can have exact sets.\n */\nexport const MINIMAL_STOP_CUTS = 12;\n\n/**\n * This function gives the minimal sets of cuts that stop the supply: each set stops it, and no smaller part of a set stops it.\n * With more than `MINIMAL_STOP_CUTS` cuts, the result is `undefined`.\n */\nexport function minimalStops(count: number, stops: (cuts: readonly number[]) => boolean): number[][] | undefined {\n if (count > MINIMAL_STOP_CUTS) return undefined;\n const found: number[][] = [];\n const masks: number[] = [];\n const all = Array.from({ length: 1 << count }, (_, mask) => mask).sort((x, y) => popCount(x) - popCount(y) || x - y);\n for (const mask of all) {\n if (mask === 0 || masks.some((other) => (other & mask) === other)) continue;\n const cuts = Array.from({ length: count }, (_, index) => index).filter((index) => (mask >> index) & 1);\n if (!stops(cuts)) continue;\n masks.push(mask);\n found.push(cuts);\n }\n return found;\n}\n\nfunction popCount(mask: number): number {\n let total = 0;\n for (let rest = mask; rest > 0; rest &= rest - 1) total += 1;\n return total;\n}\n\n/**\n * This function gives an upper limit of the curve of a stop for each dependence of the cuts.\n * At each time it is `min(1, sum over the minimal sets of the smallest chance of the set)`.\n * With no minimal sets, as for too many cuts, it is `min(1, sum of the chances)`.\n *\n * @param curves - The curves of the cuts\n * @param sets - The minimal sets of `minimalStops`, or `undefined`\n * @throws RangeError when a curve does not end at a chance of 0\n */\nexport function upperStop(curves: readonly Survival[], sets: readonly (readonly number[])[] | undefined): Survival {\n const groups = sets ?? curves.map((_, index) => [index]);\n const sum = (days: number): number => groups.reduce((total, set) => total + Math.min(...set.map((index) => survivalAt(curves[index] ?? [], days))), 0);\n // The sum is linear between two times of bendTimes. A point where it falls through 1 is a bend of min(1, sum).\n const times = bendTimes(curves);\n const bends = new Set(times);\n for (let index = 1; index < times.length; index += 1) {\n const t0 = times[index - 1] ?? 0;\n const t1 = times[index] ?? 0;\n const s0 = sum(t0) - 1;\n const s1 = sum(t1) - 1;\n if (s0 * s1 < 0) bends.add(t0 + ((t1 - t0) * s0) / (s0 - s1));\n }\n return curveFrom([...bends].sort((x, y) => x - y), (days) => Math.min(1, sum(days)));\n}\n\n/** The largest difference between `independentStop` and the true chance of a stop of independent cuts, at each time. */\nexport const INDEPENDENT_TOLERANCE = 1e-6;\n\n/**\n * The default budget of `independentStop` for its groups of more than `MINIMAL_STOP_CUTS` cuts.\n * The budget counts the steps of the expansion times the count of points of the curve.\n * It is near the work of the sum over the states of 12 cuts.\n */\nexport const INDEPENDENT_MAX_WORK: number = 2 ** 26;\n\n/**\n * This function gives the curve of a stop of some cuts when the cuts are independent.\n * At each time `t`, the supply is stopped when the cuts that are still on contain a minimal set.\n * Its chance is a sum over each set of cuts that stops the supply.\n * Each term is the product of `s(t)` for the cuts that are on, and of `1 - s(t)` for the other cuts.\n *\n * - When any one cut stops the supply, the result is `1 - prod(1 - s)`. It is not less than the longest cut (`eventStop`).\n * - When the supply needs `any` of two parts, the stop of the two is `s1 * s2`. It is not more than the shorter cut.\n * - The result is not more than `upperStop` of the same sets, because `upperStop` is a limit for each dependence.\n * - Between two points of the curves the chance is a polynomial, not a line. The function splits each such segment into equal pieces.\n * The chance is linear in each `s`, and each mixed second derivative is between -1 and 1.\n * Thus `|f''| <= (sum |s'|)^2 - sum s'^2`, and the line of a piece of length `h` is within `h^2 |f''| / 8` of the chance.\n * The count of pieces keeps each line within `INDEPENDENT_TOLERANCE`. With a margin of 10 %, the count of points is less than `n / sqrt(7.2 * INDEPENDENT_TOLERANCE)` plus the segments, for `n` cuts.\n *\n * - Up to `MINIMAL_STOP_CUTS` cuts in the sets, the function adds the chance of each of the 2 to the power of that count of states.\n * - Two groups of cuts that share no set are independent, so the chance that the supply works is the product over the groups.\n * For example, 20 stages of 2 feeds give 20 groups of 2 cuts.\n * - In a group of more than `MINIMAL_STOP_CUTS` cuts, it uses the Shannon expansion of `pathSetReliability` of collections.\n * The expansion merges two states with the same sets left, and it drops a set that holds another set.\n * - The expansion is exponential in the worst case. The groups share one budget, `maxWork`.\n * When the steps of the expansions times the count of points of the curve pass it, the result is `undefined`.\n *\n * @param curves - The curves of the cuts, each one good for `checkEndurance`\n * @param sets - The minimal sets of the cuts. With `undefined`, as for no minimal sets, the result is `undefined`. With no sets, it is `[[0, 0]]`\n * @param maxWork - The budget of the expansions of the groups of more than `MINIMAL_STOP_CUTS` cuts, a whole number from 1. The default is `INDEPENDENT_MAX_WORK`\n * @throws RangeError when a curve does not end at a chance of 0, or for a bad `maxWork`\n */\nexport function independentStop(curves: readonly Survival[], sets: readonly (readonly number[])[] | undefined, maxWork: number = INDEPENDENT_MAX_WORK): Survival | undefined {\n if (!Number.isInteger(maxWork) || maxWork < 1) throw new RangeError(`The budget maxWork is ${String(maxWork)}: it is not a whole number from 1.`);\n if (sets === undefined) return undefined;\n // With no set, no cuts stop the supply, as for `eventStop` and `upperStop`.\n if (sets.length === 0) return [[0, 0]];\n // Only the cuts of a set change the chance. Their place in `used` is their index in the sets of the cuts that count.\n const used = [...new Set(sets.flat())].sort((x, y) => x - y);\n const usedCurves = used.map((index) => curves[index] ?? []);\n const usedSets = sets.map((set) => set.map((index) => used.indexOf(index)));\n const points = independentPoints(usedCurves);\n // Two groups of cuts that share no set are independent: the supply works when it works in each group.\n const groupChances: ((days: number) => number)[] = [];\n // The expansions of all groups share one budget.\n let work = maxWork;\n for (const group of cutGroups(used.length, usedSets)) {\n const curvesOf = group.map((index) => usedCurves[index] ?? []);\n const setsOf = usedSets.filter((set) => group.includes(set[0] ?? -1)).map((set) => set.map((index) => group.indexOf(index)));\n // Up to MINIMAL_STOP_CUTS cuts, the sum over the states is exact with a fixed cost. Past them, the expansion is exact within its budget.\n if (group.length <= MINIMAL_STOP_CUTS) {\n groupChances.push(stateChance(curvesOf, setsOf));\n continue;\n }\n const expanded = expandedChances(curvesOf, setsOf, points, work);\n if (expanded === undefined) return undefined;\n work -= expanded.steps * points.length;\n const chanceOf = new Map(points.map((days, index) => [days, expanded.chances[index] ?? 0]));\n groupChances.push((days) => {\n const chance = chanceOf.get(days);\n if (chance === undefined) throw new Error(`The expansion has no chance at ${String(days)} days.`);\n return chance;\n });\n }\n // With one group, the chance of the group is the result, with no rounding of 1 - (1 - chance).\n const [only] = groupChances;\n if (groupChances.length === 1 && only !== undefined) return curveFrom(points, only);\n return curveFrom(points, (days) => Math.min(1, Math.max(0, 1 - groupChances.reduce((works, chanceAt) => works * (1 - chanceAt(days)), 1))));\n}\n\n/** The groups of the cuts `0` to `count - 1`: two cuts are in one group when a chain of sets joins them. Each set has its cuts in one group. */\nfunction cutGroups(count: number, sets: readonly (readonly number[])[]): number[][] {\n const next = Array.from({ length: count }, () => new Set<number>());\n // A cycle through the cuts of each set joins them both ways, so the strongly connected components are the groups.\n for (const set of sets) for (const [at, index] of set.entries()) next[index]?.add(set[(at + 1) % set.length] ?? index);\n return stronglyConnectedComponents(\n Array.from({ length: count }, (_, index) => index),\n (index) => next[index] ?? [],\n );\n}\n\n/** The times of `independentStop`: the points of the curves, and the pieces that keep each line within `INDEPENDENT_TOLERANCE`. */\nfunction independentPoints(curves: readonly Survival[]): number[] {\n const times = [...new Set(curves.flatMap((curve) => curve.map(([days]) => days)))].sort((x, y) => x - y);\n const points: number[] = [];\n for (const [index, t1] of times.entries()) {\n const t0 = times[index - 1];\n if (t0 !== undefined) {\n const h = t1 - t0;\n const slopes = curves.map((curve) => Math.abs(survivalAt(curve, t1) - survivalAt(curve, t0)) / h);\n const sum = slopes.reduce((total, slope) => total + slope, 0);\n const bound = Math.max(0, sum * sum - slopes.reduce((total, slope) => total + slope * slope, 0));\n // A margin of 10 % keeps the rounding of the chance under the tolerance.\n const pieces = Math.ceil(h * Math.sqrt(bound / (8 * 0.9 * INDEPENDENT_TOLERANCE)));\n for (let piece = 1; piece < pieces; piece += 1) {\n const days = t0 + (h * piece) / pieces;\n // Two times that are next to each other as floats have no time between them.\n if (days > (points[points.length - 1] ?? t0) && days < t1) points.push(days);\n }\n }\n points.push(t1);\n }\n return points;\n}\n\n/** The chance of a stop at a time, as the sum over each state of `MINIMAL_STOP_CUTS` cuts or fewer. Bit k of a state is 1 when cut k is on. */\nfunction stateChance(curves: readonly Survival[], sets: readonly (readonly number[])[]): (days: number) => number {\n const setMasks = sets.map((set) => set.reduce((mask, index) => mask | (1 << index), 0));\n const stopping = Array.from({ length: 1 << curves.length }, (_, mask) => setMasks.some((set) => (set & mask) === set));\n const states = new Float64Array(1 << curves.length);\n return (days) => {\n // The chance of each state of the cuts, one cut at a time.\n states[0] = 1;\n let length = 1;\n for (const curve of curves) {\n const on = survivalAt(curve, days);\n for (let mask = 0; mask < length; mask += 1) {\n const chance = states[mask] ?? 0;\n states[mask + length] = chance * on;\n states[mask] = chance * (1 - on);\n }\n length *= 2;\n }\n let total = 0;\n for (let mask = 0; mask < length; mask += 1) if (stopping[mask]) total += states[mask] ?? 0;\n return Math.min(1, Math.max(0, total));\n };\n}\n\n/** The count of times in one expansion of `expandedChances`: the length of the vectors of its ring. */\nconst EXPANSION_WIDTH = 64;\n\n/**\n * The ring of the vectors of `width` chances, one for each time, for `pathSetReliability` of collections.\n * Each operation is on each time alone. In the order, `a` is less than `b` when it is less or equal at each time, and not equal.\n */\nfunction vectorRing(width: number): OrderedRing<Float64Array> {\n const zip = (a: Float64Array, b: Float64Array, op: (x: number, y: number) => number): Float64Array => {\n const out = new Float64Array(width);\n for (let index = 0; index < width; index += 1) out[index] = op(a[index] ?? 0, b[index] ?? 0);\n return out;\n };\n return {\n zero: new Float64Array(width),\n one: new Float64Array(width).fill(1),\n add: (a, b) => zip(a, b, (x, y) => x + y),\n sub: (a, b) => zip(a, b, (x, y) => x - y),\n mul: (a, b) => zip(a, b, (x, y) => x * y),\n compare: (a, b) => {\n let less = false;\n let more = false;\n for (let index = 0; index < width; index += 1) {\n const [x, y] = [a[index] ?? 0, b[index] ?? 0];\n if (x < y) less = true;\n else if (x > y) more = true;\n else if (x !== y) return Number.NaN;\n }\n return less ? (more ? Number.NaN : -1) : more ? 1 : 0;\n },\n };\n}\n\n/**\n * The chance of a stop at each point, from the Shannon expansion of `pathSetReliability`. A set works when each of its cuts is on.\n * One call gives `EXPANSION_WIDTH` points. When the steps of one expansion times the count of points pass `maxWork`, the result is `undefined`.\n * Else `steps` is the count of steps of one expansion.\n */\nfunction expandedChances(\n curves: readonly Survival[],\n sets: readonly (readonly number[])[],\n points: readonly number[],\n maxWork: number,\n): { readonly chances: number[]; readonly steps: number } | undefined {\n const maxSteps = Math.floor(maxWork / points.length);\n if (maxSteps < 1) return undefined;\n const out: number[] = [];\n let steps = 0;\n for (let start = 0; start < points.length; start += EXPANSION_WIDTH) {\n const times = points.slice(start, start + EXPANSION_WIDTH);\n const chances = curves.map((curve) => Float64Array.from(times, (days) => survivalAt(curve, days)));\n const result = pathSetReliability(sets, chances, vectorRing(times.length), { maxSteps });\n // Each call has the same sets, so the first call tells if the expansion is in the budget.\n if (result.kind === \"budget\") return undefined;\n steps = result.steps;\n for (const chance of result.value) out.push(Math.min(1, Math.max(0, chance)));\n }\n return { chances: out, steps };\n}\n\n/**\n * The curves of the stop of a draw. `event` is for one event that makes each cut longer together, and `independent` is for independent cuts.\n * `upper` is an upper limit for each dependence.\n */\nexport interface StopCurves {\n readonly event: Survival;\n /** The stop when the cuts are independent (`independentStop`). When `independentUpper` is true, it is `upper`. */\n readonly independent: Survival;\n readonly upper: Survival;\n /**\n * This is true when `upper` is the sum of the curves of the cuts that count, because the query has no minimal sets.\n * With a stack, the search of the needs passed its budget. With no stack, more than `MINIMAL_STOP_CUTS` cuts count.\n */\n readonly coarse: boolean;\n /** This is true when `independent` is `upper`: `coarse` is true, or the expansion of `independentStop` passed its budget. */\n readonly independentUpper: boolean;\n /**\n * The weakest bound (`weakestBound` of the core) of the curves of the cuts that the stop uses. Since 0.8.4.\n * With minimal sets, the stop uses the cuts of the sets. With no minimal sets, it uses each cut with a curve.\n * Each of the three curves does not decrease when a cut lasts longer, so it has this bound.\n */\n readonly bound: CutBound;\n}\n\n/** This function gives the parts of the stack that are down for a list of cut indexes. A case uses one memo for each of its draws. */\ntype StoppedOf = (cuts: readonly number[]) => ReadonlySet<string>;\n\nfunction stoppedMemo(caseCuts: CaseCuts, options: Pick<CaseOptions, \"stack\" | \"down\">): StoppedOf {\n const memo = new Map<string, ReadonlySet<string>>();\n return (cuts) => {\n const key = cuts.join(\",\");\n let found = memo.get(key);\n if (found === undefined) {\n found = caseStopped({ ...caseCuts, cuts: cuts.flatMap((index) => caseCuts.cuts[index] ?? []) }, options);\n memo.set(key, found);\n }\n return found;\n };\n}\n\n/** This function gives the parts whose cut can stop a supply: the supply, and each part that it needs through the stack. */\nfunction supplyReach(supply: string, options: Pick<CaseOptions, \"stack\">): Set<string> {\n const reach = options.stack === undefined ? new Set<string>() : neededParts(options.stack, supply);\n reach.add(supply);\n return reach;\n}\n\nfunction stopCurvesWith(caseCuts: CaseCuts, draw: Draw, options: StopCurveOptions, stoppedOf: StoppedOf): StopCurves | undefined {\n const reach = supplyReach(draw.supply, options);\n const relevant = caseCuts.cuts.flatMap((cut, index) => (reach.has(cut.part) ? [index] : []));\n const stops = (cuts: readonly number[]): boolean => stoppedOf(cuts.map((index) => relevant[index] ?? -1)).has(draw.supply);\n if (stops([])) return undefined;\n if (!stops(relevant.map((_, index) => index))) return undefined;\n const given = relevant.map((index) => caseCuts.cuts[index]?.duration);\n // With a stack, the needs give the minimal sets. When their search passes its budget, the sets of each list of cuts are the check.\n const parts = relevant.map((index) => caseCuts.cuts[index]?.part ?? \"\");\n const structural = options.stack === undefined ? undefined : stackStops(options.stack, draw.supply, parts, options.down, budgetsOf(options).maxSets);\n const sets = structural ?? minimalStops(given.length, stops);\n // The stop has no curve when a cut with no curve can be part of it. With no minimal sets, the query cannot tell.\n const unsourced = given.flatMap((curve, index) => (curve === undefined ? [index] : []));\n if (unsourced.length > 0 && (sets === undefined || sets.some((set) => set.some((index) => unsourced.includes(index))))) return undefined;\n // A cut with no curve is in no minimal set here, so it does not change a stop. The curves do not include it.\n const kept = given.flatMap((curve, index) => (curve === undefined ? [] : [index]));\n const curves = kept.map((index) => given[index] ?? []);\n const keptStops = (cuts: readonly number[]): boolean => stops(cuts.map((index) => kept[index] ?? -1));\n const keptSets = sets?.map((set) => set.map((index) => kept.indexOf(index)));\n const upper = upperStop(curves, keptSets);\n const independent = independentStop(curves, keptSets, budgetsOf(options).maxWork);\n // A cut in no minimal set does not change a stop, so its bound does not weaken the bound of the stop.\n const used = sets === undefined ? kept : kept.filter((index) => sets.some((set) => set.includes(index)));\n const bound = weakestBound(used.map((index) => caseCuts.cuts[relevant[index] ?? -1]?.bound ?? \"law\"));\n return { event: eventStop(curves, keptStops), independent: independent ?? upper, upper, coarse: keptSets === undefined, independentUpper: independent === undefined, bound };\n}\n\n/**\n * This function gives the curves of the duration of the stop of a draw, or `undefined` when the query has no curve.\n *\n * - A set of cuts stops the supply when the supply cannot work without the cut parts, through the needs of the stack.\n * - Only the cuts of the supply, and of the parts that it needs through the stack, count. Another cut does not change the curves.\n * - The parts of `down` are down for the full event. When they stop the supply with no cut, the query has no curve.\n * - With a stack, the minimal sets come from the paths of the needs (`stopSets` of the core), so the count of cuts has no limit of `MINIMAL_STOP_CUTS`.\n * When that search passes its budget (the option `maxSets`), `minimalStops` examines each set of up to `MINIMAL_STOP_CUTS` cuts.\n * - A cut with no `duration` gives no curve when it is in a minimal set, or when the query has no minimal sets.\n * - `event` is `eventStop`. `independent` is `independentStop`, and `upper` is `upperStop`, over the minimal sets of the cuts that count.\n * - With no minimal sets, `upper` is the sum of the curves, `independent` is `upper`, and `coarse` is true.\n * - When the expansion of `independentStop` passes its budget, `independent` is `upper`, and `independentUpper` is true.\n * - `bound` is the weakest bound of the curves of the cuts that the stop uses. A cut with no `bound` has a law.\n */\nexport function stopCurves(caseCuts: CaseCuts, draw: Draw, options: StopCurveOptions = {}): StopCurves | undefined {\n budgetsOf(options);\n return stopCurvesWith(caseCuts, draw, options, stoppedMemo(caseCuts, options));\n}\n\n/** The shortfall of each level, in user-days, and the draws that the query cannot read. */\nexport interface Shortfall {\n /**\n * The user-days of each level of the layer, when one event makes each cut longer together. The query does not add two levels.\n * This value is not a limit. The true value can be more or less. `upper` is the limit.\n */\n readonly levels: Readonly<Record<string, number>>;\n /** The user-days of each level when the cuts are independent (`StopCurves.independent`). This value is not more than `upper`. */\n readonly independent: Readonly<Record<string, number>>;\n /** The upper limit of the user-days of each level, for each dependence of the cuts. A gate of a high level can use it. */\n readonly upper: Readonly<Record<string, number>>;\n /**\n * The needs of the draws whose stop has no curve (`stopCurves`).\n * The query has no curve of their duration, so their shortfall is not in `levels`. A gate shows them as no read.\n */\n readonly unread: readonly string[];\n /** The needs of the draws whose `upper` is coarse (`StopCurves.coarse`). A gate on `upper` shows them. */\n readonly coarse: readonly string[];\n /** The needs of the draws whose `independent` is `upper` (`StopCurves.independentUpper`). A gate on `independent` shows them. */\n readonly independentUpper: readonly string[];\n /**\n * The bound of the shortfall: the weakest bound (`weakestBound` of the core) of the curves that the query uses. Since 0.8.4.\n * The shortfall does not decrease when a cut lasts longer. So with `upper`, each value is too high or equal, and with `lower` too low or equal.\n * With `none`, a value can be too high or too low.\n *\n * A draw in `unread` and a case that adds 0 do not change the bound. With no curve, the bound is `law`.\n * The bound is for each of `levels`, `independent` and `upper`, each with its own rule of the dependence of the cuts.\n */\n readonly bound: CutBound;\n}\n\nfunction zeroLevels(layer: EnduranceLayer): Record<string, number> {\n return Object.fromEntries(layer.levels.map((level) => [level, 0]));\n}\n\n/**\n * This function gives the shortfall of one event of a case: for each draw, `E[max(0, min(D, h) - T)] * users`.\n * `T` is the endurance of the draw, `D` is the duration of the stop of its supply (`stopCurves`), and `h` is the horizon.\n *\n * @param layer - The endurance layer\n * @param caseCuts - The case\n * @param endurance - The endurance of the case, from `enduranceOf`\n * @param options - The stack or the parts that are also down, as for `enduranceOf`, and the horizon\n * @throws RangeError when the horizon is not a number more than 0, or `maxSets` is not a whole number from 1\n */\nexport function caseShortfall(layer: EnduranceLayer, caseCuts: CaseCuts, endurance: Endurance, options: ShortfallOptions = {}): Shortfall {\n const horizon = horizonOf(options);\n budgetsOf(options);\n const levels = zeroLevels(layer);\n const independent = zeroLevels(layer);\n const upper = zeroLevels(layer);\n const unread: string[] = [];\n const coarse: string[] = [];\n const independentUpper: string[] = [];\n const bounds: CutBound[] = [];\n const stoppedOf = stoppedMemo(caseCuts, options);\n for (const draw of caseDraws(layer, caseCuts, caseStopped(caseCuts, options))) {\n const held = endurance.needs[draw.need];\n const curves = stopCurvesWith(caseCuts, draw, options, stoppedOf);\n if (held === undefined || curves === undefined) {\n unread.push(draw.need);\n continue;\n }\n if (curves.coarse) coarse.push(draw.need);\n if (curves.independentUpper) independentUpper.push(draw.need);\n bounds.push(curves.bound);\n const users = draw.users ?? 1;\n levels[draw.level] = (levels[draw.level] ?? 0) + tailDays(curves.event, held.days, horizon) * users;\n independent[draw.level] = (independent[draw.level] ?? 0) + tailDays(curves.independent, held.days, horizon) * users;\n upper[draw.level] = (upper[draw.level] ?? 0) + tailDays(curves.upper, held.days, horizon) * users;\n }\n return { levels, independent, upper, unread, coarse, independentUpper, bound: weakestBound(bounds) };\n}\n\n/** The shortfall of one year at one place, with the part of each case. */\nexport interface YearShortfall extends Shortfall {\n readonly place: string;\n /** The part of each case. `rate` is the expected count of its events in one year. */\n readonly cases: readonly { readonly case: string; readonly rate: number; readonly endurance: Endurance; readonly shortfall: Shortfall }[];\n}\n\n/**\n * This function gives the shortfall of one year at one place.\n * It is the sum over the cases of the layer of the expected count of the events of each case times its shortfall.\n *\n * - The expected count of a case is `perYear * reach`, from the first prior of the case at the place. Thus the result is the expected user-days of one year.\n * - A case with no prior at the place is not in the sum.\n * - `unread` is the union of the needs that a case cannot read, in the order of the cases. `coarse` and `independentUpper` are unions too.\n * - `bound` is the weakest bound of the cases in the sum. A case with no prior, or with an expected count of 0, adds 0, so it does not change the bound.\n *\n * @param layer - The endurance layer, with its cases and priors\n * @param place - The place of the priors\n * @param options - The date, the stack or the parts that are also down, and the horizon\n * @throws RangeError for a bad date, horizon or `maxSets`: refer to `caseShortfall` and `enduranceOf`\n */\nexport function yearShortfall(layer: EnduranceLayer, place: string, options: CaseOptions & ShortfallOptions): YearShortfall {\n horizonOf(options);\n budgetsOf(options);\n const levels = zeroLevels(layer);\n const independent = zeroLevels(layer);\n const upper = zeroLevels(layer);\n const unread: string[] = [];\n const coarse: string[] = [];\n const independentUpper: string[] = [];\n const cases: YearShortfall[\"cases\"][number][] = [];\n const bounds: CutBound[] = [];\n for (const caseCuts of layer.cases ?? []) {\n const prior = (layer.priors ?? []).find((item) => item.case === caseCuts.case && item.place === place);\n if (prior === undefined) continue;\n const rate = yearRate(prior);\n const endurance = enduranceOf(layer, caseCuts, options);\n const shortfall = caseShortfall(layer, caseCuts, endurance, options);\n for (const [level, days] of Object.entries(shortfall.levels)) levels[level] = (levels[level] ?? 0) + rate * days;\n for (const [level, days] of Object.entries(shortfall.independent)) independent[level] = (independent[level] ?? 0) + rate * days;\n for (const [level, days] of Object.entries(shortfall.upper)) upper[level] = (upper[level] ?? 0) + rate * days;\n for (const need of shortfall.unread) if (!unread.includes(need)) unread.push(need);\n for (const need of shortfall.coarse) if (!coarse.includes(need)) coarse.push(need);\n for (const need of shortfall.independentUpper) if (!independentUpper.includes(need)) independentUpper.push(need);\n if (rate > 0) bounds.push(shortfall.bound);\n cases.push({ case: caseCuts.case, rate, endurance, shortfall });\n }\n return { place, levels, independent, upper, unread, coarse, independentUpper, bound: weakestBound(bounds), cases };\n}\n","import { STACK_SCHEMA, type Stack } from \"@mark1russell7/system-stack\";\nimport { ENDURANCE_SCHEMA, type EnduranceLayer } from \"./layer.ts\";\n\n// A sample: a building with 3 users, and a storm that cuts the grid, the road and the water main.\n// Each name and each value is an example, except the grid curve (NREL, technical report 83092). The tests, the README files and the site use it.\n\n/** The base stack of the sample: the supplies of the building and a camp stove. */\nexport const SAMPLE_ENDURANCE_STACK: Stack = {\n schema: STACK_SCHEMA,\n parts: [\n { id: \"grid\", kind: \"power\", name: \"The power grid\" },\n { id: \"water-main\", kind: \"water\", name: \"The water main\" },\n { id: \"road\", kind: \"road\", name: \"The local road to the shops\" },\n { id: \"stove\", kind: \"device\", name: \"The camp stove\" },\n ],\n};\n\n/**\n * The endurance layer of the sample.\n *\n * - The drinking water holds 75.7 L / 11.355 L a day = 6.667 days.\n * - The food holds 4800 / 5400 = 0.889 days. The rice needs 2 L of water for each kg, and the drinking water keeps back all the water.\n * - The power holds 1000 Wh / 150 Wh a day = 6.667 days.\n * - The filled bottles are past their due date, so they give nothing.\n */\nexport const SAMPLE_ENDURANCE: EnduranceLayer = {\n schema: ENDURANCE_SCHEMA,\n levels: [\"life\", \"health\", \"comfort\"],\n resources: [\n { code: \"water.stored\", unit: \"L\" },\n { code: \"food.ready\", unit: \"kcal\" },\n { code: \"food.grain-dry\", unit: \"kg\" },\n { code: \"fuel.propane\", unit: \"kg\" },\n { code: \"energy.battery\", unit: \"Wh\" },\n ],\n stores: [\n { id: \"jugs\", resource: \"water.stored\", amount: 75.7, due: \"2028-06-01\" },\n { id: \"bottles\", resource: \"water.stored\", amount: 20, due: \"2026-09-30\" },\n { id: \"cans\", resource: \"food.ready\", amount: 4800, due: \"2028-10-01\" },\n { id: \"rice\", resource: \"food.grain-dry\", amount: 9, due: \"2036-09-28\" },\n { id: \"propane\", resource: \"fuel.propane\", amount: 0.908, due: \"2036-10-01\" },\n { id: \"battery\", resource: \"energy.battery\", amount: 1000, due: \"2031-10-01\" },\n ],\n draws: [\n { need: \"hydration.drink\", level: \"life\", perDay: 11.355, users: 3, supply: \"water-main\" },\n { need: \"food.energy\", level: \"health\", perDay: 5400, users: 3, supply: \"road\" },\n { need: \"power.electric\", level: \"comfort\", perDay: 150, users: 3, supply: \"grid\" },\n ],\n direct: [\n { resource: \"water.stored\", need: \"hydration.drink\", amount: 1 },\n { resource: \"food.ready\", need: \"food.energy\", amount: 1 },\n { resource: \"energy.battery\", need: \"power.electric\", amount: 1 },\n ],\n converters: [\n {\n id: \"cook-rice\",\n device: \"stove\",\n takes: [\n { resource: \"food.grain-dry\", amount: 1 },\n { resource: \"water.stored\", amount: 2 },\n { resource: \"fuel.propane\", amount: 0.05 },\n ],\n gives: { need: \"food.energy\", amount: 3600 },\n },\n ],\n cases: [\n {\n case: \"storm\",\n title: \"Winter storm\",\n cuts: [\n { part: \"grid\", title: \"Power outage\", duration: [[0, 1], [0.5, 0.5], [1, 0.36], [7, 0.013], [30, 0]], source: \"nrel-83092\" },\n { part: \"road\", title: \"Closed local road\", duration: [[0, 1], [1, 0.6], [3, 0.2], [10, 0]], source: \"sample\" },\n { part: \"water-main\", title: \"No water from the main\", duration: [[0, 1], [2, 0.3], [7, 0]], source: \"sample\" },\n ],\n leadSeconds: 86_400,\n },\n { case: \"fire\", title: \"Fire\", cuts: [] },\n ],\n priors: [\n { case: \"storm\", place: \"home\", perYear: 0.8, reach: 1, source: \"sample\", asOf: \"2025-12-01\" },\n { case: \"fire\", place: \"home\", perYear: 0.003, reach: 1, source: \"sample\", asOf: \"2025-12-01\" },\n ],\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwEA,SAAgB,UAAU,OAAuB,UAAoB,SAAsB,OAAqC;CAC9H,MAAM,QAAQ,IAAI,IAAI,MAAM,MAAM,KAAK,SAAS,KAAK,IAAI,CAAC;CAC1D,MAAM,UAAU,MAAM,QAAQ,SAAS,CAAC,MAAM,IAAI,IAAI,CAAC;CACvD,IAAI,QAAQ,SAAS,GAAG,MAAM,IAAI,WAAW,aAAa,QAAQ,KAAK,SAAS,IAAI,KAAK,EAAE,CAAC,CAAC,KAAK,IAAI,EAAE,0CAA0C;CAClJ,MAAM,eAAe,YAAY,UAAU,OAAO;CAClD,MAAM,QAAQ,aAAa,OAAO,QAAQ,IAAI,YAAY;CAC1D,MAAM,SAAS,IAAI,IAAI,KAAK;CAC5B,MAAM,OAAO,UAAU,OAAO,UAAU,YAAY,CAAC,CAAC,QAAQ,SAAS,OAAO,IAAI,KAAK,IAAI,CAAC;CAC5F,MAAM,UAAU,IAAI,IAAI,KAAK,KAAK,SAAS,KAAK,IAAI,CAAC;CACrD,MAAM,OAAO;EAAE,MAAM,SAAS;EAAM,IAAI,QAAQ;EAAI,MAAM,KAAK,KAAK,SAAS,KAAK,IAAI;EAAG,OAAO,CAAC,GAAG,MAAM,CAAC,CAAC,QAAQ,SAAS,CAAC,QAA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;GAAE;GACtC;IAAE,UAAU;IAAgB,QAAQ;GAAK;EAC3C;EACA,OAAO;GAAE,MAAM;GAAe,QAAQ;EAAK;CAC7C,CACF;CACA,OAAO,CACL;EACE,MAAM;EACN,OAAO;EACP,MAAM;GACJ;IAAE,MAAM;IAAQ,OAAO;IAAgB,UAAU;KAAC,CAAC,GAAG,CAAC;KAAG,CAAC,IAAK,EAAG;KAAG,CAAC,GAAG,GAAI;KAAG,CAAC,GAAG,IAAK;KAAG,CAAC,IAAI,CAAC;IAAC;IAAG,QAAQ;GAAa;GAC5H;IAAE,MAAM;IAAQ,OAAO;IAAqB,UAAU;KAAC,CAAC,GAAG,CAAC;KAAG,CAAC,GAAG,EAAG;KAAG,CAAC,GAAG,EAAG;KAAG,CAAC,IAAI,CAAC;IAAC;IAAG,QAAQ;GAAS;GAC9G;IAAE,MAAM;IAAc,OAAO;IAA0B,UAAU;KAAC,CAAC,GAAG,CAAC;KAAG,CAAC,GAAG,EAAG;KAAG,CAAC,GAAG,CAAC;IAAC;IAAG,QAAQ;GAAS;EAChH;EACA,aAAa;CACf,GACA;EAAE,MAAM;EAAQ,OAAO;EAAQ,MAAM,CAAC;CAAE,CAC1C;CACA,QAAQ,CACN;EAAE,MAAM;EAAS,OAAO;EAAQ,SAAS;EAAK,OAAO;EAAG,QAAQ;EAAU,MAAM;CAAa,GAC7F;EAAE,MAAM;EAAQ,OAAO;EAAQ,SAAS;EAAO,OAAO;EAAG,QAAQ;EAAU,MAAM;CAAa,CAChG;AACF"}
1
+ {"version":3,"file":"index.js","names":["horizonOf"],"sources":["../src/joint.ts","../src/best.ts","../src/stops.ts","../src/shortfall.ts","../src/sample.ts"],"sourcesContent":["import { type Objective, solveLexicographic } from \"@mark1russell7/linear\";\nimport { add, div, equals, mul, neg, ONE, type Rational, sign, toNumber, ZERO } from \"@mark1russell7/rational\";\nimport { type CaseOptions, caseDraws, caseStopped, drawDemand, storeAmounts } from \"./endurance.ts\";\nimport type { CaseCuts, Converter, EnduranceLayer, IsoDate } from \"./layer.ts\";\nimport { caseParts, deviceUse, drawBlock, fewestRow, Program, reachOf, valueAt } from \"./program.ts\";\nimport { addTo, dense, exact, type Row } from \"./rows.ts\";\n\n// The joint days: the largest count of days that a set of draws holds together, with the best share of the stores.\n// The query is a linear program over the totals of the span, with exact rationals (@mark1russell7/linear).\n\n/** The joint days of a set of draws in a case, with the share of the stores at the optimum. */\nexport interface JointDays {\n readonly case: string;\n readonly at: IsoDate;\n /**\n * The largest count of days that each draw of `plan` holds at the same time. It is `Infinity` when `plan` is empty,\n * or when the stores give each draw of `plan` without end.\n */\n readonly days: number;\n /** The needs of the set that take from the stores: the case stops their supply, and their demand is more than 0. The order is the order of `caseDraws`. */\n readonly plan: readonly string[];\n /** The needs of the set that take nothing from the stores, in the order of their codes. The case does not stop their supply, or their demand is 0. */\n readonly holds: readonly string[];\n /**\n * The amount of each resource that each draw of `plan` takes from the stores in `days`. The keys are the code of the need, then the code of the resource.\n * A take through a converter that makes a resource counts the inputs of the converter. A resource with no take is not in the record.\n * The record is empty when `days` is `Infinity`.\n */\n readonly takes: Readonly<Record<string, Readonly<Record<string, number>>>>;\n /**\n * The resources that limit `days`, in the order of their codes. Each one has a store in the layer, is an input of `plan` through each chain,\n * and has no stock left at the optimum. The list is empty when `days` is `Infinity`.\n */\n readonly binding: readonly string[];\n /** The count of runs of each converter at the optimum, by the `id` of the converter. A converter with no run is not in the record. */\n readonly runs: Readonly<Record<string, number>>;\n /**\n * The converters of the plan whose limit `perDay` stops more runs at the optimum, in the order of their `id`. A converter of the plan\n * gives a need of the plan, or makes an input of the plan through each chain.\n * The list is empty when `days` is `Infinity` or 0. Else it has each converter of the plan with a limit of 0.\n */\n readonly capped: readonly string[];\n}\n\n/**\n * This function gives the joint days of a set of draws. These are the largest count of days `d` at which each draw holds `d` days.\n * The draws hold at the same time, with the best share of the stores and of the runs of the converters.\n *\n * - The function solves a linear program over the totals of the span. Its variables are `d`, the take of each direct use,\n * the runs of each converter, and the share of each stock.\n * - Each draw of the plan gets `d` times its demand (`drawDemand`) from its direct uses and from the converters that give its need.\n * - The takes of each resource are not more than its stock (`storeAmounts` at `at`) plus the gifts of the converters that make it.\n * - A converter whose device stops gives nothing, and a store whose part stops gives nothing, as in `enduranceOf`.\n * - The runs of a converter with a limit `perDay` are not more than `perDay` times `devices` times `d`. The converters of one device share it, as in `enduranceOf`.\n * - A store counts with all of its amount when its due date is after `at`, as in `enduranceOf`. A due date in the span has no effect.\n * - After the largest `d`, a second objective takes the smallest sum of the shares of the stocks. Thus the takes have no waste.\n * - A third objective takes the fewest device-days of the converters. Thus the runs are not more than the plan uses.\n * - The draws that are not in the set are outside this plan. They take nothing in the program.\n * - A need of the set whose supply works, or whose demand is 0, holds without end. It goes in `holds`, as `enduranceOf` leaves it out.\n *\n * The take order of `enduranceOf` gives the stores to a higher draw first. This function gives one share for the whole set.\n * Thus a draw of the set can get fewer days here than alone, and a lower draw can get more.\n *\n * The program uses exact rationals, so the result has no error of the method. Only the change back to a number rounds.\n *\n * @param layer - The endurance layer\n * @param caseCuts - The case\n * @param options - The date, and the stack or the parts that are also down\n * @param needs - The codes of the needs of the draws of the set\n * @returns The joint days, the takes of each draw, the binding resources and the runs of each converter\n * @throws {RangeError} A code of `needs` is not the need of a draw of the layer, or a date is not `YYYY-MM-DD`.\n */\nexport function jointDays(layer: EnduranceLayer, caseCuts: CaseCuts, options: CaseOptions, needs: readonly string[]): JointDays {\n const known = new Set(layer.draws.map((draw) => draw.need));\n const unknown = needs.filter((need) => !known.has(need));\n if (unknown.length > 0) throw new RangeError(`The needs ${unknown.map((need) => `\"${need}\"`).join(\", \")} are not the needs of draws of the layer.`);\n const stoppedParts = caseStopped(caseCuts, options);\n const stock = storeAmounts(layer, options.at, stoppedParts);\n const wanted = new Set(needs);\n const plan = caseDraws(layer, caseCuts, stoppedParts).filter((draw) => wanted.has(draw.need));\n const planned = new Set(plan.map((draw) => draw.need));\n const base = { case: caseCuts.case, at: options.at, plan: plan.map((draw) => draw.need), holds: [...wanted].filter((need) => !planned.has(need)).sort() };\n const endless: JointDays = { ...base, days: Infinity, takes: {}, binding: [], runs: {}, capped: [] };\n if (plan.length === 0) return endless;\n\n const parts = caseParts(layer, stoppedParts, stock, planned);\n const program = new Program();\n const days = program.next();\n const blocks = plan.map((draw) => {\n const block = drawBlock(program, parts, draw);\n // The need of the draw: its gifts are not less than its demand times the days.\n const need: Row = new Map(block.gifts);\n addTo(need, days, neg(exact(drawDemand(draw, caseCuts))));\n program.push(need, \">=\", ZERO);\n return block;\n });\n // The limit of each device: the runs use `devices` times `d` device-days or less. A limit of 0 stops the converter.\n const runCols = blocks.flatMap((block) => [...block.runs]);\n const { limits, stopped } = deviceUse(runCols);\n for (const index of stopped) program.push(new Map([[index, ONE]]), \"<=\", ZERO);\n for (const limit of limits.values()) {\n const row: Row = new Map(limit.row);\n addTo(row, days, neg(exact(limit.devices)));\n program.push(row, \"<=\", ZERO);\n }\n // The shares of each stock are not more than the stock.\n for (const resource of parts.stocked) {\n const row: Row = new Map();\n for (const block of blocks) addTo(row, block.shares.get(resource) as number, ONE);\n program.push(row, \"<=\", exact(stock.get(resource) ?? 0));\n }\n\n const most: Row = new Map([[days, ONE]]);\n const least: Row = new Map();\n for (const block of blocks) for (const [resource, index] of block.shares) addTo(least, index, div(ONE, exact(stock.get(resource) ?? 1)));\n // The third objective takes the fewest device-days. Thus a converter whose inputs cost no stock does not give more runs than the plan uses,\n // and `runs` and `capped` have one value.\n const objectives: Objective[] = [\n { sense: \"max\", coefficients: dense(most, program.count) },\n { sense: \"min\", coefficients: dense(least, program.count) },\n { sense: \"min\", coefficients: dense(fewestRow(runCols), program.count) },\n ];\n const solved = solveLexicographic(program.constraints(), objectives);\n // The point 0 is feasible and the later objectives are not less than 0. So only an unbounded first stage has no optimum.\n if (solved.status !== \"optimal\") return endless;\n\n const x = solved.x;\n const takes: Record<string, Record<string, number>> = {};\n for (const block of blocks) {\n const record: Record<string, number> = {};\n for (const [resource, index] of block.shares) if (sign(x[index] ?? ZERO) > 0) record[resource] = toNumber(x[index] ?? ZERO);\n takes[block.draw.need] = record;\n }\n // A converter gives a need or a resource, so it is a cook or a maker, not the two.\n const total = new Map<Converter, Rational>();\n for (const [converter, index] of runCols) total.set(converter, add(total.get(converter) ?? ZERO, x[index] ?? ZERO));\n const runs: Record<string, number> = {};\n for (const [converter, value] of total) if (sign(value) > 0) runs[converter.id] = toNumber(value);\n\n const withStore = new Set(layer.stores.map((store) => store.resource));\n // The converters that the plan can use: the converters that give a need of the plan, and the makers of the resources of the closure.\n const { closure, reach } = reachOf(parts, planned);\n const binding = [...closure]\n .filter((resource) => withStore.has(resource))\n .filter((resource) => {\n // A resource with no live stock has no share, so its take is 0 and it is used up.\n const taken = blocks.reduce((sum, block) => {\n const index = block.shares.get(resource);\n return index === undefined ? sum : add(sum, x[index] ?? ZERO);\n }, ZERO);\n return equals(taken, exact(stock.get(resource) ?? 0));\n })\n .sort();\n const best = solved.values[0] ?? ZERO;\n const capped = sign(best) > 0\n ? [\n ...[...total.keys()].filter((converter) => converter.perDay !== undefined && !(converter.perDay > 0)),\n ...[...limits.values()].filter((limit) => equals(valueAt(limit.row, x), mul(exact(limit.devices), best))).flatMap((limit) => limit.converters),\n ]\n .filter((converter) => reach.has(converter))\n .map((converter) => converter.id)\n .sort()\n : [];\n return { ...base, days: toNumber(best), takes, binding, runs, capped };\n}\n","import { type Objective, solveLexicographic } from \"@mark1russell7/linear\";\nimport { add, div, equals, mul, neg, ONE, type Rational, sign, sub, toNumber, ZERO } from \"@mark1russell7/rational\";\nimport { type CaseOptions, caseDraws, caseStopped, drawDemand, storeAmounts } from \"./endurance.ts\";\nimport type { CaseCuts, Converter, Draw, DrawEndurance, Endurance, EnduranceLayer } from \"./layer.ts\";\nimport { type CaseParts, caseParts, deviceUse, drawBlock, type DrawBlock, fewestRow, Program, reachOf, valueAt } from \"./program.ts\";\nimport { addTo, dense, exact, type Row } from \"./rows.ts\";\n\n// The best endurance: the days of each draw with the best share of the stores, the most important level first.\n// Each step is a linear program over the totals of the spans, with exact rationals (@mark1russell7/linear).\n\n/** A draw whose days are fixed. */\ninterface Fixed {\n /** The span of the draw in the programs: its days, or 1 for a draw with no end. */\n readonly span: Rational;\n /** True for a draw that holds without end. It takes no stock, and its span is one day. */\n readonly endless: boolean;\n /** The device-days of each day that the draw keeps, by the key of the device. */\n readonly keep: ReadonlyMap<string, Rational>;\n /** The `id` of each converter whose limit stops more runs at the step that fixes the draw. */\n readonly capped: readonly string[];\n /** True for a draw that holds the horizon. */\n readonly atHorizon: boolean;\n}\n\n/** The options of `bestEndurance`: the options of a case, and a horizon. */\nexport interface BestOptions extends CaseOptions {\n /**\n * The horizon in days, more than 0. The default is no horizon. A draw holds the horizon at most, thus it keeps back\n * only the horizon times its demand. The rest of the stores goes to the lower levels. Use the target of a plan, for\n * example 14 days, to ask if each draw holds the target.\n */\n readonly horizon?: number | undefined;\n}\n\n/** This function gives the horizon as a rational, or undefined for no horizon. It throws a `RangeError` for a horizon that is not more than 0. */\nfunction horizonOf(horizon: number | undefined): Rational | undefined {\n if (horizon === undefined || horizon === Infinity) return undefined;\n if (!(horizon > 0) || !Number.isFinite(horizon)) throw new RangeError(`The horizon ${String(horizon)} is not a number of days more than 0.`);\n return exact(horizon);\n}\n\n/** A program of one step, with the indexes of its parts. */\ninterface Step {\n readonly program: Program;\n readonly blocks: readonly DrawBlock[];\n /** The column of the common days of the open draws. */\n readonly floor: number;\n /** The row `days - floor >= 0` of each open draw, by the code of its need. */\n readonly floors: ReadonlyMap<string, number>;\n /** The run columns of the open draws. */\n readonly openRuns: readonly (readonly [Converter, number])[];\n /** The device-days of the open draws for each device, with the device-days of each day that the fixed draws leave. */\n readonly shared: ReadonlyMap<string, { readonly row: Row; readonly room: Rational; readonly converters: readonly Converter[] }>;\n}\n\n/**\n * This function gives the days that each draw holds when a case stops its supply. The stores and the devices have their best share.\n * The result has the form of `enduranceOf`, so `caseShortfall` takes it.\n *\n * The share is lexicographic. The draws of the first level get their best days, then the draws of the next level get theirs, and so on.\n * In one level, the share is the best for the draw with the fewest days, then for the next draw, and so on (the leximin share).\n * Thus a draw of a level cannot take a store that another draw of the level needs more.\n *\n * - The function solves a sequence of linear programs over the totals of the spans. Each program has the days of the open draws\n * and their common floor. For each draw, it has the take of each direct use, the runs of each converter and the share of each stock.\n * - Each step takes the largest floor. A draw whose floor row has a dual value that is not 0 cannot get more days. The step fixes its days.\n * The dual values of the floor rows add to 1, so each step fixes one draw or more.\n * - A fixed draw keeps its days in each later step. Its share of the stocks can change, so a later draw can get a store that it does not need.\n * - The stores, the direct uses, the converters and the devices follow the rules of `jointDays`. A store counts with all of its amount when its due date is after `at`.\n * - A fixed draw keeps the device-days of each day that it uses at its step, for all the days of the later draws. This is the safe side, as in `enduranceOf`.\n * The exact share of a device between two spans is not a linear program: the device-days of a day are the runs over the span.\n * - A step with no largest floor gives the open draws no end. Each of them takes no stock, and keeps the fewest device-days of each day.\n * - At the end, a program takes the smallest sum of the shares of the stocks, each over its stock, then the fewest device-days.\n * These are the takes of the result. A resource in `binding` has no stock left at this point.\n * - A draw in `capped` used a device with no device-days left at the step that fixed it.\n * - With a horizon, the floor of each step is the horizon at most. A step whose floor is the horizon fixes each of its\n * open draws at the horizon, with `atHorizon`. Such a draw takes only the horizon times its demand. A draw with no\n * end also holds the horizon. With no horizon, the result is the same as before the option.\n *\n * The programs use exact rationals, so the result has no error of the method. Only the change back to a number rounds.\n * The fewest days of the first level are the joint days (`jointDays`) of the draws of that level.\n *\n * @param layer - The endurance layer\n * @param caseCuts - The case\n * @param options - The date, the stack or the parts that are also down, and the horizon\n * @returns The endurance of each draw whose supply stops\n * @throws {RangeError} A date is not `YYYY-MM-DD`, or the horizon is not more than 0.\n */\nexport function bestEndurance(layer: EnduranceLayer, caseCuts: CaseCuts, options: BestOptions): Endurance {\n const horizon = horizonOf(options.horizon);\n const stoppedParts = caseStopped(caseCuts, options);\n const stock = storeAmounts(layer, options.at, stoppedParts);\n const draws = caseDraws(layer, caseCuts, stoppedParts);\n const parts = caseParts(layer, stoppedParts, stock, new Set(draws.map((draw) => draw.need)));\n // The count of devices of each key. The gate refuses two counts for one device.\n const devices = new Map([...deviceUse([...parts.cooks, ...parts.makers].map((converter) => [converter, 0] as const)).limits].map(([key, limit]) => [key, limit.devices] as const));\n const fixed = new Map<string, Fixed>();\n\n for (const level of levelGroups(layer, draws)) {\n let open = level;\n while (open.length > 0) {\n const step = buildStep(parts, caseCuts, draws, fixed, open, devices, \"span\", horizon);\n const solved = solveLexicographic(step.program.constraints(), [\n { sense: \"max\", coefficients: dense(new Map([[step.floor, ONE]]), step.program.count) },\n { sense: \"min\", coefficients: dense(fewestRow(step.openRuns), step.program.count) },\n ]);\n if (solved.status !== \"optimal\") {\n if (solved.status === \"infeasible\") throw new Error(\"The step of the best endurance has no point. The point of the last step is a point of it.\");\n fixEndless(parts, caseCuts, draws, fixed, open, devices);\n break;\n }\n const floor = solved.values[0] ?? ZERO;\n const first = solved.stages[0]?.result;\n const dual = first?.status === \"optimal\" ? first.dual : [];\n const atHorizon = horizon !== undefined && equals(floor, horizon);\n let done = atHorizon ? open : open.filter((draw) => sign(dual[step.floors.get(draw.need) as number] ?? ZERO) !== 0);\n // The dual values of the floor rows add to 1. Thus `done` is not empty. The fallback fixes each open draw at the floor.\n if (done.length === 0) done = open;\n const full = new Set([...step.shared].filter(([, limit]) => equals(valueAt(limit.row, solved.x), mul(limit.room, floor))).map(([key]) => key));\n for (const draw of done) {\n const block = step.blocks.find((item) => item.draw.need === draw.need) as DrawBlock;\n const keep = new Map<string, Rational>();\n for (const [key, limit] of deviceUse(block.runs).limits) keep.set(key, sign(floor) > 0 ? div(valueAt(limit.row, solved.x), floor) : ZERO);\n const { reach } = reachOf(parts, new Set([draw.need]));\n const capped = sign(floor) > 0\n ? [...reach]\n .filter((converter) => converter.perDay !== undefined && (!(converter.perDay > 0) || [...full].some((key) => step.shared.get(key)?.converters.includes(converter))))\n .map((converter) => converter.id)\n .sort()\n : [];\n fixed.set(draw.need, { span: floor, endless: false, keep, capped, atHorizon });\n }\n const fixedNow = new Set(done.map((draw) => draw.need));\n open = open.filter((draw) => !fixedNow.has(draw.need));\n }\n }\n\n const needs: Record<string, DrawEndurance> = {};\n if (draws.length === 0) return { case: caseCuts.case, at: options.at, needs };\n const last = buildStep(parts, caseCuts, draws, fixed, [], devices, \"span\");\n const least: Row = new Map();\n for (const block of last.blocks) for (const [resource, index] of block.shares) addTo(least, index, div(ONE, exact(stock.get(resource) ?? 1)));\n const objectives: Objective[] = [\n { sense: \"min\", coefficients: dense(least, last.program.count) },\n { sense: \"min\", coefficients: dense(fewestRow(last.blocks.flatMap((block) => [...block.runs])), last.program.count) },\n ];\n const solved = solveLexicographic(last.program.constraints(), objectives);\n if (solved.status !== \"optimal\") throw new Error(\"The last program of the best endurance has no optimum. The point of the last step is a point of it.\");\n const withStore = new Set(layer.stores.map((store) => store.resource));\n for (const block of last.blocks) {\n const need = block.draw.need;\n const fix = fixed.get(need) as Fixed;\n if (fix.endless) {\n needs[need] = { days: Infinity, binding: [], takes: {} };\n continue;\n }\n const takes: Record<string, number> = {};\n for (const [resource, index] of block.shares) if (sign(solved.x[index] ?? ZERO) > 0) takes[resource] = toNumber(solved.x[index] ?? ZERO);\n const { closure } = reachOf(parts, new Set([need]));\n const binding = [...closure]\n .filter((resource) => withStore.has(resource))\n .filter((resource) => {\n // A resource with no live stock has no share, so its take is 0 and it is used up.\n const taken = last.blocks.reduce((sum, item) => {\n const index = item.shares.get(resource);\n return index === undefined ? sum : add(sum, solved.x[index] ?? ZERO);\n }, ZERO);\n return equals(taken, exact(stock.get(resource) ?? 0));\n })\n .sort();\n const days = toNumber(fix.span);\n needs[need] = { days, binding, takes, ...(fix.capped.length === 0 ? {} : { capped: fix.capped }), ...(fix.atHorizon ? { atHorizon: true as const } : {}) };\n }\n return { case: caseCuts.case, at: options.at, needs };\n}\n\n/** This function gives the draws of each level, in the order of `levels`. The draws of a level that is not in `levels` come last, together. */\nfunction levelGroups(layer: EnduranceLayer, draws: readonly Draw[]): Draw[][] {\n const rank = (draw: Draw): number => {\n const index = layer.levels.indexOf(draw.level);\n return index < 0 ? layer.levels.length : index;\n };\n const out: Draw[][] = [];\n let previous = -1;\n for (const draw of draws) {\n if (rank(draw) !== previous) out.push([]);\n previous = rank(draw);\n out[out.length - 1]?.push(draw);\n }\n return out;\n}\n\n/**\n * This function gives the program of one step. The fixed draws keep their spans and their device-days. The open draws have a common floor.\n *\n * - With `\"span\"`, each open draw has a column of its days, not less than the floor. Its runs share the device-days that the fixed draws leave, for the floor.\n * The device-days of each day are the runs over the span. A span not less than the floor uses fewer of them, so this is the safe side.\n * - With `\"day\"`, each open draw has a span of one day and takes no stock. Its runs share the device-days of one day.\n * - With a horizon, the floor is the horizon at most.\n */\nfunction buildStep(\n parts: CaseParts,\n caseCuts: CaseCuts,\n draws: readonly Draw[],\n fixed: ReadonlyMap<string, Fixed>,\n open: readonly Draw[],\n devices: ReadonlyMap<string, number>,\n mode: \"span\" | \"day\",\n horizon?: Rational,\n): Step {\n const program = new Program();\n const floor = program.next();\n if (horizon !== undefined) program.push(new Map([[floor, ONE]]), \"<=\", horizon);\n const opened = new Set(open.map((draw) => draw.need));\n const blocks: DrawBlock[] = [];\n const floors = new Map<string, number>();\n const openRuns: (readonly [Converter, number])[] = [];\n const kept = new Map<string, Rational>();\n for (const draw of draws) {\n const fix = fixed.get(draw.need);\n if (fix === undefined && !opened.has(draw.need)) continue;\n const endless = fix?.endless ?? mode === \"day\";\n const block = drawBlock(program, parts, draw, !endless);\n blocks.push(block);\n const demand = exact(drawDemand(draw, caseCuts));\n const need: Row = new Map(block.gifts);\n if (fix !== undefined) {\n program.push(need, \">=\", mul(demand, fix.span));\n const { limits, stopped } = deviceUse(block.runs);\n for (const index of stopped) program.push(new Map([[index, ONE]]), \"<=\", ZERO);\n for (const [key, limit] of limits) program.push(limit.row, \"<=\", mul(fix.keep.get(key) ?? ZERO, fix.span));\n for (const [key, value] of fix.keep) kept.set(key, add(kept.get(key) ?? ZERO, value));\n continue;\n }\n openRuns.push(...block.runs);\n if (mode === \"day\") {\n program.push(need, \">=\", demand);\n continue;\n }\n const days = program.next();\n addTo(need, days, neg(demand));\n program.push(need, \">=\", ZERO);\n floors.set(draw.need, program.push(new Map([[days, ONE], [floor, neg(ONE)]]), \">=\", ZERO));\n }\n const shared = new Map<string, { row: Row; room: Rational; converters: readonly Converter[] }>();\n const { limits, stopped } = deviceUse(openRuns);\n for (const index of stopped) program.push(new Map([[index, ONE]]), \"<=\", ZERO);\n for (const [key, limit] of limits) {\n const left = sub(exact(devices.get(key) ?? limit.devices), kept.get(key) ?? ZERO);\n const room = sign(left) > 0 ? left : ZERO;\n shared.set(key, { row: limit.row, room, converters: limit.converters });\n if (mode === \"day\") {\n program.push(limit.row, \"<=\", room);\n continue;\n }\n const row: Row = new Map(limit.row);\n addTo(row, floor, neg(room));\n program.push(row, \"<=\", ZERO);\n }\n for (const resource of parts.stocked) {\n const row: Row = new Map();\n for (const block of blocks) {\n const index = block.shares.get(resource);\n if (index !== undefined) addTo(row, index, ONE);\n }\n if (row.size > 0) program.push(row, \"<=\", exact(parts.stock.get(resource) ?? 0));\n }\n return { program, blocks, floor, floors, openRuns, shared };\n}\n\n/**\n * This function fixes the open draws with no end. Each open draw takes no stock, and keeps the fewest device-days of each day.\n * A step with no largest floor has a direction with no take of a stock, so this program has a point.\n */\nfunction fixEndless(parts: CaseParts, caseCuts: CaseCuts, draws: readonly Draw[], fixed: Map<string, Fixed>, open: readonly Draw[], devices: ReadonlyMap<string, number>): void {\n const step = buildStep(parts, caseCuts, draws, fixed, open, devices, \"day\");\n const solved = solveLexicographic(step.program.constraints(), [{ sense: \"min\", coefficients: dense(fewestRow(step.openRuns), step.program.count) }]);\n if (solved.status !== \"optimal\") throw new Error(\"The draws with no end of the best endurance have no point of one day.\");\n for (const draw of open) {\n const block = step.blocks.find((item) => item.draw.need === draw.need) as DrawBlock;\n const keep = new Map<string, Rational>();\n for (const [key, limit] of deviceUse(block.runs).limits) keep.set(key, valueAt(limit.row, solved.x));\n fixed.set(draw.need, { span: ONE, endless: true, keep, capped: [], atHorizon: false });\n }\n}\n","import { DEFAULT_MAX_SETS, stopSets, type Stack } from \"@mark1russell7/system-stack\";\n\n// The minimal stop sets of a supply from the structure of the needs. The index does not give this entry: `stopCurves` uses it.\n\n/**\n * This function gives the minimal sets of cuts that stop a supply, from the paths of the needs of the stack (`stopSets` of the core).\n * A set is a list of indexes of `parts`, from the smallest set. Two sets of one size are in the order of `minimalStops`.\n *\n * - `parts` has the part of each cut that counts. Two cuts of one part are two cuts: each one stops what the part stops.\n * - A cut of the supply stops it alone. The other sets come from `stopSets` with the cut parts as `among`, so no other part can fail.\n * - The parts of `down` are down for the full event. The caller makes sure that they do not stop the supply with no cut.\n * - The result is `undefined` when the search passes its budget, or when the sets of cuts are more than `maxSets`.\n *\n * @param stack - The base stack\n * @param supply - The part of the supply of a draw\n * @param parts - The part of each cut that counts\n * @param down - The parts that are down for the full event\n * @param maxSets - The largest count of sets in one step of the search, and of the sets of cuts (`maxSets` of `stopSets`)\n */\nexport function stackStops(stack: Stack, supply: string, parts: readonly string[], down: readonly string[] = [], maxSets: number = DEFAULT_MAX_SETS): number[][] | undefined {\n const cutsOf = new Map<string, number[]>();\n for (const [index, part] of parts.entries()) cutsOf.set(part, [...(cutsOf.get(part) ?? []), index]);\n const own = (cutsOf.get(supply) ?? []).map((index) => [index]);\n const among = [...cutsOf.keys()].filter((part) => part !== supply);\n const found = stopSets(stack, supply, { down, among, size: among.length, maxSets });\n if (found.kind === \"budget\") return undefined;\n // The empty set: the supply is not in the stack, or it does not work in the base stack.\n // In both, `stopped` of the core does not count it as stopped, so only a cut of the supply stops it.\n if (found.sets.some((set) => set.length === 0)) return own;\n const out = [...own];\n for (const set of found.sets) {\n // Each choice of one cut for each part of the set is a minimal set of cuts.\n let choices: number[][] = [[]];\n for (const part of set) {\n const cuts = cutsOf.get(part) ?? [];\n if (choices.length * cuts.length + out.length > maxSets) return undefined;\n choices = choices.flatMap((choice) => cuts.map((cut) => [...choice, cut]));\n }\n out.push(...choices.map((choice) => choice.sort((x, y) => x - y)));\n }\n return out.sort(byMask);\n}\n\n/** The order of `minimalStops`: the smaller set first, then the set whose largest different index is smaller. */\nfunction byMask(a: readonly number[], b: readonly number[]): number {\n if (a.length !== b.length) return a.length - b.length;\n for (let index = a.length - 1; index >= 0; index -= 1) {\n const difference = (a[index] ?? 0) - (b[index] ?? 0);\n if (difference !== 0) return difference;\n }\n return 0;\n}\n","import { type OrderedRing, pathSetReliability, stronglyConnectedComponents } from \"@mark1russell7/collections/graph\";\nimport { DEFAULT_MAX_SETS, neededParts, survivalAt, weakestBound, type CutBound, type PathOptions } from \"@mark1russell7/system-stack\";\nimport { bestEndurance } from \"./best.ts\";\nimport { caseDraws, caseStopped, enduranceOf, type CaseOptions } from \"./endurance.ts\";\nimport type { CaseCuts, Draw, Endurance, EnduranceLayer, Prior, Survival } from \"./layer.ts\";\nimport { stackStops } from \"./stops.ts\";\n\n// The shortfall: the user-days in which a draw does not get its need, for one case and for one year.\n\n/** The read of a curve at a time is in the core since system-stack 0.1.13. This package gives it again, so its API does not change. */\nexport { survivalAt };\n\n/**\n * This function gives the expected days of a cut after a time, up to a horizon: `E[max(0, min(D, to) - from)]`.\n * It is the area under the curve from `from` to `to`. The curve is linear between its points, so the area is exact.\n * With no horizon, the area goes to the end of the curve.\n */\nexport function tailDays(curve: Survival, from: number, to: number = Infinity): number {\n let area = 0;\n for (let index = 1; index < curve.length; index += 1) {\n const [t0] = curve[index - 1] ?? [0, 1];\n const [t1] = curve[index] ?? [0, 0];\n const start = Math.max(t0, from);\n const end = Math.min(t1, to);\n if (start < end) area += ((survivalAt(curve, start) + survivalAt(curve, end)) / 2) * (end - start);\n }\n return area;\n}\n\n/**\n * The options of a shortfall: the stack or the parts that are also down, as for `enduranceOf`, and a horizon.\n * With a horizon of `h` days, the shortfall counts only the first `h` days of each cut. A draw that holds `h` days has no shortfall.\n * Thus a plan can aim at a target, for example 14 days and then 90 days.\n */\n/**\n * The options of `stopCurves`. With a stack, `maxSets` is the budget of the search of the needs (`stopSets` of the core).\n * When the search passes it, `minimalStops` gives the sets.\n */\nexport interface StopCurveOptions extends Pick<CaseOptions, \"stack\" | \"down\">, Pick<PathOptions, \"maxSets\"> {\n /** The budget of `independentStop` for the curve of each draw, a whole number from 1. The default is `INDEPENDENT_MAX_WORK`. */\n readonly maxWork?: number | undefined;\n}\n\nexport interface ShortfallOptions extends StopCurveOptions {\n /** The horizon in days, more than 0. The default is no horizon. */\n readonly horizon?: number | undefined;\n}\n\nfunction horizonOf(options: ShortfallOptions): number {\n const horizon = options.horizon ?? Infinity;\n if (!(horizon > 0)) throw new RangeError(`The horizon ${String(options.horizon)} is not a number of days more than 0.`);\n return horizon;\n}\n\nfunction budgetsOf(options: StopCurveOptions): { readonly maxSets: number; readonly maxWork: number } {\n const maxSets = options.maxSets ?? DEFAULT_MAX_SETS;\n if (!Number.isInteger(maxSets) || maxSets < 1) throw new RangeError(`The option maxSets is ${String(options.maxSets)}: it is not a whole number from 1.`);\n const maxWork = options.maxWork ?? INDEPENDENT_MAX_WORK;\n if (!Number.isInteger(maxWork) || maxWork < 1) throw new RangeError(`The option maxWork is ${String(options.maxWork)}: it is not a whole number from 1.`);\n return { maxSets, maxWork };\n}\n\n/**\n * This function gives the days at which the chance of the curve falls to `chance`. With `0.1`, it is the 90th percentile of the duration.\n * When the curve does not fall to `chance`, the result is `Infinity`.\n */\nexport function survivalQuantile(curve: Survival, chance: number): number {\n for (let index = 1; index < curve.length; index += 1) {\n const [t0, p0] = curve[index - 1] ?? [0, 1];\n const [t1, p1] = curve[index] ?? [0, 0];\n if (p0 <= chance) return t0;\n if (p1 <= chance) return t0 + ((p0 - chance) * (t1 - t0)) / (p0 - p1);\n }\n return Infinity;\n}\n\n/** This function gives the chance that a case reaches its place one or more times in one year: `1 - exp(-perYear * reach)`. */\nexport function yearChance(prior: Prior): number {\n return 1 - Math.exp(-prior.perYear * prior.reach);\n}\n\n/** This function gives the expected count of the events of a case at its place in one year: `perYear * reach`. */\nexport function yearRate(prior: Prior): number {\n return prior.perYear * prior.reach;\n}\n\n/** This function gives the times at which a curve of the result can bend: each point of each curve, and each crossing of two curves. */\nfunction bendTimes(curves: readonly Survival[]): number[] {\n const times = [...new Set(curves.flatMap((curve) => curve.map(([days]) => days)))].sort((x, y) => x - y);\n const out = new Set(times);\n for (let index = 1; index < times.length; index += 1) {\n const t0 = times[index - 1] ?? 0;\n const t1 = times[index] ?? 0;\n for (const [i, a] of curves.entries()) {\n for (const b of curves.slice(i + 1)) {\n const d0 = survivalAt(a, t0) - survivalAt(b, t0);\n const d1 = survivalAt(a, t1) - survivalAt(b, t1);\n if (d0 * d1 < 0) out.add(t0 + ((t1 - t0) * d0) / (d0 - d1));\n }\n }\n }\n return [...out].sort((x, y) => x - y);\n}\n\n/**\n * This function makes a survival curve from a chance at each time. It stops at the first chance of 0, and it removes an increase of rounding.\n *\n * @throws RangeError when the chance at the last time is more than 0, as for curves that do not end at a chance of 0\n */\nfunction curveFrom(times: readonly number[], chanceAt: (days: number) => number): Survival {\n const out: [number, number][] = [];\n for (const days of times) {\n const chance = Math.min(out[out.length - 1]?.[1] ?? 1, chanceAt(days));\n out.push([days, chance]);\n if (chance === 0) return out;\n }\n throw new RangeError(\"The curves do not fall to a chance of 0 at their last point.\");\n}\n\n/**\n * This function gives the curve of a stop of some cuts when one event makes each cut longer together.\n * At each time, the chance is the largest `s` at which the cuts with a chance of `s` or more stop the supply.\n *\n * - When any one cut stops the supply, the result is the largest chance of the curves (`longestStop`).\n * - When the supply needs `any` of two parts, the stop ends with the shorter of the two cuts.\n * - Between two times of `bendTimes` the order of the curves does not change. So the result is linear between its points.\n * - When no set of cuts stops the supply, the result is `[[0, 0]]`. This curve does not start at `[0, 1]`, so `checkEndurance` refuses it.\n *\n * The result is not a limit. When the cuts are independent, a stop of two cuts in series can be longer. A stop through a need of `any` can be shorter.\n *\n * @param curves - The curves of the cuts, each one good for `checkEndurance`\n * @param stops - This function tells if the cuts of a list of indexes stop the supply. A larger list stops it when a smaller list does.\n * @throws RangeError when a curve does not end at a chance of 0\n */\nexport function eventStop(curves: readonly Survival[], stops: (cuts: readonly number[]) => boolean): Survival {\n return curveFrom(bendTimes(curves), (days) => {\n const chances = curves.map((curve) => survivalAt(curve, days));\n for (const level of [...new Set(chances)].sort((x, y) => y - x)) {\n if (stops(chances.flatMap((chance, index) => (chance >= level ? [index] : [])))) return level;\n }\n return 0;\n });\n}\n\n/**\n * This function gives the curve of the longest of some stops: at each time, the largest chance of the curves.\n * It is `eventStop` when any one cut stops the supply.\n *\n * @param curves - The curves, each one good for `checkEndurance`\n * @throws RangeError when there is no curve, or when a curve does not end at a chance of 0\n */\nexport function longestStop(curves: readonly Survival[]): Survival {\n const first = curves[0];\n if (first === undefined) throw new RangeError(\"longestStop needs one or more curves.\");\n return curves.length === 1 ? first : eventStop(curves, (cuts) => cuts.length > 0);\n}\n\n/**\n * The largest count of cuts for which `minimalStops` examines each set, and for which `independentStop` adds the chance of each state.\n * With a stack, `stopCurves` finds the minimal sets from the needs, so a larger count of cuts can have exact sets.\n */\nexport const MINIMAL_STOP_CUTS = 12;\n\n/**\n * This function gives the minimal sets of cuts that stop the supply: each set stops it, and no smaller part of a set stops it.\n * With more than `MINIMAL_STOP_CUTS` cuts, the result is `undefined`.\n */\nexport function minimalStops(count: number, stops: (cuts: readonly number[]) => boolean): number[][] | undefined {\n if (count > MINIMAL_STOP_CUTS) return undefined;\n const found: number[][] = [];\n const masks: number[] = [];\n const all = Array.from({ length: 1 << count }, (_, mask) => mask).sort((x, y) => popCount(x) - popCount(y) || x - y);\n for (const mask of all) {\n if (mask === 0 || masks.some((other) => (other & mask) === other)) continue;\n const cuts = Array.from({ length: count }, (_, index) => index).filter((index) => (mask >> index) & 1);\n if (!stops(cuts)) continue;\n masks.push(mask);\n found.push(cuts);\n }\n return found;\n}\n\nfunction popCount(mask: number): number {\n let total = 0;\n for (let rest = mask; rest > 0; rest &= rest - 1) total += 1;\n return total;\n}\n\n/**\n * This function gives an upper limit of the curve of a stop for each dependence of the cuts.\n * At each time it is `min(1, sum over the minimal sets of the smallest chance of the set)`.\n * With no minimal sets, as for too many cuts, it is `min(1, sum of the chances)`.\n *\n * @param curves - The curves of the cuts\n * @param sets - The minimal sets of `minimalStops`, or `undefined`\n * @throws RangeError when a curve does not end at a chance of 0\n */\nexport function upperStop(curves: readonly Survival[], sets: readonly (readonly number[])[] | undefined): Survival {\n const groups = sets ?? curves.map((_, index) => [index]);\n const sum = (days: number): number => groups.reduce((total, set) => total + Math.min(...set.map((index) => survivalAt(curves[index] ?? [], days))), 0);\n // The sum is linear between two times of bendTimes. A point where it falls through 1 is a bend of min(1, sum).\n const times = bendTimes(curves);\n const bends = new Set(times);\n for (let index = 1; index < times.length; index += 1) {\n const t0 = times[index - 1] ?? 0;\n const t1 = times[index] ?? 0;\n const s0 = sum(t0) - 1;\n const s1 = sum(t1) - 1;\n if (s0 * s1 < 0) bends.add(t0 + ((t1 - t0) * s0) / (s0 - s1));\n }\n return curveFrom([...bends].sort((x, y) => x - y), (days) => Math.min(1, sum(days)));\n}\n\n/** The largest difference between `independentStop` and the true chance of a stop of independent cuts, at each time. */\nexport const INDEPENDENT_TOLERANCE = 1e-6;\n\n/**\n * The default budget of `independentStop` for its groups of more than `MINIMAL_STOP_CUTS` cuts.\n * The budget counts the steps of the expansion times the count of points of the curve.\n * It is near the work of the sum over the states of 12 cuts.\n */\nexport const INDEPENDENT_MAX_WORK: number = 2 ** 26;\n\n/**\n * This function gives the curve of a stop of some cuts when the cuts are independent.\n * At each time `t`, the supply is stopped when the cuts that are still on contain a minimal set.\n * Its chance is a sum over each set of cuts that stops the supply.\n * Each term is the product of `s(t)` for the cuts that are on, and of `1 - s(t)` for the other cuts.\n *\n * - When any one cut stops the supply, the result is `1 - prod(1 - s)`. It is not less than the longest cut (`eventStop`).\n * - When the supply needs `any` of two parts, the stop of the two is `s1 * s2`. It is not more than the shorter cut.\n * - The result is not more than `upperStop` of the same sets, because `upperStop` is a limit for each dependence.\n * - Between two points of the curves the chance is a polynomial, not a line. The function splits each such segment into equal pieces.\n * The chance is linear in each `s`, and each mixed second derivative is between -1 and 1.\n * Thus `|f''| <= (sum |s'|)^2 - sum s'^2`, and the line of a piece of length `h` is within `h^2 |f''| / 8` of the chance.\n * The count of pieces keeps each line within `INDEPENDENT_TOLERANCE`. With a margin of 10 %, the count of points is less than `n / sqrt(7.2 * INDEPENDENT_TOLERANCE)` plus the segments, for `n` cuts.\n *\n * - Up to `MINIMAL_STOP_CUTS` cuts in the sets, the function adds the chance of each of the 2 to the power of that count of states.\n * - Two groups of cuts that share no set are independent, so the chance that the supply works is the product over the groups.\n * For example, 20 stages of 2 feeds give 20 groups of 2 cuts.\n * - In a group of more than `MINIMAL_STOP_CUTS` cuts, it uses the Shannon expansion of `pathSetReliability` of collections.\n * The expansion merges two states with the same sets left, and it drops a set that holds another set.\n * - The expansion is exponential in the worst case. The groups share one budget, `maxWork`.\n * When the steps of the expansions times the count of points of the curve pass it, the result is `undefined`.\n *\n * @param curves - The curves of the cuts, each one good for `checkEndurance`\n * @param sets - The minimal sets of the cuts. With `undefined`, as for no minimal sets, the result is `undefined`. With no sets, it is `[[0, 0]]`\n * @param maxWork - The budget of the expansions of the groups of more than `MINIMAL_STOP_CUTS` cuts, a whole number from 1. The default is `INDEPENDENT_MAX_WORK`\n * @throws RangeError when a curve does not end at a chance of 0, or for a bad `maxWork`\n */\nexport function independentStop(curves: readonly Survival[], sets: readonly (readonly number[])[] | undefined, maxWork: number = INDEPENDENT_MAX_WORK): Survival | undefined {\n if (!Number.isInteger(maxWork) || maxWork < 1) throw new RangeError(`The budget maxWork is ${String(maxWork)}: it is not a whole number from 1.`);\n if (sets === undefined) return undefined;\n // With no set, no cuts stop the supply, as for `eventStop` and `upperStop`.\n if (sets.length === 0) return [[0, 0]];\n // Only the cuts of a set change the chance. Their place in `used` is their index in the sets of the cuts that count.\n const used = [...new Set(sets.flat())].sort((x, y) => x - y);\n const usedCurves = used.map((index) => curves[index] ?? []);\n const usedSets = sets.map((set) => set.map((index) => used.indexOf(index)));\n const points = independentPoints(usedCurves);\n // Two groups of cuts that share no set are independent: the supply works when it works in each group.\n const groupChances: ((days: number) => number)[] = [];\n // The expansions of all groups share one budget.\n let work = maxWork;\n for (const group of cutGroups(used.length, usedSets)) {\n const curvesOf = group.map((index) => usedCurves[index] ?? []);\n const setsOf = usedSets.filter((set) => group.includes(set[0] ?? -1)).map((set) => set.map((index) => group.indexOf(index)));\n // Up to MINIMAL_STOP_CUTS cuts, the sum over the states is exact with a fixed cost. Past them, the expansion is exact within its budget.\n if (group.length <= MINIMAL_STOP_CUTS) {\n groupChances.push(stateChance(curvesOf, setsOf));\n continue;\n }\n const expanded = expandedChances(curvesOf, setsOf, points, work);\n if (expanded === undefined) return undefined;\n work -= expanded.steps * points.length;\n const chanceOf = new Map(points.map((days, index) => [days, expanded.chances[index] ?? 0]));\n groupChances.push((days) => {\n const chance = chanceOf.get(days);\n if (chance === undefined) throw new Error(`The expansion has no chance at ${String(days)} days.`);\n return chance;\n });\n }\n // With one group, the chance of the group is the result, with no rounding of 1 - (1 - chance).\n const [only] = groupChances;\n if (groupChances.length === 1 && only !== undefined) return curveFrom(points, only);\n return curveFrom(points, (days) => Math.min(1, Math.max(0, 1 - groupChances.reduce((works, chanceAt) => works * (1 - chanceAt(days)), 1))));\n}\n\n/** The groups of the cuts `0` to `count - 1`: two cuts are in one group when a chain of sets joins them. Each set has its cuts in one group. */\nfunction cutGroups(count: number, sets: readonly (readonly number[])[]): number[][] {\n const next = Array.from({ length: count }, () => new Set<number>());\n // A cycle through the cuts of each set joins them both ways, so the strongly connected components are the groups.\n for (const set of sets) for (const [at, index] of set.entries()) next[index]?.add(set[(at + 1) % set.length] ?? index);\n return stronglyConnectedComponents(\n Array.from({ length: count }, (_, index) => index),\n (index) => next[index] ?? [],\n );\n}\n\n/** The times of `independentStop`: the points of the curves, and the pieces that keep each line within `INDEPENDENT_TOLERANCE`. */\nfunction independentPoints(curves: readonly Survival[]): number[] {\n const times = [...new Set(curves.flatMap((curve) => curve.map(([days]) => days)))].sort((x, y) => x - y);\n const points: number[] = [];\n for (const [index, t1] of times.entries()) {\n const t0 = times[index - 1];\n if (t0 !== undefined) {\n const h = t1 - t0;\n const slopes = curves.map((curve) => Math.abs(survivalAt(curve, t1) - survivalAt(curve, t0)) / h);\n const sum = slopes.reduce((total, slope) => total + slope, 0);\n const bound = Math.max(0, sum * sum - slopes.reduce((total, slope) => total + slope * slope, 0));\n // A margin of 10 % keeps the rounding of the chance under the tolerance.\n const pieces = Math.ceil(h * Math.sqrt(bound / (8 * 0.9 * INDEPENDENT_TOLERANCE)));\n for (let piece = 1; piece < pieces; piece += 1) {\n const days = t0 + (h * piece) / pieces;\n // Two times that are next to each other as floats have no time between them.\n if (days > (points[points.length - 1] ?? t0) && days < t1) points.push(days);\n }\n }\n points.push(t1);\n }\n return points;\n}\n\n/** The chance of a stop at a time, as the sum over each state of `MINIMAL_STOP_CUTS` cuts or fewer. Bit k of a state is 1 when cut k is on. */\nfunction stateChance(curves: readonly Survival[], sets: readonly (readonly number[])[]): (days: number) => number {\n const setMasks = sets.map((set) => set.reduce((mask, index) => mask | (1 << index), 0));\n const stopping = Array.from({ length: 1 << curves.length }, (_, mask) => setMasks.some((set) => (set & mask) === set));\n const states = new Float64Array(1 << curves.length);\n return (days) => {\n // The chance of each state of the cuts, one cut at a time.\n states[0] = 1;\n let length = 1;\n for (const curve of curves) {\n const on = survivalAt(curve, days);\n for (let mask = 0; mask < length; mask += 1) {\n const chance = states[mask] ?? 0;\n states[mask + length] = chance * on;\n states[mask] = chance * (1 - on);\n }\n length *= 2;\n }\n let total = 0;\n for (let mask = 0; mask < length; mask += 1) if (stopping[mask]) total += states[mask] ?? 0;\n return Math.min(1, Math.max(0, total));\n };\n}\n\n/** The count of times in one expansion of `expandedChances`: the length of the vectors of its ring. */\nconst EXPANSION_WIDTH = 64;\n\n/**\n * The ring of the vectors of `width` chances, one for each time, for `pathSetReliability` of collections.\n * Each operation is on each time alone. In the order, `a` is less than `b` when it is less or equal at each time, and not equal.\n */\nfunction vectorRing(width: number): OrderedRing<Float64Array> {\n const zip = (a: Float64Array, b: Float64Array, op: (x: number, y: number) => number): Float64Array => {\n const out = new Float64Array(width);\n for (let index = 0; index < width; index += 1) out[index] = op(a[index] ?? 0, b[index] ?? 0);\n return out;\n };\n return {\n zero: new Float64Array(width),\n one: new Float64Array(width).fill(1),\n add: (a, b) => zip(a, b, (x, y) => x + y),\n sub: (a, b) => zip(a, b, (x, y) => x - y),\n mul: (a, b) => zip(a, b, (x, y) => x * y),\n compare: (a, b) => {\n let less = false;\n let more = false;\n for (let index = 0; index < width; index += 1) {\n const [x, y] = [a[index] ?? 0, b[index] ?? 0];\n if (x < y) less = true;\n else if (x > y) more = true;\n else if (x !== y) return Number.NaN;\n }\n return less ? (more ? Number.NaN : -1) : more ? 1 : 0;\n },\n };\n}\n\n/**\n * The chance of a stop at each point, from the Shannon expansion of `pathSetReliability`. A set works when each of its cuts is on.\n * One call gives `EXPANSION_WIDTH` points. When the steps of one expansion times the count of points pass `maxWork`, the result is `undefined`.\n * Else `steps` is the count of steps of one expansion.\n */\nfunction expandedChances(\n curves: readonly Survival[],\n sets: readonly (readonly number[])[],\n points: readonly number[],\n maxWork: number,\n): { readonly chances: number[]; readonly steps: number } | undefined {\n const maxSteps = Math.floor(maxWork / points.length);\n if (maxSteps < 1) return undefined;\n const out: number[] = [];\n let steps = 0;\n for (let start = 0; start < points.length; start += EXPANSION_WIDTH) {\n const times = points.slice(start, start + EXPANSION_WIDTH);\n const chances = curves.map((curve) => Float64Array.from(times, (days) => survivalAt(curve, days)));\n const result = pathSetReliability(sets, chances, vectorRing(times.length), { maxSteps });\n // Each call has the same sets, so the first call tells if the expansion is in the budget.\n if (result.kind === \"budget\") return undefined;\n steps = result.steps;\n for (const chance of result.value) out.push(Math.min(1, Math.max(0, chance)));\n }\n return { chances: out, steps };\n}\n\n/**\n * The curves of the stop of a draw. `event` is for one event that makes each cut longer together, and `independent` is for independent cuts.\n * `upper` is an upper limit for each dependence.\n */\nexport interface StopCurves {\n readonly event: Survival;\n /** The stop when the cuts are independent (`independentStop`). When `independentUpper` is true, it is `upper`. */\n readonly independent: Survival;\n readonly upper: Survival;\n /**\n * This is true when `upper` is the sum of the curves of the cuts that count, because the query has no minimal sets.\n * With a stack, the search of the needs passed its budget. With no stack, more than `MINIMAL_STOP_CUTS` cuts count.\n */\n readonly coarse: boolean;\n /** This is true when `independent` is `upper`: `coarse` is true, or the expansion of `independentStop` passed its budget. */\n readonly independentUpper: boolean;\n /**\n * The weakest bound (`weakestBound` of the core) of the curves of the cuts that the stop uses. Since 0.8.4.\n * With minimal sets, the stop uses the cuts of the sets. With no minimal sets, it uses each cut with a curve.\n * Each of the three curves does not decrease when a cut lasts longer, so it has this bound.\n */\n readonly bound: CutBound;\n}\n\n/** This function gives the parts of the stack that are down for a list of cut indexes. A case uses one memo for each of its draws. */\ntype StoppedOf = (cuts: readonly number[]) => ReadonlySet<string>;\n\nfunction stoppedMemo(caseCuts: CaseCuts, options: Pick<CaseOptions, \"stack\" | \"down\">): StoppedOf {\n const memo = new Map<string, ReadonlySet<string>>();\n return (cuts) => {\n const key = cuts.join(\",\");\n let found = memo.get(key);\n if (found === undefined) {\n found = caseStopped({ ...caseCuts, cuts: cuts.flatMap((index) => caseCuts.cuts[index] ?? []) }, options);\n memo.set(key, found);\n }\n return found;\n };\n}\n\n/** This function gives the parts whose cut can stop a supply: the supply, and each part that it needs through the stack. */\nfunction supplyReach(supply: string, options: Pick<CaseOptions, \"stack\">): Set<string> {\n const reach = options.stack === undefined ? new Set<string>() : neededParts(options.stack, supply);\n reach.add(supply);\n return reach;\n}\n\nfunction stopCurvesWith(caseCuts: CaseCuts, draw: Draw, options: StopCurveOptions, stoppedOf: StoppedOf): StopCurves | undefined {\n const reach = supplyReach(draw.supply, options);\n const relevant = caseCuts.cuts.flatMap((cut, index) => (reach.has(cut.part) ? [index] : []));\n const stops = (cuts: readonly number[]): boolean => stoppedOf(cuts.map((index) => relevant[index] ?? -1)).has(draw.supply);\n if (stops([])) return undefined;\n if (!stops(relevant.map((_, index) => index))) return undefined;\n const given = relevant.map((index) => caseCuts.cuts[index]?.duration);\n // With a stack, the needs give the minimal sets. When their search passes its budget, the sets of each list of cuts are the check.\n const parts = relevant.map((index) => caseCuts.cuts[index]?.part ?? \"\");\n const structural = options.stack === undefined ? undefined : stackStops(options.stack, draw.supply, parts, options.down, budgetsOf(options).maxSets);\n const sets = structural ?? minimalStops(given.length, stops);\n // The stop has no curve when a cut with no curve can be part of it. With no minimal sets, the query cannot tell.\n const unsourced = given.flatMap((curve, index) => (curve === undefined ? [index] : []));\n if (unsourced.length > 0 && (sets === undefined || sets.some((set) => set.some((index) => unsourced.includes(index))))) return undefined;\n // A cut with no curve is in no minimal set here, so it does not change a stop. The curves do not include it.\n const kept = given.flatMap((curve, index) => (curve === undefined ? [] : [index]));\n const curves = kept.map((index) => given[index] ?? []);\n const keptStops = (cuts: readonly number[]): boolean => stops(cuts.map((index) => kept[index] ?? -1));\n const keptSets = sets?.map((set) => set.map((index) => kept.indexOf(index)));\n const upper = upperStop(curves, keptSets);\n const independent = independentStop(curves, keptSets, budgetsOf(options).maxWork);\n // A cut in no minimal set does not change a stop, so its bound does not weaken the bound of the stop.\n const used = sets === undefined ? kept : kept.filter((index) => sets.some((set) => set.includes(index)));\n const bound = weakestBound(used.map((index) => caseCuts.cuts[relevant[index] ?? -1]?.bound ?? \"law\"));\n return { event: eventStop(curves, keptStops), independent: independent ?? upper, upper, coarse: keptSets === undefined, independentUpper: independent === undefined, bound };\n}\n\n/**\n * This function gives the curves of the duration of the stop of a draw, or `undefined` when the query has no curve.\n *\n * - A set of cuts stops the supply when the supply cannot work without the cut parts, through the needs of the stack.\n * - Only the cuts of the supply, and of the parts that it needs through the stack, count. Another cut does not change the curves.\n * - The parts of `down` are down for the full event. When they stop the supply with no cut, the query has no curve.\n * - With a stack, the minimal sets come from the paths of the needs (`stopSets` of the core), so the count of cuts has no limit of `MINIMAL_STOP_CUTS`.\n * When that search passes its budget (the option `maxSets`), `minimalStops` examines each set of up to `MINIMAL_STOP_CUTS` cuts.\n * - A cut with no `duration` gives no curve when it is in a minimal set, or when the query has no minimal sets.\n * - `event` is `eventStop`. `independent` is `independentStop`, and `upper` is `upperStop`, over the minimal sets of the cuts that count.\n * - With no minimal sets, `upper` is the sum of the curves, `independent` is `upper`, and `coarse` is true.\n * - When the expansion of `independentStop` passes its budget, `independent` is `upper`, and `independentUpper` is true.\n * - `bound` is the weakest bound of the curves of the cuts that the stop uses. A cut with no `bound` has a law.\n */\nexport function stopCurves(caseCuts: CaseCuts, draw: Draw, options: StopCurveOptions = {}): StopCurves | undefined {\n budgetsOf(options);\n return stopCurvesWith(caseCuts, draw, options, stoppedMemo(caseCuts, options));\n}\n\n/** The shortfall of each level, in user-days, and the draws that the query cannot read. */\nexport interface Shortfall {\n /**\n * The user-days of each level of the layer, when one event makes each cut longer together. The query does not add two levels.\n * This value is not a limit. The true value can be more or less. `upper` is the limit.\n */\n readonly levels: Readonly<Record<string, number>>;\n /** The user-days of each level when the cuts are independent (`StopCurves.independent`). This value is not more than `upper`. */\n readonly independent: Readonly<Record<string, number>>;\n /** The upper limit of the user-days of each level, for each dependence of the cuts. A gate of a high level can use it. */\n readonly upper: Readonly<Record<string, number>>;\n /**\n * The needs of the draws whose stop has no curve (`stopCurves`).\n * The query has no curve of their duration, so their shortfall is not in `levels`. A gate shows them as no read.\n */\n readonly unread: readonly string[];\n /** The needs of the draws whose `upper` is coarse (`StopCurves.coarse`). A gate on `upper` shows them. */\n readonly coarse: readonly string[];\n /** The needs of the draws whose `independent` is `upper` (`StopCurves.independentUpper`). A gate on `independent` shows them. */\n readonly independentUpper: readonly string[];\n /**\n * The bound of the shortfall: the weakest bound (`weakestBound` of the core) of the curves that the query uses. Since 0.8.4.\n * The shortfall does not decrease when a cut lasts longer. So with `upper`, each value is too high or equal, and with `lower` too low or equal.\n * With `none`, a value can be too high or too low.\n *\n * A draw in `unread` and a case that adds 0 do not change the bound. With no curve, the bound is `law`.\n * The bound is for each of `levels`, `independent` and `upper`, each with its own rule of the dependence of the cuts.\n */\n readonly bound: CutBound;\n}\n\nfunction zeroLevels(layer: EnduranceLayer): Record<string, number> {\n return Object.fromEntries(layer.levels.map((level) => [level, 0]));\n}\n\n/**\n * This function gives the shortfall of one event of a case: for each draw, `E[max(0, min(D, h) - T)] * users`.\n * `T` is the endurance of the draw, `D` is the duration of the stop of its supply (`stopCurves`), and `h` is the horizon.\n *\n * @param layer - The endurance layer\n * @param caseCuts - The case\n * @param endurance - The endurance of the case, from `enduranceOf`\n * @param options - The stack or the parts that are also down, as for `enduranceOf`, and the horizon\n * @throws RangeError when the horizon is not a number more than 0, or `maxSets` is not a whole number from 1\n */\nexport function caseShortfall(layer: EnduranceLayer, caseCuts: CaseCuts, endurance: Endurance, options: ShortfallOptions = {}): Shortfall {\n const horizon = horizonOf(options);\n budgetsOf(options);\n const levels = zeroLevels(layer);\n const independent = zeroLevels(layer);\n const upper = zeroLevels(layer);\n const unread: string[] = [];\n const coarse: string[] = [];\n const independentUpper: string[] = [];\n const bounds: CutBound[] = [];\n const stoppedOf = stoppedMemo(caseCuts, options);\n for (const draw of caseDraws(layer, caseCuts, caseStopped(caseCuts, options))) {\n const held = endurance.needs[draw.need];\n const curves = stopCurvesWith(caseCuts, draw, options, stoppedOf);\n if (held === undefined || curves === undefined) {\n unread.push(draw.need);\n continue;\n }\n if (curves.coarse) coarse.push(draw.need);\n if (curves.independentUpper) independentUpper.push(draw.need);\n bounds.push(curves.bound);\n const users = draw.users ?? 1;\n levels[draw.level] = (levels[draw.level] ?? 0) + tailDays(curves.event, held.days, horizon) * users;\n independent[draw.level] = (independent[draw.level] ?? 0) + tailDays(curves.independent, held.days, horizon) * users;\n upper[draw.level] = (upper[draw.level] ?? 0) + tailDays(curves.upper, held.days, horizon) * users;\n }\n return { levels, independent, upper, unread, coarse, independentUpper, bound: weakestBound(bounds) };\n}\n\n/**\n * The share of the stores in a case. `take` is the take order of `enduranceOf`. `best` is the leximin share of\n * `bestEndurance`, level by level.\n */\nexport type Share = \"take\" | \"best\";\n\n/** The shares, with the default first. */\nexport const SHARES: readonly Share[] = [\"take\", \"best\"];\n\n/** The options of `yearShortfall`: the date, the stack or the parts that are also down, the horizon and the share. */\nexport interface YearShortfallOptions extends CaseOptions, ShortfallOptions {\n /**\n * The share of the stores in each case. The default `take` gives the endurance from `enduranceOf`. With `best`,\n * the endurance comes from `bestEndurance`, and the horizon of the shortfall is the horizon of the share. Thus a\n * draw at the horizon keeps back only the horizon times its demand, and the lower levels get the rest.\n */\n readonly share?: Share | undefined;\n}\n\n/** The shortfall of one year at one place, with the part of each case. */\nexport interface YearShortfall extends Shortfall {\n readonly place: string;\n /** The part of each case. `rate` is the expected count of its events in one year. */\n readonly cases: readonly { readonly case: string; readonly rate: number; readonly endurance: Endurance; readonly shortfall: Shortfall }[];\n}\n\n/**\n * This function gives the shortfall of one year at one place.\n * It is the sum over the cases of the layer of the expected count of the events of each case times its shortfall.\n *\n * - The expected count of a case is `perYear * reach`, from the first prior of the case at the place. Thus the result is the expected user-days of one year.\n * - A case with no prior at the place is not in the sum.\n * - `unread` is the union of the needs that a case cannot read, in the order of the cases. `coarse` and `independentUpper` are unions too.\n * - `bound` is the weakest bound of the cases in the sum. A case with no prior, or with an expected count of 0, adds 0, so it does not change the bound.\n *\n * @param layer - The endurance layer, with its cases and priors\n * @param place - The place of the priors\n * - With `share: \"best\"`, the endurance of each case comes from `bestEndurance` with the horizon of the shortfall.\n *\n * @param options - The date, the stack or the parts that are also down, the horizon and the share\n * @throws RangeError for a bad date, horizon, `maxSets` or share: refer to `caseShortfall` and `enduranceOf`\n */\nexport function yearShortfall(layer: EnduranceLayer, place: string, options: YearShortfallOptions): YearShortfall {\n horizonOf(options);\n budgetsOf(options);\n const share = options.share ?? \"take\";\n if (!SHARES.includes(share)) throw new RangeError(`The share ${String(options.share)} is not ${SHARES.join(\" or \")}.`);\n const levels = zeroLevels(layer);\n const independent = zeroLevels(layer);\n const upper = zeroLevels(layer);\n const unread: string[] = [];\n const coarse: string[] = [];\n const independentUpper: string[] = [];\n const cases: YearShortfall[\"cases\"][number][] = [];\n const bounds: CutBound[] = [];\n for (const caseCuts of layer.cases ?? []) {\n const prior = (layer.priors ?? []).find((item) => item.case === caseCuts.case && item.place === place);\n if (prior === undefined) continue;\n const rate = yearRate(prior);\n const endurance = share === \"best\" ? bestEndurance(layer, caseCuts, options) : enduranceOf(layer, caseCuts, options);\n const shortfall = caseShortfall(layer, caseCuts, endurance, options);\n for (const [level, days] of Object.entries(shortfall.levels)) levels[level] = (levels[level] ?? 0) + rate * days;\n for (const [level, days] of Object.entries(shortfall.independent)) independent[level] = (independent[level] ?? 0) + rate * days;\n for (const [level, days] of Object.entries(shortfall.upper)) upper[level] = (upper[level] ?? 0) + rate * days;\n for (const need of shortfall.unread) if (!unread.includes(need)) unread.push(need);\n for (const need of shortfall.coarse) if (!coarse.includes(need)) coarse.push(need);\n for (const need of shortfall.independentUpper) if (!independentUpper.includes(need)) independentUpper.push(need);\n if (rate > 0) bounds.push(shortfall.bound);\n cases.push({ case: caseCuts.case, rate, endurance, shortfall });\n }\n return { place, levels, independent, upper, unread, coarse, independentUpper, bound: weakestBound(bounds), cases };\n}\n","import { STACK_SCHEMA, type Stack } from \"@mark1russell7/system-stack\";\nimport { ENDURANCE_SCHEMA, type EnduranceLayer } from \"./layer.ts\";\n\n// A sample: a building with 3 users, and a storm that cuts the grid, the road and the water main.\n// Each name and each value is an example, except the grid curve (NREL, technical report 83092). The tests, the README files and the site use it.\n\n/** The base stack of the sample: the supplies of the building and a camp stove. */\nexport const SAMPLE_ENDURANCE_STACK: Stack = {\n schema: STACK_SCHEMA,\n parts: [\n { id: \"grid\", kind: \"power\", name: \"The power grid\" },\n { id: \"water-main\", kind: \"water\", name: \"The water main\" },\n { id: \"road\", kind: \"road\", name: \"The local road to the shops\" },\n { id: \"stove\", kind: \"device\", name: \"The camp stove\" },\n ],\n};\n\n/**\n * The endurance layer of the sample.\n *\n * - The drinking water holds 75.7 L / 11.355 L a day = 6.667 days.\n * - The food holds 4800 / 5400 = 0.889 days. The rice needs 2 L of water for each kg, and the drinking water keeps back all the water.\n * - The power holds 1000 Wh / 150 Wh a day = 6.667 days.\n * - The filled bottles are past their due date, so they give nothing.\n */\nexport const SAMPLE_ENDURANCE: EnduranceLayer = {\n schema: ENDURANCE_SCHEMA,\n levels: [\"life\", \"health\", \"comfort\"],\n resources: [\n { code: \"water.stored\", unit: \"L\" },\n { code: \"food.ready\", unit: \"kcal\" },\n { code: \"food.grain-dry\", unit: \"kg\" },\n { code: \"fuel.propane\", unit: \"kg\" },\n { code: \"energy.battery\", unit: \"Wh\" },\n ],\n stores: [\n { id: \"jugs\", resource: \"water.stored\", amount: 75.7, due: \"2028-06-01\" },\n { id: \"bottles\", resource: \"water.stored\", amount: 20, due: \"2026-09-30\" },\n { id: \"cans\", resource: \"food.ready\", amount: 4800, due: \"2028-10-01\" },\n { id: \"rice\", resource: \"food.grain-dry\", amount: 9, due: \"2036-09-28\" },\n { id: \"propane\", resource: \"fuel.propane\", amount: 0.908, due: \"2036-10-01\" },\n { id: \"battery\", resource: \"energy.battery\", amount: 1000, due: \"2031-10-01\" },\n ],\n draws: [\n { need: \"hydration.drink\", level: \"life\", perDay: 11.355, users: 3, supply: \"water-main\" },\n { need: \"food.energy\", level: \"health\", perDay: 5400, users: 3, supply: \"road\" },\n { need: \"power.electric\", level: \"comfort\", perDay: 150, users: 3, supply: \"grid\" },\n ],\n direct: [\n { resource: \"water.stored\", need: \"hydration.drink\", amount: 1 },\n { resource: \"food.ready\", need: \"food.energy\", amount: 1 },\n { resource: \"energy.battery\", need: \"power.electric\", amount: 1 },\n ],\n converters: [\n {\n id: \"cook-rice\",\n device: \"stove\",\n takes: [\n { resource: \"food.grain-dry\", amount: 1 },\n { resource: \"water.stored\", amount: 2 },\n { resource: \"fuel.propane\", amount: 0.05 },\n ],\n gives: { need: \"food.energy\", amount: 3600 },\n },\n ],\n cases: [\n {\n case: \"storm\",\n title: \"Winter storm\",\n cuts: [\n { part: \"grid\", title: \"Power outage\", duration: [[0, 1], [0.5, 0.5], [1, 0.36], [7, 0.013], [30, 0]], source: \"nrel-83092\" },\n { part: \"road\", title: \"Closed local road\", duration: [[0, 1], [1, 0.6], [3, 0.2], [10, 0]], source: \"sample\" },\n { part: \"water-main\", title: \"No water from the main\", duration: [[0, 1], [2, 0.3], [7, 0]], source: \"sample\" },\n ],\n leadSeconds: 86_400,\n },\n { case: \"fire\", title: \"Fire\", cuts: [] },\n ],\n priors: [\n { case: \"storm\", place: \"home\", perYear: 0.8, reach: 1, source: \"sample\", asOf: \"2025-12-01\" },\n { case: \"fire\", place: \"home\", perYear: 0.003, reach: 1, source: \"sample\", asOf: \"2025-12-01\" },\n ],\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwEA,SAAgB,UAAU,OAAuB,UAAoB,SAAsB,OAAqC;CAC9H,MAAM,QAAQ,IAAI,IAAI,MAAM,MAAM,KAAK,SAAS,KAAK,IAAI,CAAC;CAC1D,MAAM,UAAU,MAAM,QAAQ,SAAS,CAAC,MAAM,IAAI,IAAI,CAAC;CACvD,IAAI,QAAQ,SAAS,GAAG,MAAM,IAAI,WAAW,aAAa,QAAQ,KAAK,SAAS,IAAI,KAAK,EAAE,CAAC,CAAC,KAAK,IAAI,EAAE,0CAA0C;CAClJ,MAAM,eAAe,YAAY,UAAU,OAAO;CAClD,MAAM,QAAQ,aAAa,OAAO,QAAQ,IAAI,YAAY;CAC1D,MAAM,SAAS,IAAI,IAAI,KAAK;CAC5B,MAAM,OAAO,UAAU,OAAO,UAAU,YAAY,CAAC,CAAC,QAAQ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AC,CAAC,GAAG,CAAC;KAAG,CAAC,IAAK,EAAG;KAAG,CAAC,GAAG,GAAI;KAAG,CAAC,GAAG,IAAK;KAAG,CAAC,IAAI,CAAC;IAAC;IAAG,QAAQ;GAAa;GAC5H;IAAE,MAAM;IAAQ,OAAO;IAAqB,UAAU;KAAC,CAAC,GAAG,CAAC;KAAG,CAAC,GAAG,EAAG;KAAG,CAAC,GAAG,EAAG;KAAG,CAAC,IAAI,CAAC;IAAC;IAAG,QAAQ;GAAS;GAC9G;IAAE,MAAM;IAAc,OAAO;IAA0B,UAAU;KAAC,CAAC,GAAG,CAAC;KAAG,CAAC,GAAG,EAAG;KAAG,CAAC,GAAG,CAAC;IAAC;IAAG,QAAQ;GAAS;EAChH;EACA,aAAa;CACf,GACA;EAAE,MAAM;EAAQ,OAAO;EAAQ,MAAM,CAAC;CAAE,CAC1C;CACA,QAAQ,CACN;EAAE,MAAM;EAAS,OAAO;EAAQ,SAAS;EAAK,OAAO;EAAG,QAAQ;EAAU,MAAM;CAAa,GAC7F;EAAE,MAAM;EAAQ,OAAO;EAAQ,SAAS;EAAO,OAAO;EAAG,QAAQ;EAAU,MAAM;CAAa,CAChG;AACF"}
@@ -106,6 +106,11 @@ interface DrawEndurance {
106
106
  * those days as a full shortfall. This is the safe side for a plan.
107
107
  */
108
108
  readonly capped?: readonly string[] | undefined;
109
+ /**
110
+ * True when the draw holds the horizon of the query (`horizon` of `bestEndurance`). Then `days` is the horizon, and
111
+ * the draw can hold more days. The record has no field `atHorizon` for a draw that stops before the horizon.
112
+ */
113
+ readonly atHorizon?: true | undefined;
109
114
  }
110
115
  /** The days that each draw holds when a case stops its supply. A draw whose supply works is not in `needs`. */
111
116
  interface Endurance {
@@ -128,4 +133,4 @@ interface EnduranceLayer {
128
133
  readonly priors?: readonly Prior$1[] | undefined;
129
134
  }
130
135
  export { DirectUse as a, ENDURANCE_SCHEMA as c, Gift as d, IsoDate as f, Survival as g, Store as h, CutBound as i, Endurance as l, Resource as m, Converter as n, Draw as o, Prior as p, Cut as r, DrawEndurance as s, CaseCuts as t, EnduranceLayer as u };
131
- //# sourceMappingURL=layer-BwbOgVFi.d.ts.map
136
+ //# sourceMappingURL=layer-BdgJSBND.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"layer-BwbOgVFi.d.ts","names":["CaseCuts","Prior"],"sources":["../src/layer.ts"],"mappings":";;cAQa;;KAGD;;UAGK;WACN;WACA;;;UAIM;WACN;;WAEA;;WAEA;;WAEA,MAAM;;WAEN;;;;;;;UAQM;;WAEN;;WAEA;;WAEA;;WAEA;;WAEA;;;UAIM;WACN;WACA;WACA;;;KAIC;WAAkB;WAAuB;WAA2B;;WAA8B;WAA2B;WAAuB;;;;;;;UAO/I;WACN;;WAEA;;WAEA;aAA2B;aAA2B;;;WAEtD,OAAO;;;;;;;;;;;;;WAaP;;;;;WAKA;;;UAOM;WACN;;;;;WAKA;;WAEA,OAAO,SAAS;;;;;;;;WAQhB;;;UAIM;WACN;WACA,IAAI;;WAEJ,OAAO,SAAS,eAAe;;;UAIzB;WACN,eAAe;;WAEf;WACA,oBAAoB;WACpB,iBAAiB;WACjB,gBAAgB;WAChB,kBAAkB;WAClB,sBAAsB;WACtB,iBAAiBA;WACjB,kBAAkBC"}
1
+ {"version":3,"file":"layer-BdgJSBND.d.ts","names":["CaseCuts","Prior"],"sources":["../src/layer.ts"],"mappings":";;cAQa;;KAGD;;UAGK;WACN;WACA;;;UAIM;WACN;;WAEA;;WAEA;;WAEA,MAAM;;WAEN;;;;;;;UAQM;;WAEN;;WAEA;;WAEA;;WAEA;;WAEA;;;UAIM;WACN;WACA;WACA;;;KAIC;WAAkB;WAAuB;WAA2B;;WAA8B;WAA2B;WAAuB;;;;;;;UAO/I;WACN;;WAEA;;WAEA;aAA2B;aAA2B;;;WAEtD,OAAO;;;;;;;;;;;;;WAaP;;;;;WAKA;;;UAOM;WACN;;;;;WAKA;;WAEA,OAAO,SAAS;;;;;;;;WAQhB;;;;;WAKA;;;UAIM;WACN;WACA,IAAI;;WAEJ,OAAO,SAAS,eAAe;;;UAIzB;WACN,eAAe;;WAEf;WACA,oBAAoB;WACpB,iBAAiB;WACjB,gBAAgB;WAChB,kBAAkB;WAClB,sBAAsB;WACtB,iBAAiBA;WACjB,kBAAkBC"}
@@ -1 +1 @@
1
- {"version":3,"file":"layer-a3Fr70Uh.js","names":[],"sources":["../src/layer.ts"],"sourcesContent":["// The records of the endurance add-on. They are one layer of a stack, with the key `endurance/1` in `Stack.layers`.\n// A store holds an amount of a resource. A draw takes a need each day. A converter changes resources into a need.\n// A case cuts some parts for a time. The queries give the days that each draw holds, and the days that it does not get its need.\n// The add-on names no topic: the resources, the needs and the levels are data. The unit of time is the day.\n\nimport type { CaseCuts, Prior } from \"@mark1russell7/system-stack\";\n\n/** The name of the format of an endurance layer. It is the key of the layer in `Stack.layers`. */\nexport const ENDURANCE_SCHEMA = \"endurance/1\";\n\n/** A date as `YYYY-MM-DD`. */\nexport type IsoDate = string;\n\n/** A resource of a store, with its unit, for example `L`, `kg` or `Wh`. */\nexport interface Resource {\n readonly code: string;\n readonly unit: string;\n}\n\n/** A store: an amount of one resource. */\nexport interface Store {\n readonly id: string;\n /** The `code` of the resource. */\n readonly resource: string;\n /** The amount, in the unit of the resource. */\n readonly amount: number;\n /** The due date. On this date and after it, the store gives nothing. A store with no due date does not expire. */\n readonly due?: IsoDate | undefined;\n /** The `id` of the part of the stack that holds the store. When the part stops, the store gives nothing. */\n readonly part?: string | undefined;\n}\n\n/**\n * A draw: a need that a load takes each day from its supply.\n * Examples are the power of a rack and the drinking water of a building.\n * When the supply part stops, the draw takes the need from the stores.\n */\nexport interface Draw {\n /** The code of the need. One draw has each code. */\n readonly need: string;\n /** The level of the draw. It is one of the `levels` of the layer. */\n readonly level: string;\n /** The amount of the need for each day. */\n readonly perDay: number;\n /** The count of the users of the draw, for example the persons or the machines. The shortfall counts each user. The default is 1. */\n readonly users?: number | undefined;\n /** The `id` of the part of the stack that supplies the need when no case stops it. */\n readonly supply: string;\n}\n\n/** The direct use of a resource for a need: 1 unit of the resource gives `amount` of the need. */\nexport interface DirectUse {\n readonly resource: string;\n readonly need: string;\n readonly amount: number;\n}\n\n/** The gift of one run of a converter: an amount of a need, or an amount of a resource, in its unit. */\nexport type Gift = { readonly need: string; readonly resource?: never; readonly amount: number } | { readonly resource: string; readonly need?: never; readonly amount: number };\n\n/**\n * A converter: a device or an action that changes resources into a need or into a resource.\n * Example: a stove cooks 1 kg of dry rice with 2 L of water and 0.05 kg of fuel, and gives 3600 kcal.\n * Example: a generator changes 1 L of fuel into 3000 Wh of the battery. Then a direct use of the battery can take that energy.\n */\nexport interface Converter {\n readonly id: string;\n /** The `id` of the device in the stack. The converter stops when the device stops. */\n readonly device?: string | undefined;\n /** The resources that one run takes. */\n readonly takes: readonly { readonly resource: string; readonly amount: number }[];\n /** The need or the resource that one run gives, and its amount. A chain of converters cannot make a resource from itself. */\n readonly gives: Gift;\n /**\n * The most runs of one device in a day, for example the pots that one stove cooks in a day. It is a cited fact of the\n * device. With no `perDay`, the runs have no limit for each day.\n *\n * The converters of one `device` share its days. One run uses `1 / perDay` of a day of one device. Thus a stove with\n * a converter for rice and a converter for beans does not cook more pots in a day than its limits give.\n *\n * The limit is a rate, not a store. Over `T` days, the converter runs `perDay` times `devices` times `T` times or\n * less. The higher draws use the runs first. Each higher draw keeps back its runs of each day for all the days of a\n * lower draw. A draw that the limit stops gets the rest of its need from its other ways. When they cannot give it, the\n * draw falls short, also when the stores of the converter have more.\n */\n readonly perDay?: number | undefined;\n /**\n * The count of devices of the converter, a whole number of 1 or more. The default is 1. It has an effect only with\n * `perDay`. The converters of one `device` give one count. When the part `device` stops, all the devices stop.\n */\n readonly devices?: number | undefined;\n}\n\n// The core holds the records of the cuts of a case, so that each add-on shares them. This entry gives them again.\nexport type { CaseCuts, Cut, CutBound, Prior, Survival } from \"@mark1russell7/system-stack\";\n\n/** The days that one draw holds, and the resources that are used up at that time. */\nexport interface DrawEndurance {\n readonly days: number;\n /**\n * The inputs of the draw that are used up at `days`, through each chain of converters, in the order of their codes. A higher draw can use up an input first.\n * A resource that only converters make, with no store of the layer, is not in the list.\n */\n readonly binding: readonly string[];\n /** The amount of each resource that the draw takes in its days, by the code of the resource. A resource with no take is not in the record. */\n readonly takes: Readonly<Record<string, number>>;\n /**\n * The converters whose limit `perDay` stops the draw at `days`, while their inputs have more, in the order of their\n * `id`. The record has no field `capped` when no limit stops the draw.\n *\n * After `days`, such a draw can still get a part of its need at the rate of the limit. The shortfall counts each of\n * those days as a full shortfall. This is the safe side for a plan.\n */\n readonly capped?: readonly string[] | undefined;\n}\n\n/** The days that each draw holds when a case stops its supply. A draw whose supply works is not in `needs`. */\nexport interface Endurance {\n readonly case: string;\n readonly at: IsoDate;\n /** The result of each draw, by the code of its need. */\n readonly needs: Readonly<Record<string, DrawEndurance>>;\n}\n\n/** An endurance layer: the levels, the resources, the stores, the draws, the uses and the converters, the cases and their priors. */\nexport interface EnduranceLayer {\n readonly schema: typeof ENDURANCE_SCHEMA;\n /** The levels of the draws, the most important first, for example `[\"critical\", \"normal\"]`. A higher level takes the resources first. */\n readonly levels: readonly string[];\n readonly resources: readonly Resource[];\n readonly stores: readonly Store[];\n readonly draws: readonly Draw[];\n readonly direct?: readonly DirectUse[] | undefined;\n readonly converters?: readonly Converter[] | undefined;\n readonly cases?: readonly CaseCuts[] | undefined;\n readonly priors?: readonly Prior[] | undefined;\n}\n"],"mappings":";;AAQA,MAAa,mBAAmB"}
1
+ {"version":3,"file":"layer-a3Fr70Uh.js","names":[],"sources":["../src/layer.ts"],"sourcesContent":["// The records of the endurance add-on. They are one layer of a stack, with the key `endurance/1` in `Stack.layers`.\n// A store holds an amount of a resource. A draw takes a need each day. A converter changes resources into a need.\n// A case cuts some parts for a time. The queries give the days that each draw holds, and the days that it does not get its need.\n// The add-on names no topic: the resources, the needs and the levels are data. The unit of time is the day.\n\nimport type { CaseCuts, Prior } from \"@mark1russell7/system-stack\";\n\n/** The name of the format of an endurance layer. It is the key of the layer in `Stack.layers`. */\nexport const ENDURANCE_SCHEMA = \"endurance/1\";\n\n/** A date as `YYYY-MM-DD`. */\nexport type IsoDate = string;\n\n/** A resource of a store, with its unit, for example `L`, `kg` or `Wh`. */\nexport interface Resource {\n readonly code: string;\n readonly unit: string;\n}\n\n/** A store: an amount of one resource. */\nexport interface Store {\n readonly id: string;\n /** The `code` of the resource. */\n readonly resource: string;\n /** The amount, in the unit of the resource. */\n readonly amount: number;\n /** The due date. On this date and after it, the store gives nothing. A store with no due date does not expire. */\n readonly due?: IsoDate | undefined;\n /** The `id` of the part of the stack that holds the store. When the part stops, the store gives nothing. */\n readonly part?: string | undefined;\n}\n\n/**\n * A draw: a need that a load takes each day from its supply.\n * Examples are the power of a rack and the drinking water of a building.\n * When the supply part stops, the draw takes the need from the stores.\n */\nexport interface Draw {\n /** The code of the need. One draw has each code. */\n readonly need: string;\n /** The level of the draw. It is one of the `levels` of the layer. */\n readonly level: string;\n /** The amount of the need for each day. */\n readonly perDay: number;\n /** The count of the users of the draw, for example the persons or the machines. The shortfall counts each user. The default is 1. */\n readonly users?: number | undefined;\n /** The `id` of the part of the stack that supplies the need when no case stops it. */\n readonly supply: string;\n}\n\n/** The direct use of a resource for a need: 1 unit of the resource gives `amount` of the need. */\nexport interface DirectUse {\n readonly resource: string;\n readonly need: string;\n readonly amount: number;\n}\n\n/** The gift of one run of a converter: an amount of a need, or an amount of a resource, in its unit. */\nexport type Gift = { readonly need: string; readonly resource?: never; readonly amount: number } | { readonly resource: string; readonly need?: never; readonly amount: number };\n\n/**\n * A converter: a device or an action that changes resources into a need or into a resource.\n * Example: a stove cooks 1 kg of dry rice with 2 L of water and 0.05 kg of fuel, and gives 3600 kcal.\n * Example: a generator changes 1 L of fuel into 3000 Wh of the battery. Then a direct use of the battery can take that energy.\n */\nexport interface Converter {\n readonly id: string;\n /** The `id` of the device in the stack. The converter stops when the device stops. */\n readonly device?: string | undefined;\n /** The resources that one run takes. */\n readonly takes: readonly { readonly resource: string; readonly amount: number }[];\n /** The need or the resource that one run gives, and its amount. A chain of converters cannot make a resource from itself. */\n readonly gives: Gift;\n /**\n * The most runs of one device in a day, for example the pots that one stove cooks in a day. It is a cited fact of the\n * device. With no `perDay`, the runs have no limit for each day.\n *\n * The converters of one `device` share its days. One run uses `1 / perDay` of a day of one device. Thus a stove with\n * a converter for rice and a converter for beans does not cook more pots in a day than its limits give.\n *\n * The limit is a rate, not a store. Over `T` days, the converter runs `perDay` times `devices` times `T` times or\n * less. The higher draws use the runs first. Each higher draw keeps back its runs of each day for all the days of a\n * lower draw. A draw that the limit stops gets the rest of its need from its other ways. When they cannot give it, the\n * draw falls short, also when the stores of the converter have more.\n */\n readonly perDay?: number | undefined;\n /**\n * The count of devices of the converter, a whole number of 1 or more. The default is 1. It has an effect only with\n * `perDay`. The converters of one `device` give one count. When the part `device` stops, all the devices stop.\n */\n readonly devices?: number | undefined;\n}\n\n// The core holds the records of the cuts of a case, so that each add-on shares them. This entry gives them again.\nexport type { CaseCuts, Cut, CutBound, Prior, Survival } from \"@mark1russell7/system-stack\";\n\n/** The days that one draw holds, and the resources that are used up at that time. */\nexport interface DrawEndurance {\n readonly days: number;\n /**\n * The inputs of the draw that are used up at `days`, through each chain of converters, in the order of their codes. A higher draw can use up an input first.\n * A resource that only converters make, with no store of the layer, is not in the list.\n */\n readonly binding: readonly string[];\n /** The amount of each resource that the draw takes in its days, by the code of the resource. A resource with no take is not in the record. */\n readonly takes: Readonly<Record<string, number>>;\n /**\n * The converters whose limit `perDay` stops the draw at `days`, while their inputs have more, in the order of their\n * `id`. The record has no field `capped` when no limit stops the draw.\n *\n * After `days`, such a draw can still get a part of its need at the rate of the limit. The shortfall counts each of\n * those days as a full shortfall. This is the safe side for a plan.\n */\n readonly capped?: readonly string[] | undefined;\n /**\n * True when the draw holds the horizon of the query (`horizon` of `bestEndurance`). Then `days` is the horizon, and\n * the draw can hold more days. The record has no field `atHorizon` for a draw that stops before the horizon.\n */\n readonly atHorizon?: true | undefined;\n}\n\n/** The days that each draw holds when a case stops its supply. A draw whose supply works is not in `needs`. */\nexport interface Endurance {\n readonly case: string;\n readonly at: IsoDate;\n /** The result of each draw, by the code of its need. */\n readonly needs: Readonly<Record<string, DrawEndurance>>;\n}\n\n/** An endurance layer: the levels, the resources, the stores, the draws, the uses and the converters, the cases and their priors. */\nexport interface EnduranceLayer {\n readonly schema: typeof ENDURANCE_SCHEMA;\n /** The levels of the draws, the most important first, for example `[\"critical\", \"normal\"]`. A higher level takes the resources first. */\n readonly levels: readonly string[];\n readonly resources: readonly Resource[];\n readonly stores: readonly Store[];\n readonly draws: readonly Draw[];\n readonly direct?: readonly DirectUse[] | undefined;\n readonly converters?: readonly Converter[] | undefined;\n readonly cases?: readonly CaseCuts[] | undefined;\n readonly priors?: readonly Prior[] | undefined;\n}\n"],"mappings":";;AAQA,MAAa,mBAAmB"}
package/build/schema.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { u as EnduranceLayer } from "./layer-BwbOgVFi.js";
1
+ import { u as EnduranceLayer } from "./layer-BdgJSBND.js";
2
2
  import { z } from "zod";
3
3
  /**
4
4
  * The schema of an endurance layer. It examines the form of the record: the fields and their types.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/stack-endurance",
4
- "version": "0.8.9",
4
+ "version": "0.8.11",
5
5
  "description": "Stores, draws and converters of a system stack: the days that each draw holds when a case cuts its supply, and the shortfall of each level in one year. An add-on of system-stack.",
6
6
  "license": "MIT",
7
7
  "repository": {