@mark1russell7/capacity 0.1.0 → 0.1.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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["problem","problem"],"sources":["../src/forms.ts","../src/fit.ts","../src/knee.ts","../src/gate.ts","../src/app-metrics.ts","../src/observe.ts","../src/limit.ts","../src/scale.ts"],"sourcesContent":["import { err, ok, type Result } from \"@mark1russell7/optional\";\nimport { fitSeparable, SEPARABLE_MAX_COMBINATIONS, type SeparableFit, type SeparableModel } from \"@mark1russell7/rigor-statistics\";\nimport { app, let_, lit, ref, v, type Expr } from \"@mark1russell7/vex\";\nimport type { Constant, Form } from \"./law.ts\";\nimport { valuesOf } from \"./program.ts\";\n\n/** This name is the name of the load variable in the programs of the catalog. A binding gives its id in a law. */\nexport const FORM_VARIABLE = \"x\";\n\n/**\n * A term is one part of a form: its constant times its basis. The basis and its slope read the\n * variable and the shape constants of the form with `v(name)`. The slope is the change of the basis\n * for each unit of the variable.\n */\nexport interface Term {\n readonly constant: string;\n readonly basis: Expr;\n readonly slope: Expr;\n}\n\n/**\n * A grid gives the start candidates of one shape constant from the points of a fit.\n *\n * - `inside` gives each distinct value of the variable inside its range, and each middle of two\n * values that follow. A knee starts at these values.\n * - `scaled` gives each factor times the largest size of the variable to the `power`. With the power\n * 0, the candidates are the factors.\n */\nexport type Grid =\n | { readonly kind: \"inside\" }\n | { readonly kind: \"scaled\"; readonly factors: readonly number[]; readonly power: number };\n\n/**\n * The bounds tell where the refine of a fit can move a shape constant. They come from the points of the fit.\n *\n * - `range` is from the least value of the variable to its largest value. A knee is inside the range.\n * - `size` is from the largest size of the variable up. The capacity of a queue is past each load.\n * - `least` is from `value` up.\n */\nexport type Bounds = { readonly kind: \"range\" } | { readonly kind: \"size\" } | { readonly kind: \"least\"; readonly value: number };\n\n/**\n * A shape constant changes the shape of a form, not its size. A fit starts it at each value of its grid. Then the fit\n * refines it inside its bounds. A shape with no bounds has no limit.\n */\nexport interface Shape {\n readonly id: string;\n readonly grid: Grid;\n readonly bounds?: Bounds;\n}\n\n/**\n * A catalog form is the math of a law of one variable, as data. Its value is the sum of its terms.\n * Thus, with fixed shape constants, a fit of a form is linear in the constants of its terms.\n */\nexport interface CatalogForm {\n readonly id: string;\n readonly title: string;\n readonly terms: readonly Term[];\n readonly shapes: readonly Shape[];\n}\n\n/**\n * A binding puts a catalog form into a law. It gives the id of the variable in the law, and the id\n * in the law of each constant. A constant with no entry keeps its id from the catalog.\n */\nexport interface Binding {\n readonly variable: string;\n readonly constants?: Readonly<Record<string, string>>;\n}\n\n/** The points of a fit: the value of the variable and the measured value of each point, in the same order. */\nexport interface Points {\n readonly x: readonly number[];\n readonly y: readonly number[];\n}\n\n/** A start is the start values of the constants of a form, and the sum of the squared residuals at these values. */\nexport interface Start {\n readonly constants: readonly Constant[];\n readonly rss: number;\n}\n\nconst x = v(FORM_VARIABLE);\nconst one = lit(1);\nconst zero = lit(0);\nconst add = (...parts: readonly Expr[]): Expr => parts.reduce((sum, part) => app(\"add\", sum, part));\nconst times = (a: Expr, b: Expr): Expr => app(\"multiply\", a, b);\nconst over = (a: Expr, b: Expr): Expr => app(\"divide\", a, b);\nconst less = (a: Expr, b: Expr): Expr => app(\"subtract\", a, b);\nconst square = (a: Expr): Expr => app(\"pow\", a, lit(2));\nconst scaled = (factors: readonly number[], power: number): Grid => ({ kind: \"scaled\", factors, power });\nconst positive: Bounds = { kind: \"least\", value: 0 };\n\n/** The base term: a constant amount. Its slope is 0. */\nconst base: Term = { constant: \"base\", basis: one, slope: zero };\n\n/** The denominator of the scalability law: `1 + contention·(x − 1) + coherency·x·(x − 1)`. */\nconst contention = add(one, times(v(\"contention\"), less(x, one)), times(times(v(\"coherency\"), x), less(x, one)));\n\n/**\n * The catalog of the forms of a law, in the order of the roadmap. Each form is a sum of terms.\n *\n * - `constant`: `base`.\n * - `linear`: `base + slope·x`.\n * - `power`: `base + scale·x^exponent`.\n * - `fall-power`: `base + excess / x + scale·x^exponent`. The term `excess / x` is a cost at a low load that falls as the load grows.\n * - `logarithm`: `base + scale·ln(x)`.\n * - `hinge`: `base + slope·x + bend·max(0, x − knee)`. After the knee the slope is `slope + bend`.\n * - `queue`: `base + scale·capacity / (capacity − x)`. This is the delay of a queue. The form has no\n * finite value at the capacity.\n * - `scalability`: `unit·x / (1 + contention·(x − 1) + coherency·x·(x − 1))`. This is the\n * universal scalability law of the throughput at a concurrency `x`.\n * - `drift`: `base + drift·x + warm·(1 − e^(−x / settle))`. This is a measure over the age of a\n * process: a warm-up that settles, and a steady drift.\n */\nexport const FORMS: readonly CatalogForm[] = [\n { id: \"constant\", title: \"A constant\", terms: [base], shapes: [] },\n { id: \"linear\", title: \"A line\", terms: [base, { constant: \"slope\", basis: x, slope: one }], shapes: [] },\n {\n id: \"power\",\n title: \"A power of the variable\",\n terms: [\n base,\n {\n constant: \"scale\",\n basis: app(\"pow\", x, v(\"exponent\")),\n slope: times(v(\"exponent\"), app(\"pow\", x, less(v(\"exponent\"), one))),\n },\n ],\n shapes: [{ id: \"exponent\", grid: scaled([-1, -0.5, 0.25, 0.5, 0.75, 1, 1.25, 1.5, 2, 3], 0) }],\n },\n {\n id: \"fall-power\",\n title: \"A fall at a low load, then a power of the variable\",\n terms: [\n base,\n { constant: \"excess\", basis: over(one, x), slope: app(\"negate\", over(one, square(x))) },\n {\n constant: \"scale\",\n basis: app(\"pow\", x, v(\"exponent\")),\n slope: times(v(\"exponent\"), app(\"pow\", x, less(v(\"exponent\"), one))),\n },\n ],\n shapes: [{ id: \"exponent\", grid: scaled([0.25, 0.5, 0.75, 1, 1.25, 1.5, 2, 3], 0) }],\n },\n {\n id: \"logarithm\",\n title: \"A logarithm of the variable\",\n terms: [base, { constant: \"scale\", basis: app(\"ln\", x), slope: over(one, x) }],\n shapes: [],\n },\n {\n id: \"hinge\",\n title: \"Two lines that join at a knee\",\n terms: [\n base,\n { constant: \"slope\", basis: x, slope: one },\n {\n constant: \"bend\",\n basis: app(\"max\", zero, less(x, v(\"knee\"))),\n slope: app(\"if\", app(\"gt\", x, v(\"knee\")), one, zero),\n },\n ],\n shapes: [{ id: \"knee\", grid: { kind: \"inside\" }, bounds: { kind: \"range\" } }],\n },\n {\n id: \"queue\",\n title: \"The delay of a queue\",\n terms: [\n base,\n {\n constant: \"scale\",\n basis: over(v(\"capacity\"), less(v(\"capacity\"), x)),\n slope: over(v(\"capacity\"), square(less(v(\"capacity\"), x))),\n },\n ],\n shapes: [{ id: \"capacity\", grid: scaled([1.02, 1.05, 1.1, 1.2, 1.5, 2, 3, 5, 10], 1), bounds: { kind: \"size\" } }],\n },\n {\n id: \"scalability\",\n title: \"The universal scalability law\",\n terms: [\n {\n constant: \"unit\",\n basis: over(x, contention),\n // (D − x·D′) / D², with D′ = contention + coherency·(2x − 1): this is (1 − contention − coherency·x²) / D²\n slope: over(less(less(one, v(\"contention\")), times(v(\"coherency\"), square(x))), square(contention)),\n },\n ],\n shapes: [\n { id: \"contention\", grid: scaled([0, 0.01, 0.03, 0.1, 0.2, 0.4, 0.7], 0), bounds: positive },\n { id: \"coherency\", grid: scaled([0, 0.1, 0.3, 1, 3, 10], -2), bounds: positive },\n ],\n },\n {\n id: \"drift\",\n title: \"A warm-up and a drift with age\",\n terms: [\n base,\n { constant: \"drift\", basis: x, slope: one },\n {\n constant: \"warm\",\n basis: less(one, app(\"exp\", app(\"negate\", over(x, v(\"settle\"))))),\n slope: over(app(\"exp\", app(\"negate\", over(x, v(\"settle\")))), v(\"settle\")),\n },\n ],\n shapes: [{ id: \"settle\", grid: scaled([0.01, 0.03, 0.1, 0.3, 1, 3], 1), bounds: positive }],\n },\n];\n\n/** This function gives the form of the catalog with the id, or undefined. */\nexport const catalogForm = (id: string): CatalogForm | undefined => FORMS.find((form) => form.id === id);\n\n/** This function gives the ids of the constants of a form: the constant of each term, then each shape constant. */\nexport const constantIdsOf = (form: CatalogForm): readonly string[] => [\n ...form.terms.map((term) => term.constant),\n ...form.shapes.map((shape) => shape.id),\n];\n\n/** This function gives the sum of the terms of a form, with `part` for each term. A term of 0 does not count. */\nconst sumOf = (form: CatalogForm, part: (term: Term) => Expr): Expr => {\n const parts = form.terms\n .map((term) => ({ term, expr: part(term) }))\n .filter(({ expr }) => !(expr.tag === \"lit\" && expr.value === 0))\n .map(({ term, expr }) => (expr.tag === \"lit\" && expr.value === 1 ? v(term.constant) : times(v(term.constant), expr)));\n return parts.length === 0 ? zero : add(...parts);\n};\n\n/** This function binds the names `ids` of a form and its variable to the reads of a law. */\nconst bind = (ids: readonly string[], binding: Binding, body: Expr): Expr =>\n let_(Object.fromEntries([[FORM_VARIABLE, ref(binding.variable)], ...ids.map((id) => [id, ref(binding.constants?.[id] ?? id)])]), body);\n\n/** This function binds each name of a form to the reads of a law: the variable and each constant. */\nconst bound = (form: CatalogForm, binding: Binding, body: Expr): Expr => bind(constantIdsOf(form), binding, body);\n\n/** This function gives the program of the value of a form in a law. It reads the variable and each constant of the binding. */\nexport const programOf = (form: CatalogForm, binding: Binding): Expr => bound(form, binding, sumOf(form, (term) => term.basis));\n\n/** This function gives the program of the slope of a form in a law: the change of its value for each unit of the variable. */\nexport const slopeOf = (form: CatalogForm, binding: Binding): Expr => bound(form, binding, sumOf(form, (term) => term.slope));\n\n/** This function gives the form of a law from a form of the catalog. */\nexport const formOf = (form: CatalogForm, binding: Binding): Form => ({ id: form.id, program: programOf(form, binding) });\n\nconst records = (xs: readonly number[], constants: Readonly<Record<string, number>>): Readonly<Record<string, number>>[] =>\n xs.map((value) => ({ ...constants, [FORM_VARIABLE]: value }));\n\n/** This function gives the value of a form at each value of its variable, or the text of the first error. */\nexport const formValues = (\n form: CatalogForm,\n xs: readonly number[],\n constants: Readonly<Record<string, number>>,\n): Result<readonly number[], string> => valuesOf(programOf(form, { variable: FORM_VARIABLE }), records(xs, constants));\n\n/** This function gives the slope of a form at each value of its variable, or the text of the first error. */\nexport const formSlopes = (\n form: CatalogForm,\n xs: readonly number[],\n constants: Readonly<Record<string, number>>,\n): Result<readonly number[], string> => valuesOf(slopeOf(form, { variable: FORM_VARIABLE }), records(xs, constants));\n\n/** This function gives the largest size of the values of a variable. */\nconst sizeOf = (xs: readonly number[]): number => xs.reduce((most, value) => Math.max(most, Math.abs(value)), 0);\n\n/** This function gives the candidates of a grid for the values of a variable. */\nexport const gridOf = (grid: Grid, xs: readonly number[]): readonly number[] => {\n if (grid.kind === \"scaled\") {\n const size = sizeOf(xs);\n return grid.power === 0 ? grid.factors : size === 0 ? [] : grid.factors.map((factor) => factor * size ** grid.power);\n }\n const distinct = [...new Set(xs)].sort((a, b) => a - b);\n const middles = distinct.slice(1).map((value, index) => (value + (distinct[index] as number)) / 2);\n const low = distinct[0] ?? 0;\n const high = distinct.at(-1) ?? 0;\n return [...distinct, ...middles].filter((value) => value > low && value < high).sort((a, b) => a - b);\n};\n\n/** This function gives the bounds of the refine of a shape constant for the values of a variable. */\nconst boundsOf = (bounds: Bounds | undefined, xs: readonly number[]): { readonly min?: number; readonly max?: number } => {\n if (bounds === undefined) return {};\n if (bounds.kind === \"least\") return { min: bounds.value };\n if (bounds.kind === \"size\") return { min: sizeOf(xs) };\n return {\n min: xs.reduce((least, value) => Math.min(least, value), Number.POSITIVE_INFINITY),\n max: xs.reduce((most, value) => Math.max(most, value), Number.NEGATIVE_INFINITY),\n };\n};\n\n/**\n * This function gives a form of the catalog as a separable model of `@mark1russell7/rigor-statistics`. Each term is\n * one column of the design: the basis of the term at each point. The candidates and the bounds of each shape constant\n * come from the values `xs` of the variable. The design is null when a basis has no finite value at a point.\n */\nexport const separableOf = (form: CatalogForm, xs: readonly number[]): SeparableModel<number> => {\n const ids = form.shapes.map((shape) => shape.id);\n // a basis reads the variable and the shape constants, not the constants of the terms\n const bases = form.terms.map((term) => bind(ids, { variable: FORM_VARIABLE }, term.basis));\n return {\n terms: form.terms.map((term) => term.constant),\n shapes: form.shapes.map((shape) => ({ id: shape.id, candidates: gridOf(shape.grid, xs), ...boundsOf(shape.bounds, xs) })),\n design: (values, points) => {\n const at = Object.fromEntries(ids.map((id, index) => [id, values[index] as number]));\n const columns: (readonly number[])[] = [];\n for (const basis of bases) {\n const column = valuesOf(basis, records(points, at));\n if (column.tag === \"err\") return null;\n columns.push(column.value);\n }\n return points.map((_, row) => columns.map((column) => column[row] as number));\n },\n };\n};\n\n/** This function gives the constants of a form from a separable fit: the constant of each term, then each shape constant. */\nexport const constantsOf = (form: CatalogForm, fit: Pick<SeparableFit, \"coefficients\" | \"shapes\">): readonly Constant[] => [\n ...form.terms.map((term, index) => ({ id: term.constant, value: fit.coefficients[index] as number })),\n ...form.shapes.map((shape, index) => ({ id: shape.id, value: fit.shapes[index] as number })),\n];\n\n/** This function gives the text of the first fault of the points of a fit, or undefined. */\nexport const pointsProblem = (points: Points): string | undefined => {\n if (points.x.length === 0) return \"The fit has no points.\";\n if (points.x.length !== points.y.length) return `The points have ${points.x.length} values of x and ${points.y.length} values of y.`;\n if (![...points.x, ...points.y].every(Number.isFinite)) return \"A point has a value that is not a finite number.\";\n return undefined;\n};\n\n/** This function gives the text of the reason that the model of a form has no start, or undefined. */\nexport const modelProblem = (form: CatalogForm, model: SeparableModel<number>): string | undefined => {\n const empty = model.shapes.find((shape) => shape.candidates.length === 0);\n if (empty !== undefined) return `The form \"${form.id}\" has no start value of its shape constant \"${empty.id}\" for these points.`;\n const count = model.shapes.reduce((product, shape) => product * new Set(shape.candidates).size, 1);\n if (count > SEPARABLE_MAX_COMBINATIONS) {\n return `The form \"${form.id}\" has ${count} combinations of start values. The limit is ${SEPARABLE_MAX_COMBINATIONS}.`;\n }\n return undefined;\n};\n\n/**\n * This function gives the least-squares fit of a form to some points, as the start values of its constants.\n *\n * The fit is `fitSeparable` of `@mark1russell7/rigor-statistics`. For each combination of the grids of the shape\n * constants, the least-squares fit gives the constants of the terms. Then a golden-section search refines each shape\n * constant inside its bounds. A form with no shape constant has one combination, thus its start is its least-squares fit.\n *\n * The function gives an error when no combination has a fit, for example with fewer points than terms.\n */\nexport const startOf = (form: CatalogForm, points: Points): Result<Start, string> => {\n const fault = pointsProblem(points);\n if (fault !== undefined) return err(fault);\n const model = separableOf(form, points.x);\n const reason = modelProblem(form, model);\n if (reason !== undefined) return err(reason);\n const fit = fitSeparable(model, points.x, points.y);\n if (fit === null) return err(`The form \"${form.id}\" has no least-squares fit to ${points.x.length} points.`);\n return ok({ constants: constantsOf(form, fit), rss: fit.rss });\n};\n","import { err, ok, type Result } from \"@mark1russell7/optional\";\nimport {\n bootstrapSeparable,\n heldOutSeparable,\n rankSeparable,\n SEPARABLE_BOOTSTRAP_RUNS,\n type SeparableGroup,\n type SeparableModel,\n} from \"@mark1russell7/rigor-statistics\";\nimport { FORM_VARIABLE, FORMS, constantIdsOf, formOf, modelProblem, pointsProblem, separableOf } from \"./forms.ts\";\nimport type { Binding, CatalogForm, Points } from \"./forms.ts\";\nimport { DEFAULT_LEVEL, bootstrapDraws, leastCount, leastGroups, type FitError, type Law, type Loser, type ResidualKind } from \"./law.ts\";\n\n/** The options of `fitLaw`. */\nexport interface LawFitOptions {\n /** These forms compete for the law. The default is each form of the catalog. */\n readonly forms?: readonly CatalogForm[];\n /** This binding puts the form that wins into the law. The default is the variable `x` and the ids of the catalog. */\n readonly binding?: Binding;\n /**\n * This kind tells how the fit compares a value with a form. The default is `\"absolute\"`. A `\"relative\"` fit uses the\n * weights `1 / y^2`. Thus each value of a relative fit is not 0.\n */\n readonly residual?: ResidualKind;\n /**\n * This list gives the group of each point. The points of one group are replicates of one load. The held-out fit holds\n * out each group. The default group of a point is its value of the variable.\n */\n readonly groups?: readonly SeparableGroup[];\n /**\n * This list gives the group of each point for the bootstrap. Each run of the bootstrap draws whole groups of this\n * list. The default is the list `groups`. A group of the bootstrap is an independent unit of the data, for example\n * the job that measured its points. A plan that fixes its loads has no random load, thus a draw of whole loads is\n * the wrong model for it.\n */\n readonly bootstrapGroups?: readonly SeparableGroup[];\n /** This number is the number of runs of the bootstrap. The default is `SEPARABLE_BOOTSTRAP_RUNS` of rigor-statistics. */\n readonly runs?: number;\n /** This seed starts the draws of the bootstrap. The default is 1. */\n readonly seed?: number;\n}\n\n/** A form rank is one form that competed in a law fit, with the error of its held-out residuals. */\nexport interface FormRank {\n readonly form: string;\n /** This error comes from the held-out residuals that have a value. With no such residual, each error is NaN. */\n readonly error: FitError;\n /** This number is the number of points with no held-out prediction. */\n readonly missing: number;\n /** This text tells why the form has no fit. A form with a fit has no reason. */\n readonly reason?: string;\n}\n\n/**\n * A law fit is the part of a law that comes from a fit of its points. It has the form, the constants, the replicates and\n * the record of the fit. The list `ranks` keeps each form that competed, best first.\n */\nexport interface LawFit extends Pick<Law, \"form\" | \"constants\" | \"replicates\" | \"fit\"> {\n readonly ranks: readonly FormRank[];\n}\n\n/**\n * This function fits a law of one variable to its points. Each form competes, and the form with the smallest root mean\n * square of its held-out residuals wins. A form with a point that has no held-out prediction ranks after each form with\n * a prediction at each point.\n *\n * The fit of each form is `fitSeparable` of `@mark1russell7/rigor-statistics`. Each held-out residual comes from a fit of\n * the other groups. The replicates of the winner come from a bootstrap of the whole groups of `bootstrapGroups`. The losers of the record are\n * the other forms with a held-out prediction at each point.\n *\n * The function gives an error for points that a fit cannot use, and when no form has a held-out prediction at each point.\n * It gives an error for fewer groups of the bootstrap than `leastGroups` of the level 0.95, because their draws are too few for an interval.\n */\nexport const fitLaw = (points: Points, options: LawFitOptions = {}): Result<LawFit, string> => {\n const fault = pointsProblem(points);\n if (fault !== undefined) return err(fault);\n const n = points.x.length;\n const forms = options.forms ?? FORMS;\n if (forms.length === 0) return err(\"The fit has no form.\");\n const twice = forms.find((form, index) => forms.findIndex((other) => other.id === form.id) !== index);\n if (twice !== undefined) return err(`The form \"${twice.id}\" is in the list of forms two times.`);\n const residual = options.residual ?? \"absolute\";\n if (residual === \"relative\" && points.y.some((y) => y === 0)) return err(\"A relative fit needs values that are not 0.\");\n const groups = options.groups ?? points.x;\n if (groups.length !== n) return err(`The fit has ${groups.length} groups for ${n} points.`);\n const groupCount = new Set(groups).size;\n if (groupCount < 2) return err(\"The fit needs two groups or more, because the held-out fit holds out one group.\");\n const bootstrapGroups = options.bootstrapGroups ?? groups;\n if (bootstrapGroups.length !== n) return err(`The fit has ${bootstrapGroups.length} groups of the bootstrap for ${n} points.`);\n const bootstrapCount = new Set(bootstrapGroups).size;\n const leastBootstrap = leastGroups(DEFAULT_LEVEL);\n if (bootstrapCount < leastBootstrap) {\n return err(\n `The bootstrap draws whole groups, and the fit has ${bootstrapCount} of them. Thus the count of different draws is ` +\n `${bootstrapDraws(bootstrapCount)}. The level ${DEFAULT_LEVEL} needs ${leastCount(DEFAULT_LEVEL)}, thus ${leastBootstrap} groups or more.`,\n );\n }\n const weighted = residual === \"relative\" ? { weights: points.y.map((y) => 1 / (y * y)) } : {};\n\n const models: Record<string, SeparableModel<number>> = {};\n const skipped: FormRank[] = [];\n for (const form of forms) {\n const model = separableOf(form, points.x);\n const reason = modelProblem(form, model);\n if (reason === undefined) models[form.id] = model;\n else skipped.push({ form: form.id, error: { mae: Number.NaN, rmse: Number.NaN }, missing: n, reason });\n }\n const ranked = rankSeparable(models, points.x, points.y, { groups, residual, ...weighted });\n const ranks: FormRank[] = [\n ...ranked.map((rank): FormRank => ({\n form: rank.id,\n error: { mae: rank.error.mae, rmse: rank.error.rmse },\n missing: rank.error.missing,\n ...(rank.fit === null ? { reason: `The form \"${rank.id}\" has no least-squares fit to ${n} points.` } : {}),\n })),\n ...skipped,\n ];\n const best = ranked[0];\n if (best === undefined || best.fit === null || best.error.missing > 0) {\n return err(`No form of ${forms.length} has a held-out prediction at each of the ${n} points.`);\n }\n const winner = forms.find((form) => form.id === best.id) as CatalogForm;\n const model = models[best.id] as SeparableModel<number>;\n const held = heldOutSeparable(model, points.x, points.y, { groups, residual, ...weighted });\n const boot = bootstrapSeparable(model, points.x, points.y, {\n groups: bootstrapGroups,\n ...weighted,\n runs: options.runs ?? SEPARABLE_BOOTSTRAP_RUNS,\n seed: options.seed ?? 1,\n });\n if (boot === null) return err(`The form \"${winner.id}\" has no fit for the bootstrap.`);\n const least = leastCount(DEFAULT_LEVEL);\n if (boot.replicates.length < least) {\n return err(`The bootstrap gave ${boot.replicates.length} fits in ${boot.runs} runs. The level ${DEFAULT_LEVEL} needs ${least}.`);\n }\n const binding = options.binding ?? { variable: FORM_VARIABLE };\n const values = [...best.fit.coefficients, ...best.fit.shapes];\n const constants = constantIdsOf(winner).map((id, index) => ({ id: binding.constants?.[id] ?? id, value: values[index] as number }));\n const losers: Loser[] = ranks\n .slice(1)\n .filter((rank) => rank.missing === 0 && rank.reason === undefined)\n .map((rank) => ({ form: rank.form, error: rank.error }));\n const method =\n `separable least squares: ${Object.keys(models).length} forms ranked by the rmse of the held-out residuals of ${groupCount} groups, ` +\n `${boot.replicates.length} fits in ${boot.runs} bootstrap runs of ${bootstrapCount} whole groups (seed ${boot.seed})`;\n return ok({\n form: formOf(winner, binding),\n constants,\n replicates: boot.replicates,\n fit: { method, residual, residuals: held.residuals, losers },\n ranks,\n });\n};\n","import { err, ok, type Result } from \"@mark1russell7/optional\";\nimport { convertible, isQuantity, type Quantity, valueIn, whyNotConvertible } from \"@mark1russell7/quantity\";\nimport type { Expr } from \"@mark1russell7/vex\";\nimport { DEFAULT_LEVEL, leastCount, type Law, type LawProblem, type Variable } from \"./law.ts\";\nimport { recordOf, valuesAt } from \"./program.ts\";\nimport { intervalOf, levelProblem, type LevelOptions, type LoadPoint, type Range } from \"./value.ts\";\n\n/** This number is the count of steps of the grid of a knee search when the options give none. */\nexport const KNEE_STEPS = 64;\n\n/** This number is the largest count of steps of the grid of a knee search. It sets a limit on the work of one search. */\nexport const MAX_STEPS = 4096;\n\n/**\n * A knee rule tells where a law leaves its cheap region.\n *\n * - `rise`: the value is more than `1 + share` times the value at the start of the search.\n * - `slope`: the slope is more than `factor` times the slope at the start of the search.\n * - `floor`: the value is more than `1 + share` times the floor of the row. The floor of a row is its\n * least value on the grid of the search, before its edge. The search of a row starts at its floor.\n */\nexport type KneeRule =\n | { readonly kind: \"rise\"; readonly share: number }\n | { readonly kind: \"slope\"; readonly factor: number }\n | { readonly kind: \"floor\"; readonly share: number };\n\n/** The floor of a law is its least value with its constants on the grid of a search, and the load of that value. */\nexport interface Floor {\n readonly load: number;\n readonly value: number;\n}\n\n/**\n * These options set a knee search. The search goes along one variable, from `from` to `to`, on a\n * grid of `steps` steps. The point `at` gives the value of each other variable of the law.\n *\n * The search goes from the minimum to the maximum of the variable, on 64 steps, when the options\n * give no value. The level of the intervals is 0.95 when the options give none.\n */\nexport interface KneeOptions extends LevelOptions {\n readonly at?: LoadPoint;\n readonly from?: number;\n readonly to?: number;\n readonly steps?: number;\n}\n\n/** An open range goes from `low` to `high`. A null end is past the end of the search. */\nexport interface OpenRange {\n readonly low: number | null;\n readonly high: number | null;\n}\n\n/**\n * A crossing is a load on the variable of a search, with the interval of its replicates. A null\n * value tells that the crossing is not in the search. The flag `outside` tells that the value is\n * outside the range of the variable. Then the value is an extrapolation.\n */\nexport interface Crossing {\n readonly value: number | null;\n readonly interval: OpenRange;\n readonly outside: boolean;\n}\n\n/**\n * A knee is the result of a knee search along one variable of a law, in the unit of the variable.\n *\n * The `knee` is the first load where the law obeys the rule: there the law leaves its cheap region.\n * The `edge` is the first load where the law has no finite value. This is a pole, where the value\n * grows with no limit, or the start of a region with no value. The knee is always before the edge.\n * The list `outside` names each other variable whose value is outside its range. Only a knee of the\n * rule `floor` has the fields `floor` and `noFloor`.\n */\nexport interface Knee {\n readonly variable: string;\n readonly unit: string;\n readonly rule: KneeRule;\n readonly level: number;\n readonly search: Range;\n readonly knee: Crossing;\n readonly edge: Crossing;\n readonly outside: readonly string[];\n /** This floor is the floor of the law with its constants. */\n readonly floor?: Floor;\n /** This number is the count of replicates with no floor above 0. The rule cannot apply to them, thus the interval of the knee leaves them out. */\n readonly noFloor?: number;\n}\n\n/** A curve gives the value of one row of a law or of a composition at each load. A load with no finite value gives undefined. */\nexport type Curve = (loads: readonly number[]) => readonly (number | undefined)[];\n\n/** This number sets the farthest distance from a peak where the pole test reads the size of the law. It is a share of the width of the bracket. */\nconst NEAR = 1e-6;\n\n/** Each distance of the pole test is this share of the distance before it. */\nconst CLOSER = 1e-3;\n\n/** At a pole, the gain of size in the second step nearer is at least this share of the gain in the first step. */\nconst POLE_GAIN = 0.9;\n\n/** A gain of size less than this share of the size is the noise of the floats, not a pole. */\nconst NOISE = 1e-9;\n\n/** The step of a difference quotient, for each unit of the load. */\nconst STEP = 1e-7;\n\n/** The most rounds of a bisection or of a golden-section search. Each search stops before, when its bracket has no middle. */\nconst ROUNDS = 400;\n\nconst INVERSE_PHI = (Math.sqrt(5) - 1) / 2;\n\nconst problem = (code: LawProblem[\"code\"], path: string, message: string): LawProblem => ({ code, path, message });\n\n/** This function gives the value of a curve at one load. */\nconst valueOf = (curve: Curve, load: number): number | undefined => curve([load])[0];\n\n/**\n * This function gives the load where a test changes from false to true, with a bisection. The test\n * is false at `low` and true at `high`. The function gives the end of the last bracket where the test is true.\n */\nconst crossingOf = (test: (load: number) => boolean, low: number, high: number): number => {\n let [a, b] = [low, high];\n for (let round = 0; round < ROUNDS; round += 1) {\n const middle = a + (b - a) / 2;\n if (middle <= a || middle >= b) break;\n if (test(middle)) b = middle;\n else a = middle;\n }\n return b;\n};\n\n/** This function gives the load of the largest size in a bracket, with a golden-section search. */\nconst peakOf = (size: (load: number) => number, low: number, high: number): number => {\n let [a, b] = [low, high];\n let c = b - INVERSE_PHI * (b - a);\n let d = a + INVERSE_PHI * (b - a);\n let [sizeC, sizeD] = [size(c), size(d)];\n for (let round = 0; round < ROUNDS && a < c && c < d && d < b; round += 1) {\n if (sizeC >= sizeD) {\n [b, d, sizeD] = [d, c, sizeC];\n c = b - INVERSE_PHI * (b - a);\n sizeC = size(c);\n } else {\n [a, c, sizeC] = [c, d, sizeD];\n d = a + INVERSE_PHI * (b - a);\n sizeD = size(d);\n }\n }\n return sizeC >= sizeD ? c : d;\n};\n\n/**\n * This function tells if the size of a law grows with no bound near the top of a peak. It reads the\n * size at three distances from the top, each 1000 times nearer than the distance before it.\n *\n * At a pole, each step nearer adds as much size as the step before, or more. A power pole adds more,\n * and a logarithm pole adds the same. Near a finite peak, the second step adds about a millionth of\n * the first. A load with no value at one of the distances is an edge near the top.\n */\nconst diverges = (size: (load: number) => number, top: number, near: number): boolean => {\n const sizeAt = (distance: number): number => Math.max(size(top - distance), size(top + distance));\n const [far, middle, close] = [near, near * CLOSER, near * CLOSER * CLOSER].map(sizeAt) as [number, number, number];\n if (!Number.isFinite(close) || !Number.isFinite(middle) || !Number.isFinite(far)) return true;\n const first = middle - far;\n return first > NOISE * middle && close - middle >= POLE_GAIN * first;\n};\n\n/**\n * This function gives the edge of one row of a law: the first load of the grid where the law has\n * no finite value. It gives Infinity when the law has a finite value on all of the grid.\n *\n * The size of a law at a load is the distance of its value from the start value. A load with no\n * value has an infinite size. The search examines each peak of the size on the grid, in order. A\n * golden-section search finds the top of the peak, and the pole test examines it. A peak with no\n * value at its top starts a region with no value.\n */\nconst edgeOf = (curve: Curve, grid: readonly number[], values: readonly (number | undefined)[], start: number): number => {\n const sizeOf = (value: number | undefined): number => (value === undefined ? Infinity : Math.abs(value - start));\n const size = (load: number): number => sizeOf(valueOf(curve, load));\n const noValue = (load: number): boolean => valueOf(curve, load) === undefined;\n const sizes = values.map(sizeOf);\n const last = grid.length - 1;\n for (let index = 1; index <= last; index += 1) {\n const here = sizes[index] as number;\n const missing = values[index] === undefined;\n const peak = here > (sizes[index - 1] as number) && (index === last || missing || here >= (sizes[index + 1] as number));\n if (!peak) continue;\n const low = grid[index - 1] as number;\n const high = grid[missing ? index : Math.min(index + 1, last)] as number;\n const top = peakOf(size, low, high);\n if (noValue(top)) return crossingOf(noValue, low, top);\n if (diverges(size, top, NEAR * (high - low))) return top;\n if (missing) return crossingOf(noValue, low, grid[index] as number);\n }\n return Infinity;\n};\n\n/** This function gives the step of a difference quotient at a load. The unit is the width of the search on a linear scale, and 0 on a log scale. */\nconst stepAt = (load: number, unit: number): number => STEP * Math.max(Math.abs(load), unit);\n\n/**\n * A test tells if the law passes a mark at one load. The value at the load is optional: without\n * it, the test reads the curve. A load with no finite value does not pass.\n */\nexport type Test = (load: number, value?: number) => boolean;\n\n/**\n * The context of the test of one row: its curve, its start value, its path, its start load and its\n * step unit. It also has the grid, the values of the row on the grid and the edge of the row.\n */\nexport interface TestContext {\n readonly curve: Curve;\n readonly start: number;\n readonly path: string;\n readonly from: number;\n readonly unit: number;\n readonly grid: readonly number[];\n readonly values: readonly (number | undefined)[];\n readonly edge: number;\n}\n\n/**\n * A test maker gives the test of one row, or the problem that stops the test at the start of the\n * search. An undefined test tells that the rule cannot apply to the row. Then the row has no crossing.\n */\nexport type TestOf = (context: TestContext) => Result<Test | undefined, LawProblem>;\n\n/**\n * This function gives the first load before the edge where the test holds. It gives Infinity when\n * the test does not hold before the edge or the end of the grid.\n *\n * The search tests the loads of the grid before the edge, and one load near the edge. A bisection\n * then finds the load between the last load that fails the test and the first load that passes it.\n */\nconst firstHolds = (holds: Test, grid: readonly number[], values: readonly (number | undefined)[], edge: number): number => {\n const loads = grid.map((load, index) => ({ load, value: values[index] })).filter(({ load }) => load < edge);\n if (Number.isFinite(edge)) {\n const before = loads.at(-1)?.load ?? (grid[0] as number);\n loads.push({ load: edge - NEAR * (edge - before), value: undefined });\n }\n let previous: number | undefined;\n for (const { load, value } of loads) {\n if (holds(load, value)) return previous === undefined ? load : crossingOf((x) => holds(x), previous, load);\n previous = load;\n }\n return Infinity;\n};\n\n/** The crossing and the edge of one row of a law. An undefined crossing tells that the rule cannot apply to the row. */\nexport interface RowResult {\n readonly crossing: number | undefined;\n readonly edge: number;\n}\n\n/** This function gives the first load where one row passes its test, and the edge of the row. The text `what` names the owner of the row in a problem. */\nexport const rowOf = (\n curve: Curve,\n path: string,\n testOf: TestOf,\n grid: readonly number[],\n unit: number,\n what = \"law\",\n): Result<RowResult, LawProblem> => {\n const values = curve(grid);\n const start = values[0];\n const from = grid[0] as number;\n if (start === undefined) return err(problem(\"value\", path, `The ${what} has no value at the start of the search, ${from}.`));\n const edge = edgeOf(curve, grid, values, start);\n const test = testOf({ curve, start, path, from, unit, grid, values, edge });\n if (test.tag === \"err\") return test;\n return ok({ crossing: test.value === undefined ? undefined : firstHolds(test.value, grid, values, edge), edge });\n};\n\n/** This function gives the test of a knee rule: the value or the slope is above its mark from the start of the search. */\nconst ruleTest =\n (rule: Exclude<KneeRule, { readonly kind: \"floor\" }>): TestOf =>\n ({ curve, start, path, from, unit }) => {\n if (rule.kind === \"rise\") {\n if (!(start > 0)) {\n return err(problem(\"knee\", path, `The rule \"rise\" needs a value above 0 at the start of the search. The value is ${start}.`));\n }\n const limit = (1 + rule.share) * start;\n return ok((load, value = valueOf(curve, load)) => value !== undefined && value > limit);\n }\n const slopeAt = (load: number, value: number | undefined): number | undefined => {\n const step = stepAt(load, unit);\n const before = valueOf(curve, load - step);\n return value === undefined || before === undefined ? undefined : (value - before) / step;\n };\n const step = stepAt(from, unit);\n const after = valueOf(curve, from + step);\n const first = after === undefined ? undefined : (after - start) / step;\n if (first === undefined || !(first > 0)) {\n return err(problem(\"knee\", path, `The rule \"slope\" needs a slope above 0 at the start of the search. The slope is ${String(first)}.`));\n }\n const limit = rule.factor * first;\n return ok((load, value) => {\n const slope = slopeAt(load, value ?? valueOf(curve, load));\n return slope !== undefined && slope > limit;\n });\n };\n\n/** This function gives the test of an amount: the value is above the amount. */\nexport const amountTest =\n (amount: number): TestOf =>\n ({ curve }) =>\n ok((load, value = valueOf(curve, load)) => value !== undefined && value > amount);\n\n/** These kinds name the knee rules. */\nconst KNEE_KINDS: readonly KneeRule[\"kind\"][] = [\"rise\", \"slope\", \"floor\"];\n\n/**\n * This function gives the problem of a knee rule, or undefined for a correct rule. The rule can come\n * from data, thus the function also examines its shape. The path of a problem starts with `path`.\n */\nexport const kneeRuleProblem = (rule: unknown, path = \"rule\"): LawProblem | undefined => {\n if (typeof rule !== \"object\" || rule === null || Array.isArray(rule)) return problem(\"knee\", path, \"The rule is not a record.\");\n const { kind, share, factor } = rule as Readonly<Record<string, unknown>>;\n if (kind === \"rise\" || kind === \"floor\") {\n if (typeof share === \"number\" && Number.isFinite(share) && share > 0) return undefined;\n return problem(\"knee\", `${path}.share`, `The share of the rule \"${kind}\" is ${String(share)}. It must be a finite number above 0.`);\n }\n if (kind === \"slope\") {\n if (typeof factor === \"number\" && Number.isFinite(factor) && factor > 1) return undefined;\n return problem(\"knee\", `${path}.factor`, `The factor of the rule \"slope\" is ${String(factor)}. It must be a finite number above 1.`);\n }\n return problem(\"knee\", `${path}.kind`, `The kind of the rule is ${JSON.stringify(kind) ?? \"undefined\"}. It must be one of ${KNEE_KINDS.join(\", \")}.`);\n};\n\n/** An open value is a value of a search with the interval of its replicates. A null value or end is past the end of the search. */\nexport interface OpenValue {\n readonly value: number | null;\n readonly interval: OpenRange;\n}\n\n/**\n * This function gives the open value of the values of the rows. The first value is the value of the\n * estimate. A value past `end` is past the end of the search, and an infinite value is too.\n */\nexport const openValueOf = (values: readonly number[], level: number, end: number): OpenValue => {\n // The quantiles interpolate. A large finite number keeps each interpolation finite, and each end past the search becomes null.\n const [value, ...spread] = values.map((entry) => (Number.isFinite(entry) ? entry : Number.MAX_VALUE));\n const interval = intervalOf(value as number, spread, level);\n const open = (entry: number): number | null => (entry > end ? null : entry);\n return { value: open(value as number), interval: { low: open(interval.low), high: open(interval.high) } };\n};\n\n/** This function gives the crossing of the values of the rows. The flag `outside` tells that the value is outside `range`. */\nconst crossingFrom = (values: readonly number[], level: number, range: Range, end: number): Crossing => {\n const found = openValueOf(values, level, end);\n return { ...found, outside: found.value !== null && (found.value < range.low || found.value > range.high) };\n};\n\n/**\n * A search is the setup of a search along one variable of a law. It holds the target variable, the level,\n * the range and the grid, and the variables outside their range. The function `curveOf` gives the curve\n * of one row of constants.\n */\ninterface Search {\n readonly target: Variable;\n readonly level: number;\n readonly search: Range;\n readonly grid: readonly number[];\n readonly unit: number;\n readonly curveOf: (values: readonly number[]) => Curve;\n readonly outside: readonly string[];\n}\n\n/**\n * The result of a search along one variable of a law: the first load that passes the test, and the\n * edge. The count `skipped` tells the replicates where the rule cannot apply. The crossing leaves them out.\n */\ninterface Along {\n readonly crossing: Crossing;\n readonly edge: Crossing;\n readonly skipped: number;\n}\n\n/**\n * This function gives the grid of a search from `from` to `to` in `steps` steps, or its problem. A\n * grid on the scale `log` starts above 0. The text `owner` names the variable of the search in a problem.\n */\nexport const searchGrid = (from: number, to: number, steps: number, log: boolean, owner: string): Result<readonly number[], LawProblem> => {\n if (!(Number.isFinite(from) && Number.isFinite(to) && from < to)) {\n return err(problem(\"range\", \"from\", `The search goes from ${from} to ${to}. It must go from a finite number to a larger finite number.`));\n }\n if (log && !(from > 0)) return err(problem(\"range\", \"from\", `${owner} has the scale \"log\", thus the search starts above 0.`));\n if (!(Number.isInteger(steps) && steps >= 2 && steps <= MAX_STEPS)) {\n return err(problem(\"knee\", \"steps\", `The search has ${steps} steps. It must have a whole number of steps from 2 to ${MAX_STEPS}.`));\n }\n return ok(\n Array.from({ length: steps + 1 }, (_, index) =>\n index === steps ? to : log ? from * (to / from) ** (index / steps) : from + ((to - from) * index) / steps,\n ),\n );\n};\n\n/**\n * This function gives the setup of a search along one variable of a law, or its problem. The function\n * `check` gives the problem of the test before the setup.\n */\nconst searchOf = (law: Law, variable: string, options: KneeOptions, check: () => LawProblem | undefined): Result<Search, LawProblem> => {\n const level = options.level ?? DEFAULT_LEVEL;\n const noLevel = levelProblem(law, level, false);\n if (noLevel !== undefined) return err(noLevel);\n const target = law.variables.find((entry) => entry.id === variable);\n if (target === undefined) return err(problem(\"point\", \"variable\", `The law has no variable \"${variable}\".`));\n const badTest = check();\n if (badTest !== undefined) return err(badTest);\n\n const at = options.at ?? {};\n for (const name of Object.keys(at)) {\n if (name === variable) return err(problem(\"point\", `at.${name}`, `The point \"at\" gives \"${name}\", the variable of the search.`));\n if (!law.variables.some((entry) => entry.id === name)) return err(problem(\"point\", `at.${name}`, `The law has no variable \"${name}\".`));\n }\n const base: Record<string, number> = {};\n for (const other of law.variables) {\n if (other.id === variable) continue;\n const value = at[other.id];\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n return err(problem(\"point\", `at.${other.id}`, `The point \"at\" gives no finite value for the variable \"${other.id}\".`));\n }\n base[other.id] = value;\n }\n\n const from = options.from ?? target.min;\n const to = options.to ?? target.max;\n const log = target.scale === \"log\";\n const grid = searchGrid(from, to, options.steps ?? KNEE_STEPS, log, `The variable \"${variable}\"`);\n if (grid.tag === \"err\") return grid;\n const names = law.constants.map((constant) => constant.id);\n const program: Expr = law.form.program;\n const curveOf =\n (values: readonly number[]): Curve =>\n (loads) =>\n valuesAt(program, loads.map((load) => recordOf(names, values, { ...base, [variable]: load })));\n const outside = law.variables\n .filter((entry) => entry.id !== variable && ((base[entry.id] as number) < entry.min || (base[entry.id] as number) > entry.max))\n .map((entry) => entry.id);\n return ok({ target, level, search: { low: from, high: to }, grid: grid.value, unit: log ? 0 : to - from, curveOf, outside });\n};\n\n/** This function searches a law for the first load that passes a test, in the constants and in each replicate. */\nconst along = (law: Law, setup: Search, testOf: TestOf): Result<Along, LawProblem> => {\n const rows = [\n { path: \"constants\", values: law.constants.map((constant) => constant.value) },\n ...law.replicates.map((row, index) => ({ path: `replicates[${index}]`, values: row })),\n ];\n const crossings: number[] = [];\n const edges: number[] = [];\n let skipped = 0;\n for (const row of rows) {\n const result = rowOf(setup.curveOf(row.values), row.path, testOf, setup.grid, setup.unit);\n if (result.tag === \"err\") return result;\n edges.push(result.value.edge);\n const { crossing } = result.value;\n if (crossing === undefined) {\n // The first crossing is the crossing of the estimate. Thus the rule must apply to the constants.\n if (row.path === \"constants\") return err(problem(\"knee\", row.path, \"The rule cannot apply to the constants of the law.\"));\n skipped += 1;\n } else {\n crossings.push(crossing);\n }\n }\n const range: Range = { low: setup.target.min, high: setup.target.max };\n return ok({\n crossing: crossingFrom(crossings, setup.level, range, setup.search.high),\n edge: crossingFrom(edges, setup.level, range, setup.search.high),\n skipped,\n });\n};\n\n/** This function gives the floor of one row: its least value on the grid, at the loads before its edge. */\nconst rowFloor = (grid: readonly number[], values: readonly (number | undefined)[], edge: number, start: number): Floor => {\n let floor: Floor = { load: grid[0] as number, value: start };\n grid.forEach((load, index) => {\n const value = values[index];\n if (load < edge && value !== undefined && value < floor.value) floor = { load, value };\n });\n return floor;\n};\n\n/**\n * This function gives the floor of a law on the grid of a search. The floor is the least value of the\n * law with its constants, at the loads before its edge. The rule `floor` needs a floor above 0.\n */\nconst floorOf = (law: Law, setup: Search): Result<Floor, LawProblem> => {\n const curve = setup.curveOf(law.constants.map((constant) => constant.value));\n const values = curve(setup.grid);\n const start = values[0];\n if (start === undefined) return err(problem(\"value\", \"constants\", `The law has no value at the start of the search, ${setup.grid[0]}.`));\n const floor = rowFloor(setup.grid, values, edgeOf(curve, setup.grid, values, start), start);\n if (!(floor.value > 0)) {\n return err(problem(\"knee\", \"constants\", `The rule \"floor\" needs a floor above 0. The floor is ${floor.value} at ${floor.load}.`));\n }\n return ok(floor);\n};\n\n/**\n * This function gives the test of the rule `floor` for one row. From the load of the floor of the\n * row, the value is above `1 + share` times that floor. A row with no floor above 0 has no test.\n */\nconst floorTest =\n (share: number): TestOf =>\n ({ curve, start, grid, values, edge }) => {\n const floor = rowFloor(grid, values, edge, start);\n if (!(floor.value > 0)) return ok(undefined);\n const limit = (1 + share) * floor.value;\n return ok((load, value = valueOf(curve, load)) => load >= floor.load && value !== undefined && value > limit);\n };\n\n/**\n * This function gives the largest count of replicates that a knee interval can leave out. The count is\n * at most the replicates of one tail of the level, and at least `leastCount` replicates stay.\n */\nconst mostSkipped = (replicates: number, level: number): number =>\n Math.min(Math.floor((replicates * (1 - level)) / 2 + 1e-9), replicates - leastCount(level));\n\n/**\n * This function gives the knee of a law along one variable, with an interval. It also gives the\n * edge: the first load where the law has no finite value.\n *\n * The point `at` of the options gives each other variable of the law. The function evaluates the\n * law with its constants, then with each replicate. The interval of the knee and of the edge is the\n * share `level` of the values of the replicates, made wider to hold the value.\n *\n * The search tests a grid of loads, then a bisection finds each crossing. A crossing between two\n * loads of the grid is found. Two edges in one step of the grid can hide the first edge.\n *\n * The rule `floor` gives each row its own floor. Thus the knee of a row is always after its floor,\n * and the uncertainty of the floor is in the interval. A replicate with no floor above 0 has no knee:\n * the field `noFloor` counts these replicates, and the interval leaves them out. When they are more\n * than one tail of the level, the function gives a problem.\n *\n * The function gives a problem for a variable or a point that the law cannot read. A bad search\n * range, rule or count of steps, and a level that the law cannot show, also give a problem. The last\n * problems are a law with no value at the start of the search, and a rule that cannot apply there.\n */\nexport const lawKnee = (law: Law, variable: string, rule: KneeRule, options: KneeOptions = {}): Result<Knee, LawProblem> => {\n const setup = searchOf(law, variable, options, () => kneeRuleProblem(rule));\n if (setup.tag === \"err\") return setup;\n let floor: Floor | undefined;\n if (rule.kind === \"floor\") {\n const least = floorOf(law, setup.value);\n if (least.tag === \"err\") return least;\n floor = least.value;\n }\n const found = along(law, setup.value, rule.kind === \"floor\" ? floorTest(rule.share) : ruleTest(rule));\n if (found.tag === \"err\") return found;\n const { target, level, search, outside } = setup.value;\n const knee: Knee = { variable, unit: target.unit, rule, level, search, knee: found.value.crossing, edge: found.value.edge, outside };\n if (floor === undefined) return ok(knee);\n const { skipped } = found.value;\n const most = mostSkipped(law.replicates.length, level);\n if (skipped > most) {\n const message = `The rule \"floor\" needs a floor above 0. ${skipped} of ${law.replicates.length} replicates have a floor of 0 or less. The interval of the level ${level} can leave out at most ${most}.`;\n return err(problem(\"knee\", \"replicates\", message));\n }\n return ok({ ...knee, floor, noFloor: skipped });\n};\n\n/**\n * A reach is the result of a search along one variable for the first load where a law is above an\n * amount. The loads are in the unit of the variable. Before the `crossing`, the law holds the amount.\n *\n * Thus for a law that grows along the variable, the crossing is the largest load that holds the\n * amount. The `edge` and the list `outside` are as in a knee.\n */\nexport interface Reach {\n readonly variable: string;\n readonly unit: string;\n /** This amount is the amount of the search, in the unit of the measure of the law. */\n readonly amount: number;\n readonly level: number;\n readonly search: Range;\n readonly crossing: Crossing;\n readonly edge: Crossing;\n readonly outside: readonly string[];\n}\n\n/**\n * This function gives the first load along one variable where a law is above an amount, with an\n * interval. This is the inverse query of one law: the largest load that one limit holds.\n *\n * The options are the options of `lawKnee`. When the law is above the amount at the start of the\n * search, the crossing is the start. When the law holds the amount on all of the search, the\n * crossing is null. A pole is above each amount, so the crossing is before the pole.\n *\n * The function gives each problem of `lawKnee` that is not about a rule. An amount that is not finite\n * gives a problem. An amount that does not convert to the unit of the measure also gives a problem.\n */\nexport const lawReach = (law: Law, variable: string, amount: Quantity, options: KneeOptions = {}): Result<Reach, LawProblem> => {\n if (!isQuantity(amount) || !Number.isFinite(amount.value)) {\n return err(problem(\"value\", \"amount\", \"The amount is not a finite quantity.\"));\n }\n if (!convertible(amount.unit, law.measure.unit)) {\n const why = whyNotConvertible(amount.unit, law.measure.unit) ?? \"the units are different\";\n return err(problem(\"unit\", \"amount\", `The amount is in \"${amount.unit}\", and the measure of the law is in \"${law.measure.unit}\": ${why}.`));\n }\n const value = valueIn(amount, law.measure.unit);\n const setup = searchOf(law, variable, options, () => undefined);\n if (setup.tag === \"err\") return setup;\n const found = along(law, setup.value, amountTest(value));\n if (found.tag === \"err\") return found;\n const { target, level, search, outside } = setup.value;\n return ok({ variable, unit: target.unit, amount: value, level, search, crossing: found.value.crossing, edge: found.value.edge, outside });\n};\n","import { err, ok, type Result } from \"@mark1russell7/optional\";\nimport { gateOf, type Gate, type GateCaseOutcome, type LimitOutcome } from \"@mark1russell7/rigor-bench\";\nimport { binomialTest, holm, partialConjunction } from \"@mark1russell7/rigor-statistics\";\nimport { DEFAULT_LEVEL, type Law, type LawProblem } from \"./law.ts\";\nimport { lawValue, type LevelOptions, type LoadPoint, type Range } from \"./value.ts\";\n\n/** This level is the level of the family of tests of a gate. It is the chance of one false block or more in one run of the gate. */\nexport const GATE_ALPHA = 0.01;\n\n/**\n * This count is the jobs that each must show the same side before the gate blocks. One job on a slow runner\n * cannot block alone. It is the default of `jobs` of `notSlowerVerdict` of `@mark1russell7/rigor-bench`.\n */\nexport const GATE_JOBS = 2;\n\n/** The side of a measured value against the run range of its law. */\nexport type ReadSide = \"within\" | \"high\" | \"low\";\n\n/** A law read tells where one measured value falls against the run range of its law at one load point. */\nexport interface LawRead {\n readonly value: number;\n /** This range is the range `run` of `lawValue`: where one measured run falls. */\n readonly run: Range;\n readonly side: ReadSide;\n}\n\nconst problem = (code: LawProblem[\"code\"], path: string, message: string): LawProblem => ({ code, path, message });\n\n/**\n * This function tells where one measured value falls against the run range of a law at a load point. The range is\n * the range `run` of `lawValue`. A value above the range is `high`, and a value below it is `low`.\n *\n * The function gives a problem for a point outside the range of a variable, because there the law has no value to\n * compare. It also gives each problem of `lawValue`, and a problem for a value that is not finite.\n */\nexport const lawRead = (law: Law, point: LoadPoint, value: number, options: LevelOptions = {}): Result<LawRead, LawProblem> => {\n if (!Number.isFinite(value)) return err(problem(\"value\", \"value\", `The measured value ${value} is not finite.`));\n const found = lawValue(law, point, options);\n if (found.tag === \"err\") return found;\n const [outside] = found.value.outside;\n if (outside !== undefined) {\n const variable = law.variables.find((each) => each.id === outside);\n const range = variable === undefined ? \"\" : ` from ${variable.min} to ${variable.max}`;\n return err(problem(\"point\", outside, `The point is outside the range of the variable \"${outside}\"${range}. The law has no value there to compare.`));\n }\n const { run } = found.value;\n return ok({ value, run, side: value > run.high ? \"high\" : value < run.low ? \"low\" : \"within\" });\n};\n\n/** A gate read is one measured value of one job at one load point. */\nexport interface GateRead {\n readonly point: LoadPoint;\n readonly value: number;\n}\n\n/**\n * A gate job is the reads of one job for one law. A job with a reason in `noRead` gives no read, for example a job with a\n * noise floor over its limit. The caller gives only the reads in the conditions of the law.\n */\nexport interface GateJob {\n /** This name is the name of the job, for example the address of its CI run and its start. */\n readonly job: string;\n readonly reads: readonly GateRead[];\n readonly noRead?: string;\n /** These texts tell each read that the caller left out, for example a point that the law leaves out. The counts do not use them. */\n readonly unread?: readonly string[];\n}\n\n/** A gate case is one law and the jobs that measured its subject in its conditions. */\nexport interface GateCase {\n readonly law: Law;\n readonly jobs: readonly GateJob[];\n}\n\n/** These options set the level of the run range, the level of the family of tests and the count of jobs of a side. */\nexport interface LawGateOptions extends LevelOptions {\n /** This level is the level of the family of tests. The default is `GATE_ALPHA`. */\n readonly alpha?: number;\n /** This count is the jobs that each must show a side. The default is `GATE_JOBS`. */\n readonly jobs?: number;\n}\n\n/** A job count tells the reads of one job for one law, and the p of the count of each side. */\nexport interface JobCount {\n readonly job: string;\n /** This count is the reads in the range of the law. */\n readonly reads: number;\n readonly high: number;\n readonly low: number;\n /** This p is the p of the binomial test of the count `high`, with the chance of one side under the claim. */\n readonly pHigh: number;\n readonly pLow: number;\n /** These texts tell each read that the caller left out (`GateJob.unread`), and each read that the law cannot compare. */\n readonly unread: readonly string[];\n}\n\n/** A side test is the test of one side of one law over the jobs, after the Holm correction of the family. */\nexport interface SideTest {\n readonly side: \"high\" | \"low\";\n /** This p is the p of the claim \"`jobs` jobs or more show this side\" (`partialConjunction`). */\n readonly p: number;\n /** This p is the p after the Holm correction of the family. */\n readonly adjusted: number;\n readonly reject: boolean;\n}\n\n/** A job with no read tells the job and the reason. */\nexport interface NoReadJob {\n readonly job: string;\n readonly reason: string;\n}\n\n/** A law gate case is the outcome of one law, with the counts of each job and the test of each side. */\nexport interface LawGateCase extends GateCaseOutcome {\n /** This name is the id of the law. */\n readonly case: string;\n readonly outcome: LimitOutcome;\n /** This text tells the reason of the outcome, in one sentence. */\n readonly reason: string;\n readonly jobs: readonly JobCount[];\n readonly noRead: readonly NoReadJob[];\n /** These tests are the two sides, or an empty list for a case with too few jobs. */\n readonly sides: readonly SideTest[];\n}\n\n/** A law gate is the gate of `@mark1russell7/rigor-bench` over the laws, with the facts that it uses. */\nexport interface LawGate extends Gate {\n readonly level: number;\n readonly alpha: number;\n /** This count is the jobs that each must show a side. */\n readonly need: number;\n /** This chance is the chance of one side for one read of a job that agrees with its law: `(1 - level) / 2`. */\n readonly share: number;\n readonly cases: readonly LawGateCase[];\n}\n\n/** This function gives the text of a number with at most 3 significant digits. */\nconst short = (value: number): string => (Number.isInteger(value) ? String(value) : value.toPrecision(3));\n\n/** This function gives the counts of one job for one law, or the reason that the job gives no read. */\nconst countOf = (law: Law, job: GateJob, level: number, share: number): JobCount | NoReadJob => {\n if (job.noRead !== undefined) return { job: job.job, reason: job.noRead };\n let high = 0;\n let low = 0;\n let reads = 0;\n const unread: string[] = [...(job.unread ?? [])];\n for (const each of job.reads) {\n const found = lawRead(law, each.point, each.value, { level });\n if (found.tag === \"err\") {\n unread.push(`${JSON.stringify(each.point)}: ${found.error.message}`);\n continue;\n }\n reads += 1;\n if (found.value.side === \"high\") high += 1;\n if (found.value.side === \"low\") low += 1;\n }\n if (reads === 0) return { job: job.job, reason: `The job has no read in the range of the law. ${unread[0] ?? \"The job has no read.\"}` };\n return { job: job.job, reads, high, low, pHigh: binomialTest(high, reads, share, \"greater\"), pLow: binomialTest(low, reads, share, \"greater\"), unread };\n};\n\n/** The counts of one case before the family test. */\ninterface Counted {\n readonly law: Law;\n readonly jobs: readonly JobCount[];\n readonly noRead: readonly NoReadJob[];\n}\n\n/**\n * This function gives the gate of some laws. For each law, it tells if the measured values of the jobs stay in the run\n * range of the law. It is the rule of a gate of the laws of a subject, for example on a pull request.\n *\n * - **A read:** each value of a job falls `within`, `high` or `low` against the run range of its law (`lawRead`).\n * A read of a job that agrees with its law falls on one side with a chance of `share`, `(1 - level) / 2`, or less.\n * - **A job:** for each side, the binomial test of the count of reads on that side gives the p of the job.\n * A job with `noRead`, or with no read in the range of the law, gives no read.\n * - **A side:** `partialConjunction` joins the p of the jobs for the claim \"`jobs` jobs or more show this side\". Thus one\n * job on an odd runner cannot block alone. The claim has no condition on how the reads of one job depend on each other.\n * - **The family:** `holm` corrects the tests of the two sides of each law at the level `alpha`. A rejected side makes the\n * case `beyond`. A low side is a block too: the law is no longer the law of the subject, and a new fit must replace it.\n * - **No read:** a case with fewer than `jobs` jobs that read is `cannot decide`. So is a case whose reads are too few to\n * reject a side, also with each read on that side. The gate of `@mark1russell7/rigor-bench` (`gateOf`) joins the cases.\n * A gate with no case, or with a case that cannot decide and no block, is \"no read\". It does not pass.\n *\n * The function throws a `RangeError` for a level, an alpha or a count of jobs that is not valid.\n */\nexport const lawGate = (cases: readonly GateCase[], options: LawGateOptions = {}): LawGate => {\n const level = options.level ?? DEFAULT_LEVEL;\n const alpha = options.alpha ?? GATE_ALPHA;\n const need = options.jobs ?? GATE_JOBS;\n if (!(level > 0 && level < 1)) throw new RangeError(`The level ${level} is not between 0 and 1.`);\n if (!(alpha > 0 && alpha < 1)) throw new RangeError(`The alpha ${alpha} is not between 0 and 1.`);\n if (!Number.isInteger(need) || need < 1) throw new RangeError(`The count of jobs ${need} is not a whole number above 0.`);\n const share = (1 - level) / 2;\n\n const counted: Counted[] = cases.map(({ law, jobs }) => {\n const found = jobs.map((job) => countOf(law, job, level, share));\n return { law, jobs: found.filter((each): each is JobCount => \"reads\" in each), noRead: found.filter((each): each is NoReadJob => \"reason\" in each) };\n });\n const decidable = counted.filter((each) => each.jobs.length >= need);\n const tests = decidable.length * 2;\n const pOf = (jobs: readonly JobCount[], side: \"high\" | \"low\"): number => partialConjunction(jobs.map((job) => (side === \"high\" ? job.pHigh : job.pLow)), need);\n const corrected = holm(\n decidable.flatMap((each) => [pOf(each.jobs, \"high\"), pOf(each.jobs, \"low\")]),\n alpha,\n );\n\n let next = 0;\n const outcomes: LawGateCase[] = counted.map(({ law, jobs, noRead }) => {\n const base = { case: law.id, jobs, noRead };\n if (jobs.length < need) {\n const reason = `${jobs.length} jobs read the law. The gate needs ${need} jobs or more.${noRead.length > 0 ? ` ${noRead[0]!.reason}` : \"\"}`;\n return { ...base, outcome: \"cannot decide\", reason, sides: [] };\n }\n const sides: SideTest[] = ([\"high\", \"low\"] as const).map((side) => {\n const test = corrected[next];\n next += 1;\n return { side, p: test?.p ?? 1, adjusted: test?.adjusted ?? 1, reject: test?.reject ?? false };\n });\n // The best p of a side is the p with each read on that side. Above the first step of Holm, no count can reject the side.\n const best = partialConjunction(jobs.map((job) => binomialTest(job.reads, job.reads, share, \"greater\")), need);\n const reads = jobs.reduce((sum, job) => sum + job.reads, 0);\n const high = jobs.reduce((sum, job) => sum + job.high, 0);\n const low = jobs.reduce((sum, job) => sum + job.low, 0);\n const counts = `${high} of ${reads} reads in ${jobs.length} jobs are above the run range and ${low} are below`;\n const rejected = sides.find((side) => side.reject);\n if (rejected !== undefined) {\n const what = rejected.side === \"high\" ? \"The measure is above its law\" : \"The measure is below its law: the law is out of date, and a new fit must replace it\";\n return { ...base, outcome: \"beyond\", reason: `${what}. ${counts}. The adjusted p is ${short(rejected.adjusted)}, below ${alpha}.`, sides };\n }\n if (best > alpha / tests) {\n const reason = `The reads are too few to reject a side: with each read on one side, the p is ${short(best)}, above ${short(alpha / tests)}.`;\n return { ...base, outcome: \"cannot decide\", reason, sides };\n }\n return { ...base, outcome: \"within\", reason: `${counts}, as the chance ${short(share)} of each side gives.`, sides };\n });\n return { ...gateOf(outcomes), level, alpha, need, share, cases: outcomes };\n};\n","import { err, ok, type Result } from \"@mark1russell7/optional\";\nimport { quantity, valueIn, type Quantity } from \"@mark1russell7/quantity\";\nimport { mean } from \"@mark1russell7/rigor-statistics\";\nimport { metricsGaps } from \"./app-check.ts\";\nimport type { AppContract, AppProblem, AppSeries } from \"./app.ts\";\nimport { isUtc } from \"./names.ts\";\nimport type { Observation, ObservedClass } from \"./observe.ts\";\n\n/** A reading is one value of one series of an app at one time. `series` is the id of the series, and `at` is a UTC time. */\nexport interface SeriesReading {\n readonly series: string;\n readonly at: string;\n readonly value: number;\n}\n\n/** A window of the live metrics goes from `from` to `to`, two UTC times. Its `origin` names the place of the metrics. */\nexport interface MetricsWindow {\n readonly origin: string;\n readonly from: string;\n readonly to: string;\n}\n\n/**\n * This function gives the increase of a counter from its values in the order of their times. A value below\n * the value before it is a new start of the process. The counter starts again at 0, thus the increase adds\n * the whole value.\n */\nexport const counterIncrease = (values: readonly number[]): number =>\n values.reduce((total, value, index) => {\n if (index === 0) return total;\n const before = values[index - 1] ?? 0;\n return total + (value >= before ? value - before : value);\n }, 0);\n\n/** This function makes a problem of the readings of an app. */\nconst readingProblem = (path: string, message: string): AppProblem => ({ code: \"series\", path, message });\n\n/**\n * This function gives the observation of an app in a window. The observation has the count of the requests of\n * each class, the mean of each request variable and each level. It reads only the readings in the window.\n *\n * - The count of a class is the increase of its counter. A class with no request in the window is not in the observation.\n * - The mean of a request variable is the increase of the counter of its total, over the count of its class.\n * - A level is the mean of the readings of its gauge, with the same weight for each reading. Item CAP-63 adds a weight for the time of each reading.\n *\n * It gives a problem for each gap of the metrics of the app (`metricsGaps`). It also gives a problem for a\n * counter with fewer than 2 readings, and for a gauge with no reading. `observedWorkload` gives the workload\n * of the observation.\n */\nexport const observationOf = (app: AppContract, window: MetricsWindow, readings: readonly SeriesReading[]): Result<Observation, readonly AppProblem[]> => {\n const { origin, from, to } = window;\n if (!isUtc(from) || !isUtc(to) || !(Date.parse(from) < Date.parse(to))) {\n return err([readingProblem(\"window\", \"The window does not go from a UTC time to a later UTC time.\")]);\n }\n const problems: AppProblem[] = metricsGaps(app).map((gap) => readingProblem(\"metrics\", gap.message));\n const start = Date.parse(from);\n const end = Date.parse(to);\n\n /** This function gives the values of a series in the window, in the order of their times. */\n const valuesOf = (series: AppSeries): readonly number[] =>\n readings\n .filter((reading) => reading.series === series.id && isUtc(reading.at) && Date.parse(reading.at) >= start && Date.parse(reading.at) <= end)\n .sort((a, b) => Date.parse(a.at) - Date.parse(b.at))\n .map((reading) => reading.value)\n .filter((value) => Number.isFinite(value));\n\n /** This function gives the increase of a counter in the window, in the unit of the series, or a problem. */\n const increaseOf = (series: AppSeries): number | undefined => {\n const values = valuesOf(series);\n if (values.length >= 2) return counterIncrease(values);\n problems.push(readingProblem(`readings.${series.id}`, `The counter \"${series.id}\" has ${values.length} readings in the window. Its increase needs 2 or more.`));\n return undefined;\n };\n\n const classes: ObservedClass[] = [];\n for (const entry of app.classes) {\n const counter = app.metrics.find((series) => \"rate\" in series.of && series.of.rate === entry.id);\n if (counter === undefined) continue;\n const count = increaseOf(counter);\n if (count === undefined || count === 0) continue;\n const request: Record<string, Quantity> = {};\n for (const name of entry.request) {\n const total = app.metrics.find((series) => \"total\" in series.of && series.of.total === name && series.of.class === entry.id);\n const variable = app.variables.find((each) => each.id === name);\n if (total === undefined || variable === undefined) continue;\n const sum = increaseOf(total);\n if (sum !== undefined) request[name] = quantity(valueIn(quantity(sum, total.unit), variable.unit) / count, variable.unit);\n }\n classes.push({ id: entry.id, count: quantity(count, counter.unit), request });\n }\n\n const levels: Record<string, Quantity> = {};\n for (const variable of app.variables) {\n if (variable.kind !== \"level\") continue;\n const gauge = app.metrics.find((series) => \"level\" in series.of && series.of.level === variable.id);\n if (gauge === undefined) continue;\n const values = valuesOf(gauge);\n if (values.length === 0) {\n problems.push(readingProblem(`readings.${gauge.id}`, `The gauge \"${gauge.id}\" has no reading in the window.`));\n continue;\n }\n levels[variable.id] = quantity(valueIn(quantity(mean(values), gauge.unit), variable.unit), variable.unit);\n }\n return problems.length > 0 ? err(problems) : ok({ origin, from, to, classes, levels });\n};\n","import { err, ok, type Result } from \"@mark1russell7/optional\";\nimport { isCanonicalUnit, isQuantity, kindOf, quantity, type Quantity } from \"@mark1russell7/quantity\";\nimport { isUtc } from \"./names.ts\";\nimport { checkWorkload, workloadProblem } from \"./workload-check.ts\";\nimport { WORKLOAD_FORMAT, type Amounts, type Workload, type WorkloadClass, type WorkloadProblem } from \"./workload.ts\";\n\n/**\n * An observed class is the count of the requests of one class in a window of the live metrics, for\n * example `{ value: 1200, unit: \"{request}\" }`. Its `request` gives each variable of one request.\n */\nexport interface ObservedClass {\n readonly id: string;\n readonly count: Quantity;\n readonly request: Amounts;\n}\n\n/**\n * An observation is the live metrics of an app in one window, from `from` to `to`. Its `origin`\n * names the place of the metrics. Each level is the level in the window.\n */\nexport interface Observation {\n readonly origin: string;\n readonly from: string;\n readonly to: string;\n readonly classes: readonly ObservedClass[];\n readonly levels: Amounts;\n}\n\n/** A workload name is the id and the title of a workload. */\nexport interface WorkloadName {\n readonly id: string;\n readonly title: string;\n}\n\n/**\n * This function gives the workload of an observation. The rate of a class is its count, divided by\n * the seconds of the window. Thus the rate is the mean rate of the window. For the load at a peak,\n * give the window of the peak.\n *\n * It gives each problem of an observation that is not correct, and each problem of the workload.\n */\nexport const observedWorkload = (observation: Observation, name: WorkloadName): Result<Workload, readonly WorkloadProblem[]> => {\n const { origin, from, to } = observation;\n const seconds = isUtc(from) && isUtc(to) ? (Date.parse(to) - Date.parse(from)) / 1000 : Number.NaN;\n if (!(seconds > 0)) {\n return err([workloadProblem(\"source\", \"source\", \"The window does not go from a UTC time to a later UTC time.\")]);\n }\n\n const problems: WorkloadProblem[] = [];\n const classes: WorkloadClass[] = [];\n observation.classes.forEach((entry, index) => {\n const { count } = entry;\n const unit = isQuantity(count) && kindOf(count.unit) === \"count\" ? `${count.unit}/s` : undefined;\n if (unit === undefined || !isCanonicalUnit(unit) || kindOf(unit) !== \"frequency\" || count.value < 0) {\n problems.push(\n workloadProblem(\"rate\", `classes[${index}].count`, `The count of the class \"${entry.id}\" is not a count of 0 or more, for example in \"{request}\".`),\n );\n return;\n }\n classes.push({ id: entry.id, rate: quantity(count.value / seconds, unit), request: entry.request });\n });\n if (problems.length > 0) return err(problems);\n\n const workload: Workload = {\n format: WORKLOAD_FORMAT,\n id: name.id,\n title: name.title,\n classes,\n levels: observation.levels,\n source: { kind: \"metrics\", origin, from, to },\n };\n const found = checkWorkload(workload);\n return found.length > 0 ? err(found) : ok(workload);\n};\n","import { err, ok, type Result } from \"@mark1russell7/optional\";\nimport { convertible, isQuantity, scale, valueIn, whyNotConvertible, type Quantity } from \"@mark1russell7/quantity\";\nimport { limitProblem, limitProblems } from \"./instance-check.ts\";\nimport type { Instance, Limit, LimitProblem } from \"./instance.ts\";\nimport { finite, repeated } from \"./names.ts\";\nimport type { Amounts } from \"./workload.ts\";\n\n/**\n * A limit use tells how much of a limit one value of its measure takes. The `amount` is the amount\n * of the limit: its ceiling, less its headroom. The `use` is the value, divided by that amount.\n * The limit holds when the `use` is 1 or less.\n */\nexport interface LimitUse {\n /** This id is the id of the limit. */\n readonly limit: string;\n readonly measure: string;\n readonly value: Quantity;\n readonly amount: Quantity;\n readonly use: number;\n readonly holds: boolean;\n}\n\n/** This function gives the amount of a limit at the path `at`, or the problem that stops it. */\nconst amountAt = (limit: Limit, instance: Instance, at: string): Result<Quantity, LimitProblem> => {\n const bad = limitProblems(limit, at)[0];\n if (bad !== undefined) return err(bad);\n let ceiling: Quantity;\n if (limit.ceiling.kind === \"amount\") {\n ceiling = limit.ceiling.amount;\n } else {\n const name = limit.ceiling.resource;\n if (!Object.hasOwn(instance.resources, name)) {\n return err(limitProblem(\"resource\", `resources.${name}`, `The instance has no resource \"${name}\" for the limit \"${limit.id}\".`));\n }\n const resource: unknown = instance.resources[name];\n if (!isQuantity(resource) || !(resource.value > 0)) {\n return err(limitProblem(\"resource\", `resources.${name}`, `The resource \"${name}\" of the instance is not a finite amount above 0.`));\n }\n ceiling = resource;\n }\n const amount = scale(ceiling, 1 - limit.headroom);\n if (!(amount.value > 0) || !finite(amount.value)) {\n const field = at === \"\" ? \"ceiling\" : `${at}.ceiling`;\n return err(limitProblem(\"amount\", field, `The ceiling of the limit \"${limit.id}\", less its headroom, is not a finite amount above 0.`));\n }\n return ok(amount);\n};\n\n/** This function gives the use of a limit, with the path of the limit and the path of the value for a problem. */\nconst useAt = (limit: Limit, instance: Instance, value: Quantity, at: string, valuePath: string): Result<LimitUse, LimitProblem> => {\n const amount = amountAt(limit, instance, at);\n if (amount.tag === \"err\") return amount;\n if (!isQuantity(value) || value.value < 0) {\n return err(limitProblem(\"amount\", valuePath, `The value of the measure \"${limit.measure}\" is not a finite amount of 0 or more.`));\n }\n if (!convertible(value.unit, amount.value.unit)) {\n const why = whyNotConvertible(value.unit, amount.value.unit) ?? \"the units are different\";\n return err(\n limitProblem(\n \"unit\",\n valuePath,\n `The measure \"${limit.measure}\" is in \"${value.unit}\", and the ceiling of the limit \"${limit.id}\" is in \"${amount.value.unit}\": ${why}.`,\n ),\n );\n }\n const use = valueIn(value, amount.value.unit) / amount.value.value;\n if (!finite(use)) return err(limitProblem(\"amount\", valuePath, `The value of the measure \"${limit.measure}\" has no finite use.`));\n return ok({ limit: limit.id, measure: limit.measure, value, amount: amount.value, use, holds: use <= 1 });\n};\n\n/**\n * This function gives the amount of a limit on an instance: the ceiling, less the headroom. It is\n * the largest value of the measure that holds the limit, in the unit of the ceiling.\n *\n * It gives a problem for a limit that is not correct. It gives a problem for a ceiling that names\n * a resource when the instance does not have that resource.\n */\nexport const limitAmount = (limit: Limit, instance: Instance): Result<Quantity, LimitProblem> => amountAt(limit, instance, \"\");\n\n/**\n * This function gives the use of a limit on an instance by one value of its measure. The use is\n * the value, divided by the amount of the limit. Thus a use of 1 is exactly at the limit.\n *\n * It gives each problem of `limitAmount`. It gives a problem for a value that is not a finite\n * amount of 0 or more. It gives a problem for a value that does not convert to the unit of the ceiling.\n */\nexport const limitUse = (limit: Limit, instance: Instance, value: Quantity): Result<LimitUse, LimitProblem> =>\n useAt(limit, instance, value, \"\", \"value\");\n\n/**\n * This function gives the use of each limit on an instance. The `values` give the value of each\n * measure, by the id of the measure. The uses go from the largest to the smallest. Thus the first\n * use is the limit that binds.\n *\n * A limit with no value is a problem, and not a limit that holds. The function also gives a\n * problem for two limits with one id, and each problem of `limitUse`.\n */\nexport const limitUses = (limits: readonly Limit[], instance: Instance, values: Amounts): Result<readonly LimitUse[], LimitProblem> => {\n const twice = repeated(limits.map((limit) => limit.id));\n if (twice !== undefined) return err(limitProblem(\"id\", \"limits\", `Two limits have the id \"${twice}\".`));\n const uses: LimitUse[] = [];\n for (const [index, limit] of limits.entries()) {\n const at = `limits[${index}]`;\n if (!Object.hasOwn(values, limit.measure)) {\n return err(limitProblem(\"measure\", `${at}.measure`, `The values give no amount for the measure \"${limit.measure}\" of the limit \"${limit.id}\".`));\n }\n const use = useAt(limit, instance, values[limit.measure] as Quantity, at, `values.${limit.measure}`);\n if (use.tag === \"err\") return use;\n uses.push(use.value);\n }\n return ok(uses.sort((a, b) => b.use - a.use));\n};\n","import { err, ok, type Result } from \"@mark1russell7/optional\";\nimport { convertible, factorOf, whyNotConvertible } from \"@mark1russell7/quantity\";\nimport {\n flatPartsOf,\n partsOutside,\n preparedOf,\n rowValueOf,\n rowValuesOf,\n type Catalog,\n type Composition,\n type CompositionProblemCode,\n type FlatPart,\n type Prepared,\n} from \"./composition.ts\";\nimport { portionOf } from \"./demand.ts\";\nimport type { Instance, Limit, LimitProblemCode } from \"./instance.ts\";\nimport { MAX_STEPS, amountTest, openValueOf, rowOf, searchGrid, type Curve, type OpenValue } from \"./knee.ts\";\nimport { DEFAULT_LEVEL, type Problem } from \"./law.ts\";\nimport { limitAmount } from \"./limit.ts\";\nimport { repeated } from \"./names.ts\";\nimport type { LevelOptions, Range } from \"./value.ts\";\nimport { demandProblems } from \"./workload-check.ts\";\nimport type { Amounts, Demand } from \"./workload.ts\";\n\n/** This number is the largest count of instances of a scale search when the options give none: 2 to the power 20. */\nexport const SCALE_MOST: number = 2 ** 20;\n\n/** This number is the count of steps of the grid of a scale search when the options give none. */\nexport const SCALE_STEPS: number = 128;\n\n/**\n * A scale model holds what the scale queries of a service read: the resources of one instance, the\n * limits of the service and the compositions. Each limit reads the composition of its measure. The\n * catalog gives each law and each nested composition that the compositions name.\n */\nexport interface ScaleModel {\n readonly instance: Instance;\n readonly limits: readonly Limit[];\n /** Each composition gives one measure, by the id of its measure. The list can hold compositions that no limit reads. */\n readonly compositions: readonly Composition[];\n readonly catalog: Catalog;\n}\n\n/**\n * These options set a scale query. The field `given` gives the state of each instance, for example\n * its heap. A level in `whole` does not divide between the instances, as in `shareOf`.\n *\n * The count search goes up to `most` instances. The load search goes from `1 / most` to `most`\n * times the demand. Each search has a grid of `steps` steps on a log scale. The level of the\n * intervals is 0.95 when the options give none.\n */\nexport interface ScaleOptions extends LevelOptions {\n readonly given?: Amounts;\n readonly whole?: readonly string[];\n readonly most?: number;\n readonly steps?: number;\n}\n\n/** A scale problem code names the part of a scale model, or of a scale query, that is not correct. */\nexport type ScaleProblemCode = CompositionProblemCode | LimitProblemCode;\n\n/** A scale problem tells what is not correct, and where: `path` is the path of the field in the model or in the query. */\nexport type ScaleProblem = Problem<ScaleProblemCode>;\n\n/**\n * A limit count is the lowest count of instances that holds one limit at a load. Each larger count\n * also holds the limit. A null count is more than the largest count of the search.\n */\nexport interface LimitCount {\n readonly limit: string;\n readonly measure: string;\n readonly count: OpenValue;\n /** This number is the share of the replicates where this limit needs more instances than each other limit. */\n readonly binds: number;\n /** This flag tells that the composition has no value past the share of the estimate. Then the edge of the composition sets the count. */\n readonly edge: boolean;\n /** This flag tells that a law of the composition reads a variable outside its range at the count of the estimate. */\n readonly extrapolated: boolean;\n}\n\n/**\n * A limit reach is the first load where one limit breaks at a count of instances, as a factor of\n * the demand. Below this factor, the limit holds. A null factor is past the end of the search.\n */\nexport interface LimitReach {\n readonly limit: string;\n readonly measure: string;\n readonly factor: OpenValue;\n /** This number is the share of the replicates where this limit breaks before each other limit. */\n readonly binds: number;\n /** This flag tells that the composition has no value past the factor of the estimate. Then the edge of the composition sets the factor. */\n readonly edge: boolean;\n /** This flag tells that a law of the composition reads a variable outside its range at the factor of the estimate. */\n readonly extrapolated: boolean;\n}\n\n/**\n * A count reach is the highest load that a count of instances holds, as a factor of the demand. The\n * demand at the factor `f` is `scaleDemand(demand, f)`. The `factor` is the first factor where a\n * limit breaks, and the `binding` limit breaks there in the estimate.\n *\n * The limits go from the first limit that breaks to the last. The flag `extrapolated` tells that a\n * law reads a variable outside its range at the factor of the estimate.\n */\nexport interface CountReach {\n readonly count: number;\n readonly level: number;\n readonly search: Range;\n readonly factor: OpenValue;\n readonly binding: string | null;\n readonly extrapolated: boolean;\n readonly limits: readonly LimitReach[];\n}\n\n/**\n * A scale rule is the lowest count of instances that holds each limit at a load, with its interval.\n * Each larger count also holds each limit. A null count is more than `most` instances.\n *\n * The `binding` limit needs the most instances in the estimate. It is null when one instance holds\n * each limit at each share of the search. The limits go from the largest count to the smallest. The\n * reach `next` is the highest load of the count of the estimate: there the service needs one more instance.\n */\nexport interface ScaleRule {\n readonly level: number;\n readonly most: number;\n readonly count: OpenValue;\n readonly binding: string | null;\n readonly extrapolated: boolean;\n readonly limits: readonly LimitCount[];\n readonly next: CountReach | null;\n}\n\n/** The setup of one limit: its composition, and the number that changes a value of the composition to a use of the limit. */\ninterface LimitSetup {\n readonly limit: Limit;\n readonly path: string;\n /** This index is the index of the composition in the model. */\n readonly at: number;\n readonly prepared: Prepared;\n /** This number times a value of the composition is the use of the limit. A use above 1 breaks the limit. */\n readonly per: number;\n}\n\n/** The setup of a scale query: each limit, the count of rows that the limits share, and the options. */\ninterface Setup {\n readonly limits: readonly LimitSetup[];\n readonly rows: number;\n readonly level: number;\n readonly given: Amounts;\n readonly whole: readonly string[];\n readonly most: number;\n readonly steps: number;\n readonly demand: Demand;\n}\n\n/** A path of demands gives the demand on one instance at each load of a search. */\ntype DemandAt = (load: number) => Demand | undefined;\n\n/** The search of one limit: the first load where each row breaks the limit, and if the edge sets the load of the estimate. Row 0 is the estimate. */\ninterface LimitBreaks {\n readonly rows: readonly number[];\n readonly edge: boolean;\n}\n\n/**\n * The summary holds the rows of all limits: the first load where each row breaks a limit. It also holds the limit that\n * breaks first in the estimate, and the share of the rows where each limit is first.\n */\ninterface Summary {\n readonly rows: readonly number[];\n readonly binding: number | null;\n readonly binds: readonly number[];\n /** These indexes put the limits in the order of the load of the estimate, from the first limit that breaks. */\n readonly order: readonly number[];\n}\n\nconst problem = (code: ScaleProblemCode, path: string, message: string): ScaleProblem => ({ code, path, message });\n\n/** This function gives a problem with `owner` in front of its path. */\nconst under = (found: Problem<string>, owner: string): ScaleProblem => ({\n code: found.code as ScaleProblemCode,\n path: `${owner}.${found.path}`,\n message: found.message,\n});\n\n/**\n * This function gives a problem of a composition of the model, with the path in the model. A path of\n * the catalog starts with `laws` or `compositions`, and each other path is in the composition.\n */\nconst inComposition = (found: Problem<string>, at: number): ScaleProblem =>\n under(found, /^(laws|compositions)\\./.test(found.path) ? \"catalog\" : `compositions[${at}]`);\n\n/** This function gives the setup of a scale query, or the first problem of the model, the demand or the options. */\nconst setupOf = (model: ScaleModel, demand: Demand, options: ScaleOptions): Result<Setup, ScaleProblem> => {\n const level = options.level ?? DEFAULT_LEVEL;\n const most = options.most ?? SCALE_MOST;\n if (!Number.isSafeInteger(most) || most < 2) {\n return err(problem(\"factor\", \"most\", `The largest count of the search, ${most}, is not a whole number of 2 or more.`));\n }\n const badDemand = demandProblems(demand)[0];\n if (badDemand !== undefined) return err(under(badDemand, \"demand\"));\n const whole = options.whole ?? [];\n const unknown = whole.find((name) => !Object.hasOwn(demand.levels, name));\n if (unknown !== undefined) return err(problem(\"variable\", \"whole\", `The demand has no level \"${unknown}\".`));\n if (model.limits.length === 0) return err(problem(\"measure\", \"limits\", \"The model has no limit.\"));\n const twice = repeated(model.limits.map((limit) => limit.id));\n if (twice !== undefined) return err(problem(\"id\", \"limits\", `Two limits have the id \"${twice}\".`));\n\n const byMeasure = new Map<string, number>();\n for (const [index, composition] of model.compositions.entries()) {\n const measure = composition.measure.id;\n if (byMeasure.has(measure)) return err(problem(\"measure\", `compositions[${index}].measure.id`, `Two compositions give the measure \"${measure}\".`));\n byMeasure.set(measure, index);\n }\n const prepared = new Map<number, Prepared>();\n const limits: LimitSetup[] = [];\n for (const [index, limit] of model.limits.entries()) {\n const path = `limits[${index}]`;\n const amount = limitAmount(limit, model.instance);\n if (amount.tag === \"err\") return err(under(amount.error, amount.error.path.startsWith(\"resources.\") ? \"instance\" : path));\n const at = byMeasure.get(limit.measure);\n if (at === undefined) {\n return err(problem(\"measure\", `${path}.measure`, `The model has no composition of the measure \"${limit.measure}\" of the limit \"${limit.id}\".`));\n }\n const composition = model.compositions[at] as Composition;\n let ready = prepared.get(at);\n if (ready === undefined) {\n const found = preparedOf(composition, model.catalog, level);\n if (found.tag === \"err\") return err(inComposition(found.error, at));\n ready = found.value;\n prepared.set(at, ready);\n }\n const unit = composition.measure.unit;\n const ceiling = amount.value;\n if (!convertible(unit, ceiling.unit)) {\n const why = whyNotConvertible(unit, ceiling.unit) ?? \"the units are different\";\n const message = `The composition of the limit \"${limit.id}\" gives \"${unit}\", and the ceiling of the limit is in \"${ceiling.unit}\": ${why}.`;\n return err(problem(\"unit\", `compositions[${at}].measure.unit`, message));\n }\n limits.push({ limit, path, at, prepared: ready, per: factorOf(unit, ceiling.unit) / ceiling.value });\n }\n const rows = Math.min(...limits.map((each) => each.prepared.rows));\n return ok({ limits, rows, level, given: options.given ?? {}, whole, most, steps: options.steps ?? SCALE_STEPS, demand });\n};\n\n/** This function gives the flat parts of the composition of a limit at one load of a path, or undefined when the load has none. */\nconst partsAt = (setup: Setup, each: LimitSetup, demandAt: DemandAt, load: number): readonly FlatPart[] | undefined => {\n const demand = demandAt(load);\n if (demand === undefined) return undefined;\n const parts = flatPartsOf(each.prepared, demand, setup.given);\n return parts.tag === \"ok\" ? parts.value : undefined;\n};\n\n/**\n * This function searches each limit along a path of demands. For each row of each limit, it gives the first load\n * where the use of the limit is above 1. A load where the composition has no value also breaks the row.\n * Infinity tells that the row holds the limit on all of the grid.\n *\n * A problem of the composition at the start of the search is a problem of the model, and not an edge.\n */\nconst breaksOf = (setup: Setup, grid: readonly number[], demandAt: DemandAt): Result<readonly LimitBreaks[], ScaleProblem> => {\n const found: LimitBreaks[] = [];\n const start = grid[0] as number;\n for (const each of setup.limits) {\n const demand = demandAt(start);\n if (demand !== undefined) {\n const first = flatPartsOf(each.prepared, demand, setup.given);\n if (first.tag === \"err\") return err(inComposition(first.error, each.at));\n }\n // The loads of the grid repeat in each row. Thus the parts of a load are kept for the next row.\n const known = new Map<number, readonly FlatPart[] | undefined>();\n const cached = (load: number): readonly FlatPart[] | undefined => {\n if (!known.has(load)) known.set(load, partsAt(setup, each, demandAt, load));\n return known.get(load);\n };\n // Each row reads each load of the grid. Thus the values of all the rows at a load of the grid come from one call.\n // The loads of a bisection differ for each row, so they give the value of one row.\n const onGrid = new Set(grid);\n const gridRows = new Map<number, readonly (number | undefined)[] | undefined>();\n const valueAt = (load: number, row: number): number | undefined => {\n if (onGrid.has(load)) {\n if (!gridRows.has(load)) {\n const parts = cached(load);\n gridRows.set(load, parts === undefined ? undefined : rowValuesOf(parts, 0, setup.rows));\n }\n return gridRows.get(load)?.[row];\n }\n const parts = cached(load);\n return parts === undefined ? undefined : rowValueOf(parts, row);\n };\n const rows: number[] = [];\n let edge = false;\n for (let row = 0; row <= setup.rows; row += 1) {\n const curve: Curve = (loads) =>\n loads.map((load) => {\n const value = valueAt(load, row);\n return value === undefined ? undefined : each.per * value;\n });\n const result = rowOf(curve, `${each.path}.rows[${row}]`, amountTest(1), grid, 0, \"composition\");\n if (result.tag === \"err\") return result;\n const crossing = result.value.crossing ?? Infinity;\n if (row === 0) edge = result.value.edge <= crossing && Number.isFinite(result.value.edge);\n rows.push(Math.min(crossing, result.value.edge));\n }\n found.push({ rows, edge });\n }\n return ok(found);\n};\n\n/** This function gives the index of the least finite value, the first on a tie, or null when no value is finite. */\nconst leastOf = (values: readonly number[]): number | null => {\n let best: number | null = null;\n for (const [index, value] of values.entries()) {\n if (Number.isFinite(value) && (best === null || value < (values[best] as number))) best = index;\n }\n return best;\n};\n\n/** This function joins the rows of the limits. Each row breaks at the first load where one of its limits breaks. */\nconst summaryOf = (breaks: readonly LimitBreaks[], rows: number): Summary => {\n const joined: number[] = [];\n const counts = new Array<number>(breaks.length).fill(0);\n for (let row = 0; row <= rows; row += 1) {\n const loads = breaks.map((each) => each.rows[row] as number);\n const first = leastOf(loads);\n joined.push(first === null ? Infinity : (loads[first] as number));\n if (row > 0 && first !== null) counts[first] = (counts[first] as number) + 1;\n }\n const estimate = breaks.map((each) => each.rows[0] as number);\n const order = estimate.map((_, index) => index).sort((a, b) => (estimate[a] as number) - (estimate[b] as number) || a - b);\n return { rows: joined, binding: leastOf(estimate), binds: counts.map((count) => count / rows), order };\n};\n\n/** This function tells if a law of the composition of a limit reads a variable outside its range at one load of a path. */\nconst outsideAt = (setup: Setup, each: LimitSetup, demandAt: DemandAt, load: number): boolean => {\n const parts = partsAt(setup, each, demandAt, load);\n return parts !== undefined && partsOutside(parts);\n};\n\n/** This function tells if a law of the composition of a limit reads a variable outside its range at one load. */\ntype OutsideAt = (each: LimitSetup, load: number) => boolean;\n\n/** This function gives the reach of a count of instances from the breaks of each limit along the factor of the demand. */\nconst reachFrom = (setup: Setup, count: number, breaks: readonly LimitBreaks[], outside: OutsideAt): CountReach => {\n const { most, level } = setup;\n const summary = summaryOf(breaks, setup.rows);\n const at = (value: number | null): number => value ?? most;\n const limits = summary.order.map((index): LimitReach => {\n const each = setup.limits[index] as LimitSetup;\n const found = breaks[index] as LimitBreaks;\n const factor = openValueOf(found.rows, level, most);\n return {\n limit: each.limit.id,\n measure: each.limit.measure,\n factor,\n binds: summary.binds[index] as number,\n edge: found.edge,\n extrapolated: outside(each, at(factor.value)),\n };\n });\n const factor = openValueOf(summary.rows, level, most);\n return {\n count,\n level,\n search: { low: 1 / most, high: most },\n factor,\n binding: summary.binding === null ? null : (setup.limits[summary.binding] as LimitSetup).limit.id,\n extrapolated: setup.limits.some((each) => outside(each, at(factor.value))),\n limits,\n };\n};\n\n/** This function gives the reach of a count of instances, from a correct setup. */\nconst reachOf = (setup: Setup, count: number): Result<CountReach, ScaleProblem> => {\n const { most, whole } = setup;\n const grid = searchGrid(1 / most, most, setup.steps, true, \"The factor of the demand\");\n if (grid.tag === \"err\") return grid;\n const demandAt: DemandAt = (factor) => {\n const portion = portionOf(setup.demand, factor / count, factor, whole);\n return portion.tag === \"ok\" ? portion.value : undefined;\n };\n const breaks = breaksOf(setup, grid.value, demandAt);\n if (breaks.tag === \"err\") return breaks;\n return ok(reachFrom(setup, count, breaks.value, (each, factor) => outsideAt(setup, each, demandAt, factor)));\n};\n\n/**\n * This function gives the highest load that a count of instances holds, as a factor of the demand,\n * with an interval. Thus it is the inverse query of the scale rule. The demand divides between the\n * instances, as in `shareOf`, and the levels in `options.whole` do not divide.\n *\n * Each row of the doubt of the laws has its own search. Row `i` of each limit reads row `i` of each\n * law, thus the rows of the limits pair. The factor of a row is the first factor where one limit\n * of the row breaks, or where a composition has no value. The interval is the share `level` of the\n * factors of the replicates, made wider to hold the factor of the estimate.\n *\n * The search tests a grid of factors, then a bisection finds each crossing. A crossing between two\n * loads of the grid is found. Two crossings in one step of the grid can hide the first.\n *\n * The function gives a problem for a model, a demand or options that are not correct. It gives a\n * problem for a count that is not a whole number of 1 or more. It also gives a problem when a\n * composition has no value at the start of the search.\n */\nexport const countReach = (model: ScaleModel, count: number, demand: Demand, options: ScaleOptions = {}): Result<CountReach, ScaleProblem> => {\n const setup = setupOf(model, demand, options);\n if (setup.tag === \"err\") return setup;\n if (!Number.isSafeInteger(count) || count < 1) {\n return err(problem(\"factor\", \"count\", `The count of instances ${count} is not a whole number of 1 or more.`));\n }\n return reachOf(setup.value, count);\n};\n\n/** This function gives the lowest count of instances for a share of one instance where a limit breaks. A null count is more than `most`. */\nconst countAt = (share: number | null, most: number): number | null => {\n if (share === null) return 1;\n const count = Math.floor(1 / share) + 1;\n return count > most ? null : count;\n};\n\n/** This function changes an open value of the share of one instance to an open value of the count. The ends change places. */\nconst countsOf = (share: OpenValue, most: number): OpenValue => ({\n value: countAt(share.value, most),\n interval: { low: countAt(share.interval.high, most), high: countAt(share.interval.low, most) },\n});\n\n/**\n * This function gives the scale rule of a service at a load: the lowest count of instances that\n * holds each limit, with an interval. It also gives the limit that binds first, and the load of the\n * next step: the highest load of that count, from `countReach`.\n *\n * The search goes along the share of the demand on one instance: the share of `n` instances is\n * `1 / n`. It starts at the share of `most` instances and goes up to the share of one instance. The\n * count of a row comes from the first share where one limit of the row breaks. Thus the count holds\n * each limit, and each larger count also holds each limit. A level in `options.whole` does not divide.\n *\n * Each row of the doubt of the laws has its own search, and the rows of the limits pair, as in\n * `countReach`. The interval of the count is the share `level` of the counts of the replicates, made\n * wider to hold the count of the estimate. The field `binds` of each limit is the share of the\n * replicates where that limit sets the count.\n *\n * The function gives each problem of `countReach` that is not about a count.\n */\nexport const scaleRule = (model: ScaleModel, demand: Demand, options: ScaleOptions = {}): Result<ScaleRule, ScaleProblem> => {\n const setup = setupOf(model, demand, options);\n if (setup.tag === \"err\") return setup;\n const { most, whole } = setup.value;\n const grid = searchGrid(1 / most, 1, setup.value.steps, true, \"The share of one instance\");\n if (grid.tag === \"err\") return grid;\n const demandAt: DemandAt = (share) => {\n const portion = portionOf(setup.value.demand, share, 1, whole);\n return portion.tag === \"ok\" ? portion.value : undefined;\n };\n const breaks = breaksOf(setup.value, grid.value, demandAt);\n if (breaks.tag === \"err\") return breaks;\n return ruleFrom(\n setup.value,\n breaks.value,\n (each, share) => outsideAt(setup.value, each, demandAt, share),\n (count) => reachOf(setup.value, count),\n );\n};\n\n/** This function gives the scale rule from the breaks of each limit along the share of one instance, and the reach of a count. */\nconst ruleFrom = (\n setup: Setup,\n breaks: readonly LimitBreaks[],\n outside: OutsideAt,\n reachAt: (count: number) => Result<CountReach, ScaleProblem>,\n): Result<ScaleRule, ScaleProblem> => {\n const { most, level } = setup;\n const summary = summaryOf(breaks, setup.rows);\n const shareOfCount = (count: number | null): number => 1 / (count ?? most);\n const limits = summary.order.map((index): LimitCount => {\n const each = setup.limits[index] as LimitSetup;\n const found = breaks[index] as LimitBreaks;\n const count = countsOf(openValueOf(found.rows, level, 1), most);\n return {\n limit: each.limit.id,\n measure: each.limit.measure,\n count,\n binds: summary.binds[index] as number,\n edge: found.edge,\n extrapolated: outside(each, shareOfCount(count.value)),\n };\n });\n const count = countsOf(openValueOf(summary.rows, level, 1), most);\n let next: CountReach | null = null;\n if (count.value !== null) {\n const reach = reachAt(count.value);\n if (reach.tag === \"err\") return reach;\n next = reach.value;\n }\n return ok({\n level,\n most,\n count,\n binding: summary.binding === null ? null : (setup.limits[summary.binding] as LimitSetup).limit.id,\n extrapolated: setup.limits.some((each) => outside(each, shareOfCount(count.value))),\n limits,\n next,\n });\n};\n\n/** A limit ladder holds, for each row of one limit, the first load on one instance where the row breaks the limit. */\nexport interface LimitLadder {\n readonly limit: string;\n readonly measure: string;\n /**\n * Each value is the first load on one instance, as a factor of the demand, where one row breaks the limit. Row 0 is the\n * estimate. A load where the composition has no value also breaks the row. Infinity tells that the row holds on all of the search.\n */\n readonly rows: readonly number[];\n /** This flag tells that the edge of the composition sets the load of row 0. */\n readonly edge: boolean;\n}\n\n/**\n * A scale ladder is the scale rule of a service at each load of a range, from one search. With no level in `whole`, the\n * demand on one of `n` instances at `f` times the load is the demand at `f / n` times the load. Thus each row of each\n * limit breaks at one load on one instance, and a count needs only arithmetic.\n *\n * The function `ruleAt(f)` gives the value of `scaleRule` at the demand `scaleDemand(demand, f)`. The function\n * `reachAt(n, f)` gives the value of `countReach` for `n` instances at the same demand. Each of them reads the\n * compositions only for the flags `extrapolated`, one value for each limit.\n */\nexport interface ScaleLadder {\n readonly level: number;\n readonly most: number;\n /** This range holds the factors of the demand that the ladder answers. */\n readonly range: Range;\n /** This range holds the loads on one instance of the search, as factors of the demand. */\n readonly search: Range;\n /** The limits are in the order of the model. */\n readonly limits: readonly LimitLadder[];\n readonly ruleAt: (factor: number) => Result<ScaleRule, ScaleProblem>;\n readonly reachAt: (count: number, factor: number) => Result<CountReach, ScaleProblem>;\n}\n\n/**\n * This function changes the loads on one instance of a ladder to the loads of a search from `low` to `high`. A load\n * past `high` holds on all of that search, and a load before `low` breaks at its start, as in `rowOf`.\n */\nconst loadsIn = (rows: readonly number[], times: number, low: number, high: number): number[] =>\n rows.map((load) => {\n const found = load * times;\n return found > high ? Infinity : Math.max(found, low);\n });\n\n/**\n * This function gives the scale ladder of a service over the factors of the demand from `range.low` to `range.high`.\n * The search covers the loads on one instance that `scaleRule` and `countReach` read at each factor of the range: from\n * `range.low / most` to `range.high * most`. Its grid has the density of the grid of `scaleRule`, up to the largest\n * count of steps.\n *\n * The values of the ladder agree with `scaleRule` and `countReach` to the precision of their bisections. They can differ\n * when two crossings are in one step of a grid, because the grids are different.\n *\n * The function gives each problem of `scaleRule`. It also gives a problem for a level in `options.whole`. With such a level,\n * the demand on one instance does not depend only on the load over the count. It gives a problem for a range that does not\n * go from a number above 0 to a larger finite number.\n */\nexport const scaleLadder = (model: ScaleModel, demand: Demand, range: Range, options: ScaleOptions = {}): Result<ScaleLadder, ScaleProblem> => {\n const found = setupOf(model, demand, options);\n if (found.tag === \"err\") return found;\n const setup = found.value;\n if (setup.whole.length > 0) {\n return err(problem(\"variable\", \"whole\", \"A ladder needs a demand that divides between the instances. Use scaleRule for a level in whole.\"));\n }\n if (!(range.low > 0 && Number.isFinite(range.high) && range.low < range.high)) {\n return err(problem(\"factor\", \"range\", `The range goes from ${range.low} to ${range.high}. It must go from a number above 0 to a larger finite number.`));\n }\n const { most, level } = setup;\n const search: Range = { low: range.low / most, high: range.high * most };\n // The grid of scaleRule has `steps` steps over the factor `most`. This grid keeps that count of steps for each factor.\n const steps = Math.min(MAX_STEPS, Math.max(setup.steps, Math.ceil((setup.steps * Math.log(search.high / search.low)) / Math.log(most))));\n const grid = searchGrid(search.low, search.high, steps, true, \"The load on one instance\");\n if (grid.tag === \"err\") return grid;\n const demandAt: DemandAt = (load) => {\n const portion = portionOf(setup.demand, load, load, []);\n return portion.tag === \"ok\" ? portion.value : undefined;\n };\n const breaks = breaksOf(setup, grid.value, demandAt);\n if (breaks.tag === \"err\") return breaks;\n const ladder = breaks.value;\n const outsideOn = (each: LimitSetup, load: number): boolean => outsideAt(setup, each, demandAt, load);\n const inRange = (factor: number): Result<number, ScaleProblem> =>\n factor >= range.low && factor <= range.high\n ? ok(factor)\n : err(problem(\"factor\", \"factor\", `The factor ${factor} is outside the range of the ladder, from ${range.low} to ${range.high}.`));\n /** This function gives the breaks of each limit along the factor of a search from `low` to `high`. The load on one instance is `times` the factor. */\n const breaksIn = (times: number, low: number, high: number): LimitBreaks[] =>\n ladder.map((each) => {\n const rows = loadsIn(each.rows, 1 / times, low, high);\n return { rows, edge: each.edge && Number.isFinite(rows[0] as number) };\n });\n const reachIn = (count: number, factor: number): CountReach =>\n reachFrom(setup, count, breaksIn(factor / count, 1 / most, most), (each, at) => outsideOn(each, (factor * at) / count));\n const reachAt = (count: number, factor: number): Result<CountReach, ScaleProblem> => {\n if (!Number.isSafeInteger(count) || count < 1) {\n return err(problem(\"factor\", \"count\", `The count of instances ${count} is not a whole number of 1 or more.`));\n }\n const at = inRange(factor);\n return at.tag === \"err\" ? at : ok(reachIn(count, factor));\n };\n const ruleAt = (factor: number): Result<ScaleRule, ScaleProblem> => {\n const at = inRange(factor);\n if (at.tag === \"err\") return at;\n return ruleFrom(\n setup,\n breaksIn(factor, 1 / most, 1),\n (each, share) => outsideOn(each, factor * share),\n (count) => ok(reachIn(count, factor)),\n );\n };\n const limits = setup.limits.map((each, index): LimitLadder => ({ limit: each.limit.id, measure: each.limit.measure, ...(ladder[index] as LimitBreaks) }));\n return ok({ level, most, range, search, limits, ruleAt, reachAt });\n};\n"],"mappings":";;;;;;;;AAOA,MAAa,gBAAgB;AA4E7B,MAAM,IAAI,EAAA,GAAe;AACzB,MAAM,MAAM,IAAI,CAAC;AACjB,MAAM,OAAO,IAAI,CAAC;AAClB,MAAM,OAAO,GAAG,UAAiC,MAAM,QAAQ,KAAK,SAAS,IAAI,OAAO,KAAK,IAAI,CAAC;AAClG,MAAM,SAAS,GAAS,MAAkB,IAAI,YAAY,GAAG,CAAC;AAC9D,MAAM,QAAQ,GAAS,MAAkB,IAAI,UAAU,GAAG,CAAC;AAC3D,MAAM,QAAQ,GAAS,MAAkB,IAAI,YAAY,GAAG,CAAC;AAC7D,MAAM,UAAU,MAAkB,IAAI,OAAO,GAAG,IAAI,CAAC,CAAC;AACt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AAqD;EACnF,IAAI,CAAC,OAAO,cAAc,KAAK,KAAK,QAAQ,GAC1C,OAAO,IAAI,QAAQ,UAAU,SAAS,0BAA0B,MAAM,qCAAqC,CAAC;EAE9G,MAAM,KAAK,QAAQ,MAAM;EACzB,OAAO,GAAG,QAAQ,QAAQ,KAAK,GAAG,QAAQ,OAAO,MAAM,CAAC;CAC1D;CACA,MAAM,UAAU,WAAoD;EAClE,MAAM,KAAK,QAAQ,MAAM;EACzB,IAAI,GAAG,QAAQ,OAAO,OAAO;EAC7B,OAAO,SACL,OACA,SAAS,QAAQ,IAAI,MAAM,CAAC,IAC3B,MAAM,UAAU,UAAU,MAAM,SAAS,KAAK,IAC9C,UAAU,GAAG,QAAQ,OAAO,MAAM,CAAC,CACtC;CACF;CACA,MAAM,SAAS,MAAM,OAAO,KAAK,MAAM,WAAwB;EAAE,OAAO,KAAK,MAAM;EAAI,SAAS,KAAK,MAAM;EAAS,GAAI,OAAO;CAAuB,EAAE;CACxJ,OAAO,GAAG;EAAE;EAAO;EAAM;EAAO;EAAQ;EAAQ;EAAQ;CAAQ,CAAC;AACnE"}
1
+ {"version":3,"file":"index.js","names":["problem","problem"],"sources":["../src/forms.ts","../src/fit.ts","../src/knee.ts","../src/gate.ts","../src/app-metrics.ts","../src/observe.ts","../src/limit.ts","../src/scale.ts"],"sourcesContent":["import { err, ok, type Result } from \"@mark1russell7/optional\";\nimport { fitSeparable, SEPARABLE_MAX_COMBINATIONS, type SeparableFit, type SeparableModel } from \"@mark1russell7/rigor-statistics\";\nimport { app, let_, lit, ref, v, type Expr } from \"@mark1russell7/vex\";\nimport type { Constant, Form } from \"./law.ts\";\nimport { valuesOf } from \"./program.ts\";\n\n/** This name is the name of the load variable in the programs of the catalog. A binding gives its id in a law. */\nexport const FORM_VARIABLE = \"x\";\n\n/**\n * A term is one part of a form: its constant times its basis. The basis and its slope read the\n * variable and the shape constants of the form with `v(name)`. The slope is the change of the basis\n * for each unit of the variable.\n */\nexport interface Term {\n readonly constant: string;\n readonly basis: Expr;\n readonly slope: Expr;\n}\n\n/**\n * A grid gives the start candidates of one shape constant from the points of a fit.\n *\n * - `inside` gives each distinct value of the variable inside its range, and each middle of two\n * values that follow. A knee starts at these values.\n * - `scaled` gives each factor times the largest size of the variable to the `power`. With the power\n * 0, the candidates are the factors.\n */\nexport type Grid =\n | { readonly kind: \"inside\" }\n | { readonly kind: \"scaled\"; readonly factors: readonly number[]; readonly power: number };\n\n/**\n * The bounds tell where the refine of a fit can move a shape constant. They come from the points of the fit.\n *\n * - `range` is from the least value of the variable to its largest value. A knee is inside the range.\n * - `size` is from the largest size of the variable up. The capacity of a queue is past each load.\n * - `least` is from `value` up.\n */\nexport type Bounds = { readonly kind: \"range\" } | { readonly kind: \"size\" } | { readonly kind: \"least\"; readonly value: number };\n\n/**\n * A shape constant changes the shape of a form, not its size. A fit starts it at each value of its grid. Then the fit\n * refines it inside its bounds. A shape with no bounds has no limit.\n */\nexport interface Shape {\n readonly id: string;\n readonly grid: Grid;\n readonly bounds?: Bounds;\n}\n\n/**\n * A catalog form is the math of a law of one variable, as data. Its value is the sum of its terms.\n * Thus, with fixed shape constants, a fit of a form is linear in the constants of its terms.\n */\nexport interface CatalogForm {\n readonly id: string;\n readonly title: string;\n readonly terms: readonly Term[];\n readonly shapes: readonly Shape[];\n}\n\n/**\n * A binding puts a catalog form into a law. It gives the id of the variable in the law, and the id\n * in the law of each constant. A constant with no entry keeps its id from the catalog.\n */\nexport interface Binding {\n readonly variable: string;\n readonly constants?: Readonly<Record<string, string>>;\n}\n\n/** The points of a fit: the value of the variable and the measured value of each point, in the same order. */\nexport interface Points {\n readonly x: readonly number[];\n readonly y: readonly number[];\n}\n\n/** A start is the start values of the constants of a form, and the sum of the squared residuals at these values. */\nexport interface Start {\n readonly constants: readonly Constant[];\n readonly rss: number;\n}\n\nconst x = v(FORM_VARIABLE);\nconst one = lit(1);\nconst zero = lit(0);\nconst add = (...parts: readonly Expr[]): Expr => parts.reduce((sum, part) => app(\"add\", sum, part));\nconst times = (a: Expr, b: Expr): Expr => app(\"multiply\", a, b);\nconst over = (a: Expr, b: Expr): Expr => app(\"divide\", a, b);\nconst less = (a: Expr, b: Expr): Expr => app(\"subtract\", a, b);\nconst square = (a: Expr): Expr => app(\"pow\", a, lit(2));\nconst scaled = (factors: readonly number[], power: number): Grid => ({ kind: \"scaled\", factors, power });\nconst positive: Bounds = { kind: \"least\", value: 0 };\n\n/** The base term: a constant amount. Its slope is 0. */\nconst base: Term = { constant: \"base\", basis: one, slope: zero };\n\n/** The denominator of the scalability law: `1 + contention·(x − 1) + coherency·x·(x − 1)`. */\nconst contention = add(one, times(v(\"contention\"), less(x, one)), times(times(v(\"coherency\"), x), less(x, one)));\n\n/**\n * The catalog of the forms of a law, in the order of the roadmap. Each form is a sum of terms.\n *\n * - `constant`: `base`.\n * - `linear`: `base + slope·x`.\n * - `power`: `base + scale·x^exponent`.\n * - `fall-power`: `base + excess / x + scale·x^exponent`. The term `excess / x` is a cost at a low load that falls as the load grows.\n * - `logarithm`: `base + scale·ln(x)`.\n * - `hinge`: `base + slope·x + bend·max(0, x − knee)`. After the knee the slope is `slope + bend`.\n * - `queue`: `base + scale·capacity / (capacity − x)`. This is the delay of a queue. The form has no\n * finite value at the capacity.\n * - `scalability`: `unit·x / (1 + contention·(x − 1) + coherency·x·(x − 1))`. This is the\n * universal scalability law of the throughput at a concurrency `x`.\n * - `drift`: `base + drift·x + warm·(1 − e^(−x / settle))`. This is a measure over the age of a\n * process: a warm-up that settles, and a steady drift.\n */\nexport const FORMS: readonly CatalogForm[] = [\n { id: \"constant\", title: \"A constant\", terms: [base], shapes: [] },\n { id: \"linear\", title: \"A line\", terms: [base, { constant: \"slope\", basis: x, slope: one }], shapes: [] },\n {\n id: \"power\",\n title: \"A power of the variable\",\n terms: [\n base,\n {\n constant: \"scale\",\n basis: app(\"pow\", x, v(\"exponent\")),\n slope: times(v(\"exponent\"), app(\"pow\", x, less(v(\"exponent\"), one))),\n },\n ],\n shapes: [{ id: \"exponent\", grid: scaled([-1, -0.5, 0.25, 0.5, 0.75, 1, 1.25, 1.5, 2, 3], 0) }],\n },\n {\n id: \"fall-power\",\n title: \"A fall at a low load, then a power of the variable\",\n terms: [\n base,\n { constant: \"excess\", basis: over(one, x), slope: app(\"negate\", over(one, square(x))) },\n {\n constant: \"scale\",\n basis: app(\"pow\", x, v(\"exponent\")),\n slope: times(v(\"exponent\"), app(\"pow\", x, less(v(\"exponent\"), one))),\n },\n ],\n shapes: [{ id: \"exponent\", grid: scaled([0.25, 0.5, 0.75, 1, 1.25, 1.5, 2, 3], 0) }],\n },\n {\n id: \"logarithm\",\n title: \"A logarithm of the variable\",\n terms: [base, { constant: \"scale\", basis: app(\"ln\", x), slope: over(one, x) }],\n shapes: [],\n },\n {\n id: \"hinge\",\n title: \"Two lines that join at a knee\",\n terms: [\n base,\n { constant: \"slope\", basis: x, slope: one },\n {\n constant: \"bend\",\n basis: app(\"max\", zero, less(x, v(\"knee\"))),\n slope: app(\"if\", app(\"gt\", x, v(\"knee\")), one, zero),\n },\n ],\n shapes: [{ id: \"knee\", grid: { kind: \"inside\" }, bounds: { kind: \"range\" } }],\n },\n {\n id: \"queue\",\n title: \"The delay of a queue\",\n terms: [\n base,\n {\n constant: \"scale\",\n basis: over(v(\"capacity\"), less(v(\"capacity\"), x)),\n slope: over(v(\"capacity\"), square(less(v(\"capacity\"), x))),\n },\n ],\n shapes: [{ id: \"capacity\", grid: scaled([1.02, 1.05, 1.1, 1.2, 1.5, 2, 3, 5, 10], 1), bounds: { kind: \"size\" } }],\n },\n {\n id: \"scalability\",\n title: \"The universal scalability law\",\n terms: [\n {\n constant: \"unit\",\n basis: over(x, contention),\n // (D − x·D′) / D², with D′ = contention + coherency·(2x − 1): this is (1 − contention − coherency·x²) / D²\n slope: over(less(less(one, v(\"contention\")), times(v(\"coherency\"), square(x))), square(contention)),\n },\n ],\n shapes: [\n { id: \"contention\", grid: scaled([0, 0.01, 0.03, 0.1, 0.2, 0.4, 0.7], 0), bounds: positive },\n { id: \"coherency\", grid: scaled([0, 0.1, 0.3, 1, 3, 10], -2), bounds: positive },\n ],\n },\n {\n id: \"drift\",\n title: \"A warm-up and a drift with age\",\n terms: [\n base,\n { constant: \"drift\", basis: x, slope: one },\n {\n constant: \"warm\",\n basis: less(one, app(\"exp\", app(\"negate\", over(x, v(\"settle\"))))),\n slope: over(app(\"exp\", app(\"negate\", over(x, v(\"settle\")))), v(\"settle\")),\n },\n ],\n shapes: [{ id: \"settle\", grid: scaled([0.01, 0.03, 0.1, 0.3, 1, 3], 1), bounds: positive }],\n },\n];\n\n/** This function gives the form of the catalog with the id, or undefined. */\nexport const catalogForm = (id: string): CatalogForm | undefined => FORMS.find((form) => form.id === id);\n\n/** This function gives the ids of the constants of a form: the constant of each term, then each shape constant. */\nexport const constantIdsOf = (form: CatalogForm): readonly string[] => [\n ...form.terms.map((term) => term.constant),\n ...form.shapes.map((shape) => shape.id),\n];\n\n/** This function gives the sum of the terms of a form, with `part` for each term. A term of 0 does not count. */\nconst sumOf = (form: CatalogForm, part: (term: Term) => Expr): Expr => {\n const parts = form.terms\n .map((term) => ({ term, expr: part(term) }))\n .filter(({ expr }) => !(expr.tag === \"lit\" && expr.value === 0))\n .map(({ term, expr }) => (expr.tag === \"lit\" && expr.value === 1 ? v(term.constant) : times(v(term.constant), expr)));\n return parts.length === 0 ? zero : add(...parts);\n};\n\n/** This function binds the names `ids` of a form and its variable to the reads of a law. */\nconst bind = (ids: readonly string[], binding: Binding, body: Expr): Expr =>\n let_(Object.fromEntries([[FORM_VARIABLE, ref(binding.variable)], ...ids.map((id) => [id, ref(binding.constants?.[id] ?? id)])]), body);\n\n/** This function binds each name of a form to the reads of a law: the variable and each constant. */\nconst bound = (form: CatalogForm, binding: Binding, body: Expr): Expr => bind(constantIdsOf(form), binding, body);\n\n/** This function gives the program of the value of a form in a law. It reads the variable and each constant of the binding. */\nexport const programOf = (form: CatalogForm, binding: Binding): Expr => bound(form, binding, sumOf(form, (term) => term.basis));\n\n/** This function gives the program of the slope of a form in a law: the change of its value for each unit of the variable. */\nexport const slopeOf = (form: CatalogForm, binding: Binding): Expr => bound(form, binding, sumOf(form, (term) => term.slope));\n\n/** This function gives the form of a law from a form of the catalog. */\nexport const formOf = (form: CatalogForm, binding: Binding): Form => ({ id: form.id, program: programOf(form, binding) });\n\nconst records = (xs: readonly number[], constants: Readonly<Record<string, number>>): Readonly<Record<string, number>>[] =>\n xs.map((value) => ({ ...constants, [FORM_VARIABLE]: value }));\n\n/** This function gives the value of a form at each value of its variable, or the text of the first error. */\nexport const formValues = (\n form: CatalogForm,\n xs: readonly number[],\n constants: Readonly<Record<string, number>>,\n): Result<readonly number[], string> => valuesOf(programOf(form, { variable: FORM_VARIABLE }), records(xs, constants));\n\n/** This function gives the slope of a form at each value of its variable, or the text of the first error. */\nexport const formSlopes = (\n form: CatalogForm,\n xs: readonly number[],\n constants: Readonly<Record<string, number>>,\n): Result<readonly number[], string> => valuesOf(slopeOf(form, { variable: FORM_VARIABLE }), records(xs, constants));\n\n/** This function gives the largest size of the values of a variable. */\nconst sizeOf = (xs: readonly number[]): number => xs.reduce((most, value) => Math.max(most, Math.abs(value)), 0);\n\n/** This function gives the candidates of a grid for the values of a variable. */\nexport const gridOf = (grid: Grid, xs: readonly number[]): readonly number[] => {\n if (grid.kind === \"scaled\") {\n const size = sizeOf(xs);\n return grid.power === 0 ? grid.factors : size === 0 ? [] : grid.factors.map((factor) => factor * size ** grid.power);\n }\n const distinct = [...new Set(xs)].sort((a, b) => a - b);\n const middles = distinct.slice(1).map((value, index) => (value + (distinct[index] as number)) / 2);\n const low = distinct[0] ?? 0;\n const high = distinct.at(-1) ?? 0;\n return [...distinct, ...middles].filter((value) => value > low && value < high).sort((a, b) => a - b);\n};\n\n/** This function gives the bounds of the refine of a shape constant for the values of a variable. */\nconst boundsOf = (bounds: Bounds | undefined, xs: readonly number[]): { readonly min?: number; readonly max?: number } => {\n if (bounds === undefined) return {};\n if (bounds.kind === \"least\") return { min: bounds.value };\n if (bounds.kind === \"size\") return { min: sizeOf(xs) };\n return {\n min: xs.reduce((least, value) => Math.min(least, value), Number.POSITIVE_INFINITY),\n max: xs.reduce((most, value) => Math.max(most, value), Number.NEGATIVE_INFINITY),\n };\n};\n\n/**\n * This function gives a form of the catalog as a separable model of `@mark1russell7/rigor-statistics`. Each term is\n * one column of the design: the basis of the term at each point. The candidates and the bounds of each shape constant\n * come from the values `xs` of the variable. The design is null when a basis has no finite value at a point.\n */\nexport const separableOf = (form: CatalogForm, xs: readonly number[]): SeparableModel<number> => {\n const ids = form.shapes.map((shape) => shape.id);\n // a basis reads the variable and the shape constants, not the constants of the terms\n const bases = form.terms.map((term) => bind(ids, { variable: FORM_VARIABLE }, term.basis));\n return {\n terms: form.terms.map((term) => term.constant),\n shapes: form.shapes.map((shape) => ({ id: shape.id, candidates: gridOf(shape.grid, xs), ...boundsOf(shape.bounds, xs) })),\n design: (values, points) => {\n const at = Object.fromEntries(ids.map((id, index) => [id, values[index] as number]));\n const columns: (readonly number[])[] = [];\n for (const basis of bases) {\n const column = valuesOf(basis, records(points, at));\n if (column.tag === \"err\") return null;\n columns.push(column.value);\n }\n return points.map((_, row) => columns.map((column) => column[row] as number));\n },\n };\n};\n\n/** This function gives the constants of a form from a separable fit: the constant of each term, then each shape constant. */\nexport const constantsOf = (form: CatalogForm, fit: Pick<SeparableFit, \"coefficients\" | \"shapes\">): readonly Constant[] => [\n ...form.terms.map((term, index) => ({ id: term.constant, value: fit.coefficients[index] as number })),\n ...form.shapes.map((shape, index) => ({ id: shape.id, value: fit.shapes[index] as number })),\n];\n\n/** This function gives the text of the first fault of the points of a fit, or undefined. */\nexport const pointsProblem = (points: Points): string | undefined => {\n if (points.x.length === 0) return \"The fit has no points.\";\n if (points.x.length !== points.y.length) return `The points have ${points.x.length} values of x and ${points.y.length} values of y.`;\n if (![...points.x, ...points.y].every(Number.isFinite)) return \"A point has a value that is not a finite number.\";\n return undefined;\n};\n\n/** This function gives the text of the reason that the model of a form has no start, or undefined. */\nexport const modelProblem = (form: CatalogForm, model: SeparableModel<number>): string | undefined => {\n const empty = model.shapes.find((shape) => shape.candidates.length === 0);\n if (empty !== undefined) return `The form \"${form.id}\" has no start value of its shape constant \"${empty.id}\" for these points.`;\n const count = model.shapes.reduce((product, shape) => product * new Set(shape.candidates).size, 1);\n if (count > SEPARABLE_MAX_COMBINATIONS) {\n return `The form \"${form.id}\" has ${count} combinations of start values. The limit is ${SEPARABLE_MAX_COMBINATIONS}.`;\n }\n return undefined;\n};\n\n/**\n * This function gives the least-squares fit of a form to some points, as the start values of its constants.\n *\n * The fit is `fitSeparable` of `@mark1russell7/rigor-statistics`. For each combination of the grids of the shape\n * constants, the least-squares fit gives the constants of the terms. Then a golden-section search refines each shape\n * constant inside its bounds. A form with no shape constant has one combination, thus its start is its least-squares fit.\n *\n * The function gives an error when no combination has a fit, for example with fewer points than terms.\n */\nexport const startOf = (form: CatalogForm, points: Points): Result<Start, string> => {\n const fault = pointsProblem(points);\n if (fault !== undefined) return err(fault);\n const model = separableOf(form, points.x);\n const reason = modelProblem(form, model);\n if (reason !== undefined) return err(reason);\n const fit = fitSeparable(model, points.x, points.y);\n if (fit === null) return err(`The form \"${form.id}\" has no least-squares fit to ${points.x.length} points.`);\n return ok({ constants: constantsOf(form, fit), rss: fit.rss });\n};\n","import { err, ok, type Result } from \"@mark1russell7/optional\";\nimport {\n bootstrapSeparable,\n heldOutSeparable,\n rankSeparable,\n SEPARABLE_BOOTSTRAP_RUNS,\n type SeparableGroup,\n type SeparableModel,\n} from \"@mark1russell7/rigor-statistics\";\nimport { FORM_VARIABLE, FORMS, constantIdsOf, formOf, modelProblem, pointsProblem, separableOf } from \"./forms.ts\";\nimport type { Binding, CatalogForm, Points } from \"./forms.ts\";\nimport { DEFAULT_LEVEL, bootstrapDraws, leastCount, leastGroups, type FitError, type Law, type Loser, type ResidualKind } from \"./law.ts\";\n\n/** The options of `fitLaw`. */\nexport interface LawFitOptions {\n /** These forms compete for the law. The default is each form of the catalog. */\n readonly forms?: readonly CatalogForm[];\n /** This binding puts the form that wins into the law. The default is the variable `x` and the ids of the catalog. */\n readonly binding?: Binding;\n /**\n * This kind tells how the fit compares a value with a form. The default is `\"absolute\"`. A `\"relative\"` fit uses the\n * weights `1 / y^2`. Thus each value of a relative fit is not 0.\n */\n readonly residual?: ResidualKind;\n /**\n * This list gives the group of each point. The points of one group are replicates of one load. The held-out fit holds\n * out each group. The default group of a point is its value of the variable.\n */\n readonly groups?: readonly SeparableGroup[];\n /**\n * This list gives the group of each point for the bootstrap. Each run of the bootstrap draws whole groups of this\n * list. The default is the list `groups`. A group of the bootstrap is an independent unit of the data, for example\n * the job that measured its points. A plan that fixes its loads has no random load, thus a draw of whole loads is\n * the wrong model for it.\n */\n readonly bootstrapGroups?: readonly SeparableGroup[];\n /** This number is the number of runs of the bootstrap. The default is `SEPARABLE_BOOTSTRAP_RUNS` of rigor-statistics. */\n readonly runs?: number;\n /** This seed starts the draws of the bootstrap. The default is 1. */\n readonly seed?: number;\n}\n\n/** A form rank is one form that competed in a law fit, with the error of its held-out residuals. */\nexport interface FormRank {\n readonly form: string;\n /** This error comes from the held-out residuals that have a value. With no such residual, each error is NaN. */\n readonly error: FitError;\n /** This number is the number of points with no held-out prediction. */\n readonly missing: number;\n /** This text tells why the form has no fit. A form with a fit has no reason. */\n readonly reason?: string;\n}\n\n/**\n * A law fit is the part of a law that comes from a fit of its points. It has the form, the constants, the replicates and\n * the record of the fit. The list `ranks` keeps each form that competed, best first.\n */\nexport interface LawFit extends Pick<Law, \"form\" | \"constants\" | \"replicates\" | \"fit\"> {\n readonly ranks: readonly FormRank[];\n}\n\n/**\n * This function fits a law of one variable to its points. Each form competes, and the form with the smallest root mean\n * square of its held-out residuals wins. A form with a point that has no held-out prediction ranks after each form with\n * a prediction at each point.\n *\n * The fit of each form is `fitSeparable` of `@mark1russell7/rigor-statistics`. Each held-out residual comes from a fit of\n * the other groups. The replicates of the winner come from a bootstrap of the whole groups of `bootstrapGroups`. The losers of the record are\n * the other forms with a held-out prediction at each point.\n *\n * The function gives an error for points that a fit cannot use, and when no form has a held-out prediction at each point.\n * It gives an error for fewer groups of the bootstrap than `leastGroups` of the level 0.95, because their draws are too few for an interval.\n */\nexport const fitLaw = (points: Points, options: LawFitOptions = {}): Result<LawFit, string> => {\n const fault = pointsProblem(points);\n if (fault !== undefined) return err(fault);\n const n = points.x.length;\n const forms = options.forms ?? FORMS;\n if (forms.length === 0) return err(\"The fit has no form.\");\n const twice = forms.find((form, index) => forms.findIndex((other) => other.id === form.id) !== index);\n if (twice !== undefined) return err(`The form \"${twice.id}\" is in the list of forms two times.`);\n const residual = options.residual ?? \"absolute\";\n if (residual === \"relative\" && points.y.some((y) => y === 0)) return err(\"A relative fit needs values that are not 0.\");\n const groups = options.groups ?? points.x;\n if (groups.length !== n) return err(`The fit has ${groups.length} groups for ${n} points.`);\n const groupCount = new Set(groups).size;\n if (groupCount < 2) return err(\"The fit needs two groups or more, because the held-out fit holds out one group.\");\n const bootstrapGroups = options.bootstrapGroups ?? groups;\n if (bootstrapGroups.length !== n) return err(`The fit has ${bootstrapGroups.length} groups of the bootstrap for ${n} points.`);\n const bootstrapCount = new Set(bootstrapGroups).size;\n const leastBootstrap = leastGroups(DEFAULT_LEVEL);\n if (bootstrapCount < leastBootstrap) {\n return err(\n `The bootstrap draws whole groups, and the fit has ${bootstrapCount} of them. Thus the count of different draws is ` +\n `${bootstrapDraws(bootstrapCount)}. The level ${DEFAULT_LEVEL} needs ${leastCount(DEFAULT_LEVEL)}, thus ${leastBootstrap} groups or more.`,\n );\n }\n const weighted = residual === \"relative\" ? { weights: points.y.map((y) => 1 / (y * y)) } : {};\n\n const models: Record<string, SeparableModel<number>> = {};\n const skipped: FormRank[] = [];\n for (const form of forms) {\n const model = separableOf(form, points.x);\n const reason = modelProblem(form, model);\n if (reason === undefined) models[form.id] = model;\n else skipped.push({ form: form.id, error: { mae: Number.NaN, rmse: Number.NaN }, missing: n, reason });\n }\n const ranked = rankSeparable(models, points.x, points.y, { groups, residual, ...weighted });\n const ranks: FormRank[] = [\n ...ranked.map((rank): FormRank => ({\n form: rank.id,\n error: { mae: rank.error.mae, rmse: rank.error.rmse },\n missing: rank.error.missing,\n ...(rank.fit === null ? { reason: `The form \"${rank.id}\" has no least-squares fit to ${n} points.` } : {}),\n })),\n ...skipped,\n ];\n const best = ranked[0];\n if (best === undefined || best.fit === null || best.error.missing > 0) {\n return err(`No form of ${forms.length} has a held-out prediction at each of the ${n} points.`);\n }\n const winner = forms.find((form) => form.id === best.id) as CatalogForm;\n const model = models[best.id] as SeparableModel<number>;\n const held = heldOutSeparable(model, points.x, points.y, { groups, residual, ...weighted });\n const boot = bootstrapSeparable(model, points.x, points.y, {\n groups: bootstrapGroups,\n ...weighted,\n runs: options.runs ?? SEPARABLE_BOOTSTRAP_RUNS,\n seed: options.seed ?? 1,\n });\n if (boot === null) return err(`The form \"${winner.id}\" has no fit for the bootstrap.`);\n const least = leastCount(DEFAULT_LEVEL);\n if (boot.replicates.length < least) {\n return err(`The bootstrap gave ${boot.replicates.length} fits in ${boot.runs} runs. The level ${DEFAULT_LEVEL} needs ${least}.`);\n }\n const binding = options.binding ?? { variable: FORM_VARIABLE };\n const values = [...best.fit.coefficients, ...best.fit.shapes];\n const constants = constantIdsOf(winner).map((id, index) => ({ id: binding.constants?.[id] ?? id, value: values[index] as number }));\n const losers: Loser[] = ranks\n .slice(1)\n .filter((rank) => rank.missing === 0 && rank.reason === undefined)\n .map((rank) => ({ form: rank.form, error: rank.error }));\n const method =\n `separable least squares: ${Object.keys(models).length} forms ranked by the rmse of the held-out residuals of ${groupCount} groups, ` +\n `${boot.replicates.length} fits in ${boot.runs} bootstrap runs of ${bootstrapCount} whole groups (seed ${boot.seed})`;\n return ok({\n form: formOf(winner, binding),\n constants,\n replicates: boot.replicates,\n fit: { method, residual, residuals: held.residuals, losers },\n ranks,\n });\n};\n","import { err, ok, type Result } from \"@mark1russell7/optional\";\nimport { convertible, isQuantity, type Quantity, valueIn, whyNotConvertible } from \"@mark1russell7/quantity\";\nimport type { Expr } from \"@mark1russell7/vex\";\nimport { DEFAULT_LEVEL, leastCount, type Law, type LawProblem, type Variable } from \"./law.ts\";\nimport { recordOf, valuesAt } from \"./program.ts\";\nimport { intervalOf, levelProblem, type LevelOptions, type LoadPoint, type Range } from \"./value.ts\";\n\n/** This number is the count of steps of the grid of a knee search when the options give none. */\nexport const KNEE_STEPS = 64;\n\n/** This number is the largest count of steps of the grid of a knee search. It sets a limit on the work of one search. */\nexport const MAX_STEPS = 4096;\n\n/**\n * A knee rule tells where a law leaves its cheap region.\n *\n * - `rise`: the value is more than `1 + share` times the value at the start of the search.\n * - `slope`: the slope is more than `factor` times the slope at the start of the search.\n * - `floor`: the value is more than `1 + share` times the floor of the row. The floor of a row is its\n * least value on the grid of the search, before its edge. The search of a row starts at its floor.\n */\nexport type KneeRule =\n | { readonly kind: \"rise\"; readonly share: number }\n | { readonly kind: \"slope\"; readonly factor: number }\n | { readonly kind: \"floor\"; readonly share: number };\n\n/** The floor of a law is its least value with its constants on the grid of a search, and the load of that value. */\nexport interface Floor {\n readonly load: number;\n readonly value: number;\n}\n\n/**\n * These options set a knee search. The search goes along one variable, from `from` to `to`, on a\n * grid of `steps` steps. The point `at` gives the value of each other variable of the law.\n *\n * The search goes from the minimum to the maximum of the variable, on 64 steps, when the options\n * give no value. The level of the intervals is 0.95 when the options give none.\n */\nexport interface KneeOptions extends LevelOptions {\n readonly at?: LoadPoint;\n readonly from?: number;\n readonly to?: number;\n readonly steps?: number;\n}\n\n/** An open range goes from `low` to `high`. A null end is past the end of the search. */\nexport interface OpenRange {\n readonly low: number | null;\n readonly high: number | null;\n}\n\n/**\n * A crossing is a load on the variable of a search, with the interval of its replicates. A null\n * value tells that the crossing is not in the search. The flag `outside` tells that the value is\n * outside the range of the variable. Then the value is an extrapolation.\n */\nexport interface Crossing {\n readonly value: number | null;\n readonly interval: OpenRange;\n readonly outside: boolean;\n}\n\n/**\n * A knee is the result of a knee search along one variable of a law, in the unit of the variable.\n *\n * The `knee` is the first load where the law obeys the rule: there the law leaves its cheap region.\n * The `edge` is the first load where the law has no finite value. This is a pole, where the value\n * grows with no limit, or the start of a region with no value. The knee is always before the edge.\n * The list `outside` names each other variable whose value is outside its range. Only a knee of the\n * rule `floor` has the fields `floor` and `noFloor`.\n */\nexport interface Knee {\n readonly variable: string;\n readonly unit: string;\n readonly rule: KneeRule;\n readonly level: number;\n readonly search: Range;\n readonly knee: Crossing;\n readonly edge: Crossing;\n readonly outside: readonly string[];\n /** This floor is the floor of the law with its constants. */\n readonly floor?: Floor;\n /** This number is the count of replicates with no floor above 0. The rule cannot apply to them, thus the interval of the knee leaves them out. */\n readonly noFloor?: number;\n}\n\n/** A curve gives the value of one row of a law or of a composition at each load. A load with no finite value gives undefined. */\nexport type Curve = (loads: readonly number[]) => readonly (number | undefined)[];\n\n/** This number sets the farthest distance from a peak where the pole test reads the size of the law. It is a share of the width of the bracket. */\nconst NEAR = 1e-6;\n\n/** Each distance of the pole test is this share of the distance before it. */\nconst CLOSER = 1e-3;\n\n/** At a pole, the gain of size in the second step nearer is at least this share of the gain in the first step. */\nconst POLE_GAIN = 0.9;\n\n/** A gain of size less than this share of the size is the noise of the floats, not a pole. */\nconst NOISE = 1e-9;\n\n/** The step of a difference quotient, for each unit of the load. */\nconst STEP = 1e-7;\n\n/** The most rounds of a bisection or of a golden-section search. Each search stops before, when its bracket has no middle. */\nconst ROUNDS = 400;\n\nconst INVERSE_PHI = (Math.sqrt(5) - 1) / 2;\n\nconst problem = (code: LawProblem[\"code\"], path: string, message: string): LawProblem => ({ code, path, message });\n\n/** This function gives the value of a curve at one load. */\nconst valueOf = (curve: Curve, load: number): number | undefined => curve([load])[0];\n\n/**\n * This function gives the load where a test changes from false to true, with a bisection. The test\n * is false at `low` and true at `high`. The function gives the end of the last bracket where the test is true.\n */\nconst crossingOf = (test: (load: number) => boolean, low: number, high: number): number => {\n let [a, b] = [low, high];\n for (let round = 0; round < ROUNDS; round += 1) {\n const middle = a + (b - a) / 2;\n if (middle <= a || middle >= b) break;\n if (test(middle)) b = middle;\n else a = middle;\n }\n return b;\n};\n\n/** This function gives the load of the largest size in a bracket, with a golden-section search. */\nconst peakOf = (size: (load: number) => number, low: number, high: number): number => {\n let [a, b] = [low, high];\n let c = b - INVERSE_PHI * (b - a);\n let d = a + INVERSE_PHI * (b - a);\n let [sizeC, sizeD] = [size(c), size(d)];\n for (let round = 0; round < ROUNDS && a < c && c < d && d < b; round += 1) {\n if (sizeC >= sizeD) {\n [b, d, sizeD] = [d, c, sizeC];\n c = b - INVERSE_PHI * (b - a);\n sizeC = size(c);\n } else {\n [a, c, sizeC] = [c, d, sizeD];\n d = a + INVERSE_PHI * (b - a);\n sizeD = size(d);\n }\n }\n return sizeC >= sizeD ? c : d;\n};\n\n/**\n * This function tells if the size of a law grows with no bound near the top of a peak. It reads the\n * size at three distances from the top, each 1000 times nearer than the distance before it.\n *\n * At a pole, each step nearer adds as much size as the step before, or more. A power pole adds more,\n * and a logarithm pole adds the same. Near a finite peak, the second step adds about a millionth of\n * the first. A load with no value at one of the distances is an edge near the top.\n */\nconst diverges = (size: (load: number) => number, top: number, near: number): boolean => {\n const sizeAt = (distance: number): number => Math.max(size(top - distance), size(top + distance));\n const [far, middle, close] = [near, near * CLOSER, near * CLOSER * CLOSER].map(sizeAt) as [number, number, number];\n if (!Number.isFinite(close) || !Number.isFinite(middle) || !Number.isFinite(far)) return true;\n const first = middle - far;\n return first > NOISE * middle && close - middle >= POLE_GAIN * first;\n};\n\n/**\n * This function gives the edge of one row of a law: the first load of the grid where the law has\n * no finite value. It gives Infinity when the law has a finite value on all of the grid.\n *\n * The size of a law at a load is the distance of its value from the start value. A load with no\n * value has an infinite size. The search examines each peak of the size on the grid, in order. A\n * golden-section search finds the top of the peak, and the pole test examines it. A peak with no\n * value at its top starts a region with no value.\n */\nconst edgeOf = (curve: Curve, grid: readonly number[], values: readonly (number | undefined)[], start: number): number => {\n const sizeOf = (value: number | undefined): number => (value === undefined ? Infinity : Math.abs(value - start));\n const size = (load: number): number => sizeOf(valueOf(curve, load));\n const noValue = (load: number): boolean => valueOf(curve, load) === undefined;\n const sizes = values.map(sizeOf);\n const last = grid.length - 1;\n for (let index = 1; index <= last; index += 1) {\n const here = sizes[index] as number;\n const missing = values[index] === undefined;\n const peak = here > (sizes[index - 1] as number) && (index === last || missing || here >= (sizes[index + 1] as number));\n if (!peak) continue;\n const low = grid[index - 1] as number;\n const high = grid[missing ? index : Math.min(index + 1, last)] as number;\n const top = peakOf(size, low, high);\n if (noValue(top)) return crossingOf(noValue, low, top);\n if (diverges(size, top, NEAR * (high - low))) return top;\n if (missing) return crossingOf(noValue, low, grid[index] as number);\n }\n return Infinity;\n};\n\n/** This function gives the step of a difference quotient at a load. The unit is the width of the search on a linear scale, and 0 on a log scale. */\nconst stepAt = (load: number, unit: number): number => STEP * Math.max(Math.abs(load), unit);\n\n/**\n * A test tells if the law passes a mark at one load. The value at the load is optional: without\n * it, the test reads the curve. A load with no finite value does not pass.\n */\nexport type Test = (load: number, value?: number) => boolean;\n\n/**\n * The context of the test of one row: its curve, its start value, its path, its start load and its\n * step unit. It also has the grid, the values of the row on the grid and the edge of the row.\n */\nexport interface TestContext {\n readonly curve: Curve;\n readonly start: number;\n readonly path: string;\n readonly from: number;\n readonly unit: number;\n readonly grid: readonly number[];\n readonly values: readonly (number | undefined)[];\n readonly edge: number;\n}\n\n/**\n * A test maker gives the test of one row, or the problem that stops the test at the start of the\n * search. An undefined test tells that the rule cannot apply to the row. Then the row has no crossing.\n */\nexport type TestOf = (context: TestContext) => Result<Test | undefined, LawProblem>;\n\n/**\n * This function gives the first load before the edge where the test holds. It gives Infinity when\n * the test does not hold before the edge or the end of the grid.\n *\n * The search tests the loads of the grid before the edge, and one load near the edge. A bisection\n * then finds the load between the last load that fails the test and the first load that passes it.\n */\nconst firstHolds = (holds: Test, grid: readonly number[], values: readonly (number | undefined)[], edge: number): number => {\n const loads = grid.map((load, index) => ({ load, value: values[index] })).filter(({ load }) => load < edge);\n if (Number.isFinite(edge)) {\n const before = loads.at(-1)?.load ?? (grid[0] as number);\n loads.push({ load: edge - NEAR * (edge - before), value: undefined });\n }\n let previous: number | undefined;\n for (const { load, value } of loads) {\n if (holds(load, value)) return previous === undefined ? load : crossingOf((x) => holds(x), previous, load);\n previous = load;\n }\n return Infinity;\n};\n\n/** The crossing and the edge of one row of a law. An undefined crossing tells that the rule cannot apply to the row. */\nexport interface RowResult {\n readonly crossing: number | undefined;\n readonly edge: number;\n}\n\n/** This function gives the first load where one row passes its test, and the edge of the row. The text `what` names the owner of the row in a problem. */\nexport const rowOf = (\n curve: Curve,\n path: string,\n testOf: TestOf,\n grid: readonly number[],\n unit: number,\n what = \"law\",\n): Result<RowResult, LawProblem> => {\n const values = curve(grid);\n const start = values[0];\n const from = grid[0] as number;\n if (start === undefined) return err(problem(\"value\", path, `The ${what} has no value at the start of the search, ${from}.`));\n const edge = edgeOf(curve, grid, values, start);\n const test = testOf({ curve, start, path, from, unit, grid, values, edge });\n if (test.tag === \"err\") return test;\n return ok({ crossing: test.value === undefined ? undefined : firstHolds(test.value, grid, values, edge), edge });\n};\n\n/** This function gives the test of a knee rule: the value or the slope is above its mark from the start of the search. */\nconst ruleTest =\n (rule: Exclude<KneeRule, { readonly kind: \"floor\" }>): TestOf =>\n ({ curve, start, path, from, unit }) => {\n if (rule.kind === \"rise\") {\n if (!(start > 0)) {\n return err(problem(\"knee\", path, `The rule \"rise\" needs a value above 0 at the start of the search. The value is ${start}.`));\n }\n const limit = (1 + rule.share) * start;\n return ok((load, value = valueOf(curve, load)) => value !== undefined && value > limit);\n }\n const slopeAt = (load: number, value: number | undefined): number | undefined => {\n const step = stepAt(load, unit);\n const before = valueOf(curve, load - step);\n return value === undefined || before === undefined ? undefined : (value - before) / step;\n };\n const step = stepAt(from, unit);\n const after = valueOf(curve, from + step);\n const first = after === undefined ? undefined : (after - start) / step;\n if (first === undefined || !(first > 0)) {\n return err(problem(\"knee\", path, `The rule \"slope\" needs a slope above 0 at the start of the search. The slope is ${String(first)}.`));\n }\n const limit = rule.factor * first;\n return ok((load, value) => {\n const slope = slopeAt(load, value ?? valueOf(curve, load));\n return slope !== undefined && slope > limit;\n });\n };\n\n/** This function gives the test of an amount: the value is above the amount. */\nexport const amountTest =\n (amount: number): TestOf =>\n ({ curve }) =>\n ok((load, value = valueOf(curve, load)) => value !== undefined && value > amount);\n\n/** These kinds name the knee rules. */\nconst KNEE_KINDS: readonly KneeRule[\"kind\"][] = [\"rise\", \"slope\", \"floor\"];\n\n/**\n * This function gives the problem of a knee rule, or undefined for a correct rule. The rule can come\n * from data, thus the function also examines its shape. The path of a problem starts with `path`.\n */\nexport const kneeRuleProblem = (rule: unknown, path = \"rule\"): LawProblem | undefined => {\n if (typeof rule !== \"object\" || rule === null || Array.isArray(rule)) return problem(\"knee\", path, \"The rule is not a record.\");\n const { kind, share, factor } = rule as Readonly<Record<string, unknown>>;\n if (kind === \"rise\" || kind === \"floor\") {\n if (typeof share === \"number\" && Number.isFinite(share) && share > 0) return undefined;\n return problem(\"knee\", `${path}.share`, `The share of the rule \"${kind}\" is ${String(share)}. It must be a finite number above 0.`);\n }\n if (kind === \"slope\") {\n if (typeof factor === \"number\" && Number.isFinite(factor) && factor > 1) return undefined;\n return problem(\"knee\", `${path}.factor`, `The factor of the rule \"slope\" is ${String(factor)}. It must be a finite number above 1.`);\n }\n return problem(\"knee\", `${path}.kind`, `The kind of the rule is ${JSON.stringify(kind) ?? \"undefined\"}. It must be one of ${KNEE_KINDS.join(\", \")}.`);\n};\n\n/** An open value is a value of a search with the interval of its replicates. A null value or end is past the end of the search. */\nexport interface OpenValue {\n readonly value: number | null;\n readonly interval: OpenRange;\n}\n\n/**\n * This function gives the open value of the values of the rows. The first value is the value of the\n * estimate. A value past `end` is past the end of the search, and an infinite value is too.\n */\nexport const openValueOf = (values: readonly number[], level: number, end: number): OpenValue => {\n // The quantiles interpolate. A large finite number keeps each interpolation finite, and each end past the search becomes null.\n const [value, ...spread] = values.map((entry) => (Number.isFinite(entry) ? entry : Number.MAX_VALUE));\n const interval = intervalOf(value as number, spread, level);\n const open = (entry: number): number | null => (entry > end ? null : entry);\n return { value: open(value as number), interval: { low: open(interval.low), high: open(interval.high) } };\n};\n\n/** This function gives the crossing of the values of the rows. The flag `outside` tells that the value is outside `range`. */\nconst crossingFrom = (values: readonly number[], level: number, range: Range, end: number): Crossing => {\n const found = openValueOf(values, level, end);\n return { ...found, outside: found.value !== null && (found.value < range.low || found.value > range.high) };\n};\n\n/**\n * A search is the setup of a search along one variable of a law. It holds the target variable, the level,\n * the range and the grid, and the variables outside their range. The function `curveOf` gives the curve\n * of one row of constants.\n */\ninterface Search {\n readonly target: Variable;\n readonly level: number;\n readonly search: Range;\n readonly grid: readonly number[];\n readonly unit: number;\n readonly curveOf: (values: readonly number[]) => Curve;\n readonly outside: readonly string[];\n}\n\n/**\n * The result of a search along one variable of a law: the first load that passes the test, and the\n * edge. The count `skipped` tells the replicates where the rule cannot apply. The crossing leaves them out.\n */\ninterface Along {\n readonly crossing: Crossing;\n readonly edge: Crossing;\n readonly skipped: number;\n}\n\n/**\n * This function gives the grid of a search from `from` to `to` in `steps` steps, or its problem. A\n * grid on the scale `log` starts above 0. The text `owner` names the variable of the search in a problem.\n */\nexport const searchGrid = (from: number, to: number, steps: number, log: boolean, owner: string): Result<readonly number[], LawProblem> => {\n if (!(Number.isFinite(from) && Number.isFinite(to) && from < to)) {\n return err(problem(\"range\", \"from\", `The search goes from ${from} to ${to}. It must go from a finite number to a larger finite number.`));\n }\n if (log && !(from > 0)) return err(problem(\"range\", \"from\", `${owner} has the scale \"log\", thus the search starts above 0.`));\n if (!(Number.isInteger(steps) && steps >= 2 && steps <= MAX_STEPS)) {\n return err(problem(\"knee\", \"steps\", `The search has ${steps} steps. It must have a whole number of steps from 2 to ${MAX_STEPS}.`));\n }\n return ok(\n Array.from({ length: steps + 1 }, (_, index) =>\n index === steps ? to : log ? from * (to / from) ** (index / steps) : from + ((to - from) * index) / steps,\n ),\n );\n};\n\n/**\n * This function gives the setup of a search along one variable of a law, or its problem. The function\n * `check` gives the problem of the test before the setup.\n */\nconst searchOf = (law: Law, variable: string, options: KneeOptions, check: () => LawProblem | undefined): Result<Search, LawProblem> => {\n const level = options.level ?? DEFAULT_LEVEL;\n const noLevel = levelProblem(law, level, false);\n if (noLevel !== undefined) return err(noLevel);\n const target = law.variables.find((entry) => entry.id === variable);\n if (target === undefined) return err(problem(\"point\", \"variable\", `The law has no variable \"${variable}\".`));\n const badTest = check();\n if (badTest !== undefined) return err(badTest);\n\n const at = options.at ?? {};\n for (const name of Object.keys(at)) {\n if (name === variable) return err(problem(\"point\", `at.${name}`, `The point \"at\" gives \"${name}\", the variable of the search.`));\n if (!law.variables.some((entry) => entry.id === name)) return err(problem(\"point\", `at.${name}`, `The law has no variable \"${name}\".`));\n }\n const base: Record<string, number> = {};\n for (const other of law.variables) {\n if (other.id === variable) continue;\n const value = at[other.id];\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n return err(problem(\"point\", `at.${other.id}`, `The point \"at\" gives no finite value for the variable \"${other.id}\".`));\n }\n base[other.id] = value;\n }\n\n const from = options.from ?? target.min;\n const to = options.to ?? target.max;\n const log = target.scale === \"log\";\n const grid = searchGrid(from, to, options.steps ?? KNEE_STEPS, log, `The variable \"${variable}\"`);\n if (grid.tag === \"err\") return grid;\n const names = law.constants.map((constant) => constant.id);\n const program: Expr = law.form.program;\n const curveOf =\n (values: readonly number[]): Curve =>\n (loads) =>\n valuesAt(program, loads.map((load) => recordOf(names, values, { ...base, [variable]: load })));\n const outside = law.variables\n .filter((entry) => entry.id !== variable && ((base[entry.id] as number) < entry.min || (base[entry.id] as number) > entry.max))\n .map((entry) => entry.id);\n return ok({ target, level, search: { low: from, high: to }, grid: grid.value, unit: log ? 0 : to - from, curveOf, outside });\n};\n\n/** This function searches a law for the first load that passes a test, in the constants and in each replicate. */\nconst along = (law: Law, setup: Search, testOf: TestOf): Result<Along, LawProblem> => {\n const rows = [\n { path: \"constants\", values: law.constants.map((constant) => constant.value) },\n ...law.replicates.map((row, index) => ({ path: `replicates[${index}]`, values: row })),\n ];\n const crossings: number[] = [];\n const edges: number[] = [];\n let skipped = 0;\n for (const row of rows) {\n const result = rowOf(setup.curveOf(row.values), row.path, testOf, setup.grid, setup.unit);\n if (result.tag === \"err\") return result;\n edges.push(result.value.edge);\n const { crossing } = result.value;\n if (crossing === undefined) {\n // The first crossing is the crossing of the estimate. Thus the rule must apply to the constants.\n if (row.path === \"constants\") return err(problem(\"knee\", row.path, \"The rule cannot apply to the constants of the law.\"));\n skipped += 1;\n } else {\n crossings.push(crossing);\n }\n }\n const range: Range = { low: setup.target.min, high: setup.target.max };\n return ok({\n crossing: crossingFrom(crossings, setup.level, range, setup.search.high),\n edge: crossingFrom(edges, setup.level, range, setup.search.high),\n skipped,\n });\n};\n\n/** This function gives the floor of one row: its least value on the grid, at the loads before its edge. */\nconst rowFloor = (grid: readonly number[], values: readonly (number | undefined)[], edge: number, start: number): Floor => {\n let floor: Floor = { load: grid[0] as number, value: start };\n grid.forEach((load, index) => {\n const value = values[index];\n if (load < edge && value !== undefined && value < floor.value) floor = { load, value };\n });\n return floor;\n};\n\n/**\n * This function gives the floor of a law on the grid of a search. The floor is the least value of the\n * law with its constants, at the loads before its edge. The rule `floor` needs a floor above 0.\n */\nconst floorOf = (law: Law, setup: Search): Result<Floor, LawProblem> => {\n const curve = setup.curveOf(law.constants.map((constant) => constant.value));\n const values = curve(setup.grid);\n const start = values[0];\n if (start === undefined) return err(problem(\"value\", \"constants\", `The law has no value at the start of the search, ${setup.grid[0]}.`));\n const floor = rowFloor(setup.grid, values, edgeOf(curve, setup.grid, values, start), start);\n if (!(floor.value > 0)) {\n return err(problem(\"knee\", \"constants\", `The rule \"floor\" needs a floor above 0. The floor is ${floor.value} at ${floor.load}.`));\n }\n return ok(floor);\n};\n\n/**\n * This function gives the test of the rule `floor` for one row. From the load of the floor of the\n * row, the value is above `1 + share` times that floor. A row with no floor above 0 has no test.\n */\nconst floorTest =\n (share: number): TestOf =>\n ({ curve, start, grid, values, edge }) => {\n const floor = rowFloor(grid, values, edge, start);\n if (!(floor.value > 0)) return ok(undefined);\n const limit = (1 + share) * floor.value;\n return ok((load, value = valueOf(curve, load)) => load >= floor.load && value !== undefined && value > limit);\n };\n\n/**\n * This function gives the largest count of replicates that a knee interval can leave out. The count is\n * at most the replicates of one tail of the level, and at least `leastCount` replicates stay.\n */\nconst mostSkipped = (replicates: number, level: number): number =>\n Math.min(Math.floor((replicates * (1 - level)) / 2 + 1e-9), replicates - leastCount(level));\n\n/**\n * This function gives the knee of a law along one variable, with an interval. It also gives the\n * edge: the first load where the law has no finite value.\n *\n * The point `at` of the options gives each other variable of the law. The function evaluates the\n * law with its constants, then with each replicate. The interval of the knee and of the edge is the\n * share `level` of the values of the replicates, made wider to hold the value.\n *\n * The search tests a grid of loads, then a bisection finds each crossing. A crossing between two\n * loads of the grid is found. Two edges in one step of the grid can hide the first edge.\n *\n * The rule `floor` gives each row its own floor. Thus the knee of a row is always after its floor,\n * and the uncertainty of the floor is in the interval. A replicate with no floor above 0 has no knee:\n * the field `noFloor` counts these replicates, and the interval leaves them out. When they are more\n * than one tail of the level, the function gives a problem.\n *\n * The function gives a problem for a variable or a point that the law cannot read. A bad search\n * range, rule or count of steps, and a level that the law cannot show, also give a problem. The last\n * problems are a law with no value at the start of the search, and a rule that cannot apply there.\n */\nexport const lawKnee = (law: Law, variable: string, rule: KneeRule, options: KneeOptions = {}): Result<Knee, LawProblem> => {\n const setup = searchOf(law, variable, options, () => kneeRuleProblem(rule));\n if (setup.tag === \"err\") return setup;\n let floor: Floor | undefined;\n if (rule.kind === \"floor\") {\n const least = floorOf(law, setup.value);\n if (least.tag === \"err\") return least;\n floor = least.value;\n }\n const found = along(law, setup.value, rule.kind === \"floor\" ? floorTest(rule.share) : ruleTest(rule));\n if (found.tag === \"err\") return found;\n const { target, level, search, outside } = setup.value;\n const knee: Knee = { variable, unit: target.unit, rule, level, search, knee: found.value.crossing, edge: found.value.edge, outside };\n if (floor === undefined) return ok(knee);\n const { skipped } = found.value;\n const most = mostSkipped(law.replicates.length, level);\n if (skipped > most) {\n const message = `The rule \"floor\" needs a floor above 0. ${skipped} of ${law.replicates.length} replicates have a floor of 0 or less. The interval of the level ${level} can leave out at most ${most}.`;\n return err(problem(\"knee\", \"replicates\", message));\n }\n return ok({ ...knee, floor, noFloor: skipped });\n};\n\n/**\n * A reach is the result of a search along one variable for the first load where a law is above an\n * amount. The loads are in the unit of the variable. Before the `crossing`, the law holds the amount.\n *\n * Thus for a law that grows along the variable, the crossing is the largest load that holds the\n * amount. The `edge` and the list `outside` are as in a knee.\n */\nexport interface Reach {\n readonly variable: string;\n readonly unit: string;\n /** This amount is the amount of the search, in the unit of the measure of the law. */\n readonly amount: number;\n readonly level: number;\n readonly search: Range;\n readonly crossing: Crossing;\n readonly edge: Crossing;\n readonly outside: readonly string[];\n}\n\n/**\n * This function gives the first load along one variable where a law is above an amount, with an\n * interval. This is the inverse query of one law: the largest load that one limit holds.\n *\n * The options are the options of `lawKnee`. When the law is above the amount at the start of the\n * search, the crossing is the start. When the law holds the amount on all of the search, the\n * crossing is null. A pole is above each amount, so the crossing is before the pole.\n *\n * The function gives each problem of `lawKnee` that is not about a rule. An amount that is not finite\n * gives a problem. An amount that does not convert to the unit of the measure also gives a problem.\n */\nexport const lawReach = (law: Law, variable: string, amount: Quantity, options: KneeOptions = {}): Result<Reach, LawProblem> => {\n if (!isQuantity(amount) || !Number.isFinite(amount.value)) {\n return err(problem(\"value\", \"amount\", \"The amount is not a finite quantity.\"));\n }\n if (!convertible(amount.unit, law.measure.unit)) {\n const why = whyNotConvertible(amount.unit, law.measure.unit) ?? \"the units are different\";\n return err(problem(\"unit\", \"amount\", `The amount is in \"${amount.unit}\", and the measure of the law is in \"${law.measure.unit}\": ${why}.`));\n }\n const value = valueIn(amount, law.measure.unit);\n const setup = searchOf(law, variable, options, () => undefined);\n if (setup.tag === \"err\") return setup;\n const found = along(law, setup.value, amountTest(value));\n if (found.tag === \"err\") return found;\n const { target, level, search, outside } = setup.value;\n return ok({ variable, unit: target.unit, amount: value, level, search, crossing: found.value.crossing, edge: found.value.edge, outside });\n};\n","import { err, ok, type Result } from \"@mark1russell7/optional\";\nimport { gateOf, type Gate, type GateCaseOutcome, type LimitOutcome } from \"@mark1russell7/rigor-bench\";\nimport { binomialTest, holm, partialConjunction } from \"@mark1russell7/rigor-statistics\";\nimport { DEFAULT_LEVEL, type Law, type LawProblem } from \"./law.ts\";\nimport { lawValue, type LevelOptions, type LoadPoint, type Range } from \"./value.ts\";\n\n/** This level is the level of the family of tests of a gate. It is the chance of one false block or more in one run of the gate. */\nexport const GATE_ALPHA = 0.01;\n\n/**\n * This count is the jobs that each must show the same side before the gate blocks. One job on a slow runner\n * cannot block alone. It is the default of `jobs` of `notSlowerVerdict` of `@mark1russell7/rigor-bench`.\n */\nexport const GATE_JOBS = 2;\n\n/** The side of a measured value against the run range of its law. */\nexport type ReadSide = \"within\" | \"high\" | \"low\";\n\n/** A law read tells where one measured value falls against the run range of its law at one load point. */\nexport interface LawRead {\n readonly value: number;\n /** This range is the range `run` of `lawValue`: where one measured run falls. */\n readonly run: Range;\n readonly side: ReadSide;\n}\n\nconst problem = (code: LawProblem[\"code\"], path: string, message: string): LawProblem => ({ code, path, message });\n\n/**\n * This function tells where one measured value falls against the run range of a law at a load point. The range is\n * the range `run` of `lawValue`. A value above the range is `high`, and a value below it is `low`.\n *\n * The function gives a problem for a point outside the range of a variable, because there the law has no value to\n * compare. It also gives each problem of `lawValue`, and a problem for a value that is not finite.\n */\nexport const lawRead = (law: Law, point: LoadPoint, value: number, options: LevelOptions = {}): Result<LawRead, LawProblem> => {\n if (!Number.isFinite(value)) return err(problem(\"value\", \"value\", `The measured value ${value} is not finite.`));\n const found = lawValue(law, point, options);\n if (found.tag === \"err\") return found;\n const [outside] = found.value.outside;\n if (outside !== undefined) {\n const variable = law.variables.find((each) => each.id === outside);\n const range = variable === undefined ? \"\" : ` from ${variable.min} to ${variable.max}`;\n return err(problem(\"point\", outside, `The point is outside the range of the variable \"${outside}\"${range}. The law has no value there to compare.`));\n }\n const { run } = found.value;\n return ok({ value, run, side: value > run.high ? \"high\" : value < run.low ? \"low\" : \"within\" });\n};\n\n/** A gate read is one measured value of one job at one load point. */\nexport interface GateRead {\n readonly point: LoadPoint;\n readonly value: number;\n}\n\n/**\n * A gate job is the reads of one job for one law. A job with a reason in `noRead` gives no read, for example a job with a\n * noise floor over its limit. The caller gives only the reads in the conditions of the law.\n */\nexport interface GateJob {\n /** This name is the name of the job, for example the address of its CI run and its start. */\n readonly job: string;\n readonly reads: readonly GateRead[];\n readonly noRead?: string;\n /** These texts tell each read that the caller left out, for example a point that the law leaves out. The counts do not use them. */\n readonly unread?: readonly string[];\n}\n\n/** A gate case is one law and the jobs that measured its subject in its conditions. */\nexport interface GateCase {\n readonly law: Law;\n readonly jobs: readonly GateJob[];\n}\n\n/** These options set the level of the run range, the level of the family of tests and the count of jobs of a side. */\nexport interface LawGateOptions extends LevelOptions {\n /** This level is the level of the family of tests. The default is `GATE_ALPHA`. */\n readonly alpha?: number;\n /** This count is the jobs that each must show a side. The default is `GATE_JOBS`. */\n readonly jobs?: number;\n}\n\n/** A job count tells the reads of one job for one law, and the p of the count of each side. */\nexport interface JobCount {\n readonly job: string;\n /** This count is the reads in the range of the law. */\n readonly reads: number;\n readonly high: number;\n readonly low: number;\n /** This p is the p of the binomial test of the count `high`, with the chance of one side under the claim. */\n readonly pHigh: number;\n readonly pLow: number;\n /** These texts tell each read that the caller left out (`GateJob.unread`), and each read that the law cannot compare. */\n readonly unread: readonly string[];\n}\n\n/** A side test is the test of one side of one law over the jobs, after the Holm correction of the family. */\nexport interface SideTest {\n readonly side: \"high\" | \"low\";\n /** This p is the p of the claim \"`jobs` jobs or more show this side\" (`partialConjunction`). */\n readonly p: number;\n /** This p is the p after the Holm correction of the family. */\n readonly adjusted: number;\n readonly reject: boolean;\n}\n\n/** A job with no read tells the job and the reason. */\nexport interface NoReadJob {\n readonly job: string;\n readonly reason: string;\n}\n\n/** A law gate case is the outcome of one law, with the counts of each job and the test of each side. */\nexport interface LawGateCase extends GateCaseOutcome {\n /** This name is the id of the law. */\n readonly case: string;\n readonly outcome: LimitOutcome;\n /** This text tells the reason of the outcome, in one sentence. */\n readonly reason: string;\n readonly jobs: readonly JobCount[];\n readonly noRead: readonly NoReadJob[];\n /** These tests are the two sides, or an empty list for a case with too few jobs. */\n readonly sides: readonly SideTest[];\n}\n\n/** A law gate is the gate of `@mark1russell7/rigor-bench` over the laws, with the facts that it uses. */\nexport interface LawGate extends Gate {\n readonly level: number;\n readonly alpha: number;\n /** This count is the jobs that each must show a side. */\n readonly need: number;\n /** This chance is the chance of one side for one read of a job that agrees with its law: `(1 - level) / 2`. */\n readonly share: number;\n readonly cases: readonly LawGateCase[];\n}\n\n/** This function gives the text of a number with at most 3 significant digits. */\nconst short = (value: number): string => (Number.isInteger(value) ? String(value) : value.toPrecision(3));\n\n/** This function gives the counts of one job for one law, or the reason that the job gives no read. */\nconst countOf = (law: Law, job: GateJob, level: number, share: number): JobCount | NoReadJob => {\n if (job.noRead !== undefined) return { job: job.job, reason: job.noRead };\n let high = 0;\n let low = 0;\n let reads = 0;\n const unread: string[] = [...(job.unread ?? [])];\n for (const each of job.reads) {\n const found = lawRead(law, each.point, each.value, { level });\n if (found.tag === \"err\") {\n unread.push(`${JSON.stringify(each.point)}: ${found.error.message}`);\n continue;\n }\n reads += 1;\n if (found.value.side === \"high\") high += 1;\n if (found.value.side === \"low\") low += 1;\n }\n if (reads === 0) return { job: job.job, reason: `The job has no read in the range of the law. ${unread[0] ?? \"The job has no read.\"}` };\n return { job: job.job, reads, high, low, pHigh: binomialTest(high, reads, share, \"greater\"), pLow: binomialTest(low, reads, share, \"greater\"), unread };\n};\n\n/** The counts of one case before the family test. */\ninterface Counted {\n readonly law: Law;\n readonly jobs: readonly JobCount[];\n readonly noRead: readonly NoReadJob[];\n}\n\n/**\n * This function gives the gate of some laws. For each law, it tells if the measured values of the jobs stay in the run\n * range of the law. It is the rule of a gate of the laws of a subject, for example on a pull request.\n *\n * - **A read:** each value of a job falls `within`, `high` or `low` against the run range of its law (`lawRead`).\n * A read of a job that agrees with its law falls on one side with a chance of `share`, `(1 - level) / 2`, or less.\n * - **A job:** for each side, the binomial test of the count of reads on that side gives the p of the job.\n * A job with `noRead`, or with no read in the range of the law, gives no read.\n * - **A side:** `partialConjunction` joins the p of the jobs for the claim \"`jobs` jobs or more show this side\". Thus one\n * job on an odd runner cannot block alone. The claim has no condition on how the reads of one job depend on each other.\n * - **The family:** `holm` corrects the tests of the two sides of each law at the level `alpha`. A rejected side makes the\n * case `beyond`. A low side is a block too: the law is no longer the law of the subject, and a new fit must replace it.\n * - **No read:** a case with fewer than `jobs` jobs that read is `cannot decide`. So is a case whose reads are too few to\n * reject a side, also with each read on that side. The gate of `@mark1russell7/rigor-bench` (`gateOf`) joins the cases.\n * A gate with no case, or with a case that cannot decide and no block, is \"no read\". It does not pass.\n *\n * The function throws a `RangeError` for a level, an alpha or a count of jobs that is not valid.\n */\nexport const lawGate = (cases: readonly GateCase[], options: LawGateOptions = {}): LawGate => {\n const level = options.level ?? DEFAULT_LEVEL;\n const alpha = options.alpha ?? GATE_ALPHA;\n const need = options.jobs ?? GATE_JOBS;\n if (!(level > 0 && level < 1)) throw new RangeError(`The level ${level} is not between 0 and 1.`);\n if (!(alpha > 0 && alpha < 1)) throw new RangeError(`The alpha ${alpha} is not between 0 and 1.`);\n if (!Number.isInteger(need) || need < 1) throw new RangeError(`The count of jobs ${need} is not a whole number above 0.`);\n const share = (1 - level) / 2;\n\n const counted: Counted[] = cases.map(({ law, jobs }) => {\n const found = jobs.map((job) => countOf(law, job, level, share));\n return { law, jobs: found.filter((each): each is JobCount => \"reads\" in each), noRead: found.filter((each): each is NoReadJob => \"reason\" in each) };\n });\n const decidable = counted.filter((each) => each.jobs.length >= need);\n const tests = decidable.length * 2;\n const pOf = (jobs: readonly JobCount[], side: \"high\" | \"low\"): number => partialConjunction(jobs.map((job) => (side === \"high\" ? job.pHigh : job.pLow)), need);\n const corrected = holm(\n decidable.flatMap((each) => [pOf(each.jobs, \"high\"), pOf(each.jobs, \"low\")]),\n alpha,\n );\n\n let next = 0;\n const outcomes: LawGateCase[] = counted.map(({ law, jobs, noRead }) => {\n const base = { case: law.id, jobs, noRead };\n if (jobs.length < need) {\n const reason = `${jobs.length} jobs read the law. The gate needs ${need} jobs or more.${noRead.length > 0 ? ` ${noRead[0]!.reason}` : \"\"}`;\n return { ...base, outcome: \"cannot decide\", reason, sides: [] };\n }\n const sides: SideTest[] = ([\"high\", \"low\"] as const).map((side) => {\n const test = corrected[next];\n next += 1;\n return { side, p: test?.p ?? 1, adjusted: test?.adjusted ?? 1, reject: test?.reject ?? false };\n });\n // The best p of a side is the p with each read on that side. Above the first step of Holm, no count can reject the side.\n const best = partialConjunction(jobs.map((job) => binomialTest(job.reads, job.reads, share, \"greater\")), need);\n const reads = jobs.reduce((sum, job) => sum + job.reads, 0);\n const high = jobs.reduce((sum, job) => sum + job.high, 0);\n const low = jobs.reduce((sum, job) => sum + job.low, 0);\n const counts = `${high} of ${reads} reads in ${jobs.length} jobs are above the run range and ${low} are below`;\n const rejected = sides.find((side) => side.reject);\n if (rejected !== undefined) {\n const what = rejected.side === \"high\" ? \"The measure is above its law\" : \"The measure is below its law: the law is out of date, and a new fit must replace it\";\n return { ...base, outcome: \"beyond\", reason: `${what}. ${counts}. The adjusted p is ${short(rejected.adjusted)}, below ${alpha}.`, sides };\n }\n if (best > alpha / tests) {\n const reason = `The reads are too few to reject a side: with each read on one side, the p is ${short(best)}, above ${short(alpha / tests)}.`;\n return { ...base, outcome: \"cannot decide\", reason, sides };\n }\n return { ...base, outcome: \"within\", reason: `${counts}, as the chance ${short(share)} of each side gives.`, sides };\n });\n return { ...gateOf(outcomes), level, alpha, need, share, cases: outcomes };\n};\n\n/** This count is the most reads in one job that `gateReadsFor` examines. */\nconst MAX_GATE_READS = 64;\n\n/**\n * This function gives the least count of reads in each job with which `lawGate` can decide a case. Let each job have r\n * reads, each on one side. The count is the least r for which `jobs` jobs give a p of `alpha / (2 × laws)` or less. This\n * bound is the first step of Holm when each of `laws` laws is a case of the gate.\n *\n * A job with fewer reads cannot reject a side, also when each of its reads is on that side. Thus a plan of a gate must\n * give each job this count of points that each law reads. More jobs do not correct too few reads in each job.\n *\n * The function throws a `RangeError` in three cases. The first is `jobs` or `laws` that is not a whole number above 0.\n * The second is `jobs` below the count of jobs of a side. The third is no count up to 64 reads that can decide.\n */\nexport const gateReadsFor = (jobs: number, laws: number, options: LawGateOptions = {}): number => {\n const level = options.level ?? DEFAULT_LEVEL;\n const alpha = options.alpha ?? GATE_ALPHA;\n const need = options.jobs ?? GATE_JOBS;\n if (!(level > 0 && level < 1)) throw new RangeError(`The level ${level} is not between 0 and 1.`);\n if (!(alpha > 0 && alpha < 1)) throw new RangeError(`The alpha ${alpha} is not between 0 and 1.`);\n if (!Number.isInteger(need) || need < 1) throw new RangeError(`The count of jobs ${need} is not a whole number above 0.`);\n if (!Number.isInteger(laws) || laws < 1) throw new RangeError(`The count of laws ${laws} is not a whole number above 0.`);\n if (!Number.isInteger(jobs) || jobs < need) throw new RangeError(`The count of jobs ${jobs} is not a whole number of ${need} or more.`);\n const share = (1 - level) / 2;\n for (let reads = 1; reads <= MAX_GATE_READS; reads += 1) {\n const best = partialConjunction(Array.from({ length: jobs }, () => binomialTest(reads, reads, share, \"greater\")), need);\n if (best <= alpha / (2 * laws)) return reads;\n }\n throw new RangeError(`At ${jobs} jobs and ${laws} laws, ${MAX_GATE_READS} reads in each job cannot decide a case.`);\n};\n","import { err, ok, type Result } from \"@mark1russell7/optional\";\nimport { quantity, valueIn, type Quantity } from \"@mark1russell7/quantity\";\nimport { mean } from \"@mark1russell7/rigor-statistics\";\nimport { metricsGaps } from \"./app-check.ts\";\nimport type { AppContract, AppProblem, AppSeries } from \"./app.ts\";\nimport { isUtc } from \"./names.ts\";\nimport type { Observation, ObservedClass } from \"./observe.ts\";\n\n/** A reading is one value of one series of an app at one time. `series` is the id of the series, and `at` is a UTC time. */\nexport interface SeriesReading {\n readonly series: string;\n readonly at: string;\n readonly value: number;\n}\n\n/** A window of the live metrics goes from `from` to `to`, two UTC times. Its `origin` names the place of the metrics. */\nexport interface MetricsWindow {\n readonly origin: string;\n readonly from: string;\n readonly to: string;\n}\n\n/**\n * This function gives the increase of a counter from its values in the order of their times. A value below\n * the value before it is a new start of the process. The counter starts again at 0, thus the increase adds\n * the whole value.\n */\nexport const counterIncrease = (values: readonly number[]): number =>\n values.reduce((total, value, index) => {\n if (index === 0) return total;\n const before = values[index - 1] ?? 0;\n return total + (value >= before ? value - before : value);\n }, 0);\n\n/** This function makes a problem of the readings of an app. */\nconst readingProblem = (path: string, message: string): AppProblem => ({ code: \"series\", path, message });\n\n/**\n * This function gives the observation of an app in a window. The observation has the count of the requests of\n * each class, the mean of each request variable and each level. It reads only the readings in the window.\n *\n * - The count of a class is the increase of its counter. A class with no request in the window is not in the observation.\n * - The mean of a request variable is the increase of the counter of its total, over the count of its class.\n * - A level is the mean of the readings of its gauge, with the same weight for each reading. Item CAP-63 adds a weight for the time of each reading.\n *\n * It gives a problem for each gap of the metrics of the app (`metricsGaps`). It also gives a problem for a\n * counter with fewer than 2 readings, and for a gauge with no reading. `observedWorkload` gives the workload\n * of the observation.\n */\nexport const observationOf = (app: AppContract, window: MetricsWindow, readings: readonly SeriesReading[]): Result<Observation, readonly AppProblem[]> => {\n const { origin, from, to } = window;\n if (!isUtc(from) || !isUtc(to) || !(Date.parse(from) < Date.parse(to))) {\n return err([readingProblem(\"window\", \"The window does not go from a UTC time to a later UTC time.\")]);\n }\n const problems: AppProblem[] = metricsGaps(app).map((gap) => readingProblem(\"metrics\", gap.message));\n const start = Date.parse(from);\n const end = Date.parse(to);\n\n /** This function gives the values of a series in the window, in the order of their times. */\n const valuesOf = (series: AppSeries): readonly number[] =>\n readings\n .filter((reading) => reading.series === series.id && isUtc(reading.at) && Date.parse(reading.at) >= start && Date.parse(reading.at) <= end)\n .sort((a, b) => Date.parse(a.at) - Date.parse(b.at))\n .map((reading) => reading.value)\n .filter((value) => Number.isFinite(value));\n\n /** This function gives the increase of a counter in the window, in the unit of the series, or a problem. */\n const increaseOf = (series: AppSeries): number | undefined => {\n const values = valuesOf(series);\n if (values.length >= 2) return counterIncrease(values);\n problems.push(readingProblem(`readings.${series.id}`, `The counter \"${series.id}\" has ${values.length} readings in the window. Its increase needs 2 or more.`));\n return undefined;\n };\n\n const classes: ObservedClass[] = [];\n for (const entry of app.classes) {\n const counter = app.metrics.find((series) => \"rate\" in series.of && series.of.rate === entry.id);\n if (counter === undefined) continue;\n const count = increaseOf(counter);\n if (count === undefined || count === 0) continue;\n const request: Record<string, Quantity> = {};\n for (const name of entry.request) {\n const total = app.metrics.find((series) => \"total\" in series.of && series.of.total === name && series.of.class === entry.id);\n const variable = app.variables.find((each) => each.id === name);\n if (total === undefined || variable === undefined) continue;\n const sum = increaseOf(total);\n if (sum !== undefined) request[name] = quantity(valueIn(quantity(sum, total.unit), variable.unit) / count, variable.unit);\n }\n classes.push({ id: entry.id, count: quantity(count, counter.unit), request });\n }\n\n const levels: Record<string, Quantity> = {};\n for (const variable of app.variables) {\n if (variable.kind !== \"level\") continue;\n const gauge = app.metrics.find((series) => \"level\" in series.of && series.of.level === variable.id);\n if (gauge === undefined) continue;\n const values = valuesOf(gauge);\n if (values.length === 0) {\n problems.push(readingProblem(`readings.${gauge.id}`, `The gauge \"${gauge.id}\" has no reading in the window.`));\n continue;\n }\n levels[variable.id] = quantity(valueIn(quantity(mean(values), gauge.unit), variable.unit), variable.unit);\n }\n return problems.length > 0 ? err(problems) : ok({ origin, from, to, classes, levels });\n};\n","import { err, ok, type Result } from \"@mark1russell7/optional\";\nimport { isCanonicalUnit, isQuantity, kindOf, quantity, type Quantity } from \"@mark1russell7/quantity\";\nimport { isUtc } from \"./names.ts\";\nimport { checkWorkload, workloadProblem } from \"./workload-check.ts\";\nimport { WORKLOAD_FORMAT, type Amounts, type Workload, type WorkloadClass, type WorkloadProblem } from \"./workload.ts\";\n\n/**\n * An observed class is the count of the requests of one class in a window of the live metrics, for\n * example `{ value: 1200, unit: \"{request}\" }`. Its `request` gives each variable of one request.\n */\nexport interface ObservedClass {\n readonly id: string;\n readonly count: Quantity;\n readonly request: Amounts;\n}\n\n/**\n * An observation is the live metrics of an app in one window, from `from` to `to`. Its `origin`\n * names the place of the metrics. Each level is the level in the window.\n */\nexport interface Observation {\n readonly origin: string;\n readonly from: string;\n readonly to: string;\n readonly classes: readonly ObservedClass[];\n readonly levels: Amounts;\n}\n\n/** A workload name is the id and the title of a workload. */\nexport interface WorkloadName {\n readonly id: string;\n readonly title: string;\n}\n\n/**\n * This function gives the workload of an observation. The rate of a class is its count, divided by\n * the seconds of the window. Thus the rate is the mean rate of the window. For the load at a peak,\n * give the window of the peak.\n *\n * It gives each problem of an observation that is not correct, and each problem of the workload.\n */\nexport const observedWorkload = (observation: Observation, name: WorkloadName): Result<Workload, readonly WorkloadProblem[]> => {\n const { origin, from, to } = observation;\n const seconds = isUtc(from) && isUtc(to) ? (Date.parse(to) - Date.parse(from)) / 1000 : Number.NaN;\n if (!(seconds > 0)) {\n return err([workloadProblem(\"source\", \"source\", \"The window does not go from a UTC time to a later UTC time.\")]);\n }\n\n const problems: WorkloadProblem[] = [];\n const classes: WorkloadClass[] = [];\n observation.classes.forEach((entry, index) => {\n const { count } = entry;\n const unit = isQuantity(count) && kindOf(count.unit) === \"count\" ? `${count.unit}/s` : undefined;\n if (unit === undefined || !isCanonicalUnit(unit) || kindOf(unit) !== \"frequency\" || count.value < 0) {\n problems.push(\n workloadProblem(\"rate\", `classes[${index}].count`, `The count of the class \"${entry.id}\" is not a count of 0 or more, for example in \"{request}\".`),\n );\n return;\n }\n classes.push({ id: entry.id, rate: quantity(count.value / seconds, unit), request: entry.request });\n });\n if (problems.length > 0) return err(problems);\n\n const workload: Workload = {\n format: WORKLOAD_FORMAT,\n id: name.id,\n title: name.title,\n classes,\n levels: observation.levels,\n source: { kind: \"metrics\", origin, from, to },\n };\n const found = checkWorkload(workload);\n return found.length > 0 ? err(found) : ok(workload);\n};\n","import { err, ok, type Result } from \"@mark1russell7/optional\";\nimport { convertible, isQuantity, scale, valueIn, whyNotConvertible, type Quantity } from \"@mark1russell7/quantity\";\nimport { limitProblem, limitProblems } from \"./instance-check.ts\";\nimport type { Instance, Limit, LimitProblem } from \"./instance.ts\";\nimport { finite, repeated } from \"./names.ts\";\nimport type { Amounts } from \"./workload.ts\";\n\n/**\n * A limit use tells how much of a limit one value of its measure takes. The `amount` is the amount\n * of the limit: its ceiling, less its headroom. The `use` is the value, divided by that amount.\n * The limit holds when the `use` is 1 or less.\n */\nexport interface LimitUse {\n /** This id is the id of the limit. */\n readonly limit: string;\n readonly measure: string;\n readonly value: Quantity;\n readonly amount: Quantity;\n readonly use: number;\n readonly holds: boolean;\n}\n\n/** This function gives the amount of a limit at the path `at`, or the problem that stops it. */\nconst amountAt = (limit: Limit, instance: Instance, at: string): Result<Quantity, LimitProblem> => {\n const bad = limitProblems(limit, at)[0];\n if (bad !== undefined) return err(bad);\n let ceiling: Quantity;\n if (limit.ceiling.kind === \"amount\") {\n ceiling = limit.ceiling.amount;\n } else {\n const name = limit.ceiling.resource;\n if (!Object.hasOwn(instance.resources, name)) {\n return err(limitProblem(\"resource\", `resources.${name}`, `The instance has no resource \"${name}\" for the limit \"${limit.id}\".`));\n }\n const resource: unknown = instance.resources[name];\n if (!isQuantity(resource) || !(resource.value > 0)) {\n return err(limitProblem(\"resource\", `resources.${name}`, `The resource \"${name}\" of the instance is not a finite amount above 0.`));\n }\n ceiling = resource;\n }\n const amount = scale(ceiling, 1 - limit.headroom);\n if (!(amount.value > 0) || !finite(amount.value)) {\n const field = at === \"\" ? \"ceiling\" : `${at}.ceiling`;\n return err(limitProblem(\"amount\", field, `The ceiling of the limit \"${limit.id}\", less its headroom, is not a finite amount above 0.`));\n }\n return ok(amount);\n};\n\n/** This function gives the use of a limit, with the path of the limit and the path of the value for a problem. */\nconst useAt = (limit: Limit, instance: Instance, value: Quantity, at: string, valuePath: string): Result<LimitUse, LimitProblem> => {\n const amount = amountAt(limit, instance, at);\n if (amount.tag === \"err\") return amount;\n if (!isQuantity(value) || value.value < 0) {\n return err(limitProblem(\"amount\", valuePath, `The value of the measure \"${limit.measure}\" is not a finite amount of 0 or more.`));\n }\n if (!convertible(value.unit, amount.value.unit)) {\n const why = whyNotConvertible(value.unit, amount.value.unit) ?? \"the units are different\";\n return err(\n limitProblem(\n \"unit\",\n valuePath,\n `The measure \"${limit.measure}\" is in \"${value.unit}\", and the ceiling of the limit \"${limit.id}\" is in \"${amount.value.unit}\": ${why}.`,\n ),\n );\n }\n const use = valueIn(value, amount.value.unit) / amount.value.value;\n if (!finite(use)) return err(limitProblem(\"amount\", valuePath, `The value of the measure \"${limit.measure}\" has no finite use.`));\n return ok({ limit: limit.id, measure: limit.measure, value, amount: amount.value, use, holds: use <= 1 });\n};\n\n/**\n * This function gives the amount of a limit on an instance: the ceiling, less the headroom. It is\n * the largest value of the measure that holds the limit, in the unit of the ceiling.\n *\n * It gives a problem for a limit that is not correct. It gives a problem for a ceiling that names\n * a resource when the instance does not have that resource.\n */\nexport const limitAmount = (limit: Limit, instance: Instance): Result<Quantity, LimitProblem> => amountAt(limit, instance, \"\");\n\n/**\n * This function gives the use of a limit on an instance by one value of its measure. The use is\n * the value, divided by the amount of the limit. Thus a use of 1 is exactly at the limit.\n *\n * It gives each problem of `limitAmount`. It gives a problem for a value that is not a finite\n * amount of 0 or more. It gives a problem for a value that does not convert to the unit of the ceiling.\n */\nexport const limitUse = (limit: Limit, instance: Instance, value: Quantity): Result<LimitUse, LimitProblem> =>\n useAt(limit, instance, value, \"\", \"value\");\n\n/**\n * This function gives the use of each limit on an instance. The `values` give the value of each\n * measure, by the id of the measure. The uses go from the largest to the smallest. Thus the first\n * use is the limit that binds.\n *\n * A limit with no value is a problem, and not a limit that holds. The function also gives a\n * problem for two limits with one id, and each problem of `limitUse`.\n */\nexport const limitUses = (limits: readonly Limit[], instance: Instance, values: Amounts): Result<readonly LimitUse[], LimitProblem> => {\n const twice = repeated(limits.map((limit) => limit.id));\n if (twice !== undefined) return err(limitProblem(\"id\", \"limits\", `Two limits have the id \"${twice}\".`));\n const uses: LimitUse[] = [];\n for (const [index, limit] of limits.entries()) {\n const at = `limits[${index}]`;\n if (!Object.hasOwn(values, limit.measure)) {\n return err(limitProblem(\"measure\", `${at}.measure`, `The values give no amount for the measure \"${limit.measure}\" of the limit \"${limit.id}\".`));\n }\n const use = useAt(limit, instance, values[limit.measure] as Quantity, at, `values.${limit.measure}`);\n if (use.tag === \"err\") return use;\n uses.push(use.value);\n }\n return ok(uses.sort((a, b) => b.use - a.use));\n};\n","import { err, ok, type Result } from \"@mark1russell7/optional\";\nimport { convertible, factorOf, whyNotConvertible } from \"@mark1russell7/quantity\";\nimport {\n flatPartsOf,\n partsOutside,\n preparedOf,\n rowValueOf,\n rowValuesOf,\n type Catalog,\n type Composition,\n type CompositionProblemCode,\n type FlatPart,\n type Prepared,\n} from \"./composition.ts\";\nimport { portionOf } from \"./demand.ts\";\nimport type { Instance, Limit, LimitProblemCode } from \"./instance.ts\";\nimport { MAX_STEPS, amountTest, openValueOf, rowOf, searchGrid, type Curve, type OpenValue } from \"./knee.ts\";\nimport { DEFAULT_LEVEL, type Problem } from \"./law.ts\";\nimport { limitAmount } from \"./limit.ts\";\nimport { repeated } from \"./names.ts\";\nimport type { LevelOptions, Range } from \"./value.ts\";\nimport { demandProblems } from \"./workload-check.ts\";\nimport type { Amounts, Demand } from \"./workload.ts\";\n\n/** This number is the largest count of instances of a scale search when the options give none: 2 to the power 20. */\nexport const SCALE_MOST: number = 2 ** 20;\n\n/** This number is the count of steps of the grid of a scale search when the options give none. */\nexport const SCALE_STEPS: number = 128;\n\n/**\n * A scale model holds what the scale queries of a service read: the resources of one instance, the\n * limits of the service and the compositions. Each limit reads the composition of its measure. The\n * catalog gives each law and each nested composition that the compositions name.\n */\nexport interface ScaleModel {\n readonly instance: Instance;\n readonly limits: readonly Limit[];\n /** Each composition gives one measure, by the id of its measure. The list can hold compositions that no limit reads. */\n readonly compositions: readonly Composition[];\n readonly catalog: Catalog;\n}\n\n/**\n * These options set a scale query. The field `given` gives the state of each instance, for example\n * its heap. A level in `whole` does not divide between the instances, as in `shareOf`.\n *\n * The count search goes up to `most` instances. The load search goes from `1 / most` to `most`\n * times the demand. Each search has a grid of `steps` steps on a log scale. The level of the\n * intervals is 0.95 when the options give none.\n */\nexport interface ScaleOptions extends LevelOptions {\n readonly given?: Amounts;\n readonly whole?: readonly string[];\n readonly most?: number;\n readonly steps?: number;\n}\n\n/** A scale problem code names the part of a scale model, or of a scale query, that is not correct. */\nexport type ScaleProblemCode = CompositionProblemCode | LimitProblemCode;\n\n/** A scale problem tells what is not correct, and where: `path` is the path of the field in the model or in the query. */\nexport type ScaleProblem = Problem<ScaleProblemCode>;\n\n/**\n * A limit count is the lowest count of instances that holds one limit at a load. Each larger count\n * also holds the limit. A null count is more than the largest count of the search.\n */\nexport interface LimitCount {\n readonly limit: string;\n readonly measure: string;\n readonly count: OpenValue;\n /** This number is the share of the replicates where this limit needs more instances than each other limit. */\n readonly binds: number;\n /** This flag tells that the composition has no value past the share of the estimate. Then the edge of the composition sets the count. */\n readonly edge: boolean;\n /** This flag tells that a law of the composition reads a variable outside its range at the count of the estimate. */\n readonly extrapolated: boolean;\n}\n\n/**\n * A limit reach is the first load where one limit breaks at a count of instances, as a factor of\n * the demand. Below this factor, the limit holds. A null factor is past the end of the search.\n */\nexport interface LimitReach {\n readonly limit: string;\n readonly measure: string;\n readonly factor: OpenValue;\n /** This number is the share of the replicates where this limit breaks before each other limit. */\n readonly binds: number;\n /** This flag tells that the composition has no value past the factor of the estimate. Then the edge of the composition sets the factor. */\n readonly edge: boolean;\n /** This flag tells that a law of the composition reads a variable outside its range at the factor of the estimate. */\n readonly extrapolated: boolean;\n}\n\n/**\n * A count reach is the highest load that a count of instances holds, as a factor of the demand. The\n * demand at the factor `f` is `scaleDemand(demand, f)`. The `factor` is the first factor where a\n * limit breaks, and the `binding` limit breaks there in the estimate.\n *\n * The limits go from the first limit that breaks to the last. The flag `extrapolated` tells that a\n * law reads a variable outside its range at the factor of the estimate.\n */\nexport interface CountReach {\n readonly count: number;\n readonly level: number;\n readonly search: Range;\n readonly factor: OpenValue;\n readonly binding: string | null;\n readonly extrapolated: boolean;\n readonly limits: readonly LimitReach[];\n}\n\n/**\n * A scale rule is the lowest count of instances that holds each limit at a load, with its interval.\n * Each larger count also holds each limit. A null count is more than `most` instances.\n *\n * The `binding` limit needs the most instances in the estimate. It is null when one instance holds\n * each limit at each share of the search. The limits go from the largest count to the smallest. The\n * reach `next` is the highest load of the count of the estimate: there the service needs one more instance.\n */\nexport interface ScaleRule {\n readonly level: number;\n readonly most: number;\n readonly count: OpenValue;\n readonly binding: string | null;\n readonly extrapolated: boolean;\n readonly limits: readonly LimitCount[];\n readonly next: CountReach | null;\n}\n\n/** The setup of one limit: its composition, and the number that changes a value of the composition to a use of the limit. */\ninterface LimitSetup {\n readonly limit: Limit;\n readonly path: string;\n /** This index is the index of the composition in the model. */\n readonly at: number;\n readonly prepared: Prepared;\n /** This number times a value of the composition is the use of the limit. A use above 1 breaks the limit. */\n readonly per: number;\n}\n\n/** The setup of a scale query: each limit, the count of rows that the limits share, and the options. */\ninterface Setup {\n readonly limits: readonly LimitSetup[];\n readonly rows: number;\n readonly level: number;\n readonly given: Amounts;\n readonly whole: readonly string[];\n readonly most: number;\n readonly steps: number;\n readonly demand: Demand;\n}\n\n/** A path of demands gives the demand on one instance at each load of a search. */\ntype DemandAt = (load: number) => Demand | undefined;\n\n/** The search of one limit: the first load where each row breaks the limit, and if the edge sets the load of the estimate. Row 0 is the estimate. */\ninterface LimitBreaks {\n readonly rows: readonly number[];\n readonly edge: boolean;\n}\n\n/**\n * The summary holds the rows of all limits: the first load where each row breaks a limit. It also holds the limit that\n * breaks first in the estimate, and the share of the rows where each limit is first.\n */\ninterface Summary {\n readonly rows: readonly number[];\n readonly binding: number | null;\n readonly binds: readonly number[];\n /** These indexes put the limits in the order of the load of the estimate, from the first limit that breaks. */\n readonly order: readonly number[];\n}\n\nconst problem = (code: ScaleProblemCode, path: string, message: string): ScaleProblem => ({ code, path, message });\n\n/** This function gives a problem with `owner` in front of its path. */\nconst under = (found: Problem<string>, owner: string): ScaleProblem => ({\n code: found.code as ScaleProblemCode,\n path: `${owner}.${found.path}`,\n message: found.message,\n});\n\n/**\n * This function gives a problem of a composition of the model, with the path in the model. A path of\n * the catalog starts with `laws` or `compositions`, and each other path is in the composition.\n */\nconst inComposition = (found: Problem<string>, at: number): ScaleProblem =>\n under(found, /^(laws|compositions)\\./.test(found.path) ? \"catalog\" : `compositions[${at}]`);\n\n/** This function gives the setup of a scale query, or the first problem of the model, the demand or the options. */\nconst setupOf = (model: ScaleModel, demand: Demand, options: ScaleOptions): Result<Setup, ScaleProblem> => {\n const level = options.level ?? DEFAULT_LEVEL;\n const most = options.most ?? SCALE_MOST;\n if (!Number.isSafeInteger(most) || most < 2) {\n return err(problem(\"factor\", \"most\", `The largest count of the search, ${most}, is not a whole number of 2 or more.`));\n }\n const badDemand = demandProblems(demand)[0];\n if (badDemand !== undefined) return err(under(badDemand, \"demand\"));\n const whole = options.whole ?? [];\n const unknown = whole.find((name) => !Object.hasOwn(demand.levels, name));\n if (unknown !== undefined) return err(problem(\"variable\", \"whole\", `The demand has no level \"${unknown}\".`));\n if (model.limits.length === 0) return err(problem(\"measure\", \"limits\", \"The model has no limit.\"));\n const twice = repeated(model.limits.map((limit) => limit.id));\n if (twice !== undefined) return err(problem(\"id\", \"limits\", `Two limits have the id \"${twice}\".`));\n\n const byMeasure = new Map<string, number>();\n for (const [index, composition] of model.compositions.entries()) {\n const measure = composition.measure.id;\n if (byMeasure.has(measure)) return err(problem(\"measure\", `compositions[${index}].measure.id`, `Two compositions give the measure \"${measure}\".`));\n byMeasure.set(measure, index);\n }\n const prepared = new Map<number, Prepared>();\n const limits: LimitSetup[] = [];\n for (const [index, limit] of model.limits.entries()) {\n const path = `limits[${index}]`;\n const amount = limitAmount(limit, model.instance);\n if (amount.tag === \"err\") return err(under(amount.error, amount.error.path.startsWith(\"resources.\") ? \"instance\" : path));\n const at = byMeasure.get(limit.measure);\n if (at === undefined) {\n return err(problem(\"measure\", `${path}.measure`, `The model has no composition of the measure \"${limit.measure}\" of the limit \"${limit.id}\".`));\n }\n const composition = model.compositions[at] as Composition;\n let ready = prepared.get(at);\n if (ready === undefined) {\n const found = preparedOf(composition, model.catalog, level);\n if (found.tag === \"err\") return err(inComposition(found.error, at));\n ready = found.value;\n prepared.set(at, ready);\n }\n const unit = composition.measure.unit;\n const ceiling = amount.value;\n if (!convertible(unit, ceiling.unit)) {\n const why = whyNotConvertible(unit, ceiling.unit) ?? \"the units are different\";\n const message = `The composition of the limit \"${limit.id}\" gives \"${unit}\", and the ceiling of the limit is in \"${ceiling.unit}\": ${why}.`;\n return err(problem(\"unit\", `compositions[${at}].measure.unit`, message));\n }\n limits.push({ limit, path, at, prepared: ready, per: factorOf(unit, ceiling.unit) / ceiling.value });\n }\n const rows = Math.min(...limits.map((each) => each.prepared.rows));\n return ok({ limits, rows, level, given: options.given ?? {}, whole, most, steps: options.steps ?? SCALE_STEPS, demand });\n};\n\n/** This function gives the flat parts of the composition of a limit at one load of a path, or undefined when the load has none. */\nconst partsAt = (setup: Setup, each: LimitSetup, demandAt: DemandAt, load: number): readonly FlatPart[] | undefined => {\n const demand = demandAt(load);\n if (demand === undefined) return undefined;\n const parts = flatPartsOf(each.prepared, demand, setup.given);\n return parts.tag === \"ok\" ? parts.value : undefined;\n};\n\n/**\n * This function searches each limit along a path of demands. For each row of each limit, it gives the first load\n * where the use of the limit is above 1. A load where the composition has no value also breaks the row.\n * Infinity tells that the row holds the limit on all of the grid.\n *\n * A problem of the composition at the start of the search is a problem of the model, and not an edge.\n */\nconst breaksOf = (setup: Setup, grid: readonly number[], demandAt: DemandAt): Result<readonly LimitBreaks[], ScaleProblem> => {\n const found: LimitBreaks[] = [];\n const start = grid[0] as number;\n for (const each of setup.limits) {\n const demand = demandAt(start);\n if (demand !== undefined) {\n const first = flatPartsOf(each.prepared, demand, setup.given);\n if (first.tag === \"err\") return err(inComposition(first.error, each.at));\n }\n // The loads of the grid repeat in each row. Thus the parts of a load are kept for the next row.\n const known = new Map<number, readonly FlatPart[] | undefined>();\n const cached = (load: number): readonly FlatPart[] | undefined => {\n if (!known.has(load)) known.set(load, partsAt(setup, each, demandAt, load));\n return known.get(load);\n };\n // Each row reads each load of the grid. Thus the values of all the rows at a load of the grid come from one call.\n // The loads of a bisection differ for each row, so they give the value of one row.\n const onGrid = new Set(grid);\n const gridRows = new Map<number, readonly (number | undefined)[] | undefined>();\n const valueAt = (load: number, row: number): number | undefined => {\n if (onGrid.has(load)) {\n if (!gridRows.has(load)) {\n const parts = cached(load);\n gridRows.set(load, parts === undefined ? undefined : rowValuesOf(parts, 0, setup.rows));\n }\n return gridRows.get(load)?.[row];\n }\n const parts = cached(load);\n return parts === undefined ? undefined : rowValueOf(parts, row);\n };\n const rows: number[] = [];\n let edge = false;\n for (let row = 0; row <= setup.rows; row += 1) {\n const curve: Curve = (loads) =>\n loads.map((load) => {\n const value = valueAt(load, row);\n return value === undefined ? undefined : each.per * value;\n });\n const result = rowOf(curve, `${each.path}.rows[${row}]`, amountTest(1), grid, 0, \"composition\");\n if (result.tag === \"err\") return result;\n const crossing = result.value.crossing ?? Infinity;\n if (row === 0) edge = result.value.edge <= crossing && Number.isFinite(result.value.edge);\n rows.push(Math.min(crossing, result.value.edge));\n }\n found.push({ rows, edge });\n }\n return ok(found);\n};\n\n/** This function gives the index of the least finite value, the first on a tie, or null when no value is finite. */\nconst leastOf = (values: readonly number[]): number | null => {\n let best: number | null = null;\n for (const [index, value] of values.entries()) {\n if (Number.isFinite(value) && (best === null || value < (values[best] as number))) best = index;\n }\n return best;\n};\n\n/** This function joins the rows of the limits. Each row breaks at the first load where one of its limits breaks. */\nconst summaryOf = (breaks: readonly LimitBreaks[], rows: number): Summary => {\n const joined: number[] = [];\n const counts = new Array<number>(breaks.length).fill(0);\n for (let row = 0; row <= rows; row += 1) {\n const loads = breaks.map((each) => each.rows[row] as number);\n const first = leastOf(loads);\n joined.push(first === null ? Infinity : (loads[first] as number));\n if (row > 0 && first !== null) counts[first] = (counts[first] as number) + 1;\n }\n const estimate = breaks.map((each) => each.rows[0] as number);\n const order = estimate.map((_, index) => index).sort((a, b) => (estimate[a] as number) - (estimate[b] as number) || a - b);\n return { rows: joined, binding: leastOf(estimate), binds: counts.map((count) => count / rows), order };\n};\n\n/** This function tells if a law of the composition of a limit reads a variable outside its range at one load of a path. */\nconst outsideAt = (setup: Setup, each: LimitSetup, demandAt: DemandAt, load: number): boolean => {\n const parts = partsAt(setup, each, demandAt, load);\n return parts !== undefined && partsOutside(parts);\n};\n\n/** This function tells if a law of the composition of a limit reads a variable outside its range at one load. */\ntype OutsideAt = (each: LimitSetup, load: number) => boolean;\n\n/** This function gives the reach of a count of instances from the breaks of each limit along the factor of the demand. */\nconst reachFrom = (setup: Setup, count: number, breaks: readonly LimitBreaks[], outside: OutsideAt): CountReach => {\n const { most, level } = setup;\n const summary = summaryOf(breaks, setup.rows);\n const at = (value: number | null): number => value ?? most;\n const limits = summary.order.map((index): LimitReach => {\n const each = setup.limits[index] as LimitSetup;\n const found = breaks[index] as LimitBreaks;\n const factor = openValueOf(found.rows, level, most);\n return {\n limit: each.limit.id,\n measure: each.limit.measure,\n factor,\n binds: summary.binds[index] as number,\n edge: found.edge,\n extrapolated: outside(each, at(factor.value)),\n };\n });\n const factor = openValueOf(summary.rows, level, most);\n return {\n count,\n level,\n search: { low: 1 / most, high: most },\n factor,\n binding: summary.binding === null ? null : (setup.limits[summary.binding] as LimitSetup).limit.id,\n extrapolated: setup.limits.some((each) => outside(each, at(factor.value))),\n limits,\n };\n};\n\n/** This function gives the reach of a count of instances, from a correct setup. */\nconst reachOf = (setup: Setup, count: number): Result<CountReach, ScaleProblem> => {\n const { most, whole } = setup;\n const grid = searchGrid(1 / most, most, setup.steps, true, \"The factor of the demand\");\n if (grid.tag === \"err\") return grid;\n const demandAt: DemandAt = (factor) => {\n const portion = portionOf(setup.demand, factor / count, factor, whole);\n return portion.tag === \"ok\" ? portion.value : undefined;\n };\n const breaks = breaksOf(setup, grid.value, demandAt);\n if (breaks.tag === \"err\") return breaks;\n return ok(reachFrom(setup, count, breaks.value, (each, factor) => outsideAt(setup, each, demandAt, factor)));\n};\n\n/**\n * This function gives the highest load that a count of instances holds, as a factor of the demand,\n * with an interval. Thus it is the inverse query of the scale rule. The demand divides between the\n * instances, as in `shareOf`, and the levels in `options.whole` do not divide.\n *\n * Each row of the doubt of the laws has its own search. Row `i` of each limit reads row `i` of each\n * law, thus the rows of the limits pair. The factor of a row is the first factor where one limit\n * of the row breaks, or where a composition has no value. The interval is the share `level` of the\n * factors of the replicates, made wider to hold the factor of the estimate.\n *\n * The search tests a grid of factors, then a bisection finds each crossing. A crossing between two\n * loads of the grid is found. Two crossings in one step of the grid can hide the first.\n *\n * The function gives a problem for a model, a demand or options that are not correct. It gives a\n * problem for a count that is not a whole number of 1 or more. It also gives a problem when a\n * composition has no value at the start of the search.\n */\nexport const countReach = (model: ScaleModel, count: number, demand: Demand, options: ScaleOptions = {}): Result<CountReach, ScaleProblem> => {\n const setup = setupOf(model, demand, options);\n if (setup.tag === \"err\") return setup;\n if (!Number.isSafeInteger(count) || count < 1) {\n return err(problem(\"factor\", \"count\", `The count of instances ${count} is not a whole number of 1 or more.`));\n }\n return reachOf(setup.value, count);\n};\n\n/** This function gives the lowest count of instances for a share of one instance where a limit breaks. A null count is more than `most`. */\nconst countAt = (share: number | null, most: number): number | null => {\n if (share === null) return 1;\n const count = Math.floor(1 / share) + 1;\n return count > most ? null : count;\n};\n\n/** This function changes an open value of the share of one instance to an open value of the count. The ends change places. */\nconst countsOf = (share: OpenValue, most: number): OpenValue => ({\n value: countAt(share.value, most),\n interval: { low: countAt(share.interval.high, most), high: countAt(share.interval.low, most) },\n});\n\n/**\n * This function gives the scale rule of a service at a load: the lowest count of instances that\n * holds each limit, with an interval. It also gives the limit that binds first, and the load of the\n * next step: the highest load of that count, from `countReach`.\n *\n * The search goes along the share of the demand on one instance: the share of `n` instances is\n * `1 / n`. It starts at the share of `most` instances and goes up to the share of one instance. The\n * count of a row comes from the first share where one limit of the row breaks. Thus the count holds\n * each limit, and each larger count also holds each limit. A level in `options.whole` does not divide.\n *\n * Each row of the doubt of the laws has its own search, and the rows of the limits pair, as in\n * `countReach`. The interval of the count is the share `level` of the counts of the replicates, made\n * wider to hold the count of the estimate. The field `binds` of each limit is the share of the\n * replicates where that limit sets the count.\n *\n * The function gives each problem of `countReach` that is not about a count.\n */\nexport const scaleRule = (model: ScaleModel, demand: Demand, options: ScaleOptions = {}): Result<ScaleRule, ScaleProblem> => {\n const setup = setupOf(model, demand, options);\n if (setup.tag === \"err\") return setup;\n const { most, whole } = setup.value;\n const grid = searchGrid(1 / most, 1, setup.value.steps, true, \"The share of one instance\");\n if (grid.tag === \"err\") return grid;\n const demandAt: DemandAt = (share) => {\n const portion = portionOf(setup.value.demand, share, 1, whole);\n return portion.tag === \"ok\" ? portion.value : undefined;\n };\n const breaks = breaksOf(setup.value, grid.value, demandAt);\n if (breaks.tag === \"err\") return breaks;\n return ruleFrom(\n setup.value,\n breaks.value,\n (each, share) => outsideAt(setup.value, each, demandAt, share),\n (count) => reachOf(setup.value, count),\n );\n};\n\n/** This function gives the scale rule from the breaks of each limit along the share of one instance, and the reach of a count. */\nconst ruleFrom = (\n setup: Setup,\n breaks: readonly LimitBreaks[],\n outside: OutsideAt,\n reachAt: (count: number) => Result<CountReach, ScaleProblem>,\n): Result<ScaleRule, ScaleProblem> => {\n const { most, level } = setup;\n const summary = summaryOf(breaks, setup.rows);\n const shareOfCount = (count: number | null): number => 1 / (count ?? most);\n const limits = summary.order.map((index): LimitCount => {\n const each = setup.limits[index] as LimitSetup;\n const found = breaks[index] as LimitBreaks;\n const count = countsOf(openValueOf(found.rows, level, 1), most);\n return {\n limit: each.limit.id,\n measure: each.limit.measure,\n count,\n binds: summary.binds[index] as number,\n edge: found.edge,\n extrapolated: outside(each, shareOfCount(count.value)),\n };\n });\n const count = countsOf(openValueOf(summary.rows, level, 1), most);\n let next: CountReach | null = null;\n if (count.value !== null) {\n const reach = reachAt(count.value);\n if (reach.tag === \"err\") return reach;\n next = reach.value;\n }\n return ok({\n level,\n most,\n count,\n binding: summary.binding === null ? null : (setup.limits[summary.binding] as LimitSetup).limit.id,\n extrapolated: setup.limits.some((each) => outside(each, shareOfCount(count.value))),\n limits,\n next,\n });\n};\n\n/** A limit ladder holds, for each row of one limit, the first load on one instance where the row breaks the limit. */\nexport interface LimitLadder {\n readonly limit: string;\n readonly measure: string;\n /**\n * Each value is the first load on one instance, as a factor of the demand, where one row breaks the limit. Row 0 is the\n * estimate. A load where the composition has no value also breaks the row. Infinity tells that the row holds on all of the search.\n */\n readonly rows: readonly number[];\n /** This flag tells that the edge of the composition sets the load of row 0. */\n readonly edge: boolean;\n}\n\n/**\n * A scale ladder is the scale rule of a service at each load of a range, from one search. With no level in `whole`, the\n * demand on one of `n` instances at `f` times the load is the demand at `f / n` times the load. Thus each row of each\n * limit breaks at one load on one instance, and a count needs only arithmetic.\n *\n * The function `ruleAt(f)` gives the value of `scaleRule` at the demand `scaleDemand(demand, f)`. The function\n * `reachAt(n, f)` gives the value of `countReach` for `n` instances at the same demand. Each of them reads the\n * compositions only for the flags `extrapolated`, one value for each limit.\n */\nexport interface ScaleLadder {\n readonly level: number;\n readonly most: number;\n /** This range holds the factors of the demand that the ladder answers. */\n readonly range: Range;\n /** This range holds the loads on one instance of the search, as factors of the demand. */\n readonly search: Range;\n /** The limits are in the order of the model. */\n readonly limits: readonly LimitLadder[];\n readonly ruleAt: (factor: number) => Result<ScaleRule, ScaleProblem>;\n readonly reachAt: (count: number, factor: number) => Result<CountReach, ScaleProblem>;\n}\n\n/**\n * This function changes the loads on one instance of a ladder to the loads of a search from `low` to `high`. A load\n * past `high` holds on all of that search, and a load before `low` breaks at its start, as in `rowOf`.\n */\nconst loadsIn = (rows: readonly number[], times: number, low: number, high: number): number[] =>\n rows.map((load) => {\n const found = load * times;\n return found > high ? Infinity : Math.max(found, low);\n });\n\n/**\n * This function gives the scale ladder of a service over the factors of the demand from `range.low` to `range.high`.\n * The search covers the loads on one instance that `scaleRule` and `countReach` read at each factor of the range: from\n * `range.low / most` to `range.high * most`. Its grid has the density of the grid of `scaleRule`, up to the largest\n * count of steps.\n *\n * The values of the ladder agree with `scaleRule` and `countReach` to the precision of their bisections. They can differ\n * when two crossings are in one step of a grid, because the grids are different.\n *\n * The function gives each problem of `scaleRule`. It also gives a problem for a level in `options.whole`. With such a level,\n * the demand on one instance does not depend only on the load over the count. It gives a problem for a range that does not\n * go from a number above 0 to a larger finite number.\n */\nexport const scaleLadder = (model: ScaleModel, demand: Demand, range: Range, options: ScaleOptions = {}): Result<ScaleLadder, ScaleProblem> => {\n const found = setupOf(model, demand, options);\n if (found.tag === \"err\") return found;\n const setup = found.value;\n if (setup.whole.length > 0) {\n return err(problem(\"variable\", \"whole\", \"A ladder needs a demand that divides between the instances. Use scaleRule for a level in whole.\"));\n }\n if (!(range.low > 0 && Number.isFinite(range.high) && range.low < range.high)) {\n return err(problem(\"factor\", \"range\", `The range goes from ${range.low} to ${range.high}. It must go from a number above 0 to a larger finite number.`));\n }\n const { most, level } = setup;\n const search: Range = { low: range.low / most, high: range.high * most };\n // The grid of scaleRule has `steps` steps over the factor `most`. This grid keeps that count of steps for each factor.\n const steps = Math.min(MAX_STEPS, Math.max(setup.steps, Math.ceil((setup.steps * Math.log(search.high / search.low)) / Math.log(most))));\n const grid = searchGrid(search.low, search.high, steps, true, \"The load on one instance\");\n if (grid.tag === \"err\") return grid;\n const demandAt: DemandAt = (load) => {\n const portion = portionOf(setup.demand, load, load, []);\n return portion.tag === \"ok\" ? portion.value : undefined;\n };\n const breaks = breaksOf(setup, grid.value, demandAt);\n if (breaks.tag === \"err\") return breaks;\n const ladder = breaks.value;\n const outsideOn = (each: LimitSetup, load: number): boolean => outsideAt(setup, each, demandAt, load);\n const inRange = (factor: number): Result<number, ScaleProblem> =>\n factor >= range.low && factor <= range.high\n ? ok(factor)\n : err(problem(\"factor\", \"factor\", `The factor ${factor} is outside the range of the ladder, from ${range.low} to ${range.high}.`));\n /** This function gives the breaks of each limit along the factor of a search from `low` to `high`. The load on one instance is `times` the factor. */\n const breaksIn = (times: number, low: number, high: number): LimitBreaks[] =>\n ladder.map((each) => {\n const rows = loadsIn(each.rows, 1 / times, low, high);\n return { rows, edge: each.edge && Number.isFinite(rows[0] as number) };\n });\n const reachIn = (count: number, factor: number): CountReach =>\n reachFrom(setup, count, breaksIn(factor / count, 1 / most, most), (each, at) => outsideOn(each, (factor * at) / count));\n const reachAt = (count: number, factor: number): Result<CountReach, ScaleProblem> => {\n if (!Number.isSafeInteger(count) || count < 1) {\n return err(problem(\"factor\", \"count\", `The count of instances ${count} is not a whole number of 1 or more.`));\n }\n const at = inRange(factor);\n return at.tag === \"err\" ? at : ok(reachIn(count, factor));\n };\n const ruleAt = (factor: number): Result<ScaleRule, ScaleProblem> => {\n const at = inRange(factor);\n if (at.tag === \"err\") return at;\n return ruleFrom(\n setup,\n breaksIn(factor, 1 / most, 1),\n (each, share) => outsideOn(each, factor * share),\n (count) => ok(reachIn(count, factor)),\n );\n };\n const limits = setup.limits.map((each, index): LimitLadder => ({ limit: each.limit.id, measure: each.limit.measure, ...(ladder[index] as LimitBreaks) }));\n return ok({ level, most, range, search, limits, ruleAt, reachAt });\n};\n"],"mappings":";;;;;;;;AAOA,MAAa,gBAAgB;AA4E7B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