@mark1russell7/stack-endurance 0.8.28 → 0.8.30

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,10 +1,1678 @@
1
1
  import { t as ENDURANCE_SCHEMA } from "./layer-a3Fr70Uh.js";
2
- import { A as deviceUse, C as fixStops, D as storeCapacities, E as seasonPlan, F as addTo, I as dense, L as exact, M as fewestRow, N as reachOf, O as Program, P as valueAt, R as deviceKey, S as firstStop, T as seasonJoint, _ as seasonSupply, a as hasEnduranceError, b as storeAmounts, c as caseStopped, d as giftNeed, f as giftResource, g as monthlyShares, h as monthOf, i as curveFault, j as drawBlock, k as caseParts, l as drawDemand, m as monthEdges, n as ENDURANCE_CODES, o as SEASON_HORIZON_DAYS, p as hasSeason, r as checkEndurance, s as caseDraws, t as joinEndurance, u as enduranceOf, v as shareOf, w as seasonBest, x as fewestOpen, y as sowDays, z as isSource } from "./join-r5ht3vQ9.js";
3
- import { DEFAULT_MAX_SETS, STACK_SCHEMA, countsFault, dateOfDay, dayNumber, neededParts, stopSets, survivalAt, weakestBound } from "@mark1russell7/system-stack";
4
- import { ONE, ZERO, add, div, equals, mul, neg, sign, sub, toNumber } from "@mark1russell7/rational";
2
+ import { a as hasEnduranceError, c as giftNeed, d as isSource, f as monthlyShares, i as curveFault, l as giftResource, n as ENDURANCE_CODES, o as canRun, p as shareOf, r as checkEndurance, s as deviceKey, t as joinEndurance, u as inputsOf } from "./join-CsR-FKzr.js";
3
+ import { DEFAULT_MAX_SETS, STACK_SCHEMA, countsFault, dateOfDay, dayNumber, neededParts, stopSets, stopped, sumsFault, survivalAt, weakestBound } from "@mark1russell7/system-stack";
4
+ import { ONE, ZERO, add, div, equals, fromFloat, mul, neg, sign, sub, toNumber } from "@mark1russell7/rational";
5
5
  import { solveLexicographic } from "@mark1russell7/linear";
6
6
  import { pathSetReliability, stronglyConnectedComponents } from "@mark1russell7/collections/graph";
