@mark1russell7/stack-endurance 0.8.5 → 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/build/index.js CHANGED
@@ -1,9 +1,161 @@
1
1
  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
- import { DEFAULT_MAX_SETS, STACK_SCHEMA, neededParts, stopSets, weakestBound } from "@mark1russell7/system-stack";
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 direct = (layer.direct ?? []).filter((use) => planned.has(use.need) && use.amount > 0);
61
- const live = (layer.converters ?? []).filter((converter) => canRun(converter, stoppedParts));
62
- const cooks = live.filter((converter) => planned.has(giftNeed(converter) ?? ""));
63
- const makers = live.filter((converter) => giftResource(converter) !== void 0);
64
- const resources = /* @__PURE__ */ new Set([...direct.map((use) => use.resource), ...[...cooks, ...makers].flatMap((converter) => [...inputsOf(converter).keys()])]);
65
- for (const maker of makers) resources.add(giftResource(maker) ?? "");
66
- const stocked = [...resources].filter((resource) => (stock.get(resource) ?? 0) > 0).sort();
67
- let count = 0;
68
- const next = () => count++;
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 = new Map([...cooks.map((cook, c) => [cook, [cookCol[c]]]), ...makers.map((maker, m) => [maker, makerCol.map((row) => row[m])])]);
110
- const limits = /* @__PURE__ */ new Map();
111
- for (const [converter, indexes] of runCols) {
112
- if (converter.perDay === void 0) continue;
113
- if (!(converter.perDay > 0)) {
114
- for (const index of indexes) rows.push({
115
- row: /* @__PURE__ */ new Map([[index, ONE]]),
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 { row } of limits.values()) rows.push({
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 shares of shareCol) addTo(row, shares.get(resource), ONE);
138
- rows.push({
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 shares of shareCol) for (const [resource, index] of shares) addTo(least, index, div(ONE, exact(stock.get(resource) ?? 1)));
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(fewest, count)
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
- plan.forEach((draw, i) => {
256
+ for (const block of blocks) {
177
257
  const record = {};
178
- for (const [resource, index] of shareCol[i] ?? []) if (sign(at(index)) > 0) record[resource] = toNumber(at(index));
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 ran = (converter, value) => {
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 = inputClosure(direct.map((use) => use.resource), cooks, makers);
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 = shareCol.reduce((sum, shares) => {
192
- const index = shares.get(resource);
193
- return index === void 0 ? sum : add(sum, at(index));
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 used = (row) => [...row].reduce((sum, [index, value]) => add(sum, mul(value, at(index))), ZERO);
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 each resource that the plan can use: the direct resources and the inputs of the converters of the plan.
211
- * It also gives the inputs of their makers, through each chain.
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 inputClosure(direct, cooks, makers) {
214
- const out = /* @__PURE__ */ new Set();
215
- const queue = [...direct, ...cooks.flatMap((cook) => [...inputsOf(cook).keys()])];
216
- for (let resource = queue.shift(); resource !== void 0; resource = queue.shift()) {
217
- if (out.has(resource)) continue;
218
- out.add(resource);
219
- for (const maker of makers) if (giftResource(maker) === resource) queue.push(...inputsOf(maker).keys());
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).
@@ -271,20 +582,6 @@ function byMask(a, b) {
271
582
  return 0;
272
583
  }
273
584
  // src/shortfall.ts
274
- /** This function gives the chance that a cut lasts more than `days`, linear between the points of the curve. After the last point it is 0. */
275
- function survivalAt(curve, days) {
276
- if (days <= 0) return curve[0]?.[1] ?? 0;
277
- for (let index = 1; index < curve.length; index += 1) {
278
- const [t0, p0] = curve[index - 1] ?? [0, 1];
279
- const [t1, p1] = curve[index] ?? [0, 0];
280
- if (days < t1) {
281
- const chance = p0 + (p1 - p0) * ((days - t0) / (t1 - t0));
282
- return Math.min(Math.max(p0, p1), Math.max(Math.min(p0, p1), chance));
283
- }
284
- if (days === t1) return p1;
285
- }
286
- return 0;
287
- }
288
585
  /**
289
586
  * This function gives the expected days of a cut after a time, up to a horizon: `E[max(0, min(D, to) - from)]`.
290
587
  * It is the area under the curve from `from` to `to`. The curve is linear between its points, so the area is exact.
@@ -1017,6 +1314,6 @@ const SAMPLE_ENDURANCE = {
1017
1314
  asOf: "2025-12-01"
1018
1315
  }]
1019
1316
  };
1020
- 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 };
1021
1318
 
1022
1319
  //# sourceMappingURL=index.js.map