@mark1russell7/stack-endurance 0.8.28 → 0.8.29
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/add-on.js +1 -1
- package/build/index.d.ts +37 -37
- package/build/index.d.ts.map +1 -1
- package/build/index.js +1674 -9
- package/build/index.js.map +1 -1
- package/build/join-NN0eFb6s.js +382 -0
- package/build/join-NN0eFb6s.js.map +1 -0
- package/package.json +1 -1
- package/build/join-r5ht3vQ9.js +0 -2050
- package/build/join-r5ht3vQ9.js.map +0 -1
package/build/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["horizonOf","shareOf","rankOrder"],"sources":["../src/joint.ts","../src/best.ts","../src/stops.ts","../src/shortfall.ts","../src/sample.ts","../src/sensitivity.ts","../src/buy.ts"],"sourcesContent":["import { type Objective, solveLexicographic } from \"@mark1russell7/linear\";\nimport { add, div, equals, mul, neg, ONE, type Rational, sign, toNumber, ZERO } from \"@mark1russell7/rational\";\nimport { type CaseOptions, caseDraws, caseStopped, drawDemand, hasSeason, seasonSupply, storeAmounts } from \"./endurance.ts\";\nimport type { CaseCuts, Converter, EnduranceLayer, IsoDate } from \"./layer.ts\";\nimport { caseParts, deviceUse, drawBlock, fewestRow, Program, reachOf, valueAt } from \"./program.ts\";\nimport { addTo, dense, exact, type Row } from \"./rows.ts\";\nimport { seasonJoint, seasonPlan, storeCapacities } from \"./seasonal.ts\";\n\n// The joint days: the largest count of days that a set of draws holds together, with the best share of the stores.\n// The query is a linear program over the totals of the span, with exact rationals (@mark1russell7/linear).\n\n/** The joint days of a set of draws in a case, with the share of the stores at the optimum. */\nexport interface JointDays {\n readonly case: string;\n readonly at: IsoDate;\n /**\n * The largest count of days that each draw of `plan` holds at the same time. It is `Infinity` when `plan` is empty,\n * or when the stores give each draw of `plan` without end.\n */\n readonly days: number;\n /** The needs of the set that take from the stores: the case stops their supply, and their demand is more than 0. The order is the order of `caseDraws`. */\n readonly plan: readonly string[];\n /** The needs of the set that take nothing from the stores, in the order of their codes. The case does not stop their supply, or their demand is 0. */\n readonly holds: readonly string[];\n /**\n * The amount of each resource that each draw of `plan` takes from the stores in `days`. The keys are the code of the need, then the code of the resource.\n * A take through a converter that makes a resource counts the inputs of the converter. A resource with no take is not in the record.\n * The record is empty when `days` is `Infinity`.\n */\n readonly takes: Readonly<Record<string, Readonly<Record<string, number>>>>;\n /**\n * The resources that limit `days`, in the order of their codes. Each one has a store in the layer, is an input of `plan` through each chain,\n * and has no stock left at the optimum. The list is empty when `days` is `Infinity`.\n */\n readonly binding: readonly string[];\n /** The count of runs of each converter at the optimum, by the `id` of the converter. A converter with no run is not in the record. */\n readonly runs: Readonly<Record<string, number>>;\n /**\n * The converters of the plan whose limit `perDay` stops more runs at the optimum, in the order of their `id`. A converter of the plan\n * gives a need of the plan, or makes an input of the plan through each chain.\n * The list is empty when `days` is `Infinity` or 0. Else it has each converter of the plan with a limit of 0.\n */\n readonly capped: readonly string[];\n /** True when a layer with a season holds the plan to the horizon (M2-grow-share). `days` is then the horizon. */\n readonly atHorizon?: true | undefined;\n}\n\n/**\n * This function gives the joint days of a set of draws. These are the largest count of days `d` at which each draw holds `d` days.\n * The draws hold at the same time, with the best share of the stores and of the runs of the converters.\n *\n * - The function solves a linear program over the totals of the span. Its variables are `d`, the take of each direct use,\n * the runs of each converter, and the share of each stock.\n * - Each draw of the plan gets `d` times its demand (`drawDemand`) from its direct uses and from the converters that give its need.\n * - The takes of each resource are not more than its stock (`storeAmounts` at `at`) plus the gifts of the converters that make it.\n * - A converter whose device stops gives nothing, and a store whose part stops gives nothing, as in `enduranceOf`.\n * - The runs of a converter with a limit `perDay` are not more than `perDay` times `devices` times `d`. The converters of one device share it, as in `enduranceOf`.\n * - A store counts with all of its amount when its due date is after `at`, as in `enduranceOf`. A due date in the span has no effect.\n * - After the largest `d`, a second objective takes the smallest sum of the shares of the stocks. Thus the takes have no waste.\n * - A third objective takes the fewest device-days of the converters. Thus the runs are not more than the plan uses.\n * - The draws that are not in the set are outside this plan. They take nothing in the program.\n * - A need of the set whose supply works, or whose demand is 0, holds without end. It goes in `holds`, as `enduranceOf` leaves it out.\n *\n * The take order of `enduranceOf` gives the stores to a higher draw first. This function gives one share for the whole set.\n * Thus a draw of the set can get fewer days here than alone, and a lower draw can get more.\n *\n * The program uses exact rationals, so the result has no error of the method. Only the change back to a number rounds.\n *\n * With a converter with a season, `days` is the largest common first stop of the plan (M2-grow-share). The sowings, the lots and\n * the segments are those of `bestEndurance`. The plan holds the horizon at most (default `SEASON_HORIZON_DAYS`), with `atHorizon`.\n *\n * @param layer - The endurance layer\n * @param caseCuts - The case\n * @param options - The date, and the stack or the parts that are also down\n * @param needs - The codes of the needs of the draws of the set\n * @returns The joint days, the takes of each draw, the binding resources and the runs of each converter\n * @throws {RangeError} A code of `needs` is not the need of a draw of the layer, or a date is not `YYYY-MM-DD`. Or the horizon of a layer with a season is not more than 0.\n */\nexport function jointDays(layer: EnduranceLayer, caseCuts: CaseCuts, options: CaseOptions, needs: readonly string[]): JointDays {\n const known = new Set(layer.draws.map((draw) => draw.need));\n const unknown = needs.filter((need) => !known.has(need));\n if (unknown.length > 0) throw new RangeError(`The needs ${unknown.map((need) => `\"${need}\"`).join(\", \")} are not the needs of draws of the layer.`);\n const stoppedParts = caseStopped(caseCuts, options);\n const seasonal = hasSeason(layer, stoppedParts);\n const supply = seasonal ? seasonSupply(layer, stoppedParts, options) : undefined;\n const stock = supply?.stock ?? storeAmounts(layer, options.at, stoppedParts);\n const wanted = new Set(needs);\n const plan = caseDraws(layer, caseCuts, stoppedParts).filter((draw) => wanted.has(draw.need));\n const planned = new Set(plan.map((draw) => draw.need));\n const base = { case: caseCuts.case, at: options.at, plan: plan.map((draw) => draw.need), holds: [...wanted].filter((need) => !planned.has(need)).sort() };\n const endless: JointDays = { ...base, days: Infinity, takes: {}, binding: [], runs: {}, capped: [] };\n if (plan.length === 0) return endless;\n\n const parts = caseParts(layer, stoppedParts, stock, planned);\n if (supply !== undefined) {\n const devices = new Map([...deviceUse([...parts.cooks, ...parts.makers].map((converter) => [converter, 0] as const)).limits].map(([key, limit]) => [key, limit.devices] as const));\n const { atHorizon, ...joint } = seasonJoint(seasonPlan(supply, parts, caseCuts, plan, devices, storeCapacities(layer, stoppedParts)), new Set(layer.stores.map((store) => store.resource)));\n return { ...base, ...joint, ...(atHorizon ? { atHorizon: true as const } : {}) };\n }\n const program = new Program();\n const days = program.next();\n const blocks = plan.map((draw) => {\n const block = drawBlock(program, parts, draw);\n // The need of the draw: its gifts are not less than its demand times the days.\n const need: Row = new Map(block.gifts);\n addTo(need, days, neg(exact(drawDemand(draw, caseCuts))));\n program.push(need, \">=\", ZERO);\n return block;\n });\n // The limit of each device: the runs use `devices` times `d` device-days or less. A limit of 0 stops the converter.\n const runCols = blocks.flatMap((block) => [...block.runs]);\n const { limits, stopped } = deviceUse(runCols);\n for (const index of stopped) program.push(new Map([[index, ONE]]), \"<=\", ZERO);\n for (const limit of limits.values()) {\n const row: Row = new Map(limit.row);\n addTo(row, days, neg(exact(limit.devices)));\n program.push(row, \"<=\", ZERO);\n }\n // The shares of each stock are not more than the stock.\n for (const resource of parts.stocked) {\n const row: Row = new Map();\n // A draw has a share only of a resource that it can use (`drawBlock`).\n for (const block of blocks) {\n const index = block.shares.get(resource);\n if (index !== undefined) addTo(row, index, ONE);\n }\n if (row.size > 0) program.push(row, \"<=\", exact(stock.get(resource) ?? 0));\n }\n\n const most: Row = new Map([[days, ONE]]);\n const least: Row = new Map();\n for (const block of blocks) for (const [resource, index] of block.shares) addTo(least, index, div(ONE, exact(stock.get(resource) ?? 1)));\n // The third objective takes the fewest device-days. Thus a converter whose inputs cost no stock does not give more runs than the plan uses,\n // and `runs` and `capped` have one value.\n const objectives: Objective[] = [\n { sense: \"max\", coefficients: dense(most, program.count) },\n { sense: \"min\", coefficients: dense(least, program.count) },\n { sense: \"min\", coefficients: dense(fewestRow(runCols), program.count) },\n ];\n // Each later stage starts from the optimal basis of the stage before it (M2-linear-warm-start). No later program reads this point.\n const solved = solveLexicographic(program.constraints(), objectives, { warm: true });\n // The point 0 is feasible and the later objectives are not less than 0. So only an unbounded first stage has no optimum.\n if (solved.status !== \"optimal\") return endless;\n\n const x = solved.x;\n const takes: Record<string, Record<string, number>> = {};\n for (const block of blocks) {\n const record: Record<string, number> = {};\n for (const [resource, index] of block.shares) if (sign(x[index] ?? ZERO) > 0) record[resource] = toNumber(x[index] ?? ZERO);\n takes[block.draw.need] = record;\n }\n // A converter gives a need or a resource, so it is a cook or a maker, not the two.\n const total = new Map<Converter, Rational>();\n for (const [converter, index] of runCols) total.set(converter, add(total.get(converter) ?? ZERO, x[index] ?? ZERO));\n const runs: Record<string, number> = {};\n for (const [converter, value] of total) if (sign(value) > 0) runs[converter.id] = toNumber(value);\n\n const withStore = new Set(layer.stores.map((store) => store.resource));\n // The converters that the plan can use: the converters that give a need of the plan, and the makers of the resources of the closure.\n const { closure, reach } = reachOf(parts, planned);\n const binding = [...closure]\n .filter((resource) => withStore.has(resource))\n .filter((resource) => {\n // A resource with no live stock has no share, so its take is 0 and it is used up.\n const taken = blocks.reduce((sum, block) => {\n const index = block.shares.get(resource);\n return index === undefined ? sum : add(sum, x[index] ?? ZERO);\n }, ZERO);\n return equals(taken, exact(stock.get(resource) ?? 0));\n })\n .sort();\n const best = solved.values[0] ?? ZERO;\n const capped = sign(best) > 0\n ? [\n ...[...total.keys()].filter((converter) => converter.perDay !== undefined && !(converter.perDay > 0)),\n ...[...limits.values()].filter((limit) => equals(valueAt(limit.row, x), mul(exact(limit.devices), best))).flatMap((limit) => limit.converters),\n ]\n .filter((converter) => reach.has(converter))\n .map((converter) => converter.id)\n .sort()\n : [];\n return { ...base, days: toNumber(best), takes, binding, runs, capped };\n}\n","import { type Objective, solveLexicographic } from \"@mark1russell7/linear\";\nimport { add, div, equals, mul, neg, ONE, type Rational, sign, sub, toNumber, ZERO } from \"@mark1russell7/rational\";\nimport { type CaseOptions, caseDraws, caseStopped, drawDemand, hasSeason, seasonSupply, storeAmounts } from \"./endurance.ts\";\nimport type { CaseCuts, Converter, Draw, DrawEndurance, Endurance, EnduranceLayer } from \"./layer.ts\";\nimport { type CaseParts, caseParts, deviceUse, drawBlock, type DrawBlock, fewestRow, Program, reachOf, valueAt } from \"./program.ts\";\nimport { addTo, dense, exact, type Row } from \"./rows.ts\";\nimport { firstStop, fewestOpen, type FixedStop, fixStops, seasonBest, seasonPlan, storeCapacities } from \"./seasonal.ts\";\n\n// The best endurance: the days of each draw with the best share of the stores, the most important level first.\n// Each step is a linear program over the totals of the spans, with exact rationals (@mark1russell7/linear).\n\n/** A draw whose days are fixed. */\ninterface Fixed {\n /** The span of the draw in the programs: its days, or 1 for a draw with no end. */\n readonly span: Rational;\n /** True for a draw that holds without end. It takes no stock, and its span is one day. */\n readonly endless: boolean;\n /** The device-days of each day that the draw keeps, by the key of the device. */\n readonly keep: ReadonlyMap<string, Rational>;\n /** The `id` of each converter whose limit stops more runs at the step that fixes the draw. */\n readonly capped: readonly string[];\n /** True for a draw that holds the horizon. */\n readonly atHorizon: boolean;\n}\n\n/** The options of `bestEndurance`: the options of a case, and a horizon. */\nexport interface BestOptions extends CaseOptions {\n /**\n * The horizon in days, more than 0. The default is no horizon. A draw holds the horizon at most, thus it keeps back\n * only the horizon times its demand. The rest of the stores goes to the lower levels. Use the target of a plan, for\n * example 14 days, to ask if each draw holds the target.\n */\n readonly horizon?: number | undefined;\n}\n\n/** This function gives the horizon as a rational, or undefined for no horizon. It throws a `RangeError` for a horizon that is not more than 0. */\nfunction horizonOf(horizon: number | undefined): Rational | undefined {\n if (horizon === undefined || horizon === Infinity) return undefined;\n if (!(horizon > 0) || !Number.isFinite(horizon)) throw new RangeError(`The horizon ${String(horizon)} is not a number of days more than 0.`);\n return exact(horizon);\n}\n\n/** A program of one step, with the indexes of its parts. */\ninterface Step {\n readonly program: Program;\n readonly blocks: readonly DrawBlock[];\n /** The column of the common days of the open draws. */\n readonly floor: number;\n /** The row `days - floor >= 0` of each open draw, by the code of its need. */\n readonly floors: ReadonlyMap<string, number>;\n /** The run columns of the open draws. */\n readonly openRuns: readonly (readonly [Converter, number])[];\n /** The device-days of the open draws for each device, with the device-days of each day that the fixed draws leave. */\n readonly shared: ReadonlyMap<string, { readonly row: Row; readonly room: Rational; readonly converters: readonly Converter[] }>;\n}\n\n/**\n * This function gives the days that each draw holds when a case stops its supply. The stores and the devices have their best share.\n * The result has the form of `enduranceOf`, so `caseShortfall` takes it.\n *\n * The share is lexicographic. The draws of the first level get their best days, then the draws of the next level get theirs, and so on.\n * In one level, the share is the best for the draw with the fewest days, then for the next draw, and so on (the leximin share).\n * Thus a draw of a level cannot take a store that another draw of the level needs more.\n *\n * - The function solves a sequence of linear programs over the totals of the spans. Each program has the days of the open draws\n * and their common floor. For each draw, it has the take of each direct use, the runs of each converter and the share of each stock.\n * - Each step takes the largest floor. A draw whose floor row has a dual value that is not 0 cannot get more days. The step fixes its days.\n * The dual values of the floor rows add to 1, so each step fixes one draw or more.\n * - A fixed draw keeps its days in each later step. Its share of the stocks can change, so a later draw can get a store that it does not need.\n * - The stores, the direct uses, the converters and the devices follow the rules of `jointDays`. A store counts with all of its amount when its due date is after `at`.\n * - A fixed draw keeps the device-days of each day that it uses at its step, for all the days of the later draws. This is the safe side, as in `enduranceOf`.\n * The exact share of a device between two spans is not a linear program: the device-days of a day are the runs over the span.\n * - A step with no largest floor gives the open draws no end. Each of them takes no stock, and keeps the fewest device-days of each day.\n * - At the end, a program takes the smallest sum of the shares of the stocks, each over its stock, then the fewest device-days.\n * These are the takes of the result. A resource in `binding` has no stock left at this point.\n * - A draw in `capped` used a device with no device-days left at the step that fixed it.\n * - With a horizon, the floor of each step is the horizon at most. A step whose floor is the horizon fixes each of its\n * open draws at the horizon, with `atHorizon`. Such a draw takes only the horizon times its demand. A draw with no\n * end also holds the horizon. With no horizon, the result is the same as before the option.\n *\n * The programs use exact rationals, so the result has no error of the method. Only the change back to a number rounds.\n * The fewest days of the first level are the joint days (`jointDays`) of the draws of that level.\n *\n * A layer with a converter with a season has the programs of a season (M2-grow-share):\n * - The sowings take their inputs before the draws, as in `enduranceOf`. Each harvest is a lot from its day, and its rest spoils on its spoil day.\n * - The days go in segments that end at each harvest day, at each spoil day and at the horizon (default `SEASON_HORIZON_DAYS`). A segment takes only\n * the lots that are ready and not spoiled in all of it.\n * - `days` is the first stop of each draw, with the same leximin share. The days to a stop are not linear, so each step tries the segments in order.\n * - After the stops, a last program gives the most fed days to each level in order. `again` gives the spans in which a later harvest feeds a draw.\n * In such a span, the runs share the device-days of the whole segment that the stops leave.\n * - The result has the field `harvests`. It has no field `spoiled`: the share of a lot between the draws has no spoil of one draw.\n *\n * @param layer - The endurance layer\n * @param caseCuts - The case\n * @param options - The date, the stack or the parts that are also down, and the horizon\n * @returns The endurance of each draw whose supply stops\n * @throws {RangeError} A date is not `YYYY-MM-DD`, or the horizon is not more than 0.\n */\nexport function bestEndurance(layer: EnduranceLayer, caseCuts: CaseCuts, options: BestOptions): Endurance {\n const horizon = horizonOf(options.horizon);\n const stoppedParts = caseStopped(caseCuts, options);\n if (hasSeason(layer, stoppedParts)) return bestSeason(layer, caseCuts, options, stoppedParts);\n const stock = storeAmounts(layer, options.at, stoppedParts);\n const draws = caseDraws(layer, caseCuts, stoppedParts);\n const parts = caseParts(layer, stoppedParts, stock, new Set(draws.map((draw) => draw.need)));\n // The count of devices of each key. The gate refuses two counts for one device.\n const devices = new Map([...deviceUse([...parts.cooks, ...parts.makers].map((converter) => [converter, 0] as const)).limits].map(([key, limit]) => [key, limit.devices] as const));\n const fixed = new Map<string, Fixed>();\n\n for (const level of levelGroups(layer, draws)) {\n let open = level;\n while (open.length > 0) {\n const step = buildStep(parts, caseCuts, draws, fixed, open, devices, \"span\", horizon);\n // This solve stays cold (M2-linear-warm-start). No objective fixes the shares of the stocks, thus the fewest runs can have a tie.\n // The point x gives the device-days that each fixed draw keeps for the later steps. A different optimal point can change their days.\n const solved = solveLexicographic(step.program.constraints(), [\n { sense: \"max\", coefficients: dense(new Map([[step.floor, ONE]]), step.program.count) },\n { sense: \"min\", coefficients: dense(fewestRow(step.openRuns), step.program.count) },\n ]);\n if (solved.status !== \"optimal\") {\n if (solved.status === \"infeasible\") throw new Error(\"The step of the best endurance has no point. The point of the last step is a point of it.\");\n fixEndless(parts, caseCuts, draws, fixed, open, devices);\n break;\n }\n const floor = solved.values[0] ?? ZERO;\n const first = solved.stages[0]?.result;\n const dual = first?.status === \"optimal\" ? first.dual : [];\n const atHorizon = horizon !== undefined && equals(floor, horizon);\n let done = atHorizon ? open : open.filter((draw) => sign(dual[step.floors.get(draw.need) as number] ?? ZERO) !== 0);\n // The dual values of the floor rows add to 1. Thus `done` is not empty. The fallback fixes each open draw at the floor.\n if (done.length === 0) done = open;\n const full = new Set([...step.shared].filter(([, limit]) => equals(valueAt(limit.row, solved.x), mul(limit.room, floor))).map(([key]) => key));\n for (const draw of done) {\n const block = step.blocks.find((item) => item.draw.need === draw.need) as DrawBlock;\n const keep = new Map<string, Rational>();\n for (const [key, limit] of deviceUse(block.runs).limits) keep.set(key, sign(floor) > 0 ? div(valueAt(limit.row, solved.x), floor) : ZERO);\n const { reach } = reachOf(parts, new Set([draw.need]));\n const capped = sign(floor) > 0\n ? [...reach]\n .filter((converter) => converter.perDay !== undefined && (!(converter.perDay > 0) || [...full].some((key) => step.shared.get(key)?.converters.includes(converter))))\n .map((converter) => converter.id)\n .sort()\n : [];\n fixed.set(draw.need, { span: floor, endless: false, keep, capped, atHorizon });\n }\n const fixedNow = new Set(done.map((draw) => draw.need));\n open = open.filter((draw) => !fixedNow.has(draw.need));\n }\n }\n\n const needs: Record<string, DrawEndurance> = {};\n if (draws.length === 0) return { case: caseCuts.case, at: options.at, needs };\n const last = buildStep(parts, caseCuts, draws, fixed, [], devices, \"span\");\n const least: Row = new Map();\n for (const block of last.blocks) for (const [resource, index] of block.shares) addTo(least, index, div(ONE, exact(stock.get(resource) ?? 1)));\n const objectives: Objective[] = [\n { sense: \"min\", coefficients: dense(least, last.program.count) },\n { sense: \"min\", coefficients: dense(fewestRow(last.blocks.flatMap((block) => [...block.runs])), last.program.count) },\n ];\n // The second stage starts from the optimal basis of the first stage (M2-linear-warm-start). No later program reads this point.\n const solved = solveLexicographic(last.program.constraints(), objectives, { warm: true });\n if (solved.status !== \"optimal\") throw new Error(\"The last program of the best endurance has no optimum. The point of the last step is a point of it.\");\n const withStore = new Set(layer.stores.map((store) => store.resource));\n for (const block of last.blocks) {\n const need = block.draw.need;\n const fix = fixed.get(need) as Fixed;\n if (fix.endless) {\n needs[need] = { days: Infinity, binding: [], takes: {} };\n continue;\n }\n const takes: Record<string, number> = {};\n for (const [resource, index] of block.shares) if (sign(solved.x[index] ?? ZERO) > 0) takes[resource] = toNumber(solved.x[index] ?? ZERO);\n const { closure } = reachOf(parts, new Set([need]));\n const binding = [...closure]\n .filter((resource) => withStore.has(resource))\n .filter((resource) => {\n // A resource with no live stock has no share, so its take is 0 and it is used up.\n const taken = last.blocks.reduce((sum, item) => {\n const index = item.shares.get(resource);\n return index === undefined ? sum : add(sum, solved.x[index] ?? ZERO);\n }, ZERO);\n return equals(taken, exact(stock.get(resource) ?? 0));\n })\n .sort();\n const days = toNumber(fix.span);\n needs[need] = { days, binding, takes, ...(fix.capped.length === 0 ? {} : { capped: fix.capped }), ...(fix.atHorizon ? { atHorizon: true as const } : {}) };\n }\n return { case: caseCuts.case, at: options.at, needs };\n}\n\n/** This function gives the best endurance of a case with a season (M2-grow-share). */\nfunction bestSeason(layer: EnduranceLayer, caseCuts: CaseCuts, options: BestOptions, stoppedParts: ReadonlySet<string>): Endurance {\n const supply = seasonSupply(layer, stoppedParts, options);\n const draws = caseDraws(layer, caseCuts, stoppedParts);\n const parts = caseParts(layer, stoppedParts, supply.stock, new Set(draws.map((draw) => draw.need)));\n const devices = new Map([...deviceUse([...parts.cooks, ...parts.makers].map((converter) => [converter, 0] as const)).limits].map(([key, limit]) => [key, limit.devices] as const));\n const plan = seasonPlan(supply, parts, caseCuts, draws, devices, storeCapacities(layer, stoppedParts));\n const harvests = supply.harvests.length === 0 ? {} : { harvests: supply.harvests };\n if (draws.length === 0) return { case: caseCuts.case, at: options.at, needs: {}, ...harvests };\n const levels = levelGroups(layer, draws);\n const fixed = new Map<string, FixedStop>();\n for (const level of levels) {\n let open = level;\n while (open.length > 0) {\n const opened = new Set(open.map((draw) => draw.need));\n const stop = firstStop(plan, fixed, open, (step) => [fewestOpen(step, opened)]);\n // A draw whose floor row has a dual value that is not 0 cannot get more days. The fallback fixes each open draw.\n let done = stop.atHorizon ? open : open.filter((draw) => sign(stop.dual[stop.step.floors.get(draw.need) as number] ?? ZERO) !== 0);\n if (done.length === 0) done = open;\n fixStops(plan, stop, done, fixed);\n open = open.filter((draw) => !done.includes(draw));\n }\n }\n const { needs } = seasonBest(plan, fixed, levels, new Set(layer.stores.map((store) => store.resource)));\n return { case: caseCuts.case, at: options.at, needs, ...harvests };\n}\n\n/** This function gives the draws of each level, in the order of `levels`. The draws of a level that is not in `levels` come last, together. */\nfunction levelGroups(layer: EnduranceLayer, draws: readonly Draw[]): Draw[][] {\n const rank = (draw: Draw): number => {\n const index = layer.levels.indexOf(draw.level);\n return index < 0 ? layer.levels.length : index;\n };\n const out: Draw[][] = [];\n let previous = -1;\n for (const draw of draws) {\n if (rank(draw) !== previous) out.push([]);\n previous = rank(draw);\n out[out.length - 1]?.push(draw);\n }\n return out;\n}\n\n/**\n * This function gives the program of one step. The fixed draws keep their spans and their device-days. The open draws have a common floor.\n *\n * - With `\"span\"`, each open draw has a column of its days, not less than the floor. Its runs share the device-days that the fixed draws leave, for the floor.\n * The device-days of each day are the runs over the span. A span not less than the floor uses fewer of them, so this is the safe side.\n * - With `\"day\"`, each open draw has a span of one day and takes no stock. Its runs share the device-days of one day.\n * - With a horizon, the floor is the horizon at most.\n */\nfunction buildStep(\n parts: CaseParts,\n caseCuts: CaseCuts,\n draws: readonly Draw[],\n fixed: ReadonlyMap<string, Fixed>,\n open: readonly Draw[],\n devices: ReadonlyMap<string, number>,\n mode: \"span\" | \"day\",\n horizon?: Rational,\n): Step {\n const program = new Program();\n const floor = program.next();\n if (horizon !== undefined) program.push(new Map([[floor, ONE]]), \"<=\", horizon);\n const opened = new Set(open.map((draw) => draw.need));\n const blocks: DrawBlock[] = [];\n const floors = new Map<string, number>();\n const openRuns: (readonly [Converter, number])[] = [];\n const kept = new Map<string, Rational>();\n for (const draw of draws) {\n const fix = fixed.get(draw.need);\n if (fix === undefined && !opened.has(draw.need)) continue;\n const endless = fix?.endless ?? mode === \"day\";\n const block = drawBlock(program, parts, draw, !endless);\n blocks.push(block);\n const demand = exact(drawDemand(draw, caseCuts));\n const need: Row = new Map(block.gifts);\n if (fix !== undefined) {\n program.push(need, \">=\", mul(demand, fix.span));\n const { limits, stopped } = deviceUse(block.runs);\n for (const index of stopped) program.push(new Map([[index, ONE]]), \"<=\", ZERO);\n for (const [key, limit] of limits) program.push(limit.row, \"<=\", mul(fix.keep.get(key) ?? ZERO, fix.span));\n for (const [key, value] of fix.keep) kept.set(key, add(kept.get(key) ?? ZERO, value));\n continue;\n }\n openRuns.push(...block.runs);\n if (mode === \"day\") {\n program.push(need, \">=\", demand);\n continue;\n }\n const days = program.next();\n addTo(need, days, neg(demand));\n program.push(need, \">=\", ZERO);\n floors.set(draw.need, program.push(new Map([[days, ONE], [floor, neg(ONE)]]), \">=\", ZERO));\n }\n const shared = new Map<string, { row: Row; room: Rational; converters: readonly Converter[] }>();\n const { limits, stopped } = deviceUse(openRuns);\n for (const index of stopped) program.push(new Map([[index, ONE]]), \"<=\", ZERO);\n for (const [key, limit] of limits) {\n const left = sub(exact(devices.get(key) ?? limit.devices), kept.get(key) ?? ZERO);\n const room = sign(left) > 0 ? left : ZERO;\n shared.set(key, { row: limit.row, room, converters: limit.converters });\n if (mode === \"day\") {\n program.push(limit.row, \"<=\", room);\n continue;\n }\n const row: Row = new Map(limit.row);\n addTo(row, floor, neg(room));\n program.push(row, \"<=\", ZERO);\n }\n for (const resource of parts.stocked) {\n const row: Row = new Map();\n for (const block of blocks) {\n const index = block.shares.get(resource);\n if (index !== undefined) addTo(row, index, ONE);\n }\n if (row.size > 0) program.push(row, \"<=\", exact(parts.stock.get(resource) ?? 0));\n }\n return { program, blocks, floor, floors, openRuns, shared };\n}\n\n/**\n * This function fixes the open draws with no end. Each open draw takes no stock, and keeps the fewest device-days of each day.\n * A step with no largest floor has a direction with no take of a stock, so this program has a point.\n */\nfunction fixEndless(parts: CaseParts, caseCuts: CaseCuts, draws: readonly Draw[], fixed: Map<string, Fixed>, open: readonly Draw[], devices: ReadonlyMap<string, number>): void {\n const step = buildStep(parts, caseCuts, draws, fixed, open, devices, \"day\");\n const solved = solveLexicographic(step.program.constraints(), [{ sense: \"min\", coefficients: dense(fewestRow(step.openRuns), step.program.count) }]);\n if (solved.status !== \"optimal\") throw new Error(\"The draws with no end of the best endurance have no point of one day.\");\n for (const draw of open) {\n const block = step.blocks.find((item) => item.draw.need === draw.need) as DrawBlock;\n const keep = new Map<string, Rational>();\n for (const [key, limit] of deviceUse(block.runs).limits) keep.set(key, valueAt(limit.row, solved.x));\n fixed.set(draw.need, { span: ONE, endless: true, keep, capped: [], atHorizon: false });\n }\n}\n","import { DEFAULT_MAX_SETS, stopSets, type Stack } from \"@mark1russell7/system-stack\";\n\n// The minimal stop sets of a supply from the structure of the needs. The index does not give this entry: `stopCurves` uses it.\n\n/**\n * This function gives the minimal sets of cuts that stop a supply, from the paths of the needs of the stack (`stopSets` of the core).\n * A set is a list of indexes of `parts`, from the smallest set. Two sets of one size are in the order of `minimalStops`.\n *\n * - `parts` has the part of each cut that counts. Two cuts of one part are two cuts: each one stops what the part stops.\n * - A cut of the supply stops it alone. The other sets come from `stopSets` with the cut parts as `among`, so no other part can fail.\n * - The parts of `down` are down for the full event. The caller makes sure that they do not stop the supply with no cut.\n * - The result is `undefined` when the search passes its budget, or when the sets of cuts are more than `maxSets`.\n *\n * @param stack - The base stack\n * @param supply - The part of the supply of a draw\n * @param parts - The part of each cut that counts\n * @param down - The parts that are down for the full event\n * @param maxSets - The largest count of sets in one step of the search, and of the sets of cuts (`maxSets` of `stopSets`)\n */\nexport function stackStops(stack: Stack, supply: string, parts: readonly string[], down: readonly string[] = [], maxSets: number = DEFAULT_MAX_SETS): number[][] | undefined {\n const cutsOf = new Map<string, number[]>();\n for (const [index, part] of parts.entries()) cutsOf.set(part, [...(cutsOf.get(part) ?? []), index]);\n const own = (cutsOf.get(supply) ?? []).map((index) => [index]);\n const among = [...cutsOf.keys()].filter((part) => part !== supply);\n const found = stopSets(stack, supply, { down, among, size: among.length, maxSets });\n if (found.kind === \"budget\") return undefined;\n // The empty set: the supply is not in the stack, or it does not work in the base stack.\n // In both, `stopped` of the core does not count it as stopped, so only a cut of the supply stops it.\n if (found.sets.some((set) => set.length === 0)) return own;\n const out = [...own];\n for (const set of found.sets) {\n // Each choice of one cut for each part of the set is a minimal set of cuts.\n let choices: number[][] = [[]];\n for (const part of set) {\n const cuts = cutsOf.get(part) ?? [];\n if (choices.length * cuts.length + out.length > maxSets) return undefined;\n choices = choices.flatMap((choice) => cuts.map((cut) => [...choice, cut]));\n }\n out.push(...choices.map((choice) => choice.sort((x, y) => x - y)));\n }\n return out.sort(byMask);\n}\n\n/** The order of `minimalStops`: the smaller set first, then the set whose largest different index is smaller. */\nfunction byMask(a: readonly number[], b: readonly number[]): number {\n if (a.length !== b.length) return a.length - b.length;\n for (let index = a.length - 1; index >= 0; index -= 1) {\n const difference = (a[index] ?? 0) - (b[index] ?? 0);\n if (difference !== 0) return difference;\n }\n return 0;\n}\n","import { type OrderedRing, pathSetReliability, stronglyConnectedComponents } from \"@mark1russell7/collections/graph\";\nimport { dateOfDay, dayNumber, DEFAULT_MAX_SETS, neededParts, survivalAt, weakestBound, type CutBound, type PathOptions } from \"@mark1russell7/system-stack\";\nimport { bestEndurance } from \"./best.ts\";\nimport { caseDraws, caseStopped, enduranceOf, type CaseOptions } from \"./endurance.ts\";\nimport type { CaseCuts, Draw, DrawEndurance, Endurance, EnduranceLayer, IsoDate, Prior, Survival } from \"./layer.ts\";\nimport { stackStops } from \"./stops.ts\";\n\n// The shortfall: the user-days in which a draw does not get its need, for one case and for one year.\n\n/** The read of a curve at a time is in the core since system-stack 0.1.13. This package gives it again, so its API does not change. */\nexport { survivalAt };\n\n/**\n * This function gives the expected days of a cut after a time, up to a horizon: `E[max(0, min(D, to) - from)]`.\n * It is the area under the curve from `from` to `to`. The curve is linear between its points, so the area is exact.\n * With no horizon, the area goes to the end of the curve.\n */\nexport function tailDays(curve: Survival, from: number, to: number = Infinity): number {\n let area = 0;\n for (let index = 1; index < curve.length; index += 1) {\n const [t0] = curve[index - 1] ?? [0, 1];\n const [t1] = curve[index] ?? [0, 0];\n const start = Math.max(t0, from);\n const end = Math.min(t1, to);\n if (start < end) area += ((survivalAt(curve, start) + survivalAt(curve, end)) / 2) * (end - start);\n }\n return area;\n}\n\n/**\n * This function gives the days of a cut with the survival `curve` that a draw does not hold, up to the horizon (M2-grow).\n * It is `tailDays` from the days of the draw, less `tailDays` over each span in which a harvest feeds the draw again.\n *\n * @param curve - The survival of the stop of the draw\n * @param held - The days and the fed spans of the draw, from `enduranceOf`\n * @param horizon - The horizon in days. The default is no horizon.\n */\nexport function heldTail(curve: Survival, held: Pick<DrawEndurance, \"days\" | \"again\">, horizon: number = Infinity): number {\n let short = tailDays(curve, held.days, horizon);\n for (const span of held.again ?? []) short -= tailDays(curve, span.from, Math.min(span.to, horizon));\n return Math.max(0, short);\n}\n\n/**\n * The options of a shortfall: the stack or the parts that are also down, as for `enduranceOf`, and a horizon.\n * With a horizon of `h` days, the shortfall counts only the first `h` days of each cut. A draw that holds `h` days has no shortfall.\n * Thus a plan can aim at a target, for example 14 days and then 90 days.\n */\n/**\n * The options of `stopCurves`. With a stack, `maxSets` is the budget of the search of the needs (`stopSets` of the core).\n * When the search passes it, `minimalStops` gives the sets.\n */\nexport interface StopCurveOptions extends Pick<CaseOptions, \"stack\" | \"down\">, Pick<PathOptions, \"maxSets\"> {\n /** The budget of `independentStop` for the curve of each draw, a whole number from 1. The default is `INDEPENDENT_MAX_WORK`. */\n readonly maxWork?: number | undefined;\n}\n\nexport interface ShortfallOptions extends StopCurveOptions {\n /** The horizon in days, more than 0. The default is no horizon. */\n readonly horizon?: number | undefined;\n}\n\nfunction horizonOf(options: ShortfallOptions): number {\n const horizon = options.horizon ?? Infinity;\n if (!(horizon > 0)) throw new RangeError(`The horizon ${String(options.horizon)} is not a number of days more than 0.`);\n return horizon;\n}\n\nfunction budgetsOf(options: StopCurveOptions): { readonly maxSets: number; readonly maxWork: number } {\n const maxSets = options.maxSets ?? DEFAULT_MAX_SETS;\n if (!Number.isInteger(maxSets) || maxSets < 1) throw new RangeError(`The option maxSets is ${String(options.maxSets)}: it is not a whole number from 1.`);\n const maxWork = options.maxWork ?? INDEPENDENT_MAX_WORK;\n if (!Number.isInteger(maxWork) || maxWork < 1) throw new RangeError(`The option maxWork is ${String(options.maxWork)}: it is not a whole number from 1.`);\n return { maxSets, maxWork };\n}\n\n/**\n * This function gives the days at which the chance of the curve falls to `chance`. With `0.1`, it is the 90th percentile of the duration.\n * When the curve does not fall to `chance`, the result is `Infinity`.\n */\nexport function survivalQuantile(curve: Survival, chance: number): number {\n for (let index = 1; index < curve.length; index += 1) {\n const [t0, p0] = curve[index - 1] ?? [0, 1];\n const [t1, p1] = curve[index] ?? [0, 0];\n if (p0 <= chance) return t0;\n if (p1 <= chance) return t0 + ((p0 - chance) * (t1 - t0)) / (p0 - p1);\n }\n return Infinity;\n}\n\n/** This function gives the chance that a case reaches its place one or more times in one year: `1 - exp(-perYear * reach)`. */\nexport function yearChance(prior: Prior): number {\n return 1 - Math.exp(-prior.perYear * prior.reach);\n}\n\n/** This function gives the expected count of the events of a case at its place in one year: `perYear * reach`. */\nexport function yearRate(prior: Prior): number {\n return prior.perYear * prior.reach;\n}\n\n/** This function gives the times at which a curve of the result can bend: each point of each curve, and each crossing of two curves. */\nfunction bendTimes(curves: readonly Survival[]): number[] {\n const times = [...new Set(curves.flatMap((curve) => curve.map(([days]) => days)))].sort((x, y) => x - y);\n const out = new Set(times);\n for (let index = 1; index < times.length; index += 1) {\n const t0 = times[index - 1] ?? 0;\n const t1 = times[index] ?? 0;\n for (const [i, a] of curves.entries()) {\n for (const b of curves.slice(i + 1)) {\n const d0 = survivalAt(a, t0) - survivalAt(b, t0);\n const d1 = survivalAt(a, t1) - survivalAt(b, t1);\n if (d0 * d1 < 0) out.add(t0 + ((t1 - t0) * d0) / (d0 - d1));\n }\n }\n }\n return [...out].sort((x, y) => x - y);\n}\n\n/**\n * This function makes a survival curve from a chance at each time. It stops at the first chance of 0, and it removes an increase of rounding.\n *\n * @throws RangeError when the chance at the last time is more than 0, as for curves that do not end at a chance of 0\n */\nfunction curveFrom(times: readonly number[], chanceAt: (days: number) => number): Survival {\n const out: [number, number][] = [];\n for (const days of times) {\n const chance = Math.min(out[out.length - 1]?.[1] ?? 1, chanceAt(days));\n out.push([days, chance]);\n if (chance === 0) return out;\n }\n throw new RangeError(\"The curves do not fall to a chance of 0 at their last point.\");\n}\n\n/**\n * This function gives the curve of a stop of some cuts when one event makes each cut longer together.\n * At each time, the chance is the largest `s` at which the cuts with a chance of `s` or more stop the supply.\n *\n * - When any one cut stops the supply, the result is the largest chance of the curves (`longestStop`).\n * - When the supply needs `any` of two parts, the stop ends with the shorter of the two cuts.\n * - Between two times of `bendTimes` the order of the curves does not change. So the result is linear between its points.\n * - When no set of cuts stops the supply, the result is `[[0, 0]]`. This curve does not start at `[0, 1]`, so `checkEndurance` refuses it.\n *\n * The result is not a limit. When the cuts are independent, a stop of two cuts in series can be longer. A stop through a need of `any` can be shorter.\n *\n * @param curves - The curves of the cuts, each one good for `checkEndurance`\n * @param stops - This function tells if the cuts of a list of indexes stop the supply. A larger list stops it when a smaller list does.\n * @throws RangeError when a curve does not end at a chance of 0\n */\nexport function eventStop(curves: readonly Survival[], stops: (cuts: readonly number[]) => boolean): Survival {\n return curveFrom(bendTimes(curves), (days) => {\n const chances = curves.map((curve) => survivalAt(curve, days));\n for (const level of [...new Set(chances)].sort((x, y) => y - x)) {\n if (stops(chances.flatMap((chance, index) => (chance >= level ? [index] : [])))) return level;\n }\n return 0;\n });\n}\n\n/**\n * This function gives the curve of the longest of some stops: at each time, the largest chance of the curves.\n * It is `eventStop` when any one cut stops the supply.\n *\n * @param curves - The curves, each one good for `checkEndurance`\n * @throws RangeError when there is no curve, or when a curve does not end at a chance of 0\n */\nexport function longestStop(curves: readonly Survival[]): Survival {\n const first = curves[0];\n if (first === undefined) throw new RangeError(\"longestStop needs one or more curves.\");\n return curves.length === 1 ? first : eventStop(curves, (cuts) => cuts.length > 0);\n}\n\n/**\n * The largest count of cuts for which `minimalStops` examines each set, and for which `independentStop` adds the chance of each state.\n * With a stack, `stopCurves` finds the minimal sets from the needs, so a larger count of cuts can have exact sets.\n */\nexport const MINIMAL_STOP_CUTS = 12;\n\n/**\n * This function gives the minimal sets of cuts that stop the supply: each set stops it, and no smaller part of a set stops it.\n * With more than `MINIMAL_STOP_CUTS` cuts, the result is `undefined`.\n */\nexport function minimalStops(count: number, stops: (cuts: readonly number[]) => boolean): number[][] | undefined {\n if (count > MINIMAL_STOP_CUTS) return undefined;\n const found: number[][] = [];\n const masks: number[] = [];\n const all = Array.from({ length: 1 << count }, (_, mask) => mask).sort((x, y) => popCount(x) - popCount(y) || x - y);\n for (const mask of all) {\n if (mask === 0 || masks.some((other) => (other & mask) === other)) continue;\n const cuts = Array.from({ length: count }, (_, index) => index).filter((index) => (mask >> index) & 1);\n if (!stops(cuts)) continue;\n masks.push(mask);\n found.push(cuts);\n }\n return found;\n}\n\nfunction popCount(mask: number): number {\n let total = 0;\n for (let rest = mask; rest > 0; rest &= rest - 1) total += 1;\n return total;\n}\n\n/**\n * This function gives an upper limit of the curve of a stop for each dependence of the cuts.\n * At each time it is `min(1, sum over the minimal sets of the smallest chance of the set)`.\n * With no minimal sets, as for too many cuts, it is `min(1, sum of the chances)`.\n *\n * @param curves - The curves of the cuts\n * @param sets - The minimal sets of `minimalStops`, or `undefined`\n * @throws RangeError when a curve does not end at a chance of 0\n */\nexport function upperStop(curves: readonly Survival[], sets: readonly (readonly number[])[] | undefined): Survival {\n const groups = sets ?? curves.map((_, index) => [index]);\n const sum = (days: number): number => groups.reduce((total, set) => total + Math.min(...set.map((index) => survivalAt(curves[index] ?? [], days))), 0);\n // The sum is linear between two times of bendTimes. A point where it falls through 1 is a bend of min(1, sum).\n const times = bendTimes(curves);\n const bends = new Set(times);\n for (let index = 1; index < times.length; index += 1) {\n const t0 = times[index - 1] ?? 0;\n const t1 = times[index] ?? 0;\n const s0 = sum(t0) - 1;\n const s1 = sum(t1) - 1;\n if (s0 * s1 < 0) bends.add(t0 + ((t1 - t0) * s0) / (s0 - s1));\n }\n return curveFrom([...bends].sort((x, y) => x - y), (days) => Math.min(1, sum(days)));\n}\n\n/** The largest difference between `independentStop` and the true chance of a stop of independent cuts, at each time. */\nexport const INDEPENDENT_TOLERANCE = 1e-6;\n\n/**\n * The default budget of `independentStop` for its groups of more than `MINIMAL_STOP_CUTS` cuts.\n * The budget counts the steps of the expansion times the count of points of the curve.\n * It is near the work of the sum over the states of 12 cuts.\n */\nexport const INDEPENDENT_MAX_WORK: number = 2 ** 26;\n\n/**\n * This function gives the curve of a stop of some cuts when the cuts are independent.\n * At each time `t`, the supply is stopped when the cuts that are still on contain a minimal set.\n * Its chance is a sum over each set of cuts that stops the supply.\n * Each term is the product of `s(t)` for the cuts that are on, and of `1 - s(t)` for the other cuts.\n *\n * - When any one cut stops the supply, the result is `1 - prod(1 - s)`. It is not less than the longest cut (`eventStop`).\n * - When the supply needs `any` of two parts, the stop of the two is `s1 * s2`. It is not more than the shorter cut.\n * - The result is not more than `upperStop` of the same sets, because `upperStop` is a limit for each dependence.\n * - Between two points of the curves the chance is a polynomial, not a line. The function splits each such segment into equal pieces.\n * The chance is linear in each `s`, and each mixed second derivative is between -1 and 1.\n * Thus `|f''| <= (sum |s'|)^2 - sum s'^2`, and the line of a piece of length `h` is within `h^2 |f''| / 8` of the chance.\n * The count of pieces keeps each line within `INDEPENDENT_TOLERANCE`. With a margin of 10 %, the count of points is less than `n / sqrt(7.2 * INDEPENDENT_TOLERANCE)` plus the segments, for `n` cuts.\n *\n * - Up to `MINIMAL_STOP_CUTS` cuts in the sets, the function adds the chance of each of the 2 to the power of that count of states.\n * - Two groups of cuts that share no set are independent, so the chance that the supply works is the product over the groups.\n * For example, 20 stages of 2 feeds give 20 groups of 2 cuts.\n * - In a group of more than `MINIMAL_STOP_CUTS` cuts, it uses the Shannon expansion of `pathSetReliability` of collections.\n * The expansion merges two states with the same sets left, and it drops a set that holds another set.\n * - The expansion is exponential in the worst case. The groups share one budget, `maxWork`.\n * When the steps of the expansions times the count of points of the curve pass it, the result is `undefined`.\n *\n * @param curves - The curves of the cuts, each one good for `checkEndurance`\n * @param sets - The minimal sets of the cuts. With `undefined`, as for no minimal sets, the result is `undefined`. With no sets, it is `[[0, 0]]`\n * @param maxWork - The budget of the expansions of the groups of more than `MINIMAL_STOP_CUTS` cuts, a whole number from 1. The default is `INDEPENDENT_MAX_WORK`\n * @throws RangeError when a curve does not end at a chance of 0, or for a bad `maxWork`\n */\nexport function independentStop(curves: readonly Survival[], sets: readonly (readonly number[])[] | undefined, maxWork: number = INDEPENDENT_MAX_WORK): Survival | undefined {\n if (!Number.isInteger(maxWork) || maxWork < 1) throw new RangeError(`The budget maxWork is ${String(maxWork)}: it is not a whole number from 1.`);\n if (sets === undefined) return undefined;\n // With no set, no cuts stop the supply, as for `eventStop` and `upperStop`.\n if (sets.length === 0) return [[0, 0]];\n // Only the cuts of a set change the chance. Their place in `used` is their index in the sets of the cuts that count.\n const used = [...new Set(sets.flat())].sort((x, y) => x - y);\n const usedCurves = used.map((index) => curves[index] ?? []);\n const usedSets = sets.map((set) => set.map((index) => used.indexOf(index)));\n const points = independentPoints(usedCurves);\n // Two groups of cuts that share no set are independent: the supply works when it works in each group.\n const groupChances: ((days: number) => number)[] = [];\n // The expansions of all groups share one budget.\n let work = maxWork;\n for (const group of cutGroups(used.length, usedSets)) {\n const curvesOf = group.map((index) => usedCurves[index] ?? []);\n const setsOf = usedSets.filter((set) => group.includes(set[0] ?? -1)).map((set) => set.map((index) => group.indexOf(index)));\n // Up to MINIMAL_STOP_CUTS cuts, the sum over the states is exact with a fixed cost. Past them, the expansion is exact within its budget.\n if (group.length <= MINIMAL_STOP_CUTS) {\n groupChances.push(stateChance(curvesOf, setsOf));\n continue;\n }\n const expanded = expandedChances(curvesOf, setsOf, points, work);\n if (expanded === undefined) return undefined;\n work -= expanded.steps * points.length;\n const chanceOf = new Map(points.map((days, index) => [days, expanded.chances[index] ?? 0]));\n groupChances.push((days) => {\n const chance = chanceOf.get(days);\n if (chance === undefined) throw new Error(`The expansion has no chance at ${String(days)} days.`);\n return chance;\n });\n }\n // With one group, the chance of the group is the result, with no rounding of 1 - (1 - chance).\n const [only] = groupChances;\n if (groupChances.length === 1 && only !== undefined) return curveFrom(points, only);\n return curveFrom(points, (days) => Math.min(1, Math.max(0, 1 - groupChances.reduce((works, chanceAt) => works * (1 - chanceAt(days)), 1))));\n}\n\n/** The groups of the cuts `0` to `count - 1`: two cuts are in one group when a chain of sets joins them. Each set has its cuts in one group. */\nfunction cutGroups(count: number, sets: readonly (readonly number[])[]): number[][] {\n const next = Array.from({ length: count }, () => new Set<number>());\n // A cycle through the cuts of each set joins them both ways, so the strongly connected components are the groups.\n for (const set of sets) for (const [at, index] of set.entries()) next[index]?.add(set[(at + 1) % set.length] ?? index);\n return stronglyConnectedComponents(\n Array.from({ length: count }, (_, index) => index),\n (index) => next[index] ?? [],\n );\n}\n\n/** The times of `independentStop`: the points of the curves, and the pieces that keep each line within `INDEPENDENT_TOLERANCE`. */\nfunction independentPoints(curves: readonly Survival[]): number[] {\n const times = [...new Set(curves.flatMap((curve) => curve.map(([days]) => days)))].sort((x, y) => x - y);\n const points: number[] = [];\n for (const [index, t1] of times.entries()) {\n const t0 = times[index - 1];\n if (t0 !== undefined) {\n const h = t1 - t0;\n const slopes = curves.map((curve) => Math.abs(survivalAt(curve, t1) - survivalAt(curve, t0)) / h);\n const sum = slopes.reduce((total, slope) => total + slope, 0);\n const bound = Math.max(0, sum * sum - slopes.reduce((total, slope) => total + slope * slope, 0));\n // A margin of 10 % keeps the rounding of the chance under the tolerance.\n const pieces = Math.ceil(h * Math.sqrt(bound / (8 * 0.9 * INDEPENDENT_TOLERANCE)));\n for (let piece = 1; piece < pieces; piece += 1) {\n const days = t0 + (h * piece) / pieces;\n // Two times that are next to each other as floats have no time between them.\n if (days > (points[points.length - 1] ?? t0) && days < t1) points.push(days);\n }\n }\n points.push(t1);\n }\n return points;\n}\n\n/** The chance of a stop at a time, as the sum over each state of `MINIMAL_STOP_CUTS` cuts or fewer. Bit k of a state is 1 when cut k is on. */\nfunction stateChance(curves: readonly Survival[], sets: readonly (readonly number[])[]): (days: number) => number {\n const setMasks = sets.map((set) => set.reduce((mask, index) => mask | (1 << index), 0));\n const stopping = Array.from({ length: 1 << curves.length }, (_, mask) => setMasks.some((set) => (set & mask) === set));\n const states = new Float64Array(1 << curves.length);\n return (days) => {\n // The chance of each state of the cuts, one cut at a time.\n states[0] = 1;\n let length = 1;\n for (const curve of curves) {\n const on = survivalAt(curve, days);\n for (let mask = 0; mask < length; mask += 1) {\n const chance = states[mask] ?? 0;\n states[mask + length] = chance * on;\n states[mask] = chance * (1 - on);\n }\n length *= 2;\n }\n let total = 0;\n for (let mask = 0; mask < length; mask += 1) if (stopping[mask]) total += states[mask] ?? 0;\n return Math.min(1, Math.max(0, total));\n };\n}\n\n/** The count of times in one expansion of `expandedChances`: the length of the vectors of its ring. */\nconst EXPANSION_WIDTH = 64;\n\n/**\n * The ring of the vectors of `width` chances, one for each time, for `pathSetReliability` of collections.\n * Each operation is on each time alone. In the order, `a` is less than `b` when it is less or equal at each time, and not equal.\n */\nfunction vectorRing(width: number): OrderedRing<Float64Array> {\n const zip = (a: Float64Array, b: Float64Array, op: (x: number, y: number) => number): Float64Array => {\n const out = new Float64Array(width);\n for (let index = 0; index < width; index += 1) out[index] = op(a[index] ?? 0, b[index] ?? 0);\n return out;\n };\n return {\n zero: new Float64Array(width),\n one: new Float64Array(width).fill(1),\n add: (a, b) => zip(a, b, (x, y) => x + y),\n sub: (a, b) => zip(a, b, (x, y) => x - y),\n mul: (a, b) => zip(a, b, (x, y) => x * y),\n compare: (a, b) => {\n let less = false;\n let more = false;\n for (let index = 0; index < width; index += 1) {\n const [x, y] = [a[index] ?? 0, b[index] ?? 0];\n if (x < y) less = true;\n else if (x > y) more = true;\n else if (x !== y) return Number.NaN;\n }\n return less ? (more ? Number.NaN : -1) : more ? 1 : 0;\n },\n };\n}\n\n/**\n * The chance of a stop at each point, from the Shannon expansion of `pathSetReliability`. A set works when each of its cuts is on.\n * One call gives `EXPANSION_WIDTH` points. When the steps of one expansion times the count of points pass `maxWork`, the result is `undefined`.\n * Else `steps` is the count of steps of one expansion.\n */\nfunction expandedChances(\n curves: readonly Survival[],\n sets: readonly (readonly number[])[],\n points: readonly number[],\n maxWork: number,\n): { readonly chances: number[]; readonly steps: number } | undefined {\n const maxSteps = Math.floor(maxWork / points.length);\n if (maxSteps < 1) return undefined;\n const out: number[] = [];\n let steps = 0;\n for (let start = 0; start < points.length; start += EXPANSION_WIDTH) {\n const times = points.slice(start, start + EXPANSION_WIDTH);\n const chances = curves.map((curve) => Float64Array.from(times, (days) => survivalAt(curve, days)));\n const result = pathSetReliability(sets, chances, vectorRing(times.length), { maxSteps });\n // Each call has the same sets, so the first call tells if the expansion is in the budget.\n if (result.kind === \"budget\") return undefined;\n steps = result.steps;\n for (const chance of result.value) out.push(Math.min(1, Math.max(0, chance)));\n }\n return { chances: out, steps };\n}\n\n/**\n * The curves of the stop of a draw. `event` is for one event that makes each cut longer together, and `independent` is for independent cuts.\n * `upper` is an upper limit for each dependence.\n */\nexport interface StopCurves {\n readonly event: Survival;\n /** The stop when the cuts are independent (`independentStop`). When `independentUpper` is true, it is `upper`. */\n readonly independent: Survival;\n readonly upper: Survival;\n /**\n * This is true when `upper` is the sum of the curves of the cuts that count, because the query has no minimal sets.\n * With a stack, the search of the needs passed its budget. With no stack, more than `MINIMAL_STOP_CUTS` cuts count.\n */\n readonly coarse: boolean;\n /** This is true when `independent` is `upper`: `coarse` is true, or the expansion of `independentStop` passed its budget. */\n readonly independentUpper: boolean;\n /**\n * The weakest bound (`weakestBound` of the core) of the curves of the cuts that the stop uses. Since 0.8.4.\n * With minimal sets, the stop uses the cuts of the sets. With no minimal sets, it uses each cut with a curve.\n * Each of the three curves does not decrease when a cut lasts longer, so it has this bound.\n */\n readonly bound: CutBound;\n}\n\n/** This function gives the parts of the stack that are down for a list of cut indexes. A case uses one memo for each of its draws. */\ntype StoppedOf = (cuts: readonly number[]) => ReadonlySet<string>;\n\nfunction stoppedMemo(caseCuts: CaseCuts, options: Pick<CaseOptions, \"stack\" | \"down\">): StoppedOf {\n const memo = new Map<string, ReadonlySet<string>>();\n return (cuts) => {\n const key = cuts.join(\",\");\n let found = memo.get(key);\n if (found === undefined) {\n found = caseStopped({ ...caseCuts, cuts: cuts.flatMap((index) => caseCuts.cuts[index] ?? []) }, options);\n memo.set(key, found);\n }\n return found;\n };\n}\n\n/** This function gives the parts whose cut can stop a supply: the supply, and each part that it needs through the stack. */\nfunction supplyReach(supply: string, options: Pick<CaseOptions, \"stack\">): Set<string> {\n const reach = options.stack === undefined ? new Set<string>() : neededParts(options.stack, supply);\n reach.add(supply);\n return reach;\n}\n\n/** The curves of the stop of a draw, and the indexes in `CaseCuts.cuts` of the cuts that the stop uses. */\ninterface StopRead {\n readonly curves: StopCurves;\n readonly used: readonly number[];\n}\n\nfunction stopReadWith(caseCuts: CaseCuts, draw: Draw, options: StopCurveOptions, stoppedOf: StoppedOf): StopRead | undefined {\n const reach = supplyReach(draw.supply, options);\n const relevant = caseCuts.cuts.flatMap((cut, index) => (reach.has(cut.part) ? [index] : []));\n const stops = (cuts: readonly number[]): boolean => stoppedOf(cuts.map((index) => relevant[index] ?? -1)).has(draw.supply);\n if (stops([])) return undefined;\n if (!stops(relevant.map((_, index) => index))) return undefined;\n const given = relevant.map((index) => caseCuts.cuts[index]?.duration);\n // With a stack, the needs give the minimal sets. When their search passes its budget, the sets of each list of cuts are the check.\n const parts = relevant.map((index) => caseCuts.cuts[index]?.part ?? \"\");\n const structural = options.stack === undefined ? undefined : stackStops(options.stack, draw.supply, parts, options.down, budgetsOf(options).maxSets);\n const sets = structural ?? minimalStops(given.length, stops);\n // The stop has no curve when a cut with no curve can be part of it. With no minimal sets, the query cannot tell.\n const unsourced = given.flatMap((curve, index) => (curve === undefined ? [index] : []));\n if (unsourced.length > 0 && (sets === undefined || sets.some((set) => set.some((index) => unsourced.includes(index))))) return undefined;\n // A cut with no curve is in no minimal set here, so it does not change a stop. The curves do not include it.\n const kept = given.flatMap((curve, index) => (curve === undefined ? [] : [index]));\n const curves = kept.map((index) => given[index] ?? []);\n const keptStops = (cuts: readonly number[]): boolean => stops(cuts.map((index) => kept[index] ?? -1));\n const keptSets = sets?.map((set) => set.map((index) => kept.indexOf(index)));\n const upper = upperStop(curves, keptSets);\n const independent = independentStop(curves, keptSets, budgetsOf(options).maxWork);\n // A cut in no minimal set does not change a stop, so its bound does not weaken the bound of the stop.\n const used = sets === undefined ? kept : kept.filter((index) => sets.some((set) => set.includes(index)));\n const bound = weakestBound(used.map((index) => caseCuts.cuts[relevant[index] ?? -1]?.bound ?? \"law\"));\n return {\n curves: { event: eventStop(curves, keptStops), independent: independent ?? upper, upper, coarse: keptSets === undefined, independentUpper: independent === undefined, bound },\n used: used.map((index) => relevant[index] ?? -1),\n };\n}\n\nfunction stopCurvesWith(caseCuts: CaseCuts, draw: Draw, options: StopCurveOptions, stoppedOf: StoppedOf): StopCurves | undefined {\n return stopReadWith(caseCuts, draw, options, stoppedOf)?.curves;\n}\n\n/**\n * This function gives the curves of the duration of the stop of a draw, or `undefined` when the query has no curve.\n *\n * - A set of cuts stops the supply when the supply cannot work without the cut parts, through the needs of the stack.\n * - Only the cuts of the supply, and of the parts that it needs through the stack, count. Another cut does not change the curves.\n * - The parts of `down` are down for the full event. When they stop the supply with no cut, the query has no curve.\n * - With a stack, the minimal sets come from the paths of the needs (`stopSets` of the core), so the count of cuts has no limit of `MINIMAL_STOP_CUTS`.\n * When that search passes its budget (the option `maxSets`), `minimalStops` examines each set of up to `MINIMAL_STOP_CUTS` cuts.\n * - A cut with no `duration` gives no curve when it is in a minimal set, or when the query has no minimal sets.\n * - `event` is `eventStop`. `independent` is `independentStop`, and `upper` is `upperStop`, over the minimal sets of the cuts that count.\n * - With no minimal sets, `upper` is the sum of the curves, `independent` is `upper`, and `coarse` is true.\n * - When the expansion of `independentStop` passes its budget, `independent` is `upper`, and `independentUpper` is true.\n * - `bound` is the weakest bound of the curves of the cuts that the stop uses. A cut with no `bound` has a law.\n */\nexport function stopCurves(caseCuts: CaseCuts, draw: Draw, options: StopCurveOptions = {}): StopCurves | undefined {\n budgetsOf(options);\n return stopCurvesWith(caseCuts, draw, options, stoppedMemo(caseCuts, options));\n}\n\n/**\n * This function gives the cuts that the stop of a draw uses, as indexes in `caseCuts.cuts`, or `undefined` when `stopCurves` has no curve. Since 0.8.27.\n *\n * - A used cut has a curve, and it is in a minimal set of cuts that stops the supply. With no minimal sets, each cut with a curve is used.\n * - With one used cut, each curve of `stopCurves` is the curve of that cut. `enduranceSensitivity` reads the interval of a change of the chance from it.\n *\n * @param caseCuts - The case\n * @param draw - The draw\n * @param options - The stack or the parts that are also down, and the budgets: as for `stopCurves`\n * @throws RangeError for a bad `maxSets` or `maxWork`\n */\nexport function stopCuts(caseCuts: CaseCuts, draw: Draw, options: StopCurveOptions = {}): readonly number[] | undefined {\n budgetsOf(options);\n return stopReadWith(caseCuts, draw, options, stoppedMemo(caseCuts, options))?.used;\n}\n\n/** The shortfall of each level, in user-days, and the draws that the query cannot read. */\nexport interface Shortfall {\n /**\n * The user-days of each level of the layer, when one event makes each cut longer together. The query does not add two levels.\n * This value is not a limit. The true value can be more or less. `upper` is the limit.\n */\n readonly levels: Readonly<Record<string, number>>;\n /** The user-days of each level when the cuts are independent (`StopCurves.independent`). This value is not more than `upper`. */\n readonly independent: Readonly<Record<string, number>>;\n /** The upper limit of the user-days of each level, for each dependence of the cuts. A gate of a high level can use it. */\n readonly upper: Readonly<Record<string, number>>;\n /**\n * The needs of the draws whose stop has no curve (`stopCurves`).\n * The query has no curve of their duration, so their shortfall is not in `levels`. A gate shows them as no read.\n */\n readonly unread: readonly string[];\n /** The needs of the draws whose `upper` is coarse (`StopCurves.coarse`). A gate on `upper` shows them. */\n readonly coarse: readonly string[];\n /** The needs of the draws whose `independent` is `upper` (`StopCurves.independentUpper`). A gate on `independent` shows them. */\n readonly independentUpper: readonly string[];\n /**\n * The bound of the shortfall: the weakest bound (`weakestBound` of the core) of the curves that the query uses. Since 0.8.4.\n * The shortfall does not decrease when a cut lasts longer. So with `upper`, each value is too high or equal, and with `lower` too low or equal.\n * With `none`, a value can be too high or too low.\n *\n * A draw in `unread` and a case that adds 0 do not change the bound. With no curve, the bound is `law`.\n * The bound is for each of `levels`, `independent` and `upper`, each with its own rule of the dependence of the cuts.\n */\n readonly bound: CutBound;\n}\n\nfunction zeroLevels(layer: EnduranceLayer): Record<string, number> {\n return Object.fromEntries(layer.levels.map((level) => [level, 0]));\n}\n\n/**\n * This function gives the shortfall of one event of a case: for each draw, `E[max(0, min(D, h) - T)] * users`.\n * `T` is the endurance of the draw, `D` is the duration of the stop of its supply (`stopCurves`), and `h` is the horizon.\n *\n * @param layer - The endurance layer\n * @param caseCuts - The case\n * @param endurance - The endurance of the case, from `enduranceOf`\n * @param options - The stack or the parts that are also down, as for `enduranceOf`, and the horizon\n * @throws RangeError when the horizon is not a number more than 0, or `maxSets` is not a whole number from 1\n */\nexport function caseShortfall(layer: EnduranceLayer, caseCuts: CaseCuts, endurance: Endurance, options: ShortfallOptions = {}): Shortfall {\n const horizon = horizonOf(options);\n budgetsOf(options);\n const levels = zeroLevels(layer);\n const independent = zeroLevels(layer);\n const upper = zeroLevels(layer);\n const unread: string[] = [];\n const coarse: string[] = [];\n const independentUpper: string[] = [];\n const bounds: CutBound[] = [];\n const stoppedOf = stoppedMemo(caseCuts, options);\n for (const draw of caseDraws(layer, caseCuts, caseStopped(caseCuts, options))) {\n const held = endurance.needs[draw.need];\n const curves = stopCurvesWith(caseCuts, draw, options, stoppedOf);\n if (held === undefined || curves === undefined) {\n unread.push(draw.need);\n continue;\n }\n if (curves.coarse) coarse.push(draw.need);\n if (curves.independentUpper) independentUpper.push(draw.need);\n bounds.push(curves.bound);\n const users = draw.users ?? 1;\n levels[draw.level] = (levels[draw.level] ?? 0) + heldTail(curves.event, held, horizon) * users;\n independent[draw.level] = (independent[draw.level] ?? 0) + heldTail(curves.independent, held, horizon) * users;\n upper[draw.level] = (upper[draw.level] ?? 0) + heldTail(curves.upper, held, horizon) * users;\n }\n return { levels, independent, upper, unread, coarse, independentUpper, bound: weakestBound(bounds) };\n}\n\n/**\n * The share of the stores in a case. `take` is the take order of `enduranceOf`. `best` is the leximin share of\n * `bestEndurance`, level by level.\n */\nexport type Share = \"take\" | \"best\";\n\n/** The shares, with the default first. */\nexport const SHARES: readonly Share[] = [\"take\", \"best\"];\n\n/** This function gives the share of the options. The default is `take`. */\nfunction shareOf(options: { readonly share?: Share | undefined }): Share {\n const share = options.share ?? \"take\";\n if (!SHARES.includes(share)) throw new RangeError(`The share ${String(options.share)} is not ${SHARES.join(\" or \")}.`);\n return share;\n}\n\n/** This function gives the endurance of a case with a share: `enduranceOf` for `take`, `bestEndurance` with the horizon for `best`. */\nfunction shareEndurance(layer: EnduranceLayer, caseCuts: CaseCuts, options: CaseOptions & ShortfallOptions, share: Share): Endurance {\n return share === \"best\" ? bestEndurance(layer, caseCuts, options) : enduranceOf(layer, caseCuts, options);\n}\n\n/** The options of `yearShortfall`: the date, the stack or the parts that are also down, the horizon and the share. */\nexport interface YearShortfallOptions extends CaseOptions, ShortfallOptions {\n /**\n * The share of the stores in each case. The default `take` gives the endurance from `enduranceOf`. With `best`,\n * the endurance comes from `bestEndurance`, and the horizon of the shortfall is the horizon of the share. Thus a\n * draw at the horizon keeps back only the horizon times its demand, and the lower levels get the rest.\n */\n readonly share?: Share | undefined;\n /**\n * The count of the start dates of the events of each case, for a layer with a converter with a season (M2-grow). A\n * whole number from 1. The default is `YEAR_STARTS`. The start dates are at equal steps over one year from `at`. The\n * shortfall of a case is the mean of its shortfalls at these dates, because an event can start on each day of the\n * year. A layer with no season does not use it.\n */\n readonly starts?: number | undefined;\n}\n\n/** The default count of the start dates of the events of a year, for a layer with a season: one in each month. */\nexport const YEAR_STARTS = 12;\n\n/** The user-days of each level for each curve of the stop: the three sums of a shortfall. Since 0.8.15. */\nexport type ShortfallDays = Pick<Shortfall, \"levels\" | \"independent\" | \"upper\">;\n\n/**\n * The range of the shortfall of one year from the intervals of the rates of its cases (`Prior.interval`). Since 0.8.15.\n * `low` puts the rate of each case at the low end of its interval, and `high` puts it at the high end.\n * Each end holds only for each case alone, so the two values are a range of the sampling error, not a joint interval.\n * The mean of a skewed law can be above the high end, so the expected value can be above `high`.\n */\nexport interface RateRange {\n /** The least level of the intervals of the cases in the sum. */\n readonly level: number;\n readonly low: ShortfallDays;\n readonly high: ShortfallDays;\n /** The cases in the sum with no interval of their rate. Their rate is at the two ends. */\n readonly without: readonly string[];\n}\n\n/** The part of one case in the shortfall of one year. */\nexport interface YearCase {\n readonly case: string;\n /** The expected count of the events of the case at the place in one year (`yearRate`). */\n readonly rate: number;\n /** The interval of `rate` from the interval of the prior, times its reach. A prior with no interval gives none. Since 0.8.15. */\n readonly rateInterval?: readonly [low: number, high: number] | undefined;\n /** The endurance of the case. With a season, it is the endurance at the first start date, `at`. */\n readonly endurance: Endurance;\n /** The shortfall of the case. With a season, it is the mean of the shortfalls at the start dates. */\n readonly shortfall: Shortfall;\n /** The shortfall at each start date, for a layer with a converter with a season (M2-grow). */\n readonly starts?: readonly YearStart[] | undefined;\n}\n\n/** The shortfall of a case for one start date of its event (M2-grow). */\nexport interface YearStart {\n readonly start: IsoDate;\n readonly shortfall: ShortfallDays;\n}\n\n/** The shortfall of one year at one place, with the part of each case. */\nexport interface YearShortfall extends Shortfall {\n readonly place: string;\n /** The part of each case. `rate` is the expected count of its events in one year. */\n readonly cases: readonly YearCase[];\n /** The range from the intervals of the rates. A year with no case with an interval has no range. Since 0.8.15. */\n readonly range?: RateRange | undefined;\n}\n\n/**\n * This function gives the shortfall of one year at one place.\n * It is the sum over the cases of the layer of the expected count of the events of each case times its shortfall.\n *\n * - The expected count of a case is `perYear * reach`, from the first prior of the case at the place. Thus the result is the expected user-days of one year.\n * - A case with no prior at the place is not in the sum.\n * - `unread` is the union of the needs that a case cannot read, in the order of the cases. `coarse` and `independentUpper` are unions too.\n * - `bound` is the weakest bound of the cases in the sum. A case with no prior, or with an expected count of 0, adds 0, so it does not change the bound.\n *\n * - With `share: \"best\"`, the endurance of each case comes from `bestEndurance` with the horizon of the shortfall.\n * - `range` is the same sum with the rate of each case at each end of its interval (`RateRange`).\n *\n * @param layer - The endurance layer, with its cases and priors\n * @param place - The place of the priors\n * @param options - The date, the stack or the parts that are also down, the horizon and the share\n * @throws RangeError for a bad date, horizon, `maxSets` or share: refer to `caseShortfall` and `enduranceOf`\n */\nexport function yearShortfall(layer: EnduranceLayer, place: string, options: YearShortfallOptions): YearShortfall {\n horizonOf(options);\n budgetsOf(options);\n const share = shareOf(options);\n const dates = startDates(layer, options);\n const levels = zeroLevels(layer);\n const independent = zeroLevels(layer);\n const upper = zeroLevels(layer);\n const unread: string[] = [];\n const coarse: string[] = [];\n const independentUpper: string[] = [];\n const cases: YearCase[] = [];\n const bounds: CutBound[] = [];\n const low = { levels: zeroLevels(layer), independent: zeroLevels(layer), upper: zeroLevels(layer) };\n const high = { levels: zeroLevels(layer), independent: zeroLevels(layer), upper: zeroLevels(layer) };\n const without: string[] = [];\n let level = Infinity;\n for (const caseCuts of layer.cases ?? []) {\n const prior = (layer.priors ?? []).find((item) => item.case === caseCuts.case && item.place === place);\n if (prior === undefined) continue;\n const rate = yearRate(prior);\n // With a season, the case has one endurance and one shortfall for each start date, and its shortfall is their mean.\n const each = dates.map((start) => {\n const endurance = shareEndurance(layer, caseCuts, dates.length === 1 ? options : { ...options, start }, share);\n return { start, endurance, shortfall: caseShortfall(layer, caseCuts, endurance, options) };\n });\n const endurance = each[0]!.endurance;\n const shortfall = each.length === 1 ? each[0]!.shortfall : meanShortfall(layer, each.map((item) => item.shortfall));\n const starts = each.length === 1 ? {} : { starts: each.map((item) => ({ start: item.start, shortfall: { levels: item.shortfall.levels, independent: item.shortfall.independent, upper: item.shortfall.upper } })) };\n addDays({ levels, independent, upper }, shortfall, rate);\n const rateInterval = prior.interval === undefined ? undefined : ([prior.interval.low * prior.reach, prior.interval.high * prior.reach] as const);\n if (rateInterval === undefined) without.push(caseCuts.case);\n else level = Math.min(level, prior.interval?.level ?? level);\n addDays(low, shortfall, rateInterval?.[0] ?? rate);\n addDays(high, shortfall, rateInterval?.[1] ?? rate);\n for (const need of shortfall.unread) if (!unread.includes(need)) unread.push(need);\n for (const need of shortfall.coarse) if (!coarse.includes(need)) coarse.push(need);\n for (const need of shortfall.independentUpper) if (!independentUpper.includes(need)) independentUpper.push(need);\n if (rate > 0) bounds.push(shortfall.bound);\n cases.push({ case: caseCuts.case, rate, ...(rateInterval === undefined ? {} : { rateInterval }), endurance, shortfall, ...starts });\n }\n const range = Number.isFinite(level) ? { range: { level, low, high, without } } : {};\n return { place, levels, independent, upper, unread, coarse, independentUpper, bound: weakestBound(bounds), cases, ...range };\n}\n\n/**\n * This function gives the start dates of the events of a year: `at` alone for a layer with no converter with a season.\n * Otherwise `starts` dates at equal steps over 365 days from `at`.\n */\nfunction startDates(layer: EnduranceLayer, options: YearShortfallOptions): IsoDate[] {\n if (!(layer.converters ?? []).some((converter) => converter.season !== undefined)) return [options.at];\n const count = options.starts ?? YEAR_STARTS;\n if (!Number.isSafeInteger(count) || count < 1) throw new RangeError(`The option starts is ${String(options.starts)}: it is not a whole number from 1.`);\n const first = dayNumber(options.at);\n if (first === undefined) throw new RangeError(`The date \"${options.at}\" is not a date YYYY-MM-DD.`);\n return Array.from({ length: count }, (_, index) => dateOfDay(first + Math.floor((index * 365) / count)));\n}\n\n/** This function gives the mean of the shortfalls of one case at its start dates. The lists are unions, and the bound is the weakest. */\nfunction meanShortfall(layer: EnduranceLayer, list: readonly Shortfall[]): Shortfall {\n const days = { levels: zeroLevels(layer), independent: zeroLevels(layer), upper: zeroLevels(layer) };\n for (const shortfall of list) addDays(days, shortfall, 1 / list.length);\n const union = (pick: (shortfall: Shortfall) => readonly string[]): string[] => [...new Set(list.flatMap(pick))];\n return { ...days, unread: union((item) => item.unread), coarse: union((item) => item.coarse), independentUpper: union((item) => item.independentUpper), bound: weakestBound(list.map((item) => item.bound)) };\n}\n\n/** This function adds the user-days of a shortfall times a count of events to each sum of the days. */\nfunction addDays(days: { levels: Record<string, number>; independent: Record<string, number>; upper: Record<string, number> }, shortfall: ShortfallDays, count: number): void {\n for (const [level, value] of Object.entries(shortfall.levels)) days.levels[level] = (days.levels[level] ?? 0) + count * value;\n for (const [level, value] of Object.entries(shortfall.independent)) days.independent[level] = (days.independent[level] ?? 0) + count * value;\n for (const [level, value] of Object.entries(shortfall.upper)) days.upper[level] = (days.upper[level] ?? 0) + count * value;\n}\n\n/** The options of `caseOutlook`: the date, the stack or the parts that are also down, the horizon and the share. */\nexport type OutlookOptions = YearShortfallOptions;\n\n/** A value for each curve of the stop of a draw (`StopCurves`). */\nexport interface CurveValues {\n /** The value when one event makes each cut longer together. */\n readonly event: number;\n /** The value when the cuts are independent. */\n readonly independent: number;\n /** The value of the upper curve: the safe side for each dependence of the cuts. */\n readonly upper: number;\n}\n\n/** The chance and the shortfall of a draw at one end of the sampling bands of its cuts. Since 0.8.14. */\nexport interface BandValues {\n readonly lasts: CurveValues;\n readonly shortfall: CurveValues;\n}\n\n/**\n * The values of a draw at the two ends of the sampling bands of its cuts (`Cut.band`). Since 0.8.14.\n * `shorter` puts each cut at the low end of its band, and `longer` puts each cut at the high end.\n * Each end holds only pointwise, so the two values are a range of the sampling error, not a joint interval.\n */\nexport interface DrawBand {\n readonly shorter: BandValues;\n readonly longer: BandValues;\n}\n\n/** The outlook of one draw in one event of a case. */\nexport interface DrawOutlook {\n readonly need: string;\n readonly level: string;\n readonly supply: string;\n readonly users: number;\n /** The days that the stores give the draw (`DrawEndurance.days`). */\n readonly days: number;\n /** This is true when the draw holds to the horizon of a best share. */\n readonly atHorizon?: true;\n /**\n * The chance that the draw gets its need through the event: `P(min(D, h) <= T)`, for each curve of the stop.\n * `D` is the duration of the stop, `T` is `days` and `h` is the horizon. A draw that holds to the horizon has the chance 1.\n * The chance of `upper` is not more than the true chance, for each dependence of the cuts.\n */\n readonly lasts: CurveValues;\n /** The user-days of the shortfall in one event, `E[max(0, min(D, h) - T)] * users`, for each curve. */\n readonly shortfall: CurveValues;\n /** The bound of the curves of the stop (`StopCurves.bound`). */\n readonly bound: CutBound;\n /** This is true when the upper curve is coarse (`StopCurves.coarse`). */\n readonly coarse: boolean;\n /**\n * The values at the two ends of the sampling bands of the cuts, with the same days. Since 0.8.14.\n * It is missing when a cut that can be part of the stop has a curve and no band. Then the sampling error has no read.\n */\n readonly band?: DrawBand | undefined;\n}\n\n/** The outlook of one event of a case: the days, the chance and the shortfall of each draw. */\nexport interface CaseOutlook {\n readonly case: string;\n readonly title: string;\n readonly at: string;\n readonly share: Share;\n /** The horizon in days, or `undefined` for no horizon. */\n readonly horizon: number | undefined;\n /** Each draw whose supply the case stops and whose stop has a curve, in the order of the layer. */\n readonly draws: readonly DrawOutlook[];\n /** The needs of the draws whose supply the case does not stop. They get their need through the event. */\n readonly holds: readonly string[];\n /** The needs of the draws whose stop has no curve (`stopCurves`). They are no read, not a pass. */\n readonly unread: readonly string[];\n /** The weakest bound of the curves of `draws`. */\n readonly bound: CutBound;\n}\n\n/**\n * This function gives the outlook of one event of a case. For each draw, it gives the days, the chance that the\n * stores last through the stop, and the shortfall. A page of a place can show it for each case of its region.\n *\n * - The days come from the share of the stores: `enduranceOf` for `take`, `bestEndurance` with the horizon for `best`.\n * - The chance and the shortfall use the curves of `stopCurves`. They count the stop only up to the horizon.\n * - `upper` is the safe side: its chance is not more, and its shortfall is not less, than the true value for each dependence.\n * - `band` gives the same values with each cut at each end of its sampling band (`Cut.band`). The days do not change.\n *\n * @param layer - The endurance layer\n * @param caseCuts - The case\n * @param options - The date, the stack or the parts that are also down, the horizon and the share\n * @throws RangeError for a bad date, horizon, `maxSets` or share: refer to `caseShortfall` and `enduranceOf`\n */\nexport function caseOutlook(layer: EnduranceLayer, caseCuts: CaseCuts, options: OutlookOptions): CaseOutlook {\n const horizon = horizonOf(options);\n budgetsOf(options);\n const share = shareOf(options);\n const endurance = shareEndurance(layer, caseCuts, options, share);\n const stopped = caseDraws(layer, caseCuts, caseStopped(caseCuts, options));\n const stoppedNeeds = new Set(stopped.map((draw) => draw.need));\n const stoppedOf = stoppedMemo(caseCuts, options);\n // Each end of the bands: a cut with a band takes that end as its curve, and a cut with no band has no curve.\n const banded = caseCuts.cuts.some((cut) => cut.band !== undefined);\n const endCuts = (end: \"low\" | \"high\"): CaseCuts => ({ ...caseCuts, cuts: caseCuts.cuts.map(({ duration: _, band, ...cut }) => (band === undefined ? cut : { ...cut, duration: band[end], band })) });\n const ends = banded ? { shorter: endCuts(\"low\"), longer: endCuts(\"high\") } : undefined;\n const draws: DrawOutlook[] = [];\n const unread: string[] = [];\n const bounds: CutBound[] = [];\n for (const draw of stopped) {\n const held = endurance.needs[draw.need];\n const curves = stopCurvesWith(caseCuts, draw, options, stoppedOf);\n if (held === undefined || curves === undefined) {\n unread.push(draw.need);\n continue;\n }\n const users = draw.users ?? 1;\n const lasts = (curve: Survival): number => (held.days >= horizon ? 1 : 1 - survivalAt(curve, held.days));\n const short = (curve: Survival): number => heldTail(curve, held, horizon) * users;\n const values = (stop: StopCurves): BandValues => ({\n lasts: { event: lasts(stop.event), independent: lasts(stop.independent), upper: lasts(stop.upper) },\n shortfall: { event: short(stop.event), independent: short(stop.independent), upper: short(stop.upper) },\n });\n const shorter = ends === undefined ? undefined : stopCurvesWith(ends.shorter, draw, options, stoppedOf);\n const longer = ends === undefined ? undefined : stopCurvesWith(ends.longer, draw, options, stoppedOf);\n const band = shorter === undefined || longer === undefined ? {} : { band: { shorter: values(shorter), longer: values(longer) } };\n bounds.push(curves.bound);\n draws.push({\n need: draw.need,\n level: draw.level,\n supply: draw.supply,\n users,\n days: held.days,\n ...(held.atHorizon === true ? { atHorizon: true as const } : {}),\n ...values(curves),\n bound: curves.bound,\n coarse: curves.coarse,\n ...band,\n });\n }\n const holds = layer.draws.filter((draw) => !stoppedNeeds.has(draw.need)).map((draw) => draw.need);\n return {\n case: caseCuts.case,\n title: caseCuts.title,\n at: endurance.at,\n share,\n horizon: Number.isFinite(horizon) ? horizon : undefined,\n draws,\n holds,\n unread,\n bound: weakestBound(bounds),\n };\n}\n","import { STACK_SCHEMA, type Stack } from \"@mark1russell7/system-stack\";\nimport { ENDURANCE_SCHEMA, type EnduranceLayer } from \"./layer.ts\";\n\n// A sample: a building with 3 users, and a storm that cuts the grid, the road and the water main.\n// Each name and each value is an example, except the grid curve (NREL, technical report 83092). The tests, the README files and the site use it.\n\n/** The base stack of the sample: the supplies of the building and a camp stove. */\nexport const SAMPLE_ENDURANCE_STACK: Stack = {\n schema: STACK_SCHEMA,\n parts: [\n { id: \"grid\", kind: \"power\", name: \"The power grid\" },\n { id: \"water-main\", kind: \"water\", name: \"The water main\" },\n { id: \"road\", kind: \"road\", name: \"The local road to the shops\" },\n { id: \"stove\", kind: \"device\", name: \"The camp stove\" },\n ],\n};\n\n/**\n * The endurance layer of the sample.\n *\n * - The drinking water holds 75.7 L / 11.355 L a day = 6.667 days.\n * - The food holds 4800 / 5400 = 0.889 days. The rice needs 2 L of water for each kg, and the drinking water keeps back all the water.\n * - The power holds 1000 Wh / 150 Wh a day = 6.667 days.\n * - The filled bottles are past their due date, so they give nothing.\n */\nexport const SAMPLE_ENDURANCE: EnduranceLayer = {\n schema: ENDURANCE_SCHEMA,\n levels: [\"life\", \"health\", \"comfort\"],\n resources: [\n { code: \"water.stored\", unit: \"L\" },\n { code: \"food.ready\", unit: \"kcal\" },\n { code: \"food.grain-dry\", unit: \"kg\" },\n { code: \"fuel.propane\", unit: \"kg\" },\n { code: \"energy.battery\", unit: \"Wh\" },\n ],\n stores: [\n { id: \"jugs\", resource: \"water.stored\", amount: 75.7, due: \"2028-06-01\" },\n { id: \"bottles\", resource: \"water.stored\", amount: 20, due: \"2026-09-30\" },\n { id: \"cans\", resource: \"food.ready\", amount: 4800, due: \"2028-10-01\" },\n { id: \"rice\", resource: \"food.grain-dry\", amount: 9, due: \"2036-09-28\" },\n { id: \"propane\", resource: \"fuel.propane\", amount: 0.908, due: \"2036-10-01\" },\n { id: \"battery\", resource: \"energy.battery\", amount: 1000, due: \"2031-10-01\" },\n ],\n draws: [\n { need: \"hydration.drink\", level: \"life\", perDay: 11.355, users: 3, supply: \"water-main\" },\n { need: \"food.energy\", level: \"health\", perDay: 5400, users: 3, supply: \"road\" },\n { need: \"power.electric\", level: \"comfort\", perDay: 150, users: 3, supply: \"grid\" },\n ],\n direct: [\n { resource: \"water.stored\", need: \"hydration.drink\", amount: 1 },\n { resource: \"food.ready\", need: \"food.energy\", amount: 1 },\n { resource: \"energy.battery\", need: \"power.electric\", amount: 1 },\n ],\n converters: [\n {\n id: \"cook-rice\",\n device: \"stove\",\n takes: [\n { resource: \"food.grain-dry\", amount: 1 },\n { resource: \"water.stored\", amount: 2 },\n { resource: \"fuel.propane\", amount: 0.05 },\n ],\n gives: { need: \"food.energy\", amount: 3600 },\n },\n ],\n cases: [\n {\n case: \"storm\",\n title: \"Winter storm\",\n cuts: [\n { part: \"grid\", title: \"Power outage\", duration: [[0, 1], [0.5, 0.5], [1, 0.36], [7, 0.013], [30, 0]], source: \"nrel-83092\" },\n { part: \"road\", title: \"Closed local road\", duration: [[0, 1], [1, 0.6], [3, 0.2], [10, 0]], source: \"sample\" },\n { part: \"water-main\", title: \"No water from the main\", duration: [[0, 1], [2, 0.3], [7, 0]], source: \"sample\" },\n ],\n leadSeconds: 86_400,\n },\n { case: \"fire\", title: \"Fire\", cuts: [] },\n ],\n priors: [\n { case: \"storm\", place: \"home\", perYear: 0.8, reach: 1, source: \"sample\", asOf: \"2025-12-01\" },\n { case: \"fire\", place: \"home\", perYear: 0.003, reach: 1, source: \"sample\", asOf: \"2025-12-01\" },\n ],\n};\n","import { kaplanMeier, survivalDifference, Z95, type SurvivalCurve, type TimeToEvent } from \"@mark1russell7/rigor-statistics\";\nimport { countsFault, type DurationCounts } from \"@mark1russell7/system-stack\";\nimport { deviceKey } from \"./converter.ts\";\nimport { enduranceOf, type CaseOptions } from \"./endurance.ts\";\nimport type { CaseCuts, Converter, Endurance, EnduranceLayer, IsoDate, Survival } from \"./layer.ts\";\nimport { caseOutlook, stopCuts, type CurveValues, type DrawBand, type DrawOutlook, type ShortfallOptions, type StopCurveOptions } from \"./shortfall.ts\";\n\n// The sensitivity of a layer (M2-endurance-sensitivity): the change in the days of each draw for one step of each input.\n// The core names no topic. An input is the amount of a store, the rate of a draw or a parameter of a converter.\n\n/** The default step of `enduranceSensitivity`: 1 unit of each input. */\nexport const SENSITIVITY_STEP = 1;\n\n/** The options of `enduranceSensitivity`: the options of a case, the horizon of the chance, and the step. */\nexport interface SensitivityOptions extends CaseOptions, ShortfallOptions {\n /** The step of each input, a number more than 0, in the unit of the input. The default is `SENSITIVITY_STEP`. */\n readonly step?: number | undefined;\n}\n\n/** The kind of an input: the amount of a store, the rate of a draw, or a parameter of a converter. */\nexport type SensitivityKind = \"store\" | \"draw\" | \"converter\";\n\n/**\n * The 95% interval of the change of the chance (`SensitivityChance.change`), from the sampling error of the curve of one cut. Since 0.8.27.\n * The ends are the change minus and plus `Z95` times `se`, clamped to 0 to 1, or to -1 to 0 for a change down.\n * It is a Wald interval. Near the ends of the range, its coverage can be less than 95%.\n */\nexport interface ChanceInterval {\n /** The Greenwood standard error of the change. It includes the covariance of the chances of the curve at the days before and after the step. */\n readonly se: number;\n readonly low: number;\n readonly high: number;\n}\n\n/**\n * The change in the chance that a draw gets its need through the event (`DrawOutlook.lasts`), for one input.\n * The chance comes from the curves of the stop. Only the days change, so the curves are the same before and after.\n */\nexport interface SensitivityChance {\n /** The chance before the step, for each curve of the stop. */\n readonly before: CurveValues;\n /** The chance after the step, for each curve of the stop. */\n readonly after: CurveValues;\n /** The chance after the step minus the chance before it, for each curve. It is the change of the point values. */\n readonly change: CurveValues;\n /**\n * The 95% interval of `change`, when the stop of the draw uses one cut, and that cut has counts (`Cut.counts`) with no fault. Since 0.8.27.\n * With one cut, the three curves of the stop are the curve of the cut, so the three changes are equal.\n * Without counts, the interval is also absent.\n *\n * With two or more cuts, the interval is absent. The event curve and the upper curve are not smooth functions of the curves\n * of the cuts (a maximum, and a sum with a limit). The independent curve is a polynomial with a term for each state of the cuts.\n */\n readonly interval?: ChanceInterval | undefined;\n /** The values before the step at the two ends of the sampling bands of the cuts (`DrawOutlook.band`). */\n readonly beforeBand?: DrawBand | undefined;\n /** The values after the step at the two ends of the sampling bands of the cuts. */\n readonly afterBand?: DrawBand | undefined;\n}\n\n/** The change in the days of one draw for one input. */\nexport interface SensitivityNeed {\n readonly need: string;\n readonly level: string;\n /** The days of the draw before the step (`DrawEndurance.days`). */\n readonly before: number;\n /** The days of the draw after the step. */\n readonly after: number;\n /** The days after the step minus the days before it. */\n readonly change: number;\n /** The change for each unit of the input: `change` divided by the size of `delta`. */\n readonly perUnit: number;\n /** The change in the chance. It is missing when the stop of the draw has no curve (`CaseOutlook.unread`). */\n readonly chance?: SensitivityChance | undefined;\n}\n\n/** One input of a layer, and the change in the days of each draw for its step. */\nexport interface SensitivityInput {\n /**\n * The key of the input: `store:<id>`, `draw:<need>`, `converter:<id>.gives`, `converter:<id>.takes.<resource>` or\n * `converter:<id>.perDay`. The count of devices has the key of the device and `.devices`, for example `device:stove.devices`.\n */\n readonly id: string;\n readonly kind: SensitivityKind;\n /** The `id` of the store, the need of the draw, the `id` of the converter, or the device of a count of devices. */\n readonly target: string;\n /** The field that the step changes: `amount`, `perDay`, `gives`, `takes.<resource>` or `devices`. */\n readonly field: string;\n /** The value of the field before the step. */\n readonly value: number;\n /** The change of the value: more than 0 for more of the input, less than 0 for a lower draw or a lower take. */\n readonly delta: number;\n /** The change of each draw whose supply the case stops, in the order of `enduranceOf`. */\n readonly needs: readonly SensitivityNeed[];\n /** The sum of the changes of the draws of each level, by the level. The rank compares these sums. */\n readonly levels: Readonly<Record<string, number>>;\n}\n\n/** The sensitivity of a layer in a case: each input with its change, the largest change first. */\nexport interface Sensitivity {\n readonly case: string;\n readonly at: IsoDate;\n /** The step of the query. */\n readonly step: number;\n /** The endurance before each step. */\n readonly base: Endurance;\n /** The rank of the inputs. Refer to `enduranceSensitivity`. */\n readonly inputs: readonly SensitivityInput[];\n}\n\n/** One input and the layer after its step. */\ninterface Variant {\n readonly id: string;\n readonly kind: SensitivityKind;\n readonly target: string;\n readonly field: string;\n readonly value: number;\n readonly delta: number;\n readonly layer: EnduranceLayer;\n}\n\n/** This function gives the size of a step down from a value. It is the step, or half the value when the value is not more than the step. */\nfunction stepDown(value: number, step: number): number {\n return value > step ? step : value / 2;\n}\n\n/** This function gives each input of a layer and the layer after its step. */\nfunction variantsOf(layer: EnduranceLayer, step: number): Variant[] {\n const out: Variant[] = [];\n for (const store of layer.stores) {\n const amount = store.amount + step;\n // A store with a capacity keeps a capacity that is not less than its amount.\n const changed = { ...store, amount, ...(store.capacity !== undefined && amount > store.capacity ? { capacity: amount } : {}) };\n out.push({ id: `store:${store.id}`, kind: \"store\", target: store.id, field: \"amount\", value: store.amount, delta: step, layer: { ...layer, stores: layer.stores.map((item) => (item === store ? changed : item)) } });\n }\n for (const draw of layer.draws) {\n if (!(draw.perDay > 0)) continue;\n const delta = -stepDown(draw.perDay, step);\n const changed = { ...draw, perDay: draw.perDay + delta };\n out.push({ id: `draw:${draw.need}`, kind: \"draw\", target: draw.need, field: \"perDay\", value: draw.perDay, delta, layer: { ...layer, draws: layer.draws.map((item) => (item === draw ? changed : item)) } });\n }\n const converters = layer.converters ?? [];\n const withConverters = (change: (converter: Converter) => Converter): EnduranceLayer => ({ ...layer, converters: converters.map(change) });\n const devicesSeen = new Set<string>();\n for (const converter of converters) {\n const key = `converter:${converter.id}`;\n if (converter.gives.amount > 0) {\n const gives = { ...converter.gives, amount: converter.gives.amount + step };\n out.push({ id: `${key}.gives`, kind: \"converter\", target: converter.id, field: \"gives\", value: converter.gives.amount, delta: step, layer: withConverters((item) => (item === converter ? { ...item, gives } : item)) });\n }\n for (const input of converter.takes) {\n if (!(input.amount > 0)) continue;\n const delta = -stepDown(input.amount, step);\n const takes = converter.takes.map((item) => (item === input ? { ...item, amount: item.amount + delta } : item));\n out.push({ id: `${key}.takes.${input.resource}`, kind: \"converter\", target: converter.id, field: `takes.${input.resource}`, value: input.amount, delta, layer: withConverters((item) => (item === converter ? { ...item, takes } : item)) });\n }\n // A converter with no limit `perDay` has no limit to change, and its count of devices has no effect.\n if (converter.perDay === undefined) continue;\n const perDay = converter.perDay + step;\n out.push({ id: `${key}.perDay`, kind: \"converter\", target: converter.id, field: \"perDay\", value: converter.perDay, delta: step, layer: withConverters((item) => (item === converter ? { ...item, perDay } : item)) });\n // The converters of one device share one count of devices. A device is a whole unit, so the step of a count is 1.\n const device = deviceKey(converter);\n if (devicesSeen.has(device)) continue;\n devicesSeen.add(device);\n const count = converter.devices ?? 1;\n out.push({ id: `${device}.devices`, kind: \"converter\", target: converter.device ?? converter.id, field: \"devices\", value: count, delta: 1, layer: withConverters((item) => (deviceKey(item) === device ? { ...item, devices: count + 1 } : item)) });\n }\n return out;\n}\n\n/** This function gives `a` minus `b` for each curve. */\nfunction minus(a: CurveValues, b: CurveValues): CurveValues {\n return { event: a.event - b.event, independent: a.independent - b.independent, upper: a.upper - b.upper };\n}\n\n/** The curve of the one cut of the stop of a draw, with the Kaplan-Meier estimate of its counts. */\ninterface CountedCurve {\n readonly curve: Survival;\n readonly last: number;\n readonly estimate: SurvivalCurve;\n}\n\n/**\n * This function gives the Kaplan-Meier estimate of a table of counts, with the same chance and Greenwood sum at each step.\n * The observations that leave after a step, with no event, are censored at the day of that step, or at `last` after the last step.\n */\nfunction estimateOf(counts: DurationCounts): SurvivalCurve {\n const observations: TimeToEvent[] = [];\n for (const [index, [days, atRisk, events]] of counts.steps.entries()) {\n const next = counts.steps[index + 1];\n const left = atRisk - events - (next?.[1] ?? 0);\n observations.push({ time: days, count: events });\n if (left > 0) observations.push({ time: next === undefined ? counts.last : days, censored: true, count: left });\n }\n if (observations.length === 0) observations.push({ time: counts.last, censored: true });\n return kaplanMeier(observations);\n}\n\n/** This function gives the curve of the one cut of the stop of a draw, when that cut has counts with no fault. */\nfunction countedCurveOf(layer: EnduranceLayer, caseCuts: CaseCuts, need: string, options: StopCurveOptions): CountedCurve | undefined {\n const draw = layer.draws.find((item) => item.need === need);\n const used = draw === undefined ? undefined : stopCuts(caseCuts, draw, options);\n if (used === undefined || used.length !== 1) return undefined;\n const cut = caseCuts.cuts[used[0] ?? -1];\n if (cut?.duration === undefined || cut.counts === undefined || countsFault(cut.duration, cut.counts) !== undefined) return undefined;\n return { curve: cut.duration, last: cut.counts.last, estimate: estimateOf(cut.counts) };\n}\n\n/**\n * This function gives the points of a curve and their weights in the read of `survivalAt` of the core at `days`.\n * Between two points, the read is linear, so it has a weight on each of the two points. After the last point, the read is 0.\n */\nfunction pointWeights(curve: Survival, days: number): [day: number, weight: number][] {\n if (days <= 0) return [[curve[0]?.[0] ?? 0, 1]];\n for (let index = 1; index < curve.length; index += 1) {\n const [t0] = curve[index - 1] ?? [0, 1];\n const [t1] = curve[index] ?? [0, 0];\n if (days < t1) {\n const weight = (days - t0) / (t1 - t0);\n return weight === 0 ? [[t0, 1]] : [[t0, 1 - weight], [t1, weight]];\n }\n if (days === t1) return [[t1, 1]];\n }\n return [];\n}\n\n/**\n * This function gives the interval of the change of the chance, from the counts of the one cut of the stop.\n *\n * - The change is `S(before) - S(after)`. A read at or after the horizon is 0, so it adds no term.\n * - 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.\n * - The variance of the weighted sum uses the covariance of each two chances. `survivalDifference` of rigor-statistics gives\n * 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`.\n */\nfunction changeInterval(read: CountedCurve, before: number, after: number, horizon: number, change: number): ChanceInterval | undefined {\n const terms: [day: number, weight: number][] = [];\n const add = (days: number, sign: number): void => {\n if (days >= horizon) return;\n for (const [day, weight] of pointWeights(read.curve, days)) if (day > 0 && day <= read.last) terms.push([day, sign * weight]);\n };\n add(before, 1);\n add(after, -1);\n const square = (from: number, to: number): number | undefined => {\n const difference = survivalDifference(read.estimate, from, to);\n return difference === undefined ? undefined : difference.se * difference.se;\n };\n let variance = 0;\n for (const [a, weightA] of terms) {\n for (const [b, weightB] of terms) {\n const atA = square(0, a);\n const atB = square(0, b);\n const between = square(a, b);\n if (atA === undefined || atB === undefined || between === undefined) return undefined;\n variance += weightA * weightB * ((atA + atB - between) / 2);\n }\n }\n const se = Math.sqrt(Math.max(0, variance));\n const [floor, ceiling]: [number, number] = (after >= horizon ? Infinity : after) >= (before >= horizon ? Infinity : before) ? [0, 1] : [-1, 0];\n const clamp = (value: number): number => Math.min(ceiling, Math.max(floor, value));\n return { se, low: clamp(change - Z95 * se), high: clamp(change + Z95 * se) };\n}\n\n/** This function compares two inputs for the rank: the sums of the levels in the order of the levels, the largest first, then the key. */\nfunction rankOrder(levels: readonly string[]): (a: SensitivityInput, b: SensitivityInput) => number {\n return (a, b) => {\n for (const level of levels) {\n const diff = (b.levels[level] ?? 0) - (a.levels[level] ?? 0);\n if (diff > 0) return 1;\n if (diff < 0) return -1;\n }\n return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;\n };\n}\n\n/**\n * This function gives the change in the days of each draw for one step of each input of a layer, ranked.\n * The rank names the input that moves the days most. A lower draw costs nothing, so the rank also shows such inputs.\n *\n * - The inputs are the amount of each store and the rate `perDay` of each draw. Each converter gives the amount of its\n * gift, the amount of each take, its limit `perDay` and its count of devices.\n * - The step adds to a store, to a gift, to a limit `perDay` and to a count of devices. It takes off a draw and a take,\n * because less of them gives more days. A count of devices takes 1 more device.\n * - When the rate of a draw or a take is not more than the step, the step takes off half the value. Thus the value stays more than 0.\n * - A store with a capacity gets a capacity that is not less than its new amount.\n * - The change of a draw is a finite difference: the days of `enduranceOf` after the step minus the days before it.\n * `perUnit` divides it by the size of the change of the value.\n * - An input that no draw of the case uses has a change of 0, for example a store past its due date.\n * - The rank is by level. It compares the sum of the changes of the draws of the first level, then of the next level, and so on.\n * The largest sum comes first. Two equal inputs go in the order of their keys. Thus the order is stable.\n * - The days are exact for the inputs. `chance` is the chance that a draw gets its need through the event. It comes\n * from `caseOutlook` with the share `take`, before and after the step, with the bands of the cuts. The change of the\n * chance is the change of the point values.\n * - The change has a 95% interval (`SensitivityChance.interval`) when the stop of the draw uses one cut (`stopCuts`) with counts.\n * 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.\n *\n * The cost is one `enduranceOf` and one `caseOutlook` for each input, and one `stopCuts` for each draw of the base. The function is pure.\n *\n * @param layer - The endurance layer\n * @param caseCuts - The case\n * @param options - The date, the stack or the parts that are also down, the horizon and the step\n * @returns The endurance before the steps, and the inputs in the order of the rank\n * @throws RangeError for a step that is not a finite number more than 0, and for the errors of `enduranceOf` and `caseOutlook`\n */\nexport function enduranceSensitivity(layer: EnduranceLayer, caseCuts: CaseCuts, options: SensitivityOptions): Sensitivity {\n const { step: given, ...caseOptions } = options;\n const step = given ?? SENSITIVITY_STEP;\n if (!(step > 0) || !Number.isFinite(step)) throw new RangeError(`The step ${String(given)} is not a finite number more than 0.`);\n const base = enduranceOf(layer, caseCuts, caseOptions);\n const outlookOf = (changed: EnduranceLayer): Map<string, DrawOutlook> => new Map(caseOutlook(changed, caseCuts, { ...caseOptions, share: \"take\" }).draws.map((draw) => [draw.need, draw] as const));\n const baseOutlook = outlookOf(layer);\n // The stop of each draw uses the same cuts before and after the step, so the curve with counts comes from the base.\n const counted = new Map([...baseOutlook.keys()].flatMap((need) => {\n const read = countedCurveOf(layer, caseCuts, need, caseOptions);\n return read === undefined ? [] : [[need, read] as const];\n }));\n const horizon = caseOptions.horizon ?? Infinity;\n const levelOf = new Map(layer.draws.map((draw) => [draw.need, draw.level] as const));\n const inputs = variantsOf(layer, step).map(({ layer: changed, ...variant }): SensitivityInput => {\n const after = enduranceOf(changed, caseCuts, caseOptions);\n // With no curve of a stop, the case has no chance to read, so the query does not call `caseOutlook` again.\n const outlook = baseOutlook.size === 0 ? undefined : outlookOf(changed);\n const sums = new Map<string, number>(layer.levels.map((level) => [level, 0] as const));\n const needs = Object.entries(base.needs).map(([need, held]): SensitivityNeed => {\n const days = after.needs[need]?.days ?? held.days;\n const change = days === held.days ? 0 : days - held.days;\n const level = levelOf.get(need) ?? \"\";\n const sum = sums.get(level);\n if (sum !== undefined) sums.set(level, sum + change);\n const from = baseOutlook.get(need);\n const to = outlook?.get(need);\n const read = counted.get(need);\n const moved = from === undefined || to === undefined ? undefined : minus(to.lasts, from.lasts);\n const interval = read === undefined || from === undefined || to === undefined || moved === undefined ? undefined : changeInterval(read, from.days, to.days, horizon, moved.event);\n const chance =\n from === undefined || to === undefined || moved === undefined\n ? {}\n : {\n chance: {\n before: from.lasts,\n after: to.lasts,\n change: moved,\n ...(from.band === undefined ? {} : { beforeBand: from.band }),\n ...(to.band === undefined ? {} : { afterBand: to.band }),\n ...(interval === undefined ? {} : { interval }),\n },\n };\n return { need, level, before: held.days, after: days, change, perUnit: change / Math.abs(variant.delta), ...chance };\n });\n return { ...variant, needs, levels: Object.fromEntries(sums) };\n });\n inputs.sort(rankOrder(layer.levels));\n return { case: caseCuts.case, at: options.at, step, base, inputs };\n}\n","import type { IsoDate } from \"./layer.ts\";\nimport type { Sensitivity, SensitivityInput, SensitivityKind } from \"./sensitivity.ts\";\n\n// The rank of the next buy (M2-days-per-dollar): the days that each input adds for one unit of money.\n// The core names no topic. The prices are input data, and the caller owns their source.\n\n/**\n * A table of prices: the price of one unit of each input, in one currency.\n * The key of a price is the key of the input (`SensitivityInput.id`), for example `store:jugs` or `converter:cook.gives`.\n * The key is the input key, because the kind and the target do not identify one input. A converter has an input\n * for its gift, for each take and for its limit, all with the same target.\n */\nexport interface PriceTable {\n /** The code of the currency of each price, for example `USD`. The rank does not convert a currency. */\n readonly currency: string;\n /** The price of one unit of each input, by the key of the input. The unit is the unit of the input, for example 1 L of a store. */\n readonly prices: Readonly<Record<string, number>>;\n}\n\n/** The options of `daysPerDollar`. */\nexport interface DaysPerDollarOptions {\n /** The levels of the layer, the most important first (`EnduranceLayer.levels`). The rank compares the levels in this order. */\n readonly levels: readonly string[];\n}\n\n/** The reason why an input has no rank: the table has no price for it, or its price is bad. A bad price is not a finite number more than 0. */\nexport type UnpricedReason = \"no-price\" | \"bad-price\";\n\n/** One input with a price, and its days for one unit and for one unit of money. */\nexport interface PricedInput {\n readonly id: string;\n readonly kind: SensitivityKind;\n readonly target: string;\n readonly field: string;\n /** The price of one unit of the input, in the currency of the table. */\n readonly price: number;\n /** The days of each level for one unit of the input: the sum of the changes of the level divided by the size of `delta`. */\n readonly perUnit: Readonly<Record<string, number>>;\n /** The days of each level for one unit of money: `perUnit` divided by `price`. */\n readonly perDollar: Readonly<Record<string, number>>;\n}\n\n/** One input with no rank, and the reason. It has no price, so it has no days for one unit of money. */\nexport interface UnpricedInput {\n readonly id: string;\n readonly kind: SensitivityKind;\n readonly target: string;\n readonly field: string;\n /** The days of each level for one unit of the input. */\n readonly perUnit: Readonly<Record<string, number>>;\n readonly reason: UnpricedReason;\n}\n\n/** The rank of the inputs by the days that they add for one unit of money. */\nexport interface DaysPerDollar {\n readonly case: string;\n readonly at: IsoDate;\n /** The currency of the table. */\n readonly currency: string;\n /** The inputs with a price, in the order of the rank. The first input is the next buy. Refer to `daysPerDollar`. */\n readonly ranked: readonly PricedInput[];\n /** The inputs with no price or with a bad price, in the order of the sensitivity. They have no rank. */\n readonly unpriced: readonly UnpricedInput[];\n /** The keys of the table that are not the key of an input, in the order of their codes. A key with an error shows here. */\n readonly unused: readonly string[];\n}\n\n/** This function gives the days of each level for one unit of an input, in the order of the levels. */\nfunction perUnitOf(input: SensitivityInput, levels: readonly string[]): Record<string, number> {\n const size = Math.abs(input.delta);\n return Object.fromEntries(levels.map((level) => [level, (input.levels[level] ?? 0) / size] as const));\n}\n\n/** This function compares two inputs with a price. It compares the days for one unit of money of each level in order, the largest first, then the key. */\nfunction rankOrder(levels: readonly string[]): (a: PricedInput, b: PricedInput) => number {\n return (a, b) => {\n for (const level of levels) {\n const diff = (b.perDollar[level] ?? 0) - (a.perDollar[level] ?? 0);\n if (diff > 0) return 1;\n if (diff < 0) return -1;\n }\n return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;\n };\n}\n\n/**\n * This function ranks the inputs of a sensitivity by the days that they add for one unit of money.\n * With the price of one unit of each input, the first input of the rank is the next buy.\n *\n * - The function reads the result of `enduranceSensitivity`. It does not calculate the days again.\n * - The days of an input for one unit are the sum of the changes of each level divided by the size of `delta`.\n * Thus a step of 2, or a half step of a low draw, gives the days of 1 unit.\n * - The days for one unit of money are the days for one unit divided by the price of one unit.\n * - The rank is by level, as the rank of the sensitivity. It compares the days for one unit of money of the first level,\n * then of the next level, and so on. The largest value comes first. Two equal inputs go in the order of their keys.\n * - Thus an input that adds days to a higher level comes before each input that adds days only to lower levels. A buy\n * for a lower level does not go before a buy for a higher level, also when it gives more days for its money.\n * - An input with a change of 0 days has 0 days for one unit of money. It stays in the rank, after each input that adds\n * days at its level.\n * - An input with no price in the table has no rank. It goes in `unpriced` with the reason `no-price`. It does not get a price of 0.\n * - A price that is not a finite number more than 0 is a bad price. The input goes in `unpriced` with the reason\n * `bad-price`. The function does not throw, so one bad price of a live table does not stop the rank of the others.\n * A lower draw costs nothing, but the table gives it a price only when a buy lowers it.\n * - `unused` names each key of the table that is not the key of an input.\n *\n * The function is pure.\n *\n * @param sensitivity - The result of `enduranceSensitivity`\n * @param prices - The price of one unit of each input, by the key of the input\n * @param options - The levels of the layer, the most important first\n * @returns The inputs with a price in the order of the rank, the inputs with no rank, and the keys that are not used\n */\nexport function daysPerDollar(sensitivity: Sensitivity, prices: PriceTable, options: DaysPerDollarOptions): DaysPerDollar {\n const { levels } = options;\n const ranked: PricedInput[] = [];\n const unpriced: UnpricedInput[] = [];\n const ids = new Set<string>();\n for (const input of sensitivity.inputs) {\n ids.add(input.id);\n const { id, kind, target, field } = input;\n const perUnit = perUnitOf(input, levels);\n const price = Object.hasOwn(prices.prices, id) ? prices.prices[id] : undefined;\n if (price === undefined) {\n unpriced.push({ id, kind, target, field, perUnit, reason: \"no-price\" });\n continue;\n }\n if (!(price > 0) || !Number.isFinite(price)) {\n unpriced.push({ id, kind, target, field, perUnit, reason: \"bad-price\" });\n continue;\n }\n const perDollar = Object.fromEntries(levels.map((level) => [level, (perUnit[level] ?? 0) / price] as const));\n ranked.push({ id, kind, target, field, price, perUnit, perDollar });\n }\n ranked.sort(rankOrder(levels));\n const unused = Object.keys(prices.prices)\n .filter((key) => !ids.has(key))\n .sort();\n return { case: sensitivity.case, at: sensitivity.at, currency: prices.currency, ranked, unpriced, unused };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8EA,SAAgB,UAAU,OAAuB,UAAoB,SAAsB,OAAqC;CAC9H,MAAM,QAAQ,IAAI,IAAI,MAAM,MAAM,KAAK,SAAS,KAAK,IAAI,CAAC;CAC1D,MAAM,UAAU,MAAM,QAAQ,SAAS,CAAC,MAAM,IAAI,IAAI,CAAC;CACvD,IA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AC;EAC3G,OAAO,KAAK;GAAE;GAAI;GAAM;GAAQ;GAAO;GAAO;GAAS;EAAU,CAAC;CACpE;CACA,OAAO,KAAK,UAAU,MAAM,CAAC;CAC7B,MAAM,SAAS,OAAO,KAAK,OAAO,MAAM,CAAC,CACtC,QAAQ,QAAQ,CAAC,IAAI,IAAI,GAAG,CAAC,CAAC,CAC9B,KAAK;CACR,OAAO;EAAE,MAAM,YAAY;EAAM,IAAI,YAAY;EAAI,UAAU,OAAO;EAAU;EAAQ;EAAU;CAAO;AAC3G"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["inputClosure","buildStep","closureOf","horizonOf","shareOf","rankOrder"],"sources":["../src/fit.ts","../src/calendar.ts","../src/rows.ts","../src/program.ts","../src/supply.ts","../src/seasonal.ts","../src/share.ts","../src/endurance.ts","../src/joint.ts","../src/best.ts","../src/stops.ts","../src/shortfall.ts","../src/sample.ts","../src/sensitivity.ts","../src/buy.ts"],"sourcesContent":["/** The relative tolerance of a take and of a fit. */\nexport const TOLERANCE = 1e-13;\n\n/** One try of a fit: the amount that the stores could not give, out of the amount wanted, and the value of the try. */\nexport interface Try<T> {\n readonly short: number;\n readonly need: number;\n readonly value: T;\n}\n\n/** The result of a fit: the largest amount with no shortfall, and the value of its try. The value is `undefined` when only 0 fits. */\nexport interface Fit<T> {\n readonly x: number;\n readonly value: T | undefined;\n}\n\n/**\n * The count of the tries of `largestFit`, for the tests of the cost. It is not in the public API, and it does not change a result.\n * It is the one side effect of `largestFit` and of the queries that use it.\n */\nexport const fitTries = { count: 0 };\n\n/**\n * This function gives the largest `x` in `[0, most]` at which `attempt` has no shortfall, to the relative tolerance `TOLERANCE`.\n *\n * - A try fits when its shortfall is not more than `TOLERANCE` times its need.\n * - The shortfall must not decrease when `x` increases. A take of a chain of converters gives a shortfall that is linear in parts.\n * - The first try is `most`. After it, each step tries the zero of the line through the last two tries that do not fit.\n * With one try that does not fit, the step tries `x` times the part of the need that the stores gave.\n * - When a step does not halve the interval, the next step is a bisection. Thus a fit takes at most approximately twice the steps of a bisection.\n * - A step on the lower end tries a point just above it, so a correct estimate ends the fit in one more try.\n * - An estimate that fits with a shortfall above 0 is in the band of the tolerance above the zero, so the fit ends there.\n * A bisection step or a probe at the lower end can fit with a shortfall of rounding below the zero. The fit does not end there.\n *\n * @param most - The upper limit of `x`\n * @param attempt - The try at an amount. It must not change its input\n * @returns The largest amount that fits, and the value of its try\n */\nexport function largestFit<T>(most: number, attempt: (x: number) => Try<T>): Fit<T> {\n const fits = (tried: Try<T>): boolean => tried.short <= TOLERANCE * tried.need;\n fitTries.count += 1;\n const first = attempt(most);\n if (fits(first)) return { x: most, value: first.value };\n let low = 0;\n let best: T | undefined;\n let high = most;\n let highShort = first.short;\n let highNeed = first.need;\n let before: { readonly x: number; readonly short: number } | undefined;\n let bisect = false;\n for (let step = 0; step < 400 && high - low > 4 * TOLERANCE * high; step += 1) {\n const width = high - low;\n let x: number;\n if (bisect) x = (low + high) / 2;\n else if (before !== undefined && before.short > highShort) x = high - (highShort * (before.x - high)) / (before.short - highShort);\n else x = high * (1 - highShort / highNeed);\n // Only a secant or ratio estimate through tries that do not fit lands at or above the zero of a convex shortfall.\n const estimate = !bisect && x < high;\n if (!(x < high)) x = (low + high) / 2;\n const floor = low + 2 * TOLERANCE * high;\n const clamped = !(x > floor);\n if (clamped) x = floor;\n fitTries.count += 1;\n const tried = attempt(x);\n if (fits(tried)) {\n low = x;\n best = tried.value;\n // An estimate that fits with a shortfall is in the band of the tolerance above the zero, so the fit ends.\n if (tried.short > 0 && estimate && !clamped) break;\n } else {\n before = { x: high, short: highShort };\n high = x;\n highShort = tried.short;\n highNeed = tried.need;\n }\n bisect = !bisect && high - low > width / 2;\n }\n return { x: low, value: best };\n}\n","import { dayNumber } from \"@mark1russell7/system-stack\";\nimport type { IsoDate } from \"./layer.ts\";\n\n// The days and months of an event. This module is a leaf: it imports no module of the queries.\n\n/** This function gives the day number of a date, or throws a `RangeError` for a date that is not `YYYY-MM-DD`. */\nexport function dayOf(date: IsoDate): number {\n const day = dayNumber(date);\n if (day === undefined) throw new RangeError(`The date \"${date}\" is not a date YYYY-MM-DD.`);\n return day;\n}\n\nconst DAY_MS = 86_400_000;\n\n/** 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. */\nexport function monthOf(start: IsoDate, day: number): number {\n dayOf(start);\n return new Date(Date.parse(`${start}T00:00:00Z`) + Math.floor(day) * DAY_MS).getUTCMonth();\n}\n\n/**\n * This function gives the days from the start to the first day of each month, in increasing order (M2-solar). Each\n * day is more than 0 and less than the horizon. It throws a `RangeError` for a date that is not `YYYY-MM-DD`.\n */\nexport function monthEdges(start: IsoDate, horizon: number): number[] {\n dayOf(start);\n const first = Date.parse(`${start}T00:00:00Z`);\n const date = new Date(first);\n const out: number[] = [];\n for (let month = date.getUTCMonth() + 1; ; month += 1) {\n const day = Math.round((Date.UTC(date.getUTCFullYear(), month, 1) - first) / DAY_MS);\n if (!(day < horizon)) break;\n out.push(day);\n }\n return out;\n}\n","import { add, fromFloat, type Rational, ZERO } from \"@mark1russell7/rational\";\n\n// The internal rows of the linear programs of the queries. The root entry does not give them.\n\n/** A sparse row: the coefficient of each variable, by its index. */\nexport type Row = Map<number, Rational>;\n\n/** This function adds `value` to the coefficient of the variable `index` in `row`. It changes `row`. */\nexport function addTo(row: Row, index: number, value: Rational): void {\n row.set(index, add(row.get(index) ?? ZERO, value));\n}\n\n/** This function gives the dense form of a row: one coefficient for each of `count` variables. */\nexport function dense(row: Row, count: number): Rational[] {\n const out = new Array<Rational>(count).fill(ZERO);\n for (const [index, value] of row) out[index] = value;\n return out;\n}\n\n/** This function gives the exact rational of a finite double, with no rounding. A double is a dyadic rational. */\nexport function exact(value: number): Rational {\n return fromFloat(value);\n}\n","import type { Constraint } from \"@mark1russell7/linear\";\nimport { add, div, mul, neg, ONE, type Rational, ZERO } from \"@mark1russell7/rational\";\nimport { canRun, deviceKey, giftNeed, giftResource, inputsOf } from \"./converter.ts\";\nimport type { Converter, DirectUse, Draw, EnduranceLayer } from \"./layer.ts\";\nimport { addTo, dense, exact, type Row } from \"./rows.ts\";\n\n// The internal parts of the linear programs over the totals of a span: the parts of a case, the columns and rows of each draw,\n// and the device-days of the converters. The joint days and the best endurance use them. The root entry does not give them.\n\n/** One constraint row of a program, in its sparse form. */\nexport interface RowSpec {\n readonly row: Row;\n readonly relation: Constraint[\"relation\"];\n readonly rhs: Rational;\n}\n\n/** A program in construction: the count of its variables and its rows. */\nexport class Program {\n count = 0;\n readonly rows: RowSpec[] = [];\n\n /** This method adds a variable and gives its index. */\n next(): number {\n return this.count++;\n }\n\n /** This method adds a row and gives its index. */\n push(row: Row, relation: Constraint[\"relation\"], rhs: Rational): number {\n this.rows.push({ row, relation, rhs });\n return this.rows.length - 1;\n }\n\n /** This method gives the dense rows for `solveLexicographic`. */\n constraints(): Constraint[] {\n return this.rows.map(({ row, relation, rhs }) => ({ coefficients: dense(row, this.count), relation, rhs }));\n }\n}\n\n/** The parts of a case that the programs use. */\nexport interface CaseParts {\n /** The stock of each resource at the date of the query (`storeAmounts`). */\n readonly stock: ReadonlyMap<string, number>;\n /** The direct uses of the needs of the program, with an amount more than 0. */\n readonly direct: readonly DirectUse[];\n /** The converters that can run and give a need of the program. */\n readonly cooks: readonly Converter[];\n /** The converters that can run and give a resource. */\n readonly makers: readonly Converter[];\n /** Each resource that a direct use or a converter takes, and each resource that a maker gives. */\n readonly resources: ReadonlySet<string>;\n /** The resources of `resources` with a stock more than 0, in the order of their codes. */\n readonly stocked: readonly string[];\n}\n\n/** This function gives the parts of a case for the draws of `needs`. */\nexport function caseParts(layer: EnduranceLayer, stoppedParts: ReadonlySet<string>, stock: ReadonlyMap<string, number>, needs: ReadonlySet<string>): CaseParts {\n const direct = (layer.direct ?? []).filter((use) => needs.has(use.need) && use.amount > 0);\n // A converter with a season gives its resource only at its harvests (`seasonSupply`), thus it is not a cook or a maker of a program.\n const live = (layer.converters ?? []).filter((converter) => converter.season === undefined && canRun(converter, stoppedParts));\n const cooks = live.filter((converter) => needs.has(giftNeed(converter) ?? \"\"));\n const makers = live.filter((converter) => giftResource(converter) !== undefined);\n return partsOf(stock, direct, cooks, makers);\n}\n\n/** This function gives the parts of a case from its stock, its direct uses, its cooks and its makers. */\nexport function partsOf(stock: ReadonlyMap<string, number>, direct: readonly DirectUse[], cooks: readonly Converter[], makers: readonly Converter[]): CaseParts {\n const resources = new Set<string>([...direct.map((use) => use.resource), ...[...cooks, ...makers].flatMap((converter) => [...inputsOf(converter).keys()])]);\n for (const maker of makers) resources.add(giftResource(maker) ?? \"\");\n const stocked = [...resources].filter((resource) => (stock.get(resource) ?? 0) > 0).sort();\n return { stock, direct, cooks, makers, resources, stocked };\n}\n\n/** The columns of one draw in a program. */\nexport interface DrawBlock {\n readonly draw: Draw;\n /** The gifts of the need of the draw from the columns of its direct uses and of its cooks. The caller adds the term of the days. */\n readonly gifts: Row;\n /** The column of the share of each stock, by the code of the resource. It is empty for a draw with no stock. */\n readonly shares: ReadonlyMap<string, number>;\n /** The column of the runs of each converter for the draw: each cook of its need, and each maker. */\n readonly runs: ReadonlyMap<Converter, number>;\n}\n\n/**\n * This function adds the columns of one draw to a program, and the balance row of each of its resources.\n * In a balance row, the takes of the draw are not more than its share of the stock plus the gifts of its makers.\n * The caller adds the row of the need, with the term of the days.\n *\n * A draw has columns and rows only for the resources and the makers that it can use (`reachOf`).\n * 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.\n * This keeps each program small: the programs are dense, so each column of each draw costs a column in each row.\n *\n * @param stocked - False for a draw that takes no stock. Its shares are not columns.\n */\nexport function drawBlock(program: Program, parts: CaseParts, draw: Draw, stocked = true): DrawBlock {\n const gifts: Row = new Map();\n const { closure, reach } = reachOf(parts, new Set([draw.need]));\n const balance = new Map<string, Row>([...closure].map((resource) => [resource, new Map()]));\n const consume = (resource: string, index: number, amount: Rational): void => addTo(balance.get(resource) as Row, index, amount);\n for (const use of parts.direct) {\n if (use.need !== draw.need) continue;\n const index = program.next();\n addTo(gifts, index, exact(use.amount));\n consume(use.resource, index, ONE);\n }\n const runs = new Map<Converter, number>();\n for (const cook of parts.cooks) {\n if (giftNeed(cook) !== draw.need) continue;\n const index = program.next();\n runs.set(cook, index);\n addTo(gifts, index, exact(cook.gives.amount));\n for (const [resource, each] of inputsOf(cook)) consume(resource, index, exact(each));\n }\n for (const maker of parts.makers) {\n if (!reach.has(maker)) continue;\n const index = program.next();\n runs.set(maker, index);\n for (const [resource, each] of inputsOf(maker)) consume(resource, index, exact(each));\n consume(giftResource(maker) as string, index, neg(exact(maker.gives.amount)));\n }\n const shares = new Map(stocked ? parts.stocked.filter((resource) => closure.has(resource)).map((resource) => [resource, program.next()] as const) : []);\n for (const [resource, index] of shares) consume(resource, index, neg(ONE));\n for (const row of balance.values()) if (row.size > 0) program.push(row, \"<=\", ZERO);\n return { draw, gifts, shares, runs };\n}\n\n/** The device-days of a limit: the runs of its converters over `perDay`, the count of its devices, and its converters. */\nexport interface DeviceLimit {\n readonly row: Row;\n readonly devices: number;\n readonly converters: Converter[];\n}\n\n/**\n * This function gives the device-days of each device of a set of run columns, by the key of the device (`deviceKey`).\n * One run uses `1 / perDay` of a day of one device. The converters of one device share one limit. A converter with no device has a limit of its own.\n * A converter with no limit `perDay` is not in the record. The list `stopped` has the columns of the converters with a limit of 0.\n */\nexport function deviceUse(runs: Iterable<readonly [Converter, number]>): { readonly limits: Map<string, DeviceLimit>; readonly stopped: number[] } {\n const limits = new Map<string, DeviceLimit>();\n const stopped: number[] = [];\n for (const [converter, index] of runs) {\n if (converter.perDay === undefined) continue;\n if (!(converter.perDay > 0)) {\n stopped.push(index);\n continue;\n }\n const key = deviceKey(converter);\n const limit: DeviceLimit = limits.get(key) ?? { row: new Map(), devices: converter.devices ?? 1, converters: [] };\n limits.set(key, limit);\n if (!limit.converters.includes(converter)) limit.converters.push(converter);\n addTo(limit.row, index, div(ONE, exact(converter.perDay)));\n }\n return { limits, stopped };\n}\n\n/**\n * This function gives the row of the fewest device-days of a set of run columns: the runs over `perDay`, or the runs with no limit.\n * As an objective, it gives no more runs than the plan uses.\n */\nexport function fewestRow(runs: Iterable<readonly [Converter, number]>): Row {\n const out: Row = new Map();\n for (const [converter, index] of runs) addTo(out, index, converter.perDay !== undefined && converter.perDay > 0 ? div(ONE, exact(converter.perDay)) : ONE);\n return out;\n}\n\n/** This function gives the value of a sparse row at the point `x`. */\nexport function valueAt(row: Row, x: readonly Rational[]): Rational {\n let out = ZERO;\n for (const [index, value] of row) out = add(out, mul(value, x[index] ?? ZERO));\n return out;\n}\n\n/**\n * This function gives each resource that a draw can use: the resources of its direct uses and the inputs of its cooks.\n * It also gives the inputs of their makers, through each chain.\n */\nexport function inputClosure(direct: readonly string[], cooks: readonly Converter[], makers: readonly Converter[]): Set<string> {\n const out = new Set<string>();\n const queue = [...direct, ...cooks.flatMap((cook) => [...inputsOf(cook).keys()])];\n for (let resource = queue.shift(); resource !== undefined; resource = queue.shift()) {\n if (out.has(resource)) continue;\n out.add(resource);\n for (const maker of makers) if (giftResource(maker) === resource) queue.push(...inputsOf(maker).keys());\n }\n return out;\n}\n\n/** This function gives the resources that the draws of `needs` can use, and the converters that they can use. */\nexport function reachOf(parts: CaseParts, needs: ReadonlySet<string>): { readonly closure: Set<string>; readonly reach: Set<Converter> } {\n const cooks = parts.cooks.filter((cook) => needs.has(giftNeed(cook) ?? \"\"));\n const closure = inputClosure(parts.direct.filter((use) => needs.has(use.need)).map((use) => use.resource), cooks, parts.makers);\n return { closure, reach: new Set([...cooks, ...parts.makers.filter((maker) => closure.has(giftResource(maker) ?? \"\"))]) };\n}\n","import type { CaseCuts, Draw, Harvest, IsoDate } from \"./layer.ts\";\n\n// The demand of a draw and the supply records of a case with a season. This module is a leaf: it imports no module of the queries.\n\n/** This function gives the amount of a need for each day in a case: the rate of the draw times the factor of the case. */\nexport function drawDemand(draw: Draw, caseCuts: CaseCuts): number {\n return draw.perDay * (caseCuts.factors?.[draw.need] ?? 1);\n}\n\n/** A lot of a harvest that the draws can take: its resource, its day, its spoil day (Infinity for none) and its amount. */\nexport interface HarvestLot {\n readonly resource: string;\n readonly day: number;\n readonly spoils: number;\n readonly amount: number;\n}\n\n/** The supply of a case with a season: the stocks after the sowings, the sowings, and the lots of the harvests before the horizon. */\nexport interface SeasonSupply {\n /** The stock of each resource of the stores at `at`, less the inputs of the sowings. */\n readonly stock: Map<string, number>;\n readonly harvests: Harvest[];\n /** The rest of each harvest after the later sowings, in the order of its day. Each lot has a day before the horizon and an amount more than 0. */\n readonly lots: readonly HarvestLot[];\n /** The horizon in days (`horizon` of the options, default `SEASON_HORIZON_DAYS`). */\n readonly horizon: number;\n /** The first day of the event (`start` of the options, or `at`). The shares `monthly` read the month of each day from it (M2-solar). */\n readonly start: IsoDate;\n}\n","import { type Objective, solveLexicographic } from \"@mark1russell7/linear\";\nimport { add, div, equals, mul, neg, ONE, type Rational, sign, sub, toNumber, ZERO } from \"@mark1russell7/rational\";\nimport { monthEdges, monthOf } from \"./calendar.ts\";\nimport { deviceKey, giftResource, isSource, monthlyShares, shareOf } from \"./converter.ts\";\nimport { drawDemand, type HarvestLot, type SeasonSupply } from \"./supply.ts\";\nimport type { CaseCuts, Converter, Draw, DrawEndurance, EnduranceLayer, IsoDate } from \"./layer.ts\";\nimport { type CaseParts, caseParts, deviceUse, drawBlock, type DrawBlock, fewestRow, partsOf, Program, reachOf, valueAt } from \"./program.ts\";\nimport { addTo, dense, exact, type Row } from \"./rows.ts\";\n\n// The linear programs of a case with a season (M2-grow-share): the best endurance and the joint days with harvests.\n// The days go in segments. A segment ends at each harvest day, at each spoil day and at the horizon. In a segment,\n// no lot comes and no lot spoils, so the programs over the totals of a segment are exact. The root entry does not give them.\n// With shares `monthly` (M2-solar), a segment also ends at the start of each month, so the device-days of a segment are exact too.\n\n/** A lot of the programs: a store (day 0, no spoil day) or the rest of a harvest after the sowings. */\nexport interface PlanLot {\n readonly resource: string;\n readonly day: number;\n readonly spoils: number;\n readonly amount: Rational;\n /** The index of a harvest lot in the lots of the supply (`SeasonSupply.lots`). A store lot has none. */\n readonly origin?: number;\n}\n\n/** The parts of the programs of a case with a season. */\nexport interface SeasonPlan {\n /** The parts of the case. The stock of each resource is the stores after the sowings plus the harvests. */\n readonly parts: CaseParts;\n readonly caseCuts: CaseCuts;\n /** The draws whose supply stops, in the order of `caseDraws`. */\n readonly draws: readonly Draw[];\n /** The count of devices of each key. */\n readonly devices: ReadonlyMap<string, number>;\n readonly lots: readonly PlanLot[];\n /** The ends of the segments: 0, each harvest day and each spoil day in the horizon, and the horizon. With shares, also the start of each month. */\n readonly edges: readonly number[];\n /** The shares `monthly` of each device key (M2-solar). A key with no shares has the share 1 in each month. */\n readonly shares: ReadonlyMap<string, readonly number[]>;\n /** The month of each segment, 0 for January. */\n readonly months: readonly number[];\n /** The stores with a capacity that a source charges (M2-solar-charge), in the order of their resources. */\n readonly charges: readonly PlanCharge[];\n}\n\n/** A resource whose stores have a capacity, with the sources that charge it (M2-solar-charge). */\nexport interface PlanCharge {\n readonly resource: string;\n /** The sum of the capacities of the stores of the resource. */\n readonly capacity: Rational;\n /** The lot of the stores of the resource. Its amount is the level on day 0, and it can be 0. */\n readonly lot: PlanLot;\n /** The sources that give the resource: converters with a limit `perDay` and no inputs. */\n readonly sources: readonly Converter[];\n /** The right side of the takes of each segment (M2-solar-charge-sweep). The takes can be this much more than the level that the plan adds before the segment. */\n readonly take: readonly Rational[];\n /** The right side of the charge of each segment: the most that it can be, plus the level that the plan adds before it. */\n readonly fill: readonly Rational[];\n /** True if the higher draws of the sweep give the rest. Then two more rows keep the takes and the charges of the higher draws possible after the last cell. */\n readonly higher: boolean;\n}\n\n/**\n * The rest of a store with a capacity that the higher draws of the sweep of `enduranceOf` leave in a span of days (M2-solar-charge-sweep).\n * The takes of a lower draw in the span can be `take` more than the level that the lower draw adds before the span.\n * The charge of a lower draw in the span can be `fill` less that level.\n */\nexport interface ChargeRest {\n readonly from: number;\n readonly to: number;\n /** The level at the start of the span, less the takes of the higher draws in the span. */\n readonly take: Rational;\n /** The capacity, less the level at the start of the span and the charges of the higher draws in the span. */\n readonly fill: Rational;\n}\n\n/** This function gives the least of a list of rationals, or `none` for an empty list. */\nfunction leastOf(values: readonly Rational[], none: Rational): Rational {\n let low: Rational | undefined;\n for (const value of values) if (low === undefined || sign(sub(value, low)) < 0) low = value;\n return low ?? none;\n}\n\n/**\n * This function gives the capacity of each resource whose stores have a capacity (M2-solar-charge). A store whose part is\n * in `stoppedParts` has no capacity. A store with a due date has no charge: the gate refuses a capacity with a due date.\n */\nexport function storeCapacities(layer: EnduranceLayer, stoppedParts: ReadonlySet<string>): Map<string, number> {\n const out = new Map<string, number>();\n for (const store of layer.stores) {\n if (store.capacity === undefined || store.due !== undefined) continue;\n if (store.part !== undefined && stoppedParts.has(store.part)) continue;\n out.set(store.resource, (out.get(store.resource) ?? 0) + store.capacity);\n }\n return out;\n}\n\n/**\n * This function gives the parts of the programs of a case with a season. `parts` are the parts of the case with the\n * stock after the sowings (`seasonSupply`).\n *\n * @param rests - The rest of each store with a capacity that the higher draws of the sweep leave (M2-solar-charge-sweep).\n * A segment gets the least rest of the spans that it touches. This is the safe side.\n */\nexport function seasonPlan(\n supply: SeasonSupply,\n parts: CaseParts,\n caseCuts: CaseCuts,\n draws: readonly Draw[],\n devices: ReadonlyMap<string, number>,\n capacities: ReadonlyMap<string, number> = new Map(),\n rests: ReadonlyMap<string, readonly ChargeRest[]> = new Map(),\n): SeasonPlan {\n const total = new Map(supply.stock);\n const harvests = supply.lots.map((lot, origin) => ({ ...lot, origin })).filter((lot) => parts.resources.has(lot.resource));\n for (const lot of harvests) total.set(lot.resource, (total.get(lot.resource) ?? 0) + lot.amount);\n const found = partsOf(total, parts.direct, parts.cooks, parts.makers);\n // A store with a capacity that a source charges has a lot, also when it is empty (M2-solar-charge).\n const sourcesOf = (resource: string): Converter[] => found.makers.filter((maker) => isSource(maker) && giftResource(maker) === resource);\n const charged = [...capacities.keys()].filter((resource) => found.resources.has(resource) && sourcesOf(resource).length > 0).sort();\n const all: CaseParts = { ...found, stocked: [...new Set([...found.stocked, ...charged])].sort() };\n const storeLot = (resource: string): PlanLot => ({ resource, day: 0, spoils: Infinity, amount: exact(supply.stock.get(resource) ?? 0) });\n const lots: PlanLot[] = [\n ...all.stocked.filter((resource) => (supply.stock.get(resource) ?? 0) > 0 || charged.includes(resource)).map(storeLot),\n ...harvests.map((lot) => ({ resource: lot.resource, day: Math.max(0, lot.day), spoils: lot.spoils, amount: exact(lot.amount), origin: lot.origin })),\n ];\n const inside = (day: number): boolean => day > 0 && day < supply.horizon;\n const shares = monthlyShares([...all.cooks, ...all.makers]);\n const months = shares.size === 0 ? [] : monthEdges(supply.start, supply.horizon);\n const edges = [...new Set([0, supply.horizon, ...months, ...lots.flatMap((lot) => [lot.day, lot.spoils]).filter(inside)])].sort((a, b) => a - b);\n const charges = charged.map((resource): PlanCharge => {\n const lot = lots.find((item) => item.resource === resource && item.origin === undefined) as PlanLot;\n // The gate keeps the amount within the capacity. The largest of the two keeps the program feasible when it does not.\n const capacity = exact(Math.max(capacities.get(resource) ?? 0, toNumber(lot.amount)));\n const rest = rests.get(resource) ?? [];\n const spans = edges.slice(0, -1).map((from, index) => rest.filter((item) => item.from < (edges[index + 1] ?? Infinity) && item.to > from));\n const take = spans.map((list) => leastOf(list.map((item) => item.take), lot.amount));\n const fill = spans.map((list) => leastOf(list.map((item) => item.fill), sub(capacity, lot.amount)));\n return { resource, capacity, lot, sources: sourcesOf(resource), take, fill, higher: rest.length > 0 };\n });\n const monthOfSegment = edges.slice(0, -1).map((edge) => (shares.size === 0 ? 0 : monthOf(supply.start, edge)));\n return { parts: all, caseCuts, draws, devices, lots, edges, shares, months: monthOfSegment, charges };\n}\n\n/** The first stop of a draw whose days are fixed. */\nexport interface FixedStop {\n /** The days to the first stop. */\n readonly stop: Rational;\n /** The index of the segment of the stop. */\n readonly segment: number;\n /** The device-days of each day that the draw keeps in each segment to its stop. The keys are the index of the segment, then the key of the device. */\n readonly keep: ReadonlyMap<number, ReadonlyMap<string, Rational>>;\n readonly atHorizon: boolean;\n readonly capped: readonly string[];\n}\n\n/** The columns of one draw in one segment. */\ninterface Cell {\n readonly draw: Draw;\n readonly segment: number;\n readonly block: DrawBlock;\n /** The fed days of the cell in its segment: a constant, or the index of a column. */\n readonly fed: Rational | number;\n /** The column of the take of each lot that the cell can take. */\n readonly takes: ReadonlyMap<PlanLot, number>;\n}\n\n/** The device-days of the open cells of one segment for one device. */\ninterface Shared {\n readonly row: Row;\n readonly room: Rational;\n readonly converters: readonly Converter[];\n}\n\n/** A program of one step, with the indexes of its parts. */\ninterface Step {\n readonly program: Program;\n /** The column of the common days of the open draws to their first stop. */\n readonly t: number;\n readonly cells: readonly Cell[];\n /** The row `fed - (t - edge) >= 0` of each open draw in the segment of the stop, by the code of its need. */\n readonly floors: ReadonlyMap<string, number>;\n /** The device-days of the open cells of each segment to the stop, by the index of the segment, then the key of the device. */\n readonly shared: ReadonlyMap<number, ReadonlyMap<string, Shared>>;\n /** The index of the segment of the stop. */\n readonly segment: number;\n /** The charge columns of the step (M2-solar-charge). */\n readonly charges: Charges;\n}\n\nconst edgeOf = (plan: SeasonPlan, index: number): Rational => exact(plan.edges[index] ?? 0);\nconst lengthOf = (plan: SeasonPlan, index: number): Rational => sub(edgeOf(plan, index + 1), edgeOf(plan, index));\nconst segmentsOf = (plan: SeasonPlan): number => plan.edges.length - 1;\n\n/** 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. */\nfunction fixedFed(plan: SeasonPlan, fix: FixedStop, segment: number): Rational {\n if (segment < fix.segment) return lengthOf(plan, segment);\n if (segment === fix.segment) return sub(fix.stop, edgeOf(plan, segment));\n return ZERO;\n}\n\n/**\n * 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.\n * The share of each stock is the sum of the takes of the lots that are ready and not spoiled in the whole segment.\n */\nfunction addCell(program: Program, plan: SeasonPlan, draw: Draw, segment: number, fed: Rational | number): Cell {\n const block = drawBlock(program, plan.parts, draw);\n const demand = exact(drawDemand(draw, plan.caseCuts));\n const need: Row = new Map(block.gifts);\n if (typeof fed === \"number\") {\n addTo(need, fed, neg(demand));\n program.push(need, \">=\", ZERO);\n } else program.push(need, \">=\", mul(demand, fed));\n const from = plan.edges[segment] ?? 0;\n const to = plan.edges[segment + 1] ?? Infinity;\n const takes = new Map<PlanLot, number>();\n for (const [resource, share] of block.shares) {\n const row: Row = new Map([[share, ONE]]);\n for (const lot of plan.lots) {\n if (lot.resource !== resource || lot.day > from || lot.spoils < to) continue;\n const column = program.next();\n takes.set(lot, column);\n addTo(row, column, neg(ONE));\n }\n program.push(row, \"=\", ZERO);\n }\n return { draw, segment, block, fed, takes };\n}\n\n/** 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. */\nfunction lotRows(program: Program, plan: SeasonPlan, cells: readonly Cell[]): void {\n const charged = new Set(plan.charges.map((charge) => charge.lot));\n for (const lot of plan.lots) {\n if (charged.has(lot)) continue;\n const row: Row = new Map();\n for (const cell of cells) {\n const column = cell.takes.get(lot);\n if (column !== undefined) addTo(row, column, ONE);\n }\n if (row.size > 0) program.push(row, \"<=\", lot.amount);\n }\n}\n\n/** The charge columns of a program (M2-solar-charge). */\ninterface Charges {\n /** The pairs of a source and its charge column in each segment, for the rows of the device-days. */\n readonly pairs: ReadonlyMap<number, readonly (readonly [Converter, number])[]>;\n /** The gift of all the charges of each resource, as a row. */\n readonly gifts: ReadonlyMap<string, Row>;\n /** The gift of the charge of each resource in each segment before `through`, as a row (M2-solar-charge-sweep). */\n readonly segments: ReadonlyMap<string, readonly Row[]>;\n}\n\n/**\n * This function adds the charge of each store with a capacity in the segments before `through` (M2-solar-charge).\n * 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.\n * 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.\n * - The takes of a segment are not more than the level at its start.\n * - The level at the start of a segment plus its charge is not more than the capacity.\n * 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.\n *\n * 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.\n * With higher draws (M2-solar-charge-sweep), the right sides are the rest that they leave (`PlanCharge.take` and `fill`).\n * 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.\n */\nfunction addCharges(program: Program, plan: SeasonPlan, cells: readonly Cell[], through: number): Charges {\n const pairs = new Map<number, [Converter, number][]>();\n const gifts = new Map<string, Row>();\n const segments = new Map<string, Row[]>();\n for (const charge of plan.charges) {\n // The level at the start of the segment that the draws of the plan add.\n const level: Row = new Map();\n const given: Row = new Map();\n const each: Row[] = [];\n gifts.set(charge.resource, given);\n segments.set(charge.resource, each);\n for (let segment = 0; segment < through; segment += 1) {\n const takes: Row = new Map();\n for (const cell of cells) {\n const column = cell.segment === segment ? cell.takes.get(charge.lot) : undefined;\n if (column !== undefined) addTo(takes, column, ONE);\n }\n const most: Row = new Map(takes);\n for (const [column, value] of level) addTo(most, column, neg(value));\n program.push(most, \"<=\", charge.take[segment] ?? charge.lot.amount);\n const full: Row = new Map(level);\n const own: Row = new Map();\n each.push(own);\n if (segment + 1 < through) {\n for (const source of charge.sources) {\n const column = program.next();\n pairs.set(segment, [...(pairs.get(segment) ?? []), [source, column]]);\n const amount = exact(source.gives.amount);\n addTo(full, column, amount);\n addTo(level, column, amount);\n addTo(given, column, amount);\n addTo(own, column, amount);\n }\n program.push(full, \"<=\", charge.fill[segment] ?? sub(charge.capacity, charge.lot.amount));\n } else if (charge.higher) program.push(full, \"<=\", charge.fill[segment] ?? ZERO);\n for (const [column, value] of takes) addTo(level, column, neg(value));\n }\n if (charge.higher && through < segmentsOf(plan)) {\n // After `through`, the plan has no takes and no charge. Its level must keep the takes and the charges of the higher draws possible.\n const less: Row = new Map();\n for (const [column, value] of level) addTo(less, column, neg(value));\n program.push(less, \"<=\", leastOf(charge.take.slice(through), ZERO));\n program.push(new Map(level), \"<=\", leastOf(charge.fill.slice(through), ZERO));\n }\n }\n return { pairs, gifts, segments };\n}\n\n/**\n * This function gives the most charge, the earliest first, as an objective (M2-solar-charge-sweep). The weight of the charge of\n * 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.\n */\nfunction mostCharge(plan: SeasonPlan, charges: Charges, count: number): Objective {\n const most: Row = new Map();\n const horizon = edgeOf(plan, segmentsOf(plan));\n for (const rows of charges.segments.values()) {\n rows.forEach((row, segment) => {\n for (const [column, value] of row) addTo(most, column, mul(value, sub(horizon, edgeOf(plan, segment))));\n });\n }\n return { sense: \"max\", coefficients: dense(most, count) };\n}\n\n/**\n * This function gives the rest of each store with a capacity in each segment (M2-solar-charge-sweep). It is the rest that the\n * 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.\n */\nfunction restsOf(plan: SeasonPlan, cells: readonly Cell[], x: readonly Rational[], charges: Charges): Map<string, ChargeRest[]> {\n const out = new Map<string, ChargeRest[]>();\n for (const charge of plan.charges) {\n const rows = charges.segments.get(charge.resource) ?? [];\n // The level that the draws of the plan add before the segment.\n let added = ZERO;\n const list: ChargeRest[] = [];\n for (let segment = 0; segment < segmentsOf(plan); segment += 1) {\n let taken = ZERO;\n for (const cell of cells) if (cell.segment === segment) taken = add(taken, x[cell.takes.get(charge.lot) ?? -1] ?? ZERO);\n const row = rows[segment];\n const given = row === undefined ? ZERO : valueAt(row, x);\n const take = add(sub(charge.take[segment] ?? charge.lot.amount, taken), added);\n const fill = sub(sub(charge.fill[segment] ?? ZERO, given), added);\n list.push({ from: plan.edges[segment] ?? 0, to: plan.edges[segment + 1] ?? 0, take, fill });\n added = add(added, sub(given, taken));\n }\n out.set(charge.resource, list);\n }\n return out;\n}\n\n/**\n * 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).\n * The value comes before the shares `monthly`. The charge of a segment can come in equal parts on each of its days.\n */\nfunction chargeDaysOf(plan: SeasonPlan, charges: Charges, x: readonly Rational[]): Map<string, number> {\n const out = new Map<string, number>();\n for (const [segment, list] of charges.pairs) {\n const length = toNumber(lengthOf(plan, segment));\n if (!(length > 0)) continue;\n for (const [key, limit] of deviceUse(list).limits) {\n const share = shareIn(plan, segment, key);\n if (share > 0) out.set(key, Math.max(out.get(key) ?? 0, toNumber(valueAt(limit.row, x)) / length / share));\n }\n }\n return out;\n}\n\n/**\n * 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\n * 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.\n */\nfunction addFixed(program: Program, plan: SeasonPlan, fixed: ReadonlyMap<string, FixedStop>, cells: Cell[]): Map<number, Map<string, Rational>> {\n const kept = new Map<number, Map<string, Rational>>();\n for (const draw of plan.draws) {\n const fix = fixed.get(draw.need);\n if (fix === undefined) continue;\n for (let segment = 0; segment <= fix.segment; segment += 1) {\n const fed = fixedFed(plan, fix, segment);\n const keep = fix.keep.get(segment) ?? new Map<string, Rational>();\n // The draw keeps its device-days of each day for the whole segment. This is the safe side, as in `bestEndurance`.\n const into = kept.get(segment) ?? new Map<string, Rational>();\n kept.set(segment, into);\n for (const [key, value] of keep) into.set(key, add(into.get(key) ?? ZERO, value));\n if (sign(fed) <= 0) continue;\n const cell = addCell(program, plan, draw, segment, fed);\n cells.push(cell);\n const { limits, stopped } = deviceUse(cell.block.runs);\n for (const index of stopped) program.push(new Map([[index, ONE]]), \"<=\", ZERO);\n for (const [key, limit] of limits) program.push(limit.row, \"<=\", mul(keep.get(key) ?? ZERO, fed));\n }\n }\n return kept;\n}\n\n/** 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. */\nfunction shareIn(plan: SeasonPlan, segment: number, key: string): number {\n return shareOf(plan.shares, key, plan.months[segment] ?? 0);\n}\n\n/** 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. */\nfunction roomOf(plan: SeasonPlan, kept: ReadonlyMap<number, ReadonlyMap<string, Rational>>, segment: number, key: string, devices: number): Rational {\n const left = sub(mul(exact(plan.devices.get(key) ?? devices), exact(shareIn(plan, segment, key))), kept.get(segment)?.get(key) ?? ZERO);\n return sign(left) > 0 ? left : ZERO;\n}\n\n/**\n * This function gives the program of one step with the stop of the open draws in segment `segment`. The open draws are fed in\n * each segment before it. In it, each one is fed for `t - edge` days or more, and their runs share the device-days that\n * the fixed draws leave, for `t - edge` days. This is the safe side, as in `bestEndurance`.\n */\nfunction buildStep(plan: SeasonPlan, fixed: ReadonlyMap<string, FixedStop>, open: readonly Draw[], segment: number): Step {\n const program = new Program();\n const t = program.next();\n program.push(new Map([[t, ONE]]), \"<=\", edgeOf(plan, segment + 1));\n const cells: Cell[] = [];\n const kept = addFixed(program, plan, fixed, cells);\n const opened = new Set(open.map((draw) => draw.need));\n const floors = new Map<string, number>();\n for (const draw of plan.draws) {\n if (!opened.has(draw.need)) continue;\n for (let index = 0; index < segment; index += 1) cells.push(addCell(program, plan, draw, index, lengthOf(plan, index)));\n const fed = program.next();\n program.push(new Map([[fed, ONE]]), \"<=\", lengthOf(plan, segment));\n floors.set(draw.need, program.push(new Map([[fed, ONE], [t, neg(ONE)]]), \">=\", neg(edgeOf(plan, segment))));\n cells.push(addCell(program, plan, draw, segment, fed));\n }\n const charges = addCharges(program, plan, cells, segment + 1);\n const shared = new Map<number, Map<string, Shared>>();\n for (let index = 0; index <= segment; index += 1) {\n const runs = cells.filter((cell) => cell.segment === index && opened.has(cell.draw.need)).flatMap((cell) => [...cell.block.runs]);\n const { limits, stopped } = deviceUse([...runs, ...(charges.pairs.get(index) ?? [])]);\n for (const column of stopped) program.push(new Map([[column, ONE]]), \"<=\", ZERO);\n const bySegment = new Map<string, Shared>();\n shared.set(index, bySegment);\n for (const [key, limit] of limits) {\n const room = roomOf(plan, kept, index, key, limit.devices);\n bySegment.set(key, { row: limit.row, room, converters: limit.converters });\n const row: Row = new Map(limit.row);\n if (index < segment) program.push(row, \"<=\", mul(room, lengthOf(plan, index)));\n else {\n addTo(row, t, neg(room));\n program.push(row, \"<=\", neg(mul(room, edgeOf(plan, segment))));\n }\n }\n }\n lotRows(program, plan, cells);\n return { program, t, cells, floors, shared, segment, charges };\n}\n\n/** The first stop of a set of open draws: the step, its solution and the days. */\nexport interface Stop {\n readonly step: Step;\n readonly x: readonly Rational[];\n /** The dual value of each row of the first objective. */\n readonly dual: readonly Rational[];\n readonly days: Rational;\n readonly atHorizon: boolean;\n}\n\n/**\n * This function gives the largest common first stop of the open draws, with the fixed draws at their stops. The days to\n * a first stop are not a linear function of the takes, so the function tries the segments in order. When the days reach\n * the end of a segment, it tries the next segment. The days of the last step are exact.\n * After the largest days, the step takes the objectives of `tail`.\n */\nexport function firstStop(plan: SeasonPlan, fixed: ReadonlyMap<string, FixedStop>, open: readonly Draw[], tail: (step: Step) => Objective[] = () => []): Stop {\n const segments = segmentsOf(plan);\n for (let segment = 0; segment < segments; segment += 1) {\n const step = buildStep(plan, fixed, open, segment);\n const most: Objective = { sense: \"max\", coefficients: dense(new Map([[step.t, ONE]]), step.program.count) };\n const solved = solveLexicographic(step.program.constraints(), [most]);\n 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.\");\n const days = solved.values[0] ?? ZERO;\n const end = edgeOf(plan, segment + 1);\n if (segment + 1 < segments && equals(days, end)) continue;\n // The later objectives keep the days of the first objective as a row. This is the row that solveLexicographic adds, thus\n // the program does not solve the first objective again (M2-sweep-speed).\n // With two later objectives, the second one starts from the optimal basis of the first one (M2-linear-warm-start).\n const later = tail(step);\n const full = later.length === 0 ? solved : solveLexicographic([...step.program.constraints(), { coefficients: most.coefficients, relation: \"=\", rhs: days }], later, { warm: true });\n if (full.status !== \"optimal\") throw new Error(\"The step of a season has no optimum for its later objectives.\");\n const first = solved.stages[0]?.result;\n return { step, x: full.x, dual: first?.status === \"optimal\" ? first.dual : [], days, atHorizon: segment + 1 === segments && equals(days, end) };\n }\n throw new Error(\"A season plan has no segment.\");\n}\n\n/** This function gives the fewest device-days of the runs of the open cells of a step, as an objective. */\nexport function fewestOpen(step: Step, open: ReadonlySet<string>): Objective {\n return { sense: \"min\", coefficients: dense(fewestRow(step.cells.filter((cell) => open.has(cell.draw.need)).flatMap((cell) => [...cell.block.runs])), step.program.count) };\n}\n\n/** This function gives the smallest sum of the shares of the stocks, each over the total of its lots, as an objective. */\nexport function leastShares(plan: SeasonPlan, cells: readonly Cell[], count: number): Objective {\n const least: Row = new Map();\n // The stock of an empty store with a charge is 0 (M2-solar-charge). Its weight is 1.\n const weight = (resource: string): Rational => div(ONE, exact((plan.parts.stock.get(resource) ?? 0) > 0 ? (plan.parts.stock.get(resource) as number) : 1));\n for (const cell of cells) for (const [resource, index] of cell.block.shares) addTo(least, index, weight(resource));\n return { sense: \"min\", coefficients: dense(least, count) };\n}\n\n/** This function fixes the open draws of `done` at the stop: the device-days of each day that they keep, and their capped converters. */\nexport function fixStops(plan: SeasonPlan, stop: Stop, done: readonly Draw[], fixed: Map<string, FixedStop>): void {\n const { step, x, days } = stop;\n const fedIn = (segment: number): Rational => (segment < step.segment ? lengthOf(plan, segment) : sub(days, edgeOf(plan, step.segment)));\n const full = new Set<string>();\n for (const [segment, bySegment] of step.shared) {\n for (const [key, limit] of bySegment) if (equals(valueAt(limit.row, x), mul(limit.room, fedIn(segment)))) full.add(`${String(segment)}\\u0000${key}`);\n }\n for (const draw of done) {\n const keep = new Map<number, Map<string, Rational>>();\n const used = new Set<Converter>();\n for (const cell of step.cells) {\n if (cell.draw.need !== draw.need) continue;\n const fed = fedIn(cell.segment);\n const bySegment = new Map<string, Rational>();\n keep.set(cell.segment, bySegment);\n for (const [key, limit] of deviceUse(cell.block.runs).limits) {\n bySegment.set(key, sign(fed) > 0 ? div(valueAt(limit.row, x), fed) : ZERO);\n if (full.has(`${String(cell.segment)}\\u0000${key}`)) for (const converter of limit.converters) used.add(converter);\n }\n }\n const { reach } = reachOf(plan.parts, new Set([draw.need]));\n const capped = sign(days) > 0 && !stop.atHorizon\n ? [...reach].filter((converter) => converter.perDay !== undefined && (!(converter.perDay > 0) || used.has(converter))).map((converter) => converter.id).sort()\n : [];\n fixed.set(draw.need, { stop: days, segment: step.segment, keep, atHorizon: stop.atHorizon, capped });\n }\n}\n\n/** This function gives the sum of the take of each resource of the cells of one need, more than 0 only. */\nfunction takesOf(cells: readonly Cell[], need: string, x: readonly Rational[]): Record<string, number> {\n const sums = new Map<string, Rational>();\n for (const cell of cells) {\n if (cell.draw.need !== need) continue;\n for (const [resource, index] of cell.block.shares) sums.set(resource, add(sums.get(resource) ?? ZERO, x[index] ?? ZERO));\n }\n const out: Record<string, number> = {};\n for (const [resource, value] of [...sums].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) if (sign(value) > 0) out[resource] = toNumber(value);\n return out;\n}\n\n/** 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. */\nexport function usedUp(plan: SeasonPlan, cells: readonly Cell[], x: readonly Rational[], closure: ReadonlySet<string>, stored: ReadonlySet<string>, charges?: Charges): string[] {\n return [...closure]\n .filter((resource) => stored.has(resource))\n .filter((resource) => {\n let taken = ZERO;\n // The charges of a store with a capacity add to its lots (M2-solar-charge).\n const given = charges?.gifts.get(resource);\n let amount = given === undefined ? ZERO : valueAt(given, x);\n for (const lot of plan.lots) {\n if (lot.resource !== resource) continue;\n amount = add(amount, lot.amount);\n for (const cell of cells) taken = add(taken, x[cell.takes.get(lot) ?? -1] ?? ZERO);\n }\n return equals(taken, amount);\n })\n .sort();\n}\n\n/** This function tells if the cells of two draws or more of `cells` can use the limited device `key`. */\nfunction sharedKey(cells: readonly Cell[], key: string): boolean {\n return new Set(cells.filter((cell) => deviceUse(cell.block.runs).limits.has(key)).map((cell) => cell.draw.need)).size > 1;\n}\n\n/** The result of the last program of the best endurance with a season. */\nexport interface SeasonBest {\n readonly needs: Record<string, DrawEndurance>;\n /** The take of each lot by all the draws. */\n readonly taken: ReadonlyMap<PlanLot, number>;\n /** The most device-days of one day that each draw uses while it is fed, by the code of its need, then the key of the device. */\n readonly perDay: ReadonlyMap<string, ReadonlyMap<string, number>>;\n /** With `fill`, the rest of each store with a capacity that the plan leaves in each segment (M2-solar-charge-sweep). */\n readonly rests?: ReadonlyMap<string, readonly ChargeRest[]> | undefined;\n /** With `fill`, the most device-days of one day that the charges use, by the key of the device, before the shares `monthly`. */\n readonly chargeDays?: ReadonlyMap<string, number> | undefined;\n}\n\n/**\n * This function gives the last program of the best endurance with a season. Each draw keeps its first stop. After it, a later\n * harvest can feed the draw again (`again`). The objectives come in this order:\n * - the most fed days after the stops for each level, in the order of the levels.\n * - the earliest fed days.\n * - the smallest sum of the shares of the stocks.\n * - the fewest device-days.\n *\n * In a segment after the stops, the cells of two draws or more that can use one limited device take turns. Their fed days\n * together are not more than the segment, and each one has the device-days of each day that the stops leave. This is the\n * safe side: the cells do not use one device at the same time. Each other cell starts at the start of the segment.\n *\n * @param fill - True for the sweep of `enduranceOf` (M2-solar-charge-sweep). Then the last objective is the most charge, the\n * earliest first, and the result gives the rest of each store with a capacity. A store with a capacity is binding if the\n * takes of the segment of the stop use all the level at its start.\n */\nexport function seasonBest(plan: SeasonPlan, fixed: ReadonlyMap<string, FixedStop>, levels: readonly (readonly Draw[])[], stored: ReadonlySet<string>, fill = false): SeasonBest {\n const program = new Program();\n const cells: Cell[] = [];\n const kept = addFixed(program, plan, fixed, cells);\n const segments = segmentsOf(plan);\n const again = new Map<Cell, number>();\n // The cells that take turns in their segment.\n const taking = new Set<Cell>();\n for (const draw of plan.draws) {\n const fix = fixed.get(draw.need) as FixedStop;\n for (let segment = fix.segment + 1; segment < segments; segment += 1) {\n const fed = program.next();\n program.push(new Map([[fed, ONE]]), \"<=\", lengthOf(plan, segment));\n const cell = addCell(program, plan, draw, segment, fed);\n cells.push(cell);\n again.set(cell, fed);\n }\n }\n for (let segment = 0; segment < segments; segment += 1) {\n const later = [...again.keys()].filter((cell) => cell.segment === segment);\n const { limits, stopped } = deviceUse(later.flatMap((cell) => [...cell.block.runs]));\n for (const column of stopped) program.push(new Map([[column, ONE]]), \"<=\", ZERO);\n const turns = new Set(later.filter((cell) => [...deviceUse(cell.block.runs).limits.keys()].some((key) => sharedKey(later, key))));\n if (turns.size > 0) {\n const row: Row = new Map();\n for (const cell of turns) addTo(row, again.get(cell) as number, ONE);\n program.push(row, \"<=\", lengthOf(plan, segment));\n for (const cell of turns) taking.add(cell);\n }\n for (const [key, limit] of limits) {\n const room = roomOf(plan, kept, segment, key, limit.devices);\n for (const cell of later) {\n const own = deviceUse(cell.block.runs).limits.get(key);\n if (own === undefined) continue;\n const row: Row = new Map(own.row);\n addTo(row, again.get(cell) as number, neg(room));\n program.push(row, \"<=\", ZERO);\n }\n }\n }\n // The charge of each segment uses the device-days that the cells after the stops leave (M2-solar-charge).\n const charges = addCharges(program, plan, cells, segments);\n for (const [segment, list] of charges.pairs) {\n const later = [...again.keys()].filter((cell) => cell.segment === segment);\n const { limits } = deviceUse([...later.flatMap((cell) => [...cell.block.runs]), ...list]);\n const keys = new Set(list.map(([source]) => deviceKey(source)));\n 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)));\n }\n lotRows(program, plan, cells);\n const objectives: Objective[] = levels.map((level) => {\n const needs = new Set(level.map((draw) => draw.need));\n const row: Row = new Map();\n for (const [cell, fed] of again) if (needs.has(cell.draw.need)) addTo(row, fed, ONE);\n return { sense: \"max\", coefficients: dense(row, program.count) };\n });\n // After the fed days of each level, the fed days come as early as they can: the weight of a segment is the days from its start to the horizon.\n const early: Row = new Map();\n const horizon = edgeOf(plan, segments);\n for (const [cell, fed] of again) addTo(early, fed, sub(horizon, edgeOf(plan, cell.segment)));\n objectives.push({ sense: \"max\", coefficients: dense(early, program.count) });\n objectives.push(leastShares(plan, cells, program.count));\n objectives.push({ sense: \"min\", coefficients: dense(fewestRow(cells.flatMap((cell) => [...cell.block.runs])), program.count) });\n if (fill) objectives.push(mostCharge(plan, charges, program.count));\n // Each later stage starts from the optimal basis of the stage before it (M2-linear-warm-start). This program has the most stages.\n const solved = solveLexicographic(program.constraints(), objectives, { warm: true });\n 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.\");\n const x = solved.x;\n const rests = fill ? restsOf(plan, cells, x, charges) : undefined;\n // In the sweep, a store with a capacity is binding if the takes of the segment of the stop use all the level at its start.\n const charged = new Set(plan.charges.map((charge) => charge.resource));\n const bound = (closure: ReadonlySet<string>, segment: number): string[] => {\n const used = usedUp(plan, cells, x, closure, stored, charges);\n if (rests === undefined) return used;\n const empty = [...charged].filter((resource) => closure.has(resource) && stored.has(resource) && sign(rests.get(resource)?.[segment]?.take ?? ONE) <= 0);\n return [...used.filter((resource) => !charged.has(resource)), ...empty].sort();\n };\n // The start of the turn of each cell that takes turns: after the turns of the cells of the draws before it.\n const turn = new Map<Cell, Rational>();\n const offset = new Map<number, Rational>();\n for (const cell of [...taking].sort((a, b) => plan.draws.indexOf(a.draw) - plan.draws.indexOf(b.draw))) {\n const start = offset.get(cell.segment) ?? ZERO;\n turn.set(cell, start);\n offset.set(cell.segment, add(start, x[again.get(cell) as number] ?? ZERO));\n }\n const needs: Record<string, DrawEndurance> = {};\n for (const draw of plan.draws) {\n const fix = fixed.get(draw.need) as FixedStop;\n const spans: { from: number; to: number }[] = [];\n for (const [cell, fed] of again) {\n if (cell.draw.need !== draw.need) continue;\n const value = x[fed] ?? ZERO;\n if (sign(value) <= 0) continue;\n const start = add(edgeOf(plan, cell.segment), taking.has(cell) ? (turn.get(cell) ?? ZERO) : ZERO);\n const from = toNumber(start);\n const to = toNumber(add(start, value));\n const last = spans[spans.length - 1];\n if (last !== undefined && last.to === from) last.to = to;\n else spans.push({ from, to });\n }\n const { closure } = reachOf(plan.parts, new Set([draw.need]));\n needs[draw.need] = {\n days: toNumber(fix.stop),\n binding: fix.atHorizon ? [] : bound(closure, fix.segment),\n takes: takesOf(cells, draw.need, x),\n ...(fix.capped.length === 0 ? {} : { capped: fix.capped }),\n ...(fix.atHorizon ? { atHorizon: true as const } : {}),\n ...(spans.length === 0 ? {} : { again: spans }),\n };\n }\n const taken = new Map<PlanLot, number>();\n for (const lot of plan.lots) {\n let sum = ZERO;\n for (const cell of cells) sum = add(sum, x[cell.takes.get(lot) ?? -1] ?? ZERO);\n taken.set(lot, toNumber(sum));\n }\n const perDay = new Map<string, Map<string, number>>();\n for (const cell of cells) {\n const fed = typeof cell.fed === \"number\" ? (x[cell.fed] ?? ZERO) : cell.fed;\n if (sign(fed) <= 0) continue;\n const into = perDay.get(cell.draw.need) ?? new Map<string, number>();\n perDay.set(cell.draw.need, into);\n // The use of a segment counts as its part of the share of the segment, as in `enduranceOf` (M2-solar).\n for (const [key, limit] of deviceUse(cell.block.runs).limits) {\n const share = shareIn(plan, cell.segment, key);\n if (share > 0) into.set(key, Math.max(into.get(key) ?? 0, toNumber(div(valueAt(limit.row, x), fed)) / share));\n }\n }\n return { needs, taken, perDay, rests, chargeDays: fill ? chargeDaysOf(plan, charges, x) : undefined };\n}\n\n/** The joint days of a set of draws with a season, before the change to the record of `jointDays`. */\nexport interface SeasonJoint {\n readonly days: number;\n readonly atHorizon: boolean;\n readonly takes: Record<string, Record<string, number>>;\n readonly binding: string[];\n readonly runs: Record<string, number>;\n readonly capped: string[];\n}\n\n/**\n * This function gives the joint days of the draws of a plan with a season. The objectives come in this order:\n * - the largest common first stop.\n * - the smallest sum of the shares of the stocks.\n * - the fewest device-days.\n */\nexport function seasonJoint(plan: SeasonPlan, stored: ReadonlySet<string>): SeasonJoint {\n const open = new Set(plan.draws.map((draw) => draw.need));\n const stop = firstStop(plan, new Map(), plan.draws, (step) => [leastShares(plan, step.cells, step.program.count), fewestOpen(step, open)]);\n const { step, x } = stop;\n const takes: Record<string, Record<string, number>> = {};\n for (const draw of plan.draws) takes[draw.need] = takesOf(step.cells, draw.need, x);\n const total = new Map<Converter, Rational>();\n 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));\n const runs: Record<string, number> = {};\n 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);\n const fixed = new Map<string, FixedStop>();\n fixStops(plan, stop, plan.draws, fixed);\n const capped = [...new Set([...fixed.values()].flatMap((fix) => fix.capped))].sort();\n return { days: toNumber(stop.days), atHorizon: stop.atHorizon, takes, binding: usedUp(plan, step.cells, x, reachOf(plan.parts, open).closure, stored, step.charges), runs, capped };\n}\n\n/** The endurance of one draw with a season and a shared device, and the supply that it leaves to the lower draws. */\nexport interface SeasonDraw {\n readonly need: DrawEndurance;\n /** The stocks that the draw leaves, by the code of the resource. */\n readonly stock: Map<string, number>;\n /** The rest of each harvest lot of the input, in the same order. */\n readonly lots: number[];\n /** The most device-days of one day that the draw uses while it is fed, by the key of the device. With a charge, it includes the device-days of the charge. */\n readonly perDay: ReadonlyMap<string, number>;\n /** The rest of each store with a capacity that the draw and the higher draws leave (M2-solar-charge-sweep). */\n readonly rests: ReadonlyMap<string, readonly ChargeRest[]>;\n}\n\n/**\n * This function gives the endurance of one draw of `enduranceOf` that reaches two limited converters of one device in a layer\n * with a season (M2-grow-share-sweep). The take order cannot give the share of the device-days.\n * Thus the programs of `bestEndurance` give it for this one draw: the first stop, then the most fed days after it (`again`).\n *\n * 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).\n * - 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.\n * - 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.\n * - 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.\n * - The device-days of the charge are a part of the device-days of the draw (`perDay`). Thus a lower draw cannot use them.\n *\n * @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.\n * @param lots - The rest of each harvest lot that the higher draws leave.\n * @param room - The device-days of each day that the higher draws leave, by the key of the device, before the shares `monthly`.\n * @param start - The first day of the event, for the months of the shares.\n * @param capacities - The capacity of each resource whose stores have a capacity (`storeCapacities`).\n * @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.\n */\nexport function seasonDraw(\n layer: EnduranceLayer,\n stoppedParts: ReadonlySet<string>,\n caseCuts: CaseCuts,\n draw: Draw,\n stock: ReadonlyMap<string, number>,\n lots: readonly HarvestLot[],\n horizon: number,\n room: ReadonlyMap<string, number>,\n start: IsoDate,\n capacities: ReadonlyMap<string, number> = new Map(),\n rests: ReadonlyMap<string, readonly ChargeRest[]> = new Map(),\n): SeasonDraw {\n const supply: SeasonSupply = { stock: new Map(stock), harvests: [], lots, horizon, start };\n const plan = seasonPlan(supply, caseParts(layer, stoppedParts, supply.stock, new Set([draw.need])), caseCuts, [draw], room, capacities, rests);\n const fixed = new Map<string, FixedStop>();\n const open = new Set([draw.need]);\n const filled = plan.charges.length > 0;\n const tail = (step: Step): Objective[] => (filled ? [leastShares(plan, step.cells, step.program.count), fewestOpen(step, open)] : [fewestOpen(step, open)]);\n fixStops(plan, firstStop(plan, fixed, [draw], tail), [draw], fixed);\n const best = seasonBest(plan, fixed, [[draw]], new Set(layer.stores.map((store) => store.resource)), filled);\n const left = new Map(stock);\n const rest = lots.map((lot) => lot.amount);\n // The rest gives the level of a store with a charge to the lower draws, thus its stock does not change.\n const chargedLots = new Set(plan.charges.map((charge) => charge.lot));\n for (const [lot, amount] of best.taken) {\n if (chargedLots.has(lot)) continue;\n if (lot.origin === undefined) left.set(lot.resource, Math.max(0, (left.get(lot.resource) ?? 0) - amount));\n else rest[lot.origin] = Math.max(0, (rest[lot.origin] ?? 0) - amount);\n }\n const perDay = new Map<string, number>(best.perDay.get(draw.need) ?? []);\n for (const [key, each] of best.chargeDays ?? new Map<string, number>()) perDay.set(key, (perDay.get(key) ?? 0) + each);\n return { need: best.needs[draw.need] as DrawEndurance, stock: left, lots: rest, perDay, rests: best.rests ?? new Map<string, readonly ChargeRest[]>() };\n}\n","import { type Objective, solveLexicographic } from \"@mark1russell7/linear\";\nimport { div, neg, ONE, type Rational, sign, toNumber, ZERO } from \"@mark1russell7/rational\";\nimport type { Converter, DirectUse, Draw } from \"./layer.ts\";\nimport { deviceUse, drawBlock, fewestRow, partsOf, Program, valueAt } from \"./program.ts\";\nimport { addTo, dense, exact, type Row } from \"./rows.ts\";\n\n// The best share of one draw: a linear program over the totals of its days, with exact rationals (@mark1russell7/linear).\n// The endurance query uses it for a draw whose converters share the days of a device. The root entry does not give it.\n// The columns and rows come from program.ts, as for the joint days and the best endurance.\n\n/** The input of the best share of one draw. */\nexport interface ShareInput {\n /** The draw. */\n readonly draw: Draw;\n /** The stock of each resource that the draw can take, by the code of the resource. */\n readonly stock: ReadonlyMap<string, number>;\n /** The device-days of each day that the draw can use, by the key of the device (`deviceKey`). */\n readonly room: ReadonlyMap<string, number>;\n /** The direct uses that give the need of the draw. */\n readonly direct: readonly DirectUse[];\n /** The converters that give the need of the draw. */\n readonly converters: readonly Converter[];\n /** The makers that the draw can use: the makers of its inputs, through each chain. */\n readonly makers: readonly Converter[];\n /** The amount of the need for each day. It is more than 0. */\n readonly demand: number;\n}\n\n/** The best share of one draw: its days, the take of each stock and the device-days of each device. */\nexport interface Share {\n /** The largest count of days at which the draw gets its demand. */\n readonly days: number;\n /** The amount of each resource that the draw takes from the stock. A resource with no take is not in the map. */\n readonly taken: ReadonlyMap<string, number>;\n /** The device-days that the runs use in `days`, by the key of the device. A device with no use is not in the map. */\n readonly used: ReadonlyMap<string, number>;\n}\n\n/**\n * This function gives the best share of the stocks and of the device-days for one draw.\n * It gives `undefined` when the program has no optimum.\n *\n * - The variables are the days `T`, the take of each direct use, the runs of each converter and maker, and the take of each stock.\n * - The gifts of the direct uses and of the converters are not less than `T` times the demand.\n * - The takes of each resource are not more than the take of its stock plus the gifts of its makers. The take of a stock is not more than the stock.\n * - The runs of the converters of one device use `room` times `T` device-days or less. One run uses `1 / perDay` of a device-day. A limit of 0 stops the converter.\n * - The first objective takes the largest `T`. The second takes the smallest sum of the takes of the stocks, each over its stock. The third takes the fewest device-days.\n *\n * The gifts at `T` days are a concave function of `T`, and they are 0 at 0. Thus each count of days up to the largest `T` also fits.\n *\n * @param input - The draw, the stocks, the device-days of each day, the ways of the draw and its demand\n * @returns The days, the takes of the stocks and the device-days of each device\n */\nexport function bestShare(input: ShareInput): Share | undefined {\n const parts = partsOf(input.stock, input.direct, input.converters, input.makers);\n const program = new Program();\n const days = program.next();\n const block = drawBlock(program, parts, input.draw);\n // The need: the gifts are not less than the demand times the days.\n const need: Row = new Map(block.gifts);\n addTo(need, days, neg(exact(input.demand)));\n program.push(need, \">=\", ZERO);\n // The take of each stock is not more than the stock.\n for (const [resource, index] of block.shares) program.push(new Map([[index, ONE]]), \"<=\", exact(input.stock.get(resource) ?? 0));\n // The limit of each device: the runs use `room` times `T` device-days or less. The converters of one device share one limit.\n const { limits, stopped } = deviceUse(block.runs);\n for (const index of stopped) program.push(new Map([[index, ONE]]), \"<=\", ZERO);\n for (const [key, limit] of limits) {\n const row: Row = new Map(limit.row);\n addTo(row, days, neg(exact(input.room.get(key) ?? 0)));\n program.push(row, \"<=\", ZERO);\n }\n\n const least: Row = new Map();\n for (const [resource, index] of block.shares) addTo(least, index, div(ONE, exact(input.stock.get(resource) ?? 1)));\n const objectives: Objective[] = [\n { sense: \"max\", coefficients: dense(new Map([[days, ONE]]), program.count) },\n { sense: \"min\", coefficients: dense(least, program.count) },\n { sense: \"min\", coefficients: dense(fewestRow(block.runs), program.count) },\n ];\n // Each later stage starts from the optimal basis of the stage before it (M2-linear-warm-start). The program has one draw.\n const solved = solveLexicographic(program.constraints(), objectives, { warm: true });\n // The point 0 is feasible, and the later objectives are not less than 0. Thus only an unbounded first stage has no optimum.\n if (solved.status !== \"optimal\") return undefined;\n\n const at = (index: number): Rational => solved.x[index] ?? ZERO;\n const taken = new Map<string, number>();\n for (const [resource, index] of block.shares) if (sign(at(index)) > 0) taken.set(resource, toNumber(at(index)));\n const used = new Map<string, number>();\n for (const [key, limit] of limits) {\n const sum = valueAt(limit.row, solved.x);\n if (sign(sum) > 0) used.set(key, toNumber(sum));\n }\n return { days: toNumber(at(days)), taken, used };\n}\n","import { dayNumber, stopped, type Stack } from \"@mark1russell7/system-stack\";\nimport { canRun, deviceKey, giftNeed, giftResource, inputsOf, isSource, monthlyShares, shareOf } from \"./converter.ts\";\nimport { largestFit, type Try } from \"./fit.ts\";\nimport type { CaseCuts, Converter, DirectUse, Draw, DrawEndurance, Endurance, EnduranceLayer, Harvest, IsoDate, Season } from \"./layer.ts\";\nimport { dayOf, monthEdges, monthOf } from \"./calendar.ts\";\nimport { inputClosure as closureOf } from \"./program.ts\";\nimport { type ChargeRest, seasonDraw, storeCapacities } from \"./seasonal.ts\";\nimport { bestShare } from \"./share.ts\";\nimport { drawDemand, type SeasonSupply } from \"./supply.ts\";\n\n// The endurance query: the days that each draw holds when a case stops its supply.\n\n/** The options of the queries of a case. */\nexport interface CaseOptions {\n /** The date of the query. A store whose due date is on this date or before it gives nothing. */\n readonly at: IsoDate;\n /** The base stack. With it, a cut also stops each part that cannot work without a cut part (`stopped` of the core). */\n readonly stack?: Stack | undefined;\n /** The `id` of more parts that are down, with the cuts of the case. */\n readonly down?: readonly string[] | undefined;\n /**\n * The first day of the event, for the sow days of each converter with a season (M2-grow) and the months of the shares\n * `monthly` (M2-solar). The default is `at`. The\n * stores are the stores at `at`. Thus a query can move the event in the year and keep the stores.\n */\n readonly start?: IsoDate | undefined;\n /**\n * The horizon in days, more than 0. A layer with no converter with a season, shares `monthly` or a source does not use\n * it in `enduranceOf`. With such a converter, the query reads the sowings up to the horizon, and a draw holds the horizon at most. The default\n * is `SEASON_HORIZON_DAYS`.\n */\n readonly horizon?: number | undefined;\n}\n\n/** The default horizon of a layer with a converter with a season: 730 days, thus two seasons of each year. */\nexport const SEASON_HORIZON_DAYS = 730;\n\n/**\n * This function gives the `id` of each part that does not work in a case: the cut parts and the parts of `down`.\n * With a stack, it also gives each part that stops.\n */\nexport function caseStopped(caseCuts: CaseCuts, options: Pick<CaseOptions, \"stack\" | \"down\">): Set<string> {\n const down = [...caseCuts.cuts.map((cut) => cut.part), ...(options.down ?? [])];\n const out = new Set(down);\n if (options.stack !== undefined) for (const id of stopped(options.stack, down)) out.add(id);\n return out;\n}\n\n// The rule of a source is in converter.ts, with canRun. The root entry gives it (M2-solar).\nexport { isSource };\n\n// The helpers that program.ts, seasonal.ts and share.ts also use are in leaf modules, so these files do not import endurance.ts. The root entry gives them from here.\nexport { giftNeed, giftResource, monthlyShares, shareOf } from \"./converter.ts\";\nexport { monthEdges, monthOf } from \"./calendar.ts\";\nexport { drawDemand, type HarvestLot, type SeasonSupply } from \"./supply.ts\";\n\n/**\n * This function gives the amount of each resource in the stores at a date, by the code of the resource.\n *\n * - A store gives nothing on its due date and after it.\n * - A store gives nothing when its part is in `stoppedParts`.\n */\nexport function storeAmounts(layer: EnduranceLayer, at: IsoDate, stoppedParts: ReadonlySet<string> = new Set()): Map<string, number> {\n const today = dayOf(at);\n const out = new Map<string, number>();\n for (const store of layer.stores) {\n if (store.due !== undefined && today >= dayOf(store.due)) continue;\n if (store.part !== undefined && stoppedParts.has(store.part)) continue;\n out.set(store.resource, (out.get(store.resource) ?? 0) + store.amount);\n }\n return out;\n}\n\n/**\n * This function gives the draws that take from the stores in a case: each draw whose supply stops, with a demand more than 0.\n * The sequence is by the level (the order of `levels`), then by the code of the need.\n */\nexport function caseDraws(layer: EnduranceLayer, caseCuts: CaseCuts, stoppedParts: ReadonlySet<string>): Draw[] {\n const rank = (level: string): number => {\n const index = layer.levels.indexOf(level);\n return index < 0 ? layer.levels.length : index;\n };\n return layer.draws\n .filter((draw) => stoppedParts.has(draw.supply) && drawDemand(draw, caseCuts) > 0)\n .sort((a, b) => rank(a.level) - rank(b.level) || (a.need < b.need ? -1 : a.need > b.need ? 1 : 0));\n}\n\n/** The converters of a case that make each resource, in the order of the layer, by the code of the resource. */\ntype Makers = ReadonlyMap<string, readonly Converter[]>;\n\nfunction makersOf(layer: EnduranceLayer, stoppedParts: ReadonlySet<string>): Makers {\n const out = new Map<string, Converter[]>();\n for (const converter of layer.converters ?? []) {\n const resource = giftResource(converter);\n // A converter with a season gives its resource only at its harvests, thus it is not a maker of a take.\n if (resource === undefined || converter.season !== undefined || !canRun(converter, stoppedParts)) continue;\n out.set(resource, [...(out.get(resource) ?? []), converter]);\n }\n return out;\n}\n\n/** The ways to get one need in a case: its direct uses, then the converters that give it, in the order of the layer. `makers` make the resources. */\ninterface Ways {\n readonly direct: readonly DirectUse[];\n readonly converters: readonly Converter[];\n readonly makers: Makers;\n /** The converters that are sources (M2-solar), and the other converters, in the order of the layer. A layer with no source has no cost in the take. */\n readonly sources: readonly Converter[];\n readonly others: readonly Converter[];\n /** The sources of `converters` and of the makers. With one of them, the stock gives no limit to a span. */\n readonly open: readonly Converter[];\n}\n\nfunction waysOf(layer: EnduranceLayer, need: string, stoppedParts: ReadonlySet<string>, makers: Makers): Ways {\n const converters = (layer.converters ?? []).filter((converter) => giftNeed(converter) === need && canRun(converter, stoppedParts));\n const sources = converters.filter(isSource);\n return {\n direct: (layer.direct ?? []).filter((use) => use.need === need && use.amount > 0),\n converters,\n makers,\n sources,\n others: sources.length === 0 ? converters : converters.filter((converter) => !isSource(converter)),\n open: [...new Set([...sources, ...[...makers.values()].flat().filter(isSource)])],\n };\n}\n\n// A chain: the resources on the path of a take. A maker does not take a resource of its own path, so a cycle of the layer stops there.\nconst NO_PATH: ReadonlySet<string> = new Set();\n\n// The device-days that are left to the converters with a limit `perDay` are in the map of the resources, under a key that\n// no code of a resource has. Thus each copy of the map in a try copies them too. The converters of one device share one\n// key (`deviceKey`), and a converter with no device has a key of its own. One run of a converter uses `1 / perDay` of a device-day.\nconst RUNS = \"\\u0000runs:\";\n\nfunction runsKey(converter: Converter): string {\n return RUNS + deviceKey(converter);\n}\n\n/** This function gives the device-days that a converter has left in `left`, or undefined with no limit. */\nfunction daysLeft(left: ReadonlyMap<string, number>, converter: Converter): number | undefined {\n return converter.perDay === undefined ? undefined : left.get(runsKey(converter));\n}\n\n/** This function gives the map with no runs left of the converters: a map of the resources only. */\nfunction resourcesOnly(left: ReadonlyMap<string, number>): Map<string, number> {\n return new Map([...left].filter(([key]) => !key.startsWith(RUNS)));\n}\n\n/**\n * This function gives the most of a resource that `left` gives: its stock, and the runs of each maker.\n * It is an upper limit. When two inputs come from one resource, the true amount can be less.\n */\nfunction mostResource(left: ReadonlyMap<string, number>, makers: Makers, resource: string, path: ReadonlySet<string>): number {\n let total = left.get(resource) ?? 0;\n if (path.has(resource)) return total;\n const next = new Set(path).add(resource);\n for (const maker of makers.get(resource) ?? []) total += mostRuns(left, makers, maker, next) * maker.gives.amount;\n return total;\n}\n\n/** This function gives the most runs of a converter that `left` gives. It is an upper limit, as for `mostResource`. */\nfunction mostRuns(left: ReadonlyMap<string, number>, makers: Makers, converter: Converter, path: ReadonlySet<string>): number {\n const limit = daysLeft(left, converter);\n let runs = limit === undefined ? Infinity : limit * (converter.perDay ?? 0);\n for (const [resource, each] of inputsOf(converter)) runs = Math.min(runs, mostResource(left, makers, resource, path) / each);\n return Number.isFinite(runs) ? runs : 0;\n}\n\n/**\n * This function takes an amount of a resource from `left`: the stock first, then the makers in the order of the layer.\n * It changes `left`, and it gives the amount that it could not take.\n */\nfunction takeResource(left: Map<string, number>, makers: Makers, resource: string, amount: number, path: ReadonlySet<string>): number {\n let rest = amount;\n const ways = path.has(resource) ? undefined : makers.get(resource);\n let next: ReadonlySet<string> | undefined;\n // A source gives first: its runs of a day are lost when no draw uses them (M2-solar).\n if (ways !== undefined && ways.some(isSource)) {\n next = new Set(path).add(resource);\n for (const maker of ways) {\n if (rest <= 0) break;\n if (isSource(maker)) rest -= run(left, makers, maker, rest / maker.gives.amount, next) * maker.gives.amount;\n }\n }\n const has = left.get(resource) ?? 0;\n const got = Math.min(Math.max(0, rest), has);\n left.set(resource, has - got);\n rest -= got;\n if (rest <= 0 || ways === undefined) return Math.max(0, rest);\n next ??= new Set(path).add(resource);\n for (const maker of ways) {\n if (rest <= 0) break;\n if (!isSource(maker)) rest -= run(left, makers, maker, rest / maker.gives.amount, next) * maker.gives.amount;\n }\n return Math.max(0, rest);\n}\n\n/**\n * This function runs a converter up to `wanted` times with the resources of `left`, and it gives the count of runs.\n * It changes `left`. When two inputs come from one resource, `largestFit` finds the runs that the resources give.\n */\nfunction run(left: Map<string, number>, makers: Makers, converter: Converter, wanted: number, path: ReadonlySet<string>): number {\n const inputs = inputsOf(converter);\n const most = Math.min(wanted, mostRuns(left, makers, converter, path));\n if (!(most > 0)) return 0;\n const attempt = (runs: number): Try<Map<string, number>> => {\n const copy = new Map(left);\n let need = 0;\n let short = 0;\n // The converter takes its device-days before its inputs. Thus a maker on the same device gets only the rest.\n const limit = daysLeft(copy, converter);\n if (limit !== undefined && converter.perDay !== undefined && converter.perDay > 0) {\n const wanted = runs / converter.perDay;\n const got = Math.min(wanted, limit);\n copy.set(runsKey(converter), limit - got);\n need += runs;\n short += (wanted - got) * converter.perDay;\n }\n for (const [resource, each] of inputs) {\n need += runs * each;\n short += takeResource(copy, makers, resource, runs * each, path);\n }\n return { short, need, value: copy };\n };\n const { x: runs, value: best } = largestFit(most, attempt);\n if (best === undefined) return 0;\n for (const [resource, amount] of best) left.set(resource, amount);\n return runs;\n}\n\n/**\n * This function takes an amount of a need from the resources in `left`: the direct uses first, then the converters.\n * A direct use or a converter takes each resource from its stock first, then from its makers.\n * It changes `left`, and it gives the amount that it could not take.\n */\nfunction take(left: Map<string, number>, ways: Ways, amount: number): number {\n let rest = amount;\n // A source gives first: its runs of a day are lost when no draw uses them (M2-solar).\n for (const converter of ways.sources) {\n if (rest <= 0) break;\n rest -= run(left, ways.makers, converter, rest / converter.gives.amount, NO_PATH) * converter.gives.amount;\n }\n for (const use of ways.direct) {\n if (rest <= 0) break;\n const wanted = rest / use.amount;\n rest -= (wanted - takeResource(left, ways.makers, use.resource, wanted, NO_PATH)) * use.amount;\n }\n for (const converter of ways.others) {\n if (rest <= 0) break;\n rest -= run(left, ways.makers, converter, rest / converter.gives.amount, NO_PATH) * converter.gives.amount;\n }\n return Math.max(0, rest);\n}\n\n/** This function gives each resource that a need can use: the inputs of its ways, and the inputs of their makers, through each chain. */\nfunction inputClosure(ways: Ways): Set<string> {\n return closureOf(\n ways.direct.map((use) => use.resource),\n ways.converters,\n [...ways.makers.values()].flat(),\n );\n}\n\n/** The relative tolerance of a used-up resource. */\nconst USED_UP = 1e-9;\n\n/** This function gives the day number of a day `MM-DD` of a year. A day that the year does not have gives undefined. */\nfunction yearDay(year: number, monthDay: string): number | undefined {\n return dayNumber(`${String(year).padStart(4, \"0\")}-${monthDay}`);\n}\n\n/**\n * This function gives the sow days of a season, in days from the start of the event, before the horizon, in increasing\n * 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`\n * 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.\n *\n * @throws RangeError when the start is not `YYYY-MM-DD`, or the horizon is not more than 0.\n */\nexport function sowDays(season: Pick<Season, \"from\" | \"to\">, start: IsoDate, horizon: number): number[] {\n if (!(horizon > 0)) throw new RangeError(`The horizon ${String(horizon)} is not a number of days more than 0.`);\n const first = dayOf(start);\n const out: number[] = [];\n // The window of the year before the start can go across the end of the year into the start.\n for (let year = Number(start.slice(0, 4)) - 1; ; year += 1) {\n const from = yearDay(year, season.from);\n const sameYear = yearDay(year, season.to);\n const to = from !== undefined && sameYear !== undefined && sameYear < from ? yearDay(year + 1, season.to) : sameYear;\n const opens = from ?? yearDay(year, \"01-01\")!;\n if (opens - first >= horizon) break;\n if (from === undefined || to === undefined || to < first) continue;\n const day = Math.max(from, first) - first;\n if (day < horizon) out.push(day);\n }\n return out;\n}\n\n/**\n * A lot of a resource in the ledger of a season (M2-grow-seed): a store before the event, or a harvest. A harvest is\n * ready from `day`, and its rest spoils on `spoils`. A store has the day -Infinity and no spoil day (Infinity).\n */\ninterface Lot {\n readonly resource: string;\n readonly day: number;\n readonly spoils: number;\n /** The amount that is not taken and not spoiled. */\n left: number;\n /** The amount that spoiled. */\n lost: number;\n}\n\n/** This function gives a lot of a store: it is ready before the event, and it does not spoil. */\nfunction storeLot(resource: string, amount: number): Lot {\n return { resource, day: -Infinity, spoils: Infinity, left: amount, lost: 0 };\n}\n\n/** This function compares two numbers for a sort, also two that are Infinity. */\nfunction compare(a: number, b: number): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\n/**\n * This function takes the use of each resource from `from` to `to` from the lots, first expiring first out. It takes\n * 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\n * harvest with no spoil day. With no spoil day, the order is thus the stores, then each harvest in the order of its day.\n */\nfunction useLots(lots: readonly Lot[], from: ReadonlyMap<string, number>, to: ReadonlyMap<string, number>): void {\n for (const [resource, had] of from) {\n let rest = had - (to.get(resource) ?? 0);\n if (!(rest > 0)) continue;\n const order = lots.filter((lot) => lot.resource === resource && lot.left > 0).sort((a, b) => compare(a.spoils, b.spoils) || compare(a.day, b.day));\n for (const lot of order) {\n if (!(rest > 0)) break;\n const taken = Math.min(lot.left, rest);\n lot.left -= taken;\n rest -= taken;\n }\n }\n}\n\n/**\n * This function gives the sowings of the converters with a season that can operate in a case, up to the horizon. It\n * 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\n * from `stock`, and from each harvest that is ready and not spoiled on its sow day (M2-grow-seed). It changes `stock`,\n * and the `left` of each lot is the rest of its harvest after the later sowings.\n */\nfunction sowings(layer: EnduranceLayer, stoppedParts: ReadonlySet<string>, stock: Map<string, number>, makers: Makers, start: IsoDate, horizon: number): { readonly harvests: Harvest[]; readonly lots: Lot[] } {\n const plan: { readonly converter: Converter; readonly season: Season; readonly sow: number; readonly order: number }[] = [];\n (layer.converters ?? []).forEach((converter, order) => {\n const season = converter.season;\n if (season === undefined || !(season.runs > 0) || !canRun(converter, stoppedParts)) return;\n for (const sow of sowDays(season, start, horizon)) plan.push({ converter, season, sow, order });\n });\n plan.sort((a, b) => a.sow - b.sow || a.order - b.order);\n const stores = [...stock].map(([resource, amount]) => storeLot(resource, amount));\n const lots: Lot[] = [];\n const out: Harvest[] = [];\n for (const { converter, season, sow } of plan) {\n const ready = [...stores, ...lots.filter((lot) => lot.day <= sow && lot.spoils > sow)];\n const pool = new Map<string, number>();\n for (const lot of ready) pool.set(lot.resource, (pool.get(lot.resource) ?? 0) + lot.left);\n const had = new Map(pool);\n const runs = run(pool, makers, converter, season.runs, NO_PATH);\n useLots(ready, had, pool);\n const resource = giftResource(converter);\n if (resource === undefined) continue;\n const day = sow + season.delayDays;\n const amount = runs * converter.gives.amount;\n const spoils = season.shelfDays === undefined ? Infinity : day + season.shelfDays;\n out.push({ converter: converter.id, sow, day, runs, resource, amount, ...(season.shelfDays === undefined ? {} : { spoils }) });\n lots.push({ resource, day, spoils, left: amount, lost: 0 });\n }\n for (const store of stores) stock.set(store.resource, store.left);\n return { harvests: out, lots };\n}\n\n/**\n * This function gives the supply of a case with a season (M2-grow-share). `enduranceOf`, `bestEndurance` and `jointDays`\n * 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`.\n */\nexport function seasonSupply(layer: EnduranceLayer, stoppedParts: ReadonlySet<string>, options: CaseOptions): SeasonSupply {\n const stock = storeAmounts(layer, options.at, stoppedParts);\n const horizon = seasonHorizon(options.horizon);\n const start = options.start ?? options.at;\n const sown = sowings(layer, stoppedParts, stock, makersOf(layer, stoppedParts), start, horizon);\n // Two crops with different delays give their harvests in a different order from their sowings.\n const lots = sown.lots\n .filter((lot) => lot.day < horizon && lot.left > 0)\n .sort((a, b) => a.day - b.day)\n .map((lot) => ({ resource: lot.resource, day: lot.day, spoils: lot.spoils, amount: lot.left }));\n return { stock, harvests: sown.harvests, lots, horizon, start };\n}\n\n/**\n * This function tells if a layer has a converter with a season, with shares `monthly` or a source (M2-solar) that can run\n * 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\n * month end a segment. A source can feed a draw with no end, thus the horizon is the upper limit of its days.\n */\nexport function hasSeason(layer: EnduranceLayer, stoppedParts: ReadonlySet<string>): boolean {\n return (layer.converters ?? []).some((converter) => (converter.season !== undefined || converter.monthly !== undefined || isSource(converter)) && canRun(converter, stoppedParts));\n}\n\n/**\n * This function gives the days that each draw holds when a case stops its supply, and the resources that are used up then.\n *\n * - A draw takes from the stores only when the case stops its supply part. Each other draw holds without end, and the result leaves it out.\n * - The demand of a draw for each day is its rate times the factor of the case.\n * - The draws take the resources in the order of their level, then of their codes. A draw takes from its direct uses first, then from its converters.\n * - The days of a draw are the largest `T` at which the stores give `T` days of its demand, after each higher draw.\n * - Each higher draw keeps back its own days times its demand. Thus the takes of all the draws are not more than the stores at any time.\n * - The take order is a rule, not the best share: the direct uses in the order of the list, then the converters. The days are the days of this order.\n * A draw with a shared device is different. Refer to the last item.\n * - A converter whose device stops gives nothing. A store whose part stops gives nothing.\n * - A converter can give a resource. A take of a resource uses the stock first, then the converters that make it, through each chain.\n * - A converter with a limit `perDay` runs `perDay` times `devices` times `T` times or less in `T` days. The converters of one device share it.\n * - The higher draws use the runs of a limit first.\n * - A higher draw keeps back its runs of each day for all the days of a lower draw, also when its own days are fewer. This is the safe side.\n * - Two limited converters of one device can make the shortfall of the take order decrease when the days increase.\n * Thus a draw whose ways reach two converters of one device, each with a limit `perDay` more than 0, does not use the take order.\n * A linear program with exact rationals gives its days: the largest `T` with the best share of its stocks and of the device-days.\n * At this `T`, the draw takes the smallest sum of its takes of the stocks, each over its stock, then the fewest device-days.\n\n * - A converter with a season (M2-grow) is not a maker of a take. Its sowings take their inputs from the stores before\n * the first draw, and each harvest adds to the stocks on its day. Refer to `Season`. The query reads the sowings\n * and the harvests up to the horizon (`horizon`, default `SEASON_HORIZON_DAYS`), and a draw holds the horizon at most.\n * - With a season, each draw takes its stocks over spans from harvest to harvest. `days` is the first stop of the\n * draw. A later harvest can feed the draw again: `again` gives these spans, and `takes` is the sum to the horizon.\n * A lower draw gets the stocks that the higher draws leave, the earliest stocks first taken. This is the safe side.\n * - A draw with a shared device and a season gets the programs of `bestEndurance` for itself alone (M2-grow-share-sweep). Its stocks,\n * its harvest lots and its device-days are those that the higher draws leave. It has no field `spoiled`.\n * - 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\n * draw uses them. With shares `monthly`, the device-days of a day are the devices times the share of its month. Each\n * span also ends at the start of a month, and a draw can hold again from the start of a month.\n * - A store with a capacity that a source charges (M2-solar-charge-sweep) takes a charge. Each draw that can take it gets the\n * programs of `bestEndurance` for itself alone, in the order of the levels. Thus one draw gets the days of `bestEndurance`.\n * A lower draw takes only the level that the higher draws leave. It charges the store only with the device-days that they leave.\n *\n * The function is pure, but for an internal count of the tries of its fits for the tests. It throws a `RangeError` for a date that is not `YYYY-MM-DD`. The gate `checkEndurance` examines the layer before.\n *\n * @param layer - The endurance layer\n * @param caseCuts - The case\n * @param options - The date, and the stack or the parts that are also down\n * @returns The endurance of each draw whose supply stops\n */\nexport function enduranceOf(layer: EnduranceLayer, caseCuts: CaseCuts, options: CaseOptions): Endurance {\n const stoppedParts = caseStopped(caseCuts, options);\n const seasonal = hasSeason(layer, stoppedParts);\n const supply = seasonal ? seasonSupply(layer, stoppedParts, options) : undefined;\n const start = supply?.stock ?? storeAmounts(layer, options.at, stoppedParts);\n const makers = makersOf(layer, stoppedParts);\n const stocked = new Set(layer.stores.map((store) => store.resource));\n const limited = (layer.converters ?? []).filter((converter) => converter.perDay !== undefined && canRun(converter, stoppedParts));\n // The count of devices of each key (`deviceKey`). The gate refuses two counts for one device.\n const devices = new Map(limited.map((converter) => [deviceKey(converter), converter.devices ?? 1]));\n // The share of the device-days of each key in the month of a day (M2-solar). With no shares, each share is 1.\n const monthShares = monthlyShares(limited);\n const begin = options.start ?? options.at;\n const shareAt = (key: string, at: number): number => (monthShares.size === 0 ? 1 : shareOf(monthShares, key, monthOf(begin, at)));\n const months = monthShares.size === 0 || supply === undefined ? [] : monthEdges(begin, supply.horizon);\n const nextMonth = (at: number): number => months.find((day) => day > at) ?? Infinity;\n // The device-days of each day that the higher draws use, by the key of the device. A higher draw keeps back its\n // device-days of each day for all the days of a lower draw, also after its own days end. This is the safe side.\n const used = new Map<string, number>();\n // The stocks that the higher draws leave after their own days.\n let before = new Map(start);\n // The sowings take their inputs from the stocks before each draw (M2-grow). Each harvest is a part of the stocks\n // from its day. `later` holds the amount of each harvest that the higher draws leave.\n const horizon = supply?.horizon ?? Infinity;\n const harvests = supply?.harvests ?? [];\n // The rest of each harvest after the sowings, in the order of its day (`seasonSupply`).\n const later = (supply?.lots ?? []).map((lot) => ({ ...lot }));\n // The stores with a capacity that a source charges (M2-solar-charge-sweep), and the rest of each that the higher draws leave.\n const capacities = storeCapacities(layer, stoppedParts);\n const chargedResources = new Set([...capacities.keys()].filter((resource) => (makers.get(resource) ?? []).some(isSource)));\n const rests = new Map<string, readonly ChargeRest[]>();\n const needs: Record<string, DrawEndurance> = {};\n for (const draw of caseDraws(layer, caseCuts, stoppedParts)) {\n const ways = waysOf(layer, draw.need, stoppedParts, makers);\n const demand = drawDemand(draw, caseCuts);\n // The device-days of each day that the higher draws leave to this draw, by the key of the device.\n const room = new Map([...devices].map(([key, count]) => [key, Math.max(0, count - (used.get(key) ?? 0))] as const));\n const closure = inputClosure(ways);\n // The converters that the draw can use: the converters that give its need, and the makers of its inputs through each chain.\n const reach = new Set([...ways.converters, ...[...closure].flatMap((resource) => makers.get(resource) ?? [])]);\n // The take of `days` days of the need from `stock`, with the device-days of those days from the day `at`.\n const after = (stock: ReadonlyMap<string, number>, days: number, at = 0): { left: Map<string, number>; short: number } => {\n const tried = new Map(stock);\n for (const [key, free] of room) tried.set(RUNS + key, free * shareAt(key, at) * days);\n return { left: tried, short: take(tried, ways, days * demand) };\n };\n // The days of one span from `stock`, `limit` days or less. `bound` is an upper limit of the need that the stock gives.\n const span = (stock: ReadonlyMap<string, number>, limit: number, bound: number, at = 0): { days: number; left: Map<string, number> } => {\n const fit = largestFit(Math.min(limit, bound / demand), (days) => {\n const tried = after(stock, days, at);\n return { short: tried.short, need: days * demand, value: tried.left };\n });\n return { days: fit.x, left: fit.value ?? after(stock, fit.x, at).left };\n };\n // With two limited converters of one device, the shortfall of the take order can decrease when the days increase.\n // For such a draw, a linear program gives the best share of the device-days and of the stocks.\n const shares = sharesDevice(reach);\n // A draw that can take a store with a charge gets the same programs, with the rest that the higher draws leave (M2-solar-charge-sweep).\n const charging = [...closure].some((resource) => chargedResources.has(resource));\n if ((shares || charging) && seasonal) {\n const lots = later.map((lot) => ({ resource: lot.resource, day: lot.day, spoils: lot.spoils, amount: lot.amount }));\n const held = seasonDraw(layer, stoppedParts, caseCuts, draw, resourcesOnly(before), lots, horizon, room, begin, capacities, rests);\n needs[draw.need] = held.need;\n for (const [key, each] of held.perDay) used.set(key, (used.get(key) ?? 0) + each);\n for (const [resource, rest] of held.rests) rests.set(resource, rest);\n before = held.stock;\n for (const [index, amount] of held.lots.entries()) (later[index] as { amount: number }).amount = amount;\n continue;\n }\n const share = shares ? bestShare({ draw, stock: before, room, direct: ways.direct, converters: ways.converters, makers: [...reach].filter((converter) => !ways.converters.includes(converter)), demand }) : undefined;\n let low: number;\n let left: Map<string, number>;\n // The stocks at the end of the sweep, and the stocks that came in it: the stocks before the draw and the harvests.\n let final: Map<string, number>;\n const came = new Map(before);\n // The amount of each resource that spoils in the sweep of the draw (M2-grow-seed).\n const lost = new Map<string, number>();\n // The ledger of the sweep of a season (M2-grow-seed): a lot for each stock before the draw, then each harvest that arrives.\n const pool = [...before].map(([resource, amount]) => storeLot(resource, amount));\n const arrived: { readonly lot: Lot; readonly harvest: (typeof later)[number] }[] = [];\n const again: { from: number; to: number }[] = [];\n let atHorizon = false;\n // The device-days of each day that the draw uses, the most of each span, by the key of the device. With shares\n // `monthly`, a span gives `free` times its share, and the use counts as its part of that share (M2-solar). Thus a\n // draw that uses all the device-days of a dark month keeps all the device-days of each month. This is the safe side.\n const perDay = new Map<string, number>();\n const count = (spanLeft: ReadonlyMap<string, number>, days: number, at = 0): void => {\n if (days > 0) for (const [key, free] of room) {\n const share = shareAt(key, at);\n if (!(share > 0)) continue;\n const each = (free * share * days - (spanLeft.get(RUNS + key) ?? 0)) / days / share;\n perDay.set(key, perDay.has(key) ? Math.max(perDay.get(key)!, each) : each);\n }\n };\n // The length and the first day of the span of the first stop, for the limits of the runs.\n let spanDays: number;\n let spanAt = 0;\n if (share !== undefined) {\n low = share.days;\n spanDays = low;\n left = new Map(before);\n for (const [resource, amount] of share.taken) left.set(resource, Math.max(0, (left.get(resource) ?? 0) - amount));\n for (const [key, free] of room) left.set(RUNS + key, Math.max(0, free * low - (share.used.get(key) ?? 0)));\n final = left;\n count(left, low);\n } else if (later.length === 0 && !seasonal) {\n // The upper limit: the days that the draw holds when it takes all the stores itself. `largestFit` finds the days below it.\n ({ days: low, left } = span(before, Infinity, capacity(start, ways)));\n spanDays = low;\n final = left;\n count(left, low);\n } else {\n // The sweep from harvest to harvest (M2-grow). In each span, the draw takes from the stocks of the span, first\n // expiring first out. A span ends at the next harvest, at the next spoil day of a lot (M2-grow-seed) or at the\n // horizon. After a stop, the draw holds again from the next harvest that feeds it.\n let stock: Map<string, number> = new Map(before);\n let next = 0;\n let at = 0;\n let first: { days: number; left: Map<string, number>; spanDays: number; spanAt: number } | undefined;\n let resumed = 0;\n // The harvests arrive on their days, and then the rest of each lot spoils on its spoil day. During a stop, the\n // draw takes nothing, thus a lot that arrives and spoils in the stop is lost in full.\n const advance = (): void => {\n while (next < later.length && later[next]!.day <= at) {\n const harvest = later[next]!;\n const lot: Lot = { resource: harvest.resource, day: harvest.day, spoils: harvest.spoils, left: harvest.amount, lost: 0 };\n pool.push(lot);\n arrived.push({ lot, harvest });\n stock.set(lot.resource, (stock.get(lot.resource) ?? 0) + lot.left);\n came.set(lot.resource, (came.get(lot.resource) ?? 0) + lot.left);\n next += 1;\n }\n for (const lot of pool) {\n if (!(lot.left > 0) || lot.spoils > at) continue;\n stock.set(lot.resource, Math.max(0, (stock.get(lot.resource) ?? 0) - lot.left));\n lost.set(lot.resource, (lost.get(lot.resource) ?? 0) + lot.left);\n lot.lost += lot.left;\n lot.left = 0;\n }\n };\n advance();\n for (;;) {\n const spoil = Math.min(...pool.filter((lot) => lot.left > 0).map((lot) => lot.spoils));\n const end = Math.min(next < later.length ? later[next]!.day : Infinity, spoil, horizon, nextMonth(at));\n const part = span(stock, end - at, capacity(stock, ways, shareAt, at), at);\n count(part.left, part.days, at);\n const rest = resourcesOnly(part.left);\n useLots(pool, stock, rest);\n stock = rest;\n const stop = at + part.days;\n if (part.days < end - at) {\n if (first === undefined) first = { days: stop, left: part.left, spanDays: part.days, spanAt: at };\n else if (stop > resumed) again.push({ from: resumed, to: stop });\n // After a stop, the draw holds again from the next harvest, or from the start of the next month (M2-solar).\n const resume = Math.min(next < later.length ? later[next]!.day : Infinity, nextMonth(at));\n if (!(resume < horizon)) break;\n at = resume;\n resumed = at;\n } else {\n at = end;\n if (at >= horizon) {\n if (first === undefined) atHorizon = true;\n else again.push({ from: resumed, to: horizon });\n break;\n }\n }\n advance();\n }\n low = first?.days ?? horizon;\n left = first?.left ?? stock;\n spanDays = first?.spanDays ?? horizon;\n spanAt = first?.spanAt ?? 0;\n final = stock;\n }\n // The binding resources are of the stores only: a used-up limit of runs is in `capped`, not here.\n const stores = resourcesOnly(left);\n const binding = atHorizon\n ? []\n : [...closure]\n .filter((resource) => !makers.has(resource) || stocked.has(resource))\n .filter((resource) => mostResource(stores, makers, resource, NO_PATH) <= USED_UP * Math.max(1, start.get(resource) ?? 0))\n .sort();\n const takes: Record<string, number> = {};\n for (const [resource, amount] of came) {\n const taken = amount - (final.get(resource) ?? 0) - (lost.get(resource) ?? 0);\n if (taken > 0) takes[resource] = taken;\n }\n const spoiled = Object.fromEntries([...lost].filter(([, amount]) => amount > 0));\n // A limit stops the draw when its limit gives the converter no runs left, and its inputs give more runs.\n // The runs left are the device-days left times `perDay`. Thus a limit of 0 stops the draw, also with its device-days left.\n const runsLeft = (converter: Converter): number => (daysLeft(left, converter) ?? 0) * (converter.perDay ?? 0);\n const runsGiven = (converter: Converter): number => (devices.get(deviceKey(converter)) ?? 1) * shareAt(deviceKey(converter), spanAt) * (converter.perDay ?? 0) * spanDays;\n const capped = atHorizon\n ? []\n : limited\n .filter((converter) => reach.has(converter))\n .filter((converter) => runsLeft(converter) <= USED_UP * Math.max(1, runsGiven(converter)))\n .filter((converter) => mostRuns(stores, makers, converter, NO_PATH) > USED_UP)\n .map((converter) => converter.id)\n .sort();\n needs[draw.need] = {\n days: low,\n binding,\n takes,\n ...(capped.length === 0 ? {} : { capped }),\n ...(atHorizon ? { atHorizon: true as const } : {}),\n ...(again.length === 0 ? {} : { again }),\n ...(Object.keys(spoiled).length === 0 ? {} : { spoiled }),\n };\n // The device-days of each day of this draw count against each lower draw, for all of its days.\n for (const [key, each] of perDay) used.set(key, (used.get(key) ?? 0) + each);\n if (later.length === 0 && !seasonal) {\n before = resourcesOnly(final);\n continue;\n }\n // The lower draws get the rest of each lot after the takes of this draw. A lower draw reads the spoil of each lot\n // again, thus the spoiled rest of a lot is a part of its rest. With no spoil day, the takes come from the earliest\n // stocks: the stocks before the draw, then each harvest in the order of its day.\n for (const lot of pool) if (lot.day === -Infinity) before.set(lot.resource, lot.left);\n for (const { lot, harvest } of arrived) harvest.amount = lot.left + lot.lost;\n }\n return { case: caseCuts.case, at: options.at, needs, ...(harvests.length === 0 ? {} : { harvests }) };\n}\n\n/** This function gives the horizon of a layer with a season, or throws a `RangeError` for a horizon that is not more than 0. */\nfunction seasonHorizon(horizon: number | undefined): number {\n const value = horizon ?? SEASON_HORIZON_DAYS;\n if (!(value > 0) || !Number.isFinite(value)) throw new RangeError(`The horizon ${String(horizon)} is not a number of days more than 0.`);\n return value;\n}\n\n/** This function tells if two converters of `reach` with a limit `perDay` more than 0 share one device. */\nfunction sharesDevice(reach: ReadonlySet<Converter>): boolean {\n const seen = new Set<string>();\n for (const converter of reach) {\n if (converter.perDay === undefined || !(converter.perDay > 0)) continue;\n const key = deviceKey(converter);\n if (seen.has(key)) return true;\n seen.add(key);\n }\n return false;\n}\n\n/**\n * This function gives an upper limit of a need that the stores give with no other draw, through each chain. A source\n * (M2-solar) with a share more than 0 gives no upper limit, thus the limit is Infinity. The span of the sweep is finite.\n */\nfunction capacity(start: ReadonlyMap<string, number>, ways: Ways, shareAt?: (key: string, at: number) => number, at = 0): number {\n for (const converter of ways.open) if ((shareAt === undefined ? 1 : shareAt(deviceKey(converter), at)) > 0) return Infinity;\n let total = 0;\n for (const use of ways.direct) total += mostResource(start, ways.makers, use.resource, NO_PATH) * use.amount;\n for (const converter of ways.converters) total += mostRuns(start, ways.makers, converter, NO_PATH) * converter.gives.amount;\n return total;\n}\n","import { type Objective, solveLexicographic } from \"@mark1russell7/linear\";\nimport { add, div, equals, mul, neg, ONE, type Rational, sign, toNumber, ZERO } from \"@mark1russell7/rational\";\nimport { type CaseOptions, caseDraws, caseStopped, drawDemand, hasSeason, seasonSupply, storeAmounts } from \"./endurance.ts\";\nimport type { CaseCuts, Converter, EnduranceLayer, IsoDate } from \"./layer.ts\";\nimport { caseParts, deviceUse, drawBlock, fewestRow, Program, reachOf, valueAt } from \"./program.ts\";\nimport { addTo, dense, exact, type Row } from \"./rows.ts\";\nimport { seasonJoint, seasonPlan, storeCapacities } from \"./seasonal.ts\";\n\n// The joint days: the largest count of days that a set of draws holds together, with the best share of the stores.\n// The query is a linear program over the totals of the span, with exact rationals (@mark1russell7/linear).\n\n/** The joint days of a set of draws in a case, with the share of the stores at the optimum. */\nexport interface JointDays {\n readonly case: string;\n readonly at: IsoDate;\n /**\n * The largest count of days that each draw of `plan` holds at the same time. It is `Infinity` when `plan` is empty,\n * or when the stores give each draw of `plan` without end.\n */\n readonly days: number;\n /** The needs of the set that take from the stores: the case stops their supply, and their demand is more than 0. The order is the order of `caseDraws`. */\n readonly plan: readonly string[];\n /** The needs of the set that take nothing from the stores, in the order of their codes. The case does not stop their supply, or their demand is 0. */\n readonly holds: readonly string[];\n /**\n * The amount of each resource that each draw of `plan` takes from the stores in `days`. The keys are the code of the need, then the code of the resource.\n * A take through a converter that makes a resource counts the inputs of the converter. A resource with no take is not in the record.\n * The record is empty when `days` is `Infinity`.\n */\n readonly takes: Readonly<Record<string, Readonly<Record<string, number>>>>;\n /**\n * The resources that limit `days`, in the order of their codes. Each one has a store in the layer, is an input of `plan` through each chain,\n * and has no stock left at the optimum. The list is empty when `days` is `Infinity`.\n */\n readonly binding: readonly string[];\n /** The count of runs of each converter at the optimum, by the `id` of the converter. A converter with no run is not in the record. */\n readonly runs: Readonly<Record<string, number>>;\n /**\n * The converters of the plan whose limit `perDay` stops more runs at the optimum, in the order of their `id`. A converter of the plan\n * gives a need of the plan, or makes an input of the plan through each chain.\n * The list is empty when `days` is `Infinity` or 0. Else it has each converter of the plan with a limit of 0.\n */\n readonly capped: readonly string[];\n /** True when a layer with a season holds the plan to the horizon (M2-grow-share). `days` is then the horizon. */\n readonly atHorizon?: true | undefined;\n}\n\n/**\n * This function gives the joint days of a set of draws. These are the largest count of days `d` at which each draw holds `d` days.\n * The draws hold at the same time, with the best share of the stores and of the runs of the converters.\n *\n * - The function solves a linear program over the totals of the span. Its variables are `d`, the take of each direct use,\n * the runs of each converter, and the share of each stock.\n * - Each draw of the plan gets `d` times its demand (`drawDemand`) from its direct uses and from the converters that give its need.\n * - The takes of each resource are not more than its stock (`storeAmounts` at `at`) plus the gifts of the converters that make it.\n * - A converter whose device stops gives nothing, and a store whose part stops gives nothing, as in `enduranceOf`.\n * - The runs of a converter with a limit `perDay` are not more than `perDay` times `devices` times `d`. The converters of one device share it, as in `enduranceOf`.\n * - A store counts with all of its amount when its due date is after `at`, as in `enduranceOf`. A due date in the span has no effect.\n * - After the largest `d`, a second objective takes the smallest sum of the shares of the stocks. Thus the takes have no waste.\n * - A third objective takes the fewest device-days of the converters. Thus the runs are not more than the plan uses.\n * - The draws that are not in the set are outside this plan. They take nothing in the program.\n * - A need of the set whose supply works, or whose demand is 0, holds without end. It goes in `holds`, as `enduranceOf` leaves it out.\n *\n * The take order of `enduranceOf` gives the stores to a higher draw first. This function gives one share for the whole set.\n * Thus a draw of the set can get fewer days here than alone, and a lower draw can get more.\n *\n * The program uses exact rationals, so the result has no error of the method. Only the change back to a number rounds.\n *\n * With a converter with a season, `days` is the largest common first stop of the plan (M2-grow-share). The sowings, the lots and\n * the segments are those of `bestEndurance`. The plan holds the horizon at most (default `SEASON_HORIZON_DAYS`), with `atHorizon`.\n *\n * @param layer - The endurance layer\n * @param caseCuts - The case\n * @param options - The date, and the stack or the parts that are also down\n * @param needs - The codes of the needs of the draws of the set\n * @returns The joint days, the takes of each draw, the binding resources and the runs of each converter\n * @throws {RangeError} A code of `needs` is not the need of a draw of the layer, or a date is not `YYYY-MM-DD`. Or the horizon of a layer with a season is not more than 0.\n */\nexport function jointDays(layer: EnduranceLayer, caseCuts: CaseCuts, options: CaseOptions, needs: readonly string[]): JointDays {\n const known = new Set(layer.draws.map((draw) => draw.need));\n const unknown = needs.filter((need) => !known.has(need));\n if (unknown.length > 0) throw new RangeError(`The needs ${unknown.map((need) => `\"${need}\"`).join(\", \")} are not the needs of draws of the layer.`);\n const stoppedParts = caseStopped(caseCuts, options);\n const seasonal = hasSeason(layer, stoppedParts);\n const supply = seasonal ? seasonSupply(layer, stoppedParts, options) : undefined;\n const stock = supply?.stock ?? storeAmounts(layer, options.at, stoppedParts);\n const wanted = new Set(needs);\n const plan = caseDraws(layer, caseCuts, stoppedParts).filter((draw) => wanted.has(draw.need));\n const planned = new Set(plan.map((draw) => draw.need));\n const base = { case: caseCuts.case, at: options.at, plan: plan.map((draw) => draw.need), holds: [...wanted].filter((need) => !planned.has(need)).sort() };\n const endless: JointDays = { ...base, days: Infinity, takes: {}, binding: [], runs: {}, capped: [] };\n if (plan.length === 0) return endless;\n\n const parts = caseParts(layer, stoppedParts, stock, planned);\n if (supply !== undefined) {\n const devices = new Map([...deviceUse([...parts.cooks, ...parts.makers].map((converter) => [converter, 0] as const)).limits].map(([key, limit]) => [key, limit.devices] as const));\n const { atHorizon, ...joint } = seasonJoint(seasonPlan(supply, parts, caseCuts, plan, devices, storeCapacities(layer, stoppedParts)), new Set(layer.stores.map((store) => store.resource)));\n return { ...base, ...joint, ...(atHorizon ? { atHorizon: true as const } : {}) };\n }\n const program = new Program();\n const days = program.next();\n const blocks = plan.map((draw) => {\n const block = drawBlock(program, parts, draw);\n // The need of the draw: its gifts are not less than its demand times the days.\n const need: Row = new Map(block.gifts);\n addTo(need, days, neg(exact(drawDemand(draw, caseCuts))));\n program.push(need, \">=\", ZERO);\n return block;\n });\n // The limit of each device: the runs use `devices` times `d` device-days or less. A limit of 0 stops the converter.\n const runCols = blocks.flatMap((block) => [...block.runs]);\n const { limits, stopped } = deviceUse(runCols);\n for (const index of stopped) program.push(new Map([[index, ONE]]), \"<=\", ZERO);\n for (const limit of limits.values()) {\n const row: Row = new Map(limit.row);\n addTo(row, days, neg(exact(limit.devices)));\n program.push(row, \"<=\", ZERO);\n }\n // The shares of each stock are not more than the stock.\n for (const resource of parts.stocked) {\n const row: Row = new Map();\n // A draw has a share only of a resource that it can use (`drawBlock`).\n for (const block of blocks) {\n const index = block.shares.get(resource);\n if (index !== undefined) addTo(row, index, ONE);\n }\n if (row.size > 0) program.push(row, \"<=\", exact(stock.get(resource) ?? 0));\n }\n\n const most: Row = new Map([[days, ONE]]);\n const least: Row = new Map();\n for (const block of blocks) for (const [resource, index] of block.shares) addTo(least, index, div(ONE, exact(stock.get(resource) ?? 1)));\n // The third objective takes the fewest device-days. Thus a converter whose inputs cost no stock does not give more runs than the plan uses,\n // and `runs` and `capped` have one value.\n const objectives: Objective[] = [\n { sense: \"max\", coefficients: dense(most, program.count) },\n { sense: \"min\", coefficients: dense(least, program.count) },\n { sense: \"min\", coefficients: dense(fewestRow(runCols), program.count) },\n ];\n // Each later stage starts from the optimal basis of the stage before it (M2-linear-warm-start). No later program reads this point.\n const solved = solveLexicographic(program.constraints(), objectives, { warm: true });\n // The point 0 is feasible and the later objectives are not less than 0. So only an unbounded first stage has no optimum.\n if (solved.status !== \"optimal\") return endless;\n\n const x = solved.x;\n const takes: Record<string, Record<string, number>> = {};\n for (const block of blocks) {\n const record: Record<string, number> = {};\n for (const [resource, index] of block.shares) if (sign(x[index] ?? ZERO) > 0) record[resource] = toNumber(x[index] ?? ZERO);\n takes[block.draw.need] = record;\n }\n // A converter gives a need or a resource, so it is a cook or a maker, not the two.\n const total = new Map<Converter, Rational>();\n for (const [converter, index] of runCols) total.set(converter, add(total.get(converter) ?? ZERO, x[index] ?? ZERO));\n const runs: Record<string, number> = {};\n for (const [converter, value] of total) if (sign(value) > 0) runs[converter.id] = toNumber(value);\n\n const withStore = new Set(layer.stores.map((store) => store.resource));\n // The converters that the plan can use: the converters that give a need of the plan, and the makers of the resources of the closure.\n const { closure, reach } = reachOf(parts, planned);\n const binding = [...closure]\n .filter((resource) => withStore.has(resource))\n .filter((resource) => {\n // A resource with no live stock has no share, so its take is 0 and it is used up.\n const taken = blocks.reduce((sum, block) => {\n const index = block.shares.get(resource);\n return index === undefined ? sum : add(sum, x[index] ?? ZERO);\n }, ZERO);\n return equals(taken, exact(stock.get(resource) ?? 0));\n })\n .sort();\n const best = solved.values[0] ?? ZERO;\n const capped = sign(best) > 0\n ? [\n ...[...total.keys()].filter((converter) => converter.perDay !== undefined && !(converter.perDay > 0)),\n ...[...limits.values()].filter((limit) => equals(valueAt(limit.row, x), mul(exact(limit.devices), best))).flatMap((limit) => limit.converters),\n ]\n .filter((converter) => reach.has(converter))\n .map((converter) => converter.id)\n .sort()\n : [];\n return { ...base, days: toNumber(best), takes, binding, runs, capped };\n}\n","import { type Objective, solveLexicographic } from \"@mark1russell7/linear\";\nimport { add, div, equals, mul, neg, ONE, type Rational, sign, sub, toNumber, ZERO } from \"@mark1russell7/rational\";\nimport { type CaseOptions, caseDraws, caseStopped, drawDemand, hasSeason, seasonSupply, storeAmounts } from \"./endurance.ts\";\nimport type { CaseCuts, Converter, Draw, DrawEndurance, Endurance, EnduranceLayer } from \"./layer.ts\";\nimport { type CaseParts, caseParts, deviceUse, drawBlock, type DrawBlock, fewestRow, Program, reachOf, valueAt } from \"./program.ts\";\nimport { addTo, dense, exact, type Row } from \"./rows.ts\";\nimport { firstStop, fewestOpen, type FixedStop, fixStops, seasonBest, seasonPlan, storeCapacities } from \"./seasonal.ts\";\n\n// The best endurance: the days of each draw with the best share of the stores, the most important level first.\n// Each step is a linear program over the totals of the spans, with exact rationals (@mark1russell7/linear).\n\n/** A draw whose days are fixed. */\ninterface Fixed {\n /** The span of the draw in the programs: its days, or 1 for a draw with no end. */\n readonly span: Rational;\n /** True for a draw that holds without end. It takes no stock, and its span is one day. */\n readonly endless: boolean;\n /** The device-days of each day that the draw keeps, by the key of the device. */\n readonly keep: ReadonlyMap<string, Rational>;\n /** The `id` of each converter whose limit stops more runs at the step that fixes the draw. */\n readonly capped: readonly string[];\n /** True for a draw that holds the horizon. */\n readonly atHorizon: boolean;\n}\n\n/** The options of `bestEndurance`: the options of a case, and a horizon. */\nexport interface BestOptions extends CaseOptions {\n /**\n * The horizon in days, more than 0. The default is no horizon. A draw holds the horizon at most, thus it keeps back\n * only the horizon times its demand. The rest of the stores goes to the lower levels. Use the target of a plan, for\n * example 14 days, to ask if each draw holds the target.\n */\n readonly horizon?: number | undefined;\n}\n\n/** This function gives the horizon as a rational, or undefined for no horizon. It throws a `RangeError` for a horizon that is not more than 0. */\nfunction horizonOf(horizon: number | undefined): Rational | undefined {\n if (horizon === undefined || horizon === Infinity) return undefined;\n if (!(horizon > 0) || !Number.isFinite(horizon)) throw new RangeError(`The horizon ${String(horizon)} is not a number of days more than 0.`);\n return exact(horizon);\n}\n\n/** A program of one step, with the indexes of its parts. */\ninterface Step {\n readonly program: Program;\n readonly blocks: readonly DrawBlock[];\n /** The column of the common days of the open draws. */\n readonly floor: number;\n /** The row `days - floor >= 0` of each open draw, by the code of its need. */\n readonly floors: ReadonlyMap<string, number>;\n /** The run columns of the open draws. */\n readonly openRuns: readonly (readonly [Converter, number])[];\n /** The device-days of the open draws for each device, with the device-days of each day that the fixed draws leave. */\n readonly shared: ReadonlyMap<string, { readonly row: Row; readonly room: Rational; readonly converters: readonly Converter[] }>;\n}\n\n/**\n * This function gives the days that each draw holds when a case stops its supply. The stores and the devices have their best share.\n * The result has the form of `enduranceOf`, so `caseShortfall` takes it.\n *\n * The share is lexicographic. The draws of the first level get their best days, then the draws of the next level get theirs, and so on.\n * In one level, the share is the best for the draw with the fewest days, then for the next draw, and so on (the leximin share).\n * Thus a draw of a level cannot take a store that another draw of the level needs more.\n *\n * - The function solves a sequence of linear programs over the totals of the spans. Each program has the days of the open draws\n * and their common floor. For each draw, it has the take of each direct use, the runs of each converter and the share of each stock.\n * - Each step takes the largest floor. A draw whose floor row has a dual value that is not 0 cannot get more days. The step fixes its days.\n * The dual values of the floor rows add to 1, so each step fixes one draw or more.\n * - A fixed draw keeps its days in each later step. Its share of the stocks can change, so a later draw can get a store that it does not need.\n * - The stores, the direct uses, the converters and the devices follow the rules of `jointDays`. A store counts with all of its amount when its due date is after `at`.\n * - A fixed draw keeps the device-days of each day that it uses at its step, for all the days of the later draws. This is the safe side, as in `enduranceOf`.\n * The exact share of a device between two spans is not a linear program: the device-days of a day are the runs over the span.\n * - A step with no largest floor gives the open draws no end. Each of them takes no stock, and keeps the fewest device-days of each day.\n * - At the end, a program takes the smallest sum of the shares of the stocks, each over its stock, then the fewest device-days.\n * These are the takes of the result. A resource in `binding` has no stock left at this point.\n * - A draw in `capped` used a device with no device-days left at the step that fixed it.\n * - With a horizon, the floor of each step is the horizon at most. A step whose floor is the horizon fixes each of its\n * open draws at the horizon, with `atHorizon`. Such a draw takes only the horizon times its demand. A draw with no\n * end also holds the horizon. With no horizon, the result is the same as before the option.\n *\n * The programs use exact rationals, so the result has no error of the method. Only the change back to a number rounds.\n * The fewest days of the first level are the joint days (`jointDays`) of the draws of that level.\n *\n * A layer with a converter with a season has the programs of a season (M2-grow-share):\n * - The sowings take their inputs before the draws, as in `enduranceOf`. Each harvest is a lot from its day, and its rest spoils on its spoil day.\n * - The days go in segments that end at each harvest day, at each spoil day and at the horizon (default `SEASON_HORIZON_DAYS`). A segment takes only\n * the lots that are ready and not spoiled in all of it.\n * - `days` is the first stop of each draw, with the same leximin share. The days to a stop are not linear, so each step tries the segments in order.\n * - After the stops, a last program gives the most fed days to each level in order. `again` gives the spans in which a later harvest feeds a draw.\n * In such a span, the runs share the device-days of the whole segment that the stops leave.\n * - The result has the field `harvests`. It has no field `spoiled`: the share of a lot between the draws has no spoil of one draw.\n *\n * @param layer - The endurance layer\n * @param caseCuts - The case\n * @param options - The date, the stack or the parts that are also down, and the horizon\n * @returns The endurance of each draw whose supply stops\n * @throws {RangeError} A date is not `YYYY-MM-DD`, or the horizon is not more than 0.\n */\nexport function bestEndurance(layer: EnduranceLayer, caseCuts: CaseCuts, options: BestOptions): Endurance {\n const horizon = horizonOf(options.horizon);\n const stoppedParts = caseStopped(caseCuts, options);\n if (hasSeason(layer, stoppedParts)) return bestSeason(layer, caseCuts, options, stoppedParts);\n const stock = storeAmounts(layer, options.at, stoppedParts);\n const draws = caseDraws(layer, caseCuts, stoppedParts);\n const parts = caseParts(layer, stoppedParts, stock, new Set(draws.map((draw) => draw.need)));\n // The count of devices of each key. The gate refuses two counts for one device.\n const devices = new Map([...deviceUse([...parts.cooks, ...parts.makers].map((converter) => [converter, 0] as const)).limits].map(([key, limit]) => [key, limit.devices] as const));\n const fixed = new Map<string, Fixed>();\n\n for (const level of levelGroups(layer, draws)) {\n let open = level;\n while (open.length > 0) {\n const step = buildStep(parts, caseCuts, draws, fixed, open, devices, \"span\", horizon);\n // This solve stays cold (M2-linear-warm-start). No objective fixes the shares of the stocks, thus the fewest runs can have a tie.\n // The point x gives the device-days that each fixed draw keeps for the later steps. A different optimal point can change their days.\n const solved = solveLexicographic(step.program.constraints(), [\n { sense: \"max\", coefficients: dense(new Map([[step.floor, ONE]]), step.program.count) },\n { sense: \"min\", coefficients: dense(fewestRow(step.openRuns), step.program.count) },\n ]);\n if (solved.status !== \"optimal\") {\n if (solved.status === \"infeasible\") throw new Error(\"The step of the best endurance has no point. The point of the last step is a point of it.\");\n fixEndless(parts, caseCuts, draws, fixed, open, devices);\n break;\n }\n const floor = solved.values[0] ?? ZERO;\n const first = solved.stages[0]?.result;\n const dual = first?.status === \"optimal\" ? first.dual : [];\n const atHorizon = horizon !== undefined && equals(floor, horizon);\n let done = atHorizon ? open : open.filter((draw) => sign(dual[step.floors.get(draw.need) as number] ?? ZERO) !== 0);\n // The dual values of the floor rows add to 1. Thus `done` is not empty. The fallback fixes each open draw at the floor.\n if (done.length === 0) done = open;\n const full = new Set([...step.shared].filter(([, limit]) => equals(valueAt(limit.row, solved.x), mul(limit.room, floor))).map(([key]) => key));\n for (const draw of done) {\n const block = step.blocks.find((item) => item.draw.need === draw.need) as DrawBlock;\n const keep = new Map<string, Rational>();\n for (const [key, limit] of deviceUse(block.runs).limits) keep.set(key, sign(floor) > 0 ? div(valueAt(limit.row, solved.x), floor) : ZERO);\n const { reach } = reachOf(parts, new Set([draw.need]));\n const capped = sign(floor) > 0\n ? [...reach]\n .filter((converter) => converter.perDay !== undefined && (!(converter.perDay > 0) || [...full].some((key) => step.shared.get(key)?.converters.includes(converter))))\n .map((converter) => converter.id)\n .sort()\n : [];\n fixed.set(draw.need, { span: floor, endless: false, keep, capped, atHorizon });\n }\n const fixedNow = new Set(done.map((draw) => draw.need));\n open = open.filter((draw) => !fixedNow.has(draw.need));\n }\n }\n\n const needs: Record<string, DrawEndurance> = {};\n if (draws.length === 0) return { case: caseCuts.case, at: options.at, needs };\n const last = buildStep(parts, caseCuts, draws, fixed, [], devices, \"span\");\n const least: Row = new Map();\n for (const block of last.blocks) for (const [resource, index] of block.shares) addTo(least, index, div(ONE, exact(stock.get(resource) ?? 1)));\n const objectives: Objective[] = [\n { sense: \"min\", coefficients: dense(least, last.program.count) },\n { sense: \"min\", coefficients: dense(fewestRow(last.blocks.flatMap((block) => [...block.runs])), last.program.count) },\n ];\n // The second stage starts from the optimal basis of the first stage (M2-linear-warm-start). No later program reads this point.\n const solved = solveLexicographic(last.program.constraints(), objectives, { warm: true });\n if (solved.status !== \"optimal\") throw new Error(\"The last program of the best endurance has no optimum. The point of the last step is a point of it.\");\n const withStore = new Set(layer.stores.map((store) => store.resource));\n for (const block of last.blocks) {\n const need = block.draw.need;\n const fix = fixed.get(need) as Fixed;\n if (fix.endless) {\n needs[need] = { days: Infinity, binding: [], takes: {} };\n continue;\n }\n const takes: Record<string, number> = {};\n for (const [resource, index] of block.shares) if (sign(solved.x[index] ?? ZERO) > 0) takes[resource] = toNumber(solved.x[index] ?? ZERO);\n const { closure } = reachOf(parts, new Set([need]));\n const binding = [...closure]\n .filter((resource) => withStore.has(resource))\n .filter((resource) => {\n // A resource with no live stock has no share, so its take is 0 and it is used up.\n const taken = last.blocks.reduce((sum, item) => {\n const index = item.shares.get(resource);\n return index === undefined ? sum : add(sum, solved.x[index] ?? ZERO);\n }, ZERO);\n return equals(taken, exact(stock.get(resource) ?? 0));\n })\n .sort();\n const days = toNumber(fix.span);\n needs[need] = { days, binding, takes, ...(fix.capped.length === 0 ? {} : { capped: fix.capped }), ...(fix.atHorizon ? { atHorizon: true as const } : {}) };\n }\n return { case: caseCuts.case, at: options.at, needs };\n}\n\n/** This function gives the best endurance of a case with a season (M2-grow-share). */\nfunction bestSeason(layer: EnduranceLayer, caseCuts: CaseCuts, options: BestOptions, stoppedParts: ReadonlySet<string>): Endurance {\n const supply = seasonSupply(layer, stoppedParts, options);\n const draws = caseDraws(layer, caseCuts, stoppedParts);\n const parts = caseParts(layer, stoppedParts, supply.stock, new Set(draws.map((draw) => draw.need)));\n const devices = new Map([...deviceUse([...parts.cooks, ...parts.makers].map((converter) => [converter, 0] as const)).limits].map(([key, limit]) => [key, limit.devices] as const));\n const plan = seasonPlan(supply, parts, caseCuts, draws, devices, storeCapacities(layer, stoppedParts));\n const harvests = supply.harvests.length === 0 ? {} : { harvests: supply.harvests };\n if (draws.length === 0) return { case: caseCuts.case, at: options.at, needs: {}, ...harvests };\n const levels = levelGroups(layer, draws);\n const fixed = new Map<string, FixedStop>();\n for (const level of levels) {\n let open = level;\n while (open.length > 0) {\n const opened = new Set(open.map((draw) => draw.need));\n const stop = firstStop(plan, fixed, open, (step) => [fewestOpen(step, opened)]);\n // A draw whose floor row has a dual value that is not 0 cannot get more days. The fallback fixes each open draw.\n let done = stop.atHorizon ? open : open.filter((draw) => sign(stop.dual[stop.step.floors.get(draw.need) as number] ?? ZERO) !== 0);\n if (done.length === 0) done = open;\n fixStops(plan, stop, done, fixed);\n open = open.filter((draw) => !done.includes(draw));\n }\n }\n const { needs } = seasonBest(plan, fixed, levels, new Set(layer.stores.map((store) => store.resource)));\n return { case: caseCuts.case, at: options.at, needs, ...harvests };\n}\n\n/** This function gives the draws of each level, in the order of `levels`. The draws of a level that is not in `levels` come last, together. */\nfunction levelGroups(layer: EnduranceLayer, draws: readonly Draw[]): Draw[][] {\n const rank = (draw: Draw): number => {\n const index = layer.levels.indexOf(draw.level);\n return index < 0 ? layer.levels.length : index;\n };\n const out: Draw[][] = [];\n let previous = -1;\n for (const draw of draws) {\n if (rank(draw) !== previous) out.push([]);\n previous = rank(draw);\n out[out.length - 1]?.push(draw);\n }\n return out;\n}\n\n/**\n * This function gives the program of one step. The fixed draws keep their spans and their device-days. The open draws have a common floor.\n *\n * - With `\"span\"`, each open draw has a column of its days, not less than the floor. Its runs share the device-days that the fixed draws leave, for the floor.\n * The device-days of each day are the runs over the span. A span not less than the floor uses fewer of them, so this is the safe side.\n * - With `\"day\"`, each open draw has a span of one day and takes no stock. Its runs share the device-days of one day.\n * - With a horizon, the floor is the horizon at most.\n */\nfunction buildStep(\n parts: CaseParts,\n caseCuts: CaseCuts,\n draws: readonly Draw[],\n fixed: ReadonlyMap<string, Fixed>,\n open: readonly Draw[],\n devices: ReadonlyMap<string, number>,\n mode: \"span\" | \"day\",\n horizon?: Rational,\n): Step {\n const program = new Program();\n const floor = program.next();\n if (horizon !== undefined) program.push(new Map([[floor, ONE]]), \"<=\", horizon);\n const opened = new Set(open.map((draw) => draw.need));\n const blocks: DrawBlock[] = [];\n const floors = new Map<string, number>();\n const openRuns: (readonly [Converter, number])[] = [];\n const kept = new Map<string, Rational>();\n for (const draw of draws) {\n const fix = fixed.get(draw.need);\n if (fix === undefined && !opened.has(draw.need)) continue;\n const endless = fix?.endless ?? mode === \"day\";\n const block = drawBlock(program, parts, draw, !endless);\n blocks.push(block);\n const demand = exact(drawDemand(draw, caseCuts));\n const need: Row = new Map(block.gifts);\n if (fix !== undefined) {\n program.push(need, \">=\", mul(demand, fix.span));\n const { limits, stopped } = deviceUse(block.runs);\n for (const index of stopped) program.push(new Map([[index, ONE]]), \"<=\", ZERO);\n for (const [key, limit] of limits) program.push(limit.row, \"<=\", mul(fix.keep.get(key) ?? ZERO, fix.span));\n for (const [key, value] of fix.keep) kept.set(key, add(kept.get(key) ?? ZERO, value));\n continue;\n }\n openRuns.push(...block.runs);\n if (mode === \"day\") {\n program.push(need, \">=\", demand);\n continue;\n }\n const days = program.next();\n addTo(need, days, neg(demand));\n program.push(need, \">=\", ZERO);\n floors.set(draw.need, program.push(new Map([[days, ONE], [floor, neg(ONE)]]), \">=\", ZERO));\n }\n const shared = new Map<string, { row: Row; room: Rational; converters: readonly Converter[] }>();\n const { limits, stopped } = deviceUse(openRuns);\n for (const index of stopped) program.push(new Map([[index, ONE]]), \"<=\", ZERO);\n for (const [key, limit] of limits) {\n const left = sub(exact(devices.get(key) ?? limit.devices), kept.get(key) ?? ZERO);\n const room = sign(left) > 0 ? left : ZERO;\n shared.set(key, { row: limit.row, room, converters: limit.converters });\n if (mode === \"day\") {\n program.push(limit.row, \"<=\", room);\n continue;\n }\n const row: Row = new Map(limit.row);\n addTo(row, floor, neg(room));\n program.push(row, \"<=\", ZERO);\n }\n for (const resource of parts.stocked) {\n const row: Row = new Map();\n for (const block of blocks) {\n const index = block.shares.get(resource);\n if (index !== undefined) addTo(row, index, ONE);\n }\n if (row.size > 0) program.push(row, \"<=\", exact(parts.stock.get(resource) ?? 0));\n }\n return { program, blocks, floor, floors, openRuns, shared };\n}\n\n/**\n * This function fixes the open draws with no end. Each open draw takes no stock, and keeps the fewest device-days of each day.\n * A step with no largest floor has a direction with no take of a stock, so this program has a point.\n */\nfunction fixEndless(parts: CaseParts, caseCuts: CaseCuts, draws: readonly Draw[], fixed: Map<string, Fixed>, open: readonly Draw[], devices: ReadonlyMap<string, number>): void {\n const step = buildStep(parts, caseCuts, draws, fixed, open, devices, \"day\");\n const solved = solveLexicographic(step.program.constraints(), [{ sense: \"min\", coefficients: dense(fewestRow(step.openRuns), step.program.count) }]);\n if (solved.status !== \"optimal\") throw new Error(\"The draws with no end of the best endurance have no point of one day.\");\n for (const draw of open) {\n const block = step.blocks.find((item) => item.draw.need === draw.need) as DrawBlock;\n const keep = new Map<string, Rational>();\n for (const [key, limit] of deviceUse(block.runs).limits) keep.set(key, valueAt(limit.row, solved.x));\n fixed.set(draw.need, { span: ONE, endless: true, keep, capped: [], atHorizon: false });\n }\n}\n","import { DEFAULT_MAX_SETS, stopSets, type Stack } from \"@mark1russell7/system-stack\";\n\n// The minimal stop sets of a supply from the structure of the needs. The index does not give this entry: `stopCurves` uses it.\n\n/**\n * This function gives the minimal sets of cuts that stop a supply, from the paths of the needs of the stack (`stopSets` of the core).\n * A set is a list of indexes of `parts`, from the smallest set. Two sets of one size are in the order of `minimalStops`.\n *\n * - `parts` has the part of each cut that counts. Two cuts of one part are two cuts: each one stops what the part stops.\n * - A cut of the supply stops it alone. The other sets come from `stopSets` with the cut parts as `among`, so no other part can fail.\n * - The parts of `down` are down for the full event. The caller makes sure that they do not stop the supply with no cut.\n * - The result is `undefined` when the search passes its budget, or when the sets of cuts are more than `maxSets`.\n *\n * @param stack - The base stack\n * @param supply - The part of the supply of a draw\n * @param parts - The part of each cut that counts\n * @param down - The parts that are down for the full event\n * @param maxSets - The largest count of sets in one step of the search, and of the sets of cuts (`maxSets` of `stopSets`)\n */\nexport function stackStops(stack: Stack, supply: string, parts: readonly string[], down: readonly string[] = [], maxSets: number = DEFAULT_MAX_SETS): number[][] | undefined {\n const cutsOf = new Map<string, number[]>();\n for (const [index, part] of parts.entries()) cutsOf.set(part, [...(cutsOf.get(part) ?? []), index]);\n const own = (cutsOf.get(supply) ?? []).map((index) => [index]);\n const among = [...cutsOf.keys()].filter((part) => part !== supply);\n const found = stopSets(stack, supply, { down, among, size: among.length, maxSets });\n if (found.kind === \"budget\") return undefined;\n // The empty set: the supply is not in the stack, or it does not work in the base stack.\n // In both, `stopped` of the core does not count it as stopped, so only a cut of the supply stops it.\n if (found.sets.some((set) => set.length === 0)) return own;\n const out = [...own];\n for (const set of found.sets) {\n // Each choice of one cut for each part of the set is a minimal set of cuts.\n let choices: number[][] = [[]];\n for (const part of set) {\n const cuts = cutsOf.get(part) ?? [];\n if (choices.length * cuts.length + out.length > maxSets) return undefined;\n choices = choices.flatMap((choice) => cuts.map((cut) => [...choice, cut]));\n }\n out.push(...choices.map((choice) => choice.sort((x, y) => x - y)));\n }\n return out.sort(byMask);\n}\n\n/** The order of `minimalStops`: the smaller set first, then the set whose largest different index is smaller. */\nfunction byMask(a: readonly number[], b: readonly number[]): number {\n if (a.length !== b.length) return a.length - b.length;\n for (let index = a.length - 1; index >= 0; index -= 1) {\n const difference = (a[index] ?? 0) - (b[index] ?? 0);\n if (difference !== 0) return difference;\n }\n return 0;\n}\n","import { type OrderedRing, pathSetReliability, stronglyConnectedComponents } from \"@mark1russell7/collections/graph\";\nimport { dateOfDay, dayNumber, DEFAULT_MAX_SETS, neededParts, survivalAt, weakestBound, type CutBound, type PathOptions } from \"@mark1russell7/system-stack\";\nimport { bestEndurance } from \"./best.ts\";\nimport { caseDraws, caseStopped, enduranceOf, type CaseOptions } from \"./endurance.ts\";\nimport type { CaseCuts, Draw, DrawEndurance, Endurance, EnduranceLayer, IsoDate, Prior, Survival } from \"./layer.ts\";\nimport { stackStops } from \"./stops.ts\";\n\n// The shortfall: the user-days in which a draw does not get its need, for one case and for one year.\n\n/** The read of a curve at a time is in the core since system-stack 0.1.13. This package gives it again, so its API does not change. */\nexport { survivalAt };\n\n/**\n * This function gives the expected days of a cut after a time, up to a horizon: `E[max(0, min(D, to) - from)]`.\n * It is the area under the curve from `from` to `to`. The curve is linear between its points, so the area is exact.\n * With no horizon, the area goes to the end of the curve.\n */\nexport function tailDays(curve: Survival, from: number, to: number = Infinity): number {\n let area = 0;\n for (let index = 1; index < curve.length; index += 1) {\n const [t0] = curve[index - 1] ?? [0, 1];\n const [t1] = curve[index] ?? [0, 0];\n const start = Math.max(t0, from);\n const end = Math.min(t1, to);\n if (start < end) area += ((survivalAt(curve, start) + survivalAt(curve, end)) / 2) * (end - start);\n }\n return area;\n}\n\n/**\n * This function gives the days of a cut with the survival `curve` that a draw does not hold, up to the horizon (M2-grow).\n * It is `tailDays` from the days of the draw, less `tailDays` over each span in which a harvest feeds the draw again.\n *\n * @param curve - The survival of the stop of the draw\n * @param held - The days and the fed spans of the draw, from `enduranceOf`\n * @param horizon - The horizon in days. The default is no horizon.\n */\nexport function heldTail(curve: Survival, held: Pick<DrawEndurance, \"days\" | \"again\">, horizon: number = Infinity): number {\n let short = tailDays(curve, held.days, horizon);\n for (const span of held.again ?? []) short -= tailDays(curve, span.from, Math.min(span.to, horizon));\n return Math.max(0, short);\n}\n\n/**\n * The options of a shortfall: the stack or the parts that are also down, as for `enduranceOf`, and a horizon.\n * With a horizon of `h` days, the shortfall counts only the first `h` days of each cut. A draw that holds `h` days has no shortfall.\n * Thus a plan can aim at a target, for example 14 days and then 90 days.\n */\n/**\n * The options of `stopCurves`. With a stack, `maxSets` is the budget of the search of the needs (`stopSets` of the core).\n * When the search passes it, `minimalStops` gives the sets.\n */\nexport interface StopCurveOptions extends Pick<CaseOptions, \"stack\" | \"down\">, Pick<PathOptions, \"maxSets\"> {\n /** The budget of `independentStop` for the curve of each draw, a whole number from 1. The default is `INDEPENDENT_MAX_WORK`. */\n readonly maxWork?: number | undefined;\n}\n\nexport interface ShortfallOptions extends StopCurveOptions {\n /** The horizon in days, more than 0. The default is no horizon. */\n readonly horizon?: number | undefined;\n}\n\nfunction horizonOf(options: ShortfallOptions): number {\n const horizon = options.horizon ?? Infinity;\n if (!(horizon > 0)) throw new RangeError(`The horizon ${String(options.horizon)} is not a number of days more than 0.`);\n return horizon;\n}\n\nfunction budgetsOf(options: StopCurveOptions): { readonly maxSets: number; readonly maxWork: number } {\n const maxSets = options.maxSets ?? DEFAULT_MAX_SETS;\n if (!Number.isInteger(maxSets) || maxSets < 1) throw new RangeError(`The option maxSets is ${String(options.maxSets)}: it is not a whole number from 1.`);\n const maxWork = options.maxWork ?? INDEPENDENT_MAX_WORK;\n if (!Number.isInteger(maxWork) || maxWork < 1) throw new RangeError(`The option maxWork is ${String(options.maxWork)}: it is not a whole number from 1.`);\n return { maxSets, maxWork };\n}\n\n/**\n * This function gives the days at which the chance of the curve falls to `chance`. With `0.1`, it is the 90th percentile of the duration.\n * When the curve does not fall to `chance`, the result is `Infinity`.\n */\nexport function survivalQuantile(curve: Survival, chance: number): number {\n for (let index = 1; index < curve.length; index += 1) {\n const [t0, p0] = curve[index - 1] ?? [0, 1];\n const [t1, p1] = curve[index] ?? [0, 0];\n if (p0 <= chance) return t0;\n if (p1 <= chance) return t0 + ((p0 - chance) * (t1 - t0)) / (p0 - p1);\n }\n return Infinity;\n}\n\n/** This function gives the chance that a case reaches its place one or more times in one year: `1 - exp(-perYear * reach)`. */\nexport function yearChance(prior: Prior): number {\n return 1 - Math.exp(-prior.perYear * prior.reach);\n}\n\n/** This function gives the expected count of the events of a case at its place in one year: `perYear * reach`. */\nexport function yearRate(prior: Prior): number {\n return prior.perYear * prior.reach;\n}\n\n/** This function gives the times at which a curve of the result can bend: each point of each curve, and each crossing of two curves. */\nfunction bendTimes(curves: readonly Survival[]): number[] {\n const times = [...new Set(curves.flatMap((curve) => curve.map(([days]) => days)))].sort((x, y) => x - y);\n const out = new Set(times);\n for (let index = 1; index < times.length; index += 1) {\n const t0 = times[index - 1] ?? 0;\n const t1 = times[index] ?? 0;\n for (const [i, a] of curves.entries()) {\n for (const b of curves.slice(i + 1)) {\n const d0 = survivalAt(a, t0) - survivalAt(b, t0);\n const d1 = survivalAt(a, t1) - survivalAt(b, t1);\n if (d0 * d1 < 0) out.add(t0 + ((t1 - t0) * d0) / (d0 - d1));\n }\n }\n }\n return [...out].sort((x, y) => x - y);\n}\n\n/**\n * This function makes a survival curve from a chance at each time. It stops at the first chance of 0, and it removes an increase of rounding.\n *\n * @throws RangeError when the chance at the last time is more than 0, as for curves that do not end at a chance of 0\n */\nfunction curveFrom(times: readonly number[], chanceAt: (days: number) => number): Survival {\n const out: [number, number][] = [];\n for (const days of times) {\n const chance = Math.min(out[out.length - 1]?.[1] ?? 1, chanceAt(days));\n out.push([days, chance]);\n if (chance === 0) return out;\n }\n throw new RangeError(\"The curves do not fall to a chance of 0 at their last point.\");\n}\n\n/**\n * This function gives the curve of a stop of some cuts when one event makes each cut longer together.\n * At each time, the chance is the largest `s` at which the cuts with a chance of `s` or more stop the supply.\n *\n * - When any one cut stops the supply, the result is the largest chance of the curves (`longestStop`).\n * - When the supply needs `any` of two parts, the stop ends with the shorter of the two cuts.\n * - Between two times of `bendTimes` the order of the curves does not change. So the result is linear between its points.\n * - When no set of cuts stops the supply, the result is `[[0, 0]]`. This curve does not start at `[0, 1]`, so `checkEndurance` refuses it.\n *\n * The result is not a limit. When the cuts are independent, a stop of two cuts in series can be longer. A stop through a need of `any` can be shorter.\n *\n * @param curves - The curves of the cuts, each one good for `checkEndurance`\n * @param stops - This function tells if the cuts of a list of indexes stop the supply. A larger list stops it when a smaller list does.\n * @throws RangeError when a curve does not end at a chance of 0\n */\nexport function eventStop(curves: readonly Survival[], stops: (cuts: readonly number[]) => boolean): Survival {\n return curveFrom(bendTimes(curves), (days) => {\n const chances = curves.map((curve) => survivalAt(curve, days));\n for (const level of [...new Set(chances)].sort((x, y) => y - x)) {\n if (stops(chances.flatMap((chance, index) => (chance >= level ? [index] : [])))) return level;\n }\n return 0;\n });\n}\n\n/**\n * This function gives the curve of the longest of some stops: at each time, the largest chance of the curves.\n * It is `eventStop` when any one cut stops the supply.\n *\n * @param curves - The curves, each one good for `checkEndurance`\n * @throws RangeError when there is no curve, or when a curve does not end at a chance of 0\n */\nexport function longestStop(curves: readonly Survival[]): Survival {\n const first = curves[0];\n if (first === undefined) throw new RangeError(\"longestStop needs one or more curves.\");\n return curves.length === 1 ? first : eventStop(curves, (cuts) => cuts.length > 0);\n}\n\n/**\n * The largest count of cuts for which `minimalStops` examines each set, and for which `independentStop` adds the chance of each state.\n * With a stack, `stopCurves` finds the minimal sets from the needs, so a larger count of cuts can have exact sets.\n */\nexport const MINIMAL_STOP_CUTS = 12;\n\n/**\n * This function gives the minimal sets of cuts that stop the supply: each set stops it, and no smaller part of a set stops it.\n * With more than `MINIMAL_STOP_CUTS` cuts, the result is `undefined`.\n */\nexport function minimalStops(count: number, stops: (cuts: readonly number[]) => boolean): number[][] | undefined {\n if (count > MINIMAL_STOP_CUTS) return undefined;\n const found: number[][] = [];\n const masks: number[] = [];\n const all = Array.from({ length: 1 << count }, (_, mask) => mask).sort((x, y) => popCount(x) - popCount(y) || x - y);\n for (const mask of all) {\n if (mask === 0 || masks.some((other) => (other & mask) === other)) continue;\n const cuts = Array.from({ length: count }, (_, index) => index).filter((index) => (mask >> index) & 1);\n if (!stops(cuts)) continue;\n masks.push(mask);\n found.push(cuts);\n }\n return found;\n}\n\nfunction popCount(mask: number): number {\n let total = 0;\n for (let rest = mask; rest > 0; rest &= rest - 1) total += 1;\n return total;\n}\n\n/**\n * This function gives an upper limit of the curve of a stop for each dependence of the cuts.\n * At each time it is `min(1, sum over the minimal sets of the smallest chance of the set)`.\n * With no minimal sets, as for too many cuts, it is `min(1, sum of the chances)`.\n *\n * @param curves - The curves of the cuts\n * @param sets - The minimal sets of `minimalStops`, or `undefined`\n * @throws RangeError when a curve does not end at a chance of 0\n */\nexport function upperStop(curves: readonly Survival[], sets: readonly (readonly number[])[] | undefined): Survival {\n const groups = sets ?? curves.map((_, index) => [index]);\n const sum = (days: number): number => groups.reduce((total, set) => total + Math.min(...set.map((index) => survivalAt(curves[index] ?? [], days))), 0);\n // The sum is linear between two times of bendTimes. A point where it falls through 1 is a bend of min(1, sum).\n const times = bendTimes(curves);\n const bends = new Set(times);\n for (let index = 1; index < times.length; index += 1) {\n const t0 = times[index - 1] ?? 0;\n const t1 = times[index] ?? 0;\n const s0 = sum(t0) - 1;\n const s1 = sum(t1) - 1;\n if (s0 * s1 < 0) bends.add(t0 + ((t1 - t0) * s0) / (s0 - s1));\n }\n return curveFrom([...bends].sort((x, y) => x - y), (days) => Math.min(1, sum(days)));\n}\n\n/** The largest difference between `independentStop` and the true chance of a stop of independent cuts, at each time. */\nexport const INDEPENDENT_TOLERANCE = 1e-6;\n\n/**\n * The default budget of `independentStop` for its groups of more than `MINIMAL_STOP_CUTS` cuts.\n * The budget counts the steps of the expansion times the count of points of the curve.\n * It is near the work of the sum over the states of 12 cuts.\n */\nexport const INDEPENDENT_MAX_WORK: number = 2 ** 26;\n\n/**\n * This function gives the curve of a stop of some cuts when the cuts are independent.\n * At each time `t`, the supply is stopped when the cuts that are still on contain a minimal set.\n * Its chance is a sum over each set of cuts that stops the supply.\n * Each term is the product of `s(t)` for the cuts that are on, and of `1 - s(t)` for the other cuts.\n *\n * - When any one cut stops the supply, the result is `1 - prod(1 - s)`. It is not less than the longest cut (`eventStop`).\n * - When the supply needs `any` of two parts, the stop of the two is `s1 * s2`. It is not more than the shorter cut.\n * - The result is not more than `upperStop` of the same sets, because `upperStop` is a limit for each dependence.\n * - Between two points of the curves the chance is a polynomial, not a line. The function splits each such segment into equal pieces.\n * The chance is linear in each `s`, and each mixed second derivative is between -1 and 1.\n * Thus `|f''| <= (sum |s'|)^2 - sum s'^2`, and the line of a piece of length `h` is within `h^2 |f''| / 8` of the chance.\n * The count of pieces keeps each line within `INDEPENDENT_TOLERANCE`. With a margin of 10 %, the count of points is less than `n / sqrt(7.2 * INDEPENDENT_TOLERANCE)` plus the segments, for `n` cuts.\n *\n * - Up to `MINIMAL_STOP_CUTS` cuts in the sets, the function adds the chance of each of the 2 to the power of that count of states.\n * - Two groups of cuts that share no set are independent, so the chance that the supply works is the product over the groups.\n * For example, 20 stages of 2 feeds give 20 groups of 2 cuts.\n * - In a group of more than `MINIMAL_STOP_CUTS` cuts, it uses the Shannon expansion of `pathSetReliability` of collections.\n * The expansion merges two states with the same sets left, and it drops a set that holds another set.\n * - The expansion is exponential in the worst case. The groups share one budget, `maxWork`.\n * When the steps of the expansions times the count of points of the curve pass it, the result is `undefined`.\n *\n * @param curves - The curves of the cuts, each one good for `checkEndurance`\n * @param sets - The minimal sets of the cuts. With `undefined`, as for no minimal sets, the result is `undefined`. With no sets, it is `[[0, 0]]`\n * @param maxWork - The budget of the expansions of the groups of more than `MINIMAL_STOP_CUTS` cuts, a whole number from 1. The default is `INDEPENDENT_MAX_WORK`\n * @throws RangeError when a curve does not end at a chance of 0, or for a bad `maxWork`\n */\nexport function independentStop(curves: readonly Survival[], sets: readonly (readonly number[])[] | undefined, maxWork: number = INDEPENDENT_MAX_WORK): Survival | undefined {\n if (!Number.isInteger(maxWork) || maxWork < 1) throw new RangeError(`The budget maxWork is ${String(maxWork)}: it is not a whole number from 1.`);\n if (sets === undefined) return undefined;\n // With no set, no cuts stop the supply, as for `eventStop` and `upperStop`.\n if (sets.length === 0) return [[0, 0]];\n // Only the cuts of a set change the chance. Their place in `used` is their index in the sets of the cuts that count.\n const used = [...new Set(sets.flat())].sort((x, y) => x - y);\n const usedCurves = used.map((index) => curves[index] ?? []);\n const usedSets = sets.map((set) => set.map((index) => used.indexOf(index)));\n const points = independentPoints(usedCurves);\n // Two groups of cuts that share no set are independent: the supply works when it works in each group.\n const groupChances: ((days: number) => number)[] = [];\n // The expansions of all groups share one budget.\n let work = maxWork;\n for (const group of cutGroups(used.length, usedSets)) {\n const curvesOf = group.map((index) => usedCurves[index] ?? []);\n const setsOf = usedSets.filter((set) => group.includes(set[0] ?? -1)).map((set) => set.map((index) => group.indexOf(index)));\n // Up to MINIMAL_STOP_CUTS cuts, the sum over the states is exact with a fixed cost. Past them, the expansion is exact within its budget.\n if (group.length <= MINIMAL_STOP_CUTS) {\n groupChances.push(stateChance(curvesOf, setsOf));\n continue;\n }\n const expanded = expandedChances(curvesOf, setsOf, points, work);\n if (expanded === undefined) return undefined;\n work -= expanded.steps * points.length;\n const chanceOf = new Map(points.map((days, index) => [days, expanded.chances[index] ?? 0]));\n groupChances.push((days) => {\n const chance = chanceOf.get(days);\n if (chance === undefined) throw new Error(`The expansion has no chance at ${String(days)} days.`);\n return chance;\n });\n }\n // With one group, the chance of the group is the result, with no rounding of 1 - (1 - chance).\n const [only] = groupChances;\n if (groupChances.length === 1 && only !== undefined) return curveFrom(points, only);\n return curveFrom(points, (days) => Math.min(1, Math.max(0, 1 - groupChances.reduce((works, chanceAt) => works * (1 - chanceAt(days)), 1))));\n}\n\n/** The groups of the cuts `0` to `count - 1`: two cuts are in one group when a chain of sets joins them. Each set has its cuts in one group. */\nfunction cutGroups(count: number, sets: readonly (readonly number[])[]): number[][] {\n const next = Array.from({ length: count }, () => new Set<number>());\n // A cycle through the cuts of each set joins them both ways, so the strongly connected components are the groups.\n for (const set of sets) for (const [at, index] of set.entries()) next[index]?.add(set[(at + 1) % set.length] ?? index);\n return stronglyConnectedComponents(\n Array.from({ length: count }, (_, index) => index),\n (index) => next[index] ?? [],\n );\n}\n\n/** The times of `independentStop`: the points of the curves, and the pieces that keep each line within `INDEPENDENT_TOLERANCE`. */\nfunction independentPoints(curves: readonly Survival[]): number[] {\n const times = [...new Set(curves.flatMap((curve) => curve.map(([days]) => days)))].sort((x, y) => x - y);\n const points: number[] = [];\n for (const [index, t1] of times.entries()) {\n const t0 = times[index - 1];\n if (t0 !== undefined) {\n const h = t1 - t0;\n const slopes = curves.map((curve) => Math.abs(survivalAt(curve, t1) - survivalAt(curve, t0)) / h);\n const sum = slopes.reduce((total, slope) => total + slope, 0);\n const bound = Math.max(0, sum * sum - slopes.reduce((total, slope) => total + slope * slope, 0));\n // A margin of 10 % keeps the rounding of the chance under the tolerance.\n const pieces = Math.ceil(h * Math.sqrt(bound / (8 * 0.9 * INDEPENDENT_TOLERANCE)));\n for (let piece = 1; piece < pieces; piece += 1) {\n const days = t0 + (h * piece) / pieces;\n // Two times that are next to each other as floats have no time between them.\n if (days > (points[points.length - 1] ?? t0) && days < t1) points.push(days);\n }\n }\n points.push(t1);\n }\n return points;\n}\n\n/** The chance of a stop at a time, as the sum over each state of `MINIMAL_STOP_CUTS` cuts or fewer. Bit k of a state is 1 when cut k is on. */\nfunction stateChance(curves: readonly Survival[], sets: readonly (readonly number[])[]): (days: number) => number {\n const setMasks = sets.map((set) => set.reduce((mask, index) => mask | (1 << index), 0));\n const stopping = Array.from({ length: 1 << curves.length }, (_, mask) => setMasks.some((set) => (set & mask) === set));\n const states = new Float64Array(1 << curves.length);\n return (days) => {\n // The chance of each state of the cuts, one cut at a time.\n states[0] = 1;\n let length = 1;\n for (const curve of curves) {\n const on = survivalAt(curve, days);\n for (let mask = 0; mask < length; mask += 1) {\n const chance = states[mask] ?? 0;\n states[mask + length] = chance * on;\n states[mask] = chance * (1 - on);\n }\n length *= 2;\n }\n let total = 0;\n for (let mask = 0; mask < length; mask += 1) if (stopping[mask]) total += states[mask] ?? 0;\n return Math.min(1, Math.max(0, total));\n };\n}\n\n/** The count of times in one expansion of `expandedChances`: the length of the vectors of its ring. */\nconst EXPANSION_WIDTH = 64;\n\n/**\n * The ring of the vectors of `width` chances, one for each time, for `pathSetReliability` of collections.\n * Each operation is on each time alone. In the order, `a` is less than `b` when it is less or equal at each time, and not equal.\n */\nfunction vectorRing(width: number): OrderedRing<Float64Array> {\n const zip = (a: Float64Array, b: Float64Array, op: (x: number, y: number) => number): Float64Array => {\n const out = new Float64Array(width);\n for (let index = 0; index < width; index += 1) out[index] = op(a[index] ?? 0, b[index] ?? 0);\n return out;\n };\n return {\n zero: new Float64Array(width),\n one: new Float64Array(width).fill(1),\n add: (a, b) => zip(a, b, (x, y) => x + y),\n sub: (a, b) => zip(a, b, (x, y) => x - y),\n mul: (a, b) => zip(a, b, (x, y) => x * y),\n compare: (a, b) => {\n let less = false;\n let more = false;\n for (let index = 0; index < width; index += 1) {\n const [x, y] = [a[index] ?? 0, b[index] ?? 0];\n if (x < y) less = true;\n else if (x > y) more = true;\n else if (x !== y) return Number.NaN;\n }\n return less ? (more ? Number.NaN : -1) : more ? 1 : 0;\n },\n };\n}\n\n/**\n * The chance of a stop at each point, from the Shannon expansion of `pathSetReliability`. A set works when each of its cuts is on.\n * One call gives `EXPANSION_WIDTH` points. When the steps of one expansion times the count of points pass `maxWork`, the result is `undefined`.\n * Else `steps` is the count of steps of one expansion.\n */\nfunction expandedChances(\n curves: readonly Survival[],\n sets: readonly (readonly number[])[],\n points: readonly number[],\n maxWork: number,\n): { readonly chances: number[]; readonly steps: number } | undefined {\n const maxSteps = Math.floor(maxWork / points.length);\n if (maxSteps < 1) return undefined;\n const out: number[] = [];\n let steps = 0;\n for (let start = 0; start < points.length; start += EXPANSION_WIDTH) {\n const times = points.slice(start, start + EXPANSION_WIDTH);\n const chances = curves.map((curve) => Float64Array.from(times, (days) => survivalAt(curve, days)));\n const result = pathSetReliability(sets, chances, vectorRing(times.length), { maxSteps });\n // Each call has the same sets, so the first call tells if the expansion is in the budget.\n if (result.kind === \"budget\") return undefined;\n steps = result.steps;\n for (const chance of result.value) out.push(Math.min(1, Math.max(0, chance)));\n }\n return { chances: out, steps };\n}\n\n/**\n * The curves of the stop of a draw. `event` is for one event that makes each cut longer together, and `independent` is for independent cuts.\n * `upper` is an upper limit for each dependence.\n */\nexport interface StopCurves {\n readonly event: Survival;\n /** The stop when the cuts are independent (`independentStop`). When `independentUpper` is true, it is `upper`. */\n readonly independent: Survival;\n readonly upper: Survival;\n /**\n * This is true when `upper` is the sum of the curves of the cuts that count, because the query has no minimal sets.\n * With a stack, the search of the needs passed its budget. With no stack, more than `MINIMAL_STOP_CUTS` cuts count.\n */\n readonly coarse: boolean;\n /** This is true when `independent` is `upper`: `coarse` is true, or the expansion of `independentStop` passed its budget. */\n readonly independentUpper: boolean;\n /**\n * The weakest bound (`weakestBound` of the core) of the curves of the cuts that the stop uses. Since 0.8.4.\n * With minimal sets, the stop uses the cuts of the sets. With no minimal sets, it uses each cut with a curve.\n * Each of the three curves does not decrease when a cut lasts longer, so it has this bound.\n */\n readonly bound: CutBound;\n}\n\n/** This function gives the parts of the stack that are down for a list of cut indexes. A case uses one memo for each of its draws. */\ntype StoppedOf = (cuts: readonly number[]) => ReadonlySet<string>;\n\nfunction stoppedMemo(caseCuts: CaseCuts, options: Pick<CaseOptions, \"stack\" | \"down\">): StoppedOf {\n const memo = new Map<string, ReadonlySet<string>>();\n return (cuts) => {\n const key = cuts.join(\",\");\n let found = memo.get(key);\n if (found === undefined) {\n found = caseStopped({ ...caseCuts, cuts: cuts.flatMap((index) => caseCuts.cuts[index] ?? []) }, options);\n memo.set(key, found);\n }\n return found;\n };\n}\n\n/** This function gives the parts whose cut can stop a supply: the supply, and each part that it needs through the stack. */\nfunction supplyReach(supply: string, options: Pick<CaseOptions, \"stack\">): Set<string> {\n const reach = options.stack === undefined ? new Set<string>() : neededParts(options.stack, supply);\n reach.add(supply);\n return reach;\n}\n\n/** The curves of the stop of a draw, and the indexes in `CaseCuts.cuts` of the cuts that the stop uses. */\ninterface StopRead {\n readonly curves: StopCurves;\n readonly used: readonly number[];\n}\n\nfunction stopReadWith(caseCuts: CaseCuts, draw: Draw, options: StopCurveOptions, stoppedOf: StoppedOf): StopRead | undefined {\n const reach = supplyReach(draw.supply, options);\n const relevant = caseCuts.cuts.flatMap((cut, index) => (reach.has(cut.part) ? [index] : []));\n const stops = (cuts: readonly number[]): boolean => stoppedOf(cuts.map((index) => relevant[index] ?? -1)).has(draw.supply);\n if (stops([])) return undefined;\n if (!stops(relevant.map((_, index) => index))) return undefined;\n const given = relevant.map((index) => caseCuts.cuts[index]?.duration);\n // With a stack, the needs give the minimal sets. When their search passes its budget, the sets of each list of cuts are the check.\n const parts = relevant.map((index) => caseCuts.cuts[index]?.part ?? \"\");\n const structural = options.stack === undefined ? undefined : stackStops(options.stack, draw.supply, parts, options.down, budgetsOf(options).maxSets);\n const sets = structural ?? minimalStops(given.length, stops);\n // The stop has no curve when a cut with no curve can be part of it. With no minimal sets, the query cannot tell.\n const unsourced = given.flatMap((curve, index) => (curve === undefined ? [index] : []));\n if (unsourced.length > 0 && (sets === undefined || sets.some((set) => set.some((index) => unsourced.includes(index))))) return undefined;\n // A cut with no curve is in no minimal set here, so it does not change a stop. The curves do not include it.\n const kept = given.flatMap((curve, index) => (curve === undefined ? [] : [index]));\n const curves = kept.map((index) => given[index] ?? []);\n const keptStops = (cuts: readonly number[]): boolean => stops(cuts.map((index) => kept[index] ?? -1));\n const keptSets = sets?.map((set) => set.map((index) => kept.indexOf(index)));\n const upper = upperStop(curves, keptSets);\n const independent = independentStop(curves, keptSets, budgetsOf(options).maxWork);\n // A cut in no minimal set does not change a stop, so its bound does not weaken the bound of the stop.\n const used = sets === undefined ? kept : kept.filter((index) => sets.some((set) => set.includes(index)));\n const bound = weakestBound(used.map((index) => caseCuts.cuts[relevant[index] ?? -1]?.bound ?? \"law\"));\n return {\n curves: { event: eventStop(curves, keptStops), independent: independent ?? upper, upper, coarse: keptSets === undefined, independentUpper: independent === undefined, bound },\n used: used.map((index) => relevant[index] ?? -1),\n };\n}\n\nfunction stopCurvesWith(caseCuts: CaseCuts, draw: Draw, options: StopCurveOptions, stoppedOf: StoppedOf): StopCurves | undefined {\n return stopReadWith(caseCuts, draw, options, stoppedOf)?.curves;\n}\n\n/**\n * This function gives the curves of the duration of the stop of a draw, or `undefined` when the query has no curve.\n *\n * - A set of cuts stops the supply when the supply cannot work without the cut parts, through the needs of the stack.\n * - Only the cuts of the supply, and of the parts that it needs through the stack, count. Another cut does not change the curves.\n * - The parts of `down` are down for the full event. When they stop the supply with no cut, the query has no curve.\n * - With a stack, the minimal sets come from the paths of the needs (`stopSets` of the core), so the count of cuts has no limit of `MINIMAL_STOP_CUTS`.\n * When that search passes its budget (the option `maxSets`), `minimalStops` examines each set of up to `MINIMAL_STOP_CUTS` cuts.\n * - A cut with no `duration` gives no curve when it is in a minimal set, or when the query has no minimal sets.\n * - `event` is `eventStop`. `independent` is `independentStop`, and `upper` is `upperStop`, over the minimal sets of the cuts that count.\n * - With no minimal sets, `upper` is the sum of the curves, `independent` is `upper`, and `coarse` is true.\n * - When the expansion of `independentStop` passes its budget, `independent` is `upper`, and `independentUpper` is true.\n * - `bound` is the weakest bound of the curves of the cuts that the stop uses. A cut with no `bound` has a law.\n */\nexport function stopCurves(caseCuts: CaseCuts, draw: Draw, options: StopCurveOptions = {}): StopCurves | undefined {\n budgetsOf(options);\n return stopCurvesWith(caseCuts, draw, options, stoppedMemo(caseCuts, options));\n}\n\n/**\n * This function gives the cuts that the stop of a draw uses, as indexes in `caseCuts.cuts`, or `undefined` when `stopCurves` has no curve. Since 0.8.27.\n *\n * - A used cut has a curve, and it is in a minimal set of cuts that stops the supply. With no minimal sets, each cut with a curve is used.\n * - With one used cut, each curve of `stopCurves` is the curve of that cut. `enduranceSensitivity` reads the interval of a change of the chance from it.\n *\n * @param caseCuts - The case\n * @param draw - The draw\n * @param options - The stack or the parts that are also down, and the budgets: as for `stopCurves`\n * @throws RangeError for a bad `maxSets` or `maxWork`\n */\nexport function stopCuts(caseCuts: CaseCuts, draw: Draw, options: StopCurveOptions = {}): readonly number[] | undefined {\n budgetsOf(options);\n return stopReadWith(caseCuts, draw, options, stoppedMemo(caseCuts, options))?.used;\n}\n\n/** The shortfall of each level, in user-days, and the draws that the query cannot read. */\nexport interface Shortfall {\n /**\n * The user-days of each level of the layer, when one event makes each cut longer together. The query does not add two levels.\n * This value is not a limit. The true value can be more or less. `upper` is the limit.\n */\n readonly levels: Readonly<Record<string, number>>;\n /** The user-days of each level when the cuts are independent (`StopCurves.independent`). This value is not more than `upper`. */\n readonly independent: Readonly<Record<string, number>>;\n /** The upper limit of the user-days of each level, for each dependence of the cuts. A gate of a high level can use it. */\n readonly upper: Readonly<Record<string, number>>;\n /**\n * The needs of the draws whose stop has no curve (`stopCurves`).\n * The query has no curve of their duration, so their shortfall is not in `levels`. A gate shows them as no read.\n */\n readonly unread: readonly string[];\n /** The needs of the draws whose `upper` is coarse (`StopCurves.coarse`). A gate on `upper` shows them. */\n readonly coarse: readonly string[];\n /** The needs of the draws whose `independent` is `upper` (`StopCurves.independentUpper`). A gate on `independent` shows them. */\n readonly independentUpper: readonly string[];\n /**\n * The bound of the shortfall: the weakest bound (`weakestBound` of the core) of the curves that the query uses. Since 0.8.4.\n * The shortfall does not decrease when a cut lasts longer. So with `upper`, each value is too high or equal, and with `lower` too low or equal.\n * With `none`, a value can be too high or too low.\n *\n * A draw in `unread` and a case that adds 0 do not change the bound. With no curve, the bound is `law`.\n * The bound is for each of `levels`, `independent` and `upper`, each with its own rule of the dependence of the cuts.\n */\n readonly bound: CutBound;\n}\n\nfunction zeroLevels(layer: EnduranceLayer): Record<string, number> {\n return Object.fromEntries(layer.levels.map((level) => [level, 0]));\n}\n\n/**\n * This function gives the shortfall of one event of a case: for each draw, `E[max(0, min(D, h) - T)] * users`.\n * `T` is the endurance of the draw, `D` is the duration of the stop of its supply (`stopCurves`), and `h` is the horizon.\n *\n * @param layer - The endurance layer\n * @param caseCuts - The case\n * @param endurance - The endurance of the case, from `enduranceOf`\n * @param options - The stack or the parts that are also down, as for `enduranceOf`, and the horizon\n * @throws RangeError when the horizon is not a number more than 0, or `maxSets` is not a whole number from 1\n */\nexport function caseShortfall(layer: EnduranceLayer, caseCuts: CaseCuts, endurance: Endurance, options: ShortfallOptions = {}): Shortfall {\n const horizon = horizonOf(options);\n budgetsOf(options);\n const levels = zeroLevels(layer);\n const independent = zeroLevels(layer);\n const upper = zeroLevels(layer);\n const unread: string[] = [];\n const coarse: string[] = [];\n const independentUpper: string[] = [];\n const bounds: CutBound[] = [];\n const stoppedOf = stoppedMemo(caseCuts, options);\n for (const draw of caseDraws(layer, caseCuts, caseStopped(caseCuts, options))) {\n const held = endurance.needs[draw.need];\n const curves = stopCurvesWith(caseCuts, draw, options, stoppedOf);\n if (held === undefined || curves === undefined) {\n unread.push(draw.need);\n continue;\n }\n if (curves.coarse) coarse.push(draw.need);\n if (curves.independentUpper) independentUpper.push(draw.need);\n bounds.push(curves.bound);\n const users = draw.users ?? 1;\n levels[draw.level] = (levels[draw.level] ?? 0) + heldTail(curves.event, held, horizon) * users;\n independent[draw.level] = (independent[draw.level] ?? 0) + heldTail(curves.independent, held, horizon) * users;\n upper[draw.level] = (upper[draw.level] ?? 0) + heldTail(curves.upper, held, horizon) * users;\n }\n return { levels, independent, upper, unread, coarse, independentUpper, bound: weakestBound(bounds) };\n}\n\n/**\n * The share of the stores in a case. `take` is the take order of `enduranceOf`. `best` is the leximin share of\n * `bestEndurance`, level by level.\n */\nexport type Share = \"take\" | \"best\";\n\n/** The shares, with the default first. */\nexport const SHARES: readonly Share[] = [\"take\", \"best\"];\n\n/** This function gives the share of the options. The default is `take`. */\nfunction shareOf(options: { readonly share?: Share | undefined }): Share {\n const share = options.share ?? \"take\";\n if (!SHARES.includes(share)) throw new RangeError(`The share ${String(options.share)} is not ${SHARES.join(\" or \")}.`);\n return share;\n}\n\n/** This function gives the endurance of a case with a share: `enduranceOf` for `take`, `bestEndurance` with the horizon for `best`. */\nfunction shareEndurance(layer: EnduranceLayer, caseCuts: CaseCuts, options: CaseOptions & ShortfallOptions, share: Share): Endurance {\n return share === \"best\" ? bestEndurance(layer, caseCuts, options) : enduranceOf(layer, caseCuts, options);\n}\n\n/** The options of `yearShortfall`: the date, the stack or the parts that are also down, the horizon and the share. */\nexport interface YearShortfallOptions extends CaseOptions, ShortfallOptions {\n /**\n * The share of the stores in each case. The default `take` gives the endurance from `enduranceOf`. With `best`,\n * the endurance comes from `bestEndurance`, and the horizon of the shortfall is the horizon of the share. Thus a\n * draw at the horizon keeps back only the horizon times its demand, and the lower levels get the rest.\n */\n readonly share?: Share | undefined;\n /**\n * The count of the start dates of the events of each case, for a layer with a converter with a season (M2-grow). A\n * whole number from 1. The default is `YEAR_STARTS`. The start dates are at equal steps over one year from `at`. The\n * shortfall of a case is the mean of its shortfalls at these dates, because an event can start on each day of the\n * year. A layer with no season does not use it.\n */\n readonly starts?: number | undefined;\n}\n\n/** The default count of the start dates of the events of a year, for a layer with a season: one in each month. */\nexport const YEAR_STARTS = 12;\n\n/** The user-days of each level for each curve of the stop: the three sums of a shortfall. Since 0.8.15. */\nexport type ShortfallDays = Pick<Shortfall, \"levels\" | \"independent\" | \"upper\">;\n\n/**\n * The range of the shortfall of one year from the intervals of the rates of its cases (`Prior.interval`). Since 0.8.15.\n * `low` puts the rate of each case at the low end of its interval, and `high` puts it at the high end.\n * Each end holds only for each case alone, so the two values are a range of the sampling error, not a joint interval.\n * The mean of a skewed law can be above the high end, so the expected value can be above `high`.\n */\nexport interface RateRange {\n /** The least level of the intervals of the cases in the sum. */\n readonly level: number;\n readonly low: ShortfallDays;\n readonly high: ShortfallDays;\n /** The cases in the sum with no interval of their rate. Their rate is at the two ends. */\n readonly without: readonly string[];\n}\n\n/** The part of one case in the shortfall of one year. */\nexport interface YearCase {\n readonly case: string;\n /** The expected count of the events of the case at the place in one year (`yearRate`). */\n readonly rate: number;\n /** The interval of `rate` from the interval of the prior, times its reach. A prior with no interval gives none. Since 0.8.15. */\n readonly rateInterval?: readonly [low: number, high: number] | undefined;\n /** The endurance of the case. With a season, it is the endurance at the first start date, `at`. */\n readonly endurance: Endurance;\n /** The shortfall of the case. With a season, it is the mean of the shortfalls at the start dates. */\n readonly shortfall: Shortfall;\n /** The shortfall at each start date, for a layer with a converter with a season (M2-grow). */\n readonly starts?: readonly YearStart[] | undefined;\n}\n\n/** The shortfall of a case for one start date of its event (M2-grow). */\nexport interface YearStart {\n readonly start: IsoDate;\n readonly shortfall: ShortfallDays;\n}\n\n/** The shortfall of one year at one place, with the part of each case. */\nexport interface YearShortfall extends Shortfall {\n readonly place: string;\n /** The part of each case. `rate` is the expected count of its events in one year. */\n readonly cases: readonly YearCase[];\n /** The range from the intervals of the rates. A year with no case with an interval has no range. Since 0.8.15. */\n readonly range?: RateRange | undefined;\n}\n\n/**\n * This function gives the shortfall of one year at one place.\n * It is the sum over the cases of the layer of the expected count of the events of each case times its shortfall.\n *\n * - The expected count of a case is `perYear * reach`, from the first prior of the case at the place. Thus the result is the expected user-days of one year.\n * - A case with no prior at the place is not in the sum.\n * - `unread` is the union of the needs that a case cannot read, in the order of the cases. `coarse` and `independentUpper` are unions too.\n * - `bound` is the weakest bound of the cases in the sum. A case with no prior, or with an expected count of 0, adds 0, so it does not change the bound.\n *\n * - With `share: \"best\"`, the endurance of each case comes from `bestEndurance` with the horizon of the shortfall.\n * - `range` is the same sum with the rate of each case at each end of its interval (`RateRange`).\n *\n * @param layer - The endurance layer, with its cases and priors\n * @param place - The place of the priors\n * @param options - The date, the stack or the parts that are also down, the horizon and the share\n * @throws RangeError for a bad date, horizon, `maxSets` or share: refer to `caseShortfall` and `enduranceOf`\n */\nexport function yearShortfall(layer: EnduranceLayer, place: string, options: YearShortfallOptions): YearShortfall {\n horizonOf(options);\n budgetsOf(options);\n const share = shareOf(options);\n const dates = startDates(layer, options);\n const levels = zeroLevels(layer);\n const independent = zeroLevels(layer);\n const upper = zeroLevels(layer);\n const unread: string[] = [];\n const coarse: string[] = [];\n const independentUpper: string[] = [];\n const cases: YearCase[] = [];\n const bounds: CutBound[] = [];\n const low = { levels: zeroLevels(layer), independent: zeroLevels(layer), upper: zeroLevels(layer) };\n const high = { levels: zeroLevels(layer), independent: zeroLevels(layer), upper: zeroLevels(layer) };\n const without: string[] = [];\n let level = Infinity;\n for (const caseCuts of layer.cases ?? []) {\n const prior = (layer.priors ?? []).find((item) => item.case === caseCuts.case && item.place === place);\n if (prior === undefined) continue;\n const rate = yearRate(prior);\n // With a season, the case has one endurance and one shortfall for each start date, and its shortfall is their mean.\n const each = dates.map((start) => {\n const endurance = shareEndurance(layer, caseCuts, dates.length === 1 ? options : { ...options, start }, share);\n return { start, endurance, shortfall: caseShortfall(layer, caseCuts, endurance, options) };\n });\n const endurance = each[0]!.endurance;\n const shortfall = each.length === 1 ? each[0]!.shortfall : meanShortfall(layer, each.map((item) => item.shortfall));\n const starts = each.length === 1 ? {} : { starts: each.map((item) => ({ start: item.start, shortfall: { levels: item.shortfall.levels, independent: item.shortfall.independent, upper: item.shortfall.upper } })) };\n addDays({ levels, independent, upper }, shortfall, rate);\n const rateInterval = prior.interval === undefined ? undefined : ([prior.interval.low * prior.reach, prior.interval.high * prior.reach] as const);\n if (rateInterval === undefined) without.push(caseCuts.case);\n else level = Math.min(level, prior.interval?.level ?? level);\n addDays(low, shortfall, rateInterval?.[0] ?? rate);\n addDays(high, shortfall, rateInterval?.[1] ?? rate);\n for (const need of shortfall.unread) if (!unread.includes(need)) unread.push(need);\n for (const need of shortfall.coarse) if (!coarse.includes(need)) coarse.push(need);\n for (const need of shortfall.independentUpper) if (!independentUpper.includes(need)) independentUpper.push(need);\n if (rate > 0) bounds.push(shortfall.bound);\n cases.push({ case: caseCuts.case, rate, ...(rateInterval === undefined ? {} : { rateInterval }), endurance, shortfall, ...starts });\n }\n const range = Number.isFinite(level) ? { range: { level, low, high, without } } : {};\n return { place, levels, independent, upper, unread, coarse, independentUpper, bound: weakestBound(bounds), cases, ...range };\n}\n\n/**\n * This function gives the start dates of the events of a year: `at` alone for a layer with no converter with a season.\n * Otherwise `starts` dates at equal steps over 365 days from `at`.\n */\nfunction startDates(layer: EnduranceLayer, options: YearShortfallOptions): IsoDate[] {\n if (!(layer.converters ?? []).some((converter) => converter.season !== undefined)) return [options.at];\n const count = options.starts ?? YEAR_STARTS;\n if (!Number.isSafeInteger(count) || count < 1) throw new RangeError(`The option starts is ${String(options.starts)}: it is not a whole number from 1.`);\n const first = dayNumber(options.at);\n if (first === undefined) throw new RangeError(`The date \"${options.at}\" is not a date YYYY-MM-DD.`);\n return Array.from({ length: count }, (_, index) => dateOfDay(first + Math.floor((index * 365) / count)));\n}\n\n/** This function gives the mean of the shortfalls of one case at its start dates. The lists are unions, and the bound is the weakest. */\nfunction meanShortfall(layer: EnduranceLayer, list: readonly Shortfall[]): Shortfall {\n const days = { levels: zeroLevels(layer), independent: zeroLevels(layer), upper: zeroLevels(layer) };\n for (const shortfall of list) addDays(days, shortfall, 1 / list.length);\n const union = (pick: (shortfall: Shortfall) => readonly string[]): string[] => [...new Set(list.flatMap(pick))];\n return { ...days, unread: union((item) => item.unread), coarse: union((item) => item.coarse), independentUpper: union((item) => item.independentUpper), bound: weakestBound(list.map((item) => item.bound)) };\n}\n\n/** This function adds the user-days of a shortfall times a count of events to each sum of the days. */\nfunction addDays(days: { levels: Record<string, number>; independent: Record<string, number>; upper: Record<string, number> }, shortfall: ShortfallDays, count: number): void {\n for (const [level, value] of Object.entries(shortfall.levels)) days.levels[level] = (days.levels[level] ?? 0) + count * value;\n for (const [level, value] of Object.entries(shortfall.independent)) days.independent[level] = (days.independent[level] ?? 0) + count * value;\n for (const [level, value] of Object.entries(shortfall.upper)) days.upper[level] = (days.upper[level] ?? 0) + count * value;\n}\n\n/** The options of `caseOutlook`: the date, the stack or the parts that are also down, the horizon and the share. */\nexport type OutlookOptions = YearShortfallOptions;\n\n/** A value for each curve of the stop of a draw (`StopCurves`). */\nexport interface CurveValues {\n /** The value when one event makes each cut longer together. */\n readonly event: number;\n /** The value when the cuts are independent. */\n readonly independent: number;\n /** The value of the upper curve: the safe side for each dependence of the cuts. */\n readonly upper: number;\n}\n\n/** The chance and the shortfall of a draw at one end of the sampling bands of its cuts. Since 0.8.14. */\nexport interface BandValues {\n readonly lasts: CurveValues;\n readonly shortfall: CurveValues;\n}\n\n/**\n * The values of a draw at the two ends of the sampling bands of its cuts (`Cut.band`). Since 0.8.14.\n * `shorter` puts each cut at the low end of its band, and `longer` puts each cut at the high end.\n * Each end holds only pointwise, so the two values are a range of the sampling error, not a joint interval.\n */\nexport interface DrawBand {\n readonly shorter: BandValues;\n readonly longer: BandValues;\n}\n\n/** The outlook of one draw in one event of a case. */\nexport interface DrawOutlook {\n readonly need: string;\n readonly level: string;\n readonly supply: string;\n readonly users: number;\n /** The days that the stores give the draw (`DrawEndurance.days`). */\n readonly days: number;\n /** This is true when the draw holds to the horizon of a best share. */\n readonly atHorizon?: true;\n /**\n * The chance that the draw gets its need through the event: `P(min(D, h) <= T)`, for each curve of the stop.\n * `D` is the duration of the stop, `T` is `days` and `h` is the horizon. A draw that holds to the horizon has the chance 1.\n * The chance of `upper` is not more than the true chance, for each dependence of the cuts.\n */\n readonly lasts: CurveValues;\n /** The user-days of the shortfall in one event, `E[max(0, min(D, h) - T)] * users`, for each curve. */\n readonly shortfall: CurveValues;\n /** The bound of the curves of the stop (`StopCurves.bound`). */\n readonly bound: CutBound;\n /** This is true when the upper curve is coarse (`StopCurves.coarse`). */\n readonly coarse: boolean;\n /**\n * The values at the two ends of the sampling bands of the cuts, with the same days. Since 0.8.14.\n * It is missing when a cut that can be part of the stop has a curve and no band. Then the sampling error has no read.\n */\n readonly band?: DrawBand | undefined;\n}\n\n/** The outlook of one event of a case: the days, the chance and the shortfall of each draw. */\nexport interface CaseOutlook {\n readonly case: string;\n readonly title: string;\n readonly at: string;\n readonly share: Share;\n /** The horizon in days, or `undefined` for no horizon. */\n readonly horizon: number | undefined;\n /** Each draw whose supply the case stops and whose stop has a curve, in the order of the layer. */\n readonly draws: readonly DrawOutlook[];\n /** The needs of the draws whose supply the case does not stop. They get their need through the event. */\n readonly holds: readonly string[];\n /** The needs of the draws whose stop has no curve (`stopCurves`). They are no read, not a pass. */\n readonly unread: readonly string[];\n /** The weakest bound of the curves of `draws`. */\n readonly bound: CutBound;\n}\n\n/**\n * This function gives the outlook of one event of a case. For each draw, it gives the days, the chance that the\n * stores last through the stop, and the shortfall. A page of a place can show it for each case of its region.\n *\n * - The days come from the share of the stores: `enduranceOf` for `take`, `bestEndurance` with the horizon for `best`.\n * - The chance and the shortfall use the curves of `stopCurves`. They count the stop only up to the horizon.\n * - `upper` is the safe side: its chance is not more, and its shortfall is not less, than the true value for each dependence.\n * - `band` gives the same values with each cut at each end of its sampling band (`Cut.band`). The days do not change.\n *\n * @param layer - The endurance layer\n * @param caseCuts - The case\n * @param options - The date, the stack or the parts that are also down, the horizon and the share\n * @throws RangeError for a bad date, horizon, `maxSets` or share: refer to `caseShortfall` and `enduranceOf`\n */\nexport function caseOutlook(layer: EnduranceLayer, caseCuts: CaseCuts, options: OutlookOptions): CaseOutlook {\n const horizon = horizonOf(options);\n budgetsOf(options);\n const share = shareOf(options);\n const endurance = shareEndurance(layer, caseCuts, options, share);\n const stopped = caseDraws(layer, caseCuts, caseStopped(caseCuts, options));\n const stoppedNeeds = new Set(stopped.map((draw) => draw.need));\n const stoppedOf = stoppedMemo(caseCuts, options);\n // Each end of the bands: a cut with a band takes that end as its curve, and a cut with no band has no curve.\n const banded = caseCuts.cuts.some((cut) => cut.band !== undefined);\n const endCuts = (end: \"low\" | \"high\"): CaseCuts => ({ ...caseCuts, cuts: caseCuts.cuts.map(({ duration: _, band, ...cut }) => (band === undefined ? cut : { ...cut, duration: band[end], band })) });\n const ends = banded ? { shorter: endCuts(\"low\"), longer: endCuts(\"high\") } : undefined;\n const draws: DrawOutlook[] = [];\n const unread: string[] = [];\n const bounds: CutBound[] = [];\n for (const draw of stopped) {\n const held = endurance.needs[draw.need];\n const curves = stopCurvesWith(caseCuts, draw, options, stoppedOf);\n if (held === undefined || curves === undefined) {\n unread.push(draw.need);\n continue;\n }\n const users = draw.users ?? 1;\n const lasts = (curve: Survival): number => (held.days >= horizon ? 1 : 1 - survivalAt(curve, held.days));\n const short = (curve: Survival): number => heldTail(curve, held, horizon) * users;\n const values = (stop: StopCurves): BandValues => ({\n lasts: { event: lasts(stop.event), independent: lasts(stop.independent), upper: lasts(stop.upper) },\n shortfall: { event: short(stop.event), independent: short(stop.independent), upper: short(stop.upper) },\n });\n const shorter = ends === undefined ? undefined : stopCurvesWith(ends.shorter, draw, options, stoppedOf);\n const longer = ends === undefined ? undefined : stopCurvesWith(ends.longer, draw, options, stoppedOf);\n const band = shorter === undefined || longer === undefined ? {} : { band: { shorter: values(shorter), longer: values(longer) } };\n bounds.push(curves.bound);\n draws.push({\n need: draw.need,\n level: draw.level,\n supply: draw.supply,\n users,\n days: held.days,\n ...(held.atHorizon === true ? { atHorizon: true as const } : {}),\n ...values(curves),\n bound: curves.bound,\n coarse: curves.coarse,\n ...band,\n });\n }\n const holds = layer.draws.filter((draw) => !stoppedNeeds.has(draw.need)).map((draw) => draw.need);\n return {\n case: caseCuts.case,\n title: caseCuts.title,\n at: endurance.at,\n share,\n horizon: Number.isFinite(horizon) ? horizon : undefined,\n draws,\n holds,\n unread,\n bound: weakestBound(bounds),\n };\n}\n","import { STACK_SCHEMA, type Stack } from \"@mark1russell7/system-stack\";\nimport { ENDURANCE_SCHEMA, type EnduranceLayer } from \"./layer.ts\";\n\n// A sample: a building with 3 users, and a storm that cuts the grid, the road and the water main.\n// Each name and each value is an example, except the grid curve (NREL, technical report 83092). The tests, the README files and the site use it.\n\n/** The base stack of the sample: the supplies of the building and a camp stove. */\nexport const SAMPLE_ENDURANCE_STACK: Stack = {\n schema: STACK_SCHEMA,\n parts: [\n { id: \"grid\", kind: \"power\", name: \"The power grid\" },\n { id: \"water-main\", kind: \"water\", name: \"The water main\" },\n { id: \"road\", kind: \"road\", name: \"The local road to the shops\" },\n { id: \"stove\", kind: \"device\", name: \"The camp stove\" },\n ],\n};\n\n/**\n * The endurance layer of the sample.\n *\n * - The drinking water holds 75.7 L / 11.355 L a day = 6.667 days.\n * - The food holds 4800 / 5400 = 0.889 days. The rice needs 2 L of water for each kg, and the drinking water keeps back all the water.\n * - The power holds 1000 Wh / 150 Wh a day = 6.667 days.\n * - The filled bottles are past their due date, so they give nothing.\n */\nexport const SAMPLE_ENDURANCE: EnduranceLayer = {\n schema: ENDURANCE_SCHEMA,\n levels: [\"life\", \"health\", \"comfort\"],\n resources: [\n { code: \"water.stored\", unit: \"L\" },\n { code: \"food.ready\", unit: \"kcal\" },\n { code: \"food.grain-dry\", unit: \"kg\" },\n { code: \"fuel.propane\", unit: \"kg\" },\n { code: \"energy.battery\", unit: \"Wh\" },\n ],\n stores: [\n { id: \"jugs\", resource: \"water.stored\", amount: 75.7, due: \"2028-06-01\" },\n { id: \"bottles\", resource: \"water.stored\", amount: 20, due: \"2026-09-30\" },\n { id: \"cans\", resource: \"food.ready\", amount: 4800, due: \"2028-10-01\" },\n { id: \"rice\", resource: \"food.grain-dry\", amount: 9, due: \"2036-09-28\" },\n { id: \"propane\", resource: \"fuel.propane\", amount: 0.908, due: \"2036-10-01\" },\n { id: \"battery\", resource: \"energy.battery\", amount: 1000, due: \"2031-10-01\" },\n ],\n draws: [\n { need: \"hydration.drink\", level: \"life\", perDay: 11.355, users: 3, supply: \"water-main\" },\n { need: \"food.energy\", level: \"health\", perDay: 5400, users: 3, supply: \"road\" },\n { need: \"power.electric\", level: \"comfort\", perDay: 150, users: 3, supply: \"grid\" },\n ],\n direct: [\n { resource: \"water.stored\", need: \"hydration.drink\", amount: 1 },\n { resource: \"food.ready\", need: \"food.energy\", amount: 1 },\n { resource: \"energy.battery\", need: \"power.electric\", amount: 1 },\n ],\n converters: [\n {\n id: \"cook-rice\",\n device: \"stove\",\n takes: [\n { resource: \"food.grain-dry\", amount: 1 },\n { resource: \"water.stored\", amount: 2 },\n { resource: \"fuel.propane\", amount: 0.05 },\n ],\n gives: { need: \"food.energy\", amount: 3600 },\n },\n ],\n cases: [\n {\n case: \"storm\",\n title: \"Winter storm\",\n cuts: [\n { part: \"grid\", title: \"Power outage\", duration: [[0, 1], [0.5, 0.5], [1, 0.36], [7, 0.013], [30, 0]], source: \"nrel-83092\" },\n { part: \"road\", title: \"Closed local road\", duration: [[0, 1], [1, 0.6], [3, 0.2], [10, 0]], source: \"sample\" },\n { part: \"water-main\", title: \"No water from the main\", duration: [[0, 1], [2, 0.3], [7, 0]], source: \"sample\" },\n ],\n leadSeconds: 86_400,\n },\n { case: \"fire\", title: \"Fire\", cuts: [] },\n ],\n priors: [\n { case: \"storm\", place: \"home\", perYear: 0.8, reach: 1, source: \"sample\", asOf: \"2025-12-01\" },\n { case: \"fire\", place: \"home\", perYear: 0.003, reach: 1, source: \"sample\", asOf: \"2025-12-01\" },\n ],\n};\n","import { kaplanMeier, survivalDifference, Z95, type SurvivalCurve, type TimeToEvent } from \"@mark1russell7/rigor-statistics\";\nimport { countsFault, type DurationCounts } from \"@mark1russell7/system-stack\";\nimport { deviceKey } from \"./converter.ts\";\nimport { enduranceOf, type CaseOptions } from \"./endurance.ts\";\nimport type { CaseCuts, Converter, Endurance, EnduranceLayer, IsoDate, Survival } from \"./layer.ts\";\nimport { caseOutlook, stopCuts, type CurveValues, type DrawBand, type DrawOutlook, type ShortfallOptions, type StopCurveOptions } from \"./shortfall.ts\";\n\n// The sensitivity of a layer (M2-endurance-sensitivity): the change in the days of each draw for one step of each input.\n// The core names no topic. An input is the amount of a store, the rate of a draw or a parameter of a converter.\n\n/** The default step of `enduranceSensitivity`: 1 unit of each input. */\nexport const SENSITIVITY_STEP = 1;\n\n/** The options of `enduranceSensitivity`: the options of a case, the horizon of the chance, and the step. */\nexport interface SensitivityOptions extends CaseOptions, ShortfallOptions {\n /** The step of each input, a number more than 0, in the unit of the input. The default is `SENSITIVITY_STEP`. */\n readonly step?: number | undefined;\n}\n\n/** The kind of an input: the amount of a store, the rate of a draw, or a parameter of a converter. */\nexport type SensitivityKind = \"store\" | \"draw\" | \"converter\";\n\n/**\n * The 95% interval of the change of the chance (`SensitivityChance.change`), from the sampling error of the curve of one cut. Since 0.8.27.\n * The ends are the change minus and plus `Z95` times `se`, clamped to 0 to 1, or to -1 to 0 for a change down.\n * It is a Wald interval. Near the ends of the range, its coverage can be less than 95%.\n */\nexport interface ChanceInterval {\n /** The Greenwood standard error of the change. It includes the covariance of the chances of the curve at the days before and after the step. */\n readonly se: number;\n readonly low: number;\n readonly high: number;\n}\n\n/**\n * The change in the chance that a draw gets its need through the event (`DrawOutlook.lasts`), for one input.\n * The chance comes from the curves of the stop. Only the days change, so the curves are the same before and after.\n */\nexport interface SensitivityChance {\n /** The chance before the step, for each curve of the stop. */\n readonly before: CurveValues;\n /** The chance after the step, for each curve of the stop. */\n readonly after: CurveValues;\n /** The chance after the step minus the chance before it, for each curve. It is the change of the point values. */\n readonly change: CurveValues;\n /**\n * The 95% interval of `change`, when the stop of the draw uses one cut, and that cut has counts (`Cut.counts`) with no fault. Since 0.8.27.\n * With one cut, the three curves of the stop are the curve of the cut, so the three changes are equal.\n * Without counts, the interval is also absent.\n *\n * With two or more cuts, the interval is absent. The event curve and the upper curve are not smooth functions of the curves\n * of the cuts (a maximum, and a sum with a limit). The independent curve is a polynomial with a term for each state of the cuts.\n */\n readonly interval?: ChanceInterval | undefined;\n /** The values before the step at the two ends of the sampling bands of the cuts (`DrawOutlook.band`). */\n readonly beforeBand?: DrawBand | undefined;\n /** The values after the step at the two ends of the sampling bands of the cuts. */\n readonly afterBand?: DrawBand | undefined;\n}\n\n/** The change in the days of one draw for one input. */\nexport interface SensitivityNeed {\n readonly need: string;\n readonly level: string;\n /** The days of the draw before the step (`DrawEndurance.days`). */\n readonly before: number;\n /** The days of the draw after the step. */\n readonly after: number;\n /** The days after the step minus the days before it. */\n readonly change: number;\n /** The change for each unit of the input: `change` divided by the size of `delta`. */\n readonly perUnit: number;\n /** The change in the chance. It is missing when the stop of the draw has no curve (`CaseOutlook.unread`). */\n readonly chance?: SensitivityChance | undefined;\n}\n\n/** One input of a layer, and the change in the days of each draw for its step. */\nexport interface SensitivityInput {\n /**\n * The key of the input: `store:<id>`, `draw:<need>`, `converter:<id>.gives`, `converter:<id>.takes.<resource>` or\n * `converter:<id>.perDay`. The count of devices has the key of the device and `.devices`, for example `device:stove.devices`.\n */\n readonly id: string;\n readonly kind: SensitivityKind;\n /** The `id` of the store, the need of the draw, the `id` of the converter, or the device of a count of devices. */\n readonly target: string;\n /** The field that the step changes: `amount`, `perDay`, `gives`, `takes.<resource>` or `devices`. */\n readonly field: string;\n /** The value of the field before the step. */\n readonly value: number;\n /** The change of the value: more than 0 for more of the input, less than 0 for a lower draw or a lower take. */\n readonly delta: number;\n /** The change of each draw whose supply the case stops, in the order of `enduranceOf`. */\n readonly needs: readonly SensitivityNeed[];\n /** The sum of the changes of the draws of each level, by the level. The rank compares these sums. */\n readonly levels: Readonly<Record<string, number>>;\n}\n\n/** The sensitivity of a layer in a case: each input with its change, the largest change first. */\nexport interface Sensitivity {\n readonly case: string;\n readonly at: IsoDate;\n /** The step of the query. */\n readonly step: number;\n /** The endurance before each step. */\n readonly base: Endurance;\n /** The rank of the inputs. Refer to `enduranceSensitivity`. */\n readonly inputs: readonly SensitivityInput[];\n}\n\n/** One input and the layer after its step. */\ninterface Variant {\n readonly id: string;\n readonly kind: SensitivityKind;\n readonly target: string;\n readonly field: string;\n readonly value: number;\n readonly delta: number;\n readonly layer: EnduranceLayer;\n}\n\n/** This function gives the size of a step down from a value. It is the step, or half the value when the value is not more than the step. */\nfunction stepDown(value: number, step: number): number {\n return value > step ? step : value / 2;\n}\n\n/** This function gives each input of a layer and the layer after its step. */\nfunction variantsOf(layer: EnduranceLayer, step: number): Variant[] {\n const out: Variant[] = [];\n for (const store of layer.stores) {\n const amount = store.amount + step;\n // A store with a capacity keeps a capacity that is not less than its amount.\n const changed = { ...store, amount, ...(store.capacity !== undefined && amount > store.capacity ? { capacity: amount } : {}) };\n out.push({ id: `store:${store.id}`, kind: \"store\", target: store.id, field: \"amount\", value: store.amount, delta: step, layer: { ...layer, stores: layer.stores.map((item) => (item === store ? changed : item)) } });\n }\n for (const draw of layer.draws) {\n if (!(draw.perDay > 0)) continue;\n const delta = -stepDown(draw.perDay, step);\n const changed = { ...draw, perDay: draw.perDay + delta };\n out.push({ id: `draw:${draw.need}`, kind: \"draw\", target: draw.need, field: \"perDay\", value: draw.perDay, delta, layer: { ...layer, draws: layer.draws.map((item) => (item === draw ? changed : item)) } });\n }\n const converters = layer.converters ?? [];\n const withConverters = (change: (converter: Converter) => Converter): EnduranceLayer => ({ ...layer, converters: converters.map(change) });\n const devicesSeen = new Set<string>();\n for (const converter of converters) {\n const key = `converter:${converter.id}`;\n if (converter.gives.amount > 0) {\n const gives = { ...converter.gives, amount: converter.gives.amount + step };\n out.push({ id: `${key}.gives`, kind: \"converter\", target: converter.id, field: \"gives\", value: converter.gives.amount, delta: step, layer: withConverters((item) => (item === converter ? { ...item, gives } : item)) });\n }\n for (const input of converter.takes) {\n if (!(input.amount > 0)) continue;\n const delta = -stepDown(input.amount, step);\n const takes = converter.takes.map((item) => (item === input ? { ...item, amount: item.amount + delta } : item));\n out.push({ id: `${key}.takes.${input.resource}`, kind: \"converter\", target: converter.id, field: `takes.${input.resource}`, value: input.amount, delta, layer: withConverters((item) => (item === converter ? { ...item, takes } : item)) });\n }\n // A converter with no limit `perDay` has no limit to change, and its count of devices has no effect.\n if (converter.perDay === undefined) continue;\n const perDay = converter.perDay + step;\n out.push({ id: `${key}.perDay`, kind: \"converter\", target: converter.id, field: \"perDay\", value: converter.perDay, delta: step, layer: withConverters((item) => (item === converter ? { ...item, perDay } : item)) });\n // The converters of one device share one count of devices. A device is a whole unit, so the step of a count is 1.\n const device = deviceKey(converter);\n if (devicesSeen.has(device)) continue;\n devicesSeen.add(device);\n const count = converter.devices ?? 1;\n out.push({ id: `${device}.devices`, kind: \"converter\", target: converter.device ?? converter.id, field: \"devices\", value: count, delta: 1, layer: withConverters((item) => (deviceKey(item) === device ? { ...item, devices: count + 1 } : item)) });\n }\n return out;\n}\n\n/** This function gives `a` minus `b` for each curve. */\nfunction minus(a: CurveValues, b: CurveValues): CurveValues {\n return { event: a.event - b.event, independent: a.independent - b.independent, upper: a.upper - b.upper };\n}\n\n/** The curve of the one cut of the stop of a draw, with the Kaplan-Meier estimate of its counts. */\ninterface CountedCurve {\n readonly curve: Survival;\n readonly last: number;\n readonly estimate: SurvivalCurve;\n}\n\n/**\n * This function gives the Kaplan-Meier estimate of a table of counts, with the same chance and Greenwood sum at each step.\n * The observations that leave after a step, with no event, are censored at the day of that step, or at `last` after the last step.\n */\nfunction estimateOf(counts: DurationCounts): SurvivalCurve {\n const observations: TimeToEvent[] = [];\n for (const [index, [days, atRisk, events]] of counts.steps.entries()) {\n const next = counts.steps[index + 1];\n const left = atRisk - events - (next?.[1] ?? 0);\n observations.push({ time: days, count: events });\n if (left > 0) observations.push({ time: next === undefined ? counts.last : days, censored: true, count: left });\n }\n if (observations.length === 0) observations.push({ time: counts.last, censored: true });\n return kaplanMeier(observations);\n}\n\n/** This function gives the curve of the one cut of the stop of a draw, when that cut has counts with no fault. */\nfunction countedCurveOf(layer: EnduranceLayer, caseCuts: CaseCuts, need: string, options: StopCurveOptions): CountedCurve | undefined {\n const draw = layer.draws.find((item) => item.need === need);\n const used = draw === undefined ? undefined : stopCuts(caseCuts, draw, options);\n if (used === undefined || used.length !== 1) return undefined;\n const cut = caseCuts.cuts[used[0] ?? -1];\n if (cut?.duration === undefined || cut.counts === undefined || countsFault(cut.duration, cut.counts) !== undefined) return undefined;\n return { curve: cut.duration, last: cut.counts.last, estimate: estimateOf(cut.counts) };\n}\n\n/**\n * This function gives the points of a curve and their weights in the read of `survivalAt` of the core at `days`.\n * Between two points, the read is linear, so it has a weight on each of the two points. After the last point, the read is 0.\n */\nfunction pointWeights(curve: Survival, days: number): [day: number, weight: number][] {\n if (days <= 0) return [[curve[0]?.[0] ?? 0, 1]];\n for (let index = 1; index < curve.length; index += 1) {\n const [t0] = curve[index - 1] ?? [0, 1];\n const [t1] = curve[index] ?? [0, 0];\n if (days < t1) {\n const weight = (days - t0) / (t1 - t0);\n return weight === 0 ? [[t0, 1]] : [[t0, 1 - weight], [t1, weight]];\n }\n if (days === t1) return [[t1, 1]];\n }\n return [];\n}\n\n/**\n * This function gives the interval of the change of the chance, from the counts of the one cut of the stop.\n *\n * - The change is `S(before) - S(after)`. A read at or after the horizon is 0, so it adds no term.\n * - 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.\n * - The variance of the weighted sum uses the covariance of each two chances. `survivalDifference` of rigor-statistics gives\n * 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`.\n */\nfunction changeInterval(read: CountedCurve, before: number, after: number, horizon: number, change: number): ChanceInterval | undefined {\n const terms: [day: number, weight: number][] = [];\n const add = (days: number, sign: number): void => {\n if (days >= horizon) return;\n for (const [day, weight] of pointWeights(read.curve, days)) if (day > 0 && day <= read.last) terms.push([day, sign * weight]);\n };\n add(before, 1);\n add(after, -1);\n const square = (from: number, to: number): number | undefined => {\n const difference = survivalDifference(read.estimate, from, to);\n return difference === undefined ? undefined : difference.se * difference.se;\n };\n let variance = 0;\n for (const [a, weightA] of terms) {\n for (const [b, weightB] of terms) {\n const atA = square(0, a);\n const atB = square(0, b);\n const between = square(a, b);\n if (atA === undefined || atB === undefined || between === undefined) return undefined;\n variance += weightA * weightB * ((atA + atB - between) / 2);\n }\n }\n const se = Math.sqrt(Math.max(0, variance));\n const [floor, ceiling]: [number, number] = (after >= horizon ? Infinity : after) >= (before >= horizon ? Infinity : before) ? [0, 1] : [-1, 0];\n const clamp = (value: number): number => Math.min(ceiling, Math.max(floor, value));\n return { se, low: clamp(change - Z95 * se), high: clamp(change + Z95 * se) };\n}\n\n/** This function compares two inputs for the rank: the sums of the levels in the order of the levels, the largest first, then the key. */\nfunction rankOrder(levels: readonly string[]): (a: SensitivityInput, b: SensitivityInput) => number {\n return (a, b) => {\n for (const level of levels) {\n const diff = (b.levels[level] ?? 0) - (a.levels[level] ?? 0);\n if (diff > 0) return 1;\n if (diff < 0) return -1;\n }\n return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;\n };\n}\n\n/**\n * This function gives the change in the days of each draw for one step of each input of a layer, ranked.\n * The rank names the input that moves the days most. A lower draw costs nothing, so the rank also shows such inputs.\n *\n * - The inputs are the amount of each store and the rate `perDay` of each draw. Each converter gives the amount of its\n * gift, the amount of each take, its limit `perDay` and its count of devices.\n * - The step adds to a store, to a gift, to a limit `perDay` and to a count of devices. It takes off a draw and a take,\n * because less of them gives more days. A count of devices takes 1 more device.\n * - When the rate of a draw or a take is not more than the step, the step takes off half the value. Thus the value stays more than 0.\n * - A store with a capacity gets a capacity that is not less than its new amount.\n * - The change of a draw is a finite difference: the days of `enduranceOf` after the step minus the days before it.\n * `perUnit` divides it by the size of the change of the value.\n * - An input that no draw of the case uses has a change of 0, for example a store past its due date.\n * - The rank is by level. It compares the sum of the changes of the draws of the first level, then of the next level, and so on.\n * The largest sum comes first. Two equal inputs go in the order of their keys. Thus the order is stable.\n * - The days are exact for the inputs. `chance` is the chance that a draw gets its need through the event. It comes\n * from `caseOutlook` with the share `take`, before and after the step, with the bands of the cuts. The change of the\n * chance is the change of the point values.\n * - The change has a 95% interval (`SensitivityChance.interval`) when the stop of the draw uses one cut (`stopCuts`) with counts.\n * 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.\n *\n * The cost is one `enduranceOf` and one `caseOutlook` for each input, and one `stopCuts` for each draw of the base. The function is pure.\n *\n * @param layer - The endurance layer\n * @param caseCuts - The case\n * @param options - The date, the stack or the parts that are also down, the horizon and the step\n * @returns The endurance before the steps, and the inputs in the order of the rank\n * @throws RangeError for a step that is not a finite number more than 0, and for the errors of `enduranceOf` and `caseOutlook`\n */\nexport function enduranceSensitivity(layer: EnduranceLayer, caseCuts: CaseCuts, options: SensitivityOptions): Sensitivity {\n const { step: given, ...caseOptions } = options;\n const step = given ?? SENSITIVITY_STEP;\n if (!(step > 0) || !Number.isFinite(step)) throw new RangeError(`The step ${String(given)} is not a finite number more than 0.`);\n const base = enduranceOf(layer, caseCuts, caseOptions);\n const outlookOf = (changed: EnduranceLayer): Map<string, DrawOutlook> => new Map(caseOutlook(changed, caseCuts, { ...caseOptions, share: \"take\" }).draws.map((draw) => [draw.need, draw] as const));\n const baseOutlook = outlookOf(layer);\n // The stop of each draw uses the same cuts before and after the step, so the curve with counts comes from the base.\n const counted = new Map([...baseOutlook.keys()].flatMap((need) => {\n const read = countedCurveOf(layer, caseCuts, need, caseOptions);\n return read === undefined ? [] : [[need, read] as const];\n }));\n const horizon = caseOptions.horizon ?? Infinity;\n const levelOf = new Map(layer.draws.map((draw) => [draw.need, draw.level] as const));\n const inputs = variantsOf(layer, step).map(({ layer: changed, ...variant }): SensitivityInput => {\n const after = enduranceOf(changed, caseCuts, caseOptions);\n // With no curve of a stop, the case has no chance to read, so the query does not call `caseOutlook` again.\n const outlook = baseOutlook.size === 0 ? undefined : outlookOf(changed);\n const sums = new Map<string, number>(layer.levels.map((level) => [level, 0] as const));\n const needs = Object.entries(base.needs).map(([need, held]): SensitivityNeed => {\n const days = after.needs[need]?.days ?? held.days;\n const change = days === held.days ? 0 : days - held.days;\n const level = levelOf.get(need) ?? \"\";\n const sum = sums.get(level);\n if (sum !== undefined) sums.set(level, sum + change);\n const from = baseOutlook.get(need);\n const to = outlook?.get(need);\n const read = counted.get(need);\n const moved = from === undefined || to === undefined ? undefined : minus(to.lasts, from.lasts);\n const interval = read === undefined || from === undefined || to === undefined || moved === undefined ? undefined : changeInterval(read, from.days, to.days, horizon, moved.event);\n const chance =\n from === undefined || to === undefined || moved === undefined\n ? {}\n : {\n chance: {\n before: from.lasts,\n after: to.lasts,\n change: moved,\n ...(from.band === undefined ? {} : { beforeBand: from.band }),\n ...(to.band === undefined ? {} : { afterBand: to.band }),\n ...(interval === undefined ? {} : { interval }),\n },\n };\n return { need, level, before: held.days, after: days, change, perUnit: change / Math.abs(variant.delta), ...chance };\n });\n return { ...variant, needs, levels: Object.fromEntries(sums) };\n });\n inputs.sort(rankOrder(layer.levels));\n return { case: caseCuts.case, at: options.at, step, base, inputs };\n}\n","import type { IsoDate } from \"./layer.ts\";\nimport type { Sensitivity, SensitivityInput, SensitivityKind } from \"./sensitivity.ts\";\n\n// The rank of the next buy (M2-days-per-dollar): the days that each input adds for one unit of money.\n// The core names no topic. The prices are input data, and the caller owns their source.\n\n/**\n * A table of prices: the price of one unit of each input, in one currency.\n * The key of a price is the key of the input (`SensitivityInput.id`), for example `store:jugs` or `converter:cook.gives`.\n * The key is the input key, because the kind and the target do not identify one input. A converter has an input\n * for its gift, for each take and for its limit, all with the same target.\n */\nexport interface PriceTable {\n /** The code of the currency of each price, for example `USD`. The rank does not convert a currency. */\n readonly currency: string;\n /** The price of one unit of each input, by the key of the input. The unit is the unit of the input, for example 1 L of a store. */\n readonly prices: Readonly<Record<string, number>>;\n}\n\n/** The options of `daysPerDollar`. */\nexport interface DaysPerDollarOptions {\n /** The levels of the layer, the most important first (`EnduranceLayer.levels`). The rank compares the levels in this order. */\n readonly levels: readonly string[];\n}\n\n/** The reason why an input has no rank: the table has no price for it, or its price is bad. A bad price is not a finite number more than 0. */\nexport type UnpricedReason = \"no-price\" | \"bad-price\";\n\n/** One input with a price, and its days for one unit and for one unit of money. */\nexport interface PricedInput {\n readonly id: string;\n readonly kind: SensitivityKind;\n readonly target: string;\n readonly field: string;\n /** The price of one unit of the input, in the currency of the table. */\n readonly price: number;\n /** The days of each level for one unit of the input: the sum of the changes of the level divided by the size of `delta`. */\n readonly perUnit: Readonly<Record<string, number>>;\n /** The days of each level for one unit of money: `perUnit` divided by `price`. */\n readonly perDollar: Readonly<Record<string, number>>;\n}\n\n/** One input with no rank, and the reason. It has no price, so it has no days for one unit of money. */\nexport interface UnpricedInput {\n readonly id: string;\n readonly kind: SensitivityKind;\n readonly target: string;\n readonly field: string;\n /** The days of each level for one unit of the input. */\n readonly perUnit: Readonly<Record<string, number>>;\n readonly reason: UnpricedReason;\n}\n\n/** The rank of the inputs by the days that they add for one unit of money. */\nexport interface DaysPerDollar {\n readonly case: string;\n readonly at: IsoDate;\n /** The currency of the table. */\n readonly currency: string;\n /** The inputs with a price, in the order of the rank. The first input is the next buy. Refer to `daysPerDollar`. */\n readonly ranked: readonly PricedInput[];\n /** The inputs with no price or with a bad price, in the order of the sensitivity. They have no rank. */\n readonly unpriced: readonly UnpricedInput[];\n /** The keys of the table that are not the key of an input, in the order of their codes. A key with an error shows here. */\n readonly unused: readonly string[];\n}\n\n/** This function gives the days of each level for one unit of an input, in the order of the levels. */\nfunction perUnitOf(input: SensitivityInput, levels: readonly string[]): Record<string, number> {\n const size = Math.abs(input.delta);\n return Object.fromEntries(levels.map((level) => [level, (input.levels[level] ?? 0) / size] as const));\n}\n\n/** This function compares two inputs with a price. It compares the days for one unit of money of each level in order, the largest first, then the key. */\nfunction rankOrder(levels: readonly string[]): (a: PricedInput, b: PricedInput) => number {\n return (a, b) => {\n for (const level of levels) {\n const diff = (b.perDollar[level] ?? 0) - (a.perDollar[level] ?? 0);\n if (diff > 0) return 1;\n if (diff < 0) return -1;\n }\n return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;\n };\n}\n\n/**\n * This function ranks the inputs of a sensitivity by the days that they add for one unit of money.\n * With the price of one unit of each input, the first input of the rank is the next buy.\n *\n * - The function reads the result of `enduranceSensitivity`. It does not calculate the days again.\n * - The days of an input for one unit are the sum of the changes of each level divided by the size of `delta`.\n * Thus a step of 2, or a half step of a low draw, gives the days of 1 unit.\n * - The days for one unit of money are the days for one unit divided by the price of one unit.\n * - The rank is by level, as the rank of the sensitivity. It compares the days for one unit of money of the first level,\n * then of the next level, and so on. The largest value comes first. Two equal inputs go in the order of their keys.\n * - Thus an input that adds days to a higher level comes before each input that adds days only to lower levels. A buy\n * for a lower level does not go before a buy for a higher level, also when it gives more days for its money.\n * - An input with a change of 0 days has 0 days for one unit of money. It stays in the rank, after each input that adds\n * days at its level.\n * - An input with no price in the table has no rank. It goes in `unpriced` with the reason `no-price`. It does not get a price of 0.\n * - A price that is not a finite number more than 0 is a bad price. The input goes in `unpriced` with the reason\n * `bad-price`. The function does not throw, so one bad price of a live table does not stop the rank of the others.\n * A lower draw costs nothing, but the table gives it a price only when a buy lowers it.\n * - `unused` names each key of the table that is not the key of an input.\n *\n * The function is pure.\n *\n * @param sensitivity - The result of `enduranceSensitivity`\n * @param prices - The price of one unit of each input, by the key of the input\n * @param options - The levels of the layer, the most important first\n * @returns The inputs with a price in the order of the rank, the inputs with no rank, and the keys that are not used\n */\nexport function daysPerDollar(sensitivity: Sensitivity, prices: PriceTable, options: DaysPerDollarOptions): DaysPerDollar {\n const { levels } = options;\n const ranked: PricedInput[] = [];\n const unpriced: UnpricedInput[] = [];\n const ids = new Set<string>();\n for (const input of sensitivity.inputs) {\n ids.add(input.id);\n const { id, kind, target, field } = input;\n const perUnit = perUnitOf(input, levels);\n const price = Object.hasOwn(prices.prices, id) ? prices.prices[id] : undefined;\n if (price === undefined) {\n unpriced.push({ id, kind, target, field, perUnit, reason: \"no-price\" });\n continue;\n }\n if (!(price > 0) || !Number.isFinite(price)) {\n unpriced.push({ id, kind, target, field, perUnit, reason: \"bad-price\" });\n continue;\n }\n const perDollar = Object.fromEntries(levels.map((level) => [level, (perUnit[level] ?? 0) / price] as const));\n ranked.push({ id, kind, target, field, price, perUnit, perDollar });\n }\n ranked.sort(rankOrder(levels));\n const unused = Object.keys(prices.prices)\n .filter((key) => !ids.has(key))\n .sort();\n return { case: sensitivity.case, at: sensitivity.at, currency: prices.currency, ranked, unpriced, unused };\n}\n"],"mappings":";;;;;;;;;AACA,MAAa,YAAY;;;;;AAmBzB,MAAa,WAAW,EAAE,OAAO,EAAE;;;;;;;;;;;;;;;;;AAkBnC,SAAgB,WAAc,MAAc,SAAwC;CAClF,MAAM,QAAQ,UAA2B,MAAM,SAAS,YAAY,MAAM;CAC1E,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