7
- import { Z95, kaplanMeier, survivalDifference } from "@mark1russell7/rigor-statistics";
7
+ import { Z95, greenwoodRead, kaplanMeier, survivalCombination } from "@mark1russell7/rigor-statistics";
8
+ // src/fit.ts
9
+ /** The relative tolerance of a take and of a fit. */
10
+ const TOLERANCE = 1e-13;
11
+ /**
12
+ * The count of the tries of `largestFit`, for the tests of the cost. It is not in the public API, and it does not change a result.
13
+ * It is the one side effect of `largestFit` and of the queries that use it.
14
+ */
15
+ const fitTries = { count: 0 };
16
+ /**
17
+ * This function gives the largest `x` in `[0, most]` at which `attempt` has no shortfall, to the relative tolerance `TOLERANCE`.
18
+ *
19
+ * - A try fits when its shortfall is not more than `TOLERANCE` times its need.
20
+ * - The shortfall must not decrease when `x` increases. A take of a chain of converters gives a shortfall that is linear in parts.
21
+ * - The first try is `most`. After it, each step tries the zero of the line through the last two tries that do not fit.
22
+ * With one try that does not fit, the step tries `x` times the part of the need that the stores gave.
23
+ * - When a step does not halve the interval, the next step is a bisection. Thus a fit takes at most approximately twice the steps of a bisection.
24
+ * - A step on the lower end tries a point just above it, so a correct estimate ends the fit in one more try.
25
+ * - An estimate that fits with a shortfall above 0 is in the band of the tolerance above the zero, so the fit ends there.
26
+ * A bisection step or a probe at the lower end can fit with a shortfall of rounding below the zero. The fit does not end there.
27
+ *
28
+ * @param most - The upper limit of `x`
29
+ * @param attempt - The try at an amount. It must not change its input
30
+ * @returns The largest amount that fits, and the value of its try
31
+ */
32
+ function largestFit(most, attempt) {
33
+ const fits = (tried) => tried.short <= TOLERANCE * tried.need;
34
+ fitTries.count += 1;
35
+ const first = attempt(most);
36
+ if (fits(first)) return {
37
+ x: most,
38
+ value: first.value
39
+ };
40
+ let low = 0;
41
+ let best;
42
+ let high = most;
43
+ let highShort = first.short;
44
+ let highNeed = first.need;
45
+ let before;
46
+ let bisect = false;
47
+ for (let step = 0; step < 400 && high - low > 4e-13 * high; step += 1) {
48
+ const width = high - low;
49
+ let x;
50
+ if (bisect) x = (low + high) / 2;
51
+ else if (before !== void 0 && before.short > highShort) x = high - highShort * (before.x - high) / (before.short - highShort);
52
+ else x = high * (1 - highShort / highNeed);
53
+ const estimate = !bisect && x < high;
54
+ if (!(x < high)) x = (low + high) / 2;
55
+ const floor = low + 2 * TOLERANCE * high;
56
+ const clamped = !(x > floor);
57
+ if (clamped) x = floor;
58
+ fitTries.count += 1;
59
+ const tried = attempt(x);
60
+ if (fits(tried)) {
61
+ low = x;
62
+ best = tried.value;
63
+ if (tried.short > 0 && estimate && !clamped) break;
64
+ } else {
65
+ before = {
66
+ x: high,
67
+ short: highShort
68
+ };
69
+ high = x;
70
+ highShort = tried.short;
71
+ highNeed = tried.need;
72
+ }
73
+ bisect = !bisect && high - low > width / 2;
74
+ }
75
+ return {
76
+ x: low,
77
+ value: best
78
+ };
79
+ }
80
+ // src/calendar.ts
81
+ /** This function gives the day number of a date, or throws a `RangeError` for a date that is not `YYYY-MM-DD`. */
82
+ function dayOf(date) {
83
+ const day = dayNumber(date);
84
+ if (day === void 0) throw new RangeError(`The date "${date}" is not a date YYYY-MM-DD.`);
85
+ return day;
86
+ }
87
+ const DAY_MS = 864e5;
88
+ /** This function gives the month of the day `day` after the start, 0 for January (M2-solar). It throws a `RangeError` for a bad date. */
89
+ function monthOf(start, day) {
90
+ dayOf(start);
91
+ return new Date(Date.parse(`${start}T00:00:00Z`) + Math.floor(day) * DAY_MS).getUTCMonth();
92
+ }
93
+ /**
94
+ * This function gives the days from the start to the first day of each month, in increasing order (M2-solar). Each
95
+ * day is more than 0 and less than the horizon. It throws a `RangeError` for a date that is not `YYYY-MM-DD`.
96
+ */
97
+ function monthEdges(start, horizon) {
98
+ dayOf(start);
99
+ const first = Date.parse(`${start}T00:00:00Z`);
100
+ const date = new Date(first);
101
+ const out = [];
102
+ for (let month = date.getUTCMonth() + 1;; month += 1) {
103
+ const day = Math.round((Date.UTC(date.getUTCFullYear(), month, 1) - first) / DAY_MS);
104
+ if (!(day < horizon)) break;
105
+ out.push(day);
106
+ }
107
+ return out;
108
+ }
109
+ // src/rows.ts
110
+ /** This function adds `value` to the coefficient of the variable `index` in `row`. It changes `row`. */
111
+ function addTo(row, index, value) {
112
+ row.set(index, add(row.get(index) ?? ZERO, value));
113
+ }
114
+ /** This function gives the dense form of a row: one coefficient for each of `count` variables. */
115
+ function dense(row, count) {
116
+ const out = new Array(count).fill(ZERO);
117
+ for (const [index, value] of row) out[index] = value;
118
+ return out;
119
+ }
120
+ /** This function gives the exact rational of a finite double, with no rounding. A double is a dyadic rational. */
121
+ function exact(value) {
122
+ return fromFloat(value);
123
+ }
124
+ // src/program.ts
125
+ /** A program in construction: the count of its variables and its rows. */
126
+ var Program = class {
127
+ count = 0;
128
+ rows = [];
129
+ /** This method adds a variable and gives its index. */
130
+ next() {
131
+ return this.count++;
132
+ }
133
+ /** This method adds a row and gives its index. */
134
+ push(row, relation, rhs) {
135
+ this.rows.push({
136
+ row,
137
+ relation,
138
+ rhs
139
+ });
140
+ return this.rows.length - 1;
141
+ }
142
+ /** This method gives the dense rows for `solveLexicographic`. */
143
+ constraints() {
144
+ return this.rows.map(({ row, relation, rhs }) => ({
145
+ coefficients: dense(row, this.count),
146
+ relation,
147
+ rhs
148
+ }));
149
+ }
150
+ };
151
+ /** This function gives the parts of a case for the draws of `needs`. */
152
+ function caseParts(layer, stoppedParts, stock, needs) {
153
+ const direct = (layer.direct ?? []).filter((use) => needs.has(use.need) && use.amount > 0);
154
+ const live = (layer.converters ?? []).filter((converter) => converter.season === void 0 && canRun(converter, stoppedParts));
155
+ return partsOf(stock, direct, live.filter((converter) => needs.has(giftNeed(converter) ?? "")), live.filter((converter) => giftResource(converter) !== void 0));
156
+ }
157
+ /** This function gives the parts of a case from its stock, its direct uses, its cooks and its makers. */
158
+ function partsOf(stock, direct, cooks, makers) {
159
+ const resources = /* @__PURE__ */ new Set([...direct.map((use) => use.resource), ...[...cooks, ...makers].flatMap((converter) => [...inputsOf(converter).keys()])]);
160
+ for (const maker of makers) resources.add(giftResource(maker) ?? "");
161
+ return {
162
+ stock,
163
+ direct,
164
+ cooks,
165
+ makers,
166
+ resources,
167
+ stocked: [...resources].filter((resource) => (stock.get(resource) ?? 0) > 0).sort()
168
+ };
169
+ }
170
+ /**
171
+ * This function adds the columns of one draw to a program, and the balance row of each of its resources.
172
+ * In a balance row, the takes of the draw are not more than its share of the stock plus the gifts of its makers.
173
+ * The caller adds the row of the need, with the term of the days.
174
+ *
175
+ * A draw has columns and rows only for the resources and the makers that it can use (`reachOf`).
176
+ * A share of another resource or the runs of another maker cannot give the need of the draw. Thus the optimum of each program is the same.
177
+ * This keeps each program small: the programs are dense, so each column of each draw costs a column in each row.
178
+ *
179
+ * @param stocked - False for a draw that takes no stock. Its shares are not columns.
180
+ */
181
+ function drawBlock(program, parts, draw, stocked = true) {
182
+ const gifts = /* @__PURE__ */ new Map();
183
+ const { closure, reach } = reachOf(parts, /* @__PURE__ */ new Set([draw.need]));
184
+ const balance = new Map([...closure].map((resource) => [resource, /* @__PURE__ */ new Map()]));
185
+ const consume = (resource, index, amount) => addTo(balance.get(resource), index, amount);
186
+ for (const use of parts.direct) {
187
+ if (use.need !== draw.need) continue;
188
+ const index = program.next();
189
+ addTo(gifts, index, exact(use.amount));
190
+ consume(use.resource, index, ONE);
191
+ }
192
+ const runs = /* @__PURE__ */ new Map();
193
+ for (const cook of parts.cooks) {
194
+ if (giftNeed(cook) !== draw.need) continue;
195
+ const index = program.next();
196
+ runs.set(cook, index);
197
+ addTo(gifts, index, exact(cook.gives.amount));
198
+ for (const [resource, each] of inputsOf(cook)) consume(resource, index, exact(each));
199
+ }
200
+ for (const maker of parts.makers) {
201
+ if (!reach.has(maker)) continue;
202
+ const index = program.next();
203
+ runs.set(maker, index);
204
+ for (const [resource, each] of inputsOf(maker)) consume(resource, index, exact(each));
205
+ consume(giftResource(maker), index, neg(exact(maker.gives.amount)));
206
+ }
207
+ const shares = new Map(stocked ? parts.stocked.filter((resource) => closure.has(resource)).map((resource) => [resource, program.next()]) : []);
208
+ for (const [resource, index] of shares) consume(resource, index, neg(ONE));
209
+ for (const row of balance.values()) if (row.size > 0) program.push(row, "<=", ZERO);
210
+ return {
211
+ draw,
212
+ gifts,
213
+ shares,
214
+ runs
215
+ };
216
+ }
217
+ /**
218
+ * This function gives the device-days of each device of a set of run columns, by the key of the device (`deviceKey`).
219
+ * 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.
220
+ * 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.
221
+ */
222
+ function deviceUse(runs) {
223
+ const limits = /* @__PURE__ */ new Map();
224
+ const stopped = [];
225
+ for (const [converter, index] of runs) {
226
+ if (converter.perDay === void 0) continue;
227
+ if (!(converter.perDay > 0)) {
228
+ stopped.push(index);
229
+ continue;
230
+ }
231
+ const key = deviceKey(converter);
232
+ const limit = limits.get(key) ?? {
233
+ row: /* @__PURE__ */ new Map(),
234
+ devices: converter.devices ?? 1,
235
+ converters: []
236
+ };
237
+ limits.set(key, limit);
238
+ if (!limit.converters.includes(converter)) limit.converters.push(converter);
239
+ addTo(limit.row, index, div(ONE, exact(converter.perDay)));
240
+ }
241
+ return {
242
+ limits,
243
+ stopped
244
+ };
245
+ }
246
+ /**
247
+ * 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.
248
+ * As an objective, it gives no more runs than the plan uses.
249
+ */
250
+ function fewestRow(runs) {
251
+ const out = /* @__PURE__ */ new Map();
252
+ for (const [converter, index] of runs) addTo(out, index, converter.perDay !== void 0 && converter.perDay > 0 ? div(ONE, exact(converter.perDay)) : ONE);
253
+ return out;
254
+ }
255
+ /** This function gives the value of a sparse row at the point `x`. */
256
+ function valueAt(row, x) {
257
+ let out = ZERO;
258
+ for (const [index, value] of row) out = add(out, mul(value, x[index] ?? ZERO));
259
+ return out;
260
+ }
261
+ /**
262
+ * This function gives each resource that a draw can use: the resources of its direct uses and the inputs of its cooks.
263
+ * It also gives the inputs of their makers, through each chain.
264
+ */
265
+ function inputClosure$1(direct, cooks, makers) {
266
+ const out = /* @__PURE__ */ new Set();
267
+ const queue = [...direct, ...cooks.flatMap((cook) => [...inputsOf(cook).keys()])];
268
+ for (let resource = queue.shift(); resource !== void 0; resource = queue.shift()) {
269
+ if (out.has(resource)) continue;
270
+ out.add(resource);
271
+ for (const maker of makers) if (giftResource(maker) === resource) queue.push(...inputsOf(maker).keys());
272
+ }
273
+ return out;
274
+ }
275
+ /** This function gives the resources that the draws of `needs` can use, and the converters that they can use. */
276
+ function reachOf(parts, needs) {
277
+ const cooks = parts.cooks.filter((cook) => needs.has(giftNeed(cook) ?? ""));
278
+ const closure = inputClosure$1(parts.direct.filter((use) => needs.has(use.need)).map((use) => use.resource), cooks, parts.makers);
279
+ return {
280
+ closure,
281
+ reach: /* @__PURE__ */ new Set([...cooks, ...parts.makers.filter((maker) => closure.has(giftResource(maker) ?? ""))])
282
+ };
283
+ }
284
+ // src/supply.ts
285
+ /** This function gives the amount of a need for each day in a case: the rate of the draw times the factor of the case. */
286
+ function drawDemand(draw, caseCuts) {
287
+ return draw.perDay * (caseCuts.factors?.[draw.need] ?? 1);
288
+ }
289
+ // src/seasonal.ts
290
+ /** This function gives the least of a list of rationals, or `none` for an empty list. */
291
+ function leastOf(values, none) {
292
+ let low;
293
+ for (const value of values) if (low === void 0 || sign(sub(value, low)) < 0) low = value;
294
+ return low ?? none;
295
+ }
296
+ /**
297
+ * This function gives the capacity of each resource whose stores have a capacity (M2-solar-charge). A store whose part is
298
+ * in `stoppedParts` has no capacity. A store with a due date has no charge: the gate refuses a capacity with a due date.
299
+ */
300
+ function storeCapacities(layer, stoppedParts) {
301
+ const out = /* @__PURE__ */ new Map();
302
+ for (const store of layer.stores) {
303
+ if (store.capacity === void 0 || store.due !== void 0) continue;
304
+ if (store.part !== void 0 && stoppedParts.has(store.part)) continue;
305
+ out.set(store.resource, (out.get(store.resource) ?? 0) + store.capacity);
306
+ }
307
+ return out;
308
+ }
309
+ /**
310
+ * This function gives the parts of the programs of a case with a season. `parts` are the parts of the case with the
311
+ * stock after the sowings (`seasonSupply`).
312
+ *
313
+ * @param rests - The rest of each store with a capacity that the higher draws of the sweep leave (M2-solar-charge-sweep).
314
+ * A segment gets the least rest of the spans that it touches. This is the safe side.
315
+ */
316
+ function seasonPlan(supply, parts, caseCuts, draws, devices, capacities = /* @__PURE__ */ new Map(), rests = /* @__PURE__ */ new Map()) {
317
+ const total = new Map(supply.stock);
318
+ const harvests = supply.lots.map((lot, origin) => ({
319
+ ...lot,
320
+ origin
321
+ })).filter((lot) => parts.resources.has(lot.resource));
322
+ for (const lot of harvests) total.set(lot.resource, (total.get(lot.resource) ?? 0) + lot.amount);
323
+ const found = partsOf(total, parts.direct, parts.cooks, parts.makers);
324
+ const sourcesOf = (resource) => found.makers.filter((maker) => isSource(maker) && giftResource(maker) === resource);
325
+ const charged = [...capacities.keys()].filter((resource) => found.resources.has(resource) && sourcesOf(resource).length > 0).sort();
326
+ const all = {
327
+ ...found,
328
+ stocked: [.../* @__PURE__ */ new Set([...found.stocked, ...charged])].sort()
329
+ };
330
+ const storeLot = (resource) => ({
331
+ resource,
332
+ day: 0,
333
+ spoils: 1e400,
334
+ amount: exact(supply.stock.get(resource) ?? 0)
335
+ });
336
+ const lots = [...all.stocked.filter((resource) => (supply.stock.get(resource) ?? 0) > 0 || charged.includes(resource)).map(storeLot), ...harvests.map((lot) => ({
337
+ resource: lot.resource,
338
+ day: Math.max(0, lot.day),
339
+ spoils: lot.spoils,
340
+ amount: exact(lot.amount),
341
+ origin: lot.origin
342
+ }))];
343
+ const inside = (day) => day > 0 && day < supply.horizon;
344
+ const shares = monthlyShares([...all.cooks, ...all.makers]);
345
+ const months = shares.size === 0 ? [] : monthEdges(supply.start, supply.horizon);
346
+ const edges = [.../* @__PURE__ */ new Set([
347
+ 0,
348
+ supply.horizon,
349
+ ...months,
350
+ ...lots.flatMap((lot) => [lot.day, lot.spoils]).filter(inside)
351
+ ])].sort((a, b) => a - b);
352
+ const charges = charged.map((resource) => {
353
+ const lot = lots.find((item) => item.resource === resource && item.origin === void 0);
354
+ const capacity = exact(Math.max(capacities.get(resource) ?? 0, toNumber(lot.amount)));
355
+ const rest = rests.get(resource) ?? [];
356
+ const spans = edges.slice(0, -1).map((from, index) => rest.filter((item) => item.from < (edges[index + 1] ?? 1e400) && item.to > from));
357
+ const take = spans.map((list) => leastOf(list.map((item) => item.take), lot.amount));
358
+ const fill = spans.map((list) => leastOf(list.map((item) => item.fill), sub(capacity, lot.amount)));
359
+ return {
360
+ resource,
361
+ capacity,
362
+ lot,
363
+ sources: sourcesOf(resource),
364
+ take,
365
+ fill,
366
+ higher: rest.length > 0
367
+ };
368
+ });
369
+ return {
370
+ parts: all,
371
+ caseCuts,
372
+ draws,
373
+ devices,
374
+ lots,
375
+ edges,
376
+ shares,
377
+ months: edges.slice(0, -1).map((edge) => shares.size === 0 ? 0 : monthOf(supply.start, edge)),
378
+ charges
379
+ };
380
+ }
381
+ const edgeOf = (plan, index) => exact(plan.edges[index] ?? 0);
382
+ const lengthOf = (plan, index) => sub(edgeOf(plan, index + 1), edgeOf(plan, index));
383
+ const segmentsOf = (plan) => plan.edges.length - 1;
384
+ /** This function gives the fed days of a fixed draw in a segment. It is all of a segment before the stop, the part to the stop, then 0. */
385
+ function fixedFed(plan, fix, segment) {
386
+ if (segment < fix.segment) return lengthOf(plan, segment);
387
+ if (segment === fix.segment) return sub(fix.stop, edgeOf(plan, segment));
388
+ return ZERO;
389
+ }
390
+ /**
391
+ * This function adds the columns of one draw in one segment. The gifts of the need are not less than the demand times the fed days.
392
+ * The share of each stock is the sum of the takes of the lots that are ready and not spoiled in the whole segment.
393
+ */
394
+ function addCell(program, plan, draw, segment, fed) {
395
+ const block = drawBlock(program, plan.parts, draw);
396
+ const demand = exact(drawDemand(draw, plan.caseCuts));
397
+ const need = new Map(block.gifts);
398
+ if (typeof fed === "number") {
399
+ addTo(need, fed, neg(demand));
400
+ program.push(need, ">=", ZERO);
401
+ } else program.push(need, ">=", mul(demand, fed));
402
+ const from = plan.edges[segment] ?? 0;
403
+ const to = plan.edges[segment + 1] ?? 1e400;
404
+ const takes = /* @__PURE__ */ new Map();
405
+ for (const [resource, share] of block.shares) {
406
+ const row = /* @__PURE__ */ new Map([[share, ONE]]);
407
+ for (const lot of plan.lots) {
408
+ if (lot.resource !== resource || lot.day > from || lot.spoils < to) continue;
409
+ const column = program.next();
410
+ takes.set(lot, column);
411
+ addTo(row, column, neg(ONE));
412
+ }
413
+ program.push(row, "=", ZERO);
414
+ }
415
+ return {
416
+ draw,
417
+ segment,
418
+ block,
419
+ fed,
420
+ takes
421
+ };
422
+ }
423
+ /** This function adds the row of each lot: the takes of all the cells are not more than its amount. The rows of `addCharges` cover the lot of a charge. */
424
+ function lotRows(program, plan, cells) {
425
+ const charged = new Set(plan.charges.map((charge) => charge.lot));
426
+ for (const lot of plan.lots) {
427
+ if (charged.has(lot)) continue;
428
+ const row = /* @__PURE__ */ new Map();
429
+ for (const cell of cells) {
430
+ const column = cell.takes.get(lot);
431
+ if (column !== void 0) addTo(row, column, ONE);
432
+ }
433
+ if (row.size > 0) program.push(row, "<=", lot.amount);
434
+ }
435
+ }
436
+ /**
437
+ * This function adds the charge of each store with a capacity in the segments before `through` (M2-solar-charge).
438
+ * Each source has one charge column in each segment before the last one: no take of the program uses the charge of the last one.
439
+ * The level at the start of a segment is the amount of the lot plus the charges of the segments before it, less their takes.
440
+ * - The takes of a segment are not more than the level at its start.
441
+ * - The level at the start of a segment plus its charge is not more than the capacity.
442
+ * Thus each order of the takes and the charges in a segment is a plan. The caller adds the charge columns to the rows of the device-days.
443
+ *
444
+ * With no higher draws, the right side of the takes is the amount of the lot. The right side of the charge is the capacity less that amount.
445
+ * With higher draws (M2-solar-charge-sweep), the right sides are the rest that they leave (`PlanCharge.take` and `fill`).
446
+ * Then each segment has the row of its charge, and two more rows keep the level after `through` in the rest of the later segments.
447
+ */
448
+ function addCharges(program, plan, cells, through) {
449
+ const pairs = /* @__PURE__ */ new Map();
450
+ const gifts = /* @__PURE__ */ new Map();
451
+ const segments = /* @__PURE__ */ new Map();
452
+ for (const charge of plan.charges) {
453
+ const level = /* @__PURE__ */ new Map();
454
+ const given = /* @__PURE__ */ new Map();
455
+ const each = [];
456
+ gifts.set(charge.resource, given);
457
+ segments.set(charge.resource, each);
458
+ for (let segment = 0; segment < through; segment += 1) {
459
+ const takes = /* @__PURE__ */ new Map();
460
+ for (const cell of cells) {
461
+ const column = cell.segment === segment ? cell.takes.get(charge.lot) : void 0;
462
+ if (column !== void 0) addTo(takes, column, ONE);
463
+ }
464
+ const most = new Map(takes);
465
+ for (const [column, value] of level) addTo(most, column, neg(value));
466
+ program.push(most, "<=", charge.take[segment] ?? charge.lot.amount);
467
+ const full = new Map(level);
468
+ const own = /* @__PURE__ */ new Map();
469
+ each.push(own);
470
+ if (segment + 1 < through) {
471
+ for (const source of charge.sources) {
472
+ const column = program.next();
473
+ pairs.set(segment, [...pairs.get(segment) ?? [], [source, column]]);
474
+ const amount = exact(source.gives.amount);
475
+ addTo(full, column, amount);
476
+ addTo(level, column, amount);
477
+ addTo(given, column, amount);
478
+ addTo(own, column, amount);
479
+ }
480
+ program.push(full, "<=", charge.fill[segment] ?? sub(charge.capacity, charge.lot.amount));
481
+ } else if (charge.higher) program.push(full, "<=", charge.fill[segment] ?? ZERO);
482
+ for (const [column, value] of takes) addTo(level, column, neg(value));
483
+ }
484
+ if (charge.higher && through < segmentsOf(plan)) {
485
+ const less = /* @__PURE__ */ new Map();
486
+ for (const [column, value] of level) addTo(less, column, neg(value));
487
+ program.push(less, "<=", leastOf(charge.take.slice(through), ZERO));
488
+ program.push(new Map(level), "<=", leastOf(charge.fill.slice(through), ZERO));
489
+ }
490
+ }
491
+ return {
492
+ pairs,
493
+ gifts,
494
+ segments
495
+ };
496
+ }
497
+ /**
498
+ * This function gives the most charge, the earliest first, as an objective (M2-solar-charge-sweep). The weight of the charge of
499
+ * a segment is the days from its start to the horizon. Thus the store keeps the highest level that it can for the lower draws.
500
+ */
501
+ function mostCharge(plan, charges, count) {
502
+ const most = /* @__PURE__ */ new Map();
503
+ const horizon = edgeOf(plan, segmentsOf(plan));
504
+ for (const rows of charges.segments.values()) rows.forEach((row, segment) => {
505
+ for (const [column, value] of row) addTo(most, column, mul(value, sub(horizon, edgeOf(plan, segment))));
506
+ });
507
+ return {
508
+ sense: "max",
509
+ coefficients: dense(most, count)
510
+ };
511
+ }
512
+ /**
513
+ * This function gives the rest of each store with a capacity in each segment (M2-solar-charge-sweep). It is the rest that the
514
+ * draws of a plan and the higher draws leave. The takes and the charges of the plan come out of the rest that the plan got.
515
+ */
516
+ function restsOf(plan, cells, x, charges) {
517
+ const out = /* @__PURE__ */ new Map();
518
+ for (const charge of plan.charges) {
519
+ const rows = charges.segments.get(charge.resource) ?? [];
520
+ let added = ZERO;
521
+ const list = [];
522
+ for (let segment = 0; segment < segmentsOf(plan); segment += 1) {
523
+ let taken = ZERO;
524
+ for (const cell of cells) if (cell.segment === segment) taken = add(taken, x[cell.takes.get(charge.lot) ?? -1] ?? ZERO);
525
+ const row = rows[segment];
526
+ const given = row === void 0 ? ZERO : valueAt(row, x);
527
+ const take = add(sub(charge.take[segment] ?? charge.lot.amount, taken), added);
528
+ const fill = sub(sub(charge.fill[segment] ?? ZERO, given), added);
529
+ list.push({
530
+ from: plan.edges[segment] ?? 0,
531
+ to: plan.edges[segment + 1] ?? 0,
532
+ take,
533
+ fill
534
+ });
535
+ added = add(added, sub(given, taken));
536
+ }
537
+ out.set(charge.resource, list);
538
+ }
539
+ return out;
540
+ }
541
+ /**
542
+ * This function gives the most device-days of one day that the charges of a plan use, by the key of the device (M2-solar-charge-sweep).
543
+ * The value comes before the shares `monthly`. The charge of a segment can come in equal parts on each of its days.
544
+ */
545
+ function chargeDaysOf(plan, charges, x) {
546
+ const out = /* @__PURE__ */ new Map();
547
+ for (const [segment, list] of charges.pairs) {
548
+ const length = toNumber(lengthOf(plan, segment));
549
+ if (!(length > 0)) continue;
550
+ for (const [key, limit] of deviceUse(list).limits) {
551
+ const share = shareIn(plan, segment, key);
552
+ if (share > 0) out.set(key, Math.max(out.get(key) ?? 0, toNumber(valueAt(limit.row, x)) / length / share));
553
+ }
554
+ }
555
+ return out;
556
+ }
557
+ /**
558
+ * This function adds the cells of the fixed draws. Each one is fed to its first stop, and its runs use the device-days of each day
559
+ * that it keeps. It gives the device-days of each day that the fixed draws keep, by the index of the segment, then the key.
560
+ */
561
+ function addFixed(program, plan, fixed, cells) {
562
+ const kept = /* @__PURE__ */ new Map();
563
+ for (const draw of plan.draws) {
564
+ const fix = fixed.get(draw.need);
565
+ if (fix === void 0) continue;
566
+ for (let segment = 0; segment <= fix.segment; segment += 1) {
567
+ const fed = fixedFed(plan, fix, segment);
568
+ const keep = fix.keep.get(segment) ?? /* @__PURE__ */ new Map();
569
+ const into = kept.get(segment) ?? /* @__PURE__ */ new Map();
570
+ kept.set(segment, into);
571
+ for (const [key, value] of keep) into.set(key, add(into.get(key) ?? ZERO, value));
572
+ if (sign(fed) <= 0) continue;
573
+ const cell = addCell(program, plan, draw, segment, fed);
574
+ cells.push(cell);
575
+ const { limits, stopped } = deviceUse(cell.block.runs);
576
+ for (const index of stopped) program.push(/* @__PURE__ */ new Map([[index, ONE]]), "<=", ZERO);
577
+ for (const [key, limit] of limits) program.push(limit.row, "<=", mul(keep.get(key) ?? ZERO, fed));
578
+ }
579
+ }
580
+ return kept;
581
+ }
582
+ /** The share of the device-days of a key in a segment (M2-solar): its share `monthly` in the month of the segment, or 1. */
583
+ function shareIn(plan, segment, key) {
584
+ return shareOf(plan.shares, key, plan.months[segment] ?? 0);
585
+ }
586
+ /** This function gives the device-days of each day that the fixed draws leave in a segment: the devices times the share, less the kept device-days. */
587
+ function roomOf(plan, kept, segment, key, devices) {
588
+ const left = sub(mul(exact(plan.devices.get(key) ?? devices), exact(shareIn(plan, segment, key))), kept.get(segment)?.get(key) ?? ZERO);
589
+ return sign(left) > 0 ? left : ZERO;
590
+ }
591
+ /**
592
+ * This function gives the program of one step with the stop of the open draws in segment `segment`. The open draws are fed in
593
+ * each segment before it. In it, each one is fed for `t - edge` days or more, and their runs share the device-days that
594
+ * the fixed draws leave, for `t - edge` days. This is the safe side, as in `bestEndurance`.
595
+ */
596
+ function buildStep$1(plan, fixed, open, segment) {
597
+ const program = new Program();
598
+ const t = program.next();
599
+ program.push(/* @__PURE__ */ new Map([[t, ONE]]), "<=", edgeOf(plan, segment + 1));
600
+ const cells = [];
601
+ const kept = addFixed(program, plan, fixed, cells);
602
+ const opened = new Set(open.map((draw) => draw.need));
603
+ const floors = /* @__PURE__ */ new Map();
604
+ for (const draw of plan.draws) {
605
+ if (!opened.has(draw.need)) continue;
606
+ for (let index = 0; index < segment; index += 1) cells.push(addCell(program, plan, draw, index, lengthOf(plan, index)));
607
+ const fed = program.next();
608
+ program.push(/* @__PURE__ */ new Map([[fed, ONE]]), "<=", lengthOf(plan, segment));
609
+ floors.set(draw.need, program.push(/* @__PURE__ */ new Map([[fed, ONE], [t, neg(ONE)]]), ">=", neg(edgeOf(plan, segment))));
610
+ cells.push(addCell(program, plan, draw, segment, fed));
611
+ }
612
+ const charges = addCharges(program, plan, cells, segment + 1);
613
+ const shared = /* @__PURE__ */ new Map();
614
+ for (let index = 0; index <= segment; index += 1) {
615
+ const { limits, stopped } = deviceUse([...cells.filter((cell) => cell.segment === index && opened.has(cell.draw.need)).flatMap((cell) => [...cell.block.runs]), ...charges.pairs.get(index) ?? []]);
616
+ for (const column of stopped) program.push(/* @__PURE__ */ new Map([[column, ONE]]), "<=", ZERO);
617
+ const bySegment = /* @__PURE__ */ new Map();
618
+ shared.set(index, bySegment);
619
+ for (const [key, limit] of limits) {
620
+ const room = roomOf(plan, kept, index, key, limit.devices);
621
+ bySegment.set(key, {
622
+ row: limit.row,
623
+ room,
624
+ converters: limit.converters
625
+ });
626
+ const row = new Map(limit.row);
627
+ if (index < segment) program.push(row, "<=", mul(room, lengthOf(plan, index)));
628
+ else {
629
+ addTo(row, t, neg(room));
630
+ program.push(row, "<=", neg(mul(room, edgeOf(plan, segment))));
631
+ }
632
+ }
633
+ }
634
+ lotRows(program, plan, cells);
635
+ return {
636
+ program,
637
+ t,
638
+ cells,
639
+ floors,
640
+ shared,
641
+ segment,
642
+ charges
643
+ };
644
+ }
645
+ /**
646
+ * This function gives the largest common first stop of the open draws, with the fixed draws at their stops. The days to
647
+ * a first stop are not a linear function of the takes, so the function tries the segments in order. When the days reach
648
+ * the end of a segment, it tries the next segment. The days of the last step are exact.
649
+ * After the largest days, the step takes the objectives of `tail`.
650
+ */
651
+ function firstStop(plan, fixed, open, tail = () => []) {
652
+ const segments = segmentsOf(plan);
653
+ for (let segment = 0; segment < segments; segment += 1) {
654
+ const step = buildStep$1(plan, fixed, open, segment);
655
+ const most = {
656
+ sense: "max",
657
+ coefficients: dense(/* @__PURE__ */ new Map([[step.t, ONE]]), step.program.count)
658
+ };
659
+ const solved = solveLexicographic(step.program.constraints(), [most]);
660
+ if (solved.status !== "optimal") throw new Error("The step of a season has no optimum. The point of the stop of the last segment is a point of it.");
661
+ const days = solved.values[0] ?? ZERO;
662
+ const end = edgeOf(plan, segment + 1);
663
+ if (segment + 1 < segments && equals(days, end)) continue;
664
+ const later = tail(step);
665
+ const full = later.length === 0 ? solved : solveLexicographic([...step.program.constraints(), {
666
+ coefficients: most.coefficients,
667
+ relation: "=",
668
+ rhs: days
669
+ }], later, { warm: true });
670
+ if (full.status !== "optimal") throw new Error("The step of a season has no optimum for its later objectives.");
671
+ const first = solved.stages[0]?.result;
672
+ return {
673
+ step,
674
+ x: full.x,
675
+ dual: first?.status === "optimal" ? first.dual : [],
676
+ days,
677
+ atHorizon: segment + 1 === segments && equals(days, end)
678
+ };
679
+ }
680
+ throw new Error("A season plan has no segment.");
681
+ }
682
+ /** This function gives the fewest device-days of the runs of the open cells of a step, as an objective. */
683
+ function fewestOpen(step, open) {
684
+ return {
685
+ sense: "min",
686
+ coefficients: dense(fewestRow(step.cells.filter((cell) => open.has(cell.draw.need)).flatMap((cell) => [...cell.block.runs])), step.program.count)
687
+ };
688
+ }
689
+ /** This function gives the smallest sum of the shares of the stocks, each over the total of its lots, as an objective. */
690
+ function leastShares(plan, cells, count) {
691
+ const least = /* @__PURE__ */ new Map();
692
+ const weight = (resource) => div(ONE, exact((plan.parts.stock.get(resource) ?? 0) > 0 ? plan.parts.stock.get(resource) : 1));
693
+ for (const cell of cells) for (const [resource, index] of cell.block.shares) addTo(least, index, weight(resource));
694
+ return {
695
+ sense: "min",
696
+ coefficients: dense(least, count)
697
+ };
698
+ }
699
+ /** This function fixes the open draws of `done` at the stop: the device-days of each day that they keep, and their capped converters. */
700
+ function fixStops(plan, stop, done, fixed) {
701
+ const { step, x, days } = stop;
702
+ const fedIn = (segment) => segment < step.segment ? lengthOf(plan, segment) : sub(days, edgeOf(plan, step.segment));
703
+ const full = /* @__PURE__ */ new Set();
704
+ for (const [segment, bySegment] of step.shared) for (const [key, limit] of bySegment) if (equals(valueAt(limit.row, x), mul(limit.room, fedIn(segment)))) full.add(`${String(segment)}\u0000${key}`);
705
+ for (const draw of done) {
706
+ const keep = /* @__PURE__ */ new Map();
707
+ const used = /* @__PURE__ */ new Set();
708
+ for (const cell of step.cells) {
709
+ if (cell.draw.need !== draw.need) continue;
710
+ const fed = fedIn(cell.segment);
711
+ const bySegment = /* @__PURE__ */ new Map();
712
+ keep.set(cell.segment, bySegment);
713
+ for (const [key, limit] of deviceUse(cell.block.runs).limits) {
714
+ bySegment.set(key, sign(fed) > 0 ? div(valueAt(limit.row, x), fed) : ZERO);
715
+ if (full.has(`${String(cell.segment)}\u0000${key}`)) for (const converter of limit.converters) used.add(converter);
716
+ }
717
+ }
718
+ const { reach } = reachOf(plan.parts, /* @__PURE__ */ new Set([draw.need]));
719
+ const capped = sign(days) > 0 && !stop.atHorizon ? [...reach].filter((converter) => converter.perDay !== void 0 && (!(converter.perDay > 0) || used.has(converter))).map((converter) => converter.id).sort() : [];
720
+ fixed.set(draw.need, {
721
+ stop: days,
722
+ segment: step.segment,
723
+ keep,
724
+ atHorizon: stop.atHorizon,
725
+ capped
726
+ });
727
+ }
728
+ }
729
+ /** This function gives the sum of the take of each resource of the cells of one need, more than 0 only. */
730
+ function takesOf(cells, need, x) {
731
+ const sums = /* @__PURE__ */ new Map();
732
+ for (const cell of cells) {
733
+ if (cell.draw.need !== need) continue;
734
+ for (const [resource, index] of cell.block.shares) sums.set(resource, add(sums.get(resource) ?? ZERO, x[index] ?? ZERO));
735
+ }
736
+ const out = {};
737
+ for (const [resource, value] of [...sums].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) if (sign(value) > 0) out[resource] = toNumber(value);
738
+ return out;
739
+ }
740
+ /** This function gives the resources of `closure` with a store in the layer whose lots are used up at `x`. They are in the order of their codes. */
741
+ function usedUp(plan, cells, x, closure, stored, charges) {
742
+ return [...closure].filter((resource) => stored.has(resource)).filter((resource) => {
743
+ let taken = ZERO;
744
+ const given = charges?.gifts.get(resource);
745
+ let amount = given === void 0 ? ZERO : valueAt(given, x);
746
+ for (const lot of plan.lots) {
747
+ if (lot.resource !== resource) continue;
748
+ amount = add(amount, lot.amount);
749
+ for (const cell of cells) taken = add(taken, x[cell.takes.get(lot) ?? -1] ?? ZERO);
750
+ }
751
+ return equals(taken, amount);
752
+ }).sort();
753
+ }
754
+ /** This function tells if the cells of two draws or more of `cells` can use the limited device `key`. */
755
+ function sharedKey(cells, key) {
756
+ return new Set(cells.filter((cell) => deviceUse(cell.block.runs).limits.has(key)).map((cell) => cell.draw.need)).size > 1;
757
+ }
758
+ /**
759
+ * This function gives the last program of the best endurance with a season. Each draw keeps its first stop. After it, a later
760
+ * harvest can feed the draw again (`again`). The objectives come in this order:
761
+ * - the most fed days after the stops for each level, in the order of the levels.
762
+ * - the earliest fed days.
763
+ * - the smallest sum of the shares of the stocks.
764
+ * - the fewest device-days.
765
+ *
766
+ * In a segment after the stops, the cells of two draws or more that can use one limited device take turns. Their fed days
767
+ * together are not more than the segment, and each one has the device-days of each day that the stops leave. This is the
768
+ * safe side: the cells do not use one device at the same time. Each other cell starts at the start of the segment.
769
+ *
770
+ * @param fill - True for the sweep of `enduranceOf` (M2-solar-charge-sweep). Then the last objective is the most charge, the
771
+ * earliest first, and the result gives the rest of each store with a capacity. A store with a capacity is binding if the
772
+ * takes of the segment of the stop use all the level at its start.
773
+ */
774
+ function seasonBest(plan, fixed, levels, stored, fill = false) {
775
+ const program = new Program();
776
+ const cells = [];
777
+ const kept = addFixed(program, plan, fixed, cells);
778
+ const segments = segmentsOf(plan);
779
+ const again = /* @__PURE__ */ new Map();
780
+ const taking = /* @__PURE__ */ new Set();
781
+ for (const draw of plan.draws) {
782
+ const fix = fixed.get(draw.need);
783
+ for (let segment = fix.segment + 1; segment < segments; segment += 1) {
784
+ const fed = program.next();
785
+ program.push(/* @__PURE__ */ new Map([[fed, ONE]]), "<=", lengthOf(plan, segment));
786
+ const cell = addCell(program, plan, draw, segment, fed);
787
+ cells.push(cell);
788
+ again.set(cell, fed);
789
+ }
790
+ }
791
+ for (let segment = 0; segment < segments; segment += 1) {
792
+ const later = [...again.keys()].filter((cell) => cell.segment === segment);
793
+ const { limits, stopped } = deviceUse(later.flatMap((cell) => [...cell.block.runs]));
794
+ for (const column of stopped) program.push(/* @__PURE__ */ new Map([[column, ONE]]), "<=", ZERO);
795
+ const turns = new Set(later.filter((cell) => [...deviceUse(cell.block.runs).limits.keys()].some((key) => sharedKey(later, key))));
796
+ if (turns.size > 0) {
797
+ const row = /* @__PURE__ */ new Map();
798
+ for (const cell of turns) addTo(row, again.get(cell), ONE);
799
+ program.push(row, "<=", lengthOf(plan, segment));
800
+ for (const cell of turns) taking.add(cell);
801
+ }
802
+ for (const [key, limit] of limits) {
803
+ const room = roomOf(plan, kept, segment, key, limit.devices);
804
+ for (const cell of later) {
805
+ const own = deviceUse(cell.block.runs).limits.get(key);
806
+ if (own === void 0) continue;
807
+ const row = new Map(own.row);
808
+ addTo(row, again.get(cell), neg(room));
809
+ program.push(row, "<=", ZERO);
810
+ }
811
+ }
812
+ }
813
+ const charges = addCharges(program, plan, cells, segments);
814
+ for (const [segment, list] of charges.pairs) {
815
+ const { limits } = deviceUse([...[...again.keys()].filter((cell) => cell.segment === segment).flatMap((cell) => [...cell.block.runs]), ...list]);
816
+ const keys = new Set(list.map(([source]) => deviceKey(source)));
817
+ for (const [key, limit] of limits) if (keys.has(key)) program.push(limit.row, "<=", mul(roomOf(plan, kept, segment, key, limit.devices), lengthOf(plan, segment)));
818
+ }
819
+ lotRows(program, plan, cells);
820
+ const objectives = levels.map((level) => {
821
+ const needs = new Set(level.map((draw) => draw.need));
822
+ const row = /* @__PURE__ */ new Map();
823
+ for (const [cell, fed] of again) if (needs.has(cell.draw.need)) addTo(row, fed, ONE);
824
+ return {
825
+ sense: "max",
826
+ coefficients: dense(row, program.count)
827
+ };
828
+ });
829
+ const early = /* @__PURE__ */ new Map();
830
+ const horizon = edgeOf(plan, segments);
831
+ for (const [cell, fed] of again) addTo(early, fed, sub(horizon, edgeOf(plan, cell.segment)));
832
+ objectives.push({
833
+ sense: "max",
834
+ coefficients: dense(early, program.count)
835
+ });
836
+ objectives.push(leastShares(plan, cells, program.count));
837
+ objectives.push({
838
+ sense: "min",
839
+ coefficients: dense(fewestRow(cells.flatMap((cell) => [...cell.block.runs])), program.count)
840
+ });
841
+ if (fill) objectives.push(mostCharge(plan, charges, program.count));
842
+ const solved = solveLexicographic(program.constraints(), objectives, { warm: true });
843
+ if (solved.status !== "optimal") throw new Error("The last program of the best endurance with a season has no optimum. The point of the last step is a point of it.");
844
+ const x = solved.x;
845
+ const rests = fill ? restsOf(plan, cells, x, charges) : void 0;
846
+ const charged = new Set(plan.charges.map((charge) => charge.resource));
847
+ const bound = (closure, segment) => {
848
+ const used = usedUp(plan, cells, x, closure, stored, charges);
849
+ if (rests === void 0) return used;
850
+ const empty = [...charged].filter((resource) => closure.has(resource) && stored.has(resource) && sign(rests.get(resource)?.[segment]?.take ?? ONE) <= 0);
851
+ return [...used.filter((resource) => !charged.has(resource)), ...empty].sort();
852
+ };
853
+ const turn = /* @__PURE__ */ new Map();
854
+ const offset = /* @__PURE__ */ new Map();
855
+ for (const cell of [...taking].sort((a, b) => plan.draws.indexOf(a.draw) - plan.draws.indexOf(b.draw))) {
856
+ const start = offset.get(cell.segment) ?? ZERO;
857
+ turn.set(cell, start);
858
+ offset.set(cell.segment, add(start, x[again.get(cell)] ?? ZERO));
859
+ }
860
+ const needs = {};
861
+ for (const draw of plan.draws) {
862
+ const fix = fixed.get(draw.need);
863
+ const spans = [];
864
+ for (const [cell, fed] of again) {
865
+ if (cell.draw.need !== draw.need) continue;
866
+ const value = x[fed] ?? ZERO;
867
+ if (sign(value) <= 0) continue;
868
+ const start = add(edgeOf(plan, cell.segment), taking.has(cell) ? turn.get(cell) ?? ZERO : ZERO);
869
+ const from = toNumber(start);
870
+ const to = toNumber(add(start, value));
871
+ const last = spans[spans.length - 1];
872
+ if (last !== void 0 && last.to === from) last.to = to;
873
+ else spans.push({
874
+ from,
875
+ to
876
+ });
877
+ }
878
+ const { closure } = reachOf(plan.parts, /* @__PURE__ */ new Set([draw.need]));
879
+ needs[draw.need] = {
880
+ days: toNumber(fix.stop),
881
+ binding: fix.atHorizon ? [] : bound(closure, fix.segment),
882
+ takes: takesOf(cells, draw.need, x),
883
+ ...fix.capped.length === 0 ? {} : { capped: fix.capped },
884
+ ...fix.atHorizon ? { atHorizon: true } : {},
885
+ ...spans.length === 0 ? {} : { again: spans }
886
+ };
887
+ }
888
+ const taken = /* @__PURE__ */ new Map();
889
+ for (const lot of plan.lots) {
890
+ let sum = ZERO;
891
+ for (const cell of cells) sum = add(sum, x[cell.takes.get(lot) ?? -1] ?? ZERO);
892
+ taken.set(lot, toNumber(sum));
893
+ }
894
+ const perDay = /* @__PURE__ */ new Map();
895
+ for (const cell of cells) {
896
+ const fed = typeof cell.fed === "number" ? x[cell.fed] ?? ZERO : cell.fed;
897
+ if (sign(fed) <= 0) continue;
898
+ const into = perDay.get(cell.draw.need) ?? /* @__PURE__ */ new Map();
899
+ perDay.set(cell.draw.need, into);
900
+ for (const [key, limit] of deviceUse(cell.block.runs).limits) {
901
+ const share = shareIn(plan, cell.segment, key);
902
+ if (share > 0) into.set(key, Math.max(into.get(key) ?? 0, toNumber(div(valueAt(limit.row, x), fed)) / share));
903
+ }
904
+ }
905
+ return {
906
+ needs,
907
+ taken,
908
+ perDay,
909
+ rests,
910
+ chargeDays: fill ? chargeDaysOf(plan, charges, x) : void 0
911
+ };
912
+ }
913
+ /**
914
+ * This function gives the joint days of the draws of a plan with a season. The objectives come in this order:
915
+ * - the largest common first stop.
916
+ * - the smallest sum of the shares of the stocks.
917
+ * - the fewest device-days.
918
+ */
919
+ function seasonJoint(plan, stored) {
920
+ const open = new Set(plan.draws.map((draw) => draw.need));
921
+ const stop = firstStop(plan, /* @__PURE__ */ new Map(), plan.draws, (step) => [leastShares(plan, step.cells, step.program.count), fewestOpen(step, open)]);
922
+ const { step, x } = stop;
923
+ const takes = {};
924
+ for (const draw of plan.draws) takes[draw.need] = takesOf(step.cells, draw.need, x);
925
+ const total = /* @__PURE__ */ new Map();
926
+ for (const cell of step.cells) for (const [converter, index] of cell.block.runs) total.set(converter, add(total.get(converter) ?? ZERO, x[index] ?? ZERO));
927
+ const runs = {};
928
+ for (const [converter, value] of [...total].sort(([a], [b]) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0)) if (sign(value) > 0) runs[converter.id] = toNumber(value);
929
+ const fixed = /* @__PURE__ */ new Map();
930
+ fixStops(plan, stop, plan.draws, fixed);
931
+ const capped = [...new Set([...fixed.values()].flatMap((fix) => fix.capped))].sort();
932
+ return {
933
+ days: toNumber(stop.days),
934
+ atHorizon: stop.atHorizon,
935
+ takes,
936
+ binding: usedUp(plan, step.cells, x, reachOf(plan.parts, open).closure, stored, step.charges),
937
+ runs,
938
+ capped
939
+ };
940
+ }
941
+ /**
942
+ * This function gives the endurance of one draw of `enduranceOf` that reaches two limited converters of one device in a layer
943
+ * with a season (M2-grow-share-sweep). The take order cannot give the share of the device-days.
944
+ * Thus the programs of `bestEndurance` give it for this one draw: the first stop, then the most fed days after it (`again`).
945
+ *
946
+ * The function also gives the endurance of a draw that can take a store with a capacity that a source charges (M2-solar-charge-sweep).
947
+ * - The takes of the store come from the rest that the higher draws leave (`rests`). Thus the takes and the charges of the higher draws stay possible.
948
+ * - The first stop takes the fewest stocks, thus the draw keeps the most runs of a source and the most level for the lower draws.
949
+ * - The last program charges the store as much as it can, the earliest first. The draw gives the rest that it leaves to the lower draws.
950
+ * - The device-days of the charge are a part of the device-days of the draw (`perDay`). Thus a lower draw cannot use them.
951
+ *
952
+ * @param stock - The stocks that the higher draws leave. The stock of a store with a charge is its amount on day 0, because the rest gives the takes of the higher draws.
953
+ * @param lots - The rest of each harvest lot that the higher draws leave.
954
+ * @param room - The device-days of each day that the higher draws leave, by the key of the device, before the shares `monthly`.
955
+ * @param start - The first day of the event, for the months of the shares.
956
+ * @param capacities - The capacity of each resource whose stores have a capacity (`storeCapacities`).
957
+ * @param rests - The rest of each store with a capacity that the higher draws leave. With no rest, the store has its amount and its capacity.
958
+ */
959
+ function seasonDraw(layer, stoppedParts, caseCuts, draw, stock, lots, horizon, room, start, capacities = /* @__PURE__ */ new Map(), rests = /* @__PURE__ */ new Map()) {
960
+ const supply = {
961
+ stock: new Map(stock),
962
+ harvests: [],
963
+ lots,
964
+ horizon,
965
+ start
966
+ };
967
+ const plan = seasonPlan(supply, caseParts(layer, stoppedParts, supply.stock, /* @__PURE__ */ new Set([draw.need])), caseCuts, [draw], room, capacities, rests);
968
+ const fixed = /* @__PURE__ */ new Map();
969
+ const open = /* @__PURE__ */ new Set([draw.need]);
970
+ const filled = plan.charges.length > 0;
971
+ const tail = (step) => filled ? [leastShares(plan, step.cells, step.program.count), fewestOpen(step, open)] : [fewestOpen(step, open)];
972
+ fixStops(plan, firstStop(plan, fixed, [draw], tail), [draw], fixed);
973
+ const best = seasonBest(plan, fixed, [[draw]], new Set(layer.stores.map((store) => store.resource)), filled);
974
+ const left = new Map(stock);
975
+ const rest = lots.map((lot) => lot.amount);
976
+ const chargedLots = new Set(plan.charges.map((charge) => charge.lot));
977
+ for (const [lot, amount] of best.taken) {
978
+ if (chargedLots.has(lot)) continue;
979
+ if (lot.origin === void 0) left.set(lot.resource, Math.max(0, (left.get(lot.resource) ?? 0) - amount));
980
+ else rest[lot.origin] = Math.max(0, (rest[lot.origin] ?? 0) - amount);
981
+ }
982
+ const perDay = new Map(best.perDay.get(draw.need) ?? []);
983
+ for (const [key, each] of best.chargeDays ?? /* @__PURE__ */ new Map()) perDay.set(key, (perDay.get(key) ?? 0) + each);
984
+ return {
985
+ need: best.needs[draw.need],
986
+ stock: left,
987
+ lots: rest,
988
+ perDay,
989
+ rests: best.rests ?? /* @__PURE__ */ new Map()
990
+ };
991
+ }
992
+ // src/share.ts
993
+ /**
994
+ * This function gives the best share of the stocks and of the device-days for one draw.
995
+ * It gives `undefined` when the program has no optimum.
996
+ *
997
+ * - The variables are the days `T`, the take of each direct use, the runs of each converter and maker, and the take of each stock.
998
+ * - The gifts of the direct uses and of the converters are not less than `T` times the demand.
999
+ * - The takes of each resource are not more than the take of its stock plus the gifts of its makers. The take of a stock is not more than the stock.
1000
+ * - The runs of the converters of one device use `room` times `T` device-days or less. One run uses `1 / perDay` of a device-day. A limit of 0 stops the converter.
1001
+ * - The first objective takes the largest `T`. The second takes the smallest sum of the takes of the stocks, each over its stock. The third takes the fewest device-days.
1002
+ *
1003
+ * The gifts at `T` days are a concave function of `T`, and they are 0 at 0. Thus each count of days up to the largest `T` also fits.
1004
+ *
1005
+ * @param input - The draw, the stocks, the device-days of each day, the ways of the draw and its demand
1006
+ * @returns The days, the takes of the stocks and the device-days of each device
1007
+ */
1008
+ function bestShare(input) {
1009
+ const parts = partsOf(input.stock, input.direct, input.converters, input.makers);
1010
+ const program = new Program();
1011
+ const days = program.next();
1012
+ const block = drawBlock(program, parts, input.draw);
1013
+ const need = new Map(block.gifts);
1014
+ addTo(need, days, neg(exact(input.demand)));
1015
+ program.push(need, ">=", ZERO);
1016
+ for (const [resource, index] of block.shares) program.push(/* @__PURE__ */ new Map([[index, ONE]]), "<=", exact(input.stock.get(resource) ?? 0));
1017
+ const { limits, stopped } = deviceUse(block.runs);
1018
+ for (const index of stopped) program.push(/* @__PURE__ */ new Map([[index, ONE]]), "<=", ZERO);
1019
+ for (const [key, limit] of limits) {
1020
+ const row = new Map(limit.row);
1021
+ addTo(row, days, neg(exact(input.room.get(key) ?? 0)));
1022
+ program.push(row, "<=", ZERO);
1023
+ }
1024
+ const least = /* @__PURE__ */ new Map();
1025
+ for (const [resource, index] of block.shares) addTo(least, index, div(ONE, exact(input.stock.get(resource) ?? 1)));
1026
+ const objectives = [
1027
+ {
1028
+ sense: "max",
1029
+ coefficients: dense(/* @__PURE__ */ new Map([[days, ONE]]), program.count)
1030
+ },
1031
+ {
1032
+ sense: "min",
1033
+ coefficients: dense(least, program.count)
1034
+ },
1035
+ {
1036
+ sense: "min",
1037
+ coefficients: dense(fewestRow(block.runs), program.count)
1038
+ }
1039
+ ];
1040
+ const solved = solveLexicographic(program.constraints(), objectives, { warm: true });
1041
+ if (solved.status !== "optimal") return void 0;
1042
+ const at = (index) => solved.x[index] ?? ZERO;
1043
+ const taken = /* @__PURE__ */ new Map();
1044
+ for (const [resource, index] of block.shares) if (sign(at(index)) > 0) taken.set(resource, toNumber(at(index)));
1045
+ const used = /* @__PURE__ */ new Map();
1046
+ for (const [key, limit] of limits) {
1047
+ const sum = valueAt(limit.row, solved.x);
1048
+ if (sign(sum) > 0) used.set(key, toNumber(sum));
1049
+ }
1050
+ return {
1051
+ days: toNumber(at(days)),
1052
+ taken,
1053
+ used
1054
+ };
1055
+ }
1056
+ // src/endurance.ts
1057
+ /** The default horizon of a layer with a converter with a season: 730 days, thus two seasons of each year. */
1058
+ const SEASON_HORIZON_DAYS = 730;
1059
+ /**
1060
+ * This function gives the `id` of each part that does not work in a case: the cut parts and the parts of `down`.
1061
+ * With a stack, it also gives each part that stops.
1062
+ */
1063
+ function caseStopped(caseCuts, options) {
1064
+ const down = [...caseCuts.cuts.map((cut) => cut.part), ...options.down ?? []];
1065
+ const out = new Set(down);
1066
+ if (options.stack !== void 0) for (const id of stopped(options.stack, down)) out.add(id);
1067
+ return out;
1068
+ }
1069
+ /**
1070
+ * This function gives the amount of each resource in the stores at a date, by the code of the resource.
1071
+ *
1072
+ * - A store gives nothing on its due date and after it.
1073
+ * - A store gives nothing when its part is in `stoppedParts`.
1074
+ */
1075
+ function storeAmounts(layer, at, stoppedParts = /* @__PURE__ */ new Set()) {
1076
+ const today = dayOf(at);
1077
+ const out = /* @__PURE__ */ new Map();
1078
+ for (const store of layer.stores) {
1079
+ if (store.due !== void 0 && today >= dayOf(store.due)) continue;
1080
+ if (store.part !== void 0 && stoppedParts.has(store.part)) continue;
1081
+ out.set(store.resource, (out.get(store.resource) ?? 0) + store.amount);
1082
+ }
1083
+ return out;
1084
+ }
1085
+ /**
1086
+ * This function gives the draws that take from the stores in a case: each draw whose supply stops, with a demand more than 0.
1087
+ * The sequence is by the level (the order of `levels`), then by the code of the need.
1088
+ */
1089
+ function caseDraws(layer, caseCuts, stoppedParts) {
1090
+ const rank = (level) => {
1091
+ const index = layer.levels.indexOf(level);
1092
+ return index < 0 ? layer.levels.length : index;
1093
+ };
1094
+ return layer.draws.filter((draw) => stoppedParts.has(draw.supply) && drawDemand(draw, caseCuts) > 0).sort((a, b) => rank(a.level) - rank(b.level) || (a.need < b.need ? -1 : a.need > b.need ? 1 : 0));
1095
+ }
1096
+ function makersOf(layer, stoppedParts) {
1097
+ const out = /* @__PURE__ */ new Map();
1098
+ for (const converter of layer.converters ?? []) {
1099
+ const resource = giftResource(converter);
1100
+ if (resource === void 0 || converter.season !== void 0 || !canRun(converter, stoppedParts)) continue;
1101
+ out.set(resource, [...out.get(resource) ?? [], converter]);
1102
+ }
1103
+ return out;
1104
+ }
1105
+ function waysOf(layer, need, stoppedParts, makers) {
1106
+ const converters = (layer.converters ?? []).filter((converter) => giftNeed(converter) === need && canRun(converter, stoppedParts));
1107
+ const sources = converters.filter(isSource);
1108
+ return {
1109
+ direct: (layer.direct ?? []).filter((use) => use.need === need && use.amount > 0),
1110
+ converters,
1111
+ makers,
1112
+ sources,
1113
+ others: sources.length === 0 ? converters : converters.filter((converter) => !isSource(converter)),
1114
+ open: [.../* @__PURE__ */ new Set([...sources, ...[...makers.values()].flat().filter(isSource)])]
1115
+ };
1116
+ }
1117
+ const NO_PATH = /* @__PURE__ */ new Set();
1118
+ const RUNS = "\0runs:";
1119
+ function runsKey(converter) {
1120
+ return RUNS + deviceKey(converter);
1121
+ }
1122
+ /** This function gives the device-days that a converter has left in `left`, or undefined with no limit. */
1123
+ function daysLeft(left, converter) {
1124
+ return converter.perDay === void 0 ? void 0 : left.get(runsKey(converter));
1125
+ }
1126
+ /** This function gives the map with no runs left of the converters: a map of the resources only. */
1127
+ function resourcesOnly(left) {
1128
+ return new Map([...left].filter(([key]) => !key.startsWith(RUNS)));
1129
+ }
1130
+ /**
1131
+ * This function gives the most of a resource that `left` gives: its stock, and the runs of each maker.
1132
+ * It is an upper limit. When two inputs come from one resource, the true amount can be less.
1133
+ */
1134
+ function mostResource(left, makers, resource, path) {
1135
+ let total = left.get(resource) ?? 0;
1136
+ if (path.has(resource)) return total;
1137
+ const next = new Set(path).add(resource);
1138
+ for (const maker of makers.get(resource) ?? []) total += mostRuns(left, makers, maker, next) * maker.gives.amount;
1139
+ return total;
1140
+ }
1141
+ /** This function gives the most runs of a converter that `left` gives. It is an upper limit, as for `mostResource`. */
1142
+ function mostRuns(left, makers, converter, path) {
1143
+ const limit = daysLeft(left, converter);
1144
+ let runs = limit === void 0 ? 1e400 : limit * (converter.perDay ?? 0);
1145
+ for (const [resource, each] of inputsOf(converter)) runs = Math.min(runs, mostResource(left, makers, resource, path) / each);
1146
+ return Number.isFinite(runs) ? runs : 0;
1147
+ }
1148
+ /**
1149
+ * This function takes an amount of a resource from `left`: the stock first, then the makers in the order of the layer.
1150
+ * It changes `left`, and it gives the amount that it could not take.
1151
+ */
1152
+ function takeResource(left, makers, resource, amount, path) {
1153
+ let rest = amount;
1154
+ const ways = path.has(resource) ? void 0 : makers.get(resource);
1155
+ let next;
1156
+ if (ways !== void 0 && ways.some(isSource)) {
1157
+ next = new Set(path).add(resource);
1158
+ for (const maker of ways) {
1159
+ if (rest <= 0) break;
1160
+ if (isSource(maker)) rest -= run(left, makers, maker, rest / maker.gives.amount, next) * maker.gives.amount;
1161
+ }
1162
+ }
1163
+ const has = left.get(resource) ?? 0;
1164
+ const got = Math.min(Math.max(0, rest), has);
1165
+ left.set(resource, has - got);
1166
+ rest -= got;
1167
+ if (rest <= 0 || ways === void 0) return Math.max(0, rest);
1168
+ next ??= new Set(path).add(resource);
1169
+ for (const maker of ways) {
1170
+ if (rest <= 0) break;
1171
+ if (!isSource(maker)) rest -= run(left, makers, maker, rest / maker.gives.amount, next) * maker.gives.amount;
1172
+ }
1173
+ return Math.max(0, rest);
1174
+ }
1175
+ /**
1176
+ * This function runs a converter up to `wanted` times with the resources of `left`, and it gives the count of runs.
1177
+ * It changes `left`. When two inputs come from one resource, `largestFit` finds the runs that the resources give.
1178
+ */
1179
+ function run(left, makers, converter, wanted, path) {
1180
+ const inputs = inputsOf(converter);
1181
+ const most = Math.min(wanted, mostRuns(left, makers, converter, path));
1182
+ if (!(most > 0)) return 0;
1183
+ const attempt = (runs) => {
1184
+ const copy = new Map(left);
1185
+ let need = 0;
1186
+ let short = 0;
1187
+ const limit = daysLeft(copy, converter);
1188
+ if (limit !== void 0 && converter.perDay !== void 0 && converter.perDay > 0) {
1189
+ const wanted = runs / converter.perDay;
1190
+ const got = Math.min(wanted, limit);
1191
+ copy.set(runsKey(converter), limit - got);
1192
+ need += runs;
1193
+ short += (wanted - got) * converter.perDay;
1194
+ }
1195
+ for (const [resource, each] of inputs) {
1196
+ need += runs * each;
1197
+ short += takeResource(copy, makers, resource, runs * each, path);
1198
+ }
1199
+ return {
1200
+ short,
1201
+ need,
1202
+ value: copy
1203
+ };
1204
+ };
1205
+ const { x: runs, value: best } = largestFit(most, attempt);
1206
+ if (best === void 0) return 0;
1207
+ for (const [resource, amount] of best) left.set(resource, amount);
1208
+ return runs;
1209
+ }
1210
+ /**
1211
+ * This function takes an amount of a need from the resources in `left`: the direct uses first, then the converters.
1212
+ * A direct use or a converter takes each resource from its stock first, then from its makers.
1213
+ * It changes `left`, and it gives the amount that it could not take.
1214
+ */
1215
+ function take(left, ways, amount) {
1216
+ let rest = amount;
1217
+ for (const converter of ways.sources) {
1218
+ if (rest <= 0) break;
1219
+ rest -= run(left, ways.makers, converter, rest / converter.gives.amount, NO_PATH) * converter.gives.amount;
1220
+ }
1221
+ for (const use of ways.direct) {
1222
+ if (rest <= 0) break;
1223
+ const wanted = rest / use.amount;
1224
+ rest -= (wanted - takeResource(left, ways.makers, use.resource, wanted, NO_PATH)) * use.amount;
1225
+ }
1226
+ for (const converter of ways.others) {
1227
+ if (rest <= 0) break;
1228
+ rest -= run(left, ways.makers, converter, rest / converter.gives.amount, NO_PATH) * converter.gives.amount;
1229
+ }
1230
+ return Math.max(0, rest);
1231
+ }
1232
+ /** This function gives each resource that a need can use: the inputs of its ways, and the inputs of their makers, through each chain. */
1233
+ function inputClosure(ways) {
1234
+ return inputClosure$1(ways.direct.map((use) => use.resource), ways.converters, [...ways.makers.values()].flat());
1235
+ }
1236
+ /** The relative tolerance of a used-up resource. */
1237
+ const USED_UP = 1e-9;
1238
+ /** This function gives the day number of a day `MM-DD` of a year. A day that the year does not have gives undefined. */
1239
+ function yearDay(year, monthDay) {
1240
+ return dayNumber(`${String(year).padStart(4, "0")}-${monthDay}`);
1241
+ }
1242
+ /**
1243
+ * This function gives the sow days of a season, in days from the start of the event, before the horizon, in increasing
1244
+ * order (M2-grow). The sow day of a year is the first day of its window on the start or after it. A window with `from`
1245
+ * after `to` goes across the end of the year. A year that does not have a day of the window (`02-29`) has no sowing.
1246
+ *
1247
+ * @throws RangeError when the start is not `YYYY-MM-DD`, or the horizon is not more than 0.
1248
+ */
1249
+ function sowDays(season, start, horizon) {
1250
+ if (!(horizon > 0)) throw new RangeError(`The horizon ${String(horizon)} is not a number of days more than 0.`);
1251
+ const first = dayOf(start);
1252
+ const out = [];
1253
+ for (let year = Number(start.slice(0, 4)) - 1;; year += 1) {
1254
+ const from = yearDay(year, season.from);
1255
+ const sameYear = yearDay(year, season.to);
1256
+ const to = from !== void 0 && sameYear !== void 0 && sameYear < from ? yearDay(year + 1, season.to) : sameYear;
1257
+ if ((from ?? yearDay(year, "01-01")) - first >= horizon) break;
1258
+ if (from === void 0 || to === void 0 || to < first) continue;
1259
+ const day = Math.max(from, first) - first;
1260
+ if (day < horizon) out.push(day);
1261
+ }
1262
+ return out;
1263
+ }
1264
+ /** This function gives a lot of a store: it is ready before the event, and it does not spoil. */
1265
+ function storeLot(resource, amount) {
1266
+ return {
1267
+ resource,
1268
+ day: -1e400,
1269
+ spoils: 1e400,
1270
+ left: amount,
1271
+ lost: 0
1272
+ };
1273
+ }
1274
+ /** This function compares two numbers for a sort, also two that are Infinity. */
1275
+ function compare(a, b) {
1276
+ return a < b ? -1 : a > b ? 1 : 0;
1277
+ }
1278
+ /**
1279
+ * This function takes the use of each resource from `from` to `to` from the lots, first expiring first out. It takes
1280
+ * the lot that spoils first, then the lot of the earliest day. A store comes after each lot with a spoil day, and before each
1281
+ * harvest with no spoil day. With no spoil day, the order is thus the stores, then each harvest in the order of its day.
1282
+ */
1283
+ function useLots(lots, from, to) {
1284
+ for (const [resource, had] of from) {
1285
+ let rest = had - (to.get(resource) ?? 0);
1286
+ if (!(rest > 0)) continue;
1287
+ const order = lots.filter((lot) => lot.resource === resource && lot.left > 0).sort((a, b) => compare(a.spoils, b.spoils) || compare(a.day, b.day));
1288
+ for (const lot of order) {
1289
+ if (!(rest > 0)) break;
1290
+ const taken = Math.min(lot.left, rest);
1291
+ lot.left -= taken;
1292
+ rest -= taken;
1293
+ }
1294
+ }
1295
+ }
1296
+ /**
1297
+ * This function gives the sowings of the converters with a season that can operate in a case, up to the horizon. It
1298
+ * also gives the lot of each harvest. The order is the order of their sow days, then of the layer. Each sowing takes its inputs
1299
+ * from `stock`, and from each harvest that is ready and not spoiled on its sow day (M2-grow-seed). It changes `stock`,
1300
+ * and the `left` of each lot is the rest of its harvest after the later sowings.
1301
+ */
1302
+ function sowings(layer, stoppedParts, stock, makers, start, horizon) {
1303
+ const plan = [];
1304
+ (layer.converters ?? []).forEach((converter, order) => {
1305
+ const season = converter.season;
1306
+ if (season === void 0 || !(season.runs > 0) || !canRun(converter, stoppedParts)) return;
1307
+ for (const sow of sowDays(season, start, horizon)) plan.push({
1308
+ converter,
1309
+ season,
1310
+ sow,
1311
+ order
1312
+ });
1313
+ });
1314
+ plan.sort((a, b) => a.sow - b.sow || a.order - b.order);
1315
+ const stores = [...stock].map(([resource, amount]) => storeLot(resource, amount));
1316
+ const lots = [];
1317
+ const out = [];
1318
+ for (const { converter, season, sow } of plan) {
1319
+ const ready = [...stores, ...lots.filter((lot) => lot.day <= sow && lot.spoils > sow)];
1320
+ const pool = /* @__PURE__ */ new Map();
1321
+ for (const lot of ready) pool.set(lot.resource, (pool.get(lot.resource) ?? 0) + lot.left);
1322
+ const had = new Map(pool);
1323
+ const runs = run(pool, makers, converter, season.runs, NO_PATH);
1324
+ useLots(ready, had, pool);
1325
+ const resource = giftResource(converter);
1326
+ if (resource === void 0) continue;
1327
+ const day = sow + season.delayDays;
1328
+ const amount = runs * converter.gives.amount;
1329
+ const spoils = season.shelfDays === void 0 ? 1e400 : day + season.shelfDays;
1330
+ out.push({
1331
+ converter: converter.id,
1332
+ sow,
1333
+ day,
1334
+ runs,
1335
+ resource,
1336
+ amount,
1337
+ ...season.shelfDays === void 0 ? {} : { spoils }
1338
+ });
1339
+ lots.push({
1340
+ resource,
1341
+ day,
1342
+ spoils,
1343
+ left: amount,
1344
+ lost: 0
1345
+ });
1346
+ }
1347
+ for (const store of stores) stock.set(store.resource, store.left);
1348
+ return {
1349
+ harvests: out,
1350
+ lots
1351
+ };
1352
+ }
1353
+ /**
1354
+ * This function gives the supply of a case with a season (M2-grow-share). `enduranceOf`, `bestEndurance` and `jointDays`
1355
+ * use it, so they read the same sowings. It throws a `RangeError` for a horizon that is not more than 0, or a date that is not `YYYY-MM-DD`.
1356
+ */
1357
+ function seasonSupply(layer, stoppedParts, options) {
1358
+ const stock = storeAmounts(layer, options.at, stoppedParts);
1359
+ const horizon = seasonHorizon(options.horizon);
1360
+ const start = options.start ?? options.at;
1361
+ const sown = sowings(layer, stoppedParts, stock, makersOf(layer, stoppedParts), start, horizon);
1362
+ const lots = sown.lots.filter((lot) => lot.day < horizon && lot.left > 0).sort((a, b) => a.day - b.day).map((lot) => ({
1363
+ resource: lot.resource,
1364
+ day: lot.day,
1365
+ spoils: lot.spoils,
1366
+ amount: lot.left
1367
+ }));
1368
+ return {
1369
+ stock,
1370
+ harvests: sown.harvests,
1371
+ lots,
1372
+ horizon,
1373
+ start
1374
+ };
1375
+ }
1376
+ /**
1377
+ * This function tells if a layer has a converter with a season, with shares `monthly` or a source (M2-solar) that can run
1378
+ * in a case. Such a layer needs the queries in segments of days to a horizon. A harvest, a spoil day and the start of a
1379
+ * month end a segment. A source can feed a draw with no end, thus the horizon is the upper limit of its days.
1380
+ */
1381
+ function hasSeason(layer, stoppedParts) {
1382
+ return (layer.converters ?? []).some((converter) => (converter.season !== void 0 || converter.monthly !== void 0 || isSource(converter)) && canRun(converter, stoppedParts));
1383
+ }
1384
+ /**
1385
+ * This function gives the days that each draw holds when a case stops its supply, and the resources that are used up then.
1386
+ *
1387
+ * - A draw takes from the stores only when the case stops its supply part. Each other draw holds without end, and the result leaves it out.
1388
+ * - The demand of a draw for each day is its rate times the factor of the case.
1389
+ * - The draws take the resources in the order of their level, then of their codes. A draw takes from its direct uses first, then from its converters.
1390
+ * - The days of a draw are the largest `T` at which the stores give `T` days of its demand, after each higher draw.
1391
+ * - 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.
1392
+ * - The take order is a rule, not the best share: the direct uses in the order of the list, then the converters. The days are the days of this order.
1393
+ * A draw with a shared device is different. Refer to the last item.
1394
+ * - A converter whose device stops gives nothing. A store whose part stops gives nothing.
1395
+ * - A converter can give a resource. A take of a resource uses the stock first, then the converters that make it, through each chain.
1396
+ * - A converter with a limit `perDay` runs `perDay` times `devices` times `T` times or less in `T` days. The converters of one device share it.
1397
+ * - The higher draws use the runs of a limit first.
1398
+ * - A higher draw keeps back its runs of each day for all the days of a lower draw, also when its own days are fewer. This is the safe side.
1399
+ * - Two limited converters of one device can make the shortfall of the take order decrease when the days increase.
1400
+ * Thus a draw whose ways reach two converters of one device, each with a limit `perDay` more than 0, does not use the take order.
1401
+ * A linear program with exact rationals gives its days: the largest `T` with the best share of its stocks and of the device-days.
1402
+ * At this `T`, the draw takes the smallest sum of its takes of the stocks, each over its stock, then the fewest device-days.
1403
+
1404
+ * - A converter with a season (M2-grow) is not a maker of a take. Its sowings take their inputs from the stores before
1405
+ * the first draw, and each harvest adds to the stocks on its day. Refer to `Season`. The query reads the sowings
1406
+ * and the harvests up to the horizon (`horizon`, default `SEASON_HORIZON_DAYS`), and a draw holds the horizon at most.
1407
+ * - With a season, each draw takes its stocks over spans from harvest to harvest. `days` is the first stop of the
1408
+ * draw. A later harvest can feed the draw again: `again` gives these spans, and `takes` is the sum to the horizon.
1409
+ * A lower draw gets the stocks that the higher draws leave, the earliest stocks first taken. This is the safe side.
1410
+ * - A draw with a shared device and a season gets the programs of `bestEndurance` for itself alone (M2-grow-share-sweep). Its stocks,
1411
+ * its harvest lots and its device-days are those that the higher draws leave. It has no field `spoiled`.
1412
+ * - A source (M2-solar) takes nothing and has a limit `perDay`. A take uses it first: its runs of a day are lost when no
1413
+ * draw uses them. With shares `monthly`, the device-days of a day are the devices times the share of its month. Each
1414
+ * span also ends at the start of a month, and a draw can hold again from the start of a month.
1415
+ * - A store with a capacity that a source charges (M2-solar-charge-sweep) takes a charge. Each draw that can take it gets the
1416
+ * programs of `bestEndurance` for itself alone, in the order of the levels. Thus one draw gets the days of `bestEndurance`.
1417
+ * A lower draw takes only the level that the higher draws leave. It charges the store only with the device-days that they leave.
1418
+ *
1419
+ * The function is pure, but for an internal count of the tries of its fits for the tests. It throws a `RangeError` for a date that is not `YYYY-MM-DD`. The gate `checkEndurance` examines the layer before.
1420
+ *
1421
+ * @param layer - The endurance layer
1422
+ * @param caseCuts - The case
1423
+ * @param options - The date, and the stack or the parts that are also down
1424
+ * @returns The endurance of each draw whose supply stops
1425
+ */
1426
+ function enduranceOf(layer, caseCuts, options) {
1427
+ const stoppedParts = caseStopped(caseCuts, options);
1428
+ const seasonal = hasSeason(layer, stoppedParts);
1429
+ const supply = seasonal ? seasonSupply(layer, stoppedParts, options) : void 0;
1430
+ const start = supply?.stock ?? storeAmounts(layer, options.at, stoppedParts);
1431
+ const makers = makersOf(layer, stoppedParts);
1432
+ const stocked = new Set(layer.stores.map((store) => store.resource));
1433
+ const limited = (layer.converters ?? []).filter((converter) => converter.perDay !== void 0 && canRun(converter, stoppedParts));
1434
+ const devices = new Map(limited.map((converter) => [deviceKey(converter), converter.devices ?? 1]));
1435
+ const monthShares = monthlyShares(limited);
1436
+ const begin = options.start ?? options.at;
1437
+ const shareAt = (key, at) => monthShares.size === 0 ? 1 : shareOf(monthShares, key, monthOf(begin, at));
1438
+ const months = monthShares.size === 0 || supply === void 0 ? [] : monthEdges(begin, supply.horizon);
1439
+ const nextMonth = (at) => months.find((day) => day > at) ?? 1e400;
1440
+ const used = /* @__PURE__ */ new Map();
1441
+ let before = new Map(start);
1442
+ const horizon = supply?.horizon ?? 1e400;
1443
+ const harvests = supply?.harvests ?? [];
1444
+ const later = (supply?.lots ?? []).map((lot) => ({ ...lot }));
1445
+ const capacities = storeCapacities(layer, stoppedParts);
1446
+ const chargedResources = new Set([...capacities.keys()].filter((resource) => (makers.get(resource) ?? []).some(isSource)));
1447
+ const rests = /* @__PURE__ */ new Map();
1448
+ const needs = {};
1449
+ for (const draw of caseDraws(layer, caseCuts, stoppedParts)) {
1450
+ const ways = waysOf(layer, draw.need, stoppedParts, makers);
1451
+ const demand = drawDemand(draw, caseCuts);
1452
+ const room = new Map([...devices].map(([key, count]) => [key, Math.max(0, count - (used.get(key) ?? 0))]));
1453
+ const closure = inputClosure(ways);
1454
+ const reach = /* @__PURE__ */ new Set([...ways.converters, ...[...closure].flatMap((resource) => makers.get(resource) ?? [])]);
1455
+ const after = (stock, days, at = 0) => {
1456
+ const tried = new Map(stock);
1457
+ for (const [key, free] of room) tried.set(RUNS + key, free * shareAt(key, at) * days);
1458
+ return {
1459
+ left: tried,
1460
+ short: take(tried, ways, days * demand)
1461
+ };
1462
+ };
1463
+ const span = (stock, limit, bound, at = 0) => {
1464
+ const fit = largestFit(Math.min(limit, bound / demand), (days) => {
1465
+ const tried = after(stock, days, at);
1466
+ return {
1467
+ short: tried.short,
1468
+ need: days * demand,
1469
+ value: tried.left
1470
+ };
1471
+ });
1472
+ return {
1473
+ days: fit.x,
1474
+ left: fit.value ?? after(stock, fit.x, at).left
1475
+ };
1476
+ };
1477
+ const shares = sharesDevice(reach);
1478
+ const charging = [...closure].some((resource) => chargedResources.has(resource));
1479
+ if ((shares || charging) && seasonal) {
1480
+ const lots = later.map((lot) => ({
1481
+ resource: lot.resource,
1482
+ day: lot.day,
1483
+ spoils: lot.spoils,
1484
+ amount: lot.amount
1485
+ }));
1486
+ const held = seasonDraw(layer, stoppedParts, caseCuts, draw, resourcesOnly(before), lots, horizon, room, begin, capacities, rests);
1487
+ needs[draw.need] = held.need;
1488
+ for (const [key, each] of held.perDay) used.set(key, (used.get(key) ?? 0) + each);
1489
+ for (const [resource, rest] of held.rests) rests.set(resource, rest);
1490
+ before = held.stock;
1491
+ for (const [index, amount] of held.lots.entries()) later[index].amount = amount;
1492
+ continue;
1493
+ }
1494
+ const share = shares ? bestShare({
1495
+ draw,
1496
+ stock: before,
1497
+ room,
1498
+ direct: ways.direct,
1499
+ converters: ways.converters,
1500
+ makers: [...reach].filter((converter) => !ways.converters.includes(converter)),
1501
+ demand
1502
+ }) : void 0;
1503
+ let low;
1504
+ let left;
1505
+ let final;
1506
+ const came = new Map(before);
1507
+ const lost = /* @__PURE__ */ new Map();
1508
+ const pool = [...before].map(([resource, amount]) => storeLot(resource, amount));
1509
+ const arrived = [];
1510
+ const again = [];
1511
+ let atHorizon = false;
1512
+ const perDay = /* @__PURE__ */ new Map();
1513
+ const count = (spanLeft, days, at = 0) => {
1514
+ if (days > 0) for (const [key, free] of room) {
1515
+ const share = shareAt(key, at);
1516
+ if (!(share > 0)) continue;
1517
+ const each = (free * share * days - (spanLeft.get(RUNS + key) ?? 0)) / days / share;
1518
+ perDay.set(key, perDay.has(key) ? Math.max(perDay.get(key), each) : each);
1519
+ }
1520
+ };
1521
+ let spanDays;
1522
+ let spanAt = 0;
1523
+ if (share !== void 0) {
1524
+ low = share.days;
1525
+ spanDays = low;
1526
+ left = new Map(before);
1527
+ for (const [resource, amount] of share.taken) left.set(resource, Math.max(0, (left.get(resource) ?? 0) - amount));
1528
+ for (const [key, free] of room) left.set(RUNS + key, Math.max(0, free * low - (share.used.get(key) ?? 0)));
1529
+ final = left;
1530
+ count(left, low);
1531
+ } else if (later.length === 0 && !seasonal) {
1532
+ ({days: low, left} = span(before, 1e400, capacity(start, ways)));
1533
+ spanDays = low;
1534
+ final = left;
1535
+ count(left, low);
1536
+ } else {
1537
+ let stock = new Map(before);
1538
+ let next = 0;
1539
+ let at = 0;
1540
+ let first;
1541
+ let resumed = 0;
1542
+ const advance = () => {
1543
+ while (next < later.length && later[next].day <= at) {
1544
+ const harvest = later[next];
1545
+ const lot = {
1546
+ resource: harvest.resource,
1547
+ day: harvest.day,
1548
+ spoils: harvest.spoils,
1549
+ left: harvest.amount,
1550
+ lost: 0
1551
+ };
1552
+ pool.push(lot);
1553
+ arrived.push({
1554
+ lot,
1555
+ harvest
1556
+ });
1557
+ stock.set(lot.resource, (stock.get(lot.resource) ?? 0) + lot.left);
1558
+ came.set(lot.resource, (came.get(lot.resource) ?? 0) + lot.left);
1559
+ next += 1;
1560
+ }
1561
+ for (const lot of pool) {
1562
+ if (!(lot.left > 0) || lot.spoils > at) continue;
1563
+ stock.set(lot.resource, Math.max(0, (stock.get(lot.resource) ?? 0) - lot.left));
1564
+ lost.set(lot.resource, (lost.get(lot.resource) ?? 0) + lot.left);
1565
+ lot.lost += lot.left;
1566
+ lot.left = 0;
1567
+ }
1568
+ };
1569
+ advance();
1570
+ for (;;) {
1571
+ const spoil = Math.min(...pool.filter((lot) => lot.left > 0).map((lot) => lot.spoils));
1572
+ const end = Math.min(next < later.length ? later[next].day : 1e400, spoil, horizon, nextMonth(at));
1573
+ const part = span(stock, end - at, capacity(stock, ways, shareAt, at), at);
1574
+ count(part.left, part.days, at);
1575
+ const rest = resourcesOnly(part.left);
1576
+ useLots(pool, stock, rest);
1577
+ stock = rest;
1578
+ const stop = at + part.days;
1579
+ if (part.days < end - at) {
1580
+ if (first === void 0) first = {
1581
+ days: stop,
1582
+ left: part.left,
1583
+ spanDays: part.days,
1584
+ spanAt: at
1585
+ };
1586
+ else if (stop > resumed) again.push({
1587
+ from: resumed,
1588
+ to: stop
1589
+ });
1590
+ const resume = Math.min(next < later.length ? later[next].day : 1e400, nextMonth(at));
1591
+ if (!(resume < horizon)) break;
1592
+ at = resume;
1593
+ resumed = at;
1594
+ } else {
1595
+ at = end;
1596
+ if (at >= horizon) {
1597
+ if (first === void 0) atHorizon = true;
1598
+ else again.push({
1599
+ from: resumed,
1600
+ to: horizon
1601
+ });
1602
+ break;
1603
+ }
1604
+ }
1605
+ advance();
1606
+ }
1607
+ low = first?.days ?? horizon;
1608
+ left = first?.left ?? stock;
1609
+ spanDays = first?.spanDays ?? horizon;
1610
+ spanAt = first?.spanAt ?? 0;
1611
+ final = stock;
1612
+ }
1613
+ const stores = resourcesOnly(left);
1614
+ const binding = atHorizon ? [] : [...closure].filter((resource) => !makers.has(resource) || stocked.has(resource)).filter((resource) => mostResource(stores, makers, resource, NO_PATH) <= USED_UP * Math.max(1, start.get(resource) ?? 0)).sort();
1615
+ const takes = {};
1616
+ for (const [resource, amount] of came) {
1617
+ const taken = amount - (final.get(resource) ?? 0) - (lost.get(resource) ?? 0);
1618
+ if (taken > 0) takes[resource] = taken;
1619
+ }
1620
+ const spoiled = Object.fromEntries([...lost].filter(([, amount]) => amount > 0));
1621
+ const runsLeft = (converter) => (daysLeft(left, converter) ?? 0) * (converter.perDay ?? 0);
1622
+ const runsGiven = (converter) => (devices.get(deviceKey(converter)) ?? 1) * shareAt(deviceKey(converter), spanAt) * (converter.perDay ?? 0) * spanDays;
1623
+ const capped = atHorizon ? [] : limited.filter((converter) => reach.has(converter)).filter((converter) => runsLeft(converter) <= USED_UP * Math.max(1, runsGiven(converter))).filter((converter) => mostRuns(stores, makers, converter, NO_PATH) > USED_UP).map((converter) => converter.id).sort();
1624
+ needs[draw.need] = {
1625
+ days: low,
1626
+ binding,
1627
+ takes,
1628
+ ...capped.length === 0 ? {} : { capped },
1629
+ ...atHorizon ? { atHorizon: true } : {},
1630
+ ...again.length === 0 ? {} : { again },
1631
+ ...Object.keys(spoiled).length === 0 ? {} : { spoiled }
1632
+ };
1633
+ for (const [key, each] of perDay) used.set(key, (used.get(key) ?? 0) + each);
1634
+ if (later.length === 0 && !seasonal) {
1635
+ before = resourcesOnly(final);
1636
+ continue;
1637
+ }
1638
+ for (const lot of pool) if (lot.day === -1e400) before.set(lot.resource, lot.left);
1639
+ for (const { lot, harvest } of arrived) harvest.amount = lot.left + lot.lost;
1640
+ }
1641
+ return {
1642
+ case: caseCuts.case,
1643
+ at: options.at,
1644
+ needs,
1645
+ ...harvests.length === 0 ? {} : { harvests }
1646
+ };
1647
+ }
1648
+ /** This function gives the horizon of a layer with a season, or throws a `RangeError` for a horizon that is not more than 0. */
1649
+ function seasonHorizon(horizon) {
1650
+ const value = horizon ?? 730;
1651
+ if (!(value > 0) || !Number.isFinite(value)) throw new RangeError(`The horizon ${String(horizon)} is not a number of days more than 0.`);
1652
+ return value;
1653
+ }
1654
+ /** This function tells if two converters of `reach` with a limit `perDay` more than 0 share one device. */
1655
+ function sharesDevice(reach) {
1656
+ const seen = /* @__PURE__ */ new Set();
1657
+ for (const converter of reach) {
1658
+ if (converter.perDay === void 0 || !(converter.perDay > 0)) continue;
1659
+ const key = deviceKey(converter);
1660
+ if (seen.has(key)) return true;
1661
+ seen.add(key);
1662
+ }
1663
+ return false;
1664
+ }
1665
+ /**
1666
+ * This function gives an upper limit of a need that the stores give with no other draw, through each chain. A source
1667
+ * (M2-solar) with a share more than 0 gives no upper limit, thus the limit is Infinity. The span of the sweep is finite.
1668
+ */
1669
+ function capacity(start, ways, shareAt, at = 0) {
1670
+ for (const converter of ways.open) if ((shareAt === void 0 ? 1 : shareAt(deviceKey(converter), at)) > 0) return 1e400;
1671
+ let total = 0;
1672
+ for (const use of ways.direct) total += mostResource(start, ways.makers, use.resource, NO_PATH) * use.amount;
1673
+ for (const converter of ways.converters) total += mostRuns(start, ways.makers, converter, NO_PATH) * converter.gives.amount;
1674
+ return total;
1675
+ }
8
1676
  // src/joint.ts
