@mark1russell7/stack-endurance 0.8.6 → 0.8.7
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 +31 -2
- package/build/index.d.ts +31 -0
- package/build/index.d.ts.map +1 -1
- package/build/index.js +434 -123
- package/build/index.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -29,7 +29,7 @@ Each function is a plain function with no clock, no network and no file. The uni
|
|
|
29
29
|
- The days of a draw are the largest `T` at which the stores give `T` days of its demand, after each higher draw.
|
|
30
30
|
- 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.
|
|
31
31
|
- The take order is a rule, not the best share. The days are the days of this order. A draw with a shared device is different (refer to the limit `perDay` below). `takes` gives the amount of each resource that a draw takes.
|
|
32
|
-
- `jointDays` gives the best share for a set of draws. Refer to the
|
|
32
|
+
- `jointDays` gives the best share for a set of draws. `bestEndurance` gives the best share for all the draws, level by level. Refer to the sections on the joint days and on the best endurance.
|
|
33
33
|
- A store gives nothing on its due date and after it. A store or a converter whose part stops gives nothing.
|
|
34
34
|
- A converter can have a limit `perDay`, the most runs of one device in a day, and a count `devices` (default 1). Over `T` days, the converters of one device use `devices` times `T` days of the device or less. One run uses `1 / perDay` of a day of the device. A maker and its taker on one device share these days.
|
|
35
35
|
- The higher draws use the days of a device first. Each higher draw keeps back its part of each day for all the days of a lower draw. This is the safe side.
|
|
@@ -107,11 +107,40 @@ The take order gives the drink 6.667 days. The drink keeps back all the water fo
|
|
|
107
107
|
|
|
108
108
|
The joint days are not more than the days of each draw alone. The take order tells the days of a rule of priority. The joint days tell the days of the best share.
|
|
109
109
|
|
|
110
|
+
## The best endurance
|
|
111
|
+
|
|
112
|
+
`bestEndurance(layer, caseCuts, options)` gives the days of each draw with the best share of the stores and of the devices. Its result has the form of `enduranceOf`, so `caseShortfall` takes it.
|
|
113
|
+
|
|
114
|
+
- The share is lexicographic by level. The draws of the first level get their best days. Then the draws of the next level get their best days, and so on.
|
|
115
|
+
- In one level, the share is the best for the draw with the fewest days, then for the next draw, and so on. This is the leximin share.
|
|
116
|
+
- Thus a draw cannot take a store that another draw of its level needs more. A higher draw does not take a store that a lower draw needs, when the higher draw has a second way.
|
|
117
|
+
- Each step is a linear program with exact rationals. It takes the largest common floor of the open draws.
|
|
118
|
+
- A draw whose floor row has a dual value that is not 0 cannot get more days. The step fixes its days. Each step fixes one draw or more.
|
|
119
|
+
- A fixed draw keeps its days. Its share of the stocks can change in a later step.
|
|
120
|
+
- A fixed draw keeps the device-days of each day that it uses, for all the days of the later draws. This is the safe side, as in `enduranceOf`.
|
|
121
|
+
- A draw with no end gets `Infinity` days. It takes no stock.
|
|
122
|
+
- The stores, the uses, the converters and the devices follow the rules of `jointDays`.
|
|
123
|
+
- The fewest days of the first level are the joint days of the draws of that level.
|
|
124
|
+
|
|
125
|
+
An example: the draw `a` drinks water or juice, and the draw `b` drinks only water. Each draw takes 1 L each day, and the stores have 10 L of each. The two draws are at one level.
|
|
126
|
+
|
|
127
|
+
```ts
|
|
128
|
+
import { bestEndurance, enduranceOf } from "@mark1russell7/stack-endurance";
|
|
129
|
+
|
|
130
|
+
const ordered = enduranceOf(layer, dry, { at: "2026-12-01" });
|
|
131
|
+
// ordered.needs.a.days is 20, and ordered.needs.b.days is 0.
|
|
132
|
+
const best = bestEndurance(layer, dry, { at: "2026-12-01" });
|
|
133
|
+
// best.needs.a is { days: 10, binding: ["juice", "water"], takes: { juice: 10 } }.
|
|
134
|
+
// best.needs.b is { days: 10, binding: ["water"], takes: { water: 10 } }.
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
The take order gives the water to `a` first, so `b` gets 0 days. The best share gives the juice to `a` and the water to `b`.
|
|
138
|
+
|
|
110
139
|
## The entries
|
|
111
140
|
|
|
112
141
|
| Entry | What it has |
|
|
113
142
|
| --- | --- |
|
|
114
|
-
| `@mark1russell7/stack-endurance` | The records of a layer, the endurance, joint days and shortfall queries, the gate, the join and a sample. |
|
|
143
|
+
| `@mark1russell7/stack-endurance` | The records of a layer, the endurance, joint days, best endurance and shortfall queries, the gate, the join and a sample. |
|
|
115
144
|
| `@mark1russell7/stack-endurance/schema` | `enduranceSchema`, the zod schema of a layer, with `parseEndurance`. |
|
|
116
145
|
| `@mark1russell7/stack-endurance/add-on` | `enduranceAddOn`, the add-on in the form of the layer contract of the core. |
|
|
117
146
|
|
package/build/index.d.ts
CHANGED
|
@@ -122,6 +122,37 @@ export interface JointDays {
|
|
|
122
122
|
* @throws {RangeError} A code of `needs` is not the need of a draw of the layer, or a date is not `YYYY-MM-DD`.
|
|
123
123
|
*/
|
|
124
124
|
export declare function jointDays(layer: EnduranceLayer, caseCuts: CaseCuts, options: CaseOptions, needs: readonly string[]): JointDays;
|
|
125
|
+
/**
|
|
126
|
+
* This function gives the days that each draw holds when a case stops its supply. The stores and the devices have their best share.
|
|
127
|
+
* The result has the form of `enduranceOf`, so `caseShortfall` takes it.
|
|
128
|
+
*
|
|
129
|
+
* The share is lexicographic. The draws of the first level get their best days, then the draws of the next level get theirs, and so on.
|
|
130
|
+
* In one level, the share is the best for the draw with the fewest days, then for the next draw, and so on (the leximin share).
|
|
131
|
+
* Thus a draw of a level cannot take a store that another draw of the level needs more.
|
|
132
|
+
*
|
|
133
|
+
* - The function solves a sequence of linear programs over the totals of the spans. Each program has the days of the open draws
|
|
134
|
+
* and their common floor. For each draw, it has the take of each direct use, the runs of each converter and the share of each stock.
|
|
135
|
+
* - Each step takes the largest floor. A draw whose floor row has a dual value that is not 0 cannot get more days. The step fixes its days.
|
|
136
|
+
* The dual values of the floor rows add to 1, so each step fixes one draw or more.
|
|
137
|
+
* - A fixed draw keeps its days in each later step. Its share of the stocks can change, so a later draw can get a store that it does not need.
|
|
138
|
+
* - The stores, the direct uses, the converters and the devices follow the rules of `jointDays`. A store counts with all of its amount when its due date is after `at`.
|
|
139
|
+
* - A fixed draw keeps the device-days of each day that it uses at its step, for all the days of the later draws. This is the safe side, as in `enduranceOf`.
|
|
140
|
+
* The exact share of a device between two spans is not a linear program: the device-days of a day are the runs over the span.
|
|
141
|
+
* - A step with no largest floor gives the open draws no end. Each of them takes no stock, and keeps the fewest device-days of each day.
|
|
142
|
+
* - At the end, a program takes the smallest sum of the shares of the stocks, each over its stock, then the fewest device-days.
|
|
143
|
+
* These are the takes of the result. A resource in `binding` has no stock left at this point.
|
|
144
|
+
* - A draw in `capped` used a device with no device-days left at the step that fixed it.
|
|
145
|
+
*
|
|
146
|
+
* The programs use exact rationals, so the result has no error of the method. Only the change back to a number rounds.
|
|
147
|
+
* The fewest days of the first level are the joint days (`jointDays`) of the draws of that level.
|
|
148
|
+
*
|
|
149
|
+
* @param layer - The endurance layer
|
|
150
|
+
* @param caseCuts - The case
|
|
151
|
+
* @param options - The date, and the stack or the parts that are also down
|
|
152
|
+
* @returns The endurance of each draw whose supply stops
|
|
153
|
+
* @throws {RangeError} A date is not `YYYY-MM-DD`.
|
|
154
|
+
*/
|
|
155
|
+
export declare function bestEndurance(layer: EnduranceLayer, caseCuts: CaseCuts, options: CaseOptions): Endurance;
|
|
125
156
|
/**
|
|
126
157
|
* This function gives the expected days of a cut after a time, up to a horizon: `E[max(0, min(D, to) - from)]`.
|
|
127
158
|
* It is the area under the curve from `from` to `to`. The curve is linear between its points, so the area is exact.
|
package/build/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":["CutBound"],"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;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":["CutBound"],"sources":["../src/endurance.ts","../src/joint.ts","../src/best.ts","../src/shortfall.ts","../src/check.ts","../src/join.ts","../src/sample.ts"],"mappings":";;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBCNtG,cAAc,OAAO,gBAAgB,UAAU,UAAU,SAAS,cAAc;;;;;;wBClDhF,SAAS,OA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AAwB;;;;;;;;;qBAkBxB,kBAAkB"}
|
package/build/index.js
CHANGED
|
@@ -2,8 +2,160 @@ import { t as ENDURANCE_SCHEMA } from "./layer-a3Fr70Uh.js";
|
|
|
2
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
3
|
import { DEFAULT_MAX_SETS, STACK_SCHEMA, neededParts, stopSets, survivalAt, weakestBound } from "@mark1russell7/system-stack";
|
|
4
4
|
import { solveLexicographic } from "@mark1russell7/linear";
|
|
5
|
-
import { ONE, ZERO, add, div, equals, mul, neg, sign, toNumber } from "@mark1russell7/rational";
|
|
5
|
+
import { ONE, ZERO, add, div, equals, mul, neg, sign, sub, toNumber } from "@mark1russell7/rational";
|
|
6
6
|
import { pathSetReliability, stronglyConnectedComponents } from "@mark1russell7/collections/graph";
|
|
7
|
+
// src/program.ts
|
|
8
|
+
/** A program in construction: the count of its variables and its rows. */
|
|
9
|
+
var Program = class {
|
|
10
|
+
count = 0;
|
|
11
|
+
rows = [];
|
|
12
|
+
/** This method adds a variable and gives its index. */
|
|
13
|
+
next() {
|
|
14
|
+
return this.count++;
|
|
15
|
+
}
|
|
16
|
+
/** This method adds a row and gives its index. */
|
|
17
|
+
push(row, relation, rhs) {
|
|
18
|
+
this.rows.push({
|
|
19
|
+
row,
|
|
20
|
+
relation,
|
|
21
|
+
rhs
|
|
22
|
+
});
|
|
23
|
+
return this.rows.length - 1;
|
|
24
|
+
}
|
|
25
|
+
/** This method gives the dense rows for `solveLexicographic`. */
|
|
26
|
+
constraints() {
|
|
27
|
+
return this.rows.map(({ row, relation, rhs }) => ({
|
|
28
|
+
coefficients: dense(row, this.count),
|
|
29
|
+
relation,
|
|
30
|
+
rhs
|
|
31
|
+
}));
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
/** This function gives the parts of a case for the draws of `needs`. */
|
|
35
|
+
function caseParts(layer, stoppedParts, stock, needs) {
|
|
36
|
+
const direct = (layer.direct ?? []).filter((use) => needs.has(use.need) && use.amount > 0);
|
|
37
|
+
const live = (layer.converters ?? []).filter((converter) => canRun(converter, stoppedParts));
|
|
38
|
+
const cooks = live.filter((converter) => needs.has(giftNeed(converter) ?? ""));
|
|
39
|
+
const makers = live.filter((converter) => giftResource(converter) !== void 0);
|
|
40
|
+
const resources = /* @__PURE__ */ new Set([...direct.map((use) => use.resource), ...[...cooks, ...makers].flatMap((converter) => [...inputsOf(converter).keys()])]);
|
|
41
|
+
for (const maker of makers) resources.add(giftResource(maker) ?? "");
|
|
42
|
+
return {
|
|
43
|
+
stock,
|
|
44
|
+
direct,
|
|
45
|
+
cooks,
|
|
46
|
+
makers,
|
|
47
|
+
resources,
|
|
48
|
+
stocked: [...resources].filter((resource) => (stock.get(resource) ?? 0) > 0).sort()
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* This function adds the columns of one draw to a program, and the balance row of each of its resources.
|
|
53
|
+
* In a balance row, the takes of the draw are not more than its share of the stock plus the gifts of its makers.
|
|
54
|
+
* The caller adds the row of the need, with the term of the days.
|
|
55
|
+
*
|
|
56
|
+
* @param stocked - False for a draw that takes no stock. Its shares are not columns.
|
|
57
|
+
*/
|
|
58
|
+
function drawBlock(program, parts, draw, stocked = true) {
|
|
59
|
+
const gifts = /* @__PURE__ */ new Map();
|
|
60
|
+
const balance = new Map([...parts.resources].map((resource) => [resource, /* @__PURE__ */ new Map()]));
|
|
61
|
+
const consume = (resource, index, amount) => addTo(balance.get(resource), index, amount);
|
|
62
|
+
for (const use of parts.direct) {
|
|
63
|
+
if (use.need !== draw.need) continue;
|
|
64
|
+
const index = program.next();
|
|
65
|
+
addTo(gifts, index, exact(use.amount));
|
|
66
|
+
consume(use.resource, index, ONE);
|
|
67
|
+
}
|
|
68
|
+
const runs = /* @__PURE__ */ new Map();
|
|
69
|
+
for (const cook of parts.cooks) {
|
|
70
|
+
if (giftNeed(cook) !== draw.need) continue;
|
|
71
|
+
const index = program.next();
|
|
72
|
+
runs.set(cook, index);
|
|
73
|
+
addTo(gifts, index, exact(cook.gives.amount));
|
|
74
|
+
for (const [resource, each] of inputsOf(cook)) consume(resource, index, exact(each));
|
|
75
|
+
}
|
|
76
|
+
for (const maker of parts.makers) {
|
|
77
|
+
const index = program.next();
|
|
78
|
+
runs.set(maker, index);
|
|
79
|
+
for (const [resource, each] of inputsOf(maker)) consume(resource, index, exact(each));
|
|
80
|
+
consume(giftResource(maker), index, neg(exact(maker.gives.amount)));
|
|
81
|
+
}
|
|
82
|
+
const shares = new Map(stocked ? parts.stocked.map((resource) => [resource, program.next()]) : []);
|
|
83
|
+
for (const [resource, index] of shares) consume(resource, index, neg(ONE));
|
|
84
|
+
for (const row of balance.values()) if (row.size > 0) program.push(row, "<=", ZERO);
|
|
85
|
+
return {
|
|
86
|
+
draw,
|
|
87
|
+
gifts,
|
|
88
|
+
shares,
|
|
89
|
+
runs
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* This function gives the device-days of each device of a set of run columns, by the key of the device (`deviceKey`).
|
|
94
|
+
* One run uses `1 / perDay` of a day of one device. The converters of one device share one limit. A converter with no device has a limit of its own.
|
|
95
|
+
* A converter with no limit `perDay` is not in the record. The list `stopped` has the columns of the converters with a limit of 0.
|
|
96
|
+
*/
|
|
97
|
+
function deviceUse(runs) {
|
|
98
|
+
const limits = /* @__PURE__ */ new Map();
|
|
99
|
+
const stopped = [];
|
|
100
|
+
for (const [converter, index] of runs) {
|
|
101
|
+
if (converter.perDay === void 0) continue;
|
|
102
|
+
if (!(converter.perDay > 0)) {
|
|
103
|
+
stopped.push(index);
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
const key = deviceKey(converter);
|
|
107
|
+
const limit = limits.get(key) ?? {
|
|
108
|
+
row: /* @__PURE__ */ new Map(),
|
|
109
|
+
devices: converter.devices ?? 1,
|
|
110
|
+
converters: []
|
|
111
|
+
};
|
|
112
|
+
limits.set(key, limit);
|
|
113
|
+
if (!limit.converters.includes(converter)) limit.converters.push(converter);
|
|
114
|
+
addTo(limit.row, index, div(ONE, exact(converter.perDay)));
|
|
115
|
+
}
|
|
116
|
+
return {
|
|
117
|
+
limits,
|
|
118
|
+
stopped
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* This function gives the row of the fewest device-days of a set of run columns: the runs over `perDay`, or the runs with no limit.
|
|
123
|
+
* As an objective, it gives no more runs than the plan uses.
|
|
124
|
+
*/
|
|
125
|
+
function fewestRow(runs) {
|
|
126
|
+
const out = /* @__PURE__ */ new Map();
|
|
127
|
+
for (const [converter, index] of runs) addTo(out, index, converter.perDay !== void 0 && converter.perDay > 0 ? div(ONE, exact(converter.perDay)) : ONE);
|
|
128
|
+
return out;
|
|
129
|
+
}
|
|
130
|
+
/** This function gives the value of a sparse row at the point `x`. */
|
|
131
|
+
function valueAt(row, x) {
|
|
132
|
+
let out = ZERO;
|
|
133
|
+
for (const [index, value] of row) out = add(out, mul(value, x[index] ?? ZERO));
|
|
134
|
+
return out;
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* This function gives each resource that a draw can use: the resources of its direct uses and the inputs of its cooks.
|
|
138
|
+
* It also gives the inputs of their makers, through each chain.
|
|
139
|
+
*/
|
|
140
|
+
function inputClosure(direct, cooks, makers) {
|
|
141
|
+
const out = /* @__PURE__ */ new Set();
|
|
142
|
+
const queue = [...direct, ...cooks.flatMap((cook) => [...inputsOf(cook).keys()])];
|
|
143
|
+
for (let resource = queue.shift(); resource !== void 0; resource = queue.shift()) {
|
|
144
|
+
if (out.has(resource)) continue;
|
|
145
|
+
out.add(resource);
|
|
146
|
+
for (const maker of makers) if (giftResource(maker) === resource) queue.push(...inputsOf(maker).keys());
|
|
147
|
+
}
|
|
148
|
+
return out;
|
|
149
|
+
}
|
|
150
|
+
/** This function gives the resources that the draws of `needs` can use, and the converters that they can use. */
|
|
151
|
+
function reachOf(parts, needs) {
|
|
152
|
+
const cooks = parts.cooks.filter((cook) => needs.has(giftNeed(cook) ?? ""));
|
|
153
|
+
const closure = inputClosure(parts.direct.filter((use) => needs.has(use.need)).map((use) => use.resource), cooks, parts.makers);
|
|
154
|
+
return {
|
|
155
|
+
closure,
|
|
156
|
+
reach: /* @__PURE__ */ new Set([...cooks, ...parts.makers.filter((maker) => closure.has(giftResource(maker) ?? ""))])
|
|
157
|
+
};
|
|
158
|
+
}
|
|
7
159
|
// src/joint.ts
|
|
8
160
|
/**
|
|
9
161
|
* 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.
|
|
@@ -57,146 +209,70 @@ function jointDays(layer, caseCuts, options, needs) {
|
|
|
57
209
|
capped: []
|
|
58
210
|
};
|
|
59
211
|
if (plan.length === 0) return endless;
|
|
60
|
-
const
|
|
61
|
-
const
|
|
62
|
-
const
|
|
63
|
-
const
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
const days = next();
|
|
70
|
-
const useCol = direct.map(next);
|
|
71
|
-
const cookCol = cooks.map(next);
|
|
72
|
-
const makerCol = plan.map(() => makers.map(next));
|
|
73
|
-
const shareCol = plan.map(() => new Map(stocked.map((resource) => [resource, next()])));
|
|
74
|
-
const rows = [];
|
|
75
|
-
plan.forEach((draw, i) => {
|
|
76
|
-
const need = /* @__PURE__ */ new Map([[days, neg(exact(drawDemand(draw, caseCuts)))]]);
|
|
77
|
-
direct.forEach((use, k) => {
|
|
78
|
-
if (use.need === draw.need) addTo(need, useCol[k], exact(use.amount));
|
|
79
|
-
});
|
|
80
|
-
cooks.forEach((cook, c) => {
|
|
81
|
-
if (giftNeed(cook) === draw.need) addTo(need, cookCol[c], exact(cook.gives.amount));
|
|
82
|
-
});
|
|
83
|
-
rows.push({
|
|
84
|
-
row: need,
|
|
85
|
-
relation: ">=",
|
|
86
|
-
rhs: ZERO
|
|
87
|
-
});
|
|
88
|
-
const balance = new Map([...resources].map((resource) => [resource, /* @__PURE__ */ new Map()]));
|
|
89
|
-
const consume = (resource, index, amount) => addTo(balance.get(resource), index, amount);
|
|
90
|
-
direct.forEach((use, k) => {
|
|
91
|
-
if (use.need === draw.need) consume(use.resource, useCol[k], ONE);
|
|
92
|
-
});
|
|
93
|
-
cooks.forEach((cook, c) => {
|
|
94
|
-
if (giftNeed(cook) !== draw.need) return;
|
|
95
|
-
for (const [resource, each] of inputsOf(cook)) consume(resource, cookCol[c], exact(each));
|
|
96
|
-
});
|
|
97
|
-
makers.forEach((maker, m) => {
|
|
98
|
-
const index = makerCol[i]?.[m];
|
|
99
|
-
for (const [resource, each] of inputsOf(maker)) consume(resource, index, exact(each));
|
|
100
|
-
consume(giftResource(maker), index, neg(exact(maker.gives.amount)));
|
|
101
|
-
});
|
|
102
|
-
for (const [resource, index] of shareCol[i] ?? []) consume(resource, index, neg(ONE));
|
|
103
|
-
for (const row of balance.values()) if (row.size > 0) rows.push({
|
|
104
|
-
row,
|
|
105
|
-
relation: "<=",
|
|
106
|
-
rhs: ZERO
|
|
107
|
-
});
|
|
212
|
+
const parts = caseParts(layer, stoppedParts, stock, planned);
|
|
213
|
+
const program = new Program();
|
|
214
|
+
const days = program.next();
|
|
215
|
+
const blocks = plan.map((draw) => {
|
|
216
|
+
const block = drawBlock(program, parts, draw);
|
|
217
|
+
const need = new Map(block.gifts);
|
|
218
|
+
addTo(need, days, neg(exact(drawDemand(draw, caseCuts))));
|
|
219
|
+
program.push(need, ">=", ZERO);
|
|
220
|
+
return block;
|
|
108
221
|
});
|
|
109
|
-
const runCols =
|
|
110
|
-
const limits
|
|
111
|
-
for (const [
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
relation: "<=",
|
|
117
|
-
rhs: ZERO
|
|
118
|
-
});
|
|
119
|
-
continue;
|
|
120
|
-
}
|
|
121
|
-
const key = deviceKey(converter);
|
|
122
|
-
const limit = limits.get(key) ?? {
|
|
123
|
-
row: /* @__PURE__ */ new Map([[days, neg(exact(converter.devices ?? 1))]]),
|
|
124
|
-
converters: []
|
|
125
|
-
};
|
|
126
|
-
limits.set(key, limit);
|
|
127
|
-
limit.converters.push(converter);
|
|
128
|
-
for (const index of indexes) addTo(limit.row, index, div(ONE, exact(converter.perDay)));
|
|
222
|
+
const runCols = blocks.flatMap((block) => [...block.runs]);
|
|
223
|
+
const { limits, stopped } = deviceUse(runCols);
|
|
224
|
+
for (const index of stopped) program.push(/* @__PURE__ */ new Map([[index, ONE]]), "<=", ZERO);
|
|
225
|
+
for (const limit of limits.values()) {
|
|
226
|
+
const row = new Map(limit.row);
|
|
227
|
+
addTo(row, days, neg(exact(limit.devices)));
|
|
228
|
+
program.push(row, "<=", ZERO);
|
|
129
229
|
}
|
|
130
|
-
for (const
|
|
131
|
-
row,
|
|
132
|
-
relation: "<=",
|
|
133
|
-
rhs: ZERO
|
|
134
|
-
});
|
|
135
|
-
for (const resource of stocked) {
|
|
230
|
+
for (const resource of parts.stocked) {
|
|
136
231
|
const row = /* @__PURE__ */ new Map();
|
|
137
|
-
for (const
|
|
138
|
-
|
|
139
|
-
row,
|
|
140
|
-
relation: "<=",
|
|
141
|
-
rhs: exact(stock.get(resource) ?? 0)
|
|
142
|
-
});
|
|
232
|
+
for (const block of blocks) addTo(row, block.shares.get(resource), ONE);
|
|
233
|
+
program.push(row, "<=", exact(stock.get(resource) ?? 0));
|
|
143
234
|
}
|
|
144
|
-
const constraints = rows.map(({ row, relation, rhs }) => ({
|
|
145
|
-
coefficients: dense(row, count),
|
|
146
|
-
relation,
|
|
147
|
-
rhs
|
|
148
|
-
}));
|
|
149
235
|
const most = /* @__PURE__ */ new Map([[days, ONE]]);
|
|
150
236
|
const least = /* @__PURE__ */ new Map();
|
|
151
|
-
for (const
|
|
152
|
-
const fewest = /* @__PURE__ */ new Map();
|
|
153
|
-
for (const [converter, indexes] of runCols) {
|
|
154
|
-
const weight = converter.perDay !== void 0 && converter.perDay > 0 ? div(ONE, exact(converter.perDay)) : ONE;
|
|
155
|
-
for (const index of indexes) addTo(fewest, index, weight);
|
|
156
|
-
}
|
|
237
|
+
for (const block of blocks) for (const [resource, index] of block.shares) addTo(least, index, div(ONE, exact(stock.get(resource) ?? 1)));
|
|
157
238
|
const objectives = [
|
|
158
239
|
{
|
|
159
240
|
sense: "max",
|
|
160
|
-
coefficients: dense(most, count)
|
|
241
|
+
coefficients: dense(most, program.count)
|
|
161
242
|
},
|
|
162
243
|
{
|
|
163
244
|
sense: "min",
|
|
164
|
-
coefficients: dense(least, count)
|
|
245
|
+
coefficients: dense(least, program.count)
|
|
165
246
|
},
|
|
166
247
|
{
|
|
167
248
|
sense: "min",
|
|
168
|
-
coefficients: dense(
|
|
249
|
+
coefficients: dense(fewestRow(runCols), program.count)
|
|
169
250
|
}
|
|
170
251
|
];
|
|
171
|
-
const solved = solveLexicographic(constraints, objectives);
|
|
252
|
+
const solved = solveLexicographic(program.constraints(), objectives);
|
|
172
253
|
if (solved.status !== "optimal") return endless;
|
|
173
254
|
const x = solved.x;
|
|
174
|
-
const at = (index) => x[index] ?? ZERO;
|
|
175
255
|
const takes = {};
|
|
176
|
-
|
|
256
|
+
for (const block of blocks) {
|
|
177
257
|
const record = {};
|
|
178
|
-
for (const [resource, index] of
|
|
179
|
-
takes[draw.need] = record;
|
|
180
|
-
}
|
|
258
|
+
for (const [resource, index] of block.shares) if (sign(x[index] ?? ZERO) > 0) record[resource] = toNumber(x[index] ?? ZERO);
|
|
259
|
+
takes[block.draw.need] = record;
|
|
260
|
+
}
|
|
261
|
+
const total = /* @__PURE__ */ new Map();
|
|
262
|
+
for (const [converter, index] of runCols) total.set(converter, add(total.get(converter) ?? ZERO, x[index] ?? ZERO));
|
|
181
263
|
const runs = {};
|
|
182
|
-
const
|
|
183
|
-
if (sign(value) > 0) runs[converter.id] = toNumber(value);
|
|
184
|
-
};
|
|
185
|
-
cooks.forEach((cook, c) => ran(cook, at(cookCol[c])));
|
|
186
|
-
makers.forEach((maker, m) => ran(maker, makerCol.reduce((sum, row) => add(sum, at(row[m])), ZERO)));
|
|
264
|
+
for (const [converter, value] of total) if (sign(value) > 0) runs[converter.id] = toNumber(value);
|
|
187
265
|
const withStore = new Set(layer.stores.map((store) => store.resource));
|
|
188
|
-
const closure =
|
|
189
|
-
const reach = /* @__PURE__ */ new Set([...cooks, ...makers.filter((maker) => closure.has(giftResource(maker) ?? ""))]);
|
|
266
|
+
const { closure, reach } = reachOf(parts, planned);
|
|
190
267
|
const binding = [...closure].filter((resource) => withStore.has(resource)).filter((resource) => {
|
|
191
|
-
const taken =
|
|
192
|
-
const index = shares.get(resource);
|
|
193
|
-
return index === void 0 ? sum : add(sum,
|
|
268
|
+
const taken = blocks.reduce((sum, block) => {
|
|
269
|
+
const index = block.shares.get(resource);
|
|
270
|
+
return index === void 0 ? sum : add(sum, x[index] ?? ZERO);
|
|
194
271
|
}, ZERO);
|
|
195
272
|
return equals(taken, exact(stock.get(resource) ?? 0));
|
|
196
273
|
}).sort();
|
|
197
274
|
const best = solved.values[0] ?? ZERO;
|
|
198
|
-
const
|
|
199
|
-
const capped = sign(best) > 0 ? [...[...runCols.keys()].filter((converter) => converter.perDay !== void 0 && !(converter.perDay > 0)), ...[...limits.values()].filter(({ row }) => sign(used(row)) === 0).flatMap(({ converters }) => converters)].filter((converter) => reach.has(converter)).map((converter) => converter.id).sort() : [];
|
|
275
|
+
const capped = sign(best) > 0 ? [...[...total.keys()].filter((converter) => converter.perDay !== void 0 && !(converter.perDay > 0)), ...[...limits.values()].filter((limit) => equals(valueAt(limit.row, x), mul(exact(limit.devices), best))).flatMap((limit) => limit.converters)].filter((converter) => reach.has(converter)).map((converter) => converter.id).sort() : [];
|
|
200
276
|
return {
|
|
201
277
|
...base,
|
|
202
278
|
days: toNumber(best),
|
|
@@ -206,20 +282,255 @@ function jointDays(layer, caseCuts, options, needs) {
|
|
|
206
282
|
capped
|
|
207
283
|
};
|
|
208
284
|
}
|
|
285
|
+
// src/best.ts
|
|
209
286
|
/**
|
|
210
|
-
* This function gives
|
|
211
|
-
*
|
|
287
|
+
* This function gives the days that each draw holds when a case stops its supply. The stores and the devices have their best share.
|
|
288
|
+
* The result has the form of `enduranceOf`, so `caseShortfall` takes it.
|
|
289
|
+
*
|
|
290
|
+
* The share is lexicographic. The draws of the first level get their best days, then the draws of the next level get theirs, and so on.
|
|
291
|
+
* In one level, the share is the best for the draw with the fewest days, then for the next draw, and so on (the leximin share).
|
|
292
|
+
* Thus a draw of a level cannot take a store that another draw of the level needs more.
|
|
293
|
+
*
|
|
294
|
+
* - The function solves a sequence of linear programs over the totals of the spans. Each program has the days of the open draws
|
|
295
|
+
* and their common floor. For each draw, it has the take of each direct use, the runs of each converter and the share of each stock.
|
|
296
|
+
* - Each step takes the largest floor. A draw whose floor row has a dual value that is not 0 cannot get more days. The step fixes its days.
|
|
297
|
+
* The dual values of the floor rows add to 1, so each step fixes one draw or more.
|
|
298
|
+
* - A fixed draw keeps its days in each later step. Its share of the stocks can change, so a later draw can get a store that it does not need.
|
|
299
|
+
* - The stores, the direct uses, the converters and the devices follow the rules of `jointDays`. A store counts with all of its amount when its due date is after `at`.
|
|
300
|
+
* - A fixed draw keeps the device-days of each day that it uses at its step, for all the days of the later draws. This is the safe side, as in `enduranceOf`.
|
|
301
|
+
* The exact share of a device between two spans is not a linear program: the device-days of a day are the runs over the span.
|
|
302
|
+
* - A step with no largest floor gives the open draws no end. Each of them takes no stock, and keeps the fewest device-days of each day.
|
|
303
|
+
* - At the end, a program takes the smallest sum of the shares of the stocks, each over its stock, then the fewest device-days.
|
|
304
|
+
* These are the takes of the result. A resource in `binding` has no stock left at this point.
|
|
305
|
+
* - A draw in `capped` used a device with no device-days left at the step that fixed it.
|
|
306
|
+
*
|
|
307
|
+
* The programs use exact rationals, so the result has no error of the method. Only the change back to a number rounds.
|
|
308
|
+
* The fewest days of the first level are the joint days (`jointDays`) of the draws of that level.
|
|
309
|
+
*
|
|
310
|
+
* @param layer - The endurance layer
|
|
311
|
+
* @param caseCuts - The case
|
|
312
|
+
* @param options - The date, and the stack or the parts that are also down
|
|
313
|
+
* @returns The endurance of each draw whose supply stops
|
|
314
|
+
* @throws {RangeError} A date is not `YYYY-MM-DD`.
|
|
212
315
|
*/
|
|
213
|
-
function
|
|
214
|
-
const
|
|
215
|
-
const
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
316
|
+
function bestEndurance(layer, caseCuts, options) {
|
|
317
|
+
const stoppedParts = caseStopped(caseCuts, options);
|
|
318
|
+
const stock = storeAmounts(layer, options.at, stoppedParts);
|
|
319
|
+
const draws = caseDraws(layer, caseCuts, stoppedParts);
|
|
320
|
+
const parts = caseParts(layer, stoppedParts, stock, new Set(draws.map((draw) => draw.need)));
|
|
321
|
+
const devices = new Map([...deviceUse([...parts.cooks, ...parts.makers].map((converter) => [converter, 0])).limits].map(([key, limit]) => [key, limit.devices]));
|
|
322
|
+
const fixed = /* @__PURE__ */ new Map();
|
|
323
|
+
for (const level of levelGroups(layer, draws)) {
|
|
324
|
+
let open = level;
|
|
325
|
+
while (open.length > 0) {
|
|
326
|
+
const step = buildStep(parts, caseCuts, draws, fixed, open, devices, "span");
|
|
327
|
+
const solved = solveLexicographic(step.program.constraints(), [{
|
|
328
|
+
sense: "max",
|
|
329
|
+
coefficients: dense(/* @__PURE__ */ new Map([[step.floor, ONE]]), step.program.count)
|
|
330
|
+
}, {
|
|
331
|
+
sense: "min",
|
|
332
|
+
coefficients: dense(fewestRow(step.openRuns), step.program.count)
|
|
333
|
+
}]);
|
|
334
|
+
if (solved.status !== "optimal") {
|
|
335
|
+
if (solved.status === "infeasible") throw new Error("The step of the best endurance has no point. The point of the last step is a point of it.");
|
|
336
|
+
fixEndless(parts, caseCuts, draws, fixed, open, devices);
|
|
337
|
+
break;
|
|
338
|
+
}
|
|
339
|
+
const floor = solved.values[0] ?? ZERO;
|
|
340
|
+
const first = solved.stages[0]?.result;
|
|
341
|
+
const dual = first?.status === "optimal" ? first.dual : [];
|
|
342
|
+
let done = open.filter((draw) => sign(dual[step.floors.get(draw.need)] ?? ZERO) !== 0);
|
|
343
|
+
if (done.length === 0) done = open;
|
|
344
|
+
const full = new Set([...step.shared].filter(([, limit]) => equals(valueAt(limit.row, solved.x), mul(limit.room, floor))).map(([key]) => key));
|
|
345
|
+
for (const draw of done) {
|
|
346
|
+
const block = step.blocks.find((item) => item.draw.need === draw.need);
|
|
347
|
+
const keep = /* @__PURE__ */ new Map();
|
|
348
|
+
for (const [key, limit] of deviceUse(block.runs).limits) keep.set(key, sign(floor) > 0 ? div(valueAt(limit.row, solved.x), floor) : ZERO);
|
|
349
|
+
const { reach } = reachOf(parts, /* @__PURE__ */ new Set([draw.need]));
|
|
350
|
+
const capped = sign(floor) > 0 ? [...reach].filter((converter) => converter.perDay !== void 0 && (!(converter.perDay > 0) || [...full].some((key) => step.shared.get(key)?.converters.includes(converter)))).map((converter) => converter.id).sort() : [];
|
|
351
|
+
fixed.set(draw.need, {
|
|
352
|
+
span: floor,
|
|
353
|
+
endless: false,
|
|
354
|
+
keep,
|
|
355
|
+
capped
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
const fixedNow = new Set(done.map((draw) => draw.need));
|
|
359
|
+
open = open.filter((draw) => !fixedNow.has(draw.need));
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
const needs = {};
|
|
363
|
+
if (draws.length === 0) return {
|
|
364
|
+
case: caseCuts.case,
|
|
365
|
+
at: options.at,
|
|
366
|
+
needs
|
|
367
|
+
};
|
|
368
|
+
const last = buildStep(parts, caseCuts, draws, fixed, [], devices, "span");
|
|
369
|
+
const least = /* @__PURE__ */ new Map();
|
|
370
|
+
for (const block of last.blocks) for (const [resource, index] of block.shares) addTo(least, index, div(ONE, exact(stock.get(resource) ?? 1)));
|
|
371
|
+
const objectives = [{
|
|
372
|
+
sense: "min",
|
|
373
|
+
coefficients: dense(least, last.program.count)
|
|
374
|
+
}, {
|
|
375
|
+
sense: "min",
|
|
376
|
+
coefficients: dense(fewestRow(last.blocks.flatMap((block) => [...block.runs])), last.program.count)
|
|
377
|
+
}];
|
|
378
|
+
const solved = solveLexicographic(last.program.constraints(), objectives);
|
|
379
|
+
if (solved.status !== "optimal") throw new Error("The last program of the best endurance has no optimum. The point of the last step is a point of it.");
|
|
380
|
+
const withStore = new Set(layer.stores.map((store) => store.resource));
|
|
381
|
+
for (const block of last.blocks) {
|
|
382
|
+
const need = block.draw.need;
|
|
383
|
+
const fix = fixed.get(need);
|
|
384
|
+
if (fix.endless) {
|
|
385
|
+
needs[need] = {
|
|
386
|
+
days: 1e400,
|
|
387
|
+
binding: [],
|
|
388
|
+
takes: {}
|
|
389
|
+
};
|
|
390
|
+
continue;
|
|
391
|
+
}
|
|
392
|
+
const takes = {};
|
|
393
|
+
for (const [resource, index] of block.shares) if (sign(solved.x[index] ?? ZERO) > 0) takes[resource] = toNumber(solved.x[index] ?? ZERO);
|
|
394
|
+
const { closure } = reachOf(parts, /* @__PURE__ */ new Set([need]));
|
|
395
|
+
const binding = [...closure].filter((resource) => withStore.has(resource)).filter((resource) => {
|
|
396
|
+
const taken = last.blocks.reduce((sum, item) => {
|
|
397
|
+
const index = item.shares.get(resource);
|
|
398
|
+
return index === void 0 ? sum : add(sum, solved.x[index] ?? ZERO);
|
|
399
|
+
}, ZERO);
|
|
400
|
+
return equals(taken, exact(stock.get(resource) ?? 0));
|
|
401
|
+
}).sort();
|
|
402
|
+
const days = toNumber(fix.span);
|
|
403
|
+
needs[need] = fix.capped.length === 0 ? {
|
|
404
|
+
days,
|
|
405
|
+
binding,
|
|
406
|
+
takes
|
|
407
|
+
} : {
|
|
408
|
+
days,
|
|
409
|
+
binding,
|
|
410
|
+
takes,
|
|
411
|
+
capped: fix.capped
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
return {
|
|
415
|
+
case: caseCuts.case,
|
|
416
|
+
at: options.at,
|
|
417
|
+
needs
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
/** This function gives the draws of each level, in the order of `levels`. The draws of a level that is not in `levels` come last, together. */
|
|
421
|
+
function levelGroups(layer, draws) {
|
|
422
|
+
const rank = (draw) => {
|
|
423
|
+
const index = layer.levels.indexOf(draw.level);
|
|
424
|
+
return index < 0 ? layer.levels.length : index;
|
|
425
|
+
};
|
|
426
|
+
const out = [];
|
|
427
|
+
let previous = -1;
|
|
428
|
+
for (const draw of draws) {
|
|
429
|
+
if (rank(draw) !== previous) out.push([]);
|
|
430
|
+
previous = rank(draw);
|
|
431
|
+
out[out.length - 1]?.push(draw);
|
|
220
432
|
}
|
|
221
433
|
return out;
|
|
222
434
|
}
|
|
435
|
+
/**
|
|
436
|
+
* This function gives the program of one step. The fixed draws keep their spans and their device-days. The open draws have a common floor.
|
|
437
|
+
*
|
|
438
|
+
* - With `"span"`, each open draw has a column of its days, not less than the floor. Its runs share the device-days that the fixed draws leave, for the floor.
|
|
439
|
+
* The device-days of each day are the runs over the span. A span not less than the floor uses fewer of them, so this is the safe side.
|
|
440
|
+
* - With `"day"`, each open draw has a span of one day and takes no stock. Its runs share the device-days of one day.
|
|
441
|
+
*/
|
|
442
|
+
function buildStep(parts, caseCuts, draws, fixed, open, devices, mode) {
|
|
443
|
+
const program = new Program();
|
|
444
|
+
const floor = program.next();
|
|
445
|
+
const opened = new Set(open.map((draw) => draw.need));
|
|
446
|
+
const blocks = [];
|
|
447
|
+
const floors = /* @__PURE__ */ new Map();
|
|
448
|
+
const openRuns = [];
|
|
449
|
+
const kept = /* @__PURE__ */ new Map();
|
|
450
|
+
for (const draw of draws) {
|
|
451
|
+
const fix = fixed.get(draw.need);
|
|
452
|
+
if (fix === void 0 && !opened.has(draw.need)) continue;
|
|
453
|
+
const block = drawBlock(program, parts, draw, !(fix?.endless ?? mode === "day"));
|
|
454
|
+
blocks.push(block);
|
|
455
|
+
const demand = exact(drawDemand(draw, caseCuts));
|
|
456
|
+
const need = new Map(block.gifts);
|
|
457
|
+
if (fix !== void 0) {
|
|
458
|
+
program.push(need, ">=", mul(demand, fix.span));
|
|
459
|
+
const { limits, stopped } = deviceUse(block.runs);
|
|
460
|
+
for (const index of stopped) program.push(/* @__PURE__ */ new Map([[index, ONE]]), "<=", ZERO);
|
|
461
|
+
for (const [key, limit] of limits) program.push(limit.row, "<=", mul(fix.keep.get(key) ?? ZERO, fix.span));
|
|
462
|
+
for (const [key, value] of fix.keep) kept.set(key, add(kept.get(key) ?? ZERO, value));
|
|
463
|
+
continue;
|
|
464
|
+
}
|
|
465
|
+
openRuns.push(...block.runs);
|
|
466
|
+
if (mode === "day") {
|
|
467
|
+
program.push(need, ">=", demand);
|
|
468
|
+
continue;
|
|
469
|
+
}
|
|
470
|
+
const days = program.next();
|
|
471
|
+
addTo(need, days, neg(demand));
|
|
472
|
+
program.push(need, ">=", ZERO);
|
|
473
|
+
floors.set(draw.need, program.push(/* @__PURE__ */ new Map([[days, ONE], [floor, neg(ONE)]]), ">=", ZERO));
|
|
474
|
+
}
|
|
475
|
+
const shared = /* @__PURE__ */ new Map();
|
|
476
|
+
const { limits, stopped } = deviceUse(openRuns);
|
|
477
|
+
for (const index of stopped) program.push(/* @__PURE__ */ new Map([[index, ONE]]), "<=", ZERO);
|
|
478
|
+
for (const [key, limit] of limits) {
|
|
479
|
+
const left = sub(exact(devices.get(key) ?? limit.devices), kept.get(key) ?? ZERO);
|
|
480
|
+
const room = sign(left) > 0 ? left : ZERO;
|
|
481
|
+
shared.set(key, {
|
|
482
|
+
row: limit.row,
|
|
483
|
+
room,
|
|
484
|
+
converters: limit.converters
|
|
485
|
+
});
|
|
486
|
+
if (mode === "day") {
|
|
487
|
+
program.push(limit.row, "<=", room);
|
|
488
|
+
continue;
|
|
489
|
+
}
|
|
490
|
+
const row = new Map(limit.row);
|
|
491
|
+
addTo(row, floor, neg(room));
|
|
492
|
+
program.push(row, "<=", ZERO);
|
|
493
|
+
}
|
|
494
|
+
for (const resource of parts.stocked) {
|
|
495
|
+
const row = /* @__PURE__ */ new Map();
|
|
496
|
+
for (const block of blocks) {
|
|
497
|
+
const index = block.shares.get(resource);
|
|
498
|
+
if (index !== void 0) addTo(row, index, ONE);
|
|
499
|
+
}
|
|
500
|
+
if (row.size > 0) program.push(row, "<=", exact(parts.stock.get(resource) ?? 0));
|
|
501
|
+
}
|
|
502
|
+
return {
|
|
503
|
+
program,
|
|
504
|
+
blocks,
|
|
505
|
+
floor,
|
|
506
|
+
floors,
|
|
507
|
+
openRuns,
|
|
508
|
+
shared
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
/**
|
|
512
|
+
* This function fixes the open draws with no end. Each open draw takes no stock, and keeps the fewest device-days of each day.
|
|
513
|
+
* A step with no largest floor has a direction with no take of a stock, so this program has a point.
|
|
514
|
+
*/
|
|
515
|
+
function fixEndless(parts, caseCuts, draws, fixed, open, devices) {
|
|
516
|
+
const step = buildStep(parts, caseCuts, draws, fixed, open, devices, "day");
|
|
517
|
+
const solved = solveLexicographic(step.program.constraints(), [{
|
|
518
|
+
sense: "min",
|
|
519
|
+
coefficients: dense(fewestRow(step.openRuns), step.program.count)
|
|
520
|
+
}]);
|
|
521
|
+
if (solved.status !== "optimal") throw new Error("The draws with no end of the best endurance have no point of one day.");
|
|
522
|
+
for (const draw of open) {
|
|
523
|
+
const block = step.blocks.find((item) => item.draw.need === draw.need);
|
|
524
|
+
const keep = /* @__PURE__ */ new Map();
|
|
525
|
+
for (const [key, limit] of deviceUse(block.runs).limits) keep.set(key, valueAt(limit.row, solved.x));
|
|
526
|
+
fixed.set(draw.need, {
|
|
527
|
+
span: ONE,
|
|
528
|
+
endless: true,
|
|
529
|
+
keep,
|
|
530
|
+
capped: []
|
|
531
|
+
});
|
|
532
|
+
}
|
|
533
|
+
}
|
|
223
534
|
// src/stops.ts
|
|
224
535
|
/**
|
|
225
536
|
* 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).
|
|
@@ -1003,6 +1314,6 @@ const SAMPLE_ENDURANCE = {
|
|
|
1003
1314
|
asOf: "2025-12-01"
|
|
1004
1315
|
}]
|
|
1005
1316
|
};
|
|
1006
|
-
export { ENDURANCE_CODES, ENDURANCE_SCHEMA, INDEPENDENT_MAX_WORK, INDEPENDENT_TOLERANCE, MINIMAL_STOP_CUTS, SAMPLE_ENDURANCE, SAMPLE_ENDURANCE_STACK, caseDraws, caseShortfall, caseStopped, checkEndurance, curveFault, drawDemand, enduranceOf, eventStop, giftNeed, giftResource, hasEnduranceError, independentStop, joinEndurance, jointDays, longestStop, minimalStops, stopCurves, storeAmounts, survivalAt, survivalQuantile, tailDays, upperStop, yearChance, yearRate, yearShortfall };
|
|
1317
|
+
export { ENDURANCE_CODES, ENDURANCE_SCHEMA, INDEPENDENT_MAX_WORK, INDEPENDENT_TOLERANCE, MINIMAL_STOP_CUTS, SAMPLE_ENDURANCE, SAMPLE_ENDURANCE_STACK, bestEndurance, caseDraws, caseShortfall, caseStopped, checkEndurance, curveFault, drawDemand, enduranceOf, eventStop, giftNeed, giftResource, hasEnduranceError, independentStop, joinEndurance, jointDays, longestStop, minimalStops, stopCurves, storeAmounts, survivalAt, survivalQuantile, tailDays, upperStop, yearChance, yearRate, yearShortfall };
|
|
1007
1318
|
|
|
1008
1319
|
//# sourceMappingURL=index.js.map
|
package/build/index.js.map
CHANGED
|
@@ -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, survivalAt, weakestBound, type CutBound, type PathOptions } from \"@mark1russell7/system-stack\";\nimport { caseDraws, caseStopped, enduranceOf, type CaseOptions } from \"./endurance.ts\";\nimport type { CaseCuts, Draw, Endurance, EnduranceLayer, Prior, Survival } from \"./layer.ts\";\nimport { stackStops } from \"./stops.ts\";\n\n// The shortfall: the user-days in which a draw does not get its need, for one case and for one year.\n\n/** The read of a curve at a time is in the core since system-stack 0.1.13. This package gives it again, so its API does not change. */\nexport { survivalAt };\n\n/**\n * This function gives the expected days of a cut after a time, up to a horizon: `E[max(0, min(D, to) - from)]`.\n * It is the area under the curve from `from` to `to`. The curve is linear between its points, so the area is exact.\n * With no horizon, the area goes to the end of the curve.\n */\nexport function tailDays(curve: Survival, from: number, to: number = Infinity): number {\n let area = 0;\n for (let index = 1; index < curve.length; index += 1) {\n const [t0] = curve[index - 1] ?? [0, 1];\n const [t1] = curve[index] ?? [0, 0];\n const start = Math.max(t0, from);\n const end = Math.min(t1, to);\n if (start < end) area += ((survivalAt(curve, start) + survivalAt(curve, end)) / 2) * (end - start);\n }\n return area;\n}\n\n/**\n * The options of a shortfall: the stack or the parts that are also down, as for `enduranceOf`, and a horizon.\n * With a horizon of `h` days, the shortfall counts only the first `h` days of each cut. A draw that holds `h` days has no shortfall.\n * Thus a plan can aim at a target, for example 14 days and then 90 days.\n */\n/**\n * The options of `stopCurves`. With a stack, `maxSets` is the budget of the search of the needs (`stopSets` of the core).\n * When the search passes it, `minimalStops` gives the sets.\n */\nexport interface StopCurveOptions extends Pick<CaseOptions, \"stack\" | \"down\">, Pick<PathOptions, \"maxSets\"> {\n /** The budget of `independentStop` for the curve of each draw, a whole number from 1. The default is `INDEPENDENT_MAX_WORK`. */\n readonly maxWork?: number | undefined;\n}\n\nexport interface ShortfallOptions extends StopCurveOptions {\n /** The horizon in days, more than 0. The default is no horizon. */\n readonly horizon?: number | undefined;\n}\n\nfunction horizonOf(options: ShortfallOptions): number {\n const horizon = options.horizon ?? Infinity;\n if (!(horizon > 0)) throw new RangeError(`The horizon ${String(options.horizon)} is not a number of days more than 0.`);\n return horizon;\n}\n\nfunction budgetsOf(options: StopCurveOptions): { readonly maxSets: number; readonly maxWork: number } {\n const maxSets = options.maxSets ?? DEFAULT_MAX_SETS;\n if (!Number.isInteger(maxSets) || maxSets < 1) throw new RangeError(`The option maxSets is ${String(options.maxSets)}: it is not a whole number from 1.`);\n const maxWork = options.maxWork ?? INDEPENDENT_MAX_WORK;\n if (!Number.isInteger(maxWork) || maxWork < 1) throw new RangeError(`The option maxWork is ${String(options.maxWork)}: it is not a whole number from 1.`);\n return { maxSets, maxWork };\n}\n\n/**\n * This function gives the days at which the chance of the curve falls to `chance`. With `0.1`, it is the 90th percentile of the duration.\n * When the curve does not fall to `chance`, the result is `Infinity`.\n */\nexport function survivalQuantile(curve: Survival, chance: number): number {\n for (let index = 1; index < curve.length; index += 1) {\n const [t0, p0] = curve[index - 1] ?? [0, 1];\n const [t1, p1] = curve[index] ?? [0, 0];\n if (p0 <= chance) return t0;\n if (p1 <= chance) return t0 + ((p0 - chance) * (t1 - t0)) / (p0 - p1);\n }\n return Infinity;\n}\n\n/** This function gives the chance that a case reaches its place one or more times in one year: `1 - exp(-perYear * reach)`. */\nexport function yearChance(prior: Prior): number {\n return 1 - Math.exp(-prior.perYear * prior.reach);\n}\n\n/** This function gives the expected count of the events of a case at its place in one year: `perYear * reach`. */\nexport function yearRate(prior: Prior): number {\n return prior.perYear * prior.reach;\n}\n\n/** This function gives the times at which a curve of the result can bend: each point of each curve, and each crossing of two curves. */\nfunction bendTimes(curves: readonly Survival[]): number[] {\n const times = [...new Set(curves.flatMap((curve) => curve.map(([days]) => days)))].sort((x, y) => x - y);\n const out = new Set(times);\n for (let index = 1; index < times.length; index += 1) {\n const t0 = times[index - 1] ?? 0;\n const t1 = times[index] ?? 0;\n for (const [i, a] of curves.entries()) {\n for (const b of curves.slice(i + 1)) {\n const d0 = survivalAt(a, t0) - survivalAt(b, t0);\n const d1 = survivalAt(a, t1) - survivalAt(b, t1);\n if (d0 * d1 < 0) out.add(t0 + ((t1 - t0) * d0) / (d0 - d1));\n }\n }\n }\n return [...out].sort((x, y) => x - y);\n}\n\n/**\n * This function makes a survival curve from a chance at each time. It stops at the first chance of 0, and it removes an increase of rounding.\n *\n * @throws RangeError when the chance at the last time is more than 0, as for curves that do not end at a chance of 0\n */\nfunction curveFrom(times: readonly number[], chanceAt: (days: number) => number): Survival {\n const out: [number, number][] = [];\n for (const days of times) {\n const chance = Math.min(out[out.length - 1]?.[1] ?? 1, chanceAt(days));\n out.push([days, chance]);\n if (chance === 0) return out;\n }\n throw new RangeError(\"The curves do not fall to a chance of 0 at their last point.\");\n}\n\n/**\n * This function gives the curve of a stop of some cuts when one event makes each cut longer together.\n * At each time, the chance is the largest `s` at which the cuts with a chance of `s` or more stop the supply.\n *\n * - When any one cut stops the supply, the result is the largest chance of the curves (`longestStop`).\n * - When the supply needs `any` of two parts, the stop ends with the shorter of the two cuts.\n * - Between two times of `bendTimes` the order of the curves does not change. So the result is linear between its points.\n * - When no set of cuts stops the supply, the result is `[[0, 0]]`. This curve does not start at `[0, 1]`, so `checkEndurance` refuses it.\n *\n * The result is not a limit. When the cuts are independent, a stop of two cuts in series can be longer. A stop through a need of `any` can be shorter.\n *\n * @param curves - The curves of the cuts, each one good for `checkEndurance`\n * @param stops - This function tells if the cuts of a list of indexes stop the supply. A larger list stops it when a smaller list does.\n * @throws RangeError when a curve does not end at a chance of 0\n */\nexport function eventStop(curves: readonly Survival[], stops: (cuts: readonly number[]) => boolean): Survival {\n return curveFrom(bendTimes(curves), (days) => {\n const chances = curves.map((curve) => survivalAt(curve, days));\n for (const level of [...new Set(chances)].sort((x, y) => y - x)) {\n if (stops(chances.flatMap((chance, index) => (chance >= level ? [index] : [])))) return level;\n }\n return 0;\n });\n}\n\n/**\n * This function gives the curve of the longest of some stops: at each time, the largest chance of the curves.\n * It is `eventStop` when any one cut stops the supply.\n *\n * @param curves - The curves, each one good for `checkEndurance`\n * @throws RangeError when there is no curve, or when a curve does not end at a chance of 0\n */\nexport function longestStop(curves: readonly Survival[]): Survival {\n const first = curves[0];\n if (first === undefined) throw new RangeError(\"longestStop needs one or more curves.\");\n return curves.length === 1 ? first : eventStop(curves, (cuts) => cuts.length > 0);\n}\n\n/**\n * The largest count of cuts for which `minimalStops` examines each set, and for which `independentStop` adds the chance of each state.\n * With a stack, `stopCurves` finds the minimal sets from the needs, so a larger count of cuts can have exact sets.\n */\nexport const MINIMAL_STOP_CUTS = 12;\n\n/**\n * This function gives the minimal sets of cuts that stop the supply: each set stops it, and no smaller part of a set stops it.\n * With more than `MINIMAL_STOP_CUTS` cuts, the result is `undefined`.\n */\nexport function minimalStops(count: number, stops: (cuts: readonly number[]) => boolean): number[][] | undefined {\n if (count > MINIMAL_STOP_CUTS) return undefined;\n const found: number[][] = [];\n const masks: number[] = [];\n const all = Array.from({ length: 1 << count }, (_, mask) => mask).sort((x, y) => popCount(x) - popCount(y) || x - y);\n for (const mask of all) {\n if (mask === 0 || masks.some((other) => (other & mask) === other)) continue;\n const cuts = Array.from({ length: count }, (_, index) => index).filter((index) => (mask >> index) & 1);\n if (!stops(cuts)) continue;\n masks.push(mask);\n found.push(cuts);\n }\n return found;\n}\n\nfunction popCount(mask: number): number {\n let total = 0;\n for (let rest = mask; rest > 0; rest &= rest - 1) total += 1;\n return total;\n}\n\n/**\n * This function gives an upper limit of the curve of a stop for each dependence of the cuts.\n * At each time it is `min(1, sum over the minimal sets of the smallest chance of the set)`.\n * With no minimal sets, as for too many cuts, it is `min(1, sum of the chances)`.\n *\n * @param curves - The curves of the cuts\n * @param sets - The minimal sets of `minimalStops`, or `undefined`\n * @throws RangeError when a curve does not end at a chance of 0\n */\nexport function upperStop(curves: readonly Survival[], sets: readonly (readonly number[])[] | undefined): Survival {\n const groups = sets ?? curves.map((_, index) => [index]);\n const sum = (days: number): number => groups.reduce((total, set) => total + Math.min(...set.map((index) => survivalAt(curves[index] ?? [], days))), 0);\n // The sum is linear between two times of bendTimes. A point where it falls through 1 is a bend of min(1, sum).\n const times = bendTimes(curves);\n const bends = new Set(times);\n for (let index = 1; index < times.length; index += 1) {\n const t0 = times[index - 1] ?? 0;\n const t1 = times[index] ?? 0;\n const s0 = sum(t0) - 1;\n const s1 = sum(t1) - 1;\n if (s0 * s1 < 0) bends.add(t0 + ((t1 - t0) * s0) / (s0 - s1));\n }\n return curveFrom([...bends].sort((x, y) => x - y), (days) => Math.min(1, sum(days)));\n}\n\n/** The largest difference between `independentStop` and the true chance of a stop of independent cuts, at each time. */\nexport const INDEPENDENT_TOLERANCE = 1e-6;\n\n/**\n * The default budget of `independentStop` for its groups of more than `MINIMAL_STOP_CUTS` cuts.\n * The budget counts the steps of the expansion times the count of points of the curve.\n * It is near the work of the sum over the states of 12 cuts.\n */\nexport const INDEPENDENT_MAX_WORK: number = 2 ** 26;\n\n/**\n * This function gives the curve of a stop of some cuts when the cuts are independent.\n * At each time `t`, the supply is stopped when the cuts that are still on contain a minimal set.\n * Its chance is a sum over each set of cuts that stops the supply.\n * Each term is the product of `s(t)` for the cuts that are on, and of `1 - s(t)` for the other cuts.\n *\n * - When any one cut stops the supply, the result is `1 - prod(1 - s)`. It is not less than the longest cut (`eventStop`).\n * - When the supply needs `any` of two parts, the stop of the two is `s1 * s2`. It is not more than the shorter cut.\n * - The result is not more than `upperStop` of the same sets, because `upperStop` is a limit for each dependence.\n * - Between two points of the curves the chance is a polynomial, not a line. The function splits each such segment into equal pieces.\n * The chance is linear in each `s`, and each mixed second derivative is between -1 and 1.\n * Thus `|f''| <= (sum |s'|)^2 - sum s'^2`, and the line of a piece of length `h` is within `h^2 |f''| / 8` of the chance.\n * The count of pieces keeps each line within `INDEPENDENT_TOLERANCE`. With a margin of 10 %, the count of points is less than `n / sqrt(7.2 * INDEPENDENT_TOLERANCE)` plus the segments, for `n` cuts.\n *\n * - Up to `MINIMAL_STOP_CUTS` cuts in the sets, the function adds the chance of each of the 2 to the power of that count of states.\n * - Two groups of cuts that share no set are independent, so the chance that the supply works is the product over the groups.\n * For example, 20 stages of 2 feeds give 20 groups of 2 cuts.\n * - In a group of more than `MINIMAL_STOP_CUTS` cuts, it uses the Shannon expansion of `pathSetReliability` of collections.\n * The expansion merges two states with the same sets left, and it drops a set that holds another set.\n * - The expansion is exponential in the worst case. The groups share one budget, `maxWork`.\n * When the steps of the expansions times the count of points of the curve pass it, the result is `undefined`.\n *\n * @param curves - The curves of the cuts, each one good for `checkEndurance`\n * @param sets - The minimal sets of the cuts. With `undefined`, as for no minimal sets, the result is `undefined`. With no sets, it is `[[0, 0]]`\n * @param maxWork - The budget of the expansions of the groups of more than `MINIMAL_STOP_CUTS` cuts, a whole number from 1. The default is `INDEPENDENT_MAX_WORK`\n * @throws RangeError when a curve does not end at a chance of 0, or for a bad `maxWork`\n */\nexport function independentStop(curves: readonly Survival[], sets: readonly (readonly number[])[] | undefined, maxWork: number = INDEPENDENT_MAX_WORK): Survival | undefined {\n if (!Number.isInteger(maxWork) || maxWork < 1) throw new RangeError(`The budget maxWork is ${String(maxWork)}: it is not a whole number from 1.`);\n if (sets === undefined) return undefined;\n // With no set, no cuts stop the supply, as for `eventStop` and `upperStop`.\n if (sets.length === 0) return [[0, 0]];\n // Only the cuts of a set change the chance. Their place in `used` is their index in the sets of the cuts that count.\n const used = [...new Set(sets.flat())].sort((x, y) => x - y);\n const usedCurves = used.map((index) => curves[index] ?? []);\n const usedSets = sets.map((set) => set.map((index) => used.indexOf(index)));\n const points = independentPoints(usedCurves);\n // Two groups of cuts that share no set are independent: the supply works when it works in each group.\n const groupChances: ((days: number) => number)[] = [];\n // The expansions of all groups share one budget.\n let work = maxWork;\n for (const group of cutGroups(used.length, usedSets)) {\n const curvesOf = group.map((index) => usedCurves[index] ?? []);\n const setsOf = usedSets.filter((set) => group.includes(set[0] ?? -1)).map((set) => set.map((index) => group.indexOf(index)));\n // Up to MINIMAL_STOP_CUTS cuts, the sum over the states is exact with a fixed cost. Past them, the expansion is exact within its budget.\n if (group.length <= MINIMAL_STOP_CUTS) {\n groupChances.push(stateChance(curvesOf, setsOf));\n continue;\n }\n const expanded = expandedChances(curvesOf, setsOf, points, work);\n if (expanded === undefined) return undefined;\n work -= expanded.steps * points.length;\n const chanceOf = new Map(points.map((days, index) => [days, expanded.chances[index] ?? 0]));\n groupChances.push((days) => {\n const chance = chanceOf.get(days);\n if (chance === undefined) throw new Error(`The expansion has no chance at ${String(days)} days.`);\n return chance;\n });\n }\n // With one group, the chance of the group is the result, with no rounding of 1 - (1 - chance).\n const [only] = groupChances;\n if (groupChances.length === 1 && only !== undefined) return curveFrom(points, only);\n return curveFrom(points, (days) => Math.min(1, Math.max(0, 1 - groupChances.reduce((works, chanceAt) => works * (1 - chanceAt(days)), 1))));\n}\n\n/** The groups of the cuts `0` to `count - 1`: two cuts are in one group when a chain of sets joins them. Each set has its cuts in one group. */\nfunction cutGroups(count: number, sets: readonly (readonly number[])[]): number[][] {\n const next = Array.from({ length: count }, () => new Set<number>());\n // A cycle through the cuts of each set joins them both ways, so the strongly connected components are the groups.\n for (const set of sets) for (const [at, index] of set.entries()) next[index]?.add(set[(at + 1) % set.length] ?? index);\n return stronglyConnectedComponents(\n Array.from({ length: count }, (_, index) => index),\n (index) => next[index] ?? [],\n );\n}\n\n/** The times of `independentStop`: the points of the curves, and the pieces that keep each line within `INDEPENDENT_TOLERANCE`. */\nfunction independentPoints(curves: readonly Survival[]): number[] {\n const times = [...new Set(curves.flatMap((curve) => curve.map(([days]) => days)))].sort((x, y) => x - y);\n const points: number[] = [];\n for (const [index, t1] of times.entries()) {\n const t0 = times[index - 1];\n if (t0 !== undefined) {\n const h = t1 - t0;\n const slopes = curves.map((curve) => Math.abs(survivalAt(curve, t1) - survivalAt(curve, t0)) / h);\n const sum = slopes.reduce((total, slope) => total + slope, 0);\n const bound = Math.max(0, sum * sum - slopes.reduce((total, slope) => total + slope * slope, 0));\n // A margin of 10 % keeps the rounding of the chance under the tolerance.\n const pieces = Math.ceil(h * Math.sqrt(bound / (8 * 0.9 * INDEPENDENT_TOLERANCE)));\n for (let piece = 1; piece < pieces; piece += 1) {\n const days = t0 + (h * piece) / pieces;\n // Two times that are next to each other as floats have no time between them.\n if (days > (points[points.length - 1] ?? t0) && days < t1) points.push(days);\n }\n }\n points.push(t1);\n }\n return points;\n}\n\n/** The chance of a stop at a time, as the sum over each state of `MINIMAL_STOP_CUTS` cuts or fewer. Bit k of a state is 1 when cut k is on. */\nfunction stateChance(curves: readonly Survival[], sets: readonly (readonly number[])[]): (days: number) => number {\n const setMasks = sets.map((set) => set.reduce((mask, index) => mask | (1 << index), 0));\n const stopping = Array.from({ length: 1 << curves.length }, (_, mask) => setMasks.some((set) => (set & mask) === set));\n const states = new Float64Array(1 << curves.length);\n return (days) => {\n // The chance of each state of the cuts, one cut at a time.\n states[0] = 1;\n let length = 1;\n for (const curve of curves) {\n const on = survivalAt(curve, days);\n for (let mask = 0; mask < length; mask += 1) {\n const chance = states[mask] ?? 0;\n states[mask + length] = chance * on;\n states[mask] = chance * (1 - on);\n }\n length *= 2;\n }\n let total = 0;\n for (let mask = 0; mask < length; mask += 1) if (stopping[mask]) total += states[mask] ?? 0;\n return Math.min(1, Math.max(0, total));\n };\n}\n\n/** The count of times in one expansion of `expandedChances`: the length of the vectors of its ring. */\nconst EXPANSION_WIDTH = 64;\n\n/**\n * The ring of the vectors of `width` chances, one for each time, for `pathSetReliability` of collections.\n * Each operation is on each time alone. In the order, `a` is less than `b` when it is less or equal at each time, and not equal.\n */\nfunction vectorRing(width: number): OrderedRing<Float64Array> {\n const zip = (a: Float64Array, b: Float64Array, op: (x: number, y: number) => number): Float64Array => {\n const out = new Float64Array(width);\n for (let index = 0; index < width; index += 1) out[index] = op(a[index] ?? 0, b[index] ?? 0);\n return out;\n };\n return {\n zero: new Float64Array(width),\n one: new Float64Array(width).fill(1),\n add: (a, b) => zip(a, b, (x, y) => x + y),\n sub: (a, b) => zip(a, b, (x, y) => x - y),\n mul: (a, b) => zip(a, b, (x, y) => x * y),\n compare: (a, b) => {\n let less = false;\n let more = false;\n for (let index = 0; index < width; index += 1) {\n const [x, y] = [a[index] ?? 0, b[index] ?? 0];\n if (x < y) less = true;\n else if (x > y) more = true;\n else if (x !== y) return Number.NaN;\n }\n return less ? (more ? Number.NaN : -1) : more ? 1 : 0;\n },\n };\n}\n\n/**\n * The chance of a stop at each point, from the Shannon expansion of `pathSetReliability`. A set works when each of its cuts is on.\n * One call gives `EXPANSION_WIDTH` points. When the steps of one expansion times the count of points pass `maxWork`, the result is `undefined`.\n * Else `steps` is the count of steps of one expansion.\n */\nfunction expandedChances(\n curves: readonly Survival[],\n sets: readonly (readonly number[])[],\n points: readonly number[],\n maxWork: number,\n): { readonly chances: number[]; readonly steps: number } | undefined {\n const maxSteps = Math.floor(maxWork / points.length);\n if (maxSteps < 1) return undefined;\n const out: number[] = [];\n let steps = 0;\n for (let start = 0; start < points.length; start += EXPANSION_WIDTH) {\n const times = points.slice(start, start + EXPANSION_WIDTH);\n const chances = curves.map((curve) => Float64Array.from(times, (days) => survivalAt(curve, days)));\n const result = pathSetReliability(sets, chances, vectorRing(times.length), { maxSteps });\n // Each call has the same sets, so the first call tells if the expansion is in the budget.\n if (result.kind === \"budget\") return undefined;\n steps = result.steps;\n for (const chance of result.value) out.push(Math.min(1, Math.max(0, chance)));\n }\n return { chances: out, steps };\n}\n\n/**\n * The curves of the stop of a draw. `event` is for one event that makes each cut longer together, and `independent` is for independent cuts.\n * `upper` is an upper limit for each dependence.\n */\nexport interface StopCurves {\n readonly event: Survival;\n /** The stop when the cuts are independent (`independentStop`). When `independentUpper` is true, it is `upper`. */\n readonly independent: Survival;\n readonly upper: Survival;\n /**\n * This is true when `upper` is the sum of the curves of the cuts that count, because the query has no minimal sets.\n * With a stack, the search of the needs passed its budget. With no stack, more than `MINIMAL_STOP_CUTS` cuts count.\n */\n readonly coarse: boolean;\n /** This is true when `independent` is `upper`: `coarse` is true, or the expansion of `independentStop` passed its budget. */\n readonly independentUpper: boolean;\n /**\n * The weakest bound (`weakestBound` of the core) of the curves of the cuts that the stop uses. Since 0.8.4.\n * With minimal sets, the stop uses the cuts of the sets. With no minimal sets, it uses each cut with a curve.\n * Each of the three curves does not decrease when a cut lasts longer, so it has this bound.\n */\n readonly bound: CutBound;\n}\n\n/** This function gives the parts of the stack that are down for a list of cut indexes. A case uses one memo for each of its draws. */\ntype StoppedOf = (cuts: readonly number[]) => ReadonlySet<string>;\n\nfunction stoppedMemo(caseCuts: CaseCuts, options: Pick<CaseOptions, \"stack\" | \"down\">): StoppedOf {\n const memo = new Map<string, ReadonlySet<string>>();\n return (cuts) => {\n const key = cuts.join(\",\");\n let found = memo.get(key);\n if (found === undefined) {\n found = caseStopped({ ...caseCuts, cuts: cuts.flatMap((index) => caseCuts.cuts[index] ?? []) }, options);\n memo.set(key, found);\n }\n return found;\n };\n}\n\n/** This function gives the parts whose cut can stop a supply: the supply, and each part that it needs through the stack. */\nfunction supplyReach(supply: string, options: Pick<CaseOptions, \"stack\">): Set<string> {\n const reach = options.stack === undefined ? new Set<string>() : neededParts(options.stack, supply);\n reach.add(supply);\n return reach;\n}\n\nfunction stopCurvesWith(caseCuts: CaseCuts, draw: Draw, options: StopCurveOptions, stoppedOf: StoppedOf): StopCurves | undefined {\n const reach = supplyReach(draw.supply, options);\n const relevant = caseCuts.cuts.flatMap((cut, index) => (reach.has(cut.part) ? [index] : []));\n const stops = (cuts: readonly number[]): boolean => stoppedOf(cuts.map((index) => relevant[index] ?? -1)).has(draw.supply);\n if (stops([])) return undefined;\n if (!stops(relevant.map((_, index) => index))) return undefined;\n const given = relevant.map((index) => caseCuts.cuts[index]?.duration);\n // With a stack, the needs give the minimal sets. When their search passes its budget, the sets of each list of cuts are the check.\n const parts = relevant.map((index) => caseCuts.cuts[index]?.part ?? \"\");\n const structural = options.stack === undefined ? undefined : stackStops(options.stack, draw.supply, parts, options.down, budgetsOf(options).maxSets);\n const sets = structural ?? minimalStops(given.length, stops);\n // The stop has no curve when a cut with no curve can be part of it. With no minimal sets, the query cannot tell.\n const unsourced = given.flatMap((curve, index) => (curve === undefined ? [index] : []));\n if (unsourced.length > 0 && (sets === undefined || sets.some((set) => set.some((index) => unsourced.includes(index))))) return undefined;\n // A cut with no curve is in no minimal set here, so it does not change a stop. The curves do not include it.\n const kept = given.flatMap((curve, index) => (curve === undefined ? [] : [index]));\n const curves = kept.map((index) => given[index] ?? []);\n const keptStops = (cuts: readonly number[]): boolean => stops(cuts.map((index) => kept[index] ?? -1));\n const keptSets = sets?.map((set) => set.map((index) => kept.indexOf(index)));\n const upper = upperStop(curves, keptSets);\n const independent = independentStop(curves, keptSets, budgetsOf(options).maxWork);\n // A cut in no minimal set does not change a stop, so its bound does not weaken the bound of the stop.\n const used = sets === undefined ? kept : kept.filter((index) => sets.some((set) => set.includes(index)));\n const bound = weakestBound(used.map((index) => caseCuts.cuts[relevant[index] ?? -1]?.bound ?? \"law\"));\n return { event: eventStop(curves, keptStops), independent: independent ?? upper, upper, coarse: keptSets === undefined, independentUpper: independent === undefined, bound };\n}\n\n/**\n * This function gives the curves of the duration of the stop of a draw, or `undefined` when the query has no curve.\n *\n * - A set of cuts stops the supply when the supply cannot work without the cut parts, through the needs of the stack.\n * - Only the cuts of the supply, and of the parts that it needs through the stack, count. Another cut does not change the curves.\n * - The parts of `down` are down for the full event. When they stop the supply with no cut, the query has no curve.\n * - With a stack, the minimal sets come from the paths of the needs (`stopSets` of the core), so the count of cuts has no limit of `MINIMAL_STOP_CUTS`.\n * When that search passes its budget (the option `maxSets`), `minimalStops` examines each set of up to `MINIMAL_STOP_CUTS` cuts.\n * - A cut with no `duration` gives no curve when it is in a minimal set, or when the query has no minimal sets.\n * - `event` is `eventStop`. `independent` is `independentStop`, and `upper` is `upperStop`, over the minimal sets of the cuts that count.\n * - With no minimal sets, `upper` is the sum of the curves, `independent` is `upper`, and `coarse` is true.\n * - When the expansion of `independentStop` passes its budget, `independent` is `upper`, and `independentUpper` is true.\n * - `bound` is the weakest bound of the curves of the cuts that the stop uses. A cut with no `bound` has a law.\n */\nexport function stopCurves(caseCuts: CaseCuts, draw: Draw, options: StopCurveOptions = {}): StopCurves | undefined {\n budgetsOf(options);\n return stopCurvesWith(caseCuts, draw, options, stoppedMemo(caseCuts, options));\n}\n\n/** The shortfall of each level, in user-days, and the draws that the query cannot read. */\nexport interface Shortfall {\n /**\n * The user-days of each level of the layer, when one event makes each cut longer together. The query does not add two levels.\n * This value is not a limit. The true value can be more or less. `upper` is the limit.\n */\n readonly levels: Readonly<Record<string, number>>;\n /** The user-days of each level when the cuts are independent (`StopCurves.independent`). This value is not more than `upper`. */\n readonly independent: Readonly<Record<string, number>>;\n /** The upper limit of the user-days of each level, for each dependence of the cuts. A gate of a high level can use it. */\n readonly upper: Readonly<Record<string, number>>;\n /**\n * The needs of the draws whose stop has no curve (`stopCurves`).\n * The query has no curve of their duration, so their shortfall is not in `levels`. A gate shows them as no read.\n */\n readonly unread: readonly string[];\n /** The needs of the draws whose `upper` is coarse (`StopCurves.coarse`). A gate on `upper` shows them. */\n readonly coarse: readonly string[];\n /** The needs of the draws whose `independent` is `upper` (`StopCurves.independentUpper`). A gate on `independent` shows them. */\n readonly independentUpper: readonly string[];\n /**\n * The bound of the shortfall: the weakest bound (`weakestBound` of the core) of the curves that the query uses. Since 0.8.4.\n * The shortfall does not decrease when a cut lasts longer. So with `upper`, each value is too high or equal, and with `lower` too low or equal.\n * With `none`, a value can be too high or too low.\n *\n * A draw in `unread` and a case that adds 0 do not change the bound. With no curve, the bound is `law`.\n * The bound is for each of `levels`, `independent` and `upper`, each with its own rule of the dependence of the cuts.\n */\n readonly bound: CutBound;\n}\n\nfunction zeroLevels(layer: EnduranceLayer): Record<string, number> {\n return Object.fromEntries(layer.levels.map((level) => [level, 0]));\n}\n\n/**\n * This function gives the shortfall of one event of a case: for each draw, `E[max(0, min(D, h) - T)] * users`.\n * `T` is the endurance of the draw, `D` is the duration of the stop of its supply (`stopCurves`), and `h` is the horizon.\n *\n * @param layer - The endurance layer\n * @param caseCuts - The case\n * @param endurance - The endurance of the case, from `enduranceOf`\n * @param options - The stack or the parts that are also down, as for `enduranceOf`, and the horizon\n * @throws RangeError when the horizon is not a number more than 0, or `maxSets` is not a whole number from 1\n */\nexport function caseShortfall(layer: EnduranceLayer, caseCuts: CaseCuts, endurance: Endurance, options: ShortfallOptions = {}): Shortfall {\n const horizon = horizonOf(options);\n budgetsOf(options);\n const levels = zeroLevels(layer);\n const independent = zeroLevels(layer);\n const upper = zeroLevels(layer);\n const unread: string[] = [];\n const coarse: string[] = [];\n const independentUpper: string[] = [];\n const bounds: CutBound[] = [];\n const stoppedOf = stoppedMemo(caseCuts, options);\n for (const draw of caseDraws(layer, caseCuts, caseStopped(caseCuts, options))) {\n const held = endurance.needs[draw.need];\n const curves = stopCurvesWith(caseCuts, draw, options, stoppedOf);\n if (held === undefined || curves === undefined) {\n unread.push(draw.need);\n continue;\n }\n if (curves.coarse) coarse.push(draw.need);\n if (curves.independentUpper) independentUpper.push(draw.need);\n bounds.push(curves.bound);\n const users = draw.users ?? 1;\n levels[draw.level] = (levels[draw.level] ?? 0) + tailDays(curves.event, held.days, horizon) * users;\n independent[draw.level] = (independent[draw.level] ?? 0) + tailDays(curves.independent, held.days, horizon) * users;\n upper[draw.level] = (upper[draw.level] ?? 0) + tailDays(curves.upper, held.days, horizon) * users;\n }\n return { levels, independent, upper, unread, coarse, independentUpper, bound: weakestBound(bounds) };\n}\n\n/** The shortfall of one year at one place, with the part of each case. */\nexport interface YearShortfall extends Shortfall {\n readonly place: string;\n /** The part of each case. `rate` is the expected count of its events in one year. */\n readonly cases: readonly { readonly case: string; readonly rate: number; readonly endurance: Endurance; readonly shortfall: Shortfall }[];\n}\n\n/**\n * This function gives the shortfall of one year at one place.\n * It is the sum over the cases of the layer of the expected count of the events of each case times its shortfall.\n *\n * - The expected count of a case is `perYear * reach`, from the first prior of the case at the place. Thus the result is the expected user-days of one year.\n * - A case with no prior at the place is not in the sum.\n * - `unread` is the union of the needs that a case cannot read, in the order of the cases. `coarse` and `independentUpper` are unions too.\n * - `bound` is the weakest bound of the cases in the sum. A case with no prior, or with an expected count of 0, adds 0, so it does not change the bound.\n *\n * @param layer - The endurance layer, with its cases and priors\n * @param place - The place of the priors\n * @param options - The date, the stack or the parts that are also down, and the horizon\n * @throws RangeError for a bad date, horizon or `maxSets`: refer to `caseShortfall` and `enduranceOf`\n */\nexport function yearShortfall(layer: EnduranceLayer, place: string, options: CaseOptions & ShortfallOptions): YearShortfall {\n horizonOf(options);\n budgetsOf(options);\n const levels = zeroLevels(layer);\n const independent = zeroLevels(layer);\n const upper = zeroLevels(layer);\n const unread: string[] = [];\n const coarse: string[] = [];\n const independentUpper: string[] = [];\n const cases: YearShortfall[\"cases\"][number][] = [];\n const bounds: CutBound[] = [];\n for (const caseCuts of layer.cases ?? []) {\n const prior = (layer.priors ?? []).find((item) => item.case === caseCuts.case && item.place === place);\n if (prior === undefined) continue;\n const rate = yearRate(prior);\n const endurance = enduranceOf(layer, caseCuts, options);\n const shortfall = caseShortfall(layer, caseCuts, endurance, options);\n for (const [level, days] of Object.entries(shortfall.levels)) levels[level] = (levels[level] ?? 0) + rate * days;\n for (const [level, days] of Object.entries(shortfall.independent)) independent[level] = (independent[level] ?? 0) + rate * days;\n for (const [level, days] of Object.entries(shortfall.upper)) upper[level] = (upper[level] ?? 0) + rate * days;\n for (const need of shortfall.unread) if (!unread.includes(need)) unread.push(need);\n for (const need of shortfall.coarse) if (!coarse.includes(need)) coarse.push(need);\n for (const need of shortfall.independentUpper) if (!independentUpper.includes(need)) independentUpper.push(need);\n if (rate > 0) bounds.push(shortfall.bound);\n cases.push({ case: caseCuts.case, rate, endurance, shortfall });\n }\n return { place, levels, independent, upper, unread, coarse, independentUpper, bound: weakestBound(bounds), cases };\n}\n","import { STACK_SCHEMA, type Stack } from \"@mark1russell7/system-stack\";\nimport { ENDURANCE_SCHEMA, type EnduranceLayer } from \"./layer.ts\";\n\n// A sample: a building with 3 users, and a storm that cuts the grid, the road and the water main.\n// Each name and each value is an example, except the grid curve (NREL, technical report 83092). The tests, the README files and the site use it.\n\n/** The base stack of the sample: the supplies of the building and a camp stove. */\nexport const SAMPLE_ENDURANCE_STACK: Stack = {\n schema: STACK_SCHEMA,\n parts: [\n { id: \"grid\", kind: \"power\", name: \"The power grid\" },\n { id: \"water-main\", kind: \"water\", name: \"The water main\" },\n { id: \"road\", kind: \"road\", name: \"The local road to the shops\" },\n { id: \"stove\", kind: \"device\", name: \"The camp stove\" },\n ],\n};\n\n/**\n * The endurance layer of the sample.\n *\n * - The drinking water holds 75.7 L / 11.355 L a day = 6.667 days.\n * - The food holds 4800 / 5400 = 0.889 days. The rice needs 2 L of water for each kg, and the drinking water keeps back all the water.\n * - The power holds 1000 Wh / 150 Wh a day = 6.667 days.\n * - The filled bottles are past their due date, so they give nothing.\n */\nexport const SAMPLE_ENDURANCE: EnduranceLayer = {\n schema: ENDURANCE_SCHEMA,\n levels: [\"life\", \"health\", \"comfort\"],\n resources: [\n { code: \"water.stored\", unit: \"L\" },\n { code: \"food.ready\", unit: \"kcal\" },\n { code: \"food.grain-dry\", unit: \"kg\" },\n { code: \"fuel.propane\", unit: \"kg\" },\n { code: \"energy.battery\", unit: \"Wh\" },\n ],\n stores: [\n { id: \"jugs\", resource: \"water.stored\", amount: 75.7, due: \"2028-06-01\" },\n { id: \"bottles\", resource: \"water.stored\", amount: 20, due: \"2026-09-30\" },\n { id: \"cans\", resource: \"food.ready\", amount: 4800, due: \"2028-10-01\" },\n { id: \"rice\", resource: \"food.grain-dry\", amount: 9, due: \"2036-09-28\" },\n { id: \"propane\", resource: \"fuel.propane\", amount: 0.908, due: \"2036-10-01\" },\n { id: \"battery\", resource: \"energy.battery\", amount: 1000, due: \"2031-10-01\" },\n ],\n draws: [\n { need: \"hydration.drink\", level: \"life\", perDay: 11.355, users: 3, supply: \"water-main\" },\n { need: \"food.energy\", level: \"health\", perDay: 5400, users: 3, supply: \"road\" },\n { need: \"power.electric\", level: \"comfort\", perDay: 150, users: 3, supply: \"grid\" },\n ],\n direct: [\n { resource: \"water.stored\", need: \"hydration.drink\", amount: 1 },\n { resource: \"food.ready\", need: \"food.energy\", amount: 1 },\n { resource: \"energy.battery\", need: \"power.electric\", amount: 1 },\n ],\n converters: [\n {\n id: \"cook-rice\",\n device: \"stove\",\n takes: [\n { resource: \"food.grain-dry\", amount: 1 },\n { resource: \"water.stored\", amount: 2 },\n { resource: \"fuel.propane\", amount: 0.05 },\n ],\n gives: { need: \"food.energy\", amount: 3600 },\n },\n ],\n cases: [\n {\n case: \"storm\",\n title: \"Winter storm\",\n cuts: [\n { part: \"grid\", title: \"Power outage\", duration: [[0, 1], [0.5, 0.5], [1, 0.36], [7, 0.013], [30, 0]], source: \"nrel-83092\" },\n { part: \"road\", title: \"Closed local road\", duration: [[0, 1], [1, 0.6], [3, 0.2], [10, 0]], source: \"sample\" },\n { part: \"water-main\", title: \"No water from the main\", duration: [[0, 1], [2, 0.3], [7, 0]], source: \"sample\" },\n ],\n leadSeconds: 86_400,\n },\n { case: \"fire\", title: \"Fire\", cuts: [] },\n ],\n priors: [\n { case: \"storm\", place: \"home\", perYear: 0.8, reach: 1, source: \"sample\", asOf: \"2025-12-01\" },\n { case: \"fire\", place: \"home\", perYear: 0.003, reach: 1, source: \"sample\", asOf: \"2025-12-01\" },\n ],\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwEA,SAAgB,UAAU,OAAuB,UAAoB,SAAsB,OAAqC;CAC9H,MAAM,QAAQ,IAAI,IAAI,MAAM,MAAM,KAAK,SAAS,KAAK,IAAI,CAAC;CAC1D,MAAM,UAAU,MAAM,QAAQ,SAAS,CAAC,MAAM,IAAI,IAAI,CAAC;CACvD,IAAI,QAAQ,SAAS,GAAG,MAAM,IAAI,WAAW,aAAa,QAAQ,KAAK,SAAS,IAAI,KAAK,EAAE,CAAC,CAAC,KAAK,IAAI,EAAE,0CAA0C;CAClJ,MAAM,eAAe,YAAY,UAAU,OAAO;CAClD,MAAM,QAAQ,aAAa,OAAO,QAAQ,IAAI,YAAY;CAC1D,MAAM,SAAS,IAAI,IAAI,KAAK;CAC5B,MAAM,OAAO,UAAU,OAAO,UAAU,YAAY,CAAC,CAAC,QAAQ,SA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C;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/program.ts","../src/joint.ts","../src/best.ts","../src/stops.ts","../src/shortfall.ts","../src/sample.ts"],"sourcesContent":["import type { Constraint } from \"@mark1russell7/linear\";\nimport { add, div, mul, neg, ONE, type Rational, ZERO } from \"@mark1russell7/rational\";\nimport { canRun, deviceKey, inputsOf } from \"./converter.ts\";\nimport { giftNeed, giftResource } from \"./endurance.ts\";\nimport type { Converter, DirectUse, Draw, EnduranceLayer } from \"./layer.ts\";\nimport { addTo, dense, exact, type Row } from \"./rows.ts\";\n\n// The internal parts of the linear programs over the totals of a span: the parts of a case, the columns and rows of each draw,\n// and the device-days of the converters. The joint days and the best endurance use them. The root entry does not give them.\n\n/** One constraint row of a program, in its sparse form. */\nexport interface RowSpec {\n readonly row: Row;\n readonly relation: Constraint[\"relation\"];\n readonly rhs: Rational;\n}\n\n/** A program in construction: the count of its variables and its rows. */\nexport class Program {\n count = 0;\n readonly rows: RowSpec[] = [];\n\n /** This method adds a variable and gives its index. */\n next(): number {\n return this.count++;\n }\n\n /** This method adds a row and gives its index. */\n push(row: Row, relation: Constraint[\"relation\"], rhs: Rational): number {\n this.rows.push({ row, relation, rhs });\n return this.rows.length - 1;\n }\n\n /** This method gives the dense rows for `solveLexicographic`. */\n constraints(): Constraint[] {\n return this.rows.map(({ row, relation, rhs }) => ({ coefficients: dense(row, this.count), relation, rhs }));\n }\n}\n\n/** The parts of a case that the programs use. */\nexport interface CaseParts {\n /** The stock of each resource at the date of the query (`storeAmounts`). */\n readonly stock: ReadonlyMap<string, number>;\n /** The direct uses of the needs of the program, with an amount more than 0. */\n readonly direct: readonly DirectUse[];\n /** The converters that can run and give a need of the program. */\n readonly cooks: readonly Converter[];\n /** The converters that can run and give a resource. */\n readonly makers: readonly Converter[];\n /** Each resource that a direct use or a converter takes, and each resource that a maker gives. */\n readonly resources: ReadonlySet<string>;\n /** The resources of `resources` with a stock more than 0, in the order of their codes. */\n readonly stocked: readonly string[];\n}\n\n/** This function gives the parts of a case for the draws of `needs`. */\nexport function caseParts(layer: EnduranceLayer, stoppedParts: ReadonlySet<string>, stock: ReadonlyMap<string, number>, needs: ReadonlySet<string>): CaseParts {\n const direct = (layer.direct ?? []).filter((use) => needs.has(use.need) && use.amount > 0);\n const live = (layer.converters ?? []).filter((converter) => canRun(converter, stoppedParts));\n const cooks = live.filter((converter) => needs.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 return { stock, direct, cooks, makers, resources, stocked };\n}\n\n/** The columns of one draw in a program. */\nexport interface DrawBlock {\n readonly draw: Draw;\n /** The gifts of the need of the draw from the columns of its direct uses and of its cooks. The caller adds the term of the days. */\n readonly gifts: Row;\n /** The column of the share of each stock, by the code of the resource. It is empty for a draw with no stock. */\n readonly shares: ReadonlyMap<string, number>;\n /** The column of the runs of each converter for the draw: each cook of its need, and each maker. */\n readonly runs: ReadonlyMap<Converter, number>;\n}\n\n/**\n * This function adds the columns of one draw to a program, and the balance row of each of its resources.\n * In a balance row, the takes of the draw are not more than its share of the stock plus the gifts of its makers.\n * The caller adds the row of the need, with the term of the days.\n *\n * @param stocked - False for a draw that takes no stock. Its shares are not columns.\n */\nexport function drawBlock(program: Program, parts: CaseParts, draw: Draw, stocked = true): DrawBlock {\n const gifts: Row = new Map();\n const balance = new Map<string, Row>([...parts.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 for (const use of parts.direct) {\n if (use.need !== draw.need) continue;\n const index = program.next();\n addTo(gifts, index, exact(use.amount));\n consume(use.resource, index, ONE);\n }\n const runs = new Map<Converter, number>();\n for (const cook of parts.cooks) {\n if (giftNeed(cook) !== draw.need) continue;\n const index = program.next();\n runs.set(cook, index);\n addTo(gifts, index, exact(cook.gives.amount));\n for (const [resource, each] of inputsOf(cook)) consume(resource, index, exact(each));\n }\n for (const maker of parts.makers) {\n const index = program.next();\n runs.set(maker, index);\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 const shares = new Map(stocked ? parts.stocked.map((resource) => [resource, program.next()] as const) : []);\n for (const [resource, index] of shares) consume(resource, index, neg(ONE));\n for (const row of balance.values()) if (row.size > 0) program.push(row, \"<=\", ZERO);\n return { draw, gifts, shares, runs };\n}\n\n/** The device-days of a limit: the runs of its converters over `perDay`, the count of its devices, and its converters. */\nexport interface DeviceLimit {\n readonly row: Row;\n readonly devices: number;\n readonly converters: Converter[];\n}\n\n/**\n * This function gives the device-days of each device of a set of run columns, by the key of the device (`deviceKey`).\n * One run uses `1 / perDay` of a day of one device. The converters of one device share one limit. A converter with no device has a limit of its own.\n * A converter with no limit `perDay` is not in the record. The list `stopped` has the columns of the converters with a limit of 0.\n */\nexport function deviceUse(runs: Iterable<readonly [Converter, number]>): { readonly limits: Map<string, DeviceLimit>; readonly stopped: number[] } {\n const limits = new Map<string, DeviceLimit>();\n const stopped: number[] = [];\n for (const [converter, index] of runs) {\n if (converter.perDay === undefined) continue;\n if (!(converter.perDay > 0)) {\n stopped.push(index);\n continue;\n }\n const key = deviceKey(converter);\n const limit: DeviceLimit = limits.get(key) ?? { row: new Map(), devices: converter.devices ?? 1, converters: [] };\n limits.set(key, limit);\n if (!limit.converters.includes(converter)) limit.converters.push(converter);\n addTo(limit.row, index, div(ONE, exact(converter.perDay)));\n }\n return { limits, stopped };\n}\n\n/**\n * This function gives the row of the fewest device-days of a set of run columns: the runs over `perDay`, or the runs with no limit.\n * As an objective, it gives no more runs than the plan uses.\n */\nexport function fewestRow(runs: Iterable<readonly [Converter, number]>): Row {\n const out: Row = new Map();\n for (const [converter, index] of runs) addTo(out, index, converter.perDay !== undefined && converter.perDay > 0 ? div(ONE, exact(converter.perDay)) : ONE);\n return out;\n}\n\n/** This function gives the value of a sparse row at the point `x`. */\nexport function valueAt(row: Row, x: readonly Rational[]): Rational {\n let out = ZERO;\n for (const [index, value] of row) out = add(out, mul(value, x[index] ?? ZERO));\n return out;\n}\n\n/**\n * This function gives each resource that a draw can use: the resources of its direct uses and the inputs of its cooks.\n * It also gives the inputs of their makers, through each chain.\n */\nexport function 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\n/** This function gives the resources that the draws of `needs` can use, and the converters that they can use. */\nexport function reachOf(parts: CaseParts, needs: ReadonlySet<string>): { readonly closure: Set<string>; readonly reach: Set<Converter> } {\n const cooks = parts.cooks.filter((cook) => needs.has(giftNeed(cook) ?? \"\"));\n const closure = inputClosure(parts.direct.filter((use) => needs.has(use.need)).map((use) => use.resource), cooks, parts.makers);\n return { closure, reach: new Set([...cooks, ...parts.makers.filter((maker) => closure.has(giftResource(maker) ?? \"\"))]) };\n}\n","import { type Objective, solveLexicographic } from \"@mark1russell7/linear\";\nimport { add, div, equals, mul, neg, ONE, type Rational, sign, toNumber, ZERO } from \"@mark1russell7/rational\";\nimport { type CaseOptions, caseDraws, caseStopped, drawDemand, storeAmounts } from \"./endurance.ts\";\nimport type { CaseCuts, Converter, EnduranceLayer, IsoDate } from \"./layer.ts\";\nimport { caseParts, deviceUse, drawBlock, fewestRow, Program, reachOf, valueAt } from \"./program.ts\";\nimport { addTo, dense, exact, type Row } from \"./rows.ts\";\n\n// The joint days: the largest count of days that a set of draws holds together, with the best share of the stores.\n// The query is a linear program over the totals of the span, with exact rationals (@mark1russell7/linear).\n\n/** The joint days of a set of draws in a case, with the share of the stores at the optimum. */\nexport interface JointDays {\n readonly case: string;\n readonly at: IsoDate;\n /**\n * The largest count of days that each draw of `plan` holds at the same time. It is `Infinity` when `plan` is empty,\n * or when the stores give each draw of `plan` without end.\n */\n readonly days: number;\n /** The needs of the set that take from the stores: the case stops their supply, and their demand is more than 0. The order is the order of `caseDraws`. */\n readonly plan: readonly string[];\n /** The needs of the set that take nothing from the stores, in the order of their codes. The case does not stop their supply, or their demand is 0. */\n readonly holds: readonly string[];\n /**\n * The amount of each resource that each draw of `plan` takes from the stores in `days`. The keys are the code of the need, then the code of the resource.\n * A take through a converter that makes a resource counts the inputs of the converter. A resource with no take is not in the record.\n * The record is empty when `days` is `Infinity`.\n */\n readonly takes: Readonly<Record<string, Readonly<Record<string, number>>>>;\n /**\n * The resources that limit `days`, in the order of their codes. Each one has a store in the layer, is an input of `plan` through each chain,\n * and has no stock left at the optimum. The list is empty when `days` is `Infinity`.\n */\n readonly binding: readonly string[];\n /** The count of runs of each converter at the optimum, by the `id` of the converter. A converter with no run is not in the record. */\n readonly runs: Readonly<Record<string, number>>;\n /**\n * The converters of the plan whose limit `perDay` stops more runs at the optimum, in the order of their `id`. A converter of the plan\n * gives a need of the plan, or makes an input of the plan through each chain.\n * The list is empty when `days` is `Infinity` or 0. Else it has each converter of the plan with a limit of 0.\n */\n readonly capped: readonly string[];\n}\n\n/**\n * This function gives the joint days of a set of draws. These are the largest count of days `d` at which each draw holds `d` days.\n * The draws hold at the same time, with the best share of the stores and of the runs of the converters.\n *\n * - The function solves a linear program over the totals of the span. Its variables are `d`, the take of each direct use,\n * the runs of each converter, and the share of each stock.\n * - Each draw of the plan gets `d` times its demand (`drawDemand`) from its direct uses and from the converters that give its need.\n * - The takes of each resource are not more than its stock (`storeAmounts` at `at`) plus the gifts of the converters that make it.\n * - A converter whose device stops gives nothing, and a store whose part stops gives nothing, as in `enduranceOf`.\n * - The runs of a converter with a limit `perDay` are not more than `perDay` times `devices` times `d`. The converters of one device share it, as in `enduranceOf`.\n * - A store counts with all of its amount when its due date is after `at`, as in `enduranceOf`. A due date in the span has no effect.\n * - After the largest `d`, a second objective takes the smallest sum of the shares of the stocks. Thus the takes have no waste.\n * - A third objective takes the fewest device-days of the converters. Thus the runs are not more than the plan uses.\n * - The draws that are not in the set are outside this plan. They take nothing in the program.\n * - A need of the set whose supply works, or whose demand is 0, holds without end. It goes in `holds`, as `enduranceOf` leaves it out.\n *\n * The take order of `enduranceOf` gives the stores to a higher draw first. This function gives one share for the whole set.\n * Thus a draw of the set can get fewer days here than alone, and a lower draw can get more.\n *\n * The program uses exact rationals, so the result has no error of the method. Only the change back to a number rounds.\n *\n * @param layer - The endurance layer\n * @param caseCuts - The case\n * @param options - The date, and the stack or the parts that are also down\n * @param needs - The codes of the needs of the draws of the set\n * @returns The joint days, the takes of each draw, the binding resources and the runs of each converter\n * @throws {RangeError} A code of `needs` is not the need of a draw of the layer, or a date is not `YYYY-MM-DD`.\n */\nexport function jointDays(layer: EnduranceLayer, caseCuts: CaseCuts, options: CaseOptions, needs: readonly string[]): JointDays {\n const known = new Set(layer.draws.map((draw) => draw.need));\n const unknown = needs.filter((need) => !known.has(need));\n if (unknown.length > 0) throw new RangeError(`The needs ${unknown.map((need) => `\"${need}\"`).join(\", \")} are not the needs of draws of the layer.`);\n const stoppedParts = caseStopped(caseCuts, options);\n const stock = storeAmounts(layer, options.at, stoppedParts);\n const wanted = new Set(needs);\n const plan = caseDraws(layer, caseCuts, stoppedParts).filter((draw) => wanted.has(draw.need));\n const planned = new Set(plan.map((draw) => draw.need));\n const base = { case: caseCuts.case, at: options.at, plan: plan.map((draw) => draw.need), holds: [...wanted].filter((need) => !planned.has(need)).sort() };\n const endless: JointDays = { ...base, days: Infinity, takes: {}, binding: [], runs: {}, capped: [] };\n if (plan.length === 0) return endless;\n\n const parts = caseParts(layer, stoppedParts, stock, planned);\n const program = new Program();\n const days = program.next();\n const blocks = plan.map((draw) => {\n const block = drawBlock(program, parts, draw);\n // The need of the draw: its gifts are not less than its demand times the days.\n const need: Row = new Map(block.gifts);\n addTo(need, days, neg(exact(drawDemand(draw, caseCuts))));\n program.push(need, \">=\", ZERO);\n return block;\n });\n // The limit of each device: the runs use `devices` times `d` device-days or less. A limit of 0 stops the converter.\n const runCols = blocks.flatMap((block) => [...block.runs]);\n const { limits, stopped } = deviceUse(runCols);\n for (const index of stopped) program.push(new Map([[index, ONE]]), \"<=\", ZERO);\n for (const limit of limits.values()) {\n const row: Row = new Map(limit.row);\n addTo(row, days, neg(exact(limit.devices)));\n program.push(row, \"<=\", ZERO);\n }\n // The shares of each stock are not more than the stock.\n for (const resource of parts.stocked) {\n const row: Row = new Map();\n for (const block of blocks) addTo(row, block.shares.get(resource) as number, ONE);\n program.push(row, \"<=\", exact(stock.get(resource) ?? 0));\n }\n\n const most: Row = new Map([[days, ONE]]);\n const least: Row = new Map();\n for (const block of blocks) for (const [resource, index] of block.shares) addTo(least, index, div(ONE, exact(stock.get(resource) ?? 1)));\n // The third objective takes the fewest device-days. Thus a converter whose inputs cost no stock does not give more runs than the plan uses,\n // and `runs` and `capped` have one value.\n const objectives: Objective[] = [\n { sense: \"max\", coefficients: dense(most, program.count) },\n { sense: \"min\", coefficients: dense(least, program.count) },\n { sense: \"min\", coefficients: dense(fewestRow(runCols), program.count) },\n ];\n const solved = solveLexicographic(program.constraints(), objectives);\n // The point 0 is feasible and the later objectives are not less than 0. So only an unbounded first stage has no optimum.\n if (solved.status !== \"optimal\") return endless;\n\n const x = solved.x;\n const takes: Record<string, Record<string, number>> = {};\n for (const block of blocks) {\n const record: Record<string, number> = {};\n for (const [resource, index] of block.shares) if (sign(x[index] ?? ZERO) > 0) record[resource] = toNumber(x[index] ?? ZERO);\n takes[block.draw.need] = record;\n }\n // A converter gives a need or a resource, so it is a cook or a maker, not the two.\n const total = new Map<Converter, Rational>();\n for (const [converter, index] of runCols) total.set(converter, add(total.get(converter) ?? ZERO, x[index] ?? ZERO));\n const runs: Record<string, number> = {};\n for (const [converter, value] of total) if (sign(value) > 0) runs[converter.id] = toNumber(value);\n\n const withStore = new Set(layer.stores.map((store) => store.resource));\n // The converters that the plan can use: the converters that give a need of the plan, and the makers of the resources of the closure.\n const { closure, reach } = reachOf(parts, planned);\n const binding = [...closure]\n .filter((resource) => withStore.has(resource))\n .filter((resource) => {\n // A resource with no live stock has no share, so its take is 0 and it is used up.\n const taken = blocks.reduce((sum, block) => {\n const index = block.shares.get(resource);\n return index === undefined ? sum : add(sum, x[index] ?? ZERO);\n }, ZERO);\n return equals(taken, exact(stock.get(resource) ?? 0));\n })\n .sort();\n const best = solved.values[0] ?? ZERO;\n const capped = sign(best) > 0\n ? [\n ...[...total.keys()].filter((converter) => converter.perDay !== undefined && !(converter.perDay > 0)),\n ...[...limits.values()].filter((limit) => equals(valueAt(limit.row, x), mul(exact(limit.devices), best))).flatMap((limit) => limit.converters),\n ]\n .filter((converter) => reach.has(converter))\n .map((converter) => converter.id)\n .sort()\n : [];\n return { ...base, days: toNumber(best), takes, binding, runs, capped };\n}\n","import { type Objective, solveLexicographic } from \"@mark1russell7/linear\";\nimport { add, div, equals, mul, neg, ONE, type Rational, sign, sub, toNumber, ZERO } from \"@mark1russell7/rational\";\nimport { type CaseOptions, caseDraws, caseStopped, drawDemand, storeAmounts } from \"./endurance.ts\";\nimport type { CaseCuts, Converter, Draw, DrawEndurance, Endurance, EnduranceLayer } from \"./layer.ts\";\nimport { type CaseParts, caseParts, deviceUse, drawBlock, type DrawBlock, fewestRow, Program, reachOf, valueAt } from \"./program.ts\";\nimport { addTo, dense, exact, type Row } from \"./rows.ts\";\n\n// The best endurance: the days of each draw with the best share of the stores, the most important level first.\n// Each step is a linear program over the totals of the spans, with exact rationals (@mark1russell7/linear).\n\n/** A draw whose days are fixed. */\ninterface Fixed {\n /** The span of the draw in the programs: its days, or 1 for a draw with no end. */\n readonly span: Rational;\n /** True for a draw that holds without end. It takes no stock, and its span is one day. */\n readonly endless: boolean;\n /** The device-days of each day that the draw keeps, by the key of the device. */\n readonly keep: ReadonlyMap<string, Rational>;\n /** The `id` of each converter whose limit stops more runs at the step that fixes the draw. */\n readonly capped: readonly string[];\n}\n\n/** A program of one step, with the indexes of its parts. */\ninterface Step {\n readonly program: Program;\n readonly blocks: readonly DrawBlock[];\n /** The column of the common days of the open draws. */\n readonly floor: number;\n /** The row `days - floor >= 0` of each open draw, by the code of its need. */\n readonly floors: ReadonlyMap<string, number>;\n /** The run columns of the open draws. */\n readonly openRuns: readonly (readonly [Converter, number])[];\n /** The device-days of the open draws for each device, with the device-days of each day that the fixed draws leave. */\n readonly shared: ReadonlyMap<string, { readonly row: Row; readonly room: Rational; readonly converters: readonly Converter[] }>;\n}\n\n/**\n * This function gives the days that each draw holds when a case stops its supply. The stores and the devices have their best share.\n * The result has the form of `enduranceOf`, so `caseShortfall` takes it.\n *\n * The share is lexicographic. The draws of the first level get their best days, then the draws of the next level get theirs, and so on.\n * In one level, the share is the best for the draw with the fewest days, then for the next draw, and so on (the leximin share).\n * Thus a draw of a level cannot take a store that another draw of the level needs more.\n *\n * - The function solves a sequence of linear programs over the totals of the spans. Each program has the days of the open draws\n * and their common floor. For each draw, it has the take of each direct use, the runs of each converter and the share of each stock.\n * - Each step takes the largest floor. A draw whose floor row has a dual value that is not 0 cannot get more days. The step fixes its days.\n * The dual values of the floor rows add to 1, so each step fixes one draw or more.\n * - A fixed draw keeps its days in each later step. Its share of the stocks can change, so a later draw can get a store that it does not need.\n * - The stores, the direct uses, the converters and the devices follow the rules of `jointDays`. A store counts with all of its amount when its due date is after `at`.\n * - A fixed draw keeps the device-days of each day that it uses at its step, for all the days of the later draws. This is the safe side, as in `enduranceOf`.\n * The exact share of a device between two spans is not a linear program: the device-days of a day are the runs over the span.\n * - A step with no largest floor gives the open draws no end. Each of them takes no stock, and keeps the fewest device-days of each day.\n * - At the end, a program takes the smallest sum of the shares of the stocks, each over its stock, then the fewest device-days.\n * These are the takes of the result. A resource in `binding` has no stock left at this point.\n * - A draw in `capped` used a device with no device-days left at the step that fixed it.\n *\n * The programs use exact rationals, so the result has no error of the method. Only the change back to a number rounds.\n * The fewest days of the first level are the joint days (`jointDays`) of the draws of that level.\n *\n * @param layer - The endurance layer\n * @param caseCuts - The case\n * @param options - The date, and the stack or the parts that are also down\n * @returns The endurance of each draw whose supply stops\n * @throws {RangeError} A date is not `YYYY-MM-DD`.\n */\nexport function bestEndurance(layer: EnduranceLayer, caseCuts: CaseCuts, options: CaseOptions): Endurance {\n const stoppedParts = caseStopped(caseCuts, options);\n const stock = storeAmounts(layer, options.at, stoppedParts);\n const draws = caseDraws(layer, caseCuts, stoppedParts);\n const parts = caseParts(layer, stoppedParts, stock, new Set(draws.map((draw) => draw.need)));\n // The count of devices of each key. The gate refuses two counts for one device.\n const devices = new Map([...deviceUse([...parts.cooks, ...parts.makers].map((converter) => [converter, 0] as const)).limits].map(([key, limit]) => [key, limit.devices] as const));\n const fixed = new Map<string, Fixed>();\n\n for (const level of levelGroups(layer, draws)) {\n let open = level;\n while (open.length > 0) {\n const step = buildStep(parts, caseCuts, draws, fixed, open, devices, \"span\");\n const solved = solveLexicographic(step.program.constraints(), [\n { sense: \"max\", coefficients: dense(new Map([[step.floor, ONE]]), step.program.count) },\n { sense: \"min\", coefficients: dense(fewestRow(step.openRuns), step.program.count) },\n ]);\n if (solved.status !== \"optimal\") {\n if (solved.status === \"infeasible\") throw new Error(\"The step of the best endurance has no point. The point of the last step is a point of it.\");\n fixEndless(parts, caseCuts, draws, fixed, open, devices);\n break;\n }\n const floor = solved.values[0] ?? ZERO;\n const first = solved.stages[0]?.result;\n const dual = first?.status === \"optimal\" ? first.dual : [];\n let done = open.filter((draw) => sign(dual[step.floors.get(draw.need) as number] ?? ZERO) !== 0);\n // The dual values of the floor rows add to 1. Thus `done` is not empty. The fallback fixes each open draw at the floor.\n if (done.length === 0) done = open;\n const full = new Set([...step.shared].filter(([, limit]) => equals(valueAt(limit.row, solved.x), mul(limit.room, floor))).map(([key]) => key));\n for (const draw of done) {\n const block = step.blocks.find((item) => item.draw.need === draw.need) as DrawBlock;\n const keep = new Map<string, Rational>();\n for (const [key, limit] of deviceUse(block.runs).limits) keep.set(key, sign(floor) > 0 ? div(valueAt(limit.row, solved.x), floor) : ZERO);\n const { reach } = reachOf(parts, new Set([draw.need]));\n const capped = sign(floor) > 0\n ? [...reach]\n .filter((converter) => converter.perDay !== undefined && (!(converter.perDay > 0) || [...full].some((key) => step.shared.get(key)?.converters.includes(converter))))\n .map((converter) => converter.id)\n .sort()\n : [];\n fixed.set(draw.need, { span: floor, endless: false, keep, capped });\n }\n const fixedNow = new Set(done.map((draw) => draw.need));\n open = open.filter((draw) => !fixedNow.has(draw.need));\n }\n }\n\n const needs: Record<string, DrawEndurance> = {};\n if (draws.length === 0) return { case: caseCuts.case, at: options.at, needs };\n const last = buildStep(parts, caseCuts, draws, fixed, [], devices, \"span\");\n const least: Row = new Map();\n for (const block of last.blocks) for (const [resource, index] of block.shares) addTo(least, index, div(ONE, exact(stock.get(resource) ?? 1)));\n const objectives: Objective[] = [\n { sense: \"min\", coefficients: dense(least, last.program.count) },\n { sense: \"min\", coefficients: dense(fewestRow(last.blocks.flatMap((block) => [...block.runs])), last.program.count) },\n ];\n const solved = solveLexicographic(last.program.constraints(), objectives);\n if (solved.status !== \"optimal\") throw new Error(\"The last program of the best endurance has no optimum. The point of the last step is a point of it.\");\n const withStore = new Set(layer.stores.map((store) => store.resource));\n for (const block of last.blocks) {\n const need = block.draw.need;\n const fix = fixed.get(need) as Fixed;\n if (fix.endless) {\n needs[need] = { days: Infinity, binding: [], takes: {} };\n continue;\n }\n const takes: Record<string, number> = {};\n for (const [resource, index] of block.shares) if (sign(solved.x[index] ?? ZERO) > 0) takes[resource] = toNumber(solved.x[index] ?? ZERO);\n const { closure } = reachOf(parts, new Set([need]));\n const binding = [...closure]\n .filter((resource) => withStore.has(resource))\n .filter((resource) => {\n // A resource with no live stock has no share, so its take is 0 and it is used up.\n const taken = last.blocks.reduce((sum, item) => {\n const index = item.shares.get(resource);\n return index === undefined ? sum : add(sum, solved.x[index] ?? ZERO);\n }, ZERO);\n return equals(taken, exact(stock.get(resource) ?? 0));\n })\n .sort();\n const days = toNumber(fix.span);\n needs[need] = fix.capped.length === 0 ? { days, binding, takes } : { days, binding, takes, capped: fix.capped };\n }\n return { case: caseCuts.case, at: options.at, needs };\n}\n\n/** This function gives the draws of each level, in the order of `levels`. The draws of a level that is not in `levels` come last, together. */\nfunction levelGroups(layer: EnduranceLayer, draws: readonly Draw[]): Draw[][] {\n const rank = (draw: Draw): number => {\n const index = layer.levels.indexOf(draw.level);\n return index < 0 ? layer.levels.length : index;\n };\n const out: Draw[][] = [];\n let previous = -1;\n for (const draw of draws) {\n if (rank(draw) !== previous) out.push([]);\n previous = rank(draw);\n out[out.length - 1]?.push(draw);\n }\n return out;\n}\n\n/**\n * This function gives the program of one step. The fixed draws keep their spans and their device-days. The open draws have a common floor.\n *\n * - With `\"span\"`, each open draw has a column of its days, not less than the floor. Its runs share the device-days that the fixed draws leave, for the floor.\n * The device-days of each day are the runs over the span. A span not less than the floor uses fewer of them, so this is the safe side.\n * - With `\"day\"`, each open draw has a span of one day and takes no stock. Its runs share the device-days of one day.\n */\nfunction buildStep(\n parts: CaseParts,\n caseCuts: CaseCuts,\n draws: readonly Draw[],\n fixed: ReadonlyMap<string, Fixed>,\n open: readonly Draw[],\n devices: ReadonlyMap<string, number>,\n mode: \"span\" | \"day\",\n): Step {\n const program = new Program();\n const floor = program.next();\n const opened = new Set(open.map((draw) => draw.need));\n const blocks: DrawBlock[] = [];\n const floors = new Map<string, number>();\n const openRuns: (readonly [Converter, number])[] = [];\n const kept = new Map<string, Rational>();\n for (const draw of draws) {\n const fix = fixed.get(draw.need);\n if (fix === undefined && !opened.has(draw.need)) continue;\n const endless = fix?.endless ?? mode === \"day\";\n const block = drawBlock(program, parts, draw, !endless);\n blocks.push(block);\n const demand = exact(drawDemand(draw, caseCuts));\n const need: Row = new Map(block.gifts);\n if (fix !== undefined) {\n program.push(need, \">=\", mul(demand, fix.span));\n const { limits, stopped } = deviceUse(block.runs);\n for (const index of stopped) program.push(new Map([[index, ONE]]), \"<=\", ZERO);\n for (const [key, limit] of limits) program.push(limit.row, \"<=\", mul(fix.keep.get(key) ?? ZERO, fix.span));\n for (const [key, value] of fix.keep) kept.set(key, add(kept.get(key) ?? ZERO, value));\n continue;\n }\n openRuns.push(...block.runs);\n if (mode === \"day\") {\n program.push(need, \">=\", demand);\n continue;\n }\n const days = program.next();\n addTo(need, days, neg(demand));\n program.push(need, \">=\", ZERO);\n floors.set(draw.need, program.push(new Map([[days, ONE], [floor, neg(ONE)]]), \">=\", ZERO));\n }\n const shared = new Map<string, { row: Row; room: Rational; converters: readonly Converter[] }>();\n const { limits, stopped } = deviceUse(openRuns);\n for (const index of stopped) program.push(new Map([[index, ONE]]), \"<=\", ZERO);\n for (const [key, limit] of limits) {\n const left = sub(exact(devices.get(key) ?? limit.devices), kept.get(key) ?? ZERO);\n const room = sign(left) > 0 ? left : ZERO;\n shared.set(key, { row: limit.row, room, converters: limit.converters });\n if (mode === \"day\") {\n program.push(limit.row, \"<=\", room);\n continue;\n }\n const row: Row = new Map(limit.row);\n addTo(row, floor, neg(room));\n program.push(row, \"<=\", ZERO);\n }\n for (const resource of parts.stocked) {\n const row: Row = new Map();\n for (const block of blocks) {\n const index = block.shares.get(resource);\n if (index !== undefined) addTo(row, index, ONE);\n }\n if (row.size > 0) program.push(row, \"<=\", exact(parts.stock.get(resource) ?? 0));\n }\n return { program, blocks, floor, floors, openRuns, shared };\n}\n\n/**\n * This function fixes the open draws with no end. Each open draw takes no stock, and keeps the fewest device-days of each day.\n * A step with no largest floor has a direction with no take of a stock, so this program has a point.\n */\nfunction fixEndless(parts: CaseParts, caseCuts: CaseCuts, draws: readonly Draw[], fixed: Map<string, Fixed>, open: readonly Draw[], devices: ReadonlyMap<string, number>): void {\n const step = buildStep(parts, caseCuts, draws, fixed, open, devices, \"day\");\n const solved = solveLexicographic(step.program.constraints(), [{ sense: \"min\", coefficients: dense(fewestRow(step.openRuns), step.program.count) }]);\n if (solved.status !== \"optimal\") throw new Error(\"The draws with no end of the best endurance have no point of one day.\");\n for (const draw of open) {\n const block = step.blocks.find((item) => item.draw.need === draw.need) as DrawBlock;\n const keep = new Map<string, Rational>();\n for (const [key, limit] of deviceUse(block.runs).limits) keep.set(key, valueAt(limit.row, solved.x));\n fixed.set(draw.need, { span: ONE, endless: true, keep, capped: [] });\n }\n}\n","import { DEFAULT_MAX_SETS, stopSets, type Stack } from \"@mark1russell7/system-stack\";\n\n// The minimal stop sets of a supply from the structure of the needs. The index does not give this entry: `stopCurves` uses it.\n\n/**\n * This function gives the minimal sets of cuts that stop a supply, from the paths of the needs of the stack (`stopSets` of the core).\n * A set is a list of indexes of `parts`, from the smallest set. Two sets of one size are in the order of `minimalStops`.\n *\n * - `parts` has the part of each cut that counts. Two cuts of one part are two cuts: each one stops what the part stops.\n * - A cut of the supply stops it alone. The other sets come from `stopSets` with the cut parts as `among`, so no other part can fail.\n * - The parts of `down` are down for the full event. The caller makes sure that they do not stop the supply with no cut.\n * - The result is `undefined` when the search passes its budget, or when the sets of cuts are more than `maxSets`.\n *\n * @param stack - The base stack\n * @param supply - The part of the supply of a draw\n * @param parts - The part of each cut that counts\n * @param down - The parts that are down for the full event\n * @param maxSets - The largest count of sets in one step of the search, and of the sets of cuts (`maxSets` of `stopSets`)\n */\nexport function stackStops(stack: Stack, supply: string, parts: readonly string[], down: readonly string[] = [], maxSets: number = DEFAULT_MAX_SETS): number[][] | undefined {\n const cutsOf = new Map<string, number[]>();\n for (const [index, part] of parts.entries()) cutsOf.set(part, [...(cutsOf.get(part) ?? []), index]);\n const own = (cutsOf.get(supply) ?? []).map((index) => [index]);\n const among = [...cutsOf.keys()].filter((part) => part !== supply);\n const found = stopSets(stack, supply, { down, among, size: among.length, maxSets });\n if (found.kind === \"budget\") return undefined;\n // The empty set: the supply is not in the stack, or it does not work in the base stack.\n // In both, `stopped` of the core does not count it as stopped, so only a cut of the supply stops it.\n if (found.sets.some((set) => set.length === 0)) return own;\n const out = [...own];\n for (const set of found.sets) {\n // Each choice of one cut for each part of the set is a minimal set of cuts.\n let choices: number[][] = [[]];\n for (const part of set) {\n const cuts = cutsOf.get(part) ?? [];\n if (choices.length * cuts.length + out.length > maxSets) return undefined;\n choices = choices.flatMap((choice) => cuts.map((cut) => [...choice, cut]));\n }\n out.push(...choices.map((choice) => choice.sort((x, y) => x - y)));\n }\n return out.sort(byMask);\n}\n\n/** The order of `minimalStops`: the smaller set first, then the set whose largest different index is smaller. */\nfunction byMask(a: readonly number[], b: readonly number[]): number {\n if (a.length !== b.length) return a.length - b.length;\n for (let index = a.length - 1; index >= 0; index -= 1) {\n const difference = (a[index] ?? 0) - (b[index] ?? 0);\n if (difference !== 0) return difference;\n }\n return 0;\n}\n","import { type OrderedRing, pathSetReliability, stronglyConnectedComponents } from \"@mark1russell7/collections/graph\";\nimport { DEFAULT_MAX_SETS, neededParts, survivalAt, weakestBound, type CutBound, type PathOptions } from \"@mark1russell7/system-stack\";\nimport { caseDraws, caseStopped, enduranceOf, type CaseOptions } from \"./endurance.ts\";\nimport type { CaseCuts, Draw, Endurance, EnduranceLayer, Prior, Survival } from \"./layer.ts\";\nimport { stackStops } from \"./stops.ts\";\n\n// The shortfall: the user-days in which a draw does not get its need, for one case and for one year.\n\n/** The read of a curve at a time is in the core since system-stack 0.1.13. This package gives it again, so its API does not change. */\nexport { survivalAt };\n\n/**\n * This function gives the expected days of a cut after a time, up to a horizon: `E[max(0, min(D, to) - from)]`.\n * It is the area under the curve from `from` to `to`. The curve is linear between its points, so the area is exact.\n * With no horizon, the area goes to the end of the curve.\n */\nexport function tailDays(curve: Survival, from: number, to: number = Infinity): number {\n let area = 0;\n for (let index = 1; index < curve.length; index += 1) {\n const [t0] = curve[index - 1] ?? [0, 1];\n const [t1] = curve[index] ?? [0, 0];\n const start = Math.max(t0, from);\n const end = Math.min(t1, to);\n if (start < end) area += ((survivalAt(curve, start) + survivalAt(curve, end)) / 2) * (end - start);\n }\n return area;\n}\n\n/**\n * The options of a shortfall: the stack or the parts that are also down, as for `enduranceOf`, and a horizon.\n * With a horizon of `h` days, the shortfall counts only the first `h` days of each cut. A draw that holds `h` days has no shortfall.\n * Thus a plan can aim at a target, for example 14 days and then 90 days.\n */\n/**\n * The options of `stopCurves`. With a stack, `maxSets` is the budget of the search of the needs (`stopSets` of the core).\n * When the search passes it, `minimalStops` gives the sets.\n */\nexport interface StopCurveOptions extends Pick<CaseOptions, \"stack\" | \"down\">, Pick<PathOptions, \"maxSets\"> {\n /** The budget of `independentStop` for the curve of each draw, a whole number from 1. The default is `INDEPENDENT_MAX_WORK`. */\n readonly maxWork?: number | undefined;\n}\n\nexport interface ShortfallOptions extends StopCurveOptions {\n /** The horizon in days, more than 0. The default is no horizon. */\n readonly horizon?: number | undefined;\n}\n\nfunction horizonOf(options: ShortfallOptions): number {\n const horizon = options.horizon ?? Infinity;\n if (!(horizon > 0)) throw new RangeError(`The horizon ${String(options.horizon)} is not a number of days more than 0.`);\n return horizon;\n}\n\nfunction budgetsOf(options: StopCurveOptions): { readonly maxSets: number; readonly maxWork: number } {\n const maxSets = options.maxSets ?? DEFAULT_MAX_SETS;\n if (!Number.isInteger(maxSets) || maxSets < 1) throw new RangeError(`The option maxSets is ${String(options.maxSets)}: it is not a whole number from 1.`);\n const maxWork = options.maxWork ?? INDEPENDENT_MAX_WORK;\n if (!Number.isInteger(maxWork) || maxWork < 1) throw new RangeError(`The option maxWork is ${String(options.maxWork)}: it is not a whole number from 1.`);\n return { maxSets, maxWork };\n}\n\n/**\n * This function gives the days at which the chance of the curve falls to `chance`. With `0.1`, it is the 90th percentile of the duration.\n * When the curve does not fall to `chance`, the result is `Infinity`.\n */\nexport function survivalQuantile(curve: Survival, chance: number): number {\n for (let index = 1; index < curve.length; index += 1) {\n const [t0, p0] = curve[index - 1] ?? [0, 1];\n const [t1, p1] = curve[index] ?? [0, 0];\n if (p0 <= chance) return t0;\n if (p1 <= chance) return t0 + ((p0 - chance) * (t1 - t0)) / (p0 - p1);\n }\n return Infinity;\n}\n\n/** This function gives the chance that a case reaches its place one or more times in one year: `1 - exp(-perYear * reach)`. */\nexport function yearChance(prior: Prior): number {\n return 1 - Math.exp(-prior.perYear * prior.reach);\n}\n\n/** This function gives the expected count of the events of a case at its place in one year: `perYear * reach`. */\nexport function yearRate(prior: Prior): number {\n return prior.perYear * prior.reach;\n}\n\n/** This function gives the times at which a curve of the result can bend: each point of each curve, and each crossing of two curves. */\nfunction bendTimes(curves: readonly Survival[]): number[] {\n const times = [...new Set(curves.flatMap((curve) => curve.map(([days]) => days)))].sort((x, y) => x - y);\n const out = new Set(times);\n for (let index = 1; index < times.length; index += 1) {\n const t0 = times[index - 1] ?? 0;\n const t1 = times[index] ?? 0;\n for (const [i, a] of curves.entries()) {\n for (const b of curves.slice(i + 1)) {\n const d0 = survivalAt(a, t0) - survivalAt(b, t0);\n const d1 = survivalAt(a, t1) - survivalAt(b, t1);\n if (d0 * d1 < 0) out.add(t0 + ((t1 - t0) * d0) / (d0 - d1));\n }\n }\n }\n return [...out].sort((x, y) => x - y);\n}\n\n/**\n * This function makes a survival curve from a chance at each time. It stops at the first chance of 0, and it removes an increase of rounding.\n *\n * @throws RangeError when the chance at the last time is more than 0, as for curves that do not end at a chance of 0\n */\nfunction curveFrom(times: readonly number[], chanceAt: (days: number) => number): Survival {\n const out: [number, number][] = [];\n for (const days of times) {\n const chance = Math.min(out[out.length - 1]?.[1] ?? 1, chanceAt(days));\n out.push([days, chance]);\n if (chance === 0) return out;\n }\n throw new RangeError(\"The curves do not fall to a chance of 0 at their last point.\");\n}\n\n/**\n * This function gives the curve of a stop of some cuts when one event makes each cut longer together.\n * At each time, the chance is the largest `s` at which the cuts with a chance of `s` or more stop the supply.\n *\n * - When any one cut stops the supply, the result is the largest chance of the curves (`longestStop`).\n * - When the supply needs `any` of two parts, the stop ends with the shorter of the two cuts.\n * - Between two times of `bendTimes` the order of the curves does not change. So the result is linear between its points.\n * - When no set of cuts stops the supply, the result is `[[0, 0]]`. This curve does not start at `[0, 1]`, so `checkEndurance` refuses it.\n *\n * The result is not a limit. When the cuts are independent, a stop of two cuts in series can be longer. A stop through a need of `any` can be shorter.\n *\n * @param curves - The curves of the cuts, each one good for `checkEndurance`\n * @param stops - This function tells if the cuts of a list of indexes stop the supply. A larger list stops it when a smaller list does.\n * @throws RangeError when a curve does not end at a chance of 0\n */\nexport function eventStop(curves: readonly Survival[], stops: (cuts: readonly number[]) => boolean): Survival {\n return curveFrom(bendTimes(curves), (days) => {\n const chances = curves.map((curve) => survivalAt(curve, days));\n for (const level of [...new Set(chances)].sort((x, y) => y - x)) {\n if (stops(chances.flatMap((chance, index) => (chance >= level ? [index] : [])))) return level;\n }\n return 0;\n });\n}\n\n/**\n * This function gives the curve of the longest of some stops: at each time, the largest chance of the curves.\n * It is `eventStop` when any one cut stops the supply.\n *\n * @param curves - The curves, each one good for `checkEndurance`\n * @throws RangeError when there is no curve, or when a curve does not end at a chance of 0\n */\nexport function longestStop(curves: readonly Survival[]): Survival {\n const first = curves[0];\n if (first === undefined) throw new RangeError(\"longestStop needs one or more curves.\");\n return curves.length === 1 ? first : eventStop(curves, (cuts) => cuts.length > 0);\n}\n\n/**\n * The largest count of cuts for which `minimalStops` examines each set, and for which `independentStop` adds the chance of each state.\n * With a stack, `stopCurves` finds the minimal sets from the needs, so a larger count of cuts can have exact sets.\n */\nexport const MINIMAL_STOP_CUTS = 12;\n\n/**\n * This function gives the minimal sets of cuts that stop the supply: each set stops it, and no smaller part of a set stops it.\n * With more than `MINIMAL_STOP_CUTS` cuts, the result is `undefined`.\n */\nexport function minimalStops(count: number, stops: (cuts: readonly number[]) => boolean): number[][] | undefined {\n if (count > MINIMAL_STOP_CUTS) return undefined;\n const found: number[][] = [];\n const masks: number[] = [];\n const all = Array.from({ length: 1 << count }, (_, mask) => mask).sort((x, y) => popCount(x) - popCount(y) || x - y);\n for (const mask of all) {\n if (mask === 0 || masks.some((other) => (other & mask) === other)) continue;\n const cuts = Array.from({ length: count }, (_, index) => index).filter((index) => (mask >> index) & 1);\n if (!stops(cuts)) continue;\n masks.push(mask);\n found.push(cuts);\n }\n return found;\n}\n\nfunction popCount(mask: number): number {\n let total = 0;\n for (let rest = mask; rest > 0; rest &= rest - 1) total += 1;\n return total;\n}\n\n/**\n * This function gives an upper limit of the curve of a stop for each dependence of the cuts.\n * At each time it is `min(1, sum over the minimal sets of the smallest chance of the set)`.\n * With no minimal sets, as for too many cuts, it is `min(1, sum of the chances)`.\n *\n * @param curves - The curves of the cuts\n * @param sets - The minimal sets of `minimalStops`, or `undefined`\n * @throws RangeError when a curve does not end at a chance of 0\n */\nexport function upperStop(curves: readonly Survival[], sets: readonly (readonly number[])[] | undefined): Survival {\n const groups = sets ?? curves.map((_, index) => [index]);\n const sum = (days: number): number => groups.reduce((total, set) => total + Math.min(...set.map((index) => survivalAt(curves[index] ?? [], days))), 0);\n // The sum is linear between two times of bendTimes. A point where it falls through 1 is a bend of min(1, sum).\n const times = bendTimes(curves);\n const bends = new Set(times);\n for (let index = 1; index < times.length; index += 1) {\n const t0 = times[index - 1] ?? 0;\n const t1 = times[index] ?? 0;\n const s0 = sum(t0) - 1;\n const s1 = sum(t1) - 1;\n if (s0 * s1 < 0) bends.add(t0 + ((t1 - t0) * s0) / (s0 - s1));\n }\n return curveFrom([...bends].sort((x, y) => x - y), (days) => Math.min(1, sum(days)));\n}\n\n/** The largest difference between `independentStop` and the true chance of a stop of independent cuts, at each time. */\nexport const INDEPENDENT_TOLERANCE = 1e-6;\n\n/**\n * The default budget of `independentStop` for its groups of more than `MINIMAL_STOP_CUTS` cuts.\n * The budget counts the steps of the expansion times the count of points of the curve.\n * It is near the work of the sum over the states of 12 cuts.\n */\nexport const INDEPENDENT_MAX_WORK: number = 2 ** 26;\n\n/**\n * This function gives the curve of a stop of some cuts when the cuts are independent.\n * At each time `t`, the supply is stopped when the cuts that are still on contain a minimal set.\n * Its chance is a sum over each set of cuts that stops the supply.\n * Each term is the product of `s(t)` for the cuts that are on, and of `1 - s(t)` for the other cuts.\n *\n * - When any one cut stops the supply, the result is `1 - prod(1 - s)`. It is not less than the longest cut (`eventStop`).\n * - When the supply needs `any` of two parts, the stop of the two is `s1 * s2`. It is not more than the shorter cut.\n * - The result is not more than `upperStop` of the same sets, because `upperStop` is a limit for each dependence.\n * - Between two points of the curves the chance is a polynomial, not a line. The function splits each such segment into equal pieces.\n * The chance is linear in each `s`, and each mixed second derivative is between -1 and 1.\n * Thus `|f''| <= (sum |s'|)^2 - sum s'^2`, and the line of a piece of length `h` is within `h^2 |f''| / 8` of the chance.\n * The count of pieces keeps each line within `INDEPENDENT_TOLERANCE`. With a margin of 10 %, the count of points is less than `n / sqrt(7.2 * INDEPENDENT_TOLERANCE)` plus the segments, for `n` cuts.\n *\n * - Up to `MINIMAL_STOP_CUTS` cuts in the sets, the function adds the chance of each of the 2 to the power of that count of states.\n * - Two groups of cuts that share no set are independent, so the chance that the supply works is the product over the groups.\n * For example, 20 stages of 2 feeds give 20 groups of 2 cuts.\n * - In a group of more than `MINIMAL_STOP_CUTS` cuts, it uses the Shannon expansion of `pathSetReliability` of collections.\n * The expansion merges two states with the same sets left, and it drops a set that holds another set.\n * - The expansion is exponential in the worst case. The groups share one budget, `maxWork`.\n * When the steps of the expansions times the count of points of the curve pass it, the result is `undefined`.\n *\n * @param curves - The curves of the cuts, each one good for `checkEndurance`\n * @param sets - The minimal sets of the cuts. With `undefined`, as for no minimal sets, the result is `undefined`. With no sets, it is `[[0, 0]]`\n * @param maxWork - The budget of the expansions of the groups of more than `MINIMAL_STOP_CUTS` cuts, a whole number from 1. The default is `INDEPENDENT_MAX_WORK`\n * @throws RangeError when a curve does not end at a chance of 0, or for a bad `maxWork`\n */\nexport function independentStop(curves: readonly Survival[], sets: readonly (readonly number[])[] | undefined, maxWork: number = INDEPENDENT_MAX_WORK): Survival | undefined {\n if (!Number.isInteger(maxWork) || maxWork < 1) throw new RangeError(`The budget maxWork is ${String(maxWork)}: it is not a whole number from 1.`);\n if (sets === undefined) return undefined;\n // With no set, no cuts stop the supply, as for `eventStop` and `upperStop`.\n if (sets.length === 0) return [[0, 0]];\n // Only the cuts of a set change the chance. Their place in `used` is their index in the sets of the cuts that count.\n const used = [...new Set(sets.flat())].sort((x, y) => x - y);\n const usedCurves = used.map((index) => curves[index] ?? []);\n const usedSets = sets.map((set) => set.map((index) => used.indexOf(index)));\n const points = independentPoints(usedCurves);\n // Two groups of cuts that share no set are independent: the supply works when it works in each group.\n const groupChances: ((days: number) => number)[] = [];\n // The expansions of all groups share one budget.\n let work = maxWork;\n for (const group of cutGroups(used.length, usedSets)) {\n const curvesOf = group.map((index) => usedCurves[index] ?? []);\n const setsOf = usedSets.filter((set) => group.includes(set[0] ?? -1)).map((set) => set.map((index) => group.indexOf(index)));\n // Up to MINIMAL_STOP_CUTS cuts, the sum over the states is exact with a fixed cost. Past them, the expansion is exact within its budget.\n if (group.length <= MINIMAL_STOP_CUTS) {\n groupChances.push(stateChance(curvesOf, setsOf));\n continue;\n }\n const expanded = expandedChances(curvesOf, setsOf, points, work);\n if (expanded === undefined) return undefined;\n work -= expanded.steps * points.length;\n const chanceOf = new Map(points.map((days, index) => [days, expanded.chances[index] ?? 0]));\n groupChances.push((days) => {\n const chance = chanceOf.get(days);\n if (chance === undefined) throw new Error(`The expansion has no chance at ${String(days)} days.`);\n return chance;\n });\n }\n // With one group, the chance of the group is the result, with no rounding of 1 - (1 - chance).\n const [only] = groupChances;\n if (groupChances.length === 1 && only !== undefined) return curveFrom(points, only);\n return curveFrom(points, (days) => Math.min(1, Math.max(0, 1 - groupChances.reduce((works, chanceAt) => works * (1 - chanceAt(days)), 1))));\n}\n\n/** The groups of the cuts `0` to `count - 1`: two cuts are in one group when a chain of sets joins them. Each set has its cuts in one group. */\nfunction cutGroups(count: number, sets: readonly (readonly number[])[]): number[][] {\n const next = Array.from({ length: count }, () => new Set<number>());\n // A cycle through the cuts of each set joins them both ways, so the strongly connected components are the groups.\n for (const set of sets) for (const [at, index] of set.entries()) next[index]?.add(set[(at + 1) % set.length] ?? index);\n return stronglyConnectedComponents(\n Array.from({ length: count }, (_, index) => index),\n (index) => next[index] ?? [],\n );\n}\n\n/** The times of `independentStop`: the points of the curves, and the pieces that keep each line within `INDEPENDENT_TOLERANCE`. */\nfunction independentPoints(curves: readonly Survival[]): number[] {\n const times = [...new Set(curves.flatMap((curve) => curve.map(([days]) => days)))].sort((x, y) => x - y);\n const points: number[] = [];\n for (const [index, t1] of times.entries()) {\n const t0 = times[index - 1];\n if (t0 !== undefined) {\n const h = t1 - t0;\n const slopes = curves.map((curve) => Math.abs(survivalAt(curve, t1) - survivalAt(curve, t0)) / h);\n const sum = slopes.reduce((total, slope) => total + slope, 0);\n const bound = Math.max(0, sum * sum - slopes.reduce((total, slope) => total + slope * slope, 0));\n // A margin of 10 % keeps the rounding of the chance under the tolerance.\n const pieces = Math.ceil(h * Math.sqrt(bound / (8 * 0.9 * INDEPENDENT_TOLERANCE)));\n for (let piece = 1; piece < pieces; piece += 1) {\n const days = t0 + (h * piece) / pieces;\n // Two times that are next to each other as floats have no time between them.\n if (days > (points[points.length - 1] ?? t0) && days < t1) points.push(days);\n }\n }\n points.push(t1);\n }\n return points;\n}\n\n/** The chance of a stop at a time, as the sum over each state of `MINIMAL_STOP_CUTS` cuts or fewer. Bit k of a state is 1 when cut k is on. */\nfunction stateChance(curves: readonly Survival[], sets: readonly (readonly number[])[]): (days: number) => number {\n const setMasks = sets.map((set) => set.reduce((mask, index) => mask | (1 << index), 0));\n const stopping = Array.from({ length: 1 << curves.length }, (_, mask) => setMasks.some((set) => (set & mask) === set));\n const states = new Float64Array(1 << curves.length);\n return (days) => {\n // The chance of each state of the cuts, one cut at a time.\n states[0] = 1;\n let length = 1;\n for (const curve of curves) {\n const on = survivalAt(curve, days);\n for (let mask = 0; mask < length; mask += 1) {\n const chance = states[mask] ?? 0;\n states[mask + length] = chance * on;\n states[mask] = chance * (1 - on);\n }\n length *= 2;\n }\n let total = 0;\n for (let mask = 0; mask < length; mask += 1) if (stopping[mask]) total += states[mask] ?? 0;\n return Math.min(1, Math.max(0, total));\n };\n}\n\n/** The count of times in one expansion of `expandedChances`: the length of the vectors of its ring. */\nconst EXPANSION_WIDTH = 64;\n\n/**\n * The ring of the vectors of `width` chances, one for each time, for `pathSetReliability` of collections.\n * Each operation is on each time alone. In the order, `a` is less than `b` when it is less or equal at each time, and not equal.\n */\nfunction vectorRing(width: number): OrderedRing<Float64Array> {\n const zip = (a: Float64Array, b: Float64Array, op: (x: number, y: number) => number): Float64Array => {\n const out = new Float64Array(width);\n for (let index = 0; index < width; index += 1) out[index] = op(a[index] ?? 0, b[index] ?? 0);\n return out;\n };\n return {\n zero: new Float64Array(width),\n one: new Float64Array(width).fill(1),\n add: (a, b) => zip(a, b, (x, y) => x + y),\n sub: (a, b) => zip(a, b, (x, y) => x - y),\n mul: (a, b) => zip(a, b, (x, y) => x * y),\n compare: (a, b) => {\n let less = false;\n let more = false;\n for (let index = 0; index < width; index += 1) {\n const [x, y] = [a[index] ?? 0, b[index] ?? 0];\n if (x < y) less = true;\n else if (x > y) more = true;\n else if (x !== y) return Number.NaN;\n }\n return less ? (more ? Number.NaN : -1) : more ? 1 : 0;\n },\n };\n}\n\n/**\n * The chance of a stop at each point, from the Shannon expansion of `pathSetReliability`. A set works when each of its cuts is on.\n * One call gives `EXPANSION_WIDTH` points. When the steps of one expansion times the count of points pass `maxWork`, the result is `undefined`.\n * Else `steps` is the count of steps of one expansion.\n */\nfunction expandedChances(\n curves: readonly Survival[],\n sets: readonly (readonly number[])[],\n points: readonly number[],\n maxWork: number,\n): { readonly chances: number[]; readonly steps: number } | undefined {\n const maxSteps = Math.floor(maxWork / points.length);\n if (maxSteps < 1) return undefined;\n const out: number[] = [];\n let steps = 0;\n for (let start = 0; start < points.length; start += EXPANSION_WIDTH) {\n const times = points.slice(start, start + EXPANSION_WIDTH);\n const chances = curves.map((curve) => Float64Array.from(times, (days) => survivalAt(curve, days)));\n const result = pathSetReliability(sets, chances, vectorRing(times.length), { maxSteps });\n // Each call has the same sets, so the first call tells if the expansion is in the budget.\n if (result.kind === \"budget\") return undefined;\n steps = result.steps;\n for (const chance of result.value) out.push(Math.min(1, Math.max(0, chance)));\n }\n return { chances: out, steps };\n}\n\n/**\n * The curves of the stop of a draw. `event` is for one event that makes each cut longer together, and `independent` is for independent cuts.\n * `upper` is an upper limit for each dependence.\n */\nexport interface StopCurves {\n readonly event: Survival;\n /** The stop when the cuts are independent (`independentStop`). When `independentUpper` is true, it is `upper`. */\n readonly independent: Survival;\n readonly upper: Survival;\n /**\n * This is true when `upper` is the sum of the curves of the cuts that count, because the query has no minimal sets.\n * With a stack, the search of the needs passed its budget. With no stack, more than `MINIMAL_STOP_CUTS` cuts count.\n */\n readonly coarse: boolean;\n /** This is true when `independent` is `upper`: `coarse` is true, or the expansion of `independentStop` passed its budget. */\n readonly independentUpper: boolean;\n /**\n * The weakest bound (`weakestBound` of the core) of the curves of the cuts that the stop uses. Since 0.8.4.\n * With minimal sets, the stop uses the cuts of the sets. With no minimal sets, it uses each cut with a curve.\n * Each of the three curves does not decrease when a cut lasts longer, so it has this bound.\n */\n readonly bound: CutBound;\n}\n\n/** This function gives the parts of the stack that are down for a list of cut indexes. A case uses one memo for each of its draws. */\ntype StoppedOf = (cuts: readonly number[]) => ReadonlySet<string>;\n\nfunction stoppedMemo(caseCuts: CaseCuts, options: Pick<CaseOptions, \"stack\" | \"down\">): StoppedOf {\n const memo = new Map<string, ReadonlySet<string>>();\n return (cuts) => {\n const key = cuts.join(\",\");\n let found = memo.get(key);\n if (found === undefined) {\n found = caseStopped({ ...caseCuts, cuts: cuts.flatMap((index) => caseCuts.cuts[index] ?? []) }, options);\n memo.set(key, found);\n }\n return found;\n };\n}\n\n/** This function gives the parts whose cut can stop a supply: the supply, and each part that it needs through the stack. */\nfunction supplyReach(supply: string, options: Pick<CaseOptions, \"stack\">): Set<string> {\n const reach = options.stack === undefined ? new Set<string>() : neededParts(options.stack, supply);\n reach.add(supply);\n return reach;\n}\n\nfunction stopCurvesWith(caseCuts: CaseCuts, draw: Draw, options: StopCurveOptions, stoppedOf: StoppedOf): StopCurves | undefined {\n const reach = supplyReach(draw.supply, options);\n const relevant = caseCuts.cuts.flatMap((cut, index) => (reach.has(cut.part) ? [index] : []));\n const stops = (cuts: readonly number[]): boolean => stoppedOf(cuts.map((index) => relevant[index] ?? -1)).has(draw.supply);\n if (stops([])) return undefined;\n if (!stops(relevant.map((_, index) => index))) return undefined;\n const given = relevant.map((index) => caseCuts.cuts[index]?.duration);\n // With a stack, the needs give the minimal sets. When their search passes its budget, the sets of each list of cuts are the check.\n const parts = relevant.map((index) => caseCuts.cuts[index]?.part ?? \"\");\n const structural = options.stack === undefined ? undefined : stackStops(options.stack, draw.supply, parts, options.down, budgetsOf(options).maxSets);\n const sets = structural ?? minimalStops(given.length, stops);\n // The stop has no curve when a cut with no curve can be part of it. With no minimal sets, the query cannot tell.\n const unsourced = given.flatMap((curve, index) => (curve === undefined ? [index] : []));\n if (unsourced.length > 0 && (sets === undefined || sets.some((set) => set.some((index) => unsourced.includes(index))))) return undefined;\n // A cut with no curve is in no minimal set here, so it does not change a stop. The curves do not include it.\n const kept = given.flatMap((curve, index) => (curve === undefined ? [] : [index]));\n const curves = kept.map((index) => given[index] ?? []);\n const keptStops = (cuts: readonly number[]): boolean => stops(cuts.map((index) => kept[index] ?? -1));\n const keptSets = sets?.map((set) => set.map((index) => kept.indexOf(index)));\n const upper = upperStop(curves, keptSets);\n const independent = independentStop(curves, keptSets, budgetsOf(options).maxWork);\n // A cut in no minimal set does not change a stop, so its bound does not weaken the bound of the stop.\n const used = sets === undefined ? kept : kept.filter((index) => sets.some((set) => set.includes(index)));\n const bound = weakestBound(used.map((index) => caseCuts.cuts[relevant[index] ?? -1]?.bound ?? \"law\"));\n return { event: eventStop(curves, keptStops), independent: independent ?? upper, upper, coarse: keptSets === undefined, independentUpper: independent === undefined, bound };\n}\n\n/**\n * This function gives the curves of the duration of the stop of a draw, or `undefined` when the query has no curve.\n *\n * - A set of cuts stops the supply when the supply cannot work without the cut parts, through the needs of the stack.\n * - Only the cuts of the supply, and of the parts that it needs through the stack, count. Another cut does not change the curves.\n * - The parts of `down` are down for the full event. When they stop the supply with no cut, the query has no curve.\n * - With a stack, the minimal sets come from the paths of the needs (`stopSets` of the core), so the count of cuts has no limit of `MINIMAL_STOP_CUTS`.\n * When that search passes its budget (the option `maxSets`), `minimalStops` examines each set of up to `MINIMAL_STOP_CUTS` cuts.\n * - A cut with no `duration` gives no curve when it is in a minimal set, or when the query has no minimal sets.\n * - `event` is `eventStop`. `independent` is `independentStop`, and `upper` is `upperStop`, over the minimal sets of the cuts that count.\n * - With no minimal sets, `upper` is the sum of the curves, `independent` is `upper`, and `coarse` is true.\n * - When the expansion of `independentStop` passes its budget, `independent` is `upper`, and `independentUpper` is true.\n * - `bound` is the weakest bound of the curves of the cuts that the stop uses. A cut with no `bound` has a law.\n */\nexport function stopCurves(caseCuts: CaseCuts, draw: Draw, options: StopCurveOptions = {}): StopCurves | undefined {\n budgetsOf(options);\n return stopCurvesWith(caseCuts, draw, options, stoppedMemo(caseCuts, options));\n}\n\n/** The shortfall of each level, in user-days, and the draws that the query cannot read. */\nexport interface Shortfall {\n /**\n * The user-days of each level of the layer, when one event makes each cut longer together. The query does not add two levels.\n * This value is not a limit. The true value can be more or less. `upper` is the limit.\n */\n readonly levels: Readonly<Record<string, number>>;\n /** The user-days of each level when the cuts are independent (`StopCurves.independent`). This value is not more than `upper`. */\n readonly independent: Readonly<Record<string, number>>;\n /** The upper limit of the user-days of each level, for each dependence of the cuts. A gate of a high level can use it. */\n readonly upper: Readonly<Record<string, number>>;\n /**\n * The needs of the draws whose stop has no curve (`stopCurves`).\n * The query has no curve of their duration, so their shortfall is not in `levels`. A gate shows them as no read.\n */\n readonly unread: readonly string[];\n /** The needs of the draws whose `upper` is coarse (`StopCurves.coarse`). A gate on `upper` shows them. */\n readonly coarse: readonly string[];\n /** The needs of the draws whose `independent` is `upper` (`StopCurves.independentUpper`). A gate on `independent` shows them. */\n readonly independentUpper: readonly string[];\n /**\n * The bound of the shortfall: the weakest bound (`weakestBound` of the core) of the curves that the query uses. Since 0.8.4.\n * The shortfall does not decrease when a cut lasts longer. So with `upper`, each value is too high or equal, and with `lower` too low or equal.\n * With `none`, a value can be too high or too low.\n *\n * A draw in `unread` and a case that adds 0 do not change the bound. With no curve, the bound is `law`.\n * The bound is for each of `levels`, `independent` and `upper`, each with its own rule of the dependence of the cuts.\n */\n readonly bound: CutBound;\n}\n\nfunction zeroLevels(layer: EnduranceLayer): Record<string, number> {\n return Object.fromEntries(layer.levels.map((level) => [level, 0]));\n}\n\n/**\n * This function gives the shortfall of one event of a case: for each draw, `E[max(0, min(D, h) - T)] * users`.\n * `T` is the endurance of the draw, `D` is the duration of the stop of its supply (`stopCurves`), and `h` is the horizon.\n *\n * @param layer - The endurance layer\n * @param caseCuts - The case\n * @param endurance - The endurance of the case, from `enduranceOf`\n * @param options - The stack or the parts that are also down, as for `enduranceOf`, and the horizon\n * @throws RangeError when the horizon is not a number more than 0, or `maxSets` is not a whole number from 1\n */\nexport function caseShortfall(layer: EnduranceLayer, caseCuts: CaseCuts, endurance: Endurance, options: ShortfallOptions = {}): Shortfall {\n const horizon = horizonOf(options);\n budgetsOf(options);\n const levels = zeroLevels(layer);\n const independent = zeroLevels(layer);\n const upper = zeroLevels(layer);\n const unread: string[] = [];\n const coarse: string[] = [];\n const independentUpper: string[] = [];\n const bounds: CutBound[] = [];\n const stoppedOf = stoppedMemo(caseCuts, options);\n for (const draw of caseDraws(layer, caseCuts, caseStopped(caseCuts, options))) {\n const held = endurance.needs[draw.need];\n const curves = stopCurvesWith(caseCuts, draw, options, stoppedOf);\n if (held === undefined || curves === undefined) {\n unread.push(draw.need);\n continue;\n }\n if (curves.coarse) coarse.push(draw.need);\n if (curves.independentUpper) independentUpper.push(draw.need);\n bounds.push(curves.bound);\n const users = draw.users ?? 1;\n levels[draw.level] = (levels[draw.level] ?? 0) + tailDays(curves.event, held.days, horizon) * users;\n independent[draw.level] = (independent[draw.level] ?? 0) + tailDays(curves.independent, held.days, horizon) * users;\n upper[draw.level] = (upper[draw.level] ?? 0) + tailDays(curves.upper, held.days, horizon) * users;\n }\n return { levels, independent, upper, unread, coarse, independentUpper, bound: weakestBound(bounds) };\n}\n\n/** The shortfall of one year at one place, with the part of each case. */\nexport interface YearShortfall extends Shortfall {\n readonly place: string;\n /** The part of each case. `rate` is the expected count of its events in one year. */\n readonly cases: readonly { readonly case: string; readonly rate: number; readonly endurance: Endurance; readonly shortfall: Shortfall }[];\n}\n\n/**\n * This function gives the shortfall of one year at one place.\n * It is the sum over the cases of the layer of the expected count of the events of each case times its shortfall.\n *\n * - The expected count of a case is `perYear * reach`, from the first prior of the case at the place. Thus the result is the expected user-days of one year.\n * - A case with no prior at the place is not in the sum.\n * - `unread` is the union of the needs that a case cannot read, in the order of the cases. `coarse` and `independentUpper` are unions too.\n * - `bound` is the weakest bound of the cases in the sum. A case with no prior, or with an expected count of 0, adds 0, so it does not change the bound.\n *\n * @param layer - The endurance layer, with its cases and priors\n * @param place - The place of the priors\n * @param options - The date, the stack or the parts that are also down, and the horizon\n * @throws RangeError for a bad date, horizon or `maxSets`: refer to `caseShortfall` and `enduranceOf`\n */\nexport function yearShortfall(layer: EnduranceLayer, place: string, options: CaseOptions & ShortfallOptions): YearShortfall {\n horizonOf(options);\n budgetsOf(options);\n const levels = zeroLevels(layer);\n const independent = zeroLevels(layer);\n const upper = zeroLevels(layer);\n const unread: string[] = [];\n const coarse: string[] = [];\n const independentUpper: string[] = [];\n const cases: YearShortfall[\"cases\"][number][] = [];\n const bounds: CutBound[] = [];\n for (const caseCuts of layer.cases ?? []) {\n const prior = (layer.priors ?? []).find((item) => item.case === caseCuts.case && item.place === place);\n if (prior === undefined) continue;\n const rate = yearRate(prior);\n const endurance = enduranceOf(layer, caseCuts, options);\n const shortfall = caseShortfall(layer, caseCuts, endurance, options);\n for (const [level, days] of Object.entries(shortfall.levels)) levels[level] = (levels[level] ?? 0) + rate * days;\n for (const [level, days] of Object.entries(shortfall.independent)) independent[level] = (independent[level] ?? 0) + rate * days;\n for (const [level, days] of Object.entries(shortfall.upper)) upper[level] = (upper[level] ?? 0) + rate * days;\n for (const need of shortfall.unread) if (!unread.includes(need)) unread.push(need);\n for (const need of shortfall.coarse) if (!coarse.includes(need)) coarse.push(need);\n for (const need of shortfall.independentUpper) if (!independentUpper.includes(need)) independentUpper.push(need);\n if (rate > 0) bounds.push(shortfall.bound);\n cases.push({ case: caseCuts.case, rate, endurance, shortfall });\n }\n return { place, levels, independent, upper, unread, coarse, independentUpper, bound: weakestBound(bounds), cases };\n}\n","import { STACK_SCHEMA, type Stack } from \"@mark1russell7/system-stack\";\nimport { ENDURANCE_SCHEMA, type EnduranceLayer } from \"./layer.ts\";\n\n// A sample: a building with 3 users, and a storm that cuts the grid, the road and the water main.\n// Each name and each value is an example, except the grid curve (NREL, technical report 83092). The tests, the README files and the site use it.\n\n/** The base stack of the sample: the supplies of the building and a camp stove. */\nexport const SAMPLE_ENDURANCE_STACK: Stack = {\n schema: STACK_SCHEMA,\n parts: [\n { id: \"grid\", kind: \"power\", name: \"The power grid\" },\n { id: \"water-main\", kind: \"water\", name: \"The water main\" },\n { id: \"road\", kind: \"road\", name: \"The local road to the shops\" },\n { id: \"stove\", kind: \"device\", name: \"The camp stove\" },\n ],\n};\n\n/**\n * The endurance layer of the sample.\n *\n * - The drinking water holds 75.7 L / 11.355 L a day = 6.667 days.\n * - The food holds 4800 / 5400 = 0.889 days. The rice needs 2 L of water for each kg, and the drinking water keeps back all the water.\n * - The power holds 1000 Wh / 150 Wh a day = 6.667 days.\n * - The filled bottles are past their due date, so they give nothing.\n */\nexport const SAMPLE_ENDURANCE: EnduranceLayer = {\n schema: ENDURANCE_SCHEMA,\n levels: [\"life\", \"health\", \"comfort\"],\n resources: [\n { code: \"water.stored\", unit: \"L\" },\n { code: \"food.ready\", unit: \"kcal\" },\n { code: \"food.grain-dry\", unit: \"kg\" },\n { code: \"fuel.propane\", unit: \"kg\" },\n { code: \"energy.battery\", unit: \"Wh\" },\n ],\n stores: [\n { id: \"jugs\", resource: \"water.stored\", amount: 75.7, due: \"2028-06-01\" },\n { id: \"bottles\", resource: \"water.stored\", amount: 20, due: \"2026-09-30\" },\n { id: \"cans\", resource: \"food.ready\", amount: 4800, due: \"2028-10-01\" },\n { id: \"rice\", resource: \"food.grain-dry\", amount: 9, due: \"2036-09-28\" },\n { id: \"propane\", resource: \"fuel.propane\", amount: 0.908, due: \"2036-10-01\" },\n { id: \"battery\", resource: \"energy.battery\", amount: 1000, due: \"2031-10-01\" },\n ],\n draws: [\n { need: \"hydration.drink\", level: \"life\", perDay: 11.355, users: 3, supply: \"water-main\" },\n { need: \"food.energy\", level: \"health\", perDay: 5400, users: 3, supply: \"road\" },\n { need: \"power.electric\", level: \"comfort\", perDay: 150, users: 3, supply: \"grid\" },\n ],\n direct: [\n { resource: \"water.stored\", need: \"hydration.drink\", amount: 1 },\n { resource: \"food.ready\", need: \"food.energy\", amount: 1 },\n { resource: \"energy.battery\", need: \"power.electric\", amount: 1 },\n ],\n converters: [\n {\n id: \"cook-rice\",\n device: \"stove\",\n takes: [\n { resource: \"food.grain-dry\", amount: 1 },\n { resource: \"water.stored\", amount: 2 },\n { resource: \"fuel.propane\", amount: 0.05 },\n ],\n gives: { need: \"food.energy\", amount: 3600 },\n },\n ],\n cases: [\n {\n case: \"storm\",\n title: \"Winter storm\",\n cuts: [\n { part: \"grid\", title: \"Power outage\", duration: [[0, 1], [0.5, 0.5], [1, 0.36], [7, 0.013], [30, 0]], source: \"nrel-83092\" },\n { part: \"road\", title: \"Closed local road\", duration: [[0, 1], [1, 0.6], [3, 0.2], [10, 0]], source: \"sample\" },\n { part: \"water-main\", title: \"No water from the main\", duration: [[0, 1], [2, 0.3], [7, 0]], source: \"sample\" },\n ],\n leadSeconds: 86_400,\n },\n { case: \"fire\", title: \"Fire\", cuts: [] },\n ],\n priors: [\n { case: \"storm\", place: \"home\", perYear: 0.8, reach: 1, source: \"sample\", asOf: \"2025-12-01\" },\n { case: \"fire\", place: \"home\", perYear: 0.003, reach: 1, source: \"sample\", asOf: \"2025-12-01\" },\n ],\n};\n"],"mappings":";;;;;;;;AAkBA,IAAa,UAAb,MAAqB;CACnB,QAAQ;CACC,OAAkB,CAAC;;CAG5B,OAAe;EACb,OAAO,KAAK;CACd;;CAGA,KAAK,KAAU,UAAkC,KAAuB;EACtE,KAAK,KAAK,KAAK;GAAE;GAAK;GAAU;EAAI,CAAC;EACrC,OAAO,KAAK,KAAK,SAAS;CAC5B;;CAGA,cAA4B;EAC1B,OAAO,KAAK,KAAK,KAAK,EAAE,KAAK,UAAU,WAAW;GAAE,cAAc,MAAM,KAAK,KAAK,KAAK;GAAG;GAAU;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.7",
|
|
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": {
|
|
@@ -58,7 +58,7 @@
|
|
|
58
58
|
},
|
|
59
59
|
"devDependencies": {
|
|
60
60
|
"@mark1russell7/cue": "^2.0.0",
|
|
61
|
-
"@mark1russell7/rigor-bench": "^0.3.
|
|
61
|
+
"@mark1russell7/rigor-bench": "^0.3.7",
|
|
62
62
|
"@mark1russell7/rigor-statistics": "^0.2.23",
|
|
63
63
|
"@types/node": "^26.6.5",
|
|
64
64
|
"@vitest/coverage-v8": "^5.0.3",
|