@mark1russell7/stack-endurance 0.8.18 → 0.8.20

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.
@@ -1,6 +1,6 @@
1
1
  import { t as ENDURANCE_SCHEMA } from "./layer-a3Fr70Uh.js";
2
2
  import { CUT_BOUNDS, bandFault, curveFault, curveFault as curveFault$1, dayNumber, intervalFault, isCutBound, joinRecords, joinSetting, stopped } from "@mark1russell7/system-stack";
3
- import { ONE, ZERO, add, div, fromFloat, mul, neg, sign, toNumber } from "@mark1russell7/rational";
3
+ import { ONE, ZERO, add, div, equals, fromFloat, mul, neg, sign, sub, toNumber } from "@mark1russell7/rational";
4
4
  import { solveLexicographic } from "@mark1russell7/linear";
5
5
  import { stronglyConnectedComponents } from "@mark1russell7/collections/graph";
6
6
  import { canonicalJson } from "@mark1russell7/rigor-generators";
@@ -11,9 +11,21 @@ function inputsOf(converter) {
11
11
  for (const input of converter.takes) if (input.amount > 0) out.set(input.resource, (out.get(input.resource) ?? 0) + input.amount);
12
12
  return out;
13
13
  }
14
- /** This function tells if a converter can run in a case. Its device works, it takes a resource, and it gives an amount more than 0. */
14
+ /**
15
+ * This function tells if a converter is a source (M2-solar): it takes nothing, and it has a limit `perDay` more than 0.
16
+ * Its runs of a day are lost when no draw uses them. Thus a take uses a source before a store.
17
+ */
18
+ function isSource(converter) {
19
+ if (!(converter.perDay !== void 0 && converter.perDay > 0)) return false;
20
+ for (const input of converter.takes) if (input.amount > 0) return false;
21
+ return true;
22
+ }
23
+ /**
24
+ * This function tells if a converter can run in a case. Its device works, it takes a resource or it is a source, and it
25
+ * gives an amount more than 0.
26
+ */
15
27
  function canRun(converter, stoppedParts) {
16
- return converter.gives.amount > 0 && inputsOf(converter).size > 0 && (converter.device === void 0 || !stoppedParts.has(converter.device));
28
+ return converter.gives.amount > 0 && (inputsOf(converter).size > 0 || isSource(converter)) && (converter.device === void 0 || !stoppedParts.has(converter.device));
17
29
  }
18
30
  /**
19
31
  * This function gives the key of the device-days that a converter uses. The converters of one device share one key.
@@ -269,6 +281,492 @@ function reachOf(parts, needs) {
269
281
  reach: /* @__PURE__ */ new Set([...cooks, ...parts.makers.filter((maker) => closure.has(giftResource(maker) ?? ""))])
270
282
  };
271
283
  }
