@mark1russell7/stack-endurance 0.8.2 → 0.8.4

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
@@ -52,6 +52,17 @@ A draw that only the parts of `down` stop has no curve of its duration. The quer
52
52
 
53
53
  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.
54
54
 
55
+ Since 0.8.4, `stopCurves`, `caseShortfall` and `yearShortfall` give a `bound`: the weakest bound of the curves that the result uses (`weakestBound` of the core). A cut with no `bound` has a law. The shortfall does not decrease when a cut lasts longer, so the bound of each curve carries to the result.
56
+
57
+ | Bounds of the curves | Bound of the result |
58
+ | --- | --- |
59
+ | Each one `law`, or no curve | `law` |
60
+ | `law` and `upper` | `upper`: each value is too high or equal |
61
+ | `law` and `lower` | `lower`: each value is too low or equal |
62
+ | Any `none`, or `upper` and `lower` | `none`: a value can be too high or too low |
63
+
64
+ A stop uses the cuts of its minimal sets, or each cut with a curve when the query has no minimal sets. A draw in `unread` does not change the bound of its case. In one year, a case with no prior or with an expected count of 0 adds 0, so it does not change the bound. The gate refuses a bound that is not in `CUT_BOUNDS` (`endurance-bound`).
65
+
55
66
  The cuts of one case come from one event. `levels` takes each cut longer together with the event (`eventStop`). Then a stop with two cuts lasts as long as the longer cut. A stop through a need of `any` of two parts ends with the shorter cut. `levels` is not a limit: when the cuts are independent, the true stop can be longer or shorter.
56
67
 
57
68
  `upper` is an upper limit for each dependence of the cuts (`upperStop`). At each time, its chance is the sum over the minimal sets of cuts of the smallest chance of the set, to 1 or less. A gate of a high level can use `upper`.
package/build/add-on.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { l as EnduranceLayer } from "./layer-CF0r-9ww.js";
1
+ import { u as EnduranceLayer } from "./layer-BwbOgVFi.js";
2
2
  import { StackJoiner } from "@mark1russell7/system-stack";
3
3
  /**
4
4
  * This function gives the endurance add-on.
package/build/add-on.js CHANGED
@@ -1,4 +1,4 @@
1
- import { r as checkEndurance, t as joinEndurance } from "./join-DQxIAP0v.js";
1
+ import { r as checkEndurance, t as joinEndurance } from "./join-DdVFmRh6.js";
2
2
  import { t as ENDURANCE_SCHEMA } from "./layer-a3Fr70Uh.js";
3
3
  import { parseEndurance } from "./schema.js";
4
4
  // src/add-on.ts
package/build/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { a as Draw, c as Endurance, d as IsoDate, f as Prior, h as Survival, i as DirectUse, l as EnduranceLayer, m as Store, n as Converter, o as DrawEndurance, p as Resource, r as Cut, s as ENDURANCE_SCHEMA, t as CaseCuts, u as Gift } from "./layer-CF0r-9ww.js";
2
- import { Fault, LayerParse, LayerPiece, PathOptions, Stack, curveFault } from "@mark1russell7/system-stack";
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";
2
+ import { CutBound as CutBound$1, Fault, LayerParse, LayerPiece, PathOptions, Stack, curveFault } from "@mark1russell7/system-stack";
3
3
  /** The options of the queries of a case. */
