@mark1russell7/stack-endurance 0.0.0-stage → 0.3.2
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/LICENSE +21 -0
- package/README.md +89 -2
- package/build/add-on.d.ts +12 -0
- package/build/add-on.d.ts.map +1 -0
- package/build/add-on.js +23 -0
- package/build/add-on.js.map +1 -0
- package/build/index.d.ts +286 -0
- package/build/index.d.ts.map +1 -0
- package/build/index.js +604 -0
- package/build/index.js.map +1 -0
- package/build/join-D7KyUpGf.js +557 -0
- package/build/join-D7KyUpGf.js.map +1 -0
- package/build/layer-DzGZC5XH.d.ts +143 -0
- package/build/layer-DzGZC5XH.d.ts.map +1 -0
- package/build/layer-a3Fr70Uh.js +6 -0
- package/build/layer-a3Fr70Uh.js.map +1 -0
- package/build/schema.d.ts +21 -0
- package/build/schema.d.ts.map +1 -0
- package/build/schema.js +99 -0
- package/build/schema.js.map +1 -0
- package/package.json +75 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/shortfall.ts","../src/sample.ts"],"sourcesContent":["import { neededParts } from \"@mark1russell7/system-stack\";\nimport { caseDraws, caseStopped, enduranceOf, type CaseOptions } from \"./endurance.ts\";\nimport type { CaseCuts, Draw, Endurance, EnduranceLayer, Prior, Survival } from \"./layer.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/** This function gives the chance that a cut lasts more than `days`, linear between the points of the curve. After the last point it is 0. */\nexport function survivalAt(curve: Survival, days: number): number {\n if (days <= 0) return curve[0]?.[1] ?? 0;\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 (days < t1) {\n // The chance stays between the chances of the two points, so a rounding does not go below the lower one.\n const chance = p0 + (p1 - p0) * ((days - t0) / (t1 - t0));\n return Math.min(Math.max(p0, p1), Math.max(Math.min(p0, p1), chance));\n }\n if (days === t1) return p1;\n }\n return 0;\n}\n\n/**\n * This function gives the expected days of a cut after a time, up to a horizon: `E[max(0, min(D, to) - from)]`.\n * It is the area under the curve from `from` to `to`. The curve is linear between its points, so the area is exact.\n * With no horizon, the area goes to the end of the curve.\n */\nexport function tailDays(curve: Survival, from: number, to: number = Infinity): number {\n let area = 0;\n for (let index = 1; index < curve.length; index += 1) {\n const [t0] = curve[index - 1] ?? [0, 1];\n const [t1] = curve[index] ?? [0, 0];\n const start = Math.max(t0, from);\n const end = Math.min(t1, to);\n if (start < end) area += ((survivalAt(curve, start) + survivalAt(curve, end)) / 2) * (end - start);\n }\n return area;\n}\n\n/**\n * The options of a shortfall: the stack or the parts that are also down, as for `enduranceOf`, and a horizon.\n * With a horizon of `h` days, the shortfall counts only the first `h` days of each cut. A draw that holds `h` days has no shortfall.\n * Thus a plan can aim at a target, for example 14 days and then 90 days.\n */\nexport interface ShortfallOptions extends Pick<CaseOptions, \"stack\" | \"down\"> {\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\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.\n * `stopCurves` counts only the cuts that can reach the supply. Past this count, its `upper` is coarse.\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 * 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 * @param curves - The curves of the cuts, each one good for `checkEndurance`\n * @param sets - The minimal sets of `minimalStops`. With `undefined`, as for too many cuts, the result is `undefined`. With no sets, it is `[[0, 0]]`\n * @throws RangeError when a curve does not end at a chance of 0\n */\nexport function independentStop(curves: readonly Survival[], sets: readonly (readonly number[])[] | undefined): Survival | undefined {\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 bit in a state.\n const used = [...new Set(sets.flat())].sort((x, y) => x - y);\n const usedCurves = used.map((index) => curves[index] ?? []);\n const setMasks = sets.map((set) => set.reduce((mask, index) => mask | (1 << used.indexOf(index)), 0));\n const stopping = Array.from({ length: 1 << used.length }, (_, mask) => setMasks.some((set) => (set & mask) === set));\n const states = new Float64Array(1 << used.length);\n const chanceAt = (days: number): number => {\n // The chance of each state of the cuts, one cut at a time. Bit k of a state is 1 when cut k is on.\n states[0] = 1;\n let length = 1;\n for (const curve of usedCurves) {\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 const times = [...new Set(usedCurves.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 = usedCurves.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 curveFrom(points, chanceAt);\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 `coarse` is true, it is `upper`. */\n readonly independent: Survival;\n readonly upper: Survival;\n /** This is true when `upper` is the sum of the curves of the cuts that can reach the supply, because there are more than `MINIMAL_STOP_CUTS`. */\n readonly coarse: boolean;\n}\n\n/** This function gives the parts of the stack that are down for a list of cut indexes. A case uses one memo for each of its draws. */\ntype StoppedOf = (cuts: readonly number[]) => ReadonlySet<string>;\n\nfunction stoppedMemo(caseCuts: CaseCuts, options: Pick<CaseOptions, \"stack\" | \"down\">): StoppedOf {\n const memo = new Map<string, ReadonlySet<string>>();\n return (cuts) => {\n const key = cuts.join(\",\");\n let found = memo.get(key);\n if (found === undefined) {\n found = caseStopped({ ...caseCuts, cuts: cuts.flatMap((index) => caseCuts.cuts[index] ?? []) }, options);\n memo.set(key, found);\n }\n return found;\n };\n}\n\n/** This function gives the parts whose cut can stop a supply: the supply, and each part that it needs through the stack. */\nfunction supplyReach(supply: string, options: Pick<CaseOptions, \"stack\">): Set<string> {\n const reach = options.stack === undefined ? new Set<string>() : neededParts(options.stack, supply);\n reach.add(supply);\n return reach;\n}\n\nfunction stopCurvesWith(caseCuts: CaseCuts, draw: Draw, options: Pick<CaseOptions, \"stack\" | \"down\">, stoppedOf: StoppedOf): StopCurves | undefined {\n const reach = supplyReach(draw.supply, options);\n const relevant = caseCuts.cuts.flatMap((cut, index) => (reach.has(cut.part) ? [index] : []));\n const stops = (cuts: readonly number[]): boolean => stoppedOf(cuts.map((index) => relevant[index] ?? -1)).has(draw.supply);\n if (stops([])) return undefined;\n if (!stops(relevant.map((_, index) => index))) return undefined;\n const curves = relevant.map((index) => caseCuts.cuts[index]?.duration ?? []);\n const sets = minimalStops(curves.length, stops);\n const upper = upperStop(curves, sets);\n return { event: eventStop(curves, stops), independent: independentStop(curves, sets) ?? upper, upper, coarse: sets === undefined };\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 * - `event` is `eventStop`. `independent` is `independentStop`, and `upper` is `upperStop`, over the minimal sets of the cuts that count.\n * - Past `MINIMAL_STOP_CUTS` cuts that count, `upper` is the sum of their curves, `independent` is `upper`, and `coarse` is true.\n */\nexport function stopCurves(caseCuts: CaseCuts, draw: Draw, options: Pick<CaseOptions, \"stack\" | \"down\"> = {}): StopCurves | undefined {\n return stopCurvesWith(caseCuts, draw, options, stoppedMemo(caseCuts, options));\n}\n\n/** The shortfall of each level, in user-days, and the draws that the query cannot read. */\nexport interface Shortfall {\n /**\n * The user-days of each level of the layer, when one event makes each cut longer together. The query does not add two levels.\n * This value is not a limit. The true value can be more or less. `upper` is the limit.\n */\n readonly levels: Readonly<Record<string, number>>;\n /** The user-days of each level when the cuts are independent (`StopCurves.independent`). This value is not more than `upper`. */\n readonly independent: Readonly<Record<string, number>>;\n /** The upper limit of the user-days of each level, for each dependence of the cuts. A gate of a high level can use it. */\n readonly upper: Readonly<Record<string, number>>;\n /**\n * The needs of the draws whose stop has no curve (`stopCurves`).\n * The query has no curve of their duration, so their shortfall is not in `levels`. A gate shows them as no read.\n */\n readonly unread: readonly string[];\n /** The needs of the draws whose `upper` is coarse (`StopCurves.coarse`). A gate on `upper` shows them. */\n readonly coarse: readonly string[];\n}\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\n */\nexport function caseShortfall(layer: EnduranceLayer, caseCuts: CaseCuts, endurance: Endurance, options: ShortfallOptions = {}): Shortfall {\n const horizon = horizonOf(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 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 const users = draw.users ?? 1;\n levels[draw.level] = (levels[draw.level] ?? 0) + tailDays(curves.event, held.days, horizon) * users;\n independent[draw.level] = (independent[draw.level] ?? 0) + tailDays(curves.independent, held.days, horizon) * users;\n upper[draw.level] = (upper[draw.level] ?? 0) + tailDays(curves.upper, held.days, horizon) * users;\n }\n return { levels, independent, upper, unread, coarse };\n}\n\n/** The shortfall of one year at one place, with the part of each case. */\nexport interface YearShortfall extends Shortfall {\n readonly place: string;\n /** The part of each case. `rate` is the expected count of its events in one year. */\n readonly cases: readonly { readonly case: string; readonly rate: number; readonly endurance: Endurance; readonly shortfall: Shortfall }[];\n}\n\n/**\n * This function gives the shortfall of one year at one place.\n * It is the sum over the cases of the layer of the expected count of the events of each case times its shortfall.\n *\n * - The expected count of a case is `perYear * reach`, from the first prior of the case at the place. Thus the result is the expected user-days of one year.\n * - A case with no prior at the place is not in the sum.\n * - `unread` is the union of the needs that a case cannot read, in the order of the cases. `coarse` is the union of the coarse needs.\n *\n * @param layer - The endurance layer, with its cases and priors\n * @param place - The place of the priors\n * @param options - The date, the stack or the parts that are also down, and the horizon\n * @throws RangeError when the date is not `YYYY-MM-DD`, or when the horizon is not a number more than 0\n */\nexport function yearShortfall(layer: EnduranceLayer, place: string, options: CaseOptions & ShortfallOptions): YearShortfall {\n horizonOf(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 cases: YearShortfall[\"cases\"][number][] = [];\n for (const caseCuts of layer.cases ?? []) {\n const prior = (layer.priors ?? []).find((item) => item.case === caseCuts.case && item.place === place);\n if (prior === undefined) continue;\n const rate = yearRate(prior);\n const endurance = enduranceOf(layer, caseCuts, options);\n const shortfall = caseShortfall(layer, caseCuts, endurance, options);\n for (const [level, days] of Object.entries(shortfall.levels)) levels[level] = (levels[level] ?? 0) + rate * days;\n for (const [level, days] of Object.entries(shortfall.independent)) independent[level] = (independent[level] ?? 0) + rate * days;\n for (const [level, days] of Object.entries(shortfall.upper)) upper[level] = (upper[level] ?? 0) + rate * days;\n for (const need of shortfall.unread) if (!unread.includes(need)) unread.push(need);\n for (const need of shortfall.coarse) if (!coarse.includes(need)) coarse.push(need);\n cases.push({ case: caseCuts.case, rate, endurance, shortfall });\n }\n return { place, levels, independent, upper, unread, coarse, cases };\n}\n","import { STACK_SCHEMA, type Stack } from \"@mark1russell7/system-stack\";\nimport { ENDURANCE_SCHEMA, type EnduranceLayer } from \"./layer.ts\";\n\n// A sample: a building with 3 users, and a storm that cuts the grid, the road and the water main.\n// Each name and each value is an example, except the grid curve (NREL, technical report 83092). The tests, the README files and the site use it.\n\n/** The base stack of the sample: the supplies of the building and a camp stove. */\nexport const SAMPLE_ENDURANCE_STACK: Stack = {\n schema: STACK_SCHEMA,\n parts: [\n { id: \"grid\", kind: \"power\", name: \"The power grid\" },\n { id: \"water-main\", kind: \"water\", name: \"The water main\" },\n { id: \"road\", kind: \"road\", name: \"The local road to the shops\" },\n { id: \"stove\", kind: \"device\", name: \"The camp stove\" },\n ],\n};\n\n/**\n * The endurance layer of the sample.\n *\n * - The drinking water holds 75.7 L / 11.355 L a day = 6.667 days.\n * - The food holds 4800 / 5400 = 0.889 days. The rice needs 2 L of water for each kg, and the drinking water keeps back all the water.\n * - The power holds 1000 Wh / 150 Wh a day = 6.667 days.\n * - The filled bottles are past their due date, so they give nothing.\n */\nexport const SAMPLE_ENDURANCE: EnduranceLayer = {\n schema: ENDURANCE_SCHEMA,\n levels: [\"life\", \"health\", \"comfort\"],\n resources: [\n { code: \"water.stored\", unit: \"L\" },\n { code: \"food.ready\", unit: \"kcal\" },\n { code: \"food.grain-dry\", unit: \"kg\" },\n { code: \"fuel.propane\", unit: \"kg\" },\n { code: \"energy.battery\", unit: \"Wh\" },\n ],\n stores: [\n { id: \"jugs\", resource: \"water.stored\", amount: 75.7, due: \"2028-06-01\" },\n { id: \"bottles\", resource: \"water.stored\", amount: 20, due: \"2026-09-30\" },\n { id: \"cans\", resource: \"food.ready\", amount: 4800, due: \"2028-10-01\" },\n { id: \"rice\", resource: \"food.grain-dry\", amount: 9, due: \"2036-09-28\" },\n { id: \"propane\", resource: \"fuel.propane\", amount: 0.908, due: \"2036-10-01\" },\n { id: \"battery\", resource: \"energy.battery\", amount: 1000, due: \"2031-10-01\" },\n ],\n draws: [\n { need: \"hydration.drink\", level: \"life\", perDay: 11.355, users: 3, supply: \"water-main\" },\n { need: \"food.energy\", level: \"health\", perDay: 5400, users: 3, supply: \"road\" },\n { need: \"power.electric\", level: \"comfort\", perDay: 150, users: 3, supply: \"grid\" },\n ],\n direct: [\n { resource: \"water.stored\", need: \"hydration.drink\", amount: 1 },\n { resource: \"food.ready\", need: \"food.energy\", amount: 1 },\n { resource: \"energy.battery\", need: \"power.electric\", amount: 1 },\n ],\n converters: [\n {\n id: \"cook-rice\",\n device: \"stove\",\n takes: [\n { resource: \"food.grain-dry\", amount: 1 },\n { resource: \"water.stored\", amount: 2 },\n { resource: \"fuel.propane\", amount: 0.05 },\n ],\n gives: { need: \"food.energy\", amount: 3600 },\n },\n ],\n cases: [\n {\n case: \"storm\",\n title: \"Winter storm\",\n cuts: [\n { part: \"grid\", title: \"Power outage\", duration: [[0, 1], [0.5, 0.5], [1, 0.36], [7, 0.013], [30, 0]], source: \"nrel-83092\" },\n { part: \"road\", title: \"Closed local road\", duration: [[0, 1], [1, 0.6], [3, 0.2], [10, 0]], source: \"sample\" },\n { part: \"water-main\", title: \"No water from the main\", duration: [[0, 1], [2, 0.3], [7, 0]], source: \"sample\" },\n ],\n leadSeconds: 86_400,\n },\n { case: \"fire\", title: \"Fire\", cuts: [] },\n ],\n priors: [\n { case: \"storm\", place: \"home\", perYear: 0.8, reach: 1, source: \"sample\", asOf: \"2025-12-01\" },\n { case: \"fire\", place: \"home\", perYear: 0.003, reach: 1, source: \"sample\", asOf: \"2025-12-01\" },\n ],\n};\n"],"mappings":";;;;;AAOA,SAAgB,WAAW,OAAiB,MAAsB;CAChE,IAAI,QAAQ,GAAG,OAAO,MAAM,EAAE,GAAG,MAAM;CACvC,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SAAS,GAAG;EACpD,MAAM,CAAC,IAAI,MAAM,MAAM,QAAQ,MAAM,CAAC,GAAG,CAAC;EAC1C,MAAM,CAAC,IAAI,MAAM,MAAM,UAAU,CAAC,GAAG,CAAC;EACtC,IAAI,OAAO,IAAI;GAEb,MAAM,SAAS,MAAM,KAAK,QAAQ,OAAO,OAAO,KAAK;GACrD,OAAO,KAAK,IAAI,KAAK,IAAI,IAAI,EAAE,GAAG,KAAK,IAAI,K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AAO;EAAQ,SAAS;EAAK,OAAO;EAAG,QAAQ;EAAU,MAAM;CAAa,GAC7F;EAAE,MAAM;EAAQ,OAAO;EAAQ,SAAS;EAAO,OAAO;EAAG,QAAQ;EAAU,MAAM;CAAa,CAChG;AACF"}
|
|
@@ -0,0 +1,557 @@
|
|
|
1
|
+
import { t as ENDURANCE_SCHEMA } from "./layer-a3Fr70Uh.js";
|
|
2
|
+
import { dayNumber, joinRecords, joinSetting, stopped } from "@mark1russell7/system-stack";
|
|
3
|
+
import { stronglyConnectedComponents } from "@mark1russell7/collections/graph";
|
|
4
|
+
// src/fit.ts
|
|
5
|
+
/** The relative tolerance of a take and of a fit. */
|
|
6
|
+
const TOLERANCE = 1e-13;
|
|
7
|
+
/**
|
|
8
|
+
* 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.
|
|
9
|
+
* It is the one side effect of `largestFit` and of the queries that use it.
|
|
10
|
+
*/
|
|
11
|
+
const fitTries = { count: 0 };
|
|
12
|
+
/**
|
|
13
|
+
* This function gives the largest `x` in `[0, most]` at which `attempt` has no shortfall, to the relative tolerance `TOLERANCE`.
|
|
14
|
+
*
|
|
15
|
+
* - A try fits when its shortfall is not more than `TOLERANCE` times its need.
|
|
16
|
+
* - The shortfall must not decrease when `x` increases. A take of a chain of converters gives a shortfall that is linear in parts.
|
|
17
|
+
* - The first try is `most`. After it, each step tries the zero of the line through the last two tries that do not fit.
|
|
18
|
+
* With one try that does not fit, the step tries `x` times the part of the need that the stores gave.
|
|
19
|
+
* - 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.
|
|
20
|
+
* - A step on the lower end tries a point just above it, so a correct estimate ends the fit in one more try.
|
|
21
|
+
* - An estimate that fits with a shortfall above 0 is in the band of the tolerance above the zero, so the fit ends there.
|
|
22
|
+
* 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.
|
|
23
|
+
*
|
|
24
|
+
* @param most - The upper limit of `x`
|
|
25
|
+
* @param attempt - The try at an amount. It must not change its input
|
|
26
|
+
* @returns The largest amount that fits, and the value of its try
|
|
27
|
+
*/
|
|
28
|
+
function largestFit(most, attempt) {
|
|
29
|
+
const fits = (tried) => tried.short <= TOLERANCE * tried.need;
|
|
30
|
+
fitTries.count += 1;
|
|
31
|
+
const first = attempt(most);
|
|
32
|
+
if (fits(first)) return {
|
|
33
|
+
x: most,
|
|
34
|
+
value: first.value
|
|
35
|
+
};
|
|
36
|
+
let low = 0;
|
|
37
|
+
let best;
|
|
38
|
+
let high = most;
|
|
39
|
+
let highShort = first.short;
|
|
40
|
+
let highNeed = first.need;
|
|
41
|
+
let before;
|
|
42
|
+
let bisect = false;
|
|
43
|
+
for (let step = 0; step < 400 && high - low > 4e-13 * high; step += 1) {
|
|
44
|
+
const width = high - low;
|
|
45
|
+
let x;
|
|
46
|
+
if (bisect) x = (low + high) / 2;
|
|
47
|
+
else if (before !== void 0 && before.short > highShort) x = high - highShort * (before.x - high) / (before.short - highShort);
|
|
48
|
+
else x = high * (1 - highShort / highNeed);
|
|
49
|
+
const estimate = !bisect && x < high;
|
|
50
|
+
if (!(x < high)) x = (low + high) / 2;
|
|
51
|
+
const floor = low + 2 * TOLERANCE * high;
|
|
52
|
+
const clamped = !(x > floor);
|
|
53
|
+
if (clamped) x = floor;
|
|
54
|
+
fitTries.count += 1;
|
|
55
|
+
const tried = attempt(x);
|
|
56
|
+
if (fits(tried)) {
|
|
57
|
+
low = x;
|
|
58
|
+
best = tried.value;
|
|
59
|
+
if (tried.short > 0 && estimate && !clamped) break;
|
|
60
|
+
} else {
|
|
61
|
+
before = {
|
|
62
|
+
x: high,
|
|
63
|
+
short: highShort
|
|
64
|
+
};
|
|
65
|
+
high = x;
|
|
66
|
+
highShort = tried.short;
|
|
67
|
+
highNeed = tried.need;
|
|
68
|
+
}
|
|
69
|
+
bisect = !bisect && high - low > width / 2;
|
|
70
|
+
}
|
|
71
|
+
return {
|
|
72
|
+
x: low,
|
|
73
|
+
value: best
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
// src/endurance.ts
|
|
77
|
+
/**
|
|
78
|
+
* This function gives the `id` of each part that does not work in a case: the cut parts and the parts of `down`.
|
|
79
|
+
* With a stack, it also gives each part that stops.
|
|
80
|
+
*/
|
|
81
|
+
function caseStopped(caseCuts, options) {
|
|
82
|
+
const down = [...caseCuts.cuts.map((cut) => cut.part), ...options.down ?? []];
|
|
83
|
+
const out = new Set(down);
|
|
84
|
+
if (options.stack !== void 0) for (const id of stopped(options.stack, down)) out.add(id);
|
|
85
|
+
return out;
|
|
86
|
+
}
|
|
87
|
+
/** This function gives the day number of a date, or throws a `RangeError` for a date that is not `YYYY-MM-DD`. */
|
|
88
|
+
function dayOf(date) {
|
|
89
|
+
const day = dayNumber(date);
|
|
90
|
+
if (day === void 0) throw new RangeError(`The date "${date}" is not a date YYYY-MM-DD.`);
|
|
91
|
+
return day;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* This function gives the amount of each resource in the stores at a date, by the code of the resource.
|
|
95
|
+
*
|
|
96
|
+
* - A store gives nothing on its due date and after it.
|
|
97
|
+
* - A store gives nothing when its part is in `stoppedParts`.
|
|
98
|
+
*/
|
|
99
|
+
function storeAmounts(layer, at, stoppedParts = /* @__PURE__ */ new Set()) {
|
|
100
|
+
const today = dayOf(at);
|
|
101
|
+
const out = /* @__PURE__ */ new Map();
|
|
102
|
+
for (const store of layer.stores) {
|
|
103
|
+
if (store.due !== void 0 && today >= dayOf(store.due)) continue;
|
|
104
|
+
if (store.part !== void 0 && stoppedParts.has(store.part)) continue;
|
|
105
|
+
out.set(store.resource, (out.get(store.resource) ?? 0) + store.amount);
|
|
106
|
+
}
|
|
107
|
+
return out;
|
|
108
|
+
}
|
|
109
|
+
/** 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. */
|
|
110
|
+
function drawDemand(draw, caseCuts) {
|
|
111
|
+
return draw.perDay * (caseCuts.factors?.[draw.need] ?? 1);
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* This function gives the draws that take from the stores in a case: each draw whose supply stops, with a demand more than 0.
|
|
115
|
+
* The sequence is by the level (the order of `levels`), then by the code of the need.
|
|
116
|
+
*/
|
|
117
|
+
function caseDraws(layer, caseCuts, stoppedParts) {
|
|
118
|
+
const rank = (level) => {
|
|
119
|
+
const index = layer.levels.indexOf(level);
|
|
120
|
+
return index < 0 ? layer.levels.length : index;
|
|
121
|
+
};
|
|
122
|
+
return layer.draws.filter((draw) => stoppedParts.has(draw.supply) && drawDemand(draw, caseCuts) > 0).sort((a, b) => rank(a.level) - rank(b.level) || (a.need < b.need ? -1 : a.need > b.need ? 1 : 0));
|
|
123
|
+
}
|
|
124
|
+
/** This function gives the need that a converter gives, or `undefined` when it gives a resource. */
|
|
125
|
+
function giftNeed(converter) {
|
|
126
|
+
return "need" in converter.gives ? converter.gives.need : void 0;
|
|
127
|
+
}
|
|
128
|
+
/** This function gives the resource that a converter gives, or `undefined` when it gives a need. */
|
|
129
|
+
function giftResource(converter) {
|
|
130
|
+
return "resource" in converter.gives ? converter.gives.resource : void 0;
|
|
131
|
+
}
|
|
132
|
+
/** This function gives the amount of each resource that one run of a converter takes. Two lines of one resource add. */
|
|
133
|
+
function inputsOf(converter) {
|
|
134
|
+
const out = /* @__PURE__ */ new Map();
|
|
135
|
+
for (const input of converter.takes) if (input.amount > 0) out.set(input.resource, (out.get(input.resource) ?? 0) + input.amount);
|
|
136
|
+
return out;
|
|
137
|
+
}
|
|
138
|
+
/** This function tells if a converter can run in a case. Its device works, it takes a resource, and it gives an amount more than 0. */
|
|
139
|
+
function canRun(converter, stoppedParts) {
|
|
140
|
+
return converter.gives.amount > 0 && inputsOf(converter).size > 0 && (converter.device === void 0 || !stoppedParts.has(converter.device));
|
|
141
|
+
}
|
|
142
|
+
function makersOf(layer, stoppedParts) {
|
|
143
|
+
const out = /* @__PURE__ */ new Map();
|
|
144
|
+
for (const converter of layer.converters ?? []) {
|
|
145
|
+
const resource = giftResource(converter);
|
|
146
|
+
if (resource === void 0 || !canRun(converter, stoppedParts)) continue;
|
|
147
|
+
out.set(resource, [...out.get(resource) ?? [], converter]);
|
|
148
|
+
}
|
|
149
|
+
return out;
|
|
150
|
+
}
|
|
151
|
+
function waysOf(layer, need, stoppedParts, makers) {
|
|
152
|
+
return {
|
|
153
|
+
direct: (layer.direct ?? []).filter((use) => use.need === need && use.amount > 0),
|
|
154
|
+
converters: (layer.converters ?? []).filter((converter) => giftNeed(converter) === need && canRun(converter, stoppedParts)),
|
|
155
|
+
makers
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
const NO_PATH = /* @__PURE__ */ new Set();
|
|
159
|
+
/**
|
|
160
|
+
* This function gives the most of a resource that `left` gives: its stock, and the runs of each maker.
|
|
161
|
+
* It is an upper limit. When two inputs come from one resource, the true amount can be less.
|
|
162
|
+
*/
|
|
163
|
+
function mostResource(left, makers, resource, path) {
|
|
164
|
+
let total = left.get(resource) ?? 0;
|
|
165
|
+
if (path.has(resource)) return total;
|
|
166
|
+
const next = new Set(path).add(resource);
|
|
167
|
+
for (const maker of makers.get(resource) ?? []) total += mostRuns(left, makers, maker, next) * maker.gives.amount;
|
|
168
|
+
return total;
|
|
169
|
+
}
|
|
170
|
+
/** This function gives the most runs of a converter that `left` gives. It is an upper limit, as for `mostResource`. */
|
|
171
|
+
function mostRuns(left, makers, converter, path) {
|
|
172
|
+
let runs = 1e400;
|
|
173
|
+
for (const [resource, each] of inputsOf(converter)) runs = Math.min(runs, mostResource(left, makers, resource, path) / each);
|
|
174
|
+
return Number.isFinite(runs) ? runs : 0;
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* This function takes an amount of a resource from `left`: the stock first, then the makers in the order of the layer.
|
|
178
|
+
* It changes `left`, and it gives the amount that it could not take.
|
|
179
|
+
*/
|
|
180
|
+
function takeResource(left, makers, resource, amount, path) {
|
|
181
|
+
const has = left.get(resource) ?? 0;
|
|
182
|
+
const got = Math.min(amount, has);
|
|
183
|
+
left.set(resource, has - got);
|
|
184
|
+
let rest = amount - got;
|
|
185
|
+
if (rest <= 0 || path.has(resource)) return Math.max(0, rest);
|
|
186
|
+
const next = new Set(path).add(resource);
|
|
187
|
+
for (const maker of makers.get(resource) ?? []) {
|
|
188
|
+
if (rest <= 0) break;
|
|
189
|
+
rest -= run(left, makers, maker, rest / maker.gives.amount, next) * maker.gives.amount;
|
|
190
|
+
}
|
|
191
|
+
return Math.max(0, rest);
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* This function runs a converter up to `wanted` times with the resources of `left`, and it gives the count of runs.
|
|
195
|
+
* It changes `left`. When two inputs come from one resource, `largestFit` finds the runs that the resources give.
|
|
196
|
+
*/
|
|
197
|
+
function run(left, makers, converter, wanted, path) {
|
|
198
|
+
const inputs = inputsOf(converter);
|
|
199
|
+
const most = Math.min(wanted, mostRuns(left, makers, converter, path));
|
|
200
|
+
if (!(most > 0)) return 0;
|
|
201
|
+
const attempt = (runs) => {
|
|
202
|
+
const copy = new Map(left);
|
|
203
|
+
let need = 0;
|
|
204
|
+
let short = 0;
|
|
205
|
+
for (const [resource, each] of inputs) {
|
|
206
|
+
need += runs * each;
|
|
207
|
+
short += takeResource(copy, makers, resource, runs * each, path);
|
|
208
|
+
}
|
|
209
|
+
return {
|
|
210
|
+
short,
|
|
211
|
+
need,
|
|
212
|
+
value: copy
|
|
213
|
+
};
|
|
214
|
+
};
|
|
215
|
+
const { x: runs, value: best } = largestFit(most, attempt);
|
|
216
|
+
if (best === void 0) return 0;
|
|
217
|
+
for (const [resource, amount] of best) left.set(resource, amount);
|
|
218
|
+
return runs;
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* This function takes an amount of a need from the resources in `left`: the direct uses first, then the converters.
|
|
222
|
+
* A direct use or a converter takes each resource from its stock first, then from its makers.
|
|
223
|
+
* It changes `left`, and it gives the amount that it could not take.
|
|
224
|
+
*/
|
|
225
|
+
function take(left, ways, amount) {
|
|
226
|
+
let rest = amount;
|
|
227
|
+
for (const use of ways.direct) {
|
|
228
|
+
if (rest <= 0) break;
|
|
229
|
+
const wanted = rest / use.amount;
|
|
230
|
+
rest -= (wanted - takeResource(left, ways.makers, use.resource, wanted, NO_PATH)) * use.amount;
|
|
231
|
+
}
|
|
232
|
+
for (const converter of ways.converters) {
|
|
233
|
+
if (rest <= 0) break;
|
|
234
|
+
rest -= run(left, ways.makers, converter, rest / converter.gives.amount, NO_PATH) * converter.gives.amount;
|
|
235
|
+
}
|
|
236
|
+
return Math.max(0, rest);
|
|
237
|
+
}
|
|
238
|
+
/** This function gives each resource that a need can use: the inputs of its ways, and the inputs of their makers, through each chain. */
|
|
239
|
+
function inputClosure(ways) {
|
|
240
|
+
const out = /* @__PURE__ */ new Set();
|
|
241
|
+
const queue = [...ways.direct.map((use) => use.resource), ...ways.converters.flatMap((converter) => [...inputsOf(converter).keys()])];
|
|
242
|
+
for (let resource = queue.shift(); resource !== void 0; resource = queue.shift()) {
|
|
243
|
+
if (out.has(resource)) continue;
|
|
244
|
+
out.add(resource);
|
|
245
|
+
for (const maker of ways.makers.get(resource) ?? []) queue.push(...inputsOf(maker).keys());
|
|
246
|
+
}
|
|
247
|
+
return out;
|
|
248
|
+
}
|
|
249
|
+
/** The relative tolerance of a used-up resource. */
|
|
250
|
+
const USED_UP = 1e-9;
|
|
251
|
+
/**
|
|
252
|
+
* This function gives the days that each draw holds when a case stops its supply, and the resources that are used up then.
|
|
253
|
+
*
|
|
254
|
+
* - 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.
|
|
255
|
+
* - The demand of a draw for each day is its rate times the factor of the case.
|
|
256
|
+
* - 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.
|
|
257
|
+
* - The days of a draw are the largest `T` at which the stores give `T` days of its demand, after each higher draw.
|
|
258
|
+
* - 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.
|
|
259
|
+
* - 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.
|
|
260
|
+
* - A converter whose device stops gives nothing. A store whose part stops gives nothing.
|
|
261
|
+
* - A converter can give a resource. A take of a resource uses the stock first, then the converters that make it, through each chain.
|
|
262
|
+
*
|
|
263
|
+
* 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.
|
|
264
|
+
*
|
|
265
|
+
* @param layer - The endurance layer
|
|
266
|
+
* @param caseCuts - The case
|
|
267
|
+
* @param options - The date, and the stack or the parts that are also down
|
|
268
|
+
* @returns The endurance of each draw whose supply stops
|
|
269
|
+
*/
|
|
270
|
+
function enduranceOf(layer, caseCuts, options) {
|
|
271
|
+
const stoppedParts = caseStopped(caseCuts, options);
|
|
272
|
+
const start = storeAmounts(layer, options.at, stoppedParts);
|
|
273
|
+
const makers = makersOf(layer, stoppedParts);
|
|
274
|
+
const stocked = new Set(layer.stores.map((store) => store.resource));
|
|
275
|
+
const done = [];
|
|
276
|
+
const needs = {};
|
|
277
|
+
for (const draw of caseDraws(layer, caseCuts, stoppedParts)) {
|
|
278
|
+
const ways = waysOf(layer, draw.need, stoppedParts, makers);
|
|
279
|
+
const demand = drawDemand(draw, caseCuts);
|
|
280
|
+
const before = new Map(start);
|
|
281
|
+
for (const higher of done) take(before, higher.ways, higher.days * higher.demand);
|
|
282
|
+
const after = (days) => {
|
|
283
|
+
const left = new Map(before);
|
|
284
|
+
return {
|
|
285
|
+
left,
|
|
286
|
+
short: take(left, ways, days * demand)
|
|
287
|
+
};
|
|
288
|
+
};
|
|
289
|
+
const fit = largestFit(capacity(start, ways) / demand, (days) => {
|
|
290
|
+
const tried = after(days);
|
|
291
|
+
return {
|
|
292
|
+
short: tried.short,
|
|
293
|
+
need: days * demand,
|
|
294
|
+
value: tried.left
|
|
295
|
+
};
|
|
296
|
+
});
|
|
297
|
+
const low = fit.x;
|
|
298
|
+
const left = fit.value ?? after(low).left;
|
|
299
|
+
const binding = [...inputClosure(ways)].filter((resource) => !makers.has(resource) || stocked.has(resource)).filter((resource) => mostResource(left, makers, resource, NO_PATH) <= USED_UP * Math.max(1, start.get(resource) ?? 0)).sort();
|
|
300
|
+
const takes = {};
|
|
301
|
+
for (const [resource, amount] of before) {
|
|
302
|
+
const taken = amount - (left.get(resource) ?? 0);
|
|
303
|
+
if (taken > 0) takes[resource] = taken;
|
|
304
|
+
}
|
|
305
|
+
needs[draw.need] = {
|
|
306
|
+
days: low,
|
|
307
|
+
binding,
|
|
308
|
+
takes
|
|
309
|
+
};
|
|
310
|
+
done.push({
|
|
311
|
+
ways,
|
|
312
|
+
demand,
|
|
313
|
+
days: low
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
return {
|
|
317
|
+
case: caseCuts.case,
|
|
318
|
+
at: options.at,
|
|
319
|
+
needs
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* This function gives an upper limit of a need that the stores give with no other draw, through each chain.
|
|
324
|
+
* A converter that takes nothing gives nothing: the gate refuses it.
|
|
325
|
+
*/
|
|
326
|
+
function capacity(start, ways) {
|
|
327
|
+
let total = 0;
|
|
328
|
+
for (const use of ways.direct) total += mostResource(start, ways.makers, use.resource, NO_PATH) * use.amount;
|
|
329
|
+
for (const converter of ways.converters) total += mostRuns(start, ways.makers, converter, NO_PATH) * converter.gives.amount;
|
|
330
|
+
return total;
|
|
331
|
+
}
|
|
332
|
+
// src/check.ts
|
|
333
|
+
/**
|
|
334
|
+
* These are the codes of the gate. Each code is an error, except `endurance-no-way`, which is a warning.
|
|
335
|
+
*
|
|
336
|
+
* - `endurance-twice`: two or more records of one list have one key. A key is a level, a resource, a store, a need, a converter or a case.
|
|
337
|
+
* The key of a prior is its case and its place. A converter takes each resource on one line, and a case cuts each part one time.
|
|
338
|
+
* - `endurance-level-unknown`: the level of a draw is not a level of the layer.
|
|
339
|
+
* - `endurance-resource-unknown`: a store, a use or a converter names a resource that the layer does not have.
|
|
340
|
+
* - `endurance-part-unknown`: a supply, a device, the part of a store or a cut is not a part of the base stack.
|
|
341
|
+
* - `endurance-range`: an amount, a rate, a count or a factor is not a finite number of 0 or more. Or a reach is not from 0 to 1.
|
|
342
|
+
* - `endurance-date`: a date is not a date `YYYY-MM-DD`.
|
|
343
|
+
* - `endurance-converter-empty`: a converter takes nothing, or it gives an amount of 0.
|
|
344
|
+
* - `endurance-curve`: a survival curve does not start at `[0, 1]`, or it does not end at a chance of 0.
|
|
345
|
+
* Or its days do not increase, or its chance increases.
|
|
346
|
+
* - `endurance-prior-case`: a prior names a case that the layer does not have.
|
|
347
|
+
* - `endurance-cycle`: converters make a resource from itself, through one converter or a chain. One fault names each cycle.
|
|
348
|
+
* - `endurance-no-way` (warning): a draw has no direct use and no converter, so it holds 0 days when its supply stops.
|
|
349
|
+
*/
|
|
350
|
+
const ENDURANCE_CODES = [
|
|
351
|
+
"endurance-twice",
|
|
352
|
+
"endurance-level-unknown",
|
|
353
|
+
"endurance-resource-unknown",
|
|
354
|
+
"endurance-part-unknown",
|
|
355
|
+
"endurance-range",
|
|
356
|
+
"endurance-date",
|
|
357
|
+
"endurance-converter-empty",
|
|
358
|
+
"endurance-curve",
|
|
359
|
+
"endurance-prior-case",
|
|
360
|
+
"endurance-cycle",
|
|
361
|
+
"endurance-no-way"
|
|
362
|
+
];
|
|
363
|
+
/** This function gives the first fault of a survival curve, or `undefined`. */
|
|
364
|
+
function curveFault(curve) {
|
|
365
|
+
const first = curve[0];
|
|
366
|
+
if (first === void 0 || first[0] !== 0 || first[1] !== 1) return "The curve does not start at [0, 1].";
|
|
367
|
+
for (let index = 1; index < curve.length; index += 1) {
|
|
368
|
+
const [t0, p0] = curve[index - 1] ?? [0, 1];
|
|
369
|
+
const [t1, p1] = curve[index] ?? [0, 0];
|
|
370
|
+
if (!(Number.isFinite(t1) && t1 > t0)) return `The days of the point ${String(index)} are not more than the days of the point before it.`;
|
|
371
|
+
if (!(p1 >= 0 && p1 <= p0)) return `The chance of the point ${String(index)} is not from 0 to the chance of the point before it.`;
|
|
372
|
+
}
|
|
373
|
+
if (curve[curve.length - 1]?.[1] !== 0) return "The curve does not end at a chance of 0.";
|
|
374
|
+
}
|
|
375
|
+
/**
|
|
376
|
+
* This function gives each fault of an endurance layer. With a base stack, it also examines the `id` of each part. A list with no error tells that the gate passes.
|
|
377
|
+
*
|
|
378
|
+
* The faults are in the order of the layer. The function is pure.
|
|
379
|
+
*
|
|
380
|
+
* @param layer - The endurance layer
|
|
381
|
+
* @param stack - The base stack, with the layer. With no stack, the gate does not examine the parts.
|
|
382
|
+
* @returns The faults
|
|
383
|
+
*/
|
|
384
|
+
function checkEndurance(layer, stack) {
|
|
385
|
+
const faults = [];
|
|
386
|
+
const add = (level, code, at, message) => {
|
|
387
|
+
faults.push({
|
|
388
|
+
level,
|
|
389
|
+
code,
|
|
390
|
+
at,
|
|
391
|
+
message
|
|
392
|
+
});
|
|
393
|
+
};
|
|
394
|
+
const once = (what, keys) => {
|
|
395
|
+
const seen = /* @__PURE__ */ new Set();
|
|
396
|
+
for (const key of keys) {
|
|
397
|
+
if (seen.has(key)) add("error", "endurance-twice", key, `Two or more ${what} have the key "${key}".`);
|
|
398
|
+
seen.add(key);
|
|
399
|
+
}
|
|
400
|
+
};
|
|
401
|
+
const range = (at, what, value) => {
|
|
402
|
+
if (!(Number.isFinite(value) && value >= 0)) add("error", "endurance-range", at, `The ${what} of "${at}" is ${String(value)}. It must be a finite number of 0 or more.`);
|
|
403
|
+
};
|
|
404
|
+
const date = (at, value) => {
|
|
405
|
+
if (dayNumber(value) === void 0) add("error", "endurance-date", at, `The date "${value}" of "${at}" is not a date YYYY-MM-DD.`);
|
|
406
|
+
};
|
|
407
|
+
const parts = stack === void 0 ? void 0 : new Set(stack.parts.map((part) => part.id));
|
|
408
|
+
const part = (at, what, id) => {
|
|
409
|
+
if (parts !== void 0 && id !== void 0 && !parts.has(id)) add("error", "endurance-part-unknown", at, `The ${what} "${id}" of "${at}" is not a part of the stack.`);
|
|
410
|
+
};
|
|
411
|
+
const resources = new Set(layer.resources.map((resource) => resource.code));
|
|
412
|
+
const resource = (at, code) => {
|
|
413
|
+
if (!resources.has(code)) add("error", "endurance-resource-unknown", at, `The resource "${code}" of "${at}" is not a resource of the layer.`);
|
|
414
|
+
};
|
|
415
|
+
const direct = layer.direct ?? [];
|
|
416
|
+
const converters = layer.converters ?? [];
|
|
417
|
+
const cases = layer.cases ?? [];
|
|
418
|
+
const priors = layer.priors ?? [];
|
|
419
|
+
once("levels", layer.levels);
|
|
420
|
+
once("resources", layer.resources.map((item) => item.code));
|
|
421
|
+
once("stores", layer.stores.map((store) => store.id));
|
|
422
|
+
once("draws", layer.draws.map((draw) => draw.need));
|
|
423
|
+
once("converters", converters.map((converter) => converter.id));
|
|
424
|
+
once("cases", cases.map((item) => item.case));
|
|
425
|
+
once("priors", priors.map((prior) => `${prior.case}@${prior.place}`));
|
|
426
|
+
for (const store of layer.stores) {
|
|
427
|
+
resource(store.id, store.resource);
|
|
428
|
+
range(store.id, "amount", store.amount);
|
|
429
|
+
if (store.due !== void 0) date(store.id, store.due);
|
|
430
|
+
part(store.id, "part", store.part);
|
|
431
|
+
}
|
|
432
|
+
const levels = new Set(layer.levels);
|
|
433
|
+
for (const draw of layer.draws) {
|
|
434
|
+
if (!levels.has(draw.level)) add("error", "endurance-level-unknown", draw.need, `The level "${draw.level}" of the draw "${draw.need}" is not a level of the layer.`);
|
|
435
|
+
range(draw.need, "rate", draw.perDay);
|
|
436
|
+
if (draw.users !== void 0) range(draw.need, "count of users", draw.users);
|
|
437
|
+
part(draw.need, "supply", draw.supply);
|
|
438
|
+
if (!(direct.some((use) => use.need === draw.need) || converters.some((converter) => giftNeed(converter) === draw.need))) add("warning", "endurance-no-way", draw.need, `The draw "${draw.need}" has no direct use and no converter. It holds 0 days when its supply stops.`);
|
|
439
|
+
}
|
|
440
|
+
for (const use of direct) {
|
|
441
|
+
const at = `${use.resource}>${use.need}`;
|
|
442
|
+
resource(at, use.resource);
|
|
443
|
+
range(at, "amount", use.amount);
|
|
444
|
+
}
|
|
445
|
+
for (const converter of converters) {
|
|
446
|
+
once(`resources of the converter "${converter.id}"`, converter.takes.map((input) => input.resource));
|
|
447
|
+
for (const input of converter.takes) {
|
|
448
|
+
resource(converter.id, input.resource);
|
|
449
|
+
range(converter.id, "amount", input.amount);
|
|
450
|
+
}
|
|
451
|
+
range(converter.id, "amount", converter.gives.amount);
|
|
452
|
+
const made = giftResource(converter);
|
|
453
|
+
if (made !== void 0) resource(converter.id, made);
|
|
454
|
+
if (!converter.takes.some((input) => input.amount > 0) || converter.gives.amount === 0) add("error", "endurance-converter-empty", converter.id, `The converter "${converter.id}" takes nothing, or it gives nothing.`);
|
|
455
|
+
part(converter.id, "device", converter.device);
|
|
456
|
+
}
|
|
457
|
+
const caseCodes = new Set(cases.map((item) => item.case));
|
|
458
|
+
for (const item of cases) {
|
|
459
|
+
once(`cuts of the case "${item.case}"`, item.cuts.map((cut) => cut.part));
|
|
460
|
+
for (const cut of item.cuts) {
|
|
461
|
+
const at = `${item.case}/${cut.part}`;
|
|
462
|
+
part(at, "cut", cut.part);
|
|
463
|
+
const fault = curveFault(cut.duration);
|
|
464
|
+
if (fault !== void 0) add("error", "endurance-curve", at, `The duration of the cut "${at}": ${fault}`);
|
|
465
|
+
}
|
|
466
|
+
for (const [need, factor] of Object.entries(item.factors ?? {})) range(`${item.case}/${need}`, "factor", factor);
|
|
467
|
+
if (item.leadSeconds !== void 0) range(item.case, "lead time", item.leadSeconds);
|
|
468
|
+
}
|
|
469
|
+
for (const cycle of resourceCycles(converters)) {
|
|
470
|
+
const [first = ""] = cycle;
|
|
471
|
+
const names = cycle.map((code) => `"${code}"`).join(", ");
|
|
472
|
+
add("error", "endurance-cycle", first, `${cycle.length === 1 ? `A converter makes the resource ${names} from itself.` : `Converters make the resources ${names} from each other.`} A chain of converters cannot end.`);
|
|
473
|
+
}
|
|
474
|
+
for (const prior of priors) {
|
|
475
|
+
const at = `${prior.case}@${prior.place}`;
|
|
476
|
+
if (!caseCodes.has(prior.case)) add("error", "endurance-prior-case", at, `The prior "${at}" names the case "${prior.case}", which the layer does not have.`);
|
|
477
|
+
range(at, "count of events in one year", prior.perYear);
|
|
478
|
+
if (!(prior.reach >= 0 && prior.reach <= 1)) add("error", "endurance-range", at, `The reach of "${at}" is ${String(prior.reach)}. It must be from 0 to 1.`);
|
|
479
|
+
date(at, prior.asOf);
|
|
480
|
+
}
|
|
481
|
+
return faults;
|
|
482
|
+
}
|
|
483
|
+
/** This function gives each cycle of resources: a resource is made from a resource that a converter makes from it. Each cycle is a list of codes. */
|
|
484
|
+
function resourceCycles(converters) {
|
|
485
|
+
const from = /* @__PURE__ */ new Map();
|
|
486
|
+
for (const converter of converters) {
|
|
487
|
+
const made = giftResource(converter);
|
|
488
|
+
if (made === void 0) continue;
|
|
489
|
+
const inputs = from.get(made) ?? /* @__PURE__ */ new Set();
|
|
490
|
+
for (const input of converter.takes) if (input.amount > 0) inputs.add(input.resource);
|
|
491
|
+
from.set(made, inputs);
|
|
492
|
+
}
|
|
493
|
+
const successors = (code) => from.get(code) ?? [];
|
|
494
|
+
return stronglyConnectedComponents(from.keys(), successors).filter((component) => {
|
|
495
|
+
const [only = ""] = component;
|
|
496
|
+
return component.length > 1 || (from.get(only)?.has(only) ?? false);
|
|
497
|
+
});
|
|
498
|
+
}
|
|
499
|
+
/** This function tells if a list of faults has an error. */
|
|
500
|
+
function hasEnduranceError(faults) {
|
|
501
|
+
return faults.some((fault) => fault.level === "error");
|
|
502
|
+
}
|
|
503
|
+
// src/join.ts
|
|
504
|
+
/**
|
|
505
|
+
* This function joins the endurance layers of the fragments of a stack into one layer.
|
|
506
|
+
*
|
|
507
|
+
* - The levels are one setting: each fragment that has levels gives the same list, else the join has a fault.
|
|
508
|
+
* - The records of each list are in the order of the fragments.
|
|
509
|
+
* - One key in two or more fragments is a fault, also when the records are equal. The key of a direct use is its resource and its need.
|
|
510
|
+
*
|
|
511
|
+
* The function is pure, and it changes no layer. The gate `checkEndurance` examines the joined layer afterward.
|
|
512
|
+
*
|
|
513
|
+
* @param pieces - The layers, with the name of the fragment of each one, in the order of the fragments.
|
|
514
|
+
* @returns The joined layer, or the faults of the join.
|
|
515
|
+
*/
|
|
516
|
+
function joinEndurance(pieces) {
|
|
517
|
+
const levels = joinSetting(pieces, (layer) => layer.levels.length > 0 ? layer.levels.join("\n") : void 0, "levels");
|
|
518
|
+
const resources = joinRecords(pieces, (layer) => layer.resources, (item) => item.code, "resource");
|
|
519
|
+
const stores = joinRecords(pieces, (layer) => layer.stores, (item) => item.id, "store");
|
|
520
|
+
const draws = joinRecords(pieces, (layer) => layer.draws, (item) => item.need, "draw");
|
|
521
|
+
const direct = joinRecords(pieces, (layer) => layer.direct, (item) => `${item.resource}>${item.need}`, "direct use");
|
|
522
|
+
const converters = joinRecords(pieces, (layer) => layer.converters, (item) => item.id, "converter");
|
|
523
|
+
const cases = joinRecords(pieces, (layer) => layer.cases, (item) => item.case, "case");
|
|
524
|
+
const priors = joinRecords(pieces, (layer) => layer.priors, (item) => `${item.case}@${item.place}`, "prior");
|
|
525
|
+
const errors = [
|
|
526
|
+
levels,
|
|
527
|
+
resources,
|
|
528
|
+
stores,
|
|
529
|
+
draws,
|
|
530
|
+
direct,
|
|
531
|
+
converters,
|
|
532
|
+
cases,
|
|
533
|
+
priors
|
|
534
|
+
].flatMap((join) => join.errors);
|
|
535
|
+
if (errors.length > 0) return {
|
|
536
|
+
ok: false,
|
|
537
|
+
errors
|
|
538
|
+
};
|
|
539
|
+
const has = (key) => pieces.some((piece) => piece.layer[key] !== void 0);
|
|
540
|
+
return {
|
|
541
|
+
ok: true,
|
|
542
|
+
layer: {
|
|
543
|
+
schema: ENDURANCE_SCHEMA,
|
|
544
|
+
levels: levels.value === void 0 ? [] : levels.value.split("\n"),
|
|
545
|
+
resources: resources.items,
|
|
546
|
+
stores: stores.items,
|
|
547
|
+
draws: draws.items,
|
|
548
|
+
...has("direct") ? { direct: direct.items } : {},
|
|
549
|
+
...has("converters") ? { converters: converters.items } : {},
|
|
550
|
+
...has("cases") ? { cases: cases.items } : {},
|
|
551
|
+
...has("priors") ? { priors: priors.items } : {}
|
|
552
|
+
}
|
|
553
|
+
};
|
|
554
|
+
}
|
|
555
|
+
export { hasEnduranceError as a, drawDemand as c, giftResource as d, storeAmounts as f, curveFault as i, enduranceOf as l, ENDURANCE_CODES as n, caseDraws as o, checkEndurance as r, caseStopped as s, joinEndurance as t, giftNeed as u };
|
|
556
|
+
|
|
557
|
+
//# sourceMappingURL=join-D7KyUpGf.js.map
|