284
+ // src/seasonal.ts
285
+ /**
286
+ * This function gives the parts of the programs of a case with a season. `parts` are the parts of the case with the
287
+ * stock after the sowings (`seasonSupply`).
288
+ */
289
+ function seasonPlan(supply, parts, caseCuts, draws, devices) {
290
+ const total = new Map(supply.stock);
291
+ const harvests = supply.lots.map((lot, origin) => ({
292
+ ...lot,
293
+ origin
294
+ })).filter((lot) => parts.resources.has(lot.resource));
295
+ for (const lot of harvests) total.set(lot.resource, (total.get(lot.resource) ?? 0) + lot.amount);
296
+ const all = partsOf(total, parts.direct, parts.cooks, parts.makers);
297
+ const lots = [...all.stocked.filter((resource) => (supply.stock.get(resource) ?? 0) > 0).map((resource) => ({
298
+ resource,
299
+ day: 0,
300
+ spoils: 1e400,
301
+ amount: exact(supply.stock.get(resource) ?? 0)
302
+ })), ...harvests.map((lot) => ({
303
+ resource: lot.resource,
304
+ day: Math.max(0, lot.day),
305
+ spoils: lot.spoils,
306
+ amount: exact(lot.amount),
307
+ origin: lot.origin
308
+ }))];
309
+ const inside = (day) => day > 0 && day < supply.horizon;
310
+ const shares = monthlyShares([...all.cooks, ...all.makers]);
311
+ const months = shares.size === 0 ? [] : monthEdges(supply.start, supply.horizon);
312
+ const edges = [.../* @__PURE__ */ new Set([
313
+ 0,
314
+ supply.horizon,
315
+ ...months,
316
+ ...lots.flatMap((lot) => [lot.day, lot.spoils]).filter(inside)
317
+ ])].sort((a, b) => a - b);
318
+ return {
319
+ parts: all,
320
+ caseCuts,
321
+ draws,
322
+ devices,
323
+ lots,
324
+ edges,
325
+ shares,
326
+ months: edges.slice(0, -1).map((edge) => shares.size === 0 ? 0 : monthOf(supply.start, edge))
327
+ };
328
+ }
329
+ const edgeOf = (plan, index) => exact(plan.edges[index] ?? 0);
330
+ const lengthOf = (plan, index) => sub(edgeOf(plan, index + 1), edgeOf(plan, index));
331
+ const segmentsOf = (plan) => plan.edges.length - 1;
332
+ /** 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. */
333
+ function fixedFed(plan, fix, segment) {
334
+ if (segment < fix.segment) return lengthOf(plan, segment);
335
+ if (segment === fix.segment) return sub(fix.stop, edgeOf(plan, segment));
336
+ return ZERO;
337
+ }
338
+ /**
339
+ * 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.
340
+ * The share of each stock is the sum of the takes of the lots that are ready and not spoiled in the whole segment.
341
+ */
342
+ function addCell(program, plan, draw, segment, fed) {
343
+ const block = drawBlock(program, plan.parts, draw);
344
+ const demand = exact(drawDemand(draw, plan.caseCuts));
345
+ const need = new Map(block.gifts);
346
+ if (typeof fed === "number") {
347
+ addTo(need, fed, neg(demand));
348
+ program.push(need, ">=", ZERO);
349
+ } else program.push(need, ">=", mul(demand, fed));
350
+ const from = plan.edges[segment] ?? 0;
351
+ const to = plan.edges[segment + 1] ?? 1e400;
352
+ const takes = /* @__PURE__ */ new Map();
353
+ for (const [resource, share] of block.shares) {
354
+ const row = /* @__PURE__ */ new Map([[share, ONE]]);
355
+ for (const lot of plan.lots) {
356
+ if (lot.resource !== resource || lot.day > from || lot.spoils < to) continue;
357
+ const column = program.next();
358
+ takes.set(lot, column);
359
+ addTo(row, column, neg(ONE));
360
+ }
361
+ program.push(row, "=", ZERO);
362
+ }
363
+ return {
364
+ draw,
365
+ segment,
366
+ block,
367
+ fed,
368
+ takes
369
+ };
370
+ }
371
+ /** This function adds the row of each lot: the takes of all the cells are not more than its amount. */
372
+ function lotRows(program, plan, cells) {
373
+ for (const lot of plan.lots) {
374
+ const row = /* @__PURE__ */ new Map();
375
+ for (const cell of cells) {
376
+ const column = cell.takes.get(lot);
377
+ if (column !== void 0) addTo(row, column, ONE);
378
+ }
379
+ if (row.size > 0) program.push(row, "<=", lot.amount);
380
+ }
381
+ }
382
+ /**
383
+ * 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
384
+ * 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.
385
+ */
386
+ function addFixed(program, plan, fixed, cells) {
387
+ const kept = /* @__PURE__ */ new Map();
388
+ for (const draw of plan.draws) {
389
+ const fix = fixed.get(draw.need);
390
+ if (fix === void 0) continue;
391
+ for (let segment = 0; segment <= fix.segment; segment += 1) {
392
+ const fed = fixedFed(plan, fix, segment);
393
+ const keep = fix.keep.get(segment) ?? /* @__PURE__ */ new Map();
394
+ const into = kept.get(segment) ?? /* @__PURE__ */ new Map();
395
+ kept.set(segment, into);
396
+ for (const [key, value] of keep) into.set(key, add(into.get(key) ?? ZERO, value));
397
+ if (sign(fed) <= 0) continue;
398
+ const cell = addCell(program, plan, draw, segment, fed);
399
+ cells.push(cell);
400
+ const { limits, stopped } = deviceUse(cell.block.runs);
401
+ for (const index of stopped) program.push(/* @__PURE__ */ new Map([[index, ONE]]), "<=", ZERO);
402
+ for (const [key, limit] of limits) program.push(limit.row, "<=", mul(keep.get(key) ?? ZERO, fed));
403
+ }
404
+ }
405
+ return kept;
406
+ }
407
+ /** 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. */
408
+ function shareIn(plan, segment, key) {
409
+ return shareOf(plan.shares, key, plan.months[segment] ?? 0);
410
+ }
411
+ /** 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. */
412
+ function roomOf(plan, kept, segment, key, devices) {
413
+ const left = sub(mul(exact(plan.devices.get(key) ?? devices), exact(shareIn(plan, segment, key))), kept.get(segment)?.get(key) ?? ZERO);
414
+ return sign(left) > 0 ? left : ZERO;
415
+ }
416
+ /**
417
+ * This function gives the program of one step with the stop of the open draws in segment `segment`. The open draws are fed in
418
+ * each segment before it. In it, each one is fed for `t - edge` days or more, and their runs share the device-days that
419
+ * the fixed draws leave, for `t - edge` days. This is the safe side, as in `bestEndurance`.
420
+ */
421
+ function buildStep(plan, fixed, open, segment) {
422
+ const program = new Program();
423
+ const t = program.next();
424
+ program.push(/* @__PURE__ */ new Map([[t, ONE]]), "<=", edgeOf(plan, segment + 1));
425
+ const cells = [];
426
+ const kept = addFixed(program, plan, fixed, cells);
427
+ const opened = new Set(open.map((draw) => draw.need));
428
+ const floors = /* @__PURE__ */ new Map();
429
+ for (const draw of plan.draws) {
430
+ if (!opened.has(draw.need)) continue;
431
+ for (let index = 0; index < segment; index += 1) cells.push(addCell(program, plan, draw, index, lengthOf(plan, index)));
432
+ const fed = program.next();
433
+ program.push(/* @__PURE__ */ new Map([[fed, ONE]]), "<=", lengthOf(plan, segment));
434
+ floors.set(draw.need, program.push(/* @__PURE__ */ new Map([[fed, ONE], [t, neg(ONE)]]), ">=", neg(edgeOf(plan, segment))));
435
+ cells.push(addCell(program, plan, draw, segment, fed));
436
+ }
437
+ const shared = /* @__PURE__ */ new Map();
438
+ for (let index = 0; index <= segment; index += 1) {
439
+ const { limits, stopped } = deviceUse(cells.filter((cell) => cell.segment === index && opened.has(cell.draw.need)).flatMap((cell) => [...cell.block.runs]));
440
+ for (const column of stopped) program.push(/* @__PURE__ */ new Map([[column, ONE]]), "<=", ZERO);
441
+ const bySegment = /* @__PURE__ */ new Map();
442
+ shared.set(index, bySegment);
443
+ for (const [key, limit] of limits) {
444
+ const room = roomOf(plan, kept, index, key, limit.devices);
445
+ bySegment.set(key, {
446
+ row: limit.row,
447
+ room,
448
+ converters: limit.converters
449
+ });
450
+ const row = new Map(limit.row);
451
+ if (index < segment) program.push(row, "<=", mul(room, lengthOf(plan, index)));
452
+ else {
453
+ addTo(row, t, neg(room));
454
+ program.push(row, "<=", neg(mul(room, edgeOf(plan, segment))));
455
+ }
456
+ }
457
+ }
458
+ lotRows(program, plan, cells);
459
+ return {
460
+ program,
461
+ t,
462
+ cells,
463
+ floors,
464
+ shared,
465
+ segment
466
+ };
467
+ }
468
+ /**
469
+ * This function gives the largest common first stop of the open draws, with the fixed draws at their stops. The days to
470
+ * a first stop are not a linear function of the takes, so the function tries the segments in order. When the days reach
471
+ * the end of a segment, it tries the next segment. The days of the last step are exact.
472
+ * After the largest days, the step takes the objectives of `tail`.
473
+ */
474
+ function firstStop(plan, fixed, open, tail = () => []) {
475
+ const segments = segmentsOf(plan);
476
+ for (let segment = 0; segment < segments; segment += 1) {
477
+ const step = buildStep(plan, fixed, open, segment);
478
+ const most = {
479
+ sense: "max",
480
+ coefficients: dense(/* @__PURE__ */ new Map([[step.t, ONE]]), step.program.count)
481
+ };
482
+ const solved = solveLexicographic(step.program.constraints(), [most]);
483
+ 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.");
484
+ const days = solved.values[0] ?? ZERO;
485
+ const end = edgeOf(plan, segment + 1);
486
+ if (segment + 1 < segments && equals(days, end)) continue;
487
+ const full = tail(step).length === 0 ? solved : solveLexicographic(step.program.constraints(), [most, ...tail(step)]);
488
+ if (full.status !== "optimal") throw new Error("The step of a season has no optimum for its later objectives.");
489
+ const first = full.stages[0]?.result;
490
+ return {
491
+ step,
492
+ x: full.x,
493
+ dual: first?.status === "optimal" ? first.dual : [],
494
+ days,
495
+ atHorizon: segment + 1 === segments && equals(days, end)
496
+ };
497
+ }
498
+ throw new Error("A season plan has no segment.");
499
+ }
500
+ /** This function gives the fewest device-days of the runs of the open cells of a step, as an objective. */
501
+ function fewestOpen(step, open) {
502
+ return {
503
+ sense: "min",
504
+ coefficients: dense(fewestRow(step.cells.filter((cell) => open.has(cell.draw.need)).flatMap((cell) => [...cell.block.runs])), step.program.count)
505
+ };
506
+ }
507
+ /** This function gives the smallest sum of the shares of the stocks, each over the total of its lots, as an objective. */
508
+ function leastShares(plan, cells, count) {
509
+ const least = /* @__PURE__ */ new Map();
510
+ for (const cell of cells) for (const [resource, index] of cell.block.shares) addTo(least, index, div(ONE, exact(plan.parts.stock.get(resource) ?? 1)));
511
+ return {
512
+ sense: "min",
513
+ coefficients: dense(least, count)
514
+ };
515
+ }
516
+ /** This function fixes the open draws of `done` at the stop: the device-days of each day that they keep, and their capped converters. */
517
+ function fixStops(plan, stop, done, fixed) {
518
+ const { step, x, days } = stop;
519
+ const fedIn = (segment) => segment < step.segment ? lengthOf(plan, segment) : sub(days, edgeOf(plan, step.segment));
520
+ const full = /* @__PURE__ */ new Set();
521
+ 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}`);
522
+ for (const draw of done) {
523
+ const keep = /* @__PURE__ */ new Map();
524
+ const used = /* @__PURE__ */ new Set();
525
+ for (const cell of step.cells) {
526
+ if (cell.draw.need !== draw.need) continue;
527
+ const fed = fedIn(cell.segment);
528
+ const bySegment = /* @__PURE__ */ new Map();
529
+ keep.set(cell.segment, bySegment);
530
+ for (const [key, limit] of deviceUse(cell.block.runs).limits) {
531
+ bySegment.set(key, sign(fed) > 0 ? div(valueAt(limit.row, x), fed) : ZERO);
532
+ if (full.has(`${String(cell.segment)}\u0000${key}`)) for (const converter of limit.converters) used.add(converter);
533
+ }
534
+ }
535
+ const { reach } = reachOf(plan.parts, /* @__PURE__ */ new Set([draw.need]));
536
+ 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() : [];
537
+ fixed.set(draw.need, {
538
+ stop: days,
539
+ segment: step.segment,
540
+ keep,
541
+ atHorizon: stop.atHorizon,
542
+ capped
543
+ });
544
+ }
545
+ }
546
+ /** This function gives the sum of the take of each resource of the cells of one need, more than 0 only. */
547
+ function takesOf(cells, need, x) {
548
+ const sums = /* @__PURE__ */ new Map();
549
+ for (const cell of cells) {
550
+ if (cell.draw.need !== need) continue;
551
+ for (const [resource, index] of cell.block.shares) sums.set(resource, add(sums.get(resource) ?? ZERO, x[index] ?? ZERO));
552
+ }
553
+ const out = {};
554
+ for (const [resource, value] of [...sums].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) if (sign(value) > 0) out[resource] = toNumber(value);
555
+ return out;
556
+ }
557
+ /** 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. */
558
+ function usedUp(plan, cells, x, closure, stored) {
559
+ return [...closure].filter((resource) => stored.has(resource)).filter((resource) => {
560
+ let taken = ZERO;
561
+ let amount = ZERO;
562
+ for (const lot of plan.lots) {
563
+ if (lot.resource !== resource) continue;
564
+ amount = add(amount, lot.amount);
565
+ for (const cell of cells) taken = add(taken, x[cell.takes.get(lot) ?? -1] ?? ZERO);
566
+ }
567
+ return equals(taken, amount);
568
+ }).sort();
569
+ }
570
+ /** This function tells if the cells of two draws or more of `cells` can use the limited device `key`. */
571
+ function sharedKey(cells, key) {
572
+ return new Set(cells.filter((cell) => deviceUse(cell.block.runs).limits.has(key)).map((cell) => cell.draw.need)).size > 1;
573
+ }
574
+ /**
575
+ * This function gives the last program of the best endurance with a season. Each draw keeps its first stop. After it, a later
576
+ * harvest can feed the draw again (`again`). The objectives come in this order:
577
+ * - the most fed days after the stops for each level, in the order of the levels.
578
+ * - the earliest fed days.
579
+ * - the smallest sum of the shares of the stocks.
580
+ * - the fewest device-days.
581
+ *
582
+ * In a segment after the stops, the cells of two draws or more that can use one limited device take turns. Their fed days
583
+ * together are not more than the segment, and each one has the device-days of each day that the stops leave. This is the
584
+ * safe side: the cells do not use one device at the same time. Each other cell starts at the start of the segment.
585
+ */
586
+ function seasonBest(plan, fixed, levels, stored) {
587
+ const program = new Program();
588
+ const cells = [];
589
+ const kept = addFixed(program, plan, fixed, cells);
590
+ const segments = segmentsOf(plan);
591
+ const again = /* @__PURE__ */ new Map();
592
+ const taking = /* @__PURE__ */ new Set();
593
+ for (const draw of plan.draws) {
594
+ const fix = fixed.get(draw.need);
595
+ for (let segment = fix.segment + 1; segment < segments; segment += 1) {
596
+ const fed = program.next();
597
+ program.push(/* @__PURE__ */ new Map([[fed, ONE]]), "<=", lengthOf(plan, segment));
598
+ const cell = addCell(program, plan, draw, segment, fed);
599
+ cells.push(cell);
600
+ again.set(cell, fed);
601
+ }
602
+ }
603
+ for (let segment = 0; segment < segments; segment += 1) {
604
+ const later = [...again.keys()].filter((cell) => cell.segment === segment);
605
+ const { limits, stopped } = deviceUse(later.flatMap((cell) => [...cell.block.runs]));
606
+ for (const column of stopped) program.push(/* @__PURE__ */ new Map([[column, ONE]]), "<=", ZERO);
607
+ const turns = new Set(later.filter((cell) => [...deviceUse(cell.block.runs).limits.keys()].some((key) => sharedKey(later, key))));
608
+ if (turns.size > 0) {
609
+ const row = /* @__PURE__ */ new Map();
610
+ for (const cell of turns) addTo(row, again.get(cell), ONE);
611
+ program.push(row, "<=", lengthOf(plan, segment));
612
+ for (const cell of turns) taking.add(cell);
613
+ }
614
+ for (const [key, limit] of limits) {
615
+ const room = roomOf(plan, kept, segment, key, limit.devices);
616
+ for (const cell of later) {
617
+ const own = deviceUse(cell.block.runs).limits.get(key);
618
+ if (own === void 0) continue;
619
+ const row = new Map(own.row);
620
+ addTo(row, again.get(cell), neg(room));
621
+ program.push(row, "<=", ZERO);
622
+ }
623
+ }
624
+ }
625
+ lotRows(program, plan, cells);
626
+ const objectives = levels.map((level) => {
627
+ const needs = new Set(level.map((draw) => draw.need));
628
+ const row = /* @__PURE__ */ new Map();
629
+ for (const [cell, fed] of again) if (needs.has(cell.draw.need)) addTo(row, fed, ONE);
630
+ return {
631
+ sense: "max",
632
+ coefficients: dense(row, program.count)
633
+ };
634
+ });
635
+ const early = /* @__PURE__ */ new Map();
636
+ const horizon = edgeOf(plan, segments);
637
+ for (const [cell, fed] of again) addTo(early, fed, sub(horizon, edgeOf(plan, cell.segment)));
638
+ objectives.push({
639
+ sense: "max",
640
+ coefficients: dense(early, program.count)
641
+ });
642
+ objectives.push(leastShares(plan, cells, program.count));
643
+ objectives.push({
644
+ sense: "min",
645
+ coefficients: dense(fewestRow(cells.flatMap((cell) => [...cell.block.runs])), program.count)
646
+ });
647
+ const solved = solveLexicographic(program.constraints(), objectives);
648
+ 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.");
649
+ const x = solved.x;
650
+ const turn = /* @__PURE__ */ new Map();
651
+ const offset = /* @__PURE__ */ new Map();
652
+ for (const cell of [...taking].sort((a, b) => plan.draws.indexOf(a.draw) - plan.draws.indexOf(b.draw))) {
653
+ const start = offset.get(cell.segment) ?? ZERO;
654
+ turn.set(cell, start);
655
+ offset.set(cell.segment, add(start, x[again.get(cell)] ?? ZERO));
656
+ }
657
+ const needs = {};
658
+ for (const draw of plan.draws) {
659
+ const fix = fixed.get(draw.need);
660
+ const spans = [];
661
+ for (const [cell, fed] of again) {
662
+ if (cell.draw.need !== draw.need) continue;
663
+ const value = x[fed] ?? ZERO;
664
+ if (sign(value) <= 0) continue;
665
+ const start = add(edgeOf(plan, cell.segment), taking.has(cell) ? turn.get(cell) ?? ZERO : ZERO);
666
+ const from = toNumber(start);
667
+ const to = toNumber(add(start, value));
668
+ const last = spans[spans.length - 1];
669
+ if (last !== void 0 && last.to === from) last.to = to;
670
+ else spans.push({
671
+ from,
672
+ to
673
+ });
674
+ }
675
+ const { closure } = reachOf(plan.parts, /* @__PURE__ */ new Set([draw.need]));
676
+ needs[draw.need] = {
677
+ days: toNumber(fix.stop),
678
+ binding: fix.atHorizon ? [] : usedUp(plan, cells, x, closure, stored),
679
+ takes: takesOf(cells, draw.need, x),
680
+ ...fix.capped.length === 0 ? {} : { capped: fix.capped },
681
+ ...fix.atHorizon ? { atHorizon: true } : {},
682
+ ...spans.length === 0 ? {} : { again: spans }
683
+ };
684
+ }
685
+ const taken = /* @__PURE__ */ new Map();
686
+ for (const lot of plan.lots) {
687
+ let sum = ZERO;
688
+ for (const cell of cells) sum = add(sum, x[cell.takes.get(lot) ?? -1] ?? ZERO);
689
+ taken.set(lot, toNumber(sum));
690
+ }
691
+ const perDay = /* @__PURE__ */ new Map();
692
+ for (const cell of cells) {
693
+ const fed = typeof cell.fed === "number" ? x[cell.fed] ?? ZERO : cell.fed;
694
+ if (sign(fed) <= 0) continue;
695
+ const into = perDay.get(cell.draw.need) ?? /* @__PURE__ */ new Map();
696
+ perDay.set(cell.draw.need, into);
697
+ for (const [key, limit] of deviceUse(cell.block.runs).limits) {
698
+ const share = shareIn(plan, cell.segment, key);
699
+ if (share > 0) into.set(key, Math.max(into.get(key) ?? 0, toNumber(div(valueAt(limit.row, x), fed)) / share));
700
+ }
701
+ }
702
+ return {
703
+ needs,
704
+ taken,
705
+ perDay
706
+ };
707
+ }
708
+ /**
709
+ * This function gives the joint days of the draws of a plan with a season. The objectives come in this order:
710
+ * - the largest common first stop.
711
+ * - the smallest sum of the shares of the stocks.
712
+ * - the fewest device-days.
713
+ */
714
+ function seasonJoint(plan, stored) {
715
+ const open = new Set(plan.draws.map((draw) => draw.need));
716
+ const stop = firstStop(plan, /* @__PURE__ */ new Map(), plan.draws, (step) => [leastShares(plan, step.cells, step.program.count), fewestOpen(step, open)]);
717
+ const { step, x } = stop;
718
+ const takes = {};
719
+ for (const draw of plan.draws) takes[draw.need] = takesOf(step.cells, draw.need, x);
720
+ const total = /* @__PURE__ */ new Map();
721
+ 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));
722
+ const runs = {};
723
+ 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);
724
+ const fixed = /* @__PURE__ */ new Map();
725
+ fixStops(plan, stop, plan.draws, fixed);
726
+ const capped = [...new Set([...fixed.values()].flatMap((fix) => fix.capped))].sort();
727
+ return {
728
+ days: toNumber(stop.days),
729
+ atHorizon: stop.atHorizon,
730
+ takes,
731
+ binding: usedUp(plan, step.cells, x, reachOf(plan.parts, open).closure, stored),
732
+ runs,
733
+ capped
734
+ };
735
+ }
736
+ /**
737
+ * This function gives the endurance of one draw of `enduranceOf` that reaches two limited converters of one device in a layer
738
+ * with a season (M2-grow-share-sweep). The take order cannot give the share of the device-days.
739
+ * Thus the programs of `bestEndurance` give it for this one draw: the first stop, then the most fed days after it (`again`).
740
+ *
741
+ * @param stock - The stocks that the higher draws leave.
742
+ * @param lots - The rest of each harvest lot that the higher draws leave.
743
+ * @param room - The device-days of each day that the higher draws leave, by the key of the device, before the shares `monthly`.
744
+ * @param start - The first day of the event, for the months of the shares.
745
+ */
746
+ function seasonDraw(layer, stoppedParts, caseCuts, draw, stock, lots, horizon, room, start) {
747
+ const supply = {
748
+ stock: new Map(stock),
749
+ harvests: [],
750
+ lots,
751
+ horizon,
752
+ start
753
+ };
754
+ const plan = seasonPlan(supply, caseParts(layer, stoppedParts, supply.stock, /* @__PURE__ */ new Set([draw.need])), caseCuts, [draw], room);
755
+ const fixed = /* @__PURE__ */ new Map();
756
+ const open = /* @__PURE__ */ new Set([draw.need]);
757
+ fixStops(plan, firstStop(plan, fixed, [draw], (step) => [fewestOpen(step, open)]), [draw], fixed);
758
+ const best = seasonBest(plan, fixed, [[draw]], new Set(layer.stores.map((store) => store.resource)));
759
+ const left = new Map(stock);
760
+ const rest = lots.map((lot) => lot.amount);
761
+ for (const [lot, amount] of best.taken) if (lot.origin === void 0) left.set(lot.resource, Math.max(0, (left.get(lot.resource) ?? 0) - amount));
762
+ else rest[lot.origin] = Math.max(0, (rest[lot.origin] ?? 0) - amount);
763
+ return {
764
+ need: best.needs[draw.need],
765
+ stock: left,
766
+ lots: rest,
767
+ perDay: best.perDay.get(draw.need) ?? /* @__PURE__ */ new Map()
768
+ };
769
+ }
272
770
  // src/share.ts
273
771
  /**
274
772
  * This function gives the best share of the stocks and of the device-days for one draw.
@@ -352,6 +850,38 @@ function dayOf(date) {
352
850
  if (day === void 0) throw new RangeError(`The date "${date}" is not a date YYYY-MM-DD.`);
353
851
  return day;
354
852
  }
853
+ const DAY_MS = 864e5;
854
+ /** 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. */
855
+ function monthOf(start, day) {
856
+ dayOf(start);
857
+ return new Date(Date.parse(`${start}T00:00:00Z`) + Math.floor(day) * DAY_MS).getUTCMonth();
858
+ }
859
+ /**
860
+ * This function gives the days from the start to the first day of each month, in increasing order (M2-solar). Each
861
+ * day is more than 0 and less than the horizon. It throws a `RangeError` for a date that is not `YYYY-MM-DD`.
862
+ */
863
+ function monthEdges(start, horizon) {
864
+ dayOf(start);
865
+ const first = Date.parse(`${start}T00:00:00Z`);
866
+ const date = new Date(first);
867
+ const out = [];
868
+ for (let month = date.getUTCMonth() + 1;; month += 1) {
869
+ const day = Math.round((Date.UTC(date.getUTCFullYear(), month, 1) - first) / DAY_MS);
870
+ if (!(day < horizon)) break;
871
+ out.push(day);
872
+ }
873
+ return out;
874
+ }
875
+ /** This function gives the shares `monthly` of each device key of the converters with a limit and shares (M2-solar). */
876
+ function monthlyShares(converters) {
877
+ const out = /* @__PURE__ */ new Map();
878
+ for (const converter of converters) if (converter.monthly !== void 0 && converter.perDay !== void 0) out.set(deviceKey(converter), converter.monthly);
879
+ return out;
880
+ }
881
+ /** This function gives the share of the device-days of a key in a month: its share `monthly`, or 1. */
882
+ function shareOf(shares, key, month) {
883
+ return shares.get(key)?.[month] ?? 1;
884
+ }
355
885
  /**
356
886
  * This function gives the amount of each resource in the stores at a date, by the code of the resource.
357
887
  *
@@ -401,10 +931,15 @@ function makersOf(layer, stoppedParts) {
401
931
  return out;
402
932
  }
403
933
  function waysOf(layer, need, stoppedParts, makers) {
934
+ const converters = (layer.converters ?? []).filter((converter) => giftNeed(converter) === need && canRun(converter, stoppedParts));
935
+ const sources = converters.filter(isSource);
404
936
  return {
405
937
  direct: (layer.direct ?? []).filter((use) => use.need === need && use.amount > 0),
406
- converters: (layer.converters ?? []).filter((converter) => giftNeed(converter) === need && canRun(converter, stoppedParts)),
407
- makers
938
+ converters,
939
+ makers,
940
+ sources,
941
+ others: sources.length === 0 ? converters : converters.filter((converter) => !isSource(converter)),
942
+ open: [.../* @__PURE__ */ new Set([...sources, ...[...makers.values()].flat().filter(isSource)])]
408
943
  };
409
944
  }
410
945
  const NO_PATH = /* @__PURE__ */ new Set();
@@ -443,15 +978,25 @@ function mostRuns(left, makers, converter, path) {
443
978
  * It changes `left`, and it gives the amount that it could not take.
444
979
  */
445
980
  function takeResource(left, makers, resource, amount, path) {
981
+ let rest = amount;
982
+ const ways = path.has(resource) ? void 0 : makers.get(resource);
983
+ let next;
984
+ if (ways !== void 0 && ways.some(isSource)) {
985
+ next = new Set(path).add(resource);
986
+ for (const maker of ways) {
987
+ if (rest <= 0) break;
988
+ if (isSource(maker)) rest -= run(left, makers, maker, rest / maker.gives.amount, next) * maker.gives.amount;
989
+ }
990
+ }
446
991
  const has = left.get(resource) ?? 0;
447
- const got = Math.min(amount, has);
992
+ const got = Math.min(Math.max(0, rest), has);
448
993
  left.set(resource, has - got);
449
- let rest = amount - got;
450
- if (rest <= 0 || path.has(resource)) return Math.max(0, rest);
451
- const next = new Set(path).add(resource);
452
- for (const maker of makers.get(resource) ?? []) {
994
+ rest -= got;
995
+ if (rest <= 0 || ways === void 0) return Math.max(0, rest);
996
+ next ??= new Set(path).add(resource);
997
+ for (const maker of ways) {
453
998
  if (rest <= 0) break;
454
- rest -= run(left, makers, maker, rest / maker.gives.amount, next) * maker.gives.amount;
999
+ if (!isSource(maker)) rest -= run(left, makers, maker, rest / maker.gives.amount, next) * maker.gives.amount;
455
1000
  }
456
1001
  return Math.max(0, rest);
457
1002
  }
@@ -497,12 +1042,16 @@ function run(left, makers, converter, wanted, path) {
497
1042
  */
498
1043
  function take(left, ways, amount) {
499
1044
  let rest = amount;
1045
+ for (const converter of ways.sources) {
1046
+ if (rest <= 0) break;
1047
+ rest -= run(left, ways.makers, converter, rest / converter.gives.amount, NO_PATH) * converter.gives.amount;
1048
+ }
500
1049
  for (const use of ways.direct) {
501
1050
  if (rest <= 0) break;
502
1051
  const wanted = rest / use.amount;
503
1052
  rest -= (wanted - takeResource(left, ways.makers, use.resource, wanted, NO_PATH)) * use.amount;
504
1053
  }
505
- for (const converter of ways.converters) {
1054
+ for (const converter of ways.others) {
506
1055
  if (rest <= 0) break;
507
1056
  rest -= run(left, ways.makers, converter, rest / converter.gives.amount, NO_PATH) * converter.gives.amount;
508
1057
  }
@@ -636,7 +1185,8 @@ function sowings(layer, stoppedParts, stock, makers, start, horizon) {
636
1185
  function seasonSupply(layer, stoppedParts, options) {
637
1186
  const stock = storeAmounts(layer, options.at, stoppedParts);
638
1187
  const horizon = seasonHorizon(options.horizon);
639
- const sown = sowings(layer, stoppedParts, stock, makersOf(layer, stoppedParts), options.start ?? options.at, horizon);
1188
+ const start = options.start ?? options.at;
1189
+ const sown = sowings(layer, stoppedParts, stock, makersOf(layer, stoppedParts), start, horizon);
640
1190
  const lots = sown.lots.filter((lot) => lot.day < horizon && lot.left > 0).sort((a, b) => a.day - b.day).map((lot) => ({
641
1191
  resource: lot.resource,
642
1192
  day: lot.day,
@@ -647,12 +1197,17 @@ function seasonSupply(layer, stoppedParts, options) {
647
1197
  stock,
648
1198
  harvests: sown.harvests,
649
1199
  lots,
650
- horizon
1200
+ horizon,
1201
+ start
651
1202
  };
652
1203
  }
653
- /** This function tells if a layer has a converter with a season that can run in a case. */
1204
+ /**
1205
+ * This function tells if a layer has a converter with a season, with shares `monthly` or a source (M2-solar) that can run
1206
+ * 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
1207
+ * month end a segment. A source can feed a draw with no end, thus the horizon is the upper limit of its days.
1208
+ */
654
1209
  function hasSeason(layer, stoppedParts) {
655
- return (layer.converters ?? []).some((converter) => converter.season !== void 0 && canRun(converter, stoppedParts));
1210
+ return (layer.converters ?? []).some((converter) => (converter.season !== void 0 || converter.monthly !== void 0 || isSource(converter)) && canRun(converter, stoppedParts));
656
1211
  }
657
1212
  /**
658
1213
  * This function gives the days that each draw holds when a case stops its supply, and the resources that are used up then.
@@ -680,7 +1235,11 @@ function hasSeason(layer, stoppedParts) {
680
1235
  * - With a season, each draw takes its stocks over spans from harvest to harvest. `days` is the first stop of the
681
1236
  * draw. A later harvest can feed the draw again: `again` gives these spans, and `takes` is the sum to the horizon.
682
1237
  * A lower draw gets the stocks that the higher draws leave, the earliest stocks first taken. This is the safe side.
683
- * - A draw with a shared device and a season gets a `RangeError` (M2-grow-share).
1238
+ * - A draw with a shared device and a season gets the programs of `bestEndurance` for itself alone (M2-grow-share-sweep). Its stocks,
1239
+ * its harvest lots and its device-days are those that the higher draws leave. It has no field `spoiled`.
1240
+ * - 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
1241
+ * draw uses them. With shares `monthly`, the device-days of a day are the devices times the share of its month. Each
1242
+ * span also ends at the start of a month, and a draw can hold again from the start of a month.
684
1243
  *
685
1244
  * 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.
686
1245
  *
@@ -698,6 +1257,11 @@ function enduranceOf(layer, caseCuts, options) {
698
1257
  const stocked = new Set(layer.stores.map((store) => store.resource));
699
1258
  const limited = (layer.converters ?? []).filter((converter) => converter.perDay !== void 0 && canRun(converter, stoppedParts));
700
1259
  const devices = new Map(limited.map((converter) => [deviceKey(converter), converter.devices ?? 1]));
1260
+ const monthShares = monthlyShares(limited);
1261
+ const begin = options.start ?? options.at;
1262
+ const shareAt = (key, at) => monthShares.size === 0 ? 1 : shareOf(monthShares, key, monthOf(begin, at));
1263
+ const months = monthShares.size === 0 || supply === void 0 ? [] : monthEdges(begin, supply.horizon);
1264
+ const nextMonth = (at) => months.find((day) => day > at) ?? 1e400;
701
1265
  const used = /* @__PURE__ */ new Map();
702
1266
  let before = new Map(start);
703
1267
  const horizon = supply?.horizon ?? 1e400;
@@ -710,17 +1274,17 @@ function enduranceOf(layer, caseCuts, options) {
710
1274
  const room = new Map([...devices].map(([key, count]) => [key, Math.max(0, count - (used.get(key) ?? 0))]));
711
1275
  const closure = inputClosure(ways);
712
1276
  const reach = /* @__PURE__ */ new Set([...ways.converters, ...[...closure].flatMap((resource) => makers.get(resource) ?? [])]);
713
- const after = (stock, days) => {
1277
+ const after = (stock, days, at = 0) => {
714
1278
  const tried = new Map(stock);
715
- for (const [key, free] of room) tried.set(RUNS + key, free * days);
1279
+ for (const [key, free] of room) tried.set(RUNS + key, free * shareAt(key, at) * days);
716
1280
  return {
717
1281
  left: tried,
718
1282
  short: take(tried, ways, days * demand)
719
1283
  };
720
1284
  };
721
- const span = (stock, limit, bound) => {
1285
+ const span = (stock, limit, bound, at = 0) => {
722
1286
  const fit = largestFit(Math.min(limit, bound / demand), (days) => {
723
- const tried = after(stock, days);
1287
+ const tried = after(stock, days, at);
724
1288
  return {
725
1289
  short: tried.short,
726
1290
  need: days * demand,
@@ -729,11 +1293,24 @@ function enduranceOf(layer, caseCuts, options) {
729
1293
  });
730
1294
  return {
731
1295
  days: fit.x,
732
- left: fit.value ?? after(stock, fit.x).left
1296
+ left: fit.value ?? after(stock, fit.x, at).left
733
1297
  };
734
1298
  };
735
1299
  const shares = sharesDevice(reach);
736
- if (shares && seasonal) throw new RangeError(`The draw "${draw.need}" reaches two limited converters of one device, and the layer has a converter with a season. The query does not give their share (M2-grow-share).`);
1300
+ if (shares && seasonal) {
1301
+ const lots = later.map((lot) => ({
1302
+ resource: lot.resource,
1303
+ day: lot.day,
1304
+ spoils: lot.spoils,
1305
+ amount: lot.amount
1306
+ }));
1307
+ const held = seasonDraw(layer, stoppedParts, caseCuts, draw, resourcesOnly(before), lots, horizon, room, begin);
1308
+ needs[draw.need] = held.need;
1309
+ for (const [key, each] of held.perDay) used.set(key, (used.get(key) ?? 0) + each);
1310
+ before = held.stock;
1311
+ for (const [index, amount] of held.lots.entries()) later[index].amount = amount;
1312
+ continue;
1313
+ }
737
1314
  const share = shares ? bestShare({
738
1315
  draw,
739
1316
  stock: before,
@@ -753,13 +1330,16 @@ function enduranceOf(layer, caseCuts, options) {
753
1330
  const again = [];
754
1331
  let atHorizon = false;
755
1332
  const perDay = /* @__PURE__ */ new Map();
756
- const count = (spanLeft, days) => {
1333
+ const count = (spanLeft, days, at = 0) => {
757
1334
  if (days > 0) for (const [key, free] of room) {
758
- const each = (free * days - (spanLeft.get(RUNS + key) ?? 0)) / days;
1335
+ const share = shareAt(key, at);
1336
+ if (!(share > 0)) continue;
1337
+ const each = (free * share * days - (spanLeft.get(RUNS + key) ?? 0)) / days / share;
759
1338
  perDay.set(key, perDay.has(key) ? Math.max(perDay.get(key), each) : each);
760
1339
  }
761
1340
  };
762
1341
  let spanDays;
1342
+ let spanAt = 0;
763
1343
  if (share !== void 0) {
764
1344
  low = share.days;
765
1345
  spanDays = low;
@@ -809,9 +1389,9 @@ function enduranceOf(layer, caseCuts, options) {
809
1389
  advance();
810
1390
  for (;;) {
811
1391
  const spoil = Math.min(...pool.filter((lot) => lot.left > 0).map((lot) => lot.spoils));
812
- const end = Math.min(next < later.length ? later[next].day : 1e400, spoil, horizon);
813
- const part = span(stock, end - at, capacity(stock, ways));
814
- count(part.left, part.days);
1392
+ const end = Math.min(next < later.length ? later[next].day : 1e400, spoil, horizon, nextMonth(at));
1393
+ const part = span(stock, end - at, capacity(stock, ways, shareAt, at), at);
1394
+ count(part.left, part.days, at);
815
1395
  const rest = resourcesOnly(part.left);
816
1396
  useLots(pool, stock, rest);
817
1397
  stock = rest;
@@ -820,14 +1400,16 @@ function enduranceOf(layer, caseCuts, options) {
820
1400
  if (first === void 0) first = {
821
1401
  days: stop,
822
1402
  left: part.left,
823
- spanDays: part.days
1403
+ spanDays: part.days,
1404
+ spanAt: at
824
1405
  };
825
1406
  else if (stop > resumed) again.push({
826
1407
  from: resumed,
827
1408
  to: stop
828
1409
  });
829
- if (next >= later.length) break;
830
- at = later[next].day;
1410
+ const resume = Math.min(next < later.length ? later[next].day : 1e400, nextMonth(at));
1411
+ if (!(resume < horizon)) break;
1412
+ at = resume;
831
1413
  resumed = at;
832
1414
  } else {
833
1415
  at = end;
@@ -845,6 +1427,7 @@ function enduranceOf(layer, caseCuts, options) {
845
1427
  low = first?.days ?? horizon;
846
1428
  left = first?.left ?? stock;
847
1429
  spanDays = first?.spanDays ?? horizon;
1430
+ spanAt = first?.spanAt ?? 0;
848
1431
  final = stock;
849
1432
  }
850
1433
  const stores = resourcesOnly(left);
@@ -856,7 +1439,7 @@ function enduranceOf(layer, caseCuts, options) {
856
1439
  }
857
1440
  const spoiled = Object.fromEntries([...lost].filter(([, amount]) => amount > 0));
858
1441
  const runsLeft = (converter) => (daysLeft(left, converter) ?? 0) * (converter.perDay ?? 0);
859
- const runsGiven = (converter) => (devices.get(deviceKey(converter)) ?? 1) * (converter.perDay ?? 0) * spanDays;
1442
+ const runsGiven = (converter) => (devices.get(deviceKey(converter)) ?? 1) * shareAt(deviceKey(converter), spanAt) * (converter.perDay ?? 0) * spanDays;
860
1443
  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();
861
1444
  needs[draw.need] = {
862
1445
  days: low,
@@ -900,10 +1483,11 @@ function sharesDevice(reach) {
900
1483
  return false;
901
1484
  }
902
1485
  /**
903
- * This function gives an upper limit of a need that the stores give with no other draw, through each chain.
904
- * A converter that takes nothing gives nothing: the gate refuses it.
1486
+ * This function gives an upper limit of a need that the stores give with no other draw, through each chain. A source
1487
+ * (M2-solar) with a share more than 0 gives no upper limit, thus the limit is Infinity. The span of the sweep is finite.
905
1488
  */
906
- function capacity(start, ways) {
1489
+ function capacity(start, ways, shareAt, at = 0) {
1490
+ for (const converter of ways.open) if ((shareAt === void 0 ? 1 : shareAt(deviceKey(converter), at)) > 0) return 1e400;
907
1491
  let total = 0;
908
1492
  for (const use of ways.direct) total += mostResource(start, ways.makers, use.resource, NO_PATH) * use.amount;
909
1493
  for (const converter of ways.converters) total += mostRuns(start, ways.makers, converter, NO_PATH) * converter.gives.amount;
@@ -920,7 +1504,8 @@ function capacity(start, ways) {
920
1504
  * - `endurance-part-unknown`: a supply, a device, the part of a store or a cut is not a part of the base stack.
921
1505
  * - `endurance-range`: an amount, a rate, a count or a factor is not a finite number of 0 or more. Or a reach is not from 0 to 1.
922
1506
  * - `endurance-date`: a date is not a date `YYYY-MM-DD`.
923
- * - `endurance-converter-empty`: a converter takes nothing, or it gives an amount of 0.
1507
+ * - `endurance-converter-empty`: a converter takes nothing and has no limit `perDay` more than 0, or it gives an amount of 0.
1508
+ * A converter with a limit can take nothing: it is a source, for example a solar panel. Since 0.8.20 (M2-solar).
924
1509
  * - `endurance-curve`: a survival curve does not start at `[0, 1]`, or it does not end at a chance of 0.
925
1510
  * Or its days do not increase, or its chance increases.
926
1511
  * - `endurance-bound`: the bound of a cut is not a value of `CUT_BOUNDS` of the core. Since 0.8.4.
@@ -934,6 +1519,8 @@ function capacity(start, ways) {
934
1519
  * - `endurance-season`: the season of a converter has a day that is not `MM-DD`. Or its delay or its shelf life is not more than 0.
935
1520
  * Or its count of sowings is not a finite number of 0 or more. Or the converter with a season gives a need, or it has
936
1521
  * `perDay` or `devices`. Since 0.8.16 (M2-grow).
1522
+ * - `endurance-monthly`: the shares `monthly` of a converter are not 12 numbers from 0 to 1. Or the converter has
1523
+ * `monthly` and no `perDay`, or a season. Or two converters of one device have different shares. Since 0.8.20 (M2-solar).
937
1524
  */
938
1525
  const ENDURANCE_CODES = [
939
1526
  "endurance-twice",
@@ -951,7 +1538,8 @@ const ENDURANCE_CODES = [
951
1538
  "endurance-device-mix",
952
1539
  "endurance-no-way",
953
1540
  "endurance-cut-no-curve",
954
- "endurance-season"
1541
+ "endurance-season",
1542
+ "endurance-monthly"
955
1543
  ];
956
1544
  /**
957
1545
  * This function gives each fault of an endurance layer. With a base stack, it also examines the `id` of each part. A list with no error tells that the gate passes.
@@ -1032,11 +1620,19 @@ function checkEndurance(layer, stack) {
1032
1620
  range(converter.id, "amount", converter.gives.amount);
1033
1621
  const made = giftResource(converter);
1034
1622
  if (made !== void 0) resource(converter.id, made);
1035
- if (!converter.takes.some((input) => input.amount > 0) || converter.gives.amount === 0) add("error", "endurance-converter-empty", converter.id, `The converter "${converter.id}" takes nothing, or it gives nothing.`);
1623
+ if (!(converter.perDay !== void 0 && converter.perDay > 0) && !converter.takes.some((input) => input.amount > 0) || converter.gives.amount === 0) add("error", "endurance-converter-empty", converter.id, `The converter "${converter.id}" takes nothing, or it gives nothing.`);
1036
1624
  part(converter.id, "device", converter.device);
1037
1625
  if (converter.perDay !== void 0) range(converter.id, "rate perDay", converter.perDay);
1038
1626
  if (converter.devices !== void 0 && !(Number.isSafeInteger(converter.devices) && converter.devices >= 1)) add("error", "endurance-range", converter.id, `The count of devices of "${converter.id}" is ${String(converter.devices)}. It must be a whole number of 1 or more.`);
1039
1627
  if (converter.season !== void 0) for (const message of seasonFaults(converter)) add("error", "endurance-season", converter.id, message);
1628
+ for (const message of monthlyFaults(converter)) add("error", "endurance-monthly", converter.id, message);
1629
+ }
1630
+ const shares = /* @__PURE__ */ new Map();
1631
+ for (const converter of converters) {
1632
+ if (converter.device === void 0 || converter.perDay === void 0) continue;
1633
+ const seen = shares.get(converter.device);
1634
+ if (seen === void 0) shares.set(converter.device, converter);
1635
+ else if (!sameShares(seen.monthly, converter.monthly)) add("error", "endurance-monthly", converter.id, `The converter "${converter.id}" and the converter "${seen.id}" of the device "${converter.device}" have different shares monthly. The converters of one device have the same shares.`);
1040
1636
  }
1041
1637
  const counts = /* @__PURE__ */ new Map();
1042
1638
  for (const converter of converters) {
@@ -1108,6 +1704,23 @@ function seasonFaults(converter) {
1108
1704
  if (converter.perDay !== void 0 || converter.devices !== void 0) out.push(`The converter "${converter.id}" has a season and a limit perDay or devices. A converter with a season has no such limit.`);
1109
1705
  return out;
1110
1706
  }
1707
+ /** This function gives the messages of the faults of the shares `monthly` of a converter (M2-solar). */
1708
+ function monthlyFaults(converter) {
1709
+ const monthly = converter.monthly;
1710
+ if (monthly === void 0) return [];
1711
+ const out = [];
1712
+ if (monthly.length !== 12 || !monthly.every((share) => Number.isFinite(share) && share >= 0 && share <= 1)) out.push(`The shares monthly of "${converter.id}" are not 12 numbers from 0 to 1.`);
1713
+ if (converter.perDay === void 0) out.push(`The converter "${converter.id}" has shares monthly and no limit perDay. The shares are parts of the limit.`);
1714
+ if (converter.season !== void 0) out.push(`The converter "${converter.id}" has shares monthly and a season. A converter has one or the other.`);
1715
+ return out;
1716
+ }
1717
+ /** This function tells if two lists of shares `monthly` are equal. No list is equal to a list of 12 ones. */
1718
+ function sameShares(a, b) {
1719
+ const full = (shares) => shares ?? Array.from({ length: 12 }, () => 1);
1720
+ const left = full(a);
1721
+ const right = full(b);
1722
+ return left.length === right.length && left.every((share, index) => share === right[index]);
1723
+ }
1111
1724
  /**
1112
1725
  * This function gives each cycle of resources: a resource is made from a resource that a converter makes from it. Each cycle is a list of codes.
1113
1726
  * A converter with a season is not part of a cycle: its harvest comes after its sowing, thus a chain of it ends.
@@ -1190,6 +1803,6 @@ function joinEndurance(pieces) {
1190
1803
  }
1191
1804
  };
1192
1805
  }
1193
- export { reachOf as C, exact as D, dense as E, partsOf as S, addTo as T, Program as _, hasEnduranceError as a, drawBlock as b, caseStopped as c, giftNeed as d, giftResource as f, storeAmounts as g, sowDays as h, curveFault as i, drawDemand as l, seasonSupply as m, ENDURANCE_CODES as n, SEASON_HORIZON_DAYS as o, hasSeason as p, checkEndurance as r, caseDraws as s, joinEndurance as t, enduranceOf as u, caseParts as v, valueAt as w, fewestRow as x, deviceUse as y };
1806
+ export { drawBlock as A, fixStops as C, Program as D, seasonPlan as E, dense as F, exact as I, isSource as L, reachOf as M, valueAt as N, caseParts as O, addTo as P, firstStop as S, seasonJoint as T, seasonSupply as _, hasEnduranceError as a, storeAmounts as b, caseStopped as c, giftNeed as d, giftResource as f, monthlyShares as g, monthOf as h, curveFault as i, fewestRow as j, deviceUse as k, drawDemand as l, monthEdges as m, ENDURANCE_CODES as n, SEASON_HORIZON_DAYS as o, hasSeason as p, checkEndurance as r, caseDraws as s, joinEndurance as t, enduranceOf as u, shareOf as v, seasonBest as w, fewestOpen as x, sowDays as y };
1194
1807
 
1195
- //# sourceMappingURL=join-D4KzcbbY.js.map
1808
+ //# sourceMappingURL=join-BB1qLU4e.js.map