4
4
  export interface CaseOptions {
5
5
  /** The date of the query. A store whose due date is on this date or before it gives nothing. */
@@ -252,6 +252,12 @@ export interface StopCurves {
252
252
  readonly coarse: boolean;
253
253
  /** This is true when `independent` is `upper`: `coarse` is true, or the expansion of `independentStop` passed its budget. */
254
254
  readonly independentUpper: boolean;
255
+ /**
256
+ * The weakest bound (`weakestBound` of the core) of the curves of the cuts that the stop uses. Since 0.8.4.
257
+ * With minimal sets, the stop uses the cuts of the sets. With no minimal sets, it uses each cut with a curve.
258
+ * Each of the three curves does not decrease when a cut lasts longer, so it has this bound.
259
+ */
260
+ readonly bound: CutBound$1;
255
261
  }
256
262
  /**
257
263
  * This function gives the curves of the duration of the stop of a draw, or `undefined` when the query has no curve.
@@ -265,6 +271,7 @@ export interface StopCurves {
265
271
  * - `event` is `eventStop`. `independent` is `independentStop`, and `upper` is `upperStop`, over the minimal sets of the cuts that count.
266
272
  * - With no minimal sets, `upper` is the sum of the curves, `independent` is `upper`, and `coarse` is true.
267
273
  * - When the expansion of `independentStop` passes its budget, `independent` is `upper`, and `independentUpper` is true.
274
+ * - `bound` is the weakest bound of the curves of the cuts that the stop uses. A cut with no `bound` has a law.
268
275
  */
269
276
  export declare function stopCurves(caseCuts: CaseCuts, draw: Draw, options?: StopCurveOptions): StopCurves | undefined;
270
277
  /** The shortfall of each level, in user-days, and the draws that the query cannot read. */
@@ -287,6 +294,15 @@ export interface Shortfall {
287
294
  readonly coarse: readonly string[];
288
295
  /** The needs of the draws whose `independent` is `upper` (`StopCurves.independentUpper`). A gate on `independent` shows them. */
289
296
  readonly independentUpper: readonly string[];
297
+ /**
298
+ * The bound of the shortfall: the weakest bound (`weakestBound` of the core) of the curves that the query uses. Since 0.8.4.
299
+ * 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.
300
+ * With `none`, a value can be too high or too low.
301
+ *
302
+ * A draw in `unread` and a case that adds 0 do not change the bound. With no curve, the bound is `law`.
303
+ * The bound is for each of `levels`, `independent` and `upper`, each with its own rule of the dependence of the cuts.
304
+ */
305
+ readonly bound: CutBound$1;
290
306
  }
291
307
  /**
292
308
  * This function gives the shortfall of one event of a case: for each draw, `E[max(0, min(D, h) - T)] * users`.
@@ -317,6 +333,7 @@ export interface YearShortfall extends Shortfall {
317
333
  * - 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.
318
334
  * - A case with no prior at the place is not in the sum.
319
335
  * - `unread` is the union of the needs that a case cannot read, in the order of the cases. `coarse` and `independentUpper` are unions too.
336
+ * - `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.
320
337
  *
321
338
  * @param layer - The endurance layer, with its cases and priors
322
339
  * @param place - The place of the priors
@@ -337,6 +354,7 @@ export declare function yearShortfall(layer: EnduranceLayer, place: string, opti
337
354
  * - `endurance-converter-empty`: a converter takes nothing, or it gives an amount of 0.
338
355
  * - `endurance-curve`: a survival curve does not start at `[0, 1]`, or it does not end at a chance of 0.
339
356
  * Or its days do not increase, or its chance increases.
357
+ * - `endurance-bound`: the bound of a cut is not a value of `CUT_BOUNDS` of the core. Since 0.8.4.
340
358
  * - `endurance-prior-case`: a prior names a case that the layer does not have.
341
359
  * - `endurance-cycle`: converters make a resource from itself, through one converter or a chain. One fault names each cycle.
342
360
  * - `endurance-devices`: two converters of one device give two different counts of devices.
@@ -345,7 +363,7 @@ export declare function yearShortfall(layer: EnduranceLayer, place: string, opti
345
363
  * - `endurance-no-way` (warning): a draw has no direct use and no converter, so it holds 0 days when its supply stops.
346
364
  * - `endurance-cut-no-curve` (warning): a cut has no curve of its duration. The draws whose stop it can be part of are no read in the shortfall.
347
365
  */
348
- export declare const ENDURANCE_CODES: readonly ["endurance-twice", "endurance-level-unknown", "endurance-resource-unknown", "endurance-part-unknown", "endurance-range", "endurance-date", "endurance-converter-empty", "endurance-curve", "endurance-prior-case", "endurance-cycle", "endurance-devices", "endurance-device-mix", "endurance-no-way", "endurance-cut-no-curve"];
366
+ export declare const ENDURANCE_CODES: readonly ["endurance-twice", "endurance-level-unknown", "endurance-resource-unknown", "endurance-part-unknown", "endurance-range", "endurance-date", "endurance-converter-empty", "endurance-curve", "endurance-bound", "endurance-prior-case", "endurance-cycle", "endurance-devices", "endurance-device-mix", "endurance-no-way", "endurance-cut-no-curve"];
349
367
  /** A code of `ENDURANCE_CODES`. */
350
368
  export type EnduranceCode = (typeof ENDURANCE_CODES)[number];
351
369
  /** A fault of the gate of an endurance layer. */
@@ -392,5 +410,5 @@ export declare const SAMPLE_ENDURANCE_STACK: Stack;
392
410
  * - The filled bottles are past their due date, so they give nothing.
393
411
  */
394
412
  export declare const SAMPLE_ENDURANCE: EnduranceLayer;
395
- export { type CaseCuts, Converter, type Cut, DirectUse, Draw, DrawEndurance, ENDURANCE_SCHEMA, Endurance, EnduranceLayer, Gift, IsoDate, type Prior, Resource, Store, type Survival, curveFault };
413
+ export { type CaseCuts, Converter, type Cut, type CutBound, DirectUse, Draw, DrawEndurance, ENDURANCE_SCHEMA, Endurance, EnduranceLayer, Gift, IsoDate, type Prior, Resource, Store, type Survival, curveFault };
396
414
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/endurance.ts","../src/joint.ts","../src/shortfall.ts","../src/check.ts","../src/join.ts","../src/sample.ts"],"mappings":";;;iBASiB;;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,WAAW;;wBAKpB,aAAa,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBA0LxB,YAAY,OAAO,gBAAgB,UAAU,UAAU,SAAS,cAAc;;iBC7P7E;WACN;WACA,IAAI;;;;;WAKJ;;WAEA;;WAEA;;;;;;WAMA,OAAO,SAAS,eAAe,SAAS;;;;;WAKxC;;WAEA,MAAM,SAAS;;;;;;WAMf;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBA+BK,UAAU,OAAO,gBAAgB,UAAU,UAAU,SAAS,aAAa,2BAA2B;;wBC/DtG,WAAW,OAAO,UAAU;;;;;;wBAoB5B,SAAS,OAAO,UAAU,cAAc;;;;;;;;;;iBAqBvC,yBAAyB,KAAK,gCAAgC,KAAK;;WAEzE;;iBAGM,yBAAyB;;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;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;;;;;;;;;;;;;;;;;;;;;;;qBClkBjG;;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
@@ -1,6 +1,6 @@
1
1
  import { t as ENDURANCE_SCHEMA } from "./layer-a3Fr70Uh.js";
2
- import { _ as deviceKey, a as hasEnduranceError, c as drawDemand, d as giftResource, f as storeAmounts, g as canRun, h as exact, i as curveFault, l as enduranceOf, m as dense, n as ENDURANCE_CODES, o as caseDraws, p as addTo, r as checkEndurance, s as caseStopped, t as joinEndurance, u as giftNeed, v as inputsOf } from "./join-DQxIAP0v.js";
3
- import { DEFAULT_MAX_SETS, STACK_SCHEMA, neededParts, stopSets } from "@mark1russell7/system-stack";
2
+ import { _ as deviceKey, a as hasEnduranceError, c as drawDemand, d as giftResource, f as storeAmounts, g as canRun, h as exact, i as curveFault, l as enduranceOf, m as dense, n as ENDURANCE_CODES, o as caseDraws, p as addTo, r as checkEndurance, s as caseStopped, t as joinEndurance, u as giftNeed, v as inputsOf } from "./join-DdVFmRh6.js";
3
+ import { DEFAULT_MAX_SETS, STACK_SCHEMA, neededParts, stopSets, weakestBound } from "@mark1russell7/system-stack";
4
4
  import { solveLexicographic } from "@mark1russell7/linear";
5
5
  import { ONE, ZERO, add, div, equals, mul, neg, sign, toNumber } from "@mark1russell7/rational";
6
6
  import { pathSetReliability, stronglyConnectedComponents } from "@mark1russell7/collections/graph";
@@ -658,12 +658,15 @@ function stopCurvesWith(caseCuts, draw, options, stoppedOf) {
658
658
  const keptSets = sets?.map((set) => set.map((index) => kept.indexOf(index)));
659
659
  const upper = upperStop(curves, keptSets);
660
660
  const independent = independentStop(curves, keptSets, budgetsOf(options).maxWork);
661
+ const used = sets === void 0 ? kept : kept.filter((index) => sets.some((set) => set.includes(index)));
662
+ const bound = weakestBound(used.map((index) => caseCuts.cuts[relevant[index] ?? -1]?.bound ?? "law"));
661
663
  return {
662
664
  event: eventStop(curves, keptStops),
663
665
  independent: independent ?? upper,
664
666
  upper,
665
667
  coarse: keptSets === void 0,
666
- independentUpper: independent === void 0
668
+ independentUpper: independent === void 0,
669
+ bound
667
670
  };
668
671
  }
669
672
  /**
@@ -678,6 +681,7 @@ function stopCurvesWith(caseCuts, draw, options, stoppedOf) {
678
681
  * - `event` is `eventStop`. `independent` is `independentStop`, and `upper` is `upperStop`, over the minimal sets of the cuts that count.
679
682
  * - With no minimal sets, `upper` is the sum of the curves, `independent` is `upper`, and `coarse` is true.
680
683
  * - When the expansion of `independentStop` passes its budget, `independent` is `upper`, and `independentUpper` is true.
684
+ * - `bound` is the weakest bound of the curves of the cuts that the stop uses. A cut with no `bound` has a law.
681
685
  */
682
686
  function stopCurves(caseCuts, draw, options = {}) {
683
687
  budgetsOf(options);
@@ -705,6 +709,7 @@ function caseShortfall(layer, caseCuts, endurance, options = {}) {
705
709
  const unread = [];
706
710
  const coarse = [];
707
711
  const independentUpper = [];
712
+ const bounds = [];
708
713
  const stoppedOf = stoppedMemo(caseCuts, options);
709
714
  for (const draw of caseDraws(layer, caseCuts, caseStopped(caseCuts, options))) {
710
715
  const held = endurance.needs[draw.need];
@@ -715,6 +720,7 @@ function caseShortfall(layer, caseCuts, endurance, options = {}) {
715
720
  }
716
721
  if (curves.coarse) coarse.push(draw.need);
717
722
  if (curves.independentUpper) independentUpper.push(draw.need);
723
+ bounds.push(curves.bound);
718
724
  const users = draw.users ?? 1;
719
725
  levels[draw.level] = (levels[draw.level] ?? 0) + tailDays(curves.event, held.days, horizon) * users;
720
726
  independent[draw.level] = (independent[draw.level] ?? 0) + tailDays(curves.independent, held.days, horizon) * users;
@@ -726,7 +732,8 @@ function caseShortfall(layer, caseCuts, endurance, options = {}) {
726
732
  upper,
727
733
  unread,
728
734
  coarse,
729
- independentUpper
735
+ independentUpper,
736
+ bound: weakestBound(bounds)
730
737
  };
731
738
  }
732
739
  /**
@@ -736,6 +743,7 @@ function caseShortfall(layer, caseCuts, endurance, options = {}) {
736
743
  * - 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.
737
744
  * - A case with no prior at the place is not in the sum.
738
745
  * - `unread` is the union of the needs that a case cannot read, in the order of the cases. `coarse` and `independentUpper` are unions too.
746
+ * - `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.
739
747
  *
740
748
  * @param layer - The endurance layer, with its cases and priors
741
749
  * @param place - The place of the priors
@@ -752,6 +760,7 @@ function yearShortfall(layer, place, options) {
752
760
  const coarse = [];
753
761
  const independentUpper = [];
754
762
  const cases = [];
763
+ const bounds = [];
755
764
  for (const caseCuts of layer.cases ?? []) {
756
765
  const prior = (layer.priors ?? []).find((item) => item.case === caseCuts.case && item.place === place);
757
766
  if (prior === void 0) continue;
@@ -764,6 +773,7 @@ function yearShortfall(layer, place, options) {
764
773
  for (const need of shortfall.unread) if (!unread.includes(need)) unread.push(need);
765
774
  for (const need of shortfall.coarse) if (!coarse.includes(need)) coarse.push(need);
766
775
  for (const need of shortfall.independentUpper) if (!independentUpper.includes(need)) independentUpper.push(need);
776
+ if (rate > 0) bounds.push(shortfall.bound);
767
777
  cases.push({
768
778
  case: caseCuts.case,
769
779
  rate,
@@ -779,6 +789,7 @@ function yearShortfall(layer, place, options) {
779
789
  unread,
780
790
  coarse,
781
791
  independentUpper,
792
+ bound: weakestBound(bounds),
782
793
  cases
783
794
  };
784
795
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/joint.ts","../src/stops.ts","../src/shortfall.ts","../src/sample.ts"],"sourcesContent":["import { type Constraint, type Objective, solveLexicographic } from \"@mark1russell7/linear\";\nimport { add, div, equals, mul, neg, ONE, type Rational, sign, toNumber, ZERO } from \"@mark1russell7/rational\";\nimport { canRun, deviceKey, inputsOf } from \"./converter.ts\";\nimport { type CaseOptions, caseDraws, caseStopped, drawDemand, giftNeed, giftResource, storeAmounts } from \"./endurance.ts\";\nimport type { CaseCuts, Converter, EnduranceLayer, IsoDate } from \"./layer.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 direct = (layer.direct ?? []).filter((use) => planned.has(use.need) && use.amount > 0);\n const live = (layer.converters ?? []).filter((converter) => canRun(converter, stoppedParts));\n const cooks = live.filter((converter) => planned.has(giftNeed(converter) ?? \"\"));\n const makers = live.filter((converter) => giftResource(converter) !== undefined);\n const resources = new Set<string>([...direct.map((use) => use.resource), ...[...cooks, ...makers].flatMap((converter) => [...inputsOf(converter).keys()])]);\n for (const maker of makers) resources.add(giftResource(maker) ?? \"\");\n const stocked = [...resources].filter((resource) => (stock.get(resource) ?? 0) > 0).sort();\n\n // The variables: the days, the take of each direct use, the runs of each converter that gives a need of the plan,\n // and for each draw of the plan the runs of each maker and the share of each stock. The shares tell the takes of each draw.\n let count = 0;\n const next = (): number => count++;\n const days = next();\n const useCol = direct.map(next);\n const cookCol = cooks.map(next);\n const makerCol = plan.map(() => makers.map(next));\n const shareCol = plan.map(() => new Map(stocked.map((resource) => [resource, next()] as const)));\n\n const rows: { readonly row: Row; readonly relation: Constraint[\"relation\"]; readonly rhs: Rational }[] = [];\n plan.forEach((draw, i) => {\n // The need of the draw: its gifts are not less than its demand times the days.\n const need: Row = new Map([[days, neg(exact(drawDemand(draw, caseCuts)))]]);\n direct.forEach((use, k) => {\n if (use.need === draw.need) addTo(need, useCol[k] as number, exact(use.amount));\n });\n cooks.forEach((cook, c) => {\n if (giftNeed(cook) === draw.need) addTo(need, cookCol[c] as number, exact(cook.gives.amount));\n });\n rows.push({ row: need, relation: \">=\", rhs: ZERO });\n // The balance of each resource of the draw: its takes are not more than its share of the stock plus the gifts of its makers.\n const balance = new Map<string, Row>([...resources].map((resource) => [resource, new Map()]));\n const consume = (resource: string, index: number, amount: Rational): void => addTo(balance.get(resource) as Row, index, amount);\n direct.forEach((use, k) => {\n if (use.need === draw.need) consume(use.resource, useCol[k] as number, ONE);\n });\n cooks.forEach((cook, c) => {\n if (giftNeed(cook) !== draw.need) return;\n for (const [resource, each] of inputsOf(cook)) consume(resource, cookCol[c] as number, exact(each));\n });\n makers.forEach((maker, m) => {\n const index = makerCol[i]?.[m] as number;\n for (const [resource, each] of inputsOf(maker)) consume(resource, index, exact(each));\n consume(giftResource(maker) as string, index, neg(exact(maker.gives.amount)));\n });\n for (const [resource, index] of shareCol[i] ?? []) consume(resource, index, neg(ONE));\n for (const row of balance.values()) if (row.size > 0) rows.push({ row, relation: \"<=\", rhs: ZERO });\n });\n // The limit of each device: one run uses `1 / perDay` of a day of one device, so the runs use `devices` times `d` device-days or less.\n // The converters of one device share one limit. A converter with no device has a limit of its own. A limit of 0 stops the converter.\n const runCols = new Map<Converter, readonly number[]>([\n ...cooks.map((cook, c) => [cook, [cookCol[c] as number]] as const),\n ...makers.map((maker, m) => [maker, makerCol.map((row) => row[m] as number)] as const),\n ]);\n const limits = new Map<string, { readonly row: Row; readonly converters: Converter[] }>();\n for (const [converter, indexes] of runCols) {\n if (converter.perDay === undefined) continue;\n if (!(converter.perDay > 0)) {\n for (const index of indexes) rows.push({ row: new Map([[index, ONE]]), relation: \"<=\", rhs: ZERO });\n continue;\n }\n const key = deviceKey(converter);\n const limit = limits.get(key) ?? { row: new Map([[days, neg(exact(converter.devices ?? 1))]]), converters: [] };\n limits.set(key, limit);\n limit.converters.push(converter);\n for (const index of indexes) addTo(limit.row, index, div(ONE, exact(converter.perDay)));\n }\n for (const { row } of limits.values()) rows.push({ row, relation: \"<=\", rhs: ZERO });\n // The shares of each stock are not more than the stock.\n for (const resource of stocked) {\n const row: Row = new Map();\n for (const shares of shareCol) addTo(row, shares.get(resource) as number, ONE);\n rows.push({ row, relation: \"<=\", rhs: exact(stock.get(resource) ?? 0) });\n }\n\n const constraints: Constraint[] = rows.map(({ row, relation, rhs }) => ({ coefficients: dense(row, count), relation, rhs }));\n const most: Row = new Map([[days, ONE]]);\n const least: Row = new Map();\n for (const shares of shareCol) for (const [resource, index] of shares) addTo(least, index, div(ONE, exact(stock.get(resource) ?? 1)));\n // The third objective takes the fewest device-days: the runs over `perDay`, or the runs with no limit. Thus a converter whose inputs cost\n // no stock does not give more runs than the plan uses, and `runs` and `capped` have one value.\n const fewest: Row = new Map();\n for (const [converter, indexes] of runCols) {\n const weight = converter.perDay !== undefined && converter.perDay > 0 ? div(ONE, exact(converter.perDay)) : ONE;\n for (const index of indexes) addTo(fewest, index, weight);\n }\n const objectives: Objective[] = [\n { sense: \"max\", coefficients: dense(most, count) },\n { sense: \"min\", coefficients: dense(least, count) },\n { sense: \"min\", coefficients: dense(fewest, count) },\n ];\n const solved = solveLexicographic(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 at = (index: number): Rational => x[index] ?? ZERO;\n const takes: Record<string, Record<string, number>> = {};\n plan.forEach((draw, i) => {\n const record: Record<string, number> = {};\n for (const [resource, index] of shareCol[i] ?? []) if (sign(at(index)) > 0) record[resource] = toNumber(at(index));\n takes[draw.need] = record;\n });\n const runs: Record<string, number> = {};\n // A converter gives a need or a resource, so it is a cook or a maker, not the two.\n const ran = (converter: Converter, value: Rational): void => {\n if (sign(value) > 0) runs[converter.id] = toNumber(value);\n };\n cooks.forEach((cook, c) => ran(cook, at(cookCol[c] as number)));\n makers.forEach((maker, m) => ran(maker, makerCol.reduce((sum, row) => add(sum, at(row[m] as number)), ZERO)));\n\n const withStore = new Set(layer.stores.map((store) => store.resource));\n const closure = inputClosure(direct.map((use) => use.resource), cooks, makers);\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 reach = new Set([...cooks, ...makers.filter((maker) => closure.has(giftResource(maker) ?? \"\"))]);\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 = shareCol.reduce((sum, shares) => {\n const index = shares.get(resource);\n return index === undefined ? sum : add(sum, at(index));\n }, ZERO);\n return equals(taken, exact(stock.get(resource) ?? 0));\n })\n .sort();\n const best = solved.values[0] ?? ZERO;\n const used = (row: Row): Rational => [...row].reduce((sum, [index, value]) => add(sum, mul(value, at(index))), ZERO);\n const capped = sign(best) > 0\n ? [\n ...[...runCols.keys()].filter((converter) => converter.perDay !== undefined && !(converter.perDay > 0)),\n ...[...limits.values()].filter(({ row }) => sign(used(row)) === 0).flatMap(({ converters }) => 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\n/**\n * This function gives each resource that the plan can use: the direct resources and the inputs of the converters of the plan.\n * It also gives the inputs of their makers, through each chain.\n */\nfunction inputClosure(direct: readonly string[], cooks: readonly Converter[], makers: readonly Converter[]): Set<string> {\n const out = new Set<string>();\n const queue = [...direct, ...cooks.flatMap((cook) => [...inputsOf(cook).keys()])];\n for (let resource = queue.shift(); resource !== undefined; resource = queue.shift()) {\n if (out.has(resource)) continue;\n out.add(resource);\n for (const maker of makers) if (giftResource(maker) === resource) queue.push(...inputsOf(maker).keys());\n }\n return out;\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, 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/** This function gives the chance that a cut lasts more than `days`, linear between the points of the curve. After the last point it is 0. */\nexport function survivalAt(curve: Survival, days: number): number {\n if (days <= 0) return curve[0]?.[1] ?? 0;\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 (days < t1) {\n // The chance stays between the chances of the two points, so a rounding does not go below the lower one.\n const chance = p0 + (p1 - p0) * ((days - t0) / (t1 - t0));\n return Math.min(Math.max(p0, p1), Math.max(Math.min(p0, p1), chance));\n }\n if (days === t1) return p1;\n }\n return 0;\n}\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\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 return { event: eventStop(curves, keptStops), independent: independent ?? upper, upper, coarse: keptSets === undefined, independentUpper: independent === undefined };\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 */\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\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 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 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 };\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 *\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 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 cases.push({ case: caseCuts.case, rate, endurance, shortfall });\n }\n return { place, levels, independent, upper, unread, coarse, independentUpper, 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,O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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":[],"sources":["../src/joint.ts","../src/stops.ts","../src/shortfall.ts","../src/sample.ts"],"sourcesContent":["import { type Constraint, type Objective, solveLexicographic } from \"@mark1russell7/linear\";\nimport { add, div, equals, mul, neg, ONE, type Rational, sign, toNumber, ZERO } from \"@mark1russell7/rational\";\nimport { canRun, deviceKey, inputsOf } from \"./converter.ts\";\nimport { type CaseOptions, caseDraws, caseStopped, drawDemand, giftNeed, giftResource, storeAmounts } from \"./endurance.ts\";\nimport type { CaseCuts, Converter, EnduranceLayer, IsoDate } from \"./layer.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 direct = (layer.direct ?? []).filter((use) => planned.has(use.need) && use.amount > 0);\n const live = (layer.converters ?? []).filter((converter) => canRun(converter, stoppedParts));\n const cooks = live.filter((converter) => planned.has(giftNeed(converter) ?? \"\"));\n const makers = live.filter((converter) => giftResource(converter) !== undefined);\n const resources = new Set<string>([...direct.map((use) => use.resource), ...[...cooks, ...makers].flatMap((converter) => [...inputsOf(converter).keys()])]);\n for (const maker of makers) resources.add(giftResource(maker) ?? \"\");\n const stocked = [...resources].filter((resource) => (stock.get(resource) ?? 0) > 0).sort();\n\n // The variables: the days, the take of each direct use, the runs of each converter that gives a need of the plan,\n // and for each draw of the plan the runs of each maker and the share of each stock. The shares tell the takes of each draw.\n let count = 0;\n const next = (): number => count++;\n const days = next();\n const useCol = direct.map(next);\n const cookCol = cooks.map(next);\n const makerCol = plan.map(() => makers.map(next));\n const shareCol = plan.map(() => new Map(stocked.map((resource) => [resource, next()] as const)));\n\n const rows: { readonly row: Row; readonly relation: Constraint[\"relation\"]; readonly rhs: Rational }[] = [];\n plan.forEach((draw, i) => {\n // The need of the draw: its gifts are not less than its demand times the days.\n const need: Row = new Map([[days, neg(exact(drawDemand(draw, caseCuts)))]]);\n direct.forEach((use, k) => {\n if (use.need === draw.need) addTo(need, useCol[k] as number, exact(use.amount));\n });\n cooks.forEach((cook, c) => {\n if (giftNeed(cook) === draw.need) addTo(need, cookCol[c] as number, exact(cook.gives.amount));\n });\n rows.push({ row: need, relation: \">=\", rhs: ZERO });\n // The balance of each resource of the draw: its takes are not more than its share of the stock plus the gifts of its makers.\n const balance = new Map<string, Row>([...resources].map((resource) => [resource, new Map()]));\n const consume = (resource: string, index: number, amount: Rational): void => addTo(balance.get(resource) as Row, index, amount);\n direct.forEach((use, k) => {\n if (use.need === draw.need) consume(use.resource, useCol[k] as number, ONE);\n });\n cooks.forEach((cook, c) => {\n if (giftNeed(cook) !== draw.need) return;\n for (const [resource, each] of inputsOf(cook)) consume(resource, cookCol[c] as number, exact(each));\n });\n makers.forEach((maker, m) => {\n const index = makerCol[i]?.[m] as number;\n for (const [resource, each] of inputsOf(maker)) consume(resource, index, exact(each));\n consume(giftResource(maker) as string, index, neg(exact(maker.gives.amount)));\n });\n for (const [resource, index] of shareCol[i] ?? []) consume(resource, index, neg(ONE));\n for (const row of balance.values()) if (row.size > 0) rows.push({ row, relation: \"<=\", rhs: ZERO });\n });\n // The limit of each device: one run uses `1 / perDay` of a day of one device, so the runs use `devices` times `d` device-days or less.\n // The converters of one device share one limit. A converter with no device has a limit of its own. A limit of 0 stops the converter.\n const runCols = new Map<Converter, readonly number[]>([\n ...cooks.map((cook, c) => [cook, [cookCol[c] as number]] as const),\n ...makers.map((maker, m) => [maker, makerCol.map((row) => row[m] as number)] as const),\n ]);\n const limits = new Map<string, { readonly row: Row; readonly converters: Converter[] }>();\n for (const [converter, indexes] of runCols) {\n if (converter.perDay === undefined) continue;\n if (!(converter.perDay > 0)) {\n for (const index of indexes) rows.push({ row: new Map([[index, ONE]]), relation: \"<=\", rhs: ZERO });\n continue;\n }\n const key = deviceKey(converter);\n const limit = limits.get(key) ?? { row: new Map([[days, neg(exact(converter.devices ?? 1))]]), converters: [] };\n limits.set(key, limit);\n limit.converters.push(converter);\n for (const index of indexes) addTo(limit.row, index, div(ONE, exact(converter.perDay)));\n }\n for (const { row } of limits.values()) rows.push({ row, relation: \"<=\", rhs: ZERO });\n // The shares of each stock are not more than the stock.\n for (const resource of stocked) {\n const row: Row = new Map();\n for (const shares of shareCol) addTo(row, shares.get(resource) as number, ONE);\n rows.push({ row, relation: \"<=\", rhs: exact(stock.get(resource) ?? 0) });\n }\n\n const constraints: Constraint[] = rows.map(({ row, relation, rhs }) => ({ coefficients: dense(row, count), relation, rhs }));\n const most: Row = new Map([[days, ONE]]);\n const least: Row = new Map();\n for (const shares of shareCol) for (const [resource, index] of shares) addTo(least, index, div(ONE, exact(stock.get(resource) ?? 1)));\n // The third objective takes the fewest device-days: the runs over `perDay`, or the runs with no limit. Thus a converter whose inputs cost\n // no stock does not give more runs than the plan uses, and `runs` and `capped` have one value.\n const fewest: Row = new Map();\n for (const [converter, indexes] of runCols) {\n const weight = converter.perDay !== undefined && converter.perDay > 0 ? div(ONE, exact(converter.perDay)) : ONE;\n for (const index of indexes) addTo(fewest, index, weight);\n }\n const objectives: Objective[] = [\n { sense: \"max\", coefficients: dense(most, count) },\n { sense: \"min\", coefficients: dense(least, count) },\n { sense: \"min\", coefficients: dense(fewest, count) },\n ];\n const solved = solveLexicographic(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 at = (index: number): Rational => x[index] ?? ZERO;\n const takes: Record<string, Record<string, number>> = {};\n plan.forEach((draw, i) => {\n const record: Record<string, number> = {};\n for (const [resource, index] of shareCol[i] ?? []) if (sign(at(index)) > 0) record[resource] = toNumber(at(index));\n takes[draw.need] = record;\n });\n const runs: Record<string, number> = {};\n // A converter gives a need or a resource, so it is a cook or a maker, not the two.\n const ran = (converter: Converter, value: Rational): void => {\n if (sign(value) > 0) runs[converter.id] = toNumber(value);\n };\n cooks.forEach((cook, c) => ran(cook, at(cookCol[c] as number)));\n makers.forEach((maker, m) => ran(maker, makerCol.reduce((sum, row) => add(sum, at(row[m] as number)), ZERO)));\n\n const withStore = new Set(layer.stores.map((store) => store.resource));\n const closure = inputClosure(direct.map((use) => use.resource), cooks, makers);\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 reach = new Set([...cooks, ...makers.filter((maker) => closure.has(giftResource(maker) ?? \"\"))]);\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 = shareCol.reduce((sum, shares) => {\n const index = shares.get(resource);\n return index === undefined ? sum : add(sum, at(index));\n }, ZERO);\n return equals(taken, exact(stock.get(resource) ?? 0));\n })\n .sort();\n const best = solved.values[0] ?? ZERO;\n const used = (row: Row): Rational => [...row].reduce((sum, [index, value]) => add(sum, mul(value, at(index))), ZERO);\n const capped = sign(best) > 0\n ? [\n ...[...runCols.keys()].filter((converter) => converter.perDay !== undefined && !(converter.perDay > 0)),\n ...[...limits.values()].filter(({ row }) => sign(used(row)) === 0).flatMap(({ converters }) => 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\n/**\n * This function gives each resource that the plan can use: the direct resources and the inputs of the converters of the plan.\n * It also gives the inputs of their makers, through each chain.\n */\nfunction inputClosure(direct: readonly string[], cooks: readonly Converter[], makers: readonly Converter[]): Set<string> {\n const out = new Set<string>();\n const queue = [...direct, ...cooks.flatMap((cook) => [...inputsOf(cook).keys()])];\n for (let resource = queue.shift(); resource !== undefined; resource = queue.shift()) {\n if (out.has(resource)) continue;\n out.add(resource);\n for (const maker of makers) if (giftResource(maker) === resource) queue.push(...inputsOf(maker).keys());\n }\n return out;\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, 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/** This function gives the chance that a cut lasts more than `days`, linear between the points of the curve. After the last point it is 0. */\nexport function survivalAt(curve: Survival, days: number): number {\n if (days <= 0) return curve[0]?.[1] ?? 0;\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 (days < t1) {\n // The chance stays between the chances of the two points, so a rounding does not go below the lower one.\n const chance = p0 + (p1 - p0) * ((days - t0) / (t1 - t0));\n return Math.min(Math.max(p0, p1), Math.max(Math.min(p0, p1), chance));\n }\n if (days === t1) return p1;\n }\n return 0;\n}\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,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AChG;AACF"}
@@ -1,5 +1,5 @@
1
1
  import { t as ENDURANCE_SCHEMA } from "./layer-a3Fr70Uh.js";
2
- import { curveFault, curveFault as curveFault$1, dayNumber, joinRecords, joinSetting, stopped } from "@mark1russell7/system-stack";
2
+ import { CUT_BOUNDS, curveFault, curveFault as curveFault$1, dayNumber, isCutBound, joinRecords, joinSetting, stopped } from "@mark1russell7/system-stack";
3
3
  import { solveLexicographic } from "@mark1russell7/linear";
4
4
  import { ONE, ZERO, add, div, fromFloat, mul, neg, sign, toNumber } from "@mark1russell7/rational";
5
5
  import { stronglyConnectedComponents } from "@mark1russell7/collections/graph";
@@ -568,6 +568,7 @@ function capacity(start, ways) {
568
568
  * - `endurance-converter-empty`: a converter takes nothing, or it gives an amount of 0.
569
569
  * - `endurance-curve`: a survival curve does not start at `[0, 1]`, or it does not end at a chance of 0.
570
570
  * Or its days do not increase, or its chance increases.
571
+ * - `endurance-bound`: the bound of a cut is not a value of `CUT_BOUNDS` of the core. Since 0.8.4.
571
572
  * - `endurance-prior-case`: a prior names a case that the layer does not have.
572
573
  * - `endurance-cycle`: converters make a resource from itself, through one converter or a chain. One fault names each cycle.
573
574
  * - `endurance-devices`: two converters of one device give two different counts of devices.
@@ -585,6 +586,7 @@ const ENDURANCE_CODES = [
585
586
  "endurance-date",
586
587
  "endurance-converter-empty",
587
588
  "endurance-curve",
589
+ "endurance-bound",
588
590
  "endurance-prior-case",
589
591
  "endurance-cycle",
590
592
  "endurance-devices",
@@ -699,6 +701,7 @@ function checkEndurance(layer, stack) {
699
701
  for (const cut of item.cuts) {
700
702
  const at = `${item.case}/${cut.part}`;
701
703
  part(at, "cut", cut.part);
704
+ if (cut.bound !== void 0 && !isCutBound(cut.bound)) add("error", "endurance-bound", at, `The bound of the cut "${at}" is ${JSON.stringify(cut.bound)}. It must be one of ${CUT_BOUNDS.join(", ")}.`);
702
705
  if (cut.duration === void 0) {
703
706
  add("warning", "endurance-cut-no-curve", at, `The cut "${at}" has no curve of its duration, so the draws that it can stop are no read.`);
704
707
  continue;
@@ -804,4 +807,4 @@ function joinEndurance(pieces) {
804
807
  }
805
808
  export { deviceKey as _, hasEnduranceError as a, drawDemand as c, giftResource as d, storeAmounts as f, canRun as g, exact as h, curveFault as i, enduranceOf as l, dense as m, ENDURANCE_CODES as n, caseDraws as o, addTo as p, checkEndurance as r, caseStopped as s, joinEndurance as t, giftNeed as u, inputsOf as v };
806
809
 
807
- //# sourceMappingURL=join-DQxIAP0v.js.map
810
+ //# sourceMappingURL=join-DdVFmRh6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"join-DdVFmRh6.js","names":["curveFault"],"sources":["../src/converter.ts","../src/fit.ts","../src/rows.ts","../src/share.ts","../src/endurance.ts","../src/check.ts","../src/join.ts"],"sourcesContent":["import type { Converter } from \"./layer.ts\";\n\n// The internal rules of a converter that the endurance query and the joint days share. The root entry does not give them.\n\n/** This function gives the amount of each resource that one run of a converter takes. Two lines of one resource add. */\nexport function inputsOf(converter: Converter): Map<string, number> {\n const out = new Map<string, number>();\n for (const input of converter.takes) if (input.amount > 0) out.set(input.resource, (out.get(input.resource) ?? 0) + input.amount);\n return out;\n}\n\n/** This function tells if a converter can run in a case. Its device works, it takes a resource, and it gives an amount more than 0. */\nexport function canRun(converter: Converter, stoppedParts: ReadonlySet<string>): boolean {\n return converter.gives.amount > 0 && inputsOf(converter).size > 0 && (converter.device === undefined || !stoppedParts.has(converter.device));\n}\n\n/**\n * This function gives the key of the device-days that a converter uses. The converters of one device share one key.\n * A converter with no device has a key of its own.\n */\nexport function deviceKey(converter: Converter): string {\n return converter.device === undefined ? `converter:${converter.id}` : `device:${converter.device}`;\n}\n","/** The relative tolerance of a take and of a fit. */\nexport const TOLERANCE = 1e-13;\n\n/** One try of a fit: the amount that the stores could not give, out of the amount wanted, and the value of the try. */\nexport interface Try<T> {\n readonly short: number;\n readonly need: number;\n readonly value: T;\n}\n\n/** The result of a fit: the largest amount with no shortfall, and the value of its try. The value is `undefined` when only 0 fits. */\nexport interface Fit<T> {\n readonly x: number;\n readonly value: T | undefined;\n}\n\n/**\n * The count of the tries of `largestFit`, for the tests of the cost. It is not in the public API, and it does not change a result.\n * It is the one side effect of `largestFit` and of the queries that use it.\n */\nexport const fitTries = { count: 0 };\n\n/**\n * This function gives the largest `x` in `[0, most]` at which `attempt` has no shortfall, to the relative tolerance `TOLERANCE`.\n *\n * - A try fits when its shortfall is not more than `TOLERANCE` times its need.\n * - The shortfall must not decrease when `x` increases. A take of a chain of converters gives a shortfall that is linear in parts.\n * - The first try is `most`. After it, each step tries the zero of the line through the last two tries that do not fit.\n * With one try that does not fit, the step tries `x` times the part of the need that the stores gave.\n * - When a step does not halve the interval, the next step is a bisection. Thus a fit takes at most approximately twice the steps of a bisection.\n * - A step on the lower end tries a point just above it, so a correct estimate ends the fit in one more try.\n * - An estimate that fits with a shortfall above 0 is in the band of the tolerance above the zero, so the fit ends there.\n * A bisection step or a probe at the lower end can fit with a shortfall of rounding below the zero. The fit does not end there.\n *\n * @param most - The upper limit of `x`\n * @param attempt - The try at an amount. It must not change its input\n * @returns The largest amount that fits, and the value of its try\n */\nexport function largestFit<T>(most: number, attempt: (x: number) => Try<T>): Fit<T> {\n const fits = (tried: Try<T>): boolean => tried.short <= TOLERANCE * tried.need;\n fitTries.count += 1;\n const first = attempt(most);\n if (fits(first)) return { x: most, value: first.value };\n let low = 0;\n let best: T | undefined;\n let high = most;\n let highShort = first.short;\n let highNeed = first.need;\n let before: { readonly x: number; readonly short: number } | undefined;\n let bisect = false;\n for (let step = 0; step < 400 && high - low > 4 * TOLERANCE * high; step += 1) {\n const width = high - low;\n let x: number;\n if (bisect) x = (low + high) / 2;\n else if (before !== undefined && before.short > highShort) x = high - (highShort * (before.x - high)) / (before.short - highShort);\n else x = high * (1 - highShort / highNeed);\n // Only a secant or ratio estimate through tries that do not fit lands at or above the zero of a convex shortfall.\n const estimate = !bisect && x < high;\n if (!(x < high)) x = (low + high) / 2;\n const floor = low + 2 * TOLERANCE * high;\n const clamped = !(x > floor);\n if (clamped) x = floor;\n fitTries.count += 1;\n const tried = attempt(x);\n if (fits(tried)) {\n low = x;\n best = tried.value;\n // An estimate that fits with a shortfall is in the band of the tolerance above the zero, so the fit ends.\n if (tried.short > 0 && estimate && !clamped) break;\n } else {\n before = { x: high, short: highShort };\n high = x;\n highShort = tried.short;\n highNeed = tried.need;\n }\n bisect = !bisect && high - low > width / 2;\n }\n return { x: low, value: best };\n}\n","import { add, fromFloat, type Rational, ZERO } from \"@mark1russell7/rational\";\n\n// The internal rows of the linear programs of the queries. The root entry does not give them.\n\n/** A sparse row: the coefficient of each variable, by its index. */\nexport type Row = Map<number, Rational>;\n\n/** This function adds `value` to the coefficient of the variable `index` in `row`. It changes `row`. */\nexport function addTo(row: Row, index: number, value: Rational): void {\n row.set(index, add(row.get(index) ?? ZERO, value));\n}\n\n/** This function gives the dense form of a row: one coefficient for each of `count` variables. */\nexport function dense(row: Row, count: number): Rational[] {\n const out = new Array<Rational>(count).fill(ZERO);\n for (const [index, value] of row) out[index] = value;\n return out;\n}\n\n/** This function gives the exact rational of a finite double, with no rounding. A double is a dyadic rational. */\nexport function exact(value: number): Rational {\n return fromFloat(value);\n}\n","import { type Constraint, type Objective, solveLexicographic } from \"@mark1russell7/linear\";\nimport { add, div, mul, neg, ONE, type Rational, sign, toNumber, ZERO } from \"@mark1russell7/rational\";\nimport { deviceKey, inputsOf } from \"./converter.ts\";\nimport type { Converter, DirectUse } from \"./layer.ts\";\nimport { addTo, dense, exact, type Row } from \"./rows.ts\";\n\n// The best share of one draw: a linear program over the totals of its days, with exact rationals (@mark1russell7/linear).\n// The endurance query uses it for a draw whose converters share the days of a device. The root entry does not give it.\n\n/** The input of the best share of one draw. */\nexport interface ShareInput {\n /** The stock of each resource that the draw can take, by the code of the resource. */\n readonly stock: ReadonlyMap<string, number>;\n /** The device-days of each day that the draw can use, by the key of the device (`deviceKey`). */\n readonly room: ReadonlyMap<string, number>;\n /** The direct uses that give the need of the draw. */\n readonly direct: readonly DirectUse[];\n /** The converters that give the need of the draw. */\n readonly converters: readonly Converter[];\n /** The converters that make each resource, by the code of the resource. */\n readonly makers: ReadonlyMap<string, readonly Converter[]>;\n /** The amount of the need for each day. It is more than 0. */\n readonly demand: number;\n}\n\n/** The best share of one draw: its days, the take of each stock and the device-days of each device. */\nexport interface Share {\n /** The largest count of days at which the draw gets its demand. */\n readonly days: number;\n /** The amount of each resource that the draw takes from the stock. A resource with no take is not in the map. */\n readonly taken: ReadonlyMap<string, number>;\n /** The device-days that the runs use in `days`, by the key of the device. A device with no use is not in the map. */\n readonly used: ReadonlyMap<string, number>;\n}\n\n/** This function gives the makers that a draw can use: the makers of its inputs, through each chain. */\nfunction reachedMakers(input: ShareInput): Converter[] {\n const out = new Set<Converter>();\n const seen = new Set<string>();\n const queue = [...input.direct.map((use) => use.resource), ...input.converters.flatMap((converter) => [...inputsOf(converter).keys()])];\n for (let resource = queue.shift(); resource !== undefined; resource = queue.shift()) {\n if (seen.has(resource)) continue;\n seen.add(resource);\n for (const maker of input.makers.get(resource) ?? []) {\n out.add(maker);\n queue.push(...inputsOf(maker).keys());\n }\n }\n return [...out];\n}\n\n/**\n * This function gives the best share of the stocks and of the device-days for one draw.\n * It gives `undefined` when the program has no optimum.\n *\n * - The variables are the days `T`, the take of each direct use, the runs of each converter and maker, and the take of each stock.\n * - The gifts of the direct uses and of the converters are not less than `T` times the demand.\n * - The takes of each resource are not more than the take of its stock plus the gifts of its makers. The take of a stock is not more than the stock.\n * - The runs of the converters of one device use `room` times `T` device-days or less. One run uses `1 / perDay` of a device-day. A limit of 0 stops the converter.\n * - The first objective takes the largest `T`. The second takes the smallest sum of the takes of the stocks, each over its stock. The third takes the fewest device-days.\n *\n * The gifts at `T` days are a concave function of `T`, and they are 0 at 0. Thus each count of days up to the largest `T` also fits.\n *\n * @param input - The stocks, the device-days of each day, the ways of the draw and its demand\n * @returns The days, the takes of the stocks and the device-days of each device\n */\nexport function bestShare(input: ShareInput): Share | undefined {\n const makers = reachedMakers(input);\n const resources = new Set<string>([...input.direct.map((use) => use.resource), ...[...input.converters, ...makers].flatMap((converter) => [...inputsOf(converter).keys()])]);\n for (const maker of makers) if (\"resource\" in maker.gives && maker.gives.resource !== undefined) resources.add(maker.gives.resource);\n const stocked = [...resources].filter((resource) => (input.stock.get(resource) ?? 0) > 0).sort();\n\n let count = 0;\n const next = (): number => count++;\n const days = next();\n const useCol = input.direct.map(next);\n const runs = new Map<Converter, number>([...input.converters, ...makers].map((converter) => [converter, next()] as const));\n const shareCol = new Map(stocked.map((resource) => [resource, next()] as const));\n\n const rows: { readonly row: Row; readonly relation: Constraint[\"relation\"]; readonly rhs: Rational }[] = [];\n // The need: the gifts are not less than the demand times the days.\n const need: Row = new Map([[days, neg(exact(input.demand))]]);\n input.direct.forEach((use, k) => addTo(need, useCol[k] as number, exact(use.amount)));\n for (const converter of input.converters) addTo(need, runs.get(converter) as number, exact(converter.gives.amount));\n rows.push({ row: need, relation: \">=\", rhs: ZERO });\n // The balance of each resource: its takes are not more than the take of its stock plus the gifts of its makers.\n const balance = new Map<string, Row>([...resources].map((resource) => [resource, new Map()]));\n const consume = (resource: string, index: number, amount: Rational): void => addTo(balance.get(resource) as Row, index, amount);\n input.direct.forEach((use, k) => consume(use.resource, useCol[k] as number, ONE));\n for (const [converter, index] of runs) {\n for (const [resource, each] of inputsOf(converter)) consume(resource, index, exact(each));\n if (\"resource\" in converter.gives && converter.gives.resource !== undefined) consume(converter.gives.resource, index, neg(exact(converter.gives.amount)));\n }\n for (const [resource, index] of shareCol) consume(resource, index, neg(ONE));\n for (const row of balance.values()) if (row.size > 0) rows.push({ row, relation: \"<=\", rhs: ZERO });\n // The take of each stock is not more than the stock.\n for (const [resource, index] of shareCol) rows.push({ row: new Map([[index, ONE]]), relation: \"<=\", rhs: exact(input.stock.get(resource) ?? 0) });\n // The limit of each device: the runs use `room` times `T` device-days or less. The converters of one device share one limit.\n const limits = new Map<string, Row>();\n for (const [converter, index] of runs) {\n if (converter.perDay === undefined) continue;\n if (!(converter.perDay > 0)) {\n rows.push({ row: new Map([[index, ONE]]), relation: \"<=\", rhs: ZERO });\n continue;\n }\n const key = deviceKey(converter);\n const limit = limits.get(key) ?? new Map([[days, neg(exact(input.room.get(key) ?? 0))]]);\n limits.set(key, limit);\n addTo(limit, index, div(ONE, exact(converter.perDay)));\n }\n for (const row of limits.values()) rows.push({ row, relation: \"<=\", rhs: ZERO });\n\n const most: Row = new Map([[days, ONE]]);\n const least: Row = new Map();\n for (const [resource, index] of shareCol) addTo(least, index, div(ONE, exact(input.stock.get(resource) ?? 1)));\n const fewest: Row = new Map();\n for (const [converter, index] of runs) addTo(fewest, index, converter.perDay !== undefined && converter.perDay > 0 ? div(ONE, exact(converter.perDay)) : ONE);\n const objectives: Objective[] = [\n { sense: \"max\", coefficients: dense(most, count) },\n { sense: \"min\", coefficients: dense(least, count) },\n { sense: \"min\", coefficients: dense(fewest, count) },\n ];\n const constraints: Constraint[] = rows.map(({ row, relation, rhs }) => ({ coefficients: dense(row, count), relation, rhs }));\n const solved = solveLexicographic(constraints, objectives);\n // The point 0 is feasible, and the later objectives are not less than 0. Thus only an unbounded first stage has no optimum.\n if (solved.status !== \"optimal\") return undefined;\n\n const at = (index: number): Rational => solved.x[index] ?? ZERO;\n const taken = new Map<string, number>();\n for (const [resource, index] of shareCol) if (sign(at(index)) > 0) taken.set(resource, toNumber(at(index)));\n const used = new Map<string, number>();\n for (const [key, row] of limits) {\n let sum: Rational = ZERO;\n for (const [index, value] of row) if (index !== days) sum = add(sum, mul(value, at(index)));\n if (sign(sum) > 0) used.set(key, toNumber(sum));\n }\n return { days: toNumber(at(days)), taken, used };\n}\n","import { dayNumber, stopped, type Stack } from \"@mark1russell7/system-stack\";\nimport { canRun, deviceKey, inputsOf } from \"./converter.ts\";\nimport { largestFit, type Try } from \"./fit.ts\";\nimport type { CaseCuts, Converter, DirectUse, Draw, Endurance, EnduranceLayer, IsoDate } from \"./layer.ts\";\nimport { bestShare } from \"./share.ts\";\n\n// The endurance query: the days that each draw holds when a case stops its supply.\n\n/** The options of the queries of a case. */\nexport interface CaseOptions {\n /** The date of the query. A store whose due date is on this date or before it gives nothing. */\n readonly at: IsoDate;\n /** The base stack. With it, a cut also stops each part that cannot work without a cut part (`stopped` of the core). */\n readonly stack?: Stack | undefined;\n /** The `id` of more parts that are down, with the cuts of the case. */\n readonly down?: readonly string[] | undefined;\n}\n\n/**\n * This function gives the `id` of each part that does not work in a case: the cut parts and the parts of `down`.\n * With a stack, it also gives each part that stops.\n */\nexport function caseStopped(caseCuts: CaseCuts, options: Pick<CaseOptions, \"stack\" | \"down\">): Set<string> {\n const down = [...caseCuts.cuts.map((cut) => cut.part), ...(options.down ?? [])];\n const out = new Set(down);\n if (options.stack !== undefined) for (const id of stopped(options.stack, down)) out.add(id);\n return out;\n}\n\n/** This function gives the day number of a date, or throws a `RangeError` for a date that is not `YYYY-MM-DD`. */\nfunction dayOf(date: IsoDate): number {\n const day = dayNumber(date);\n if (day === undefined) throw new RangeError(`The date \"${date}\" is not a date YYYY-MM-DD.`);\n return day;\n}\n\n/**\n * This function gives the amount of each resource in the stores at a date, by the code of the resource.\n *\n * - A store gives nothing on its due date and after it.\n * - A store gives nothing when its part is in `stoppedParts`.\n */\nexport function storeAmounts(layer: EnduranceLayer, at: IsoDate, stoppedParts: ReadonlySet<string> = new Set()): Map<string, number> {\n const today = dayOf(at);\n const out = new Map<string, number>();\n for (const store of layer.stores) {\n if (store.due !== undefined && today >= dayOf(store.due)) continue;\n if (store.part !== undefined && stoppedParts.has(store.part)) continue;\n out.set(store.resource, (out.get(store.resource) ?? 0) + store.amount);\n }\n return out;\n}\n\n/** This function gives the amount of a need for each day in a case: the rate of the draw times the factor of the case. */\nexport function drawDemand(draw: Draw, caseCuts: CaseCuts): number {\n return draw.perDay * (caseCuts.factors?.[draw.need] ?? 1);\n}\n\n/**\n * This function gives the draws that take from the stores in a case: each draw whose supply stops, with a demand more than 0.\n * The sequence is by the level (the order of `levels`), then by the code of the need.\n */\nexport function caseDraws(layer: EnduranceLayer, caseCuts: CaseCuts, stoppedParts: ReadonlySet<string>): Draw[] {\n const rank = (level: string): number => {\n const index = layer.levels.indexOf(level);\n return index < 0 ? layer.levels.length : index;\n };\n return layer.draws\n .filter((draw) => stoppedParts.has(draw.supply) && drawDemand(draw, caseCuts) > 0)\n .sort((a, b) => rank(a.level) - rank(b.level) || (a.need < b.need ? -1 : a.need > b.need ? 1 : 0));\n}\n\n/** This function gives the need that a converter gives, or `undefined` when it gives a resource. */\nexport function giftNeed(converter: Converter): string | undefined {\n return \"need\" in converter.gives ? converter.gives.need : undefined;\n}\n\n/** This function gives the resource that a converter gives, or `undefined` when it gives a need. */\nexport function giftResource(converter: Converter): string | undefined {\n return \"resource\" in converter.gives ? converter.gives.resource : undefined;\n}\n\n/** The converters of a case that make each resource, in the order of the layer, by the code of the resource. */\ntype Makers = ReadonlyMap<string, readonly Converter[]>;\n\nfunction makersOf(layer: EnduranceLayer, stoppedParts: ReadonlySet<string>): Makers {\n const out = new Map<string, Converter[]>();\n for (const converter of layer.converters ?? []) {\n const resource = giftResource(converter);\n if (resource === undefined || !canRun(converter, stoppedParts)) continue;\n out.set(resource, [...(out.get(resource) ?? []), converter]);\n }\n return out;\n}\n\n/** The ways to get one need in a case: its direct uses, then the converters that give it, in the order of the layer. `makers` make the resources. */\ninterface Ways {\n readonly direct: readonly DirectUse[];\n readonly converters: readonly Converter[];\n readonly makers: Makers;\n}\n\nfunction waysOf(layer: EnduranceLayer, need: string, stoppedParts: ReadonlySet<string>, makers: Makers): Ways {\n return {\n direct: (layer.direct ?? []).filter((use) => use.need === need && use.amount > 0),\n converters: (layer.converters ?? []).filter((converter) => giftNeed(converter) === need && canRun(converter, stoppedParts)),\n makers,\n };\n}\n\n// A chain: the resources on the path of a take. A maker does not take a resource of its own path, so a cycle of the layer stops there.\nconst NO_PATH: ReadonlySet<string> = new Set();\n\n// The device-days that are left to the converters with a limit `perDay` are in the map of the resources, under a key that\n// no code of a resource has. Thus each copy of the map in a try copies them too. The converters of one device share one\n// key (`deviceKey`), and a converter with no device has a key of its own. One run of a converter uses `1 / perDay` of a device-day.\nconst RUNS = \"\\u0000runs:\";\n\nfunction runsKey(converter: Converter): string {\n return RUNS + deviceKey(converter);\n}\n\n/** This function gives the device-days that a converter has left in `left`, or undefined with no limit. */\nfunction daysLeft(left: ReadonlyMap<string, number>, converter: Converter): number | undefined {\n return converter.perDay === undefined ? undefined : left.get(runsKey(converter));\n}\n\n/** This function gives the map with no runs left of the converters: a map of the resources only. */\nfunction resourcesOnly(left: ReadonlyMap<string, number>): Map<string, number> {\n return new Map([...left].filter(([key]) => !key.startsWith(RUNS)));\n}\n\n/**\n * This function gives the most of a resource that `left` gives: its stock, and the runs of each maker.\n * It is an upper limit. When two inputs come from one resource, the true amount can be less.\n */\nfunction mostResource(left: ReadonlyMap<string, number>, makers: Makers, resource: string, path: ReadonlySet<string>): number {\n let total = left.get(resource) ?? 0;\n if (path.has(resource)) return total;\n const next = new Set(path).add(resource);\n for (const maker of makers.get(resource) ?? []) total += mostRuns(left, makers, maker, next) * maker.gives.amount;\n return total;\n}\n\n/** This function gives the most runs of a converter that `left` gives. It is an upper limit, as for `mostResource`. */\nfunction mostRuns(left: ReadonlyMap<string, number>, makers: Makers, converter: Converter, path: ReadonlySet<string>): number {\n const limit = daysLeft(left, converter);\n let runs = limit === undefined ? Infinity : limit * (converter.perDay ?? 0);\n for (const [resource, each] of inputsOf(converter)) runs = Math.min(runs, mostResource(left, makers, resource, path) / each);\n return Number.isFinite(runs) ? runs : 0;\n}\n\n/**\n * This function takes an amount of a resource from `left`: the stock first, then the makers in the order of the layer.\n * It changes `left`, and it gives the amount that it could not take.\n */\nfunction takeResource(left: Map<string, number>, makers: Makers, resource: string, amount: number, path: ReadonlySet<string>): number {\n const has = left.get(resource) ?? 0;\n const got = Math.min(amount, has);\n left.set(resource, has - got);\n let rest = amount - got;\n if (rest <= 0 || path.has(resource)) return Math.max(0, rest);\n const next = new Set(path).add(resource);\n for (const maker of makers.get(resource) ?? []) {\n if (rest <= 0) break;\n rest -= run(left, makers, maker, rest / maker.gives.amount, next) * maker.gives.amount;\n }\n return Math.max(0, rest);\n}\n\n/**\n * This function runs a converter up to `wanted` times with the resources of `left`, and it gives the count of runs.\n * It changes `left`. When two inputs come from one resource, `largestFit` finds the runs that the resources give.\n */\nfunction run(left: Map<string, number>, makers: Makers, converter: Converter, wanted: number, path: ReadonlySet<string>): number {\n const inputs = inputsOf(converter);\n const most = Math.min(wanted, mostRuns(left, makers, converter, path));\n if (!(most > 0)) return 0;\n const attempt = (runs: number): Try<Map<string, number>> => {\n const copy = new Map(left);\n let need = 0;\n let short = 0;\n // The converter takes its device-days before its inputs. Thus a maker on the same device gets only the rest.\n const limit = daysLeft(copy, converter);\n if (limit !== undefined && converter.perDay !== undefined && converter.perDay > 0) {\n const wanted = runs / converter.perDay;\n const got = Math.min(wanted, limit);\n copy.set(runsKey(converter), limit - got);\n need += runs;\n short += (wanted - got) * converter.perDay;\n }\n for (const [resource, each] of inputs) {\n need += runs * each;\n short += takeResource(copy, makers, resource, runs * each, path);\n }\n return { short, need, value: copy };\n };\n const { x: runs, value: best } = largestFit(most, attempt);\n if (best === undefined) return 0;\n for (const [resource, amount] of best) left.set(resource, amount);\n return runs;\n}\n\n/**\n * This function takes an amount of a need from the resources in `left`: the direct uses first, then the converters.\n * A direct use or a converter takes each resource from its stock first, then from its makers.\n * It changes `left`, and it gives the amount that it could not take.\n */\nfunction take(left: Map<string, number>, ways: Ways, amount: number): number {\n let rest = amount;\n for (const use of ways.direct) {\n if (rest <= 0) break;\n const wanted = rest / use.amount;\n rest -= (wanted - takeResource(left, ways.makers, use.resource, wanted, NO_PATH)) * use.amount;\n }\n for (const converter of ways.converters) {\n if (rest <= 0) break;\n rest -= run(left, ways.makers, converter, rest / converter.gives.amount, NO_PATH) * converter.gives.amount;\n }\n return Math.max(0, rest);\n}\n\n/** This function gives each resource that a need can use: the inputs of its ways, and the inputs of their makers, through each chain. */\nfunction inputClosure(ways: Ways): Set<string> {\n const out = new Set<string>();\n const queue = [...ways.direct.map((use) => use.resource), ...ways.converters.flatMap((converter) => [...inputsOf(converter).keys()])];\n for (let resource = queue.shift(); resource !== undefined; resource = queue.shift()) {\n if (out.has(resource)) continue;\n out.add(resource);\n for (const maker of ways.makers.get(resource) ?? []) queue.push(...inputsOf(maker).keys());\n }\n return out;\n}\n\n/** The relative tolerance of a used-up resource. */\nconst USED_UP = 1e-9;\n\n/**\n * This function gives the days that each draw holds when a case stops its supply, and the resources that are used up then.\n *\n * - A draw takes from the stores only when the case stops its supply part. Each other draw holds without end, and the result leaves it out.\n * - The demand of a draw for each day is its rate times the factor of the case.\n * - The draws take the resources in the order of their level, then of their codes. A draw takes from its direct uses first, then from its converters.\n * - The days of a draw are the largest `T` at which the stores give `T` days of its demand, after each higher draw.\n * - Each higher draw keeps back its own days times its demand. Thus the takes of all the draws are not more than the stores at any time.\n * - The take order is a rule, not the best share: the direct uses in the order of the list, then the converters. The days are the days of this order.\n * A draw with a shared device is different. Refer to the last item.\n * - A converter whose device stops gives nothing. A store whose part stops gives nothing.\n * - A converter can give a resource. A take of a resource uses the stock first, then the converters that make it, through each chain.\n * - A converter with a limit `perDay` runs `perDay` times `devices` times `T` times or less in `T` days. The converters of one device share it.\n * - The higher draws use the runs of a limit first.\n * - A higher draw keeps back its runs of each day for all the days of a lower draw, also when its own days are fewer. This is the safe side.\n * - Two limited converters of one device can make the shortfall of the take order decrease when the days increase.\n * Thus a draw whose ways reach two converters of one device, each with a limit `perDay` more than 0, does not use the take order.\n * A linear program with exact rationals gives its days: the largest `T` with the best share of its stocks and of the device-days.\n * At this `T`, the draw takes the smallest sum of its takes of the stocks, each over its stock, then the fewest device-days.\n *\n * The function is pure, but for an internal count of the tries of its fits for the tests. It throws a `RangeError` for a date that is not `YYYY-MM-DD`. The gate `checkEndurance` examines the layer before.\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 */\nexport function enduranceOf(layer: EnduranceLayer, caseCuts: CaseCuts, options: CaseOptions): Endurance {\n const stoppedParts = caseStopped(caseCuts, options);\n const start = storeAmounts(layer, options.at, stoppedParts);\n const makers = makersOf(layer, stoppedParts);\n const stocked = new Set(layer.stores.map((store) => store.resource));\n const limited = (layer.converters ?? []).filter((converter) => converter.perDay !== undefined && canRun(converter, stoppedParts));\n // The count of devices of each key (`deviceKey`). The gate refuses two counts for one device.\n const devices = new Map(limited.map((converter) => [deviceKey(converter), converter.devices ?? 1]));\n // The device-days of each day that the higher draws use, by the key of the device. A higher draw keeps back its\n // device-days of each day for all the days of a lower draw, also after its own days end. This is the safe side.\n const used = new Map<string, number>();\n // The stocks that the higher draws leave after their own days.\n let before = new Map(start);\n const needs: Record<string, { days: number; binding: string[]; takes: Record<string, number>; capped?: string[] }> = {};\n for (const draw of caseDraws(layer, caseCuts, stoppedParts)) {\n const ways = waysOf(layer, draw.need, stoppedParts, makers);\n const demand = drawDemand(draw, caseCuts);\n // The device-days of each day that the higher draws leave to this draw, by the key of the device.\n const room = new Map([...devices].map(([key, count]) => [key, Math.max(0, count - (used.get(key) ?? 0))] as const));\n const closure = inputClosure(ways);\n // The converters that the draw can use: the converters that give its need, and the makers of its inputs through each chain.\n const reach = new Set([...ways.converters, ...[...closure].flatMap((resource) => makers.get(resource) ?? [])]);\n // With two limited converters of one device, the shortfall of the take order can decrease when the days increase.\n // For such a draw, a linear program gives the best share of the device-days and of the stocks.\n const share = sharesDevice(reach) ? bestShare({ stock: before, room, direct: ways.direct, converters: ways.converters, makers, demand }) : undefined;\n let low: number;\n let left: Map<string, number>;\n if (share !== undefined) {\n low = share.days;\n left = new Map(before);\n for (const [resource, amount] of share.taken) left.set(resource, Math.max(0, (left.get(resource) ?? 0) - amount));\n for (const [key, free] of room) left.set(RUNS + key, Math.max(0, free * low - (share.used.get(key) ?? 0)));\n } else {\n const after = (days: number): { left: Map<string, number>; short: number } => {\n const tried = new Map(before);\n for (const [key, free] of room) tried.set(RUNS + key, free * days);\n return { left: tried, short: take(tried, ways, days * demand) };\n };\n // The upper limit: the days that the draw holds when it takes all the stores itself. `largestFit` finds the days below it.\n const fit = largestFit(capacity(start, ways) / demand, (days) => {\n const tried = after(days);\n return { short: tried.short, need: days * demand, value: tried.left };\n });\n low = fit.x;\n left = fit.value ?? after(low).left;\n }\n // The binding resources are of the stores only: a used-up limit of runs is in `capped`, not here.\n const stores = resourcesOnly(left);\n const binding = [...closure]\n .filter((resource) => !makers.has(resource) || stocked.has(resource))\n .filter((resource) => mostResource(stores, makers, resource, NO_PATH) <= USED_UP * Math.max(1, start.get(resource) ?? 0))\n .sort();\n const takes: Record<string, number> = {};\n for (const [resource, amount] of before) {\n const taken = amount - (left.get(resource) ?? 0);\n if (taken > 0) takes[resource] = taken;\n }\n // A limit stops the draw when its limit gives the converter no runs left, and its inputs give more runs.\n // The runs left are the device-days left times `perDay`. Thus a limit of 0 stops the draw, also with its device-days left.\n const runsLeft = (converter: Converter): number => (daysLeft(left, converter) ?? 0) * (converter.perDay ?? 0);\n const runsGiven = (converter: Converter): number => (devices.get(deviceKey(converter)) ?? 1) * (converter.perDay ?? 0) * low;\n const capped = limited\n .filter((converter) => reach.has(converter))\n .filter((converter) => runsLeft(converter) <= USED_UP * Math.max(1, runsGiven(converter)))\n .filter((converter) => mostRuns(stores, makers, converter, NO_PATH) > USED_UP)\n .map((converter) => converter.id)\n .sort();\n needs[draw.need] = capped.length === 0 ? { days: low, binding, takes } : { days: low, binding, takes, capped };\n // The device-days of each day of this draw count against each lower draw, for all of its days.\n if (low > 0) for (const [key, free] of room) used.set(key, (used.get(key) ?? 0) + (free * low - (left.get(RUNS + key) ?? 0)) / low);\n before = stores;\n }\n return { case: caseCuts.case, at: options.at, needs };\n}\n\n/** This function tells if two converters of `reach` with a limit `perDay` more than 0 share one device. */\nfunction sharesDevice(reach: ReadonlySet<Converter>): boolean {\n const seen = new Set<string>();\n for (const converter of reach) {\n if (converter.perDay === undefined || !(converter.perDay > 0)) continue;\n const key = deviceKey(converter);\n if (seen.has(key)) return true;\n seen.add(key);\n }\n return false;\n}\n\n/**\n * This function gives an upper limit of a need that the stores give with no other draw, through each chain.\n * A converter that takes nothing gives nothing: the gate refuses it.\n */\nfunction capacity(start: ReadonlyMap<string, number>, ways: Ways): number {\n let total = 0;\n for (const use of ways.direct) total += mostResource(start, ways.makers, use.resource, NO_PATH) * use.amount;\n for (const converter of ways.converters) total += mostRuns(start, ways.makers, converter, NO_PATH) * converter.gives.amount;\n return total;\n}\n","import { stronglyConnectedComponents } from \"@mark1russell7/collections/graph\";\nimport { CUT_BOUNDS, curveFault, dayNumber, isCutBound, type Fault, type Stack } from \"@mark1russell7/system-stack\";\nimport { giftNeed, giftResource } from \"./endurance.ts\";\nimport type { Converter, EnduranceLayer } from \"./layer.ts\";\n\n// The gate of an endurance layer: the meaning of a layer with a correct form, for its base stack.\n\n/**\n * 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.\n *\n * - `endurance-twice`: two or more records of one list have one key. A key is a level, a resource, a store, a need, a converter or a case.\n * The key of a prior is its case and its place. A converter takes each resource on one line, and a case cuts each part one time.\n * - `endurance-level-unknown`: the level of a draw is not a level of the layer.\n * - `endurance-resource-unknown`: a store, a use or a converter names a resource that the layer does not have.\n * - `endurance-part-unknown`: a supply, a device, the part of a store or a cut is not a part of the base stack.\n * - `endurance-range`: an amount, a rate, a count or a factor is not a finite number of 0 or more. Or a reach is not from 0 to 1.\n * - `endurance-date`: a date is not a date `YYYY-MM-DD`.\n * - `endurance-converter-empty`: a converter takes nothing, or it gives an amount of 0.\n * - `endurance-curve`: a survival curve does not start at `[0, 1]`, or it does not end at a chance of 0.\n * Or its days do not increase, or its chance increases.\n * - `endurance-bound`: the bound of a cut is not a value of `CUT_BOUNDS` of the core. Since 0.8.4.\n * - `endurance-prior-case`: a prior names a case that the layer does not have.\n * - `endurance-cycle`: converters make a resource from itself, through one converter or a chain. One fault names each cycle.\n * - `endurance-devices`: two converters of one device give two different counts of devices.\n * - `endurance-device-mix` (warning): a device has a converter with a limit `perDay` and a converter with no limit. The\n * converter with no limit uses no device-days, so its runs do not reduce the runs of the limited converter.\n * - `endurance-no-way` (warning): a draw has no direct use and no converter, so it holds 0 days when its supply stops.\n * - `endurance-cut-no-curve` (warning): a cut has no curve of its duration. The draws whose stop it can be part of are no read in the shortfall.\n */\nexport const ENDURANCE_CODES: readonly [\n \"endurance-twice\",\n \"endurance-level-unknown\",\n \"endurance-resource-unknown\",\n \"endurance-part-unknown\",\n \"endurance-range\",\n \"endurance-date\",\n \"endurance-converter-empty\",\n \"endurance-curve\",\n \"endurance-bound\",\n \"endurance-prior-case\",\n \"endurance-cycle\",\n \"endurance-devices\",\n \"endurance-device-mix\",\n \"endurance-no-way\",\n \"endurance-cut-no-curve\",\n] = [\n \"endurance-twice\",\n \"endurance-level-unknown\",\n \"endurance-resource-unknown\",\n \"endurance-part-unknown\",\n \"endurance-range\",\n \"endurance-date\",\n \"endurance-converter-empty\",\n \"endurance-curve\",\n \"endurance-bound\",\n \"endurance-prior-case\",\n \"endurance-cycle\",\n \"endurance-devices\",\n \"endurance-device-mix\",\n \"endurance-no-way\",\n \"endurance-cut-no-curve\",\n];\n\n/** A code of `ENDURANCE_CODES`. */\nexport type EnduranceCode = (typeof ENDURANCE_CODES)[number];\n\n/** A fault of the gate of an endurance layer. */\nexport interface EnduranceFault extends Fault {\n readonly code: EnduranceCode;\n}\n\nexport { curveFault } from \"@mark1russell7/system-stack\";\n\n/**\n * This function gives each fault of an endurance layer. With a base stack, it also examines the `id` of each part. A list with no error tells that the gate passes.\n *\n * The faults are in the order of the layer. The function is pure.\n *\n * @param layer - The endurance layer\n * @param stack - The base stack, with the layer. With no stack, the gate does not examine the parts.\n * @returns The faults\n */\nexport function checkEndurance(layer: EnduranceLayer, stack?: Stack): EnduranceFault[] {\n const faults: EnduranceFault[] = [];\n const add = (level: EnduranceFault[\"level\"], code: EnduranceCode, at: string, message: string): void => {\n faults.push({ level, code, at, message });\n };\n const once = (what: string, keys: readonly string[]): void => {\n const seen = new Set<string>();\n for (const key of keys) {\n if (seen.has(key)) add(\"error\", \"endurance-twice\", key, `Two or more ${what} have the key \"${key}\".`);\n seen.add(key);\n }\n };\n const range = (at: string, what: string, value: number): void => {\n if (!(Number.isFinite(value) && value >= 0)) add(\"error\", \"endurance-range\", at, `The ${what} of \"${at}\" is ${String(value)}. It must be a finite number of 0 or more.`);\n };\n const date = (at: string, value: string): void => {\n if (dayNumber(value) === undefined) add(\"error\", \"endurance-date\", at, `The date \"${value}\" of \"${at}\" is not a date YYYY-MM-DD.`);\n };\n const parts = stack === undefined ? undefined : new Set(stack.parts.map((part) => part.id));\n const part = (at: string, what: string, id: string | undefined): void => {\n if (parts !== undefined && id !== undefined && !parts.has(id)) add(\"error\", \"endurance-part-unknown\", at, `The ${what} \"${id}\" of \"${at}\" is not a part of the stack.`);\n };\n const resources = new Set(layer.resources.map((resource) => resource.code));\n const resource = (at: string, code: string): void => {\n if (!resources.has(code)) add(\"error\", \"endurance-resource-unknown\", at, `The resource \"${code}\" of \"${at}\" is not a resource of the layer.`);\n };\n const direct = layer.direct ?? [];\n const converters = layer.converters ?? [];\n const cases = layer.cases ?? [];\n const priors = layer.priors ?? [];\n\n once(\"levels\", layer.levels);\n once(\"resources\", layer.resources.map((item) => item.code));\n once(\"stores\", layer.stores.map((store) => store.id));\n once(\"draws\", layer.draws.map((draw) => draw.need));\n once(\"converters\", converters.map((converter) => converter.id));\n once(\"cases\", cases.map((item) => item.case));\n once(\"priors\", priors.map((prior) => `${prior.case}@${prior.place}`));\n\n for (const store of layer.stores) {\n resource(store.id, store.resource);\n range(store.id, \"amount\", store.amount);\n if (store.due !== undefined) date(store.id, store.due);\n part(store.id, \"part\", store.part);\n }\n const levels = new Set(layer.levels);\n for (const draw of layer.draws) {\n if (!levels.has(draw.level)) add(\"error\", \"endurance-level-unknown\", draw.need, `The level \"${draw.level}\" of the draw \"${draw.need}\" is not a level of the layer.`);\n range(draw.need, \"rate\", draw.perDay);\n if (draw.users !== undefined) range(draw.need, \"count of users\", draw.users);\n part(draw.need, \"supply\", draw.supply);\n const ways = direct.some((use) => use.need === draw.need) || converters.some((converter) => giftNeed(converter) === draw.need);\n if (!ways) add(\"warning\", \"endurance-no-way\", draw.need, `The draw \"${draw.need}\" has no direct use and no converter. It holds 0 days when its supply stops.`);\n }\n for (const use of direct) {\n const at = `${use.resource}>${use.need}`;\n resource(at, use.resource);\n range(at, \"amount\", use.amount);\n }\n for (const converter of converters) {\n once(`resources of the converter \"${converter.id}\"`, converter.takes.map((input) => input.resource));\n for (const input of converter.takes) {\n resource(converter.id, input.resource);\n range(converter.id, \"amount\", input.amount);\n }\n range(converter.id, \"amount\", converter.gives.amount);\n const made = giftResource(converter);\n if (made !== undefined) resource(converter.id, made);\n if (!converter.takes.some((input) => input.amount > 0) || converter.gives.amount === 0) add(\"error\", \"endurance-converter-empty\", converter.id, `The converter \"${converter.id}\" takes nothing, or it gives nothing.`);\n part(converter.id, \"device\", converter.device);\n if (converter.perDay !== undefined) range(converter.id, \"rate perDay\", converter.perDay);\n if (converter.devices !== undefined && !(Number.isSafeInteger(converter.devices) && converter.devices >= 1))\n add(\"error\", \"endurance-range\", converter.id, `The count of devices of \"${converter.id}\" is ${String(converter.devices)}. It must be a whole number of 1 or more.`);\n }\n const counts = new Map<string, number>();\n for (const converter of converters) {\n if (converter.device === undefined) continue;\n const count = converter.devices ?? 1;\n const seen = counts.get(converter.device);\n if (seen !== undefined && seen !== count)\n add(\"error\", \"endurance-devices\", converter.id, `The converter \"${converter.id}\" gives the count ${String(count)} for the device \"${converter.device}\". An other converter gives the count ${String(seen)}.`);\n if (seen === undefined) counts.set(converter.device, count);\n }\n // One fault names each device with a limited converter and a converter with no limit, at the first converter with no limit.\n const mixed = new Set<string>();\n for (const converter of converters) {\n const device = converter.device;\n if (device === undefined || converter.perDay !== undefined || mixed.has(device)) continue;\n const limited = converters.find((other) => other.device === device && other.perDay !== undefined);\n if (limited === undefined) continue;\n mixed.add(device);\n add(\"warning\", \"endurance-device-mix\", converter.id, `The device \"${device}\" has the limited converter \"${limited.id}\" and the converter \"${converter.id}\" with no limit. \"${converter.id}\" uses no device-days.`);\n }\n const caseCodes = new Set(cases.map((item) => item.case));\n for (const item of cases) {\n once(`cuts of the case \"${item.case}\"`, item.cuts.map((cut) => cut.part));\n for (const cut of item.cuts) {\n const at = `${item.case}/${cut.part}`;\n part(at, \"cut\", cut.part);\n if (cut.bound !== undefined && !isCutBound(cut.bound))\n add(\"error\", \"endurance-bound\", at, `The bound of the cut \"${at}\" is ${JSON.stringify(cut.bound)}. It must be one of ${CUT_BOUNDS.join(\", \")}.`);\n if (cut.duration === undefined) {\n add(\"warning\", \"endurance-cut-no-curve\", at, `The cut \"${at}\" has no curve of its duration, so the draws that it can stop are no read.`);\n continue;\n }\n const fault = curveFault(cut.duration);\n if (fault !== undefined) add(\"error\", \"endurance-curve\", at, `The duration of the cut \"${at}\": ${fault}`);\n }\n for (const [need, factor] of Object.entries(item.factors ?? {})) range(`${item.case}/${need}`, \"factor\", factor);\n if (item.leadSeconds !== undefined) range(item.case, \"lead time\", item.leadSeconds);\n }\n for (const cycle of resourceCycles(converters)) {\n const [first = \"\"] = cycle;\n const names = cycle.map((code) => `\"${code}\"`).join(\", \");\n const message = cycle.length === 1 ? `A converter makes the resource ${names} from itself.` : `Converters make the resources ${names} from each other.`;\n add(\"error\", \"endurance-cycle\", first, `${message} A chain of converters cannot end.`);\n }\n for (const prior of priors) {\n const at = `${prior.case}@${prior.place}`;\n if (!caseCodes.has(prior.case)) add(\"error\", \"endurance-prior-case\", at, `The prior \"${at}\" names the case \"${prior.case}\", which the layer does not have.`);\n range(at, \"count of events in one year\", prior.perYear);\n if (!(prior.reach >= 0 && prior.reach <= 1)) add(\"error\", \"endurance-range\", at, `The reach of \"${at}\" is ${String(prior.reach)}. It must be from 0 to 1.`);\n date(at, prior.asOf);\n }\n return faults;\n}\n\n/** This function gives each cycle of resources: a resource is made from a resource that a converter makes from it. Each cycle is a list of codes. */\nfunction resourceCycles(converters: readonly Converter[]): string[][] {\n const from = new Map<string, Set<string>>();\n for (const converter of converters) {\n const made = giftResource(converter);\n if (made === undefined) continue;\n const inputs = from.get(made) ?? new Set<string>();\n for (const input of converter.takes) if (input.amount > 0) inputs.add(input.resource);\n from.set(made, inputs);\n }\n const successors = (code: string): Iterable<string> => from.get(code) ?? [];\n return stronglyConnectedComponents(from.keys(), successors).filter((component) => {\n const [only = \"\"] = component;\n return component.length > 1 || (from.get(only)?.has(only) ?? false);\n });\n}\n\n/** This function tells if a list of faults has an error. */\nexport function hasEnduranceError(faults: readonly EnduranceFault[]): boolean {\n return faults.some((fault) => fault.level === \"error\");\n}\n","import { canonicalJson } from \"@mark1russell7/rigor-generators\";\nimport { joinRecords, joinSetting, type LayerParse, type LayerPiece } from \"@mark1russell7/system-stack\";\nimport { ENDURANCE_SCHEMA, type EnduranceLayer } from \"./layer.ts\";\n\n// The join of the endurance layers of the fragments of a stack, for example one file of stores for each owner.\n\n/**\n * This function joins the endurance layers of the fragments of a stack into one layer.\n *\n * - The levels are one setting: each fragment that has levels gives the same list, else the join has a fault.\n * - The records of each list are in the order of the fragments.\n * - Two resources with one code in two fragments join into one resource when their records are equal. A different field is a fault.\n * Its message gives the canonical JSON of the record of each fragment.\n * - A code that one fragment has two times stays in the joined layer. The gate `checkEndurance` finds it.\n * - One key of each other list in two or more fragments is a fault, also when the records are equal.\n * - The key of a direct use is its resource and its need.\n *\n * The function is pure, and it changes no layer. The gate `checkEndurance` examines the joined layer afterward.\n *\n * @param pieces - The layers, with the name of the fragment of each one, in the order of the fragments.\n * @returns The joined layer, or the faults of the join.\n */\nexport function joinEndurance(pieces: readonly LayerPiece<EnduranceLayer>[]): LayerParse<EnduranceLayer> {\n const levels = joinSetting(pieces, (layer) => (layer.levels.length > 0 ? layer.levels.join(\"\\n\") : undefined), \"levels\");\n // Two fragments can declare one resource, for example `water.stored` in `L`. Canonical JSON (RFC 8785) compares the records,\n // so the order of the keys has no effect. The message of a fault gives the canonical JSON of the record of each fragment.\n const resources = joinRecords(pieces, (layer) => layer.resources, (item) => item.code, \"resource\", {\n equal: (first, other) => canonicalJson(first) === canonicalJson(other),\n text: canonicalJson,\n });\n const stores = joinRecords(pieces, (layer) => layer.stores, (item) => item.id, \"store\");\n const draws = joinRecords(pieces, (layer) => layer.draws, (item) => item.need, \"draw\");\n const direct = joinRecords(pieces, (layer) => layer.direct, (item) => `${item.resource}>${item.need}`, \"direct use\");\n const converters = joinRecords(pieces, (layer) => layer.converters, (item) => item.id, \"converter\");\n const cases = joinRecords(pieces, (layer) => layer.cases, (item) => item.case, \"case\");\n const priors = joinRecords(pieces, (layer) => layer.priors, (item) => `${item.case}@${item.place}`, \"prior\");\n const errors = [levels, resources, stores, draws, direct, converters, cases, priors].flatMap((join) => join.errors);\n if (errors.length > 0) return { ok: false, errors };\n const has = (key: \"direct\" | \"converters\" | \"cases\" | \"priors\"): boolean => pieces.some((piece) => piece.layer[key] !== undefined);\n return {\n ok: true,\n layer: {\n schema: ENDURANCE_SCHEMA,\n levels: levels.value === undefined ? [] : levels.value.split(\"\\n\"),\n resources: resources.items,\n stores: stores.items,\n draws: draws.items,\n ...(has(\"direct\") ? { direct: direct.items } : {}),\n ...(has(\"converters\") ? { converters: converters.items } : {}),\n ...(has(\"cases\") ? { cases: cases.items } : {}),\n ...(has(\"priors\") ? { priors: priors.items } : {}),\n },\n };\n}\n"],"mappings":";;;;;;;;AAKA,SAAgB,SAAS,WAA2C;CAClE,MAAM,sBAAM,IAAI,IAAoB;CACpC,KAAK,MAAM,SAAS,UAAU,OAAO,IAAI,MAAM,SAAS,GAAG,IAAI,IAAI,MAAM,WAAW,IAAI,IAAI,MAAM,QAAQ,KAAK,KAAK,MAAM,MAAM;CAChI,OAAO;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prior, Prior as Prior$1, Survival } from "@mark1russell7/system-stack";
2
2
  /** The name of the format of an endurance layer. It is the key of the layer in `Stack.layers`. */
3
3
  declare const ENDURANCE_SCHEMA = "endurance/1";
4
4
  /** A date as `YYYY-MM-DD`. */
@@ -127,5 +127,5 @@ interface EnduranceLayer {
127
127
  readonly cases?: readonly CaseCuts$1[] | undefined;
128
128
  readonly priors?: readonly Prior$1[] | undefined;
129
129
  }
130
- export { Draw as a, Endurance as c, IsoDate as d, Prior as f, Survival as h, DirectUse as i, EnduranceLayer as l, Store as m, Converter as n, DrawEndurance as o, Resource as p, Cut as r, ENDURANCE_SCHEMA as s, CaseCuts as t, Gift as u };
131
- //# sourceMappingURL=layer-CF0r-9ww.d.ts.map
130
+ 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
@@ -1 +1 @@
1
- {"version":3,"file":"layer-CF0r-9ww.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-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 +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, 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\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 { l as EnduranceLayer } from "./layer-CF0r-9ww.js";
1
+ import { u as EnduranceLayer } from "./layer-BwbOgVFi.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.
@@ -1 +1 @@
1
- {"version":3,"file":"schema.d.ts","names":[],"sources":["../src/schema.ts"],"mappings":";;;;;;qBAqEa,iBAAiB,EAAE,QAAQ;;YAa5B;WAA4B;WAAmB,OAAO;;WAA8B;WAAoB;;;;;;wBAMpG,eAAe,iBAAiB"}
1
+ {"version":3,"file":"schema.d.ts","names":[],"sources":["../src/schema.ts"],"mappings":";;;;;;qBAuEa,iBAAiB,EAAE,QAAQ;;YAa5B;WAA4B;WAAmB,OAAO;;WAA8B;WAAoB;;;;;;wBAMpG,eAAe,iBAAiB"}
package/build/schema.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { t as ENDURANCE_SCHEMA } from "./layer-a3Fr70Uh.js";
2
+ import { CUT_BOUNDS } from "@mark1russell7/system-stack";
2
3
  import { formErrors } from "@mark1russell7/system-stack/schema";
3
4
  import { z } from "zod";
4
5
  // src/schema.ts
@@ -49,6 +50,7 @@ const cut = z.strictObject({
49
50
  part: id,
50
51
  title: id,
51
52
  duration: z.array(point).readonly().optional(),
53
+ bound: z.enum(CUT_BOUNDS).optional(),
52
54
  source: id
53
55
  });
54
56
  const caseCuts = z.strictObject({
@@ -1 +1 @@
1
- {"version":3,"file":"schema.js","names":[],"sources":["../src/schema.ts"],"sourcesContent":["import { formErrors } from \"@mark1russell7/system-stack/schema\";\nimport { z } from \"zod\";\nimport { ENDURANCE_SCHEMA, type EnduranceLayer } from \"./layer.ts\";\n\n// The zod schema of an endurance layer and the read of its JSON. This module is the entry `/schema` of the package.\n// The root entry has no zod, so a host that only calculates gets no schema library.\n\nconst id = z.string().min(1);\nconst amount = z.number();\n\nconst resource = z.strictObject({ code: id, unit: id });\n\nconst store = z.strictObject({\n id,\n resource: id,\n amount,\n due: id.optional(),\n part: id.optional(),\n});\n\nconst draw = z.strictObject({\n need: id,\n level: id,\n perDay: amount,\n users: amount.optional(),\n supply: id,\n});\n\nconst directUse = z.strictObject({ resource: id, need: id, amount });\n\nconst converter = z.strictObject({\n id,\n device: id.optional(),\n takes: z.array(z.strictObject({ resource: id, amount })).readonly(),\n gives: z.union([z.strictObject({ need: id, amount }), z.strictObject({ resource: id, amount })]),\n perDay: amount.optional(),\n devices: amount.optional(),\n});\n\nconst point = z.tuple([z.number(), z.number()]).readonly();\n\nconst cut = z.strictObject({\n part: id,\n title: id,\n duration: z.array(point).readonly().optional(),\n source: id,\n});\n\nconst caseCuts = z.strictObject({\n case: id,\n title: id,\n cuts: z.array(cut).readonly(),\n factors: z.record(z.string(), amount).optional(),\n leadSeconds: amount.optional(),\n});\n\nconst prior = z.strictObject({\n case: id,\n place: id,\n perYear: amount,\n reach: amount,\n source: id,\n asOf: id,\n});\n\n/**\n * The schema of an endurance layer. It examines the form of the record: the fields and their types.\n * It refuses a field that the format does not have. `checkEndurance` examines the meaning of a layer with a correct form.\n */\nexport const enduranceSchema: z.ZodType<EnduranceLayer> = z.strictObject({\n schema: z.literal(ENDURANCE_SCHEMA),\n levels: z.array(id).readonly(),\n resources: z.array(resource).readonly(),\n stores: z.array(store).readonly(),\n draws: z.array(draw).readonly(),\n direct: z.array(directUse).readonly().optional(),\n converters: z.array(converter).readonly().optional(),\n cases: z.array(caseCuts).readonly().optional(),\n priors: z.array(prior).readonly().optional(),\n});\n\n/** The result of the read of an endurance layer: the layer, or the faults of its form. */\nexport type EnduranceParse = { readonly ok: true; readonly layer: EnduranceLayer } | { readonly ok: false; readonly errors: readonly string[] };\n\n/**\n * This function reads the JSON of an endurance layer. It gives the layer, or the faults of its form.\n * Each fault names its place in the record, for example `stores.0.amount`.\n */\nexport function parseEndurance(input: unknown): EnduranceParse {\n const read = enduranceSchema.safeParse(input);\n if (read.success) return { ok: true, layer: read.data };\n return { ok: false, errors: formErrors(ENDURANCE_SCHEMA, read.error.issues) };\n}\n"],"mappings":";;;;AAOA,MAAM,KAAK,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;AAC3B,MAAM,SAAS,EAAE,OAAO;AAExB,MAAM,WAAW,EAAE,aAAa;CAAE,MAAM;CAAI,MAAM;AAAG,CAAC;AAEtD,MAAM,QAAQ,EAAE,aAAa;CAC3B;CACA,UAAU;CACV;CACA,KAAK,GAAG,SAAS;CACjB,MAAM,G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CAC7B,WAAW,EAAE,MAAM,QAAQ,CAAC,CAAC,SAAS;CACtC,QAAQ,EAAE,MAAM,KAAK,CAAC,CAAC,SAAS;CAChC,OAAO,EAAE,MAAM,IAAI,CAAC,CAAC,SAAS;CAC9B,QAAQ,EAAE,MAAM,SAAS,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS;CAC/C,YAAY,EAAE,MAAM,SAAS,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS;CACnD,OAAO,EAAE,MAAM,QAAQ,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS;CAC7C,QAAQ,EAAE,MAAM,KAAK,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS;AAC7C,CAAC;;;;;AASD,SAAgB,eAAe,OAAgC;CAC7D,MAAM,OAAO,gBAAgB,UAAU,KAAK;CAC5C,IAAI,KAAK,SAAS,OAAO;EAAE,IAAI;EAAM,OAAO,KAAK;CAAK;CACtD,OAAO;EAAE,IAAI;EAAO,QAAQ,WAAW,kBAAkB,KAAK,MAAM,MAAM;CAAE;AAC9E"}
1
+ {"version":3,"file":"schema.js","names":[],"sources":["../src/schema.ts"],"sourcesContent":["import { CUT_BOUNDS } from \"@mark1russell7/system-stack\";\nimport { formErrors } from \"@mark1russell7/system-stack/schema\";\nimport { z } from \"zod\";\nimport { ENDURANCE_SCHEMA, type EnduranceLayer } from \"./layer.ts\";\n\n// The zod schema of an endurance layer and the read of its JSON. This module is the entry `/schema` of the package.\n// The root entry has no zod, so a host that only calculates gets no schema library.\n\nconst id = z.string().min(1);\nconst amount = z.number();\n\nconst resource = z.strictObject({ code: id, unit: id });\n\nconst store = z.strictObject({\n id,\n resource: id,\n amount,\n due: id.optional(),\n part: id.optional(),\n});\n\nconst draw = z.strictObject({\n need: id,\n level: id,\n perDay: amount,\n users: amount.optional(),\n supply: id,\n});\n\nconst directUse = z.strictObject({ resource: id, need: id, amount });\n\nconst converter = z.strictObject({\n id,\n device: id.optional(),\n takes: z.array(z.strictObject({ resource: id, amount })).readonly(),\n gives: z.union([z.strictObject({ need: id, amount }), z.strictObject({ resource: id, amount })]),\n perDay: amount.optional(),\n devices: amount.optional(),\n});\n\nconst point = z.tuple([z.number(), z.number()]).readonly();\n\nconst cut = z.strictObject({\n part: id,\n title: id,\n duration: z.array(point).readonly().optional(),\n bound: z.enum(CUT_BOUNDS).optional(),\n source: id,\n});\n\nconst caseCuts = z.strictObject({\n case: id,\n title: id,\n cuts: z.array(cut).readonly(),\n factors: z.record(z.string(), amount).optional(),\n leadSeconds: amount.optional(),\n});\n\nconst prior = z.strictObject({\n case: id,\n place: id,\n perYear: amount,\n reach: amount,\n source: id,\n asOf: id,\n});\n\n/**\n * The schema of an endurance layer. It examines the form of the record: the fields and their types.\n * It refuses a field that the format does not have. `checkEndurance` examines the meaning of a layer with a correct form.\n */\nexport const enduranceSchema: z.ZodType<EnduranceLayer> = z.strictObject({\n schema: z.literal(ENDURANCE_SCHEMA),\n levels: z.array(id).readonly(),\n resources: z.array(resource).readonly(),\n stores: z.array(store).readonly(),\n draws: z.array(draw).readonly(),\n direct: z.array(directUse).readonly().optional(),\n converters: z.array(converter).readonly().optional(),\n cases: z.array(caseCuts).readonly().optional(),\n priors: z.array(prior).readonly().optional(),\n});\n\n/** The result of the read of an endurance layer: the layer, or the faults of its form. */\nexport type EnduranceParse = { readonly ok: true; readonly layer: EnduranceLayer } | { readonly ok: false; readonly errors: readonly string[] };\n\n/**\n * This function reads the JSON of an endurance layer. It gives the layer, or the faults of its form.\n * Each fault names its place in the record, for example `stores.0.amount`.\n */\nexport function parseEndurance(input: unknown): EnduranceParse {\n const read = enduranceSchema.safeParse(input);\n if (read.success) return { ok: true, layer: read.data };\n return { ok: false, errors: formErrors(ENDURANCE_SCHEMA, read.error.issues) };\n}\n"],"mappings":";;;;;AAQA,MAAM,KAAK,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;AAC3B,MAAM,SAAS,EAAE,OAAO;AAExB,MAAM,WAAW,EAAE,aAAa;CAAE,MAAM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ACT,OAAO;CACP,QAAQ;CACR,MAAM;AACR,CAAC;;;;;AAMD,MAAa,kBAA6C,EAAE,aAAa;CACvE,QAAQ,EAAE,QAAQ,gBAAgB;CAClC,QAAQ,EAAE,MAAM,EAAE,CAAC,CAAC,SAAS;CAC7B,WAAW,EAAE,MAAM,QAAQ,CAAC,CAAC,SAAS;CACtC,QAAQ,EAAE,MAAM,KAAK,CAAC,CAAC,SAAS;CAChC,OAAO,EAAE,MAAM,IAAI,CAAC,CAAC,SAAS;CAC9B,QAAQ,EAAE,MAAM,SAAS,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS;CAC/C,YAAY,EAAE,MAAM,SAAS,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS;CACnD,OAAO,EAAE,MAAM,QAAQ,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS;CAC7C,QAAQ,EAAE,MAAM,KAAK,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS;AAC7C,CAAC;;;;;AASD,SAAgB,eAAe,OAAgC;CAC7D,MAAM,OAAO,gBAAgB,UAAU,KAAK;CAC5C,IAAI,KAAK,SAAS,OAAO;EAAE,IAAI;EAAM,OAAO,KAAK;CAAK;CACtD,OAAO;EAAE,IAAI;EAAO,QAAQ,WAAW,kBAAkB,KAAK,MAAM,MAAM;CAAE;AAC9E"}
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.2",
4
+ "version": "0.8.4",
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": {
@@ -53,12 +53,13 @@
53
53
  "@mark1russell7/linear": "^0.1.0",
54
54
  "@mark1russell7/rational": "^0.1.3",
55
55
  "@mark1russell7/rigor-generators": "^0.2.0",
56
- "@mark1russell7/system-stack": "0.1.11",
56
+ "@mark1russell7/system-stack": "0.1.12",
57
57
  "zod": "^4.6.7"
58
58
  },
59
59
  "devDependencies": {
60
60
  "@mark1russell7/cue": "^2.0.0",
61
61
  "@mark1russell7/rigor-bench": "^0.3.2",
62
+ "@mark1russell7/rigor-statistics": "^0.2.23",
62
63
  "@types/node": "^26.6.5",
63
64
  "@vitest/coverage-v8": "^5.0.3",
64
65
  "fast-check": "^4.10.2",
@@ -1 +0,0 @@
1
- {"version":3,"file":"join-DQxIAP0v.js","names":["curveFault"],"sources":["../src/converter.ts","../src/fit.ts","../src/rows.ts","../src/share.ts","../src/endurance.ts","../src/check.ts","../src/join.ts"],"sourcesContent":["import type { Converter } from \"./layer.ts\";\n\n// The internal rules of a converter that the endurance query and the joint days share. The root entry does not give them.\n\n/** This function gives the amount of each resource that one run of a converter takes. Two lines of one resource add. */\nexport function inputsOf(converter: Converter): Map<string, number> {\n const out = new Map<string, number>();\n for (const input of converter.takes) if (input.amount > 0) out.set(input.resource, (out.get(input.resource) ?? 0) + input.amount);\n return out;\n}\n\n/** This function tells if a converter can run in a case. Its device works, it takes a resource, and it gives an amount more than 0. */\nexport function canRun(converter: Converter, stoppedParts: ReadonlySet<string>): boolean {\n return converter.gives.amount > 0 && inputsOf(converter).size > 0 && (converter.device === undefined || !stoppedParts.has(converter.device));\n}\n\n/**\n * This function gives the key of the device-days that a converter uses. The converters of one device share one key.\n * A converter with no device has a key of its own.\n */\nexport function deviceKey(converter: Converter): string {\n return converter.device === undefined ? `converter:${converter.id}` : `device:${converter.device}`;\n}\n","/** The relative tolerance of a take and of a fit. */\nexport const TOLERANCE = 1e-13;\n\n/** One try of a fit: the amount that the stores could not give, out of the amount wanted, and the value of the try. */\nexport interface Try<T> {\n readonly short: number;\n readonly need: number;\n readonly value: T;\n}\n\n/** The result of a fit: the largest amount with no shortfall, and the value of its try. The value is `undefined` when only 0 fits. */\nexport interface Fit<T> {\n readonly x: number;\n readonly value: T | undefined;\n}\n\n/**\n * The count of the tries of `largestFit`, for the tests of the cost. It is not in the public API, and it does not change a result.\n * It is the one side effect of `largestFit` and of the queries that use it.\n */\nexport const fitTries = { count: 0 };\n\n/**\n * This function gives the largest `x` in `[0, most]` at which `attempt` has no shortfall, to the relative tolerance `TOLERANCE`.\n *\n * - A try fits when its shortfall is not more than `TOLERANCE` times its need.\n * - The shortfall must not decrease when `x` increases. A take of a chain of converters gives a shortfall that is linear in parts.\n * - The first try is `most`. After it, each step tries the zero of the line through the last two tries that do not fit.\n * With one try that does not fit, the step tries `x` times the part of the need that the stores gave.\n * - When a step does not halve the interval, the next step is a bisection. Thus a fit takes at most approximately twice the steps of a bisection.\n * - A step on the lower end tries a point just above it, so a correct estimate ends the fit in one more try.\n * - An estimate that fits with a shortfall above 0 is in the band of the tolerance above the zero, so the fit ends there.\n * A bisection step or a probe at the lower end can fit with a shortfall of rounding below the zero. The fit does not end there.\n *\n * @param most - The upper limit of `x`\n * @param attempt - The try at an amount. It must not change its input\n * @returns The largest amount that fits, and the value of its try\n */\nexport function largestFit<T>(most: number, attempt: (x: number) => Try<T>): Fit<T> {\n const fits = (tried: Try<T>): boolean => tried.short <= TOLERANCE * tried.need;\n fitTries.count += 1;\n const first = attempt(most);\n if (fits(first)) return { x: most, value: first.value };\n let low = 0;\n let best: T | undefined;\n let high = most;\n let highShort = first.short;\n let highNeed = first.need;\n let before: { readonly x: number; readonly short: number } | undefined;\n let bisect = false;\n for (let step = 0; step < 400 && high - low > 4 * TOLERANCE * high; step += 1) {\n const width = high - low;\n let x: number;\n if (bisect) x = (low + high) / 2;\n else if (before !== undefined && before.short > highShort) x = high - (highShort * (before.x - high)) / (before.short - highShort);\n else x = high * (1 - highShort / highNeed);\n // Only a secant or ratio estimate through tries that do not fit lands at or above the zero of a convex shortfall.\n const estimate = !bisect && x < high;\n if (!(x < high)) x = (low + high) / 2;\n const floor = low + 2 * TOLERANCE * high;\n const clamped = !(x > floor);\n if (clamped) x = floor;\n fitTries.count += 1;\n const tried = attempt(x);\n if (fits(tried)) {\n low = x;\n best = tried.value;\n // An estimate that fits with a shortfall is in the band of the tolerance above the zero, so the fit ends.\n if (tried.short > 0 && estimate && !clamped) break;\n } else {\n before = { x: high, short: highShort };\n high = x;\n highShort = tried.short;\n highNeed = tried.need;\n }\n bisect = !bisect && high - low > width / 2;\n }\n return { x: low, value: best };\n}\n","import { add, fromFloat, type Rational, ZERO } from \"@mark1russell7/rational\";\n\n// The internal rows of the linear programs of the queries. The root entry does not give them.\n\n/** A sparse row: the coefficient of each variable, by its index. */\nexport type Row = Map<number, Rational>;\n\n/** This function adds `value` to the coefficient of the variable `index` in `row`. It changes `row`. */\nexport function addTo(row: Row, index: number, value: Rational): void {\n row.set(index, add(row.get(index) ?? ZERO, value));\n}\n\n/** This function gives the dense form of a row: one coefficient for each of `count` variables. */\nexport function dense(row: Row, count: number): Rational[] {\n const out = new Array<Rational>(count).fill(ZERO);\n for (const [index, value] of row) out[index] = value;\n return out;\n}\n\n/** This function gives the exact rational of a finite double, with no rounding. A double is a dyadic rational. */\nexport function exact(value: number): Rational {\n return fromFloat(value);\n}\n","import { type Constraint, type Objective, solveLexicographic } from \"@mark1russell7/linear\";\nimport { add, div, mul, neg, ONE, type Rational, sign, toNumber, ZERO } from \"@mark1russell7/rational\";\nimport { deviceKey, inputsOf } from \"./converter.ts\";\nimport type { Converter, DirectUse } from \"./layer.ts\";\nimport { addTo, dense, exact, type Row } from \"./rows.ts\";\n\n// The best share of one draw: a linear program over the totals of its days, with exact rationals (@mark1russell7/linear).\n// The endurance query uses it for a draw whose converters share the days of a device. The root entry does not give it.\n\n/** The input of the best share of one draw. */\nexport interface ShareInput {\n /** The stock of each resource that the draw can take, by the code of the resource. */\n readonly stock: ReadonlyMap<string, number>;\n /** The device-days of each day that the draw can use, by the key of the device (`deviceKey`). */\n readonly room: ReadonlyMap<string, number>;\n /** The direct uses that give the need of the draw. */\n readonly direct: readonly DirectUse[];\n /** The converters that give the need of the draw. */\n readonly converters: readonly Converter[];\n /** The converters that make each resource, by the code of the resource. */\n readonly makers: ReadonlyMap<string, readonly Converter[]>;\n /** The amount of the need for each day. It is more than 0. */\n readonly demand: number;\n}\n\n/** The best share of one draw: its days, the take of each stock and the device-days of each device. */\nexport interface Share {\n /** The largest count of days at which the draw gets its demand. */\n readonly days: number;\n /** The amount of each resource that the draw takes from the stock. A resource with no take is not in the map. */\n readonly taken: ReadonlyMap<string, number>;\n /** The device-days that the runs use in `days`, by the key of the device. A device with no use is not in the map. */\n readonly used: ReadonlyMap<string, number>;\n}\n\n/** This function gives the makers that a draw can use: the makers of its inputs, through each chain. */\nfunction reachedMakers(input: ShareInput): Converter[] {\n const out = new Set<Converter>();\n const seen = new Set<string>();\n const queue = [...input.direct.map((use) => use.resource), ...input.converters.flatMap((converter) => [...inputsOf(converter).keys()])];\n for (let resource = queue.shift(); resource !== undefined; resource = queue.shift()) {\n if (seen.has(resource)) continue;\n seen.add(resource);\n for (const maker of input.makers.get(resource) ?? []) {\n out.add(maker);\n queue.push(...inputsOf(maker).keys());\n }\n }\n return [...out];\n}\n\n/**\n * This function gives the best share of the stocks and of the device-days for one draw.\n * It gives `undefined` when the program has no optimum.\n *\n * - The variables are the days `T`, the take of each direct use, the runs of each converter and maker, and the take of each stock.\n * - The gifts of the direct uses and of the converters are not less than `T` times the demand.\n * - The takes of each resource are not more than the take of its stock plus the gifts of its makers. The take of a stock is not more than the stock.\n * - The runs of the converters of one device use `room` times `T` device-days or less. One run uses `1 / perDay` of a device-day. A limit of 0 stops the converter.\n * - The first objective takes the largest `T`. The second takes the smallest sum of the takes of the stocks, each over its stock. The third takes the fewest device-days.\n *\n * The gifts at `T` days are a concave function of `T`, and they are 0 at 0. Thus each count of days up to the largest `T` also fits.\n *\n * @param input - The stocks, the device-days of each day, the ways of the draw and its demand\n * @returns The days, the takes of the stocks and the device-days of each device\n */\nexport function bestShare(input: ShareInput): Share | undefined {\n const makers = reachedMakers(input);\n const resources = new Set<string>([...input.direct.map((use) => use.resource), ...[...input.converters, ...makers].flatMap((converter) => [...inputsOf(converter).keys()])]);\n for (const maker of makers) if (\"resource\" in maker.gives && maker.gives.resource !== undefined) resources.add(maker.gives.resource);\n const stocked = [...resources].filter((resource) => (input.stock.get(resource) ?? 0) > 0).sort();\n\n let count = 0;\n const next = (): number => count++;\n const days = next();\n const useCol = input.direct.map(next);\n const runs = new Map<Converter, number>([...input.converters, ...makers].map((converter) => [converter, next()] as const));\n const shareCol = new Map(stocked.map((resource) => [resource, next()] as const));\n\n const rows: { readonly row: Row; readonly relation: Constraint[\"relation\"]; readonly rhs: Rational }[] = [];\n // The need: the gifts are not less than the demand times the days.\n const need: Row = new Map([[days, neg(exact(input.demand))]]);\n input.direct.forEach((use, k) => addTo(need, useCol[k] as number, exact(use.amount)));\n for (const converter of input.converters) addTo(need, runs.get(converter) as number, exact(converter.gives.amount));\n rows.push({ row: need, relation: \">=\", rhs: ZERO });\n // The balance of each resource: its takes are not more than the take of its stock plus the gifts of its makers.\n const balance = new Map<string, Row>([...resources].map((resource) => [resource, new Map()]));\n const consume = (resource: string, index: number, amount: Rational): void => addTo(balance.get(resource) as Row, index, amount);\n input.direct.forEach((use, k) => consume(use.resource, useCol[k] as number, ONE));\n for (const [converter, index] of runs) {\n for (const [resource, each] of inputsOf(converter)) consume(resource, index, exact(each));\n if (\"resource\" in converter.gives && converter.gives.resource !== undefined) consume(converter.gives.resource, index, neg(exact(converter.gives.amount)));\n }\n for (const [resource, index] of shareCol) consume(resource, index, neg(ONE));\n for (const row of balance.values()) if (row.size > 0) rows.push({ row, relation: \"<=\", rhs: ZERO });\n // The take of each stock is not more than the stock.\n for (const [resource, index] of shareCol) rows.push({ row: new Map([[index, ONE]]), relation: \"<=\", rhs: exact(input.stock.get(resource) ?? 0) });\n // The limit of each device: the runs use `room` times `T` device-days or less. The converters of one device share one limit.\n const limits = new Map<string, Row>();\n for (const [converter, index] of runs) {\n if (converter.perDay === undefined) continue;\n if (!(converter.perDay > 0)) {\n rows.push({ row: new Map([[index, ONE]]), relation: \"<=\", rhs: ZERO });\n continue;\n }\n const key = deviceKey(converter);\n const limit = limits.get(key) ?? new Map([[days, neg(exact(input.room.get(key) ?? 0))]]);\n limits.set(key, limit);\n addTo(limit, index, div(ONE, exact(converter.perDay)));\n }\n for (const row of limits.values()) rows.push({ row, relation: \"<=\", rhs: ZERO });\n\n const most: Row = new Map([[days, ONE]]);\n const least: Row = new Map();\n for (const [resource, index] of shareCol) addTo(least, index, div(ONE, exact(input.stock.get(resource) ?? 1)));\n const fewest: Row = new Map();\n for (const [converter, index] of runs) addTo(fewest, index, converter.perDay !== undefined && converter.perDay > 0 ? div(ONE, exact(converter.perDay)) : ONE);\n const objectives: Objective[] = [\n { sense: \"max\", coefficients: dense(most, count) },\n { sense: \"min\", coefficients: dense(least, count) },\n { sense: \"min\", coefficients: dense(fewest, count) },\n ];\n const constraints: Constraint[] = rows.map(({ row, relation, rhs }) => ({ coefficients: dense(row, count), relation, rhs }));\n const solved = solveLexicographic(constraints, objectives);\n // The point 0 is feasible, and the later objectives are not less than 0. Thus only an unbounded first stage has no optimum.\n if (solved.status !== \"optimal\") return undefined;\n\n const at = (index: number): Rational => solved.x[index] ?? ZERO;\n const taken = new Map<string, number>();\n for (const [resource, index] of shareCol) if (sign(at(index)) > 0) taken.set(resource, toNumber(at(index)));\n const used = new Map<string, number>();\n for (const [key, row] of limits) {\n let sum: Rational = ZERO;\n for (const [index, value] of row) if (index !== days) sum = add(sum, mul(value, at(index)));\n if (sign(sum) > 0) used.set(key, toNumber(sum));\n }\n return { days: toNumber(at(days)), taken, used };\n}\n","import { dayNumber, stopped, type Stack } from \"@mark1russell7/system-stack\";\nimport { canRun, deviceKey, inputsOf } from \"./converter.ts\";\nimport { largestFit, type Try } from \"./fit.ts\";\nimport type { CaseCuts, Converter, DirectUse, Draw, Endurance, EnduranceLayer, IsoDate } from \"./layer.ts\";\nimport { bestShare } from \"./share.ts\";\n\n// The endurance query: the days that each draw holds when a case stops its supply.\n\n/** The options of the queries of a case. */\nexport interface CaseOptions {\n /** The date of the query. A store whose due date is on this date or before it gives nothing. */\n readonly at: IsoDate;\n /** The base stack. With it, a cut also stops each part that cannot work without a cut part (`stopped` of the core). */\n readonly stack?: Stack | undefined;\n /** The `id` of more parts that are down, with the cuts of the case. */\n readonly down?: readonly string[] | undefined;\n}\n\n/**\n * This function gives the `id` of each part that does not work in a case: the cut parts and the parts of `down`.\n * With a stack, it also gives each part that stops.\n */\nexport function caseStopped(caseCuts: CaseCuts, options: Pick<CaseOptions, \"stack\" | \"down\">): Set<string> {\n const down = [...caseCuts.cuts.map((cut) => cut.part), ...(options.down ?? [])];\n const out = new Set(down);\n if (options.stack !== undefined) for (const id of stopped(options.stack, down)) out.add(id);\n return out;\n}\n\n/** This function gives the day number of a date, or throws a `RangeError` for a date that is not `YYYY-MM-DD`. */\nfunction dayOf(date: IsoDate): number {\n const day = dayNumber(date);\n if (day === undefined) throw new RangeError(`The date \"${date}\" is not a date YYYY-MM-DD.`);\n return day;\n}\n\n/**\n * This function gives the amount of each resource in the stores at a date, by the code of the resource.\n *\n * - A store gives nothing on its due date and after it.\n * - A store gives nothing when its part is in `stoppedParts`.\n */\nexport function storeAmounts(layer: EnduranceLayer, at: IsoDate, stoppedParts: ReadonlySet<string> = new Set()): Map<string, number> {\n const today = dayOf(at);\n const out = new Map<string, number>();\n for (const store of layer.stores) {\n if (store.due !== undefined && today >= dayOf(store.due)) continue;\n if (store.part !== undefined && stoppedParts.has(store.part)) continue;\n out.set(store.resource, (out.get(store.resource) ?? 0) + store.amount);\n }\n return out;\n}\n\n/** This function gives the amount of a need for each day in a case: the rate of the draw times the factor of the case. */\nexport function drawDemand(draw: Draw, caseCuts: CaseCuts): number {\n return draw.perDay * (caseCuts.factors?.[draw.need] ?? 1);\n}\n\n/**\n * This function gives the draws that take from the stores in a case: each draw whose supply stops, with a demand more than 0.\n * The sequence is by the level (the order of `levels`), then by the code of the need.\n */\nexport function caseDraws(layer: EnduranceLayer, caseCuts: CaseCuts, stoppedParts: ReadonlySet<string>): Draw[] {\n const rank = (level: string): number => {\n const index = layer.levels.indexOf(level);\n return index < 0 ? layer.levels.length : index;\n };\n return layer.draws\n .filter((draw) => stoppedParts.has(draw.supply) && drawDemand(draw, caseCuts) > 0)\n .sort((a, b) => rank(a.level) - rank(b.level) || (a.need < b.need ? -1 : a.need > b.need ? 1 : 0));\n}\n\n/** This function gives the need that a converter gives, or `undefined` when it gives a resource. */\nexport function giftNeed(converter: Converter): string | undefined {\n return \"need\" in converter.gives ? converter.gives.need : undefined;\n}\n\n/** This function gives the resource that a converter gives, or `undefined` when it gives a need. */\nexport function giftResource(converter: Converter): string | undefined {\n return \"resource\" in converter.gives ? converter.gives.resource : undefined;\n}\n\n/** The converters of a case that make each resource, in the order of the layer, by the code of the resource. */\ntype Makers = ReadonlyMap<string, readonly Converter[]>;\n\nfunction makersOf(layer: EnduranceLayer, stoppedParts: ReadonlySet<string>): Makers {\n const out = new Map<string, Converter[]>();\n for (const converter of layer.converters ?? []) {\n const resource = giftResource(converter);\n if (resource === undefined || !canRun(converter, stoppedParts)) continue;\n out.set(resource, [...(out.get(resource) ?? []), converter]);\n }\n return out;\n}\n\n/** The ways to get one need in a case: its direct uses, then the converters that give it, in the order of the layer. `makers` make the resources. */\ninterface Ways {\n readonly direct: readonly DirectUse[];\n readonly converters: readonly Converter[];\n readonly makers: Makers;\n}\n\nfunction waysOf(layer: EnduranceLayer, need: string, stoppedParts: ReadonlySet<string>, makers: Makers): Ways {\n return {\n direct: (layer.direct ?? []).filter((use) => use.need === need && use.amount > 0),\n converters: (layer.converters ?? []).filter((converter) => giftNeed(converter) === need && canRun(converter, stoppedParts)),\n makers,\n };\n}\n\n// A chain: the resources on the path of a take. A maker does not take a resource of its own path, so a cycle of the layer stops there.\nconst NO_PATH: ReadonlySet<string> = new Set();\n\n// The device-days that are left to the converters with a limit `perDay` are in the map of the resources, under a key that\n// no code of a resource has. Thus each copy of the map in a try copies them too. The converters of one device share one\n// key (`deviceKey`), and a converter with no device has a key of its own. One run of a converter uses `1 / perDay` of a device-day.\nconst RUNS = \"\\u0000runs:\";\n\nfunction runsKey(converter: Converter): string {\n return RUNS + deviceKey(converter);\n}\n\n/** This function gives the device-days that a converter has left in `left`, or undefined with no limit. */\nfunction daysLeft(left: ReadonlyMap<string, number>, converter: Converter): number | undefined {\n return converter.perDay === undefined ? undefined : left.get(runsKey(converter));\n}\n\n/** This function gives the map with no runs left of the converters: a map of the resources only. */\nfunction resourcesOnly(left: ReadonlyMap<string, number>): Map<string, number> {\n return new Map([...left].filter(([key]) => !key.startsWith(RUNS)));\n}\n\n/**\n * This function gives the most of a resource that `left` gives: its stock, and the runs of each maker.\n * It is an upper limit. When two inputs come from one resource, the true amount can be less.\n */\nfunction mostResource(left: ReadonlyMap<string, number>, makers: Makers, resource: string, path: ReadonlySet<string>): number {\n let total = left.get(resource) ?? 0;\n if (path.has(resource)) return total;\n const next = new Set(path).add(resource);\n for (const maker of makers.get(resource) ?? []) total += mostRuns(left, makers, maker, next) * maker.gives.amount;\n return total;\n}\n\n/** This function gives the most runs of a converter that `left` gives. It is an upper limit, as for `mostResource`. */\nfunction mostRuns(left: ReadonlyMap<string, number>, makers: Makers, converter: Converter, path: ReadonlySet<string>): number {\n const limit = daysLeft(left, converter);\n let runs = limit === undefined ? Infinity : limit * (converter.perDay ?? 0);\n for (const [resource, each] of inputsOf(converter)) runs = Math.min(runs, mostResource(left, makers, resource, path) / each);\n return Number.isFinite(runs) ? runs : 0;\n}\n\n/**\n * This function takes an amount of a resource from `left`: the stock first, then the makers in the order of the layer.\n * It changes `left`, and it gives the amount that it could not take.\n */\nfunction takeResource(left: Map<string, number>, makers: Makers, resource: string, amount: number, path: ReadonlySet<string>): number {\n const has = left.get(resource) ?? 0;\n const got = Math.min(amount, has);\n left.set(resource, has - got);\n let rest = amount - got;\n if (rest <= 0 || path.has(resource)) return Math.max(0, rest);\n const next = new Set(path).add(resource);\n for (const maker of makers.get(resource) ?? []) {\n if (rest <= 0) break;\n rest -= run(left, makers, maker, rest / maker.gives.amount, next) * maker.gives.amount;\n }\n return Math.max(0, rest);\n}\n\n/**\n * This function runs a converter up to `wanted` times with the resources of `left`, and it gives the count of runs.\n * It changes `left`. When two inputs come from one resource, `largestFit` finds the runs that the resources give.\n */\nfunction run(left: Map<string, number>, makers: Makers, converter: Converter, wanted: number, path: ReadonlySet<string>): number {\n const inputs = inputsOf(converter);\n const most = Math.min(wanted, mostRuns(left, makers, converter, path));\n if (!(most > 0)) return 0;\n const attempt = (runs: number): Try<Map<string, number>> => {\n const copy = new Map(left);\n let need = 0;\n let short = 0;\n // The converter takes its device-days before its inputs. Thus a maker on the same device gets only the rest.\n const limit = daysLeft(copy, converter);\n if (limit !== undefined && converter.perDay !== undefined && converter.perDay > 0) {\n const wanted = runs / converter.perDay;\n const got = Math.min(wanted, limit);\n copy.set(runsKey(converter), limit - got);\n need += runs;\n short += (wanted - got) * converter.perDay;\n }\n for (const [resource, each] of inputs) {\n need += runs * each;\n short += takeResource(copy, makers, resource, runs * each, path);\n }\n return { short, need, value: copy };\n };\n const { x: runs, value: best } = largestFit(most, attempt);\n if (best === undefined) return 0;\n for (const [resource, amount] of best) left.set(resource, amount);\n return runs;\n}\n\n/**\n * This function takes an amount of a need from the resources in `left`: the direct uses first, then the converters.\n * A direct use or a converter takes each resource from its stock first, then from its makers.\n * It changes `left`, and it gives the amount that it could not take.\n */\nfunction take(left: Map<string, number>, ways: Ways, amount: number): number {\n let rest = amount;\n for (const use of ways.direct) {\n if (rest <= 0) break;\n const wanted = rest / use.amount;\n rest -= (wanted - takeResource(left, ways.makers, use.resource, wanted, NO_PATH)) * use.amount;\n }\n for (const converter of ways.converters) {\n if (rest <= 0) break;\n rest -= run(left, ways.makers, converter, rest / converter.gives.amount, NO_PATH) * converter.gives.amount;\n }\n return Math.max(0, rest);\n}\n\n/** This function gives each resource that a need can use: the inputs of its ways, and the inputs of their makers, through each chain. */\nfunction inputClosure(ways: Ways): Set<string> {\n const out = new Set<string>();\n const queue = [...ways.direct.map((use) => use.resource), ...ways.converters.flatMap((converter) => [...inputsOf(converter).keys()])];\n for (let resource = queue.shift(); resource !== undefined; resource = queue.shift()) {\n if (out.has(resource)) continue;\n out.add(resource);\n for (const maker of ways.makers.get(resource) ?? []) queue.push(...inputsOf(maker).keys());\n }\n return out;\n}\n\n/** The relative tolerance of a used-up resource. */\nconst USED_UP = 1e-9;\n\n/**\n * This function gives the days that each draw holds when a case stops its supply, and the resources that are used up then.\n *\n * - A draw takes from the stores only when the case stops its supply part. Each other draw holds without end, and the result leaves it out.\n * - The demand of a draw for each day is its rate times the factor of the case.\n * - The draws take the resources in the order of their level, then of their codes. A draw takes from its direct uses first, then from its converters.\n * - The days of a draw are the largest `T` at which the stores give `T` days of its demand, after each higher draw.\n * - Each higher draw keeps back its own days times its demand. Thus the takes of all the draws are not more than the stores at any time.\n * - The take order is a rule, not the best share: the direct uses in the order of the list, then the converters. The days are the days of this order.\n * A draw with a shared device is different. Refer to the last item.\n * - A converter whose device stops gives nothing. A store whose part stops gives nothing.\n * - A converter can give a resource. A take of a resource uses the stock first, then the converters that make it, through each chain.\n * - A converter with a limit `perDay` runs `perDay` times `devices` times `T` times or less in `T` days. The converters of one device share it.\n * - The higher draws use the runs of a limit first.\n * - A higher draw keeps back its runs of each day for all the days of a lower draw, also when its own days are fewer. This is the safe side.\n * - Two limited converters of one device can make the shortfall of the take order decrease when the days increase.\n * Thus a draw whose ways reach two converters of one device, each with a limit `perDay` more than 0, does not use the take order.\n * A linear program with exact rationals gives its days: the largest `T` with the best share of its stocks and of the device-days.\n * At this `T`, the draw takes the smallest sum of its takes of the stocks, each over its stock, then the fewest device-days.\n *\n * The function is pure, but for an internal count of the tries of its fits for the tests. It throws a `RangeError` for a date that is not `YYYY-MM-DD`. The gate `checkEndurance` examines the layer before.\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 */\nexport function enduranceOf(layer: EnduranceLayer, caseCuts: CaseCuts, options: CaseOptions): Endurance {\n const stoppedParts = caseStopped(caseCuts, options);\n const start = storeAmounts(layer, options.at, stoppedParts);\n const makers = makersOf(layer, stoppedParts);\n const stocked = new Set(layer.stores.map((store) => store.resource));\n const limited = (layer.converters ?? []).filter((converter) => converter.perDay !== undefined && canRun(converter, stoppedParts));\n // The count of devices of each key (`deviceKey`). The gate refuses two counts for one device.\n const devices = new Map(limited.map((converter) => [deviceKey(converter), converter.devices ?? 1]));\n // The device-days of each day that the higher draws use, by the key of the device. A higher draw keeps back its\n // device-days of each day for all the days of a lower draw, also after its own days end. This is the safe side.\n const used = new Map<string, number>();\n // The stocks that the higher draws leave after their own days.\n let before = new Map(start);\n const needs: Record<string, { days: number; binding: string[]; takes: Record<string, number>; capped?: string[] }> = {};\n for (const draw of caseDraws(layer, caseCuts, stoppedParts)) {\n const ways = waysOf(layer, draw.need, stoppedParts, makers);\n const demand = drawDemand(draw, caseCuts);\n // The device-days of each day that the higher draws leave to this draw, by the key of the device.\n const room = new Map([...devices].map(([key, count]) => [key, Math.max(0, count - (used.get(key) ?? 0))] as const));\n const closure = inputClosure(ways);\n // The converters that the draw can use: the converters that give its need, and the makers of its inputs through each chain.\n const reach = new Set([...ways.converters, ...[...closure].flatMap((resource) => makers.get(resource) ?? [])]);\n // With two limited converters of one device, the shortfall of the take order can decrease when the days increase.\n // For such a draw, a linear program gives the best share of the device-days and of the stocks.\n const share = sharesDevice(reach) ? bestShare({ stock: before, room, direct: ways.direct, converters: ways.converters, makers, demand }) : undefined;\n let low: number;\n let left: Map<string, number>;\n if (share !== undefined) {\n low = share.days;\n left = new Map(before);\n for (const [resource, amount] of share.taken) left.set(resource, Math.max(0, (left.get(resource) ?? 0) - amount));\n for (const [key, free] of room) left.set(RUNS + key, Math.max(0, free * low - (share.used.get(key) ?? 0)));\n } else {\n const after = (days: number): { left: Map<string, number>; short: number } => {\n const tried = new Map(before);\n for (const [key, free] of room) tried.set(RUNS + key, free * days);\n return { left: tried, short: take(tried, ways, days * demand) };\n };\n // The upper limit: the days that the draw holds when it takes all the stores itself. `largestFit` finds the days below it.\n const fit = largestFit(capacity(start, ways) / demand, (days) => {\n const tried = after(days);\n return { short: tried.short, need: days * demand, value: tried.left };\n });\n low = fit.x;\n left = fit.value ?? after(low).left;\n }\n // The binding resources are of the stores only: a used-up limit of runs is in `capped`, not here.\n const stores = resourcesOnly(left);\n const binding = [...closure]\n .filter((resource) => !makers.has(resource) || stocked.has(resource))\n .filter((resource) => mostResource(stores, makers, resource, NO_PATH) <= USED_UP * Math.max(1, start.get(resource) ?? 0))\n .sort();\n const takes: Record<string, number> = {};\n for (const [resource, amount] of before) {\n const taken = amount - (left.get(resource) ?? 0);\n if (taken > 0) takes[resource] = taken;\n }\n // A limit stops the draw when its limit gives the converter no runs left, and its inputs give more runs.\n // The runs left are the device-days left times `perDay`. Thus a limit of 0 stops the draw, also with its device-days left.\n const runsLeft = (converter: Converter): number => (daysLeft(left, converter) ?? 0) * (converter.perDay ?? 0);\n const runsGiven = (converter: Converter): number => (devices.get(deviceKey(converter)) ?? 1) * (converter.perDay ?? 0) * low;\n const capped = limited\n .filter((converter) => reach.has(converter))\n .filter((converter) => runsLeft(converter) <= USED_UP * Math.max(1, runsGiven(converter)))\n .filter((converter) => mostRuns(stores, makers, converter, NO_PATH) > USED_UP)\n .map((converter) => converter.id)\n .sort();\n needs[draw.need] = capped.length === 0 ? { days: low, binding, takes } : { days: low, binding, takes, capped };\n // The device-days of each day of this draw count against each lower draw, for all of its days.\n if (low > 0) for (const [key, free] of room) used.set(key, (used.get(key) ?? 0) + (free * low - (left.get(RUNS + key) ?? 0)) / low);\n before = stores;\n }\n return { case: caseCuts.case, at: options.at, needs };\n}\n\n/** This function tells if two converters of `reach` with a limit `perDay` more than 0 share one device. */\nfunction sharesDevice(reach: ReadonlySet<Converter>): boolean {\n const seen = new Set<string>();\n for (const converter of reach) {\n if (converter.perDay === undefined || !(converter.perDay > 0)) continue;\n const key = deviceKey(converter);\n if (seen.has(key)) return true;\n seen.add(key);\n }\n return false;\n}\n\n/**\n * This function gives an upper limit of a need that the stores give with no other draw, through each chain.\n * A converter that takes nothing gives nothing: the gate refuses it.\n */\nfunction capacity(start: ReadonlyMap<string, number>, ways: Ways): number {\n let total = 0;\n for (const use of ways.direct) total += mostResource(start, ways.makers, use.resource, NO_PATH) * use.amount;\n for (const converter of ways.converters) total += mostRuns(start, ways.makers, converter, NO_PATH) * converter.gives.amount;\n return total;\n}\n","import { stronglyConnectedComponents } from \"@mark1russell7/collections/graph\";\nimport { curveFault, dayNumber, type Fault, type Stack } from \"@mark1russell7/system-stack\";\nimport { giftNeed, giftResource } from \"./endurance.ts\";\nimport type { Converter, EnduranceLayer } from \"./layer.ts\";\n\n// The gate of an endurance layer: the meaning of a layer with a correct form, for its base stack.\n\n/**\n * 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.\n *\n * - `endurance-twice`: two or more records of one list have one key. A key is a level, a resource, a store, a need, a converter or a case.\n * The key of a prior is its case and its place. A converter takes each resource on one line, and a case cuts each part one time.\n * - `endurance-level-unknown`: the level of a draw is not a level of the layer.\n * - `endurance-resource-unknown`: a store, a use or a converter names a resource that the layer does not have.\n * - `endurance-part-unknown`: a supply, a device, the part of a store or a cut is not a part of the base stack.\n * - `endurance-range`: an amount, a rate, a count or a factor is not a finite number of 0 or more. Or a reach is not from 0 to 1.\n * - `endurance-date`: a date is not a date `YYYY-MM-DD`.\n * - `endurance-converter-empty`: a converter takes nothing, or it gives an amount of 0.\n * - `endurance-curve`: a survival curve does not start at `[0, 1]`, or it does not end at a chance of 0.\n * Or its days do not increase, or its chance increases.\n * - `endurance-prior-case`: a prior names a case that the layer does not have.\n * - `endurance-cycle`: converters make a resource from itself, through one converter or a chain. One fault names each cycle.\n * - `endurance-devices`: two converters of one device give two different counts of devices.\n * - `endurance-device-mix` (warning): a device has a converter with a limit `perDay` and a converter with no limit. The\n * converter with no limit uses no device-days, so its runs do not reduce the runs of the limited converter.\n * - `endurance-no-way` (warning): a draw has no direct use and no converter, so it holds 0 days when its supply stops.\n * - `endurance-cut-no-curve` (warning): a cut has no curve of its duration. The draws whose stop it can be part of are no read in the shortfall.\n */\nexport const ENDURANCE_CODES: readonly [\n \"endurance-twice\",\n \"endurance-level-unknown\",\n \"endurance-resource-unknown\",\n \"endurance-part-unknown\",\n \"endurance-range\",\n \"endurance-date\",\n \"endurance-converter-empty\",\n \"endurance-curve\",\n \"endurance-prior-case\",\n \"endurance-cycle\",\n \"endurance-devices\",\n \"endurance-device-mix\",\n \"endurance-no-way\",\n \"endurance-cut-no-curve\",\n] = [\n \"endurance-twice\",\n \"endurance-level-unknown\",\n \"endurance-resource-unknown\",\n \"endurance-part-unknown\",\n \"endurance-range\",\n \"endurance-date\",\n \"endurance-converter-empty\",\n \"endurance-curve\",\n \"endurance-prior-case\",\n \"endurance-cycle\",\n \"endurance-devices\",\n \"endurance-device-mix\",\n \"endurance-no-way\",\n \"endurance-cut-no-curve\",\n];\n\n/** A code of `ENDURANCE_CODES`. */\nexport type EnduranceCode = (typeof ENDURANCE_CODES)[number];\n\n/** A fault of the gate of an endurance layer. */\nexport interface EnduranceFault extends Fault {\n readonly code: EnduranceCode;\n}\n\nexport { curveFault } from \"@mark1russell7/system-stack\";\n\n/**\n * This function gives each fault of an endurance layer. With a base stack, it also examines the `id` of each part. A list with no error tells that the gate passes.\n *\n * The faults are in the order of the layer. The function is pure.\n *\n * @param layer - The endurance layer\n * @param stack - The base stack, with the layer. With no stack, the gate does not examine the parts.\n * @returns The faults\n */\nexport function checkEndurance(layer: EnduranceLayer, stack?: Stack): EnduranceFault[] {\n const faults: EnduranceFault[] = [];\n const add = (level: EnduranceFault[\"level\"], code: EnduranceCode, at: string, message: string): void => {\n faults.push({ level, code, at, message });\n };\n const once = (what: string, keys: readonly string[]): void => {\n const seen = new Set<string>();\n for (const key of keys) {\n if (seen.has(key)) add(\"error\", \"endurance-twice\", key, `Two or more ${what} have the key \"${key}\".`);\n seen.add(key);\n }\n };\n const range = (at: string, what: string, value: number): void => {\n if (!(Number.isFinite(value) && value >= 0)) add(\"error\", \"endurance-range\", at, `The ${what} of \"${at}\" is ${String(value)}. It must be a finite number of 0 or more.`);\n };\n const date = (at: string, value: string): void => {\n if (dayNumber(value) === undefined) add(\"error\", \"endurance-date\", at, `The date \"${value}\" of \"${at}\" is not a date YYYY-MM-DD.`);\n };\n const parts = stack === undefined ? undefined : new Set(stack.parts.map((part) => part.id));\n const part = (at: string, what: string, id: string | undefined): void => {\n if (parts !== undefined && id !== undefined && !parts.has(id)) add(\"error\", \"endurance-part-unknown\", at, `The ${what} \"${id}\" of \"${at}\" is not a part of the stack.`);\n };\n const resources = new Set(layer.resources.map((resource) => resource.code));\n const resource = (at: string, code: string): void => {\n if (!resources.has(code)) add(\"error\", \"endurance-resource-unknown\", at, `The resource \"${code}\" of \"${at}\" is not a resource of the layer.`);\n };\n const direct = layer.direct ?? [];\n const converters = layer.converters ?? [];\n const cases = layer.cases ?? [];\n const priors = layer.priors ?? [];\n\n once(\"levels\", layer.levels);\n once(\"resources\", layer.resources.map((item) => item.code));\n once(\"stores\", layer.stores.map((store) => store.id));\n once(\"draws\", layer.draws.map((draw) => draw.need));\n once(\"converters\", converters.map((converter) => converter.id));\n once(\"cases\", cases.map((item) => item.case));\n once(\"priors\", priors.map((prior) => `${prior.case}@${prior.place}`));\n\n for (const store of layer.stores) {\n resource(store.id, store.resource);\n range(store.id, \"amount\", store.amount);\n if (store.due !== undefined) date(store.id, store.due);\n part(store.id, \"part\", store.part);\n }\n const levels = new Set(layer.levels);\n for (const draw of layer.draws) {\n if (!levels.has(draw.level)) add(\"error\", \"endurance-level-unknown\", draw.need, `The level \"${draw.level}\" of the draw \"${draw.need}\" is not a level of the layer.`);\n range(draw.need, \"rate\", draw.perDay);\n if (draw.users !== undefined) range(draw.need, \"count of users\", draw.users);\n part(draw.need, \"supply\", draw.supply);\n const ways = direct.some((use) => use.need === draw.need) || converters.some((converter) => giftNeed(converter) === draw.need);\n if (!ways) add(\"warning\", \"endurance-no-way\", draw.need, `The draw \"${draw.need}\" has no direct use and no converter. It holds 0 days when its supply stops.`);\n }\n for (const use of direct) {\n const at = `${use.resource}>${use.need}`;\n resource(at, use.resource);\n range(at, \"amount\", use.amount);\n }\n for (const converter of converters) {\n once(`resources of the converter \"${converter.id}\"`, converter.takes.map((input) => input.resource));\n for (const input of converter.takes) {\n resource(converter.id, input.resource);\n range(converter.id, \"amount\", input.amount);\n }\n range(converter.id, \"amount\", converter.gives.amount);\n const made = giftResource(converter);\n if (made !== undefined) resource(converter.id, made);\n if (!converter.takes.some((input) => input.amount > 0) || converter.gives.amount === 0) add(\"error\", \"endurance-converter-empty\", converter.id, `The converter \"${converter.id}\" takes nothing, or it gives nothing.`);\n part(converter.id, \"device\", converter.device);\n if (converter.perDay !== undefined) range(converter.id, \"rate perDay\", converter.perDay);\n if (converter.devices !== undefined && !(Number.isSafeInteger(converter.devices) && converter.devices >= 1))\n add(\"error\", \"endurance-range\", converter.id, `The count of devices of \"${converter.id}\" is ${String(converter.devices)}. It must be a whole number of 1 or more.`);\n }\n const counts = new Map<string, number>();\n for (const converter of converters) {\n if (converter.device === undefined) continue;\n const count = converter.devices ?? 1;\n const seen = counts.get(converter.device);\n if (seen !== undefined && seen !== count)\n add(\"error\", \"endurance-devices\", converter.id, `The converter \"${converter.id}\" gives the count ${String(count)} for the device \"${converter.device}\". An other converter gives the count ${String(seen)}.`);\n if (seen === undefined) counts.set(converter.device, count);\n }\n // One fault names each device with a limited converter and a converter with no limit, at the first converter with no limit.\n const mixed = new Set<string>();\n for (const converter of converters) {\n const device = converter.device;\n if (device === undefined || converter.perDay !== undefined || mixed.has(device)) continue;\n const limited = converters.find((other) => other.device === device && other.perDay !== undefined);\n if (limited === undefined) continue;\n mixed.add(device);\n add(\"warning\", \"endurance-device-mix\", converter.id, `The device \"${device}\" has the limited converter \"${limited.id}\" and the converter \"${converter.id}\" with no limit. \"${converter.id}\" uses no device-days.`);\n }\n const caseCodes = new Set(cases.map((item) => item.case));\n for (const item of cases) {\n once(`cuts of the case \"${item.case}\"`, item.cuts.map((cut) => cut.part));\n for (const cut of item.cuts) {\n const at = `${item.case}/${cut.part}`;\n part(at, \"cut\", cut.part);\n if (cut.duration === undefined) {\n add(\"warning\", \"endurance-cut-no-curve\", at, `The cut \"${at}\" has no curve of its duration, so the draws that it can stop are no read.`);\n continue;\n }\n const fault = curveFault(cut.duration);\n if (fault !== undefined) add(\"error\", \"endurance-curve\", at, `The duration of the cut \"${at}\": ${fault}`);\n }\n for (const [need, factor] of Object.entries(item.factors ?? {})) range(`${item.case}/${need}`, \"factor\", factor);\n if (item.leadSeconds !== undefined) range(item.case, \"lead time\", item.leadSeconds);\n }\n for (const cycle of resourceCycles(converters)) {\n const [first = \"\"] = cycle;\n const names = cycle.map((code) => `\"${code}\"`).join(\", \");\n const message = cycle.length === 1 ? `A converter makes the resource ${names} from itself.` : `Converters make the resources ${names} from each other.`;\n add(\"error\", \"endurance-cycle\", first, `${message} A chain of converters cannot end.`);\n }\n for (const prior of priors) {\n const at = `${prior.case}@${prior.place}`;\n if (!caseCodes.has(prior.case)) add(\"error\", \"endurance-prior-case\", at, `The prior \"${at}\" names the case \"${prior.case}\", which the layer does not have.`);\n range(at, \"count of events in one year\", prior.perYear);\n if (!(prior.reach >= 0 && prior.reach <= 1)) add(\"error\", \"endurance-range\", at, `The reach of \"${at}\" is ${String(prior.reach)}. It must be from 0 to 1.`);\n date(at, prior.asOf);\n }\n return faults;\n}\n\n/** This function gives each cycle of resources: a resource is made from a resource that a converter makes from it. Each cycle is a list of codes. */\nfunction resourceCycles(converters: readonly Converter[]): string[][] {\n const from = new Map<string, Set<string>>();\n for (const converter of converters) {\n const made = giftResource(converter);\n if (made === undefined) continue;\n const inputs = from.get(made) ?? new Set<string>();\n for (const input of converter.takes) if (input.amount > 0) inputs.add(input.resource);\n from.set(made, inputs);\n }\n const successors = (code: string): Iterable<string> => from.get(code) ?? [];\n return stronglyConnectedComponents(from.keys(), successors).filter((component) => {\n const [only = \"\"] = component;\n return component.length > 1 || (from.get(only)?.has(only) ?? false);\n });\n}\n\n/** This function tells if a list of faults has an error. */\nexport function hasEnduranceError(faults: readonly EnduranceFault[]): boolean {\n return faults.some((fault) => fault.level === \"error\");\n}\n","import { canonicalJson } from \"@mark1russell7/rigor-generators\";\nimport { joinRecords, joinSetting, type LayerParse, type LayerPiece } from \"@mark1russell7/system-stack\";\nimport { ENDURANCE_SCHEMA, type EnduranceLayer } from \"./layer.ts\";\n\n// The join of the endurance layers of the fragments of a stack, for example one file of stores for each owner.\n\n/**\n * This function joins the endurance layers of the fragments of a stack into one layer.\n *\n * - The levels are one setting: each fragment that has levels gives the same list, else the join has a fault.\n * - The records of each list are in the order of the fragments.\n * - Two resources with one code in two fragments join into one resource when their records are equal. A different field is a fault.\n * Its message gives the canonical JSON of the record of each fragment.\n * - A code that one fragment has two times stays in the joined layer. The gate `checkEndurance` finds it.\n * - One key of each other list in two or more fragments is a fault, also when the records are equal.\n * - The key of a direct use is its resource and its need.\n *\n * The function is pure, and it changes no layer. The gate `checkEndurance` examines the joined layer afterward.\n *\n * @param pieces - The layers, with the name of the fragment of each one, in the order of the fragments.\n * @returns The joined layer, or the faults of the join.\n */\nexport function joinEndurance(pieces: readonly LayerPiece<EnduranceLayer>[]): LayerParse<EnduranceLayer> {\n const levels = joinSetting(pieces, (layer) => (layer.levels.length > 0 ? layer.levels.join(\"\\n\") : undefined), \"levels\");\n // Two fragments can declare one resource, for example `water.stored` in `L`. Canonical JSON (RFC 8785) compares the records,\n // so the order of the keys has no effect. The message of a fault gives the canonical JSON of the record of each fragment.\n const resources = joinRecords(pieces, (layer) => layer.resources, (item) => item.code, \"resource\", {\n equal: (first, other) => canonicalJson(first) === canonicalJson(other),\n text: canonicalJson,\n });\n const stores = joinRecords(pieces, (layer) => layer.stores, (item) => item.id, \"store\");\n const draws = joinRecords(pieces, (layer) => layer.draws, (item) => item.need, \"draw\");\n const direct = joinRecords(pieces, (layer) => layer.direct, (item) => `${item.resource}>${item.need}`, \"direct use\");\n const converters = joinRecords(pieces, (layer) => layer.converters, (item) => item.id, \"converter\");\n const cases = joinRecords(pieces, (layer) => layer.cases, (item) => item.case, \"case\");\n const priors = joinRecords(pieces, (layer) => layer.priors, (item) => `${item.case}@${item.place}`, \"prior\");\n const errors = [levels, resources, stores, draws, direct, converters, cases, priors].flatMap((join) => join.errors);\n if (errors.length > 0) return { ok: false, errors };\n const has = (key: \"direct\" | \"converters\" | \"cases\" | \"priors\"): boolean => pieces.some((piece) => piece.layer[key] !== undefined);\n return {\n ok: true,\n layer: {\n schema: ENDURANCE_SCHEMA,\n levels: levels.value === undefined ? [] : levels.value.split(\"\\n\"),\n resources: resources.items,\n stores: stores.items,\n draws: draws.items,\n ...(has(\"direct\") ? { direct: direct.items } : {}),\n ...(has(\"converters\") ? { converters: converters.items } : {}),\n ...(has(\"cases\") ? { cases: cases.items } : {}),\n ...(has(\"priors\") ? { priors: priors.items } : {}),\n },\n };\n}\n"],"mappings":";;;;;;;;AAKA,SAAgB,SAAS,WAA2C;CAClE,MAAM,sBAAM,IAAI,IAAoB;CACpC,KAAK,MAAM,SAAS,UAAU,OAAO,IAAI,MAAM,SAAS,GAAG,IAAI,IAAI,MAAM,WAAW,IAAI,IAAI,MAAM,QAAQ,KAAK,KAAK,MAAM,MAAM;CAChI,OAAO;AACT;;AAGA,SAAgB,OAAO,WAAsB,cAA4C;CACvF,OAAO,UAAU,MAAM,SAAS,KAAK,SAAS,SAAS,CAAC,CAAC,OAAO,MAAM,UAAU,WAAW,KAAA,KAAa,CAAC,aAAa,IAAI,UAAU,MAAM;AAC5I;;;;;AAMA,SAAgB,UAAU,WAA8B;CACtD,OAAO,UAAU,WAAW,KAAA,IAAY,aAAa,UAAU,OAAO,UAAU,UAAU;AAC5F;;;ACrBA,MAAa,YAAY;;;;;AAmBzB,MAAa,WAAW,EAAE,OAAO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