9
1677
  /**
10
1678
  * 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.
@@ -64,8 +1732,7 @@ function jointDays(layer, caseCuts, options, needs) {
64
1732
  if (plan.length === 0) return endless;
65
1733
  const parts = caseParts(layer, stoppedParts, stock, planned);
66
1734
  if (supply !== void 0) {
67
- const devices = new Map([...deviceUse([...parts.cooks, ...parts.makers].map((converter) => [converter, 0])).limits].map(([key, limit]) => [key, limit.devices]));
68
- const { atHorizon, ...joint } = seasonJoint(seasonPlan(supply, parts, caseCuts, plan, devices, storeCapacities(layer, stoppedParts)), new Set(layer.stores.map((store) => store.resource)));
1735
+ const { atHorizon, ...joint } = seasonJoint(seasonPlan(supply, parts, caseCuts, plan, new Map([...deviceUse([...parts.cooks, ...parts.makers].map((converter) => [converter, 0])).limits].map(([key, limit]) => [key, limit.devices])), storeCapacities(layer, stoppedParts)), new Set(layer.stores.map((store) => store.resource)));
69
1736
  return {
70
1737
  ...base,
71
1738
  ...joint,
@@ -305,8 +1972,7 @@ function bestSeason(layer, caseCuts, options, stoppedParts) {
305
1972
  const supply = seasonSupply(layer, stoppedParts, options);
306
1973
  const draws = caseDraws(layer, caseCuts, stoppedParts);
307
1974
  const parts = caseParts(layer, stoppedParts, supply.stock, new Set(draws.map((draw) => draw.need)));
308
- const devices = new Map([...deviceUse([...parts.cooks, ...parts.makers].map((converter) => [converter, 0])).limits].map(([key, limit]) => [key, limit.devices]));
309
- const plan = seasonPlan(supply, parts, caseCuts, draws, devices, storeCapacities(layer, stoppedParts));
1975
+ const plan = seasonPlan(supply, parts, caseCuts, draws, new Map([...deviceUse([...parts.cooks, ...parts.makers].map((converter) => [converter, 0])).limits].map(([key, limit]) => [key, limit.devices])), storeCapacities(layer, stoppedParts));
310
1976
  const harvests = supply.harvests.length === 0 ? {} : { harvests: supply.harvests };
311
1977
  if (draws.length === 0) return {
312
1978
  case: caseCuts.case,
@@ -370,8 +2036,7 @@ function buildStep(parts, caseCuts, draws, fixed, open, devices, mode, horizon)
370
2036
  for (const draw of draws) {
371
2037
  const fix = fixed.get(draw.need);
372
2038
  if (fix === void 0 && !opened.has(draw.need)) continue;
373
- const endless = fix?.endless ?? mode === "day";
374
- const block = drawBlock(program, parts, draw, !endless);
2039
+ const block = drawBlock(program, parts, draw, !(fix?.endless ?? mode === "day"));
375
2040
  blocks.push(block);
376
2041
  const demand = exact(drawDemand(draw, caseCuts));
377
2042
  const need = new Map(block.gifts);
@@ -1626,17 +3291,46 @@ function estimateOf(counts) {
1626
3291
  });
1627
3292
  return kaplanMeier(observations);
1628
3293
  }
1629
- /** This function gives the curve of the one cut of the stop of a draw, when that cut has counts with no fault. */
1630
- function countedCurveOf(layer, caseCuts, need, options) {
3294
+ /**
3295
+ * This function gives the Greenwood reads of a curve from its sums. The read at a day is the read of the last point at or before that day.
3296
+ * This is the step rule of a Kaplan-Meier curve. `changeInterval` reads only the days of the points, so each read is the read of a point.
3297
+ */
3298
+ function sumsRead(curve, sums) {
3299
+ return (day) => {
3300
+ let found;
3301
+ for (const [index, [point, chance]] of curve.entries()) {
3302
+ if (point > day) break;
3303
+ found = {
3304
+ time: day,
3305
+ chance,
3306
+ sum: sums[index] ?? 0
3307
+ };
3308
+ }
3309
+ return found;
3310
+ };
3311
+ }
3312
+ /** This function gives the Greenwood reads of the Kaplan-Meier estimate of a table of counts. A day after `last` has no read. */
3313
+ function countsRead(counts) {
3314
+ const estimate = estimateOf(counts);
3315
+ return (day) => day > counts.last ? void 0 : greenwoodRead(estimate, day);
3316
+ }
3317
+ /**
3318
+ * This function gives the curve of the one cut of the stop of a draw, when that cut has sums or counts with no fault.
3319
+ * The sums come first, because they are the short form. A cut with sums that have a fault uses its counts.
3320
+ */
3321
+ function readCurveOf(layer, caseCuts, need, options) {
1631
3322
  const draw = layer.draws.find((item) => item.need === need);
1632
3323
  const used = draw === void 0 ? void 0 : stopCuts(caseCuts, draw, options);
1633
3324
  if (used === void 0 || used.length !== 1) return void 0;
1634
3325
  const cut = caseCuts.cuts[used[0] ?? -1];
1635
- if (cut?.duration === void 0 || cut.counts === void 0 || countsFault(cut.duration, cut.counts) !== void 0) return void 0;
1636
- return {
3326
+ if (cut?.duration === void 0) return void 0;
3327
+ if (cut.sums !== void 0 && sumsFault(cut.duration, cut.sums) === void 0) return {
3328
+ curve: cut.duration,
3329
+ read: sumsRead(cut.duration, cut.sums)
3330
+ };
3331
+ if (cut.counts !== void 0 && countsFault(cut.duration, cut.counts) === void 0) return {
1637
3332
  curve: cut.duration,
1638
- last: cut.counts.last,
1639
- estimate: estimateOf(cut.counts)
3333
+ read: countsRead(cut.counts)
1640
3334
  };
1641
3335
  }
1642
3336
  /**
@@ -1657,34 +3351,28 @@ function pointWeights(curve, days) {
1657
3351
  return [];
1658
3352
  }
1659
3353
  /**
1660
- * This function gives the interval of the change of the chance, from the counts of the one cut of the stop.
3354
+ * This function gives the interval of the change of the chance, from the sums or the counts of the one cut of the stop.
1661
3355
  *
1662
3356
  * - The change is `S(before) - S(after)`. A read at or after the horizon is 0, so it adds no term.
1663
- * - Each read of the curve is a weighted sum of the chances of the estimate at up to two points. A point after `last` has the chance 0.
1664
- * - The variance of the weighted sum uses the covariance of each two chances. `survivalDifference` of rigor-statistics gives
1665
- * the variance of each chance and of each difference, so `Cov(a, b) = (Var S(a) + Var S(b) - Var(S(a) - S(b))) / 2`.
3357
+ * - Each read of the curve is a weighted sum of the chances of the estimate at up to two points. A point with no read has the chance 0.
3358
+ * - `survivalCombination` of rigor-statistics gives the Greenwood error of the weighted sum.
3359
+ * The covariance of the chances at two points `a <= b` is `S(a) * S(b) * V(a)`.
1666
3360
  */
1667
- function changeInterval(read, before, after, horizon, change) {
3361
+ function changeInterval(curve, before, after, horizon, change) {
1668
3362
  const terms = [];
1669
3363
  const add = (days, sign) => {
1670
3364
  if (days >= horizon) return;
1671
- for (const [day, weight] of pointWeights(read.curve, days)) if (day > 0 && day <= read.last) terms.push([day, sign * weight]);
3365
+ for (const [day, weight] of pointWeights(curve.curve, days)) {
3366
+ const read = day > 0 ? curve.read(day) : void 0;
3367
+ if (read !== void 0) terms.push({
3368
+ read,
3369
+ weight: sign * weight
3370
+ });
3371
+ }
1672
3372
  };
1673
3373
  add(before, 1);
1674
3374
  add(after, -1);
1675
- const square = (from, to) => {
1676
- const difference = survivalDifference(read.estimate, from, to);
1677
- return difference === void 0 ? void 0 : difference.se * difference.se;
1678
- };
1679
- let variance = 0;
1680
- for (const [a, weightA] of terms) for (const [b, weightB] of terms) {
1681
- const atA = square(0, a);
1682
- const atB = square(0, b);
1683
- const between = square(a, b);
1684
- if (atA === void 0 || atB === void 0 || between === void 0) return void 0;
1685
- variance += weightA * weightB * ((atA + atB - between) / 2);
1686
- }
1687
- const se = Math.sqrt(Math.max(0, variance));
3375
+ const { se } = survivalCombination(terms);
1688
3376
  const [floor, ceiling] = (after >= horizon ? 1e400 : after) >= (before >= horizon ? 1e400 : before) ? [0, 1] : [-1, 0];
1689
3377
  const clamp = (value) => Math.min(ceiling, Math.max(floor, value));
1690
3378
  return {
@@ -1722,8 +3410,8 @@ function rankOrder$1(levels) {
1722
3410
  * - The days are exact for the inputs. `chance` is the chance that a draw gets its need through the event. It comes
1723
3411
  * from `caseOutlook` with the share `take`, before and after the step, with the bands of the cuts. The change of the
1724
3412
  * chance is the change of the point values.
1725
- * - The change has a 95% interval (`SensitivityChance.interval`) when the stop of the draw uses one cut (`stopCuts`) with counts.
1726
- * A stop of two or more cuts has no interval. A cut with no counts, or with counts that have a fault, also has no interval.
3413
+ * - The change has a 95% interval (`SensitivityChance.interval`) when the stop of the draw uses one cut (`stopCuts`) with sums or counts.
3414
+ * A stop of two or more cuts has no interval. A cut with no sums and no counts, or with only reads that have a fault, also has no interval.
1727
3415
  *
1728
3416
  * The cost is one `enduranceOf` and one `caseOutlook` for each input, and one `stopCuts` for each draw of the base. The function is pure.
1729
3417
  *
@@ -1744,7 +3432,7 @@ function enduranceSensitivity(layer, caseCuts, options) {
1744
3432
  }).draws.map((draw) => [draw.need, draw]));
1745
3433
  const baseOutlook = outlookOf(layer);
1746
3434
  const counted = new Map([...baseOutlook.keys()].flatMap((need) => {
1747
- const read = countedCurveOf(layer, caseCuts, need, caseOptions);
3435
+ const read = readCurveOf(layer, caseCuts, need, caseOptions);
1748
3436
  return read === void 0 ? [] : [[need, read]];
1749
3437
  }));
1750
3438
  const horizon = caseOptions.horizon ?? 1e400;