@mark1russell7/rigor-statistics 0.1.25 → 0.1.27

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":["ends","whole","whole"],"sources":["../src/describe.ts","../src/running.ts","../src/regression.ts","../src/bootstrap.ts","../src/distribution.ts","../src/ridge.ts","../src/response.ts","../src/response-parse.ts","../src/response-fit.ts","../src/response-sobol.ts","../src/tests.ts","../src/agreement.ts","../src/rank.ts","../src/discrete.ts","../src/compare.ts","../src/power.ts","../src/normal.ts","../src/coverage.ts","../src/u-statistic.ts","../src/rating.ts","../src/bradley-terry.ts"],"sourcesContent":["/**\n * The descriptive statistics: the mean, the standard deviation, the median, the quantiles and a summary of a list.\n * Each function throws a RangeError for an empty list or for a value that is NaN. Thus a missing value cannot make a\n * quiet NaN in a record.\n */\n\n/** The definitions of a quantile that the engines use (Hyndman and Fan, 1996, and the names of NumPy). */\nexport type QuantileMethod =\n /** Type 7: a linear step between the two nearest ranks. The default of R and NumPy. */\n | \"linear\"\n /** Type 1: the smallest value with at least the share `p` of the values at or below it. */\n | \"nearest-rank\"\n /**\n * The higher of the two nearest ranks of type 7: `sorted[Math.ceil(p * (n - 1))]`. This is the method `\"higher\"` of\n * NumPy. The 0.5 quantile is the upper median `sorted[Math.floor(n / 2)]`. The rank `p * (n - 1)` is rounded to\n * `1e-9` before the ceiling. Thus a float error, for example `0.55 * 100 = 55.00000000000001`, does not move the rank up.\n * The rounding keeps the exact rank while `p * (n - 1) * 1e9` is below `2 ** 53`, so for `n` up to approximately 9 million.\n */\n | \"higher\";\n\nfunction checked(name: string, values: readonly number[]): void {\n if (values.length === 0) throw new RangeError(`${name}: the list is empty.`);\n for (const v of values) if (Number.isNaN(v)) throw new RangeError(`${name}: the list has a NaN.`);\n}\n\n/** A new list with the values from the smallest to the largest. */\nexport function sorted(values: readonly number[]): number[] {\n return [...values].sort((a, b) => a - b);\n}\n\nexport function mean(values: readonly number[]): number {\n checked(\"mean\", values);\n let sum = 0;\n for (const v of values) sum += v;\n return sum / values.length;\n}\n\n/** This function tells if each value is equal to the first value. An empty list gives true. */\nexport function allEqual(values: readonly number[]): boolean {\n return values.every((v) => v === values[0]);\n}\n\n/**\n * The sample standard deviation (the divisor is n - 1). It needs 2 values or more. Equal values give exactly 0. The\n * rounding of the mean gives a small number that is not 0 for some equal values, so the function examines them first.\n */\nexport function sd(values: readonly number[]): number {\n checked(\"sd\", values);\n if (values.length < 2) throw new RangeError(\"sd: the list needs 2 values or more.\");\n if (allEqual(values)) return 0;\n const m = mean(values);\n let sum = 0;\n for (const v of values) sum += (v - m) ** 2;\n return Math.sqrt(sum / (values.length - 1));\n}\n\n/**\n * The `p` quantile of a list that is already sorted. Use it when you take several quantiles of one list.\n * The linear method gives the same numbers as the copies in highways, packing and layout-contract. The\n * nearest-rank method gives the same numbers as the copies in lag, lag-hud and the backtest of highways. The\n * higher method gives the upper median of the copies in highways with `p = 0.5`.\n */\nexport function quantileSorted(sortedValues: readonly number[], p: number, method: QuantileMethod = \"linear\"): number {\n checked(\"quantile\", sortedValues);\n if (!(p >= 0 && p <= 1)) throw new RangeError(`quantile: p is from 0 to 1, not ${p}.`);\n const n = sortedValues.length;\n if (method === \"nearest-rank\") return sortedValues[Math.min(n - 1, Math.max(0, Math.ceil(p * n) - 1))] as number;\n // The rank on a grid of 1e-9, so that a float error above a whole rank does not give the next rank.\n if (method === \"higher\") return sortedValues[Math.ceil(Math.round(p * (n - 1) * 1e9) / 1e9)] as number;\n const at = (n - 1) * p;\n const low = Math.floor(at);\n const part = at - low;\n const a = sortedValues[low] as number;\n if (part === 0) return a;\n const b = sortedValues[low + 1] as number;\n if (a === b) return a;\n return a + part * (b - a);\n}\n\n/** The `p` quantile of a list. */\nexport function quantile(values: readonly number[], p: number, method: QuantileMethod = \"linear\"): number {\n checked(\"quantile\", values);\n return quantileSorted(sorted(values), p, method);\n}\n\n/**\n * The median: the middle value, or the midpoint `(a + b) / 2` of the two middle values. The midpoint is correctly\n * rounded. `quantile(values, 0.5)` computes `a + 0.5 * (b - a)`, which can differ from it in the last bit.\n */\nexport function median(values: readonly number[]): number {\n checked(\"median\", values);\n const s = sorted(values);\n const middle = Math.floor(s.length / 2);\n return s.length % 2 === 1 ? (s[middle] as number) : ((s[middle - 1] as number) + (s[middle] as number)) / 2;\n}\n\n/** The summary of a list. The quartiles use the linear method. */\nexport interface Summary {\n readonly n: number;\n readonly mean: number;\n /** The sample standard deviation, or NaN for one value. */\n readonly sd: number;\n readonly min: number;\n /** The 0.25 quantile. */\n readonly q1: number;\n readonly median: number;\n /** The 0.75 quantile. */\n readonly q3: number;\n readonly max: number;\n /** The interquartile range: q3 - q1. */\n readonly iqr: number;\n}\n\nexport function summarize(values: readonly number[]): Summary {\n checked(\"summarize\", values);\n const s = sorted(values);\n const q1 = quantileSorted(s, 0.25);\n const q3 = quantileSorted(s, 0.75);\n return {\n n: s.length,\n // The mean and sd of the list in its own order, so that they are equal to mean(values) and sd(values).\n mean: mean(values),\n sd: s.length < 2 ? Number.NaN : sd(values),\n min: s[0] as number,\n q1,\n median: median(s),\n q3,\n max: s[s.length - 1] as number,\n iqr: q3 - q1,\n };\n}\n","/**\n * The running summary: the count, the sum, the extremes and the spread of a stream of values, one value at a time.\n * A collector, a reducer or a parallel job adds each value, or merges two summaries. The summary agrees with the\n * functions of a list: `runningMean` gives exactly `mean` of the values, and `runningSd` gives `sd` to a tolerance.\n */\n\n/**\n * A running summary of the values that were added. The record is immutable, so a fold can keep each step. The empty\n * summary is `EMPTY_RUNNING`.\n */\nexport interface RunningSummary {\n /** The count of the values. */\n readonly n: number;\n /** The sum of the values, added in their order. */\n readonly sum: number;\n /** The smallest value, or `Infinity` for no value. */\n readonly min: number;\n /** The largest value, or `-Infinity` for no value. */\n readonly max: number;\n /** The sum of the squares of the differences from the mean (Welford). `runningSd` reads it. */\n readonly m2: number;\n}\n\n/** The summary of no value. It is the unit of `mergeRunning`. */\nexport const EMPTY_RUNNING: RunningSummary = Object.freeze({ n: 0, sum: 0, min: Infinity, max: -Infinity, m2: 0 });\n\n/**\n * This function gives the summary with one more value. It throws a RangeError for NaN, as the functions of a list do.\n * The mean of each step is `sum / n`, so the mean of the fold is the mean of the list.\n */\nexport function addToRunning(s: RunningSummary, value: number): RunningSummary {\n if (Number.isNaN(value)) throw new RangeError(\"addToRunning: the value is NaN.\");\n // The sum starts at 0, as the sum of `mean` does. Thus a first value of -0 gives the sum 0 there too.\n const sum = s.sum + value;\n if (s.n === 0) return { n: 1, sum, min: value, max: value, m2: 0 };\n const n = s.n + 1;\n const m2 = s.m2 + (value - s.sum / s.n) * (value - sum / n);\n return { n, sum, min: Math.min(s.min, value), max: Math.max(s.max, value), m2 };\n}\n\n/** This function gives the summary of the values of a list or another iterable, in their order. */\nexport function runningOf(values: Iterable<number>): RunningSummary {\n let s = EMPTY_RUNNING;\n for (const v of values) s = addToRunning(s, v);\n return s;\n}\n\n/**\n * This function gives the summary of the values of two summaries (Chan, Golub and LeVeque, 1979). Thus parallel jobs\n * can each summarize a part. The sum of the merge adds the two sums, so it can differ from the fold in the last bits.\n */\nexport function mergeRunning(a: RunningSummary, b: RunningSummary): RunningSummary {\n if (a.n === 0) return b;\n if (b.n === 0) return a;\n const n = a.n + b.n;\n const delta = b.sum / b.n - a.sum / a.n;\n return {\n n,\n sum: a.sum + b.sum,\n min: Math.min(a.min, b.min),\n max: Math.max(a.max, b.max),\n m2: a.m2 + b.m2 + ((delta * delta * a.n) / n) * b.n,\n };\n}\n\n/** This function gives the mean of the values: `sum / n`. It throws a RangeError for the empty summary. */\nexport function runningMean(s: RunningSummary): number {\n if (s.n === 0) throw new RangeError(\"runningMean: the summary is empty.\");\n return s.sum / s.n;\n}\n\n/**\n * This function gives the sample standard deviation of the values (the divisor is n - 1). It needs 2 values or more.\n * Equal values give exactly 0, as `sd` gives. A rounding error cannot make the result NaN.\n */\nexport function runningSd(s: RunningSummary): number {\n if (s.n < 2) throw new RangeError(\"runningSd: the summary needs 2 values or more.\");\n if (s.min === s.max) return 0;\n return Math.sqrt(Math.max(0, s.m2) / (s.n - 1));\n}\n","/**\n * Ordinary least squares with a Householder QR decomposition. The QR decomposition does not square the condition\n * number of the design, as the normal equations do. A design without full rank gives NaN coefficients and does not\n * throw. Thus a bootstrap run with a singular draw is not finite, and it does not count.\n */\n\nexport interface LeastSquaresOptions {\n /** When true, the fit adds an intercept as coefficient 0. The default is true. */\n readonly intercept?: boolean;\n}\n\nexport interface LeastSquaresFit {\n /** The coefficients. With an intercept, coefficient 0 is the intercept and coefficient `j + 1` is predictor `j`. */\n readonly coefficients: number[];\n /** The residual standard deviation: the square root of the residual sum of squares divided by `n - k`. */\n readonly residualSd: number;\n /**\n * The coefficient of determination: 1 minus the residual sum of squares divided by the total sum of squares. With\n * an intercept, the total sum uses the distances from the mean of `y`. Without an intercept, it uses the values.\n */\n readonly r2: number;\n /** The number of rows. */\n readonly n: number;\n /** The number of coefficients, with the intercept. */\n readonly k: number;\n}\n\n/**\n * The relative tolerance of the rank test. A column is dependent when the part of it that is orthogonal to the\n * columns before it is shorter than this share of its length.\n */\nconst RANK_TOLERANCE = 1e-10;\n\n/**\n * The ordinary least-squares fit of `y` on the rows of `x`, with `k` coefficients. Each row has the same number of\n * predictors. The fit solves the problem with a Householder QR decomposition. When the design does not have full\n * rank, or when `n <= k`, the coefficients, `residualSd` and `r2` are NaN. When the total sum of squares is 0,\n * `r2` is NaN.\n *\n * This function throws a RangeError for an empty `x` and for rows of different lengths. It also throws\n * for `x` and `y` of different lengths, for a value that is not finite, and for a fit with no coefficient.\n */\nexport function leastSquares(x: readonly (readonly number[])[], y: readonly number[], options: LeastSquaresOptions = {}): LeastSquaresFit {\n const intercept = options.intercept ?? true;\n const k = checkedShape(\"leastSquares\", x, y, intercept);\n return fitRows(x, y, intercept, k);\n}\n\n/**\n * This function examines the shape and the values of a least-squares problem, and gives the number of\n * coefficients. It throws a RangeError for each fault.\n */\nexport function checkedShape(name: string, x: readonly (readonly number[])[], y: readonly number[], intercept: boolean): number {\n if (x.length === 0) throw new RangeError(`${name}: x is empty.`);\n if (x.length !== y.length) throw new RangeError(`${name}: x has ${x.length} rows and y has ${y.length} values. The two lengths must be equal.`);\n const p = (x[0] as readonly number[]).length;\n for (let i = 0; i < x.length; i++) {\n const row = x[i] as readonly number[];\n if (row.length !== p) throw new RangeError(`${name}: row ${i} of x has ${row.length} values, and row 0 has ${p}. Each row must have the same length.`);\n for (const v of row) if (!Number.isFinite(v)) throw new RangeError(`${name}: row ${i} of x has a value that is not finite.`);\n if (!Number.isFinite(y[i] as number)) throw new RangeError(`${name}: value ${i} of y is not finite.`);\n }\n const k = p + (intercept ? 1 : 0);\n if (k === 0) throw new RangeError(`${name}: the fit has no coefficient. Give a predictor or an intercept.`);\n return k;\n}\n\n/**\n * The fit of rows with a known shape. The caller examined the shape with `checkedShape`. The design is a matrix of\n * `n` rows and `k` columns, kept by column.\n */\nexport function fitRows(x: readonly (readonly number[])[], y: readonly number[], intercept: boolean, k: number): LeastSquaresFit {\n const n = x.length;\n const failed = (): LeastSquaresFit => ({ coefficients: new Array<number>(k).fill(Number.NaN), residualSd: Number.NaN, r2: Number.NaN, n, k });\n if (n <= k) return failed();\n const offset = intercept ? 1 : 0;\n const a = new Float64Array(n * k);\n for (let i = 0; i < n; i++) {\n const row = x[i] as readonly number[];\n if (intercept) a[i] = 1;\n for (let j = offset; j < k; j++) a[j * n + i] = row[j - offset] as number;\n }\n const qty = Float64Array.from(y);\n const diagonal = new Float64Array(k);\n for (let j = 0; j < k; j++) {\n const c = j * n;\n // A reflection keeps the length of a column. Thus the length of column j is the length of its first form.\n let head = 0;\n for (let i = 0; i < j; i++) head += (a[c + i] as number) ** 2;\n let tail2 = 0;\n for (let i = j; i < n; i++) tail2 += (a[c + i] as number) ** 2;\n // The tail is the part of column j that is orthogonal to the columns before it.\n const tail = Math.sqrt(tail2);\n if (!(tail > RANK_TOLERANCE * Math.sqrt(head + tail2))) return failed();\n const alpha = (a[c + j] as number) > 0 ? -tail : tail;\n // The Householder vector v is the tail of column j minus alpha times the first unit vector. It is kept in place.\n a[c + j] = (a[c + j] as number) - alpha;\n let vv = 0;\n for (let i = j; i < n; i++) vv += (a[c + i] as number) ** 2;\n const reflect = (target: Float64Array, start: number): void => {\n let dot = 0;\n for (let i = j; i < n; i++) dot += (a[c + i] as number) * (target[start + i] as number);\n const f = (2 * dot) / vv;\n for (let i = j; i < n; i++) target[start + i] = (target[start + i] as number) - f * (a[c + i] as number);\n };\n for (let m = j + 1; m < k; m++) reflect(a, m * n);\n reflect(qty, 0);\n diagonal[j] = alpha;\n }\n // The back substitution of R b = Q'y. Above the diagonal, R is in the columns of a.\n const b = new Array<number>(k).fill(0);\n for (let j = k - 1; j >= 0; j--) {\n let s = qty[j] as number;\n for (let m = j + 1; m < k; m++) s -= (a[m * n + j] as number) * (b[m] as number);\n b[j] = s / (diagonal[j] as number);\n }\n let center = 0;\n if (intercept) {\n for (const v of y) center += v;\n center /= n;\n }\n let rss = 0;\n let tss = 0;\n for (let i = 0; i < n; i++) {\n const row = x[i] as readonly number[];\n let fitted = intercept ? (b[0] as number) : 0;\n for (let j = offset; j < k; j++) fitted += (b[j] as number) * (row[j - offset] as number);\n rss += ((y[i] as number) - fitted) ** 2;\n tss += ((y[i] as number) - center) ** 2;\n }\n return { coefficients: b, residualSd: Math.sqrt(rss / (n - k)), r2: tss > 0 ? 1 - rss / tss : Number.NaN, n, k };\n}\n","/**\n * The percentile bootstrap. Each run draws n items with replacement (`below(n)` of rigor-generators, which is\n * `floor(next() * n)`), and computes the statistic of the sample. The interval is two quantiles of the statistics.\n * With the same seed, the draws are equal to the draws of the copies in highways, packing and layout-contract.\n * `bootstrapTwo` draws two independent samples in each run: first the items of `a`, then the items of `b`.\n * `bootstrapLeastSquares` draws whole rows, and gives one interval for each coefficient from the same draws.\n *\n * `sampleTotalInterval` gives the interval of a population total from a sample without replacement.\n */\nimport { type Random, random } from \"@mark1russell7/rigor-generators\";\nimport { type QuantileMethod, median, quantileSorted, sorted } from \"./describe.ts\";\nimport { type LeastSquaresOptions, checkedShape, fitRows } from \"./regression.ts\";\n\nexport interface BootstrapOptions {\n /** The number of samples. The default is 10 000. */\n readonly runs?: number;\n /** The level of the interval. The default is 0.95. */\n readonly level?: number;\n /** The seed of the draws. The default is 1. */\n readonly seed?: number | string;\n /** The quantile method of the two ends of the interval. The default is linear. */\n readonly method?: QuantileMethod;\n /**\n * The quantiles of the two ends, in place of `level`, for example [0.025, 0.975] or an interval with one side.\n * The default is from the level: (1 - level) / 2 and 1 - (1 - level) / 2. In floating point, (1 - 0.95) / 2 is\n * not 0.025, so a copy that writes 0.025 needs this option to give the same numbers.\n */\n readonly ends?: readonly [number, number];\n /**\n * The value of a claim to test, for example 0 for \"no difference\". With this option, the interval also gives `pAbove`\n * and `pBelow` from the same draws, so the ends do not change. The default is no value and no p.\n */\n readonly against?: number;\n}\n\n/** The two bootstrap p of the option `against`. The smallest p is 1 / (finite + 1), so a family correction needs enough runs. */\nexport interface SideP {\n /** The value of the option `against`. */\n readonly against: number;\n /** The p of the claim \"the statistic is above `against`\": (1 + the finite runs at or below `against`) / (finite + 1). */\n readonly pAbove: number;\n /** The p of the claim \"the statistic is below `against`\": (1 + the finite runs at or above `against`) / (finite + 1). */\n readonly pBelow: number;\n}\n\nexport interface Interval extends Partial<SideP> {\n /** The statistic of all the data. */\n readonly estimate: number;\n readonly low: number;\n readonly high: number;\n readonly level: number;\n readonly runs: number;\n /** The number of runs whose statistic is a finite number. Only these runs make the interval. */\n readonly finite: number;\n /** The seed as a 32-bit number. */\n readonly seed: number;\n}\n\n/**\n * A percentile bootstrap interval of `statistic` over `data`. A run whose statistic is not finite (NaN or an\n * infinity) does not count. When no run is finite, low and high are equal to the estimate.\n */\nexport function bootstrap<T>(data: readonly T[], statistic: (sample: readonly T[]) => number, options: BootstrapOptions = {}): Interval {\n if (data.length === 0) throw new RangeError(\"bootstrap: the data is empty.\");\n const n = data.length;\n const sample = new Array<T>(n);\n return percentile(\n \"bootstrap\",\n options,\n (r) => {\n for (let i = 0; i < n; i++) sample[i] = data[r.below(n)] as T;\n return statistic(sample);\n },\n () => statistic(data),\n );\n}\n\n/**\n * A percentile bootstrap interval of `statistic` over two independent samples `a` and `b`. Use it when the two\n * samples are not paired, for example two arms of a benchmark. Each run draws `a.length` items of `a` with\n * replacement, and then `b.length` items of `b` with replacement. All the draws come from one stream of\n * `random(seed)`. The statistic reads the two drawn samples. The estimate is the statistic of all of `a` and `b`. A\n * run whose statistic is not finite does not count. When no run is finite, low and high are equal to the estimate.\n */\nexport function bootstrapTwo<A, B>(\n a: readonly A[],\n b: readonly B[],\n statistic: (a: readonly A[], b: readonly B[]) => number,\n options: BootstrapOptions = {},\n): Interval {\n if (a.length === 0) throw new RangeError(\"bootstrapTwo: the first sample is empty.\");\n if (b.length === 0) throw new RangeError(\"bootstrapTwo: the second sample is empty.\");\n const na = a.length;\n const nb = b.length;\n const sampleA = new Array<A>(na);\n const sampleB = new Array<B>(nb);\n return percentile(\n \"bootstrapTwo\",\n options,\n (r) => {\n for (let i = 0; i < na; i++) sampleA[i] = a[r.below(na)] as A;\n for (let i = 0; i < nb; i++) sampleB[i] = b[r.below(nb)] as B;\n return statistic(sampleA, sampleB);\n },\n () => statistic(a, b),\n );\n}\n\n/**\n * A bootstrap interval of the ratio `median(numerator) / median(denominator)` of two independent samples. The\n * interval is the uncertainty of the ratio of the two medians. It is not the spread of the samples. A run whose\n * denominator median is 0 is not finite, so it does not count.\n */\nexport function bootstrapMedianRatio(numerator: readonly number[], denominator: readonly number[], options: BootstrapOptions = {}): Interval {\n return bootstrapTwo(numerator, denominator, (a, b) => median(a) / median(b), options);\n}\n\n/**\n * A percentile bootstrap interval of each coefficient of the least-squares fit of `y` on the rows of `x`. Each run\n * draws `n` row indexes with replacement, and fits the drawn rows and their `y` values. All the intervals come from\n * the same draws. The estimate of each interval is the coefficient of the fit of all the data. A run with a singular\n * design gives NaN coefficients, so it does not count. The shape errors are the errors of `leastSquares`.\n */\nexport function bootstrapLeastSquares(\n x: readonly (readonly number[])[],\n y: readonly number[],\n options: BootstrapOptions & LeastSquaresOptions = {},\n): Interval[] {\n const intercept = options.intercept ?? true;\n const k = checkedShape(\"bootstrapLeastSquares\", x, y, intercept);\n const n = x.length;\n const sampleX = new Array<readonly number[]>(n);\n const sampleY = new Array<number>(n);\n return percentiles(\n \"bootstrapLeastSquares\",\n options,\n k,\n (r) => {\n for (let i = 0; i < n; i++) {\n const row = r.below(n);\n sampleX[i] = x[row] as readonly number[];\n sampleY[i] = y[row] as number;\n }\n return fitRows(sampleX, sampleY, intercept, k).coefficients;\n },\n () => fitRows(x, y, intercept, k).coefficients,\n );\n}\n\ninterface Settings {\n readonly runs: number;\n readonly lowEnd: number;\n readonly highEnd: number;\n readonly level: number;\n readonly method: QuantileMethod;\n readonly against: number | undefined;\n}\n\n/** This function examines the options of a bootstrap, and gives the defaults. It throws a RangeError for each fault. */\nfunction settings(name: string, options: BootstrapOptions): Settings {\n const runs = options.runs ?? 10_000;\n if (!Number.isSafeInteger(runs) || runs < 1) throw new RangeError(`${name}: runs is a whole number of 1 or more, not ${runs}.`);\n const tail = (1 - (options.level ?? 0.95)) / 2;\n const [lowEnd, highEnd] = options.ends ?? [tail, 1 - tail];\n if (!(lowEnd >= 0 && lowEnd < highEnd && highEnd <= 1)) throw new RangeError(`${name}: the ends are 0 <= low < high <= 1, not ${lowEnd} and ${highEnd}.`);\n const level = options.ends ? highEnd - lowEnd : (options.level ?? 0.95);\n if (!(level > 0 && level < 1)) throw new RangeError(`${name}: level is more than 0 and less than 1, not ${level}.`);\n const against = options.against;\n if (against !== undefined && !Number.isFinite(against)) throw new RangeError(`${name}: against is a finite number, not ${against}.`);\n return { runs, lowEnd, highEnd, level, method: options.method ?? \"linear\", against };\n}\n\n/** This function gives the two p of the option `against`, or nothing without the option. With no finite run, each p is 1. */\nfunction sides(values: readonly number[], against: number | undefined): SideP | Record<string, never> {\n if (against === undefined) return {};\n let atOrBelow = 0;\n let atOrAbove = 0;\n for (const v of values) {\n if (v <= against) atOrBelow++;\n if (v >= against) atOrAbove++;\n }\n const n = values.length + 1;\n return { against, pAbove: (1 + atOrBelow) / n, pBelow: (1 + atOrAbove) / n };\n}\n\n/** The interval of the finite statistics of the runs. When no run is finite, low and high are equal to the estimate. */\nfunction ends(values: number[], estimate: number, s: Settings, seed: number): Interval {\n const { runs, level } = s;\n const p = sides(values, s.against);\n if (values.length === 0) return { estimate, low: estimate, high: estimate, level, runs, finite: 0, seed, ...p };\n const v = sorted(values);\n return { estimate, low: quantileSorted(v, s.lowEnd, s.method), high: quantileSorted(v, s.highEnd, s.method), level, runs, finite: v.length, seed, ...p };\n}\n\n/**\n * The shared part of each percentile bootstrap. It examines the options, and starts one stream of `random(seed)`.\n * Each run gives the stream to `run`, which draws the samples and returns their statistic. Then `all` gives the\n * estimate. The order of the draws is the order in `run`.\n */\nfunction percentile(name: string, options: BootstrapOptions, run: (r: Random) => number, all: () => number): Interval {\n const s = settings(name, options);\n const r = random(options.seed ?? 1);\n const values: number[] = [];\n for (let i = 0; i < s.runs; i++) {\n const v = run(r);\n if (Number.isFinite(v)) values.push(v);\n }\n return ends(values, all(), s, r.seed);\n}\n\n/**\n * The percentile bootstrap of `k` statistics from the same draws. Each run gives `k` statistics. Each statistic\n * has its own count of finite runs.\n */\nexport function percentiles(name: string, options: BootstrapOptions, k: number, run: (r: Random) => readonly number[], all: () => readonly number[]): Interval[] {\n const s = settings(name, options);\n const r = random(options.seed ?? 1);\n const values = Array.from({ length: k }, (): number[] => []);\n for (let i = 0; i < s.runs; i++) {\n const v = run(r);\n for (let j = 0; j < k; j++) if (Number.isFinite(v[j])) (values[j] as number[]).push(v[j] as number);\n }\n const estimate = all();\n return values.map((list, j) => ends(list, estimate[j] as number, s, r.seed));\n}\n\n/** A bootstrap interval of the median. */\nexport function bootstrapMedian(values: readonly number[], options: BootstrapOptions = {}): Interval {\n return bootstrap(values, median, options);\n}\n\n/**\n * A cluster bootstrap: each run draws whole clusters with replacement, and the statistic reads the rows of the drawn\n * clusters. Use it when the rows of one cluster (one board, one seed, one site) are not independent. The clusters\n * are in the order of their first row.\n */\nexport function bootstrapClusters<T>(\n rows: readonly T[],\n cluster: (row: T) => string,\n statistic: (rows: readonly T[]) => number,\n options: BootstrapOptions = {},\n): Interval {\n const groups = new Map<string, T[]>();\n for (const row of rows) {\n const key = cluster(row);\n const list = groups.get(key);\n if (list) list.push(row);\n else groups.set(key, [row]);\n }\n const clusters = [...groups.values()];\n const result = bootstrap(clusters, (drawn) => statistic(drawn.flat()), options);\n // The estimate of all the rows in their own order, not in the order of the clusters.\n const estimate = statistic(rows);\n return result.finite === 0 ? { ...result, estimate, low: estimate, high: estimate } : { ...result, estimate };\n}\n\n/**\n * A stratified bootstrap: each run draws, inside each stratum, as many items as the stratum has, with replacement.\n * So each sample keeps the size of each stratum. Use it when the strata are fixed by the design, for example the\n * families of the inputs of a benchmark. The draws of one run go through the strata in the order of the list. With one\n * stratum, the draws are equal to the draws of `bootstrap` with the same seed. The estimate is the statistic of all\n * the strata. A run whose statistic is not finite does not count.\n */\nexport function bootstrapStrata<T>(\n strata: readonly (readonly T[])[],\n statistic: (samples: readonly (readonly T[])[]) => number,\n options: BootstrapOptions = {},\n): Interval {\n if (strata.length === 0) throw new RangeError(\"bootstrapStrata: there is no stratum.\");\n for (const [i, stratum] of strata.entries()) if (stratum.length === 0) throw new RangeError(`bootstrapStrata: the stratum ${i} is empty.`);\n const samples = strata.map((stratum) => new Array<T>(stratum.length));\n return percentile(\n \"bootstrapStrata\",\n options,\n (r) => {\n for (const [k, stratum] of strata.entries()) {\n const sample = samples[k] as T[];\n const n = stratum.length;\n for (let i = 0; i < n; i++) sample[i] = stratum[r.below(n)] as T;\n }\n return statistic(samples);\n },\n () => statistic(strata),\n );\n}\n\nexport interface SampleTotalOptions extends BootstrapOptions {\n /** The number of items in the whole population, `n`. It is a whole number, and it is not less than the sample. */\n readonly population: number;\n /** The factor from the sum of the sample to the total of the population. The default is `population / values.length`. */\n readonly scale?: number;\n}\n\n/**\n * A bootstrap interval of the total of a population from a uniform sample of `m` of its `n` items, drawn without\n * replacement. The estimate is `scale * sum(values)`. Each run draws `m` values with replacement, as `bootstrap`\n * does. The deviation of each run from the sum of the sample gets the factor `scale * sqrt(1 - m / n)`, the finite\n * population correction. When `m` is `n`, the interval is the estimate.\n *\n * The sample has 2 values or more, and each value is finite. With the same seed, the result is equal to the\n * `bootstrap` of the same statistic, to the bit.\n *\n * The interval is narrow for a small sample. The draws give the variance of the sample with the divisor `m`, not\n * `m - 1`, so the width gets the factor `sqrt((m - 1) / m)`. The skew of the values adds to the miss. In the tests,\n * 400 samples of `m = 8` of `n = 40` hold the total 346 times (Wilson 0.828 to 0.895). At `m = 100` of `n = 200`,\n * the coverage agrees with 95%. For a total over the pairs of the items, use `uStatisticInterval`.\n */\nexport function sampleTotalInterval(values: readonly number[], options: SampleTotalOptions): Interval {\n const name = \"sampleTotalInterval\";\n const m = values.length;\n const n = options.population;\n if (m < 2) throw new RangeError(`${name}: the sample has 2 values or more, not ${m}.`);\n if (!Number.isSafeInteger(n) || n < m) throw new RangeError(`${name}: population is a whole number of ${m} (the sample) or more, not ${n}.`);\n for (const v of values) if (!Number.isFinite(v)) throw new RangeError(`${name}: each value is a finite number, not ${v}.`);\n const scale = options.scale ?? n / m;\n if (!(Number.isFinite(scale) && scale > 0)) throw new RangeError(`${name}: scale is a finite number more than 0, not ${scale}.`);\n const all = sum(values);\n const estimate = scale * all;\n const spread = Math.sqrt(1 - m / n) * scale;\n return bootstrap(values, (drawn) => estimate + spread * (sum(drawn) - all), options);\n}\n\n/** The sum of the values from the first to the last, as `values.reduce((s, t) => s + t, 0)`. */\nfunction sum(values: readonly number[]): number {\n let s = 0;\n for (const v of values) s += v;\n return s;\n}\n","/**\n * The shape of a sample: the count of its modes, and the smooth law with the highest likelihood. Use them to read the\n * law that a generator really emits, from its values and not from its label.\n */\nimport { mean, quantile, sd, sorted } from \"./describe.ts\";\n\n/** The smooth laws that `smoothLawScores` compares. Each law has 2 fitted numbers. */\nexport type SmoothLaw = \"uniform\" | \"normal\" | \"exponential\" | \"log-normal\" | \"pareto\";\n\n/** The value of one law at its fit. */\nexport interface SmoothLawScore {\n readonly law: SmoothLaw;\n /** The mean log density of the values at the fit of the law. A larger value is a better fit. */\n readonly meanLogDensity: number;\n}\n\n/** The options of `modeCount`. */\nexport interface ModeOptions {\n /**\n * The smallest share of the mass that makes a mode. The default is `0.1`. Half of the mass of the largest mode also\n * makes a mode, so many equal modes each count.\n */\n readonly minShare?: number;\n /** The valley between two peaks of the kernel is under this share of the lower peak. The default is `0.5`. */\n readonly valleyRatio?: number;\n}\n\n/** The points of the grid of the density estimate. */\nconst GRID = 96;\n/** The width of the kernel, in the factor of Silverman's rule. The value 0.9 of that rule hides close modes. */\nconst KERNEL_FACTOR = 0.45;\n/** The share of the values in a span of neighbours, as a factor of `n ** -0.2`. */\nconst SPAN_FACTOR = 0.1;\n/** The quantile of the spans. A low quantile stays in the clusters when most spans cross a gap. */\nconst SPAN_QUANTILE = 0.25;\n/**\n * The tight width replaces the width from the quartiles under this ratio. In seeded smooth samples the ratio stays over\n * 0.2, except for a heavy tail, and in tight clusters it stays under 0.02.\n */\nconst TIGHT_RATIO = 0.1;\n/** The kernels stop at this count of widths. */\nconst KERNEL_REACH = 3;\nconst HALF_LOG_2PI_E = 0.5 * Math.log(2 * Math.PI * Math.E);\n/** Two values closer than this share of the range are one value, so the noise of a float makes no new value. */\nconst SAME_VALUE = 1e-9;\n/** The most distinct values of a direct read of their counts. The grid resolves no more than this count of clusters. */\nconst FEW_VALUES = GRID / 4;\n/** The mean count of each value in a direct read. Under it the values are a small sample, and the kernel reads them. */\nconst MIN_REPEATS = 4;\n/** The fewest values that show the shape of a law. A sample with fewer values gives one mode for each value. */\nconst MIN_BELL_VALUES = 4;\n/** The ratio of the highest third of the counts to the lowest third, under which the counts are flat. */\nconst FLAT_RATIO = 3;\n/** The ratio of the means of the three parts of the list of counts, under which the counts have no shape. */\nconst SHAPE_RATIO = 1.75;\n/** A value with under this share of the sample is a tail. A rare value does not change the shape of the counts. */\nconst RARE_VALUE = 0.01;\n/** The fewest values of a hump of a rounded law. When most humps are narrower, the values are a discrete law. */\nconst MIN_HUMP_VALUES = 3;\n/** A count differs from another count at this z value. The two counts then differ by more than the noise of a sample. */\nconst COUNT_Z = 3;\n\n/** One hump of a series: its highest point, the sum of its points and the count of its points. */\ninterface Hump {\n readonly top: number;\n readonly mass: number;\n readonly points: number;\n}\n\n/**\n * This function gives the distances of the values from one end of the sample, in order. It takes the end that gives the\n * smaller list, so `x` and `-x` give one list and one count.\n */\nfunction fromOneEnd(values: readonly number[]): number[] {\n const order = sorted(values);\n const low = order[0]!;\n const high = order[order.length - 1]!;\n const rising = order.map((x) => x - low);\n const falling = order.map((x) => high - x).reverse();\n const first = rising.findIndex((x, i) => x !== falling[i]);\n return first >= 0 && falling[first]! < rising[first]! ? falling : rising;\n}\n\n/**\n * This function gives the width of the kernel. The width from the quartiles follows the distance between clusters, so\n * it hides many tight clusters. A low quantile of the spans of neighbouring values follows the width of a cluster.\n * The function uses the tight width only when it is far under the other width, so a smooth sample keeps its width.\n * The tight width stays over the grid step. No width goes under the median gap of the distinct values of a tight\n * sample. A step of rounding is no gap between clusters, so a rounded smooth sample keeps one mode at each size.\n */\nfunction kernelWidth(values: readonly number[], low: number, high: number): number {\n const count = values.length;\n const order = sorted(values);\n const scale = Math.min(quantile(values, 0.75) - quantile(values, 0.25), high - low) / 1.34;\n const wide = KERNEL_FACTOR * Math.max(scale, (high - low) / GRID) * count ** -0.2;\n const neighbours = Math.min(count - 1, Math.ceil(SPAN_FACTOR * count ** 0.8));\n const tight = quantile(order.slice(neighbours).map((x, i) => x - order[i]!), SPAN_QUANTILE);\n if (tight >= TIGHT_RATIO * wide) return wide;\n const distinct = order.filter((x, i) => i === 0 || x !== order[i - 1]);\n const resolution = quantile(distinct.slice(1).map((x, i) => x - distinct[i]!), 0.5);\n return Math.max(resolution, Math.min(wide, Math.max(tight, (high - low) / GRID)));\n}\n\n/** This function gives the Gaussian kernel density of the values on a grid. */\nfunction densityGrid(values: readonly number[], low: number, high: number): Float64Array {\n const width = kernelWidth(values, low, high);\n const start = low - KERNEL_REACH * width;\n const step = (high - low + 2 * KERNEL_REACH * width) / (GRID - 1);\n const density = new Float64Array(GRID);\n for (const x of values) {\n const first = Math.max(0, Math.floor((x - KERNEL_REACH * width - start) / step));\n const last = Math.min(GRID - 1, Math.ceil((x + KERNEL_REACH * width - start) / step));\n for (let i = first; i <= last; i++) {\n const u = (start + i * step - x) / width;\n density[i]! += Math.exp(-0.5 * u * u);\n }\n }\n return density;\n}\n\n/**\n * This function gives the humps of a series. It first gives each rise and fall one hump. Then it joins the two neighbours\n * with the closest valley, and again, until each valley has a closeness under the limit. The result has no direction,\n * because the order of the joins comes from the depth of the valleys and not from their position.\n */\nfunction humpsOf(series: ArrayLike<number>, closeness: (lower: number, valley: number) => number, limit: number): Hump[] {\n const humps: Hump[] = [];\n const valleys: number[] = [];\n let index = 0;\n while (index < series.length) {\n let top = index;\n while (top + 1 < series.length && series[top + 1]! >= series[top]!) top++;\n let end = top;\n while (end + 1 < series.length && series[end + 1]! < series[end]!) end++;\n let mass = 0;\n for (let i = index; i <= end; i++) mass += series[i]!;\n humps.push({ top: series[top]!, mass, points: end + 1 - index });\n if (end + 1 < series.length) valleys.push(series[end]!);\n index = end + 1;\n }\n while (valleys.length > 0) {\n const scores = valleys.map((valley, i) => closeness(Math.min(humps[i]!.top, humps[i + 1]!.top), valley));\n const closest = scores.indexOf(Math.max(...scores));\n if (scores[closest]! < limit) break;\n const [left, right] = [humps[closest]!, humps[closest + 1]!];\n humps.splice(closest, 2, { top: Math.max(left.top, right.top), mass: left.mass + right.mass, points: left.points + right.points });\n valleys.splice(closest, 1);\n }\n return humps;\n}\n\n/** This function gives the count of each distinct value, in the order of the values. */\nfunction valueCounts(values: readonly number[], low: number, high: number): number[] {\n const tie = SAME_VALUE * (high - low);\n const counts: number[] = [];\n let last = -Infinity;\n for (const x of sorted(values)) {\n if (x - last > tie) {\n counts.push(0);\n last = x;\n }\n counts[counts.length - 1]!++;\n }\n return counts;\n}\n\n/**\n * This function tells that the counts are flat. The highest third of the counts stays under `FLAT_RATIO` times the\n * lowest third, so a list of heavy and light values is not flat. The means of the first, the middle and the last third\n * of the list stay under `SHAPE_RATIO` of each other. The noise of a sample cancels in those means, and a bell does not.\n */\nfunction flatCounts(counts: readonly number[]): boolean {\n const order = [...counts].sort((a, b) => a - b);\n const third = Math.ceil(order.length / 3);\n if (mean(order.slice(-third)) >= FLAT_RATIO * mean(order.slice(0, third))) return false;\n const parts = [counts.slice(0, third), counts.slice(third, -third), counts.slice(-third)].filter((part) => part.length > 0).map((part) => mean(part));\n return Math.max(...parts) < SHAPE_RATIO * Math.min(...parts);\n}\n\n/** This function gives the closeness of a count to a valley: the negative of its height over the noise of a sample. */\nconst countCloseness = (lower: number, valley: number): number => -(lower - valley) / Math.sqrt(lower + valley);\n\n/**\n * This function counts the modes of a sample with few distinct values, from the counts of those values. The result does\n * not change with the size of the sample. Flat counts are a discrete law with one mode for each value, so the noise of\n * a sample does not take a value out. Counts with one rise and one fall are a rounded smooth law with one mode.\n */\nfunction fewValueModes(allCounts: readonly number[], total: number, minShare: number): number {\n const counts = allCounts.filter((count) => count / total >= RARE_VALUE);\n const each = counts.map((count) => count / total);\n const overLimit = (masses: readonly number[], limit: number): number => masses.filter((share) => share >= limit).length;\n if (counts.length < MIN_BELL_VALUES) return overLimit(each, Math.min(minShare, Math.max(...each) / 2));\n if (flatCounts(counts)) return overLimit(each, Math.min(minShare, quantile(each, 0.5) / FLAT_RATIO));\n const humps = humpsOf(counts, countCloseness, -COUNT_Z);\n const narrow = humps.filter((hump) => hump.points < MIN_HUMP_VALUES).length;\n const masses = 2 * narrow > humps.length ? each : humps.map((hump) => hump.mass / total);\n return overLimit(masses, Math.min(minShare, Math.max(...masses) / 2));\n}\n\n/**\n * This function gives the mass of each mode from a kernel estimate on a grid. Two peaks stay apart when the valley\n * between them is under `valleyRatio` of the lower peak.\n */\nfunction kernelMasses(values: readonly number[], low: number, high: number, valleyRatio: number): number[] {\n const density = densityGrid(values, low, high);\n const total = density.reduce((sum, d) => sum + d, 0);\n return humpsOf(density, (lower, valley) => valley / lower, valleyRatio).map((hump) => hump.mass / total);\n}\n\n/**\n * This function counts the modes of a sample. A mode counts when it holds `minShare` of the mass. The default counts the\n * modes that hold 10 percent, and a caller who needs all modes passes a smaller value. The result is at least 1. The\n * result is the same for `x` and `-x`.\n *\n * A sample with 24 or fewer distinct values, and 4 or more copies of each value on average, gets a direct read.\n * That read uses the counts of the values, and it does not change with the size of the sample.\n * It gives one mode for each value of a flat discrete law. So even groups give the count of the groups, and so does a\n * rounded uniform law with 24 or fewer steps. It gives one mode for each hump of a rounded smooth law.\n * The direct read of a sample with 3 or fewer values gives one mode for each value that holds the share.\n *\n * A kernel estimate on a grid reads each other sample. The grid has 96 points, so the kernel joins more than\n * approximately 24 evenly spaced clusters. A tight cluster also needs more than approximately `n ** 0.8 / 8` values for\n * a sample of `n` values. A cluster with an SD over 5 percent of the gap to the next cluster can join it.\n *\n * The function throws a RangeError for an empty list or for a value that is not finite.\n */\nexport function modeCount(values: readonly number[], options: ModeOptions = {}): number {\n const { minShare = 0.1, valleyRatio = 0.5 } = options;\n if (values.length === 0) throw new RangeError(\"modeCount: the list is empty.\");\n for (const v of values) if (!Number.isFinite(v)) throw new RangeError(\"modeCount: each value must be finite.\");\n const distances = fromOneEnd(values);\n const high = distances[distances.length - 1]!;\n if (high === 0) return 1;\n const counts = valueCounts(distances, 0, high);\n if (counts.length <= FEW_VALUES && values.length >= MIN_REPEATS * counts.length) return fewValueModes(counts, values.length, minShare);\n const masses = kernelMasses(distances, 0, high, valleyRatio);\n const limit = Math.min(minShare, Math.max(...masses) / 2);\n return masses.filter((share) => share >= limit).length;\n}\n\n/**\n * This function gives the mean log density of the values under each smooth law, at the closed-form fit of that law.\n * Each law has 2 fitted numbers, so the function adds no penalty. The uniform, the shifted exponential and the Pareto\n * law take the smallest value as their lower limit. This fitted end helps them at small sizes. All values are exact\n * maximum likelihoods.\n * The function throws a RangeError for an empty list, for a value that is not positive and finite, or for equal values.\n */\nexport function smoothLawScores(values: readonly number[]): readonly SmoothLawScore[] {\n if (values.length === 0) throw new RangeError(\"smoothLawScores: the list is empty.\");\n for (const v of values) if (!(v > 0 && Number.isFinite(v))) throw new RangeError(\"smoothLawScores: each value must be positive and finite.\");\n const logs = values.map((v) => Math.log(v));\n const low = quantile(values, 0);\n const high = quantile(values, 1);\n if (low === high) throw new RangeError(\"smoothLawScores: the values are equal, so no law has a density.\");\n const meanLog = mean(logs);\n const toExact = 0.5 * Math.log(values.length / (values.length - 1));\n const alpha = 1 / (meanLog - Math.log(low));\n return [\n { law: \"uniform\", meanLogDensity: -Math.log(high - low) },\n { law: \"normal\", meanLogDensity: -Math.log(sd(values)) - HALF_LOG_2PI_E + toExact },\n { law: \"exponential\", meanLogDensity: -Math.log(mean(values) - low) - 1 },\n { law: \"log-normal\", meanLogDensity: -Math.log(sd(logs)) - HALF_LOG_2PI_E - meanLog + toExact },\n { law: \"pareto\", meanLogDensity: Math.log(alpha) + alpha * Math.log(low) - (alpha + 1) * meanLog },\n ];\n}\n\n/**\n * This function gives the smooth law with the highest likelihood. Under 300 values the result is not reliable: the\n * normal and the log-normal law lose to the laws with a fitted end. The README gives the measured shares of correct\n * results. The function throws as `smoothLawScores` does.\n */\nexport function bestSmoothLaw(values: readonly number[]): SmoothLaw {\n return smoothLawScores(values).reduce((best, score) => (score.meanLogDensity > best.meanLogDensity ? score : best)).law;\n}\n","/**\n * The ridge solve of a least-squares problem from its normal equations. The caller gives the matrix `X'X` and the\n * vector `X'y`. Thus it can make them from sparse rows. It can also remove the sums of one fold of a cross-validation.\n * The solve uses a Cholesky factorization of `X'X + lambda * P`. The matrix `P` is the identity, with 0 on the\n * diagonal for each free coefficient, for example an intercept.\n */\n\nexport interface RidgeOptions {\n /** The indexes of the coefficients with no penalty, for example 0 for an intercept. The default is none. */\n readonly free?: readonly number[];\n}\n\n/**\n * The relative tolerance of the Cholesky pivots. A pivot is the squared length of the part of a column that is\n * orthogonal to the columns before it. The rounding error of a pivot is approximately 1e-16 times its diagonal value.\n * Thus a pivot of a dependent column is not exactly 0, and the tolerance is larger than that error.\n */\nconst PIVOT_TOLERANCE = 1e-12;\n\n/**\n * This function gives the coefficients `beta` that solve `(gram + lambda * P) beta = moment`.\n * - `gram` is the symmetric matrix `X'X` of size `k`, in row order. The function reads only its lower triangle.\n * - `moment` is the vector `X'y` of length `k`.\n * - With `lambda` 0, the result is the ordinary least-squares fit.\n *\n * The function does not change `gram` or `moment`. When the matrix is not positive definite, each coefficient is\n * NaN, as in `leastSquares`. The function throws a RangeError when `gram` does not have `k * k` values, and when\n * `k` is 0. It also throws for a value that is not finite, for a `lambda` below 0, and for a bad free index.\n */\nexport function ridgeSolve(gram: ArrayLike<number>, moment: ArrayLike<number>, lambda: number, options: RidgeOptions = {}): number[] {\n const k = moment.length;\n if (k === 0) throw new RangeError(\"ridgeSolve: the moment is empty.\");\n if (gram.length !== k * k) throw new RangeError(`ridgeSolve: the gram has ${gram.length} values, and a moment of length ${k} needs ${k * k}.`);\n if (!(lambda >= 0 && Number.isFinite(lambda))) throw new RangeError(`ridgeSolve: lambda is a finite number of 0 or more, not ${lambda}.`);\n const penalty = new Float64Array(k).fill(lambda);\n for (const i of options.free ?? []) {\n if (!Number.isSafeInteger(i) || i < 0 || i >= k) throw new RangeError(`ridgeSolve: a free index is a whole number from 0 to ${k - 1}, not ${i}.`);\n penalty[i] = 0;\n }\n const a = new Float64Array(k * k);\n for (let i = 0; i < k * k; i++) {\n const v = gram[i] as number;\n if (!Number.isFinite(v)) throw new RangeError(`ridgeSolve: the gram value ${i} is not finite.`);\n a[i] = v;\n }\n const x = new Float64Array(k);\n for (let i = 0; i < k; i++) {\n const v = moment[i] as number;\n if (!Number.isFinite(v)) throw new RangeError(`ridgeSolve: the moment value ${i} is not finite.`);\n x[i] = v;\n a[i * k + i] = (a[i * k + i] as number) + (penalty[i] as number);\n }\n if (!factor(a, k)) return new Array<number>(k).fill(Number.NaN);\n for (let i = 0; i < k; i++) {\n let s = x[i] as number;\n for (let j = 0; j < i; j++) s -= (a[i * k + j] as number) * (x[j] as number);\n x[i] = s / (a[i * k + i] as number);\n }\n for (let i = k - 1; i >= 0; i--) {\n let s = x[i] as number;\n for (let j = i + 1; j < k; j++) s -= (a[j * k + i] as number) * (x[j] as number);\n x[i] = s / (a[i * k + i] as number);\n }\n return Array.from(x);\n}\n\n/**\n * This function writes the Cholesky factor `L` of `a` into its lower triangle, with `a = L L'`. It returns false when\n * a pivot is not more than the tolerance times the diagonal value of its column.\n */\nexport function factor(a: Float64Array, k: number): boolean {\n for (let j = 0; j < k; j++) {\n const diagonal = a[j * k + j] as number;\n let d = diagonal;\n for (let m = 0; m < j; m++) d -= (a[j * k + m] as number) ** 2;\n if (!(d > PIVOT_TOLERANCE * Math.abs(diagonal)) || !(d > 0)) return false;\n const l = Math.sqrt(d);\n a[j * k + j] = l;\n for (let i = j + 1; i < k; i++) {\n let s = a[i * k + j] as number;\n for (let m = 0; m < j; m++) s -= (a[i * k + m] as number) * (a[j * k + m] as number);\n a[i * k + j] = s / l;\n }\n }\n return true;\n}\n","/**\n * The format `response-records/1`: the measured points of a function of many dimensions, with a fitted model and the\n * held-out error of each measure. A record is plain JSON. A browser reads it with `parseResponseRecord`, and it\n * evaluates the models with `predictResponse`. A view shows one dimension with `sliceResponse`, or two dimensions\n * with `surfaceResponse`, and it holds the other dimensions.\n *\n * This file has the types and the pure functions that read a record. `response-parse.ts` has the validator, and\n * `response-fit.ts` has the fit. The three files use no Node import, no clock and no `Math.random`.\n *\n * A model calculates integer powers with multiplication, so its terms are equal in each JavaScript engine. A log\n * scale uses `Math.log10` and `10 ** x`. An engine can give a different last bit for these two operations.\n */\nimport { mean, quantile } from \"./describe.ts\";\n\n/** The value of the field `schema` of a record. */\nexport const RESPONSE_RECORDS_SCHEMA = \"response-records/1\";\n\n/** The value of a dimension at a point: a number, or the text of a level. */\nexport type ResponseValue = number | string;\n\n/** The value of a dimension at a place. The value `null` means that a conditional dimension is absent there. */\nexport type ResponseInputValue = ResponseValue | null;\n\n/** The condition of a dimension: the dimension has a value only at these levels of its parent. */\nexport interface ResponseWhen {\n /** The id of the parent: a categorical or ordinal dimension with no condition. */\n readonly dimension: string;\n readonly levels: readonly ResponseValue[];\n}\n\n/** The fields of each kind of dimension. */\nexport interface ResponseDimensionBase {\n /** The key of the dimension in the values of a point. */\n readonly id: string;\n /** The name that a view shows. */\n readonly label: string;\n /** The unit. An empty string means that the dimension has no unit. */\n readonly unit: string;\n /** With this field, a point has a value only at the stated levels of the parent. Each other point has `null`. */\n readonly when?: ResponseWhen;\n}\n\n/** A dimension with each number in a range. */\nexport interface ContinuousDimension extends ResponseDimensionBase {\n readonly kind: \"continuous\";\n /** The smallest and the largest value. The first is less than the second. */\n readonly range: readonly [number, number];\n /** When true, a model and an axis use the base-10 logarithm of the value. All of the range is above 0. */\n readonly log?: boolean;\n}\n\n/** A dimension with levels in order. Number levels ascend. A model reads a text level as its position. */\nexport interface OrdinalDimension extends ResponseDimensionBase {\n readonly kind: \"ordinal\";\n readonly levels: readonly number[] | readonly string[];\n /** When true, a model uses the base-10 logarithm of the level. The levels are numbers above 0. */\n readonly log?: boolean;\n}\n\n/** A dimension with levels that have no order, for example the arms of a benchmark. */\nexport interface CategoricalDimension extends ResponseDimensionBase {\n readonly kind: \"categorical\";\n readonly levels: readonly string[];\n}\n\n/** A dimension of a record. */\nexport type ResponseDimension = ContinuousDimension | OrdinalDimension | CategoricalDimension;\n\n/** A measured value of each point. */\nexport interface ResponseMeasure {\n /** The key of the measure in the measures of a point. */\n readonly id: string;\n readonly label: string;\n /** The unit. An empty string means that the measure has no unit. */\n readonly unit: string;\n /** The better direction of the value. The value `none` means that no direction is better. */\n readonly direction: \"higher\" | \"lower\" | \"none\";\n /**\n * The low and the high end of the possible values, for example `[0, 1]` for a share. Each measured value is in this\n * range. A view clips its fitted values to it, and a fit does not use it.\n */\n readonly range?: readonly [number, number];\n}\n\n/** A declared reason that a measure is absent, for example infeasible, unsupported or out of budget. */\nexport interface ResponseReason {\n /** The key of the reason in the field `absent` of a point. */\n readonly id: string;\n /** The name that a view shows. */\n readonly label: string;\n}\n\n/** One measured point. */\nexport interface ResponsePoint {\n readonly id: string;\n /** The value of each dimension. */\n readonly values: Readonly<Record<string, ResponseInputValue>>;\n /** The value of each measure. The value `null` means that the run did not give the measure at this point. */\n readonly measures: Readonly<Record<string, number | null>>;\n /** The points of one group stay on one side of each split, for example the repeats of one seed. */\n readonly group?: string;\n /** The reason of a measure with `null`: a map from the id of the measure to the id of a declared reason. */\n readonly absent?: Readonly<Record<string, string>>;\n}\n\n/** One factor of a term: a power of a number dimension, or 1 at a level and 0 at each other level. */\nexport type ResponseFactor = { readonly dimension: string; readonly power: number } | { readonly dimension: string; readonly level: ResponseValue };\n\n/** The fields of each kind of input of a ridge model. */\nexport interface RidgeInputBase {\n readonly dimension: string;\n /** When true, the dimension is conditional, so `null` is a good value. Each term of an absent dimension is 0. */\n readonly conditional?: boolean;\n}\n\n/** The coordinate of a number dimension: the value (or its logarithm), less `center`, divided by `spread`. */\nexport interface RidgeNumberInput extends RidgeInputBase {\n readonly kind: \"number\";\n readonly center: number;\n readonly spread: number;\n readonly log?: boolean;\n}\n\n/** The coordinate of an ordinal dimension with text levels: the position of the level, as in `RidgeNumberInput`. */\nexport interface RidgeRankInput extends RidgeInputBase {\n readonly kind: \"rank\";\n readonly levels: readonly string[];\n readonly center: number;\n readonly spread: number;\n}\n\n/** A categorical dimension: the factors of its levels are the one-hot columns. */\nexport interface RidgeLevelInput extends RidgeInputBase {\n readonly kind: \"level\";\n readonly levels: readonly string[];\n}\n\n/** An input of a ridge model. The model holds it, so `predictResponse` needs no record. */\nexport type RidgeInput = RidgeNumberInput | RidgeRankInput | RidgeLevelInput;\n\n/** A term of a ridge model: the product of its factors, times the weight. */\nexport interface RidgeTerm {\n readonly factors: readonly ResponseFactor[];\n readonly weight: number;\n}\n\n/** The fields of each kind of model. */\nexport interface ResponseModelBase {\n /** The id of the measure of the model. */\n readonly measure: string;\n /** With `log`, the model and the held-out errors use the base-10 logarithm of the measure. */\n readonly scale: \"linear\" | \"log\";\n /** With the scale `log`, the fit gave this value to each smaller measured value. */\n readonly floor?: number;\n}\n\n/** A ridge fit over a stated expansion: the intercept, plus the sum of the terms. */\nexport interface RidgeResponseModel extends ResponseModelBase {\n readonly kind: \"ridge\";\n /** The penalty of the fit. */\n readonly lambda: number;\n readonly inputs: readonly RidgeInput[];\n readonly intercept: number;\n readonly terms: readonly RidgeTerm[];\n}\n\n/** One cell of a table model. */\nexport interface ResponseTableCell {\n /** The value of each dimension of the table, in the order of its `dimensions`. An absent dimension has `null`. */\n readonly at: readonly ResponseInputValue[];\n /** The mean of the measured values of the cell, on the scale of the model. */\n readonly value: number;\n /** The number of points of the cell. */\n readonly n: number;\n}\n\n/** The mean of each measured combination of levels. */\nexport interface TableResponseModel extends ResponseModelBase {\n readonly kind: \"table\";\n readonly dimensions: readonly string[];\n /** The ids of the dimensions of the table with a condition. Only these dimensions take `null`. */\n readonly conditional?: readonly string[];\n readonly cells: readonly ResponseTableCell[];\n /** The value of a combination with no cell: the mean of all the fitted points, on the scale of the model. */\n readonly fallback: number;\n}\n\n/** A model that a browser evaluates from plain JSON. */\nexport type ResponseModel = RidgeResponseModel | TableResponseModel;\n\n/** The held-out error of one measure in one fold, on the scale of the model. */\nexport interface ResponseFoldError {\n /** The number of held-out points with a value of the measure. */\n readonly n: number;\n /** The mean absolute error. */\n readonly mae: number;\n /** The root mean square error. */\n readonly rmse: number;\n /** The mean absolute error of the mean of the training points, used as the prediction. */\n readonly baselineMae: number;\n}\n\n/** One split of the points. The fold held out `heldOut`, and it fit a model on the other points. */\nexport interface ResponseFold {\n /** The ids of the held-out points. */\n readonly heldOut: readonly string[];\n /** The error of each measure. A measure with no held-out point or no training point has no entry. */\n readonly errors: Readonly<Record<string, ResponseFoldError>>;\n /**\n * The prediction of each held-out point with a value, on the scale of the model. The keys are the id of the measure,\n * then the id of the point. The model of this fold gave them. Only the option `outOfFold` of `fitResponse` writes this field.\n */\n readonly predictions?: Readonly<Record<string, Readonly<Record<string, number>>>>;\n}\n\n/** The data of a record, before a fit. */\nexport interface ResponseData {\n readonly schema: typeof RESPONSE_RECORDS_SCHEMA;\n readonly name: string;\n readonly dimensions: readonly ResponseDimension[];\n readonly measures: readonly ResponseMeasure[];\n /** The reasons that a measure of a point can be absent. Each id in the field `absent` of a point is in this list. */\n readonly reasons?: readonly ResponseReason[];\n readonly points: readonly ResponsePoint[];\n}\n\n/** A record: the data, one model for each measure, and the folds. */\nexport interface ResponseRecord extends ResponseData {\n readonly models: readonly ResponseModel[];\n readonly folds: readonly ResponseFold[];\n}\n\n/** The held-out error of one measure over all the folds, on the scale of the model. */\nexport interface ResponseHeldOutError {\n /** The number of held-out points. */\n readonly n: number;\n /** The number of folds with this measure. */\n readonly folds: number;\n /** The mean absolute error of all the held-out points. */\n readonly mae: number;\n /** The root mean square error of all the held-out points. */\n readonly rmse: number;\n /** The mean absolute error of the baseline. */\n readonly baselineMae: number;\n /** The value `1 - mae / baselineMae`. The value 0 is no better than the mean. A baseline of 0 gives `null`. */\n readonly skill: number | null;\n}\n\n/** The options of `sliceResponse` and `surfaceResponse`. */\nexport interface ResponseViewOptions {\n /** The value of each held dimension. Each other dimension takes its usual value, as `sliceResponse` tells. */\n readonly hold?: Readonly<Record<string, ResponseInputValue>>;\n /** The number of values on a continuous axis, 2 or more. The default is 33. */\n readonly steps?: number;\n /**\n * The share of the range of a held number dimension in which a point matches. A log dimension uses the log scale.\n * The default is 0: only an equal value matches.\n */\n readonly tolerance?: number;\n /** The half width of the band, as a multiple of the held-out root mean square error. The default is 1. */\n readonly width?: number;\n}\n\n/** The options of `sliceResponse`. */\nexport interface ResponseSliceOptions extends ResponseViewOptions {\n /** The id of the dimension of the curve. */\n readonly vary: string;\n}\n\n/** The options of `surfaceResponse`. */\nexport interface ResponseSurfaceOptions extends ResponseViewOptions {\n /** The ids of the two dimensions of the surface: first the x axis, then the y axis. */\n readonly vary: readonly [string, string];\n}\n\n/**\n * The fitted value at one place, with its band. The band is the mean error of the model, and `nearest` tells how far\n * the place is from a measurement.\n */\nexport interface ResponseBand {\n readonly value: number;\n readonly low: number;\n readonly high: number;\n /**\n * The distance from this place to the nearest measured point with a value of the measure, from 0 to 1. The value 0\n * means that a point was measured here. A number or rank dimension counts as its share of the axis. A different\n * categorical level counts 1, and an absent value against a present value counts 1. The distance is the largest\n * count over the dimensions.\n */\n readonly nearest: number;\n /** This field is true when the measure has a `range` and the view moved `value`, `low` or `high` into it. */\n readonly clipped?: true;\n}\n\n/** One place of a curve. */\nexport interface ResponseCurvePoint extends ResponseBand {\n /** The value of the varied dimension. */\n readonly at: ResponseValue;\n}\n\n/** A measured point of a slice. */\nexport interface ResponseSlicePoint {\n readonly id: string;\n /** The value of the varied dimension. */\n readonly at: ResponseValue;\n readonly value: number;\n readonly group?: string;\n}\n\n/** A point of a slice that matches the held values and has no value of the measure. */\nexport interface ResponseAbsentPoint {\n readonly id: string;\n /** The value of the varied dimension. */\n readonly at: ResponseValue;\n /** The id of the declared reason. The value `null` means that the point states no reason. */\n readonly reason: string | null;\n readonly group?: string;\n}\n\n/** The fitted curve over one dimension, and the measured points that match the held values. */\nexport interface ResponseSlice {\n readonly measure: string;\n readonly vary: string;\n /** The value of each other dimension. */\n readonly held: Readonly<Record<string, ResponseInputValue>>;\n readonly curve: readonly ResponseCurvePoint[];\n readonly points: readonly ResponseSlicePoint[];\n /** The points that match the held values and have no value of the measure, each with its reason. */\n readonly absent: readonly ResponseAbsentPoint[];\n readonly error: ResponseHeldOutError;\n /** The number of places of `curve` with the field `clipped`. */\n readonly clipped: number;\n}\n\n/** A measured point of a surface. */\nexport interface ResponseSurfacePoint {\n readonly id: string;\n /** The values of the two varied dimensions. */\n readonly at: readonly [ResponseValue, ResponseValue];\n readonly value: number;\n readonly group?: string;\n}\n\n/** A point of a surface that matches the held values and has no value of the measure. */\nexport interface ResponseSurfaceAbsentPoint {\n readonly id: string;\n /** The values of the two varied dimensions. */\n readonly at: readonly [ResponseValue, ResponseValue];\n /** The id of the declared reason. The value `null` means that the point states no reason. */\n readonly reason: string | null;\n readonly group?: string;\n}\n\n/** The fitted surface over two dimensions, and the measured points that match the held values. */\nexport interface ResponseSurface {\n readonly measure: string;\n readonly vary: readonly [string, string];\n /** The value of each other dimension. */\n readonly held: Readonly<Record<string, ResponseInputValue>>;\n readonly x: readonly ResponseValue[];\n readonly y: readonly ResponseValue[];\n /** One row for each value of `y`. Each row has one cell for each value of `x`. */\n readonly cells: readonly (readonly ResponseBand[])[];\n readonly points: readonly ResponseSurfacePoint[];\n /** The points that match the held values and have no value of the measure, each with its reason. */\n readonly absent: readonly ResponseSurfaceAbsentPoint[];\n readonly error: ResponseHeldOutError;\n /** The number of places of `cells` with the field `clipped`. */\n readonly clipped: number;\n}\n\n/** This function gives the key of the group of a point. A point without a group is a group of its own. */\nexport function groupKey(point: ResponsePoint): string {\n return point.group === undefined ? `point ${JSON.stringify(point.id)}` : `group ${JSON.stringify(point.group)}`;\n}\n\n/** This function gives true for a dimension whose value is a number. */\nexport function isNumberDimension(dimension: ResponseDimension): dimension is ContinuousDimension | (OrdinalDimension & { readonly levels: readonly number[] }) {\n return dimension.kind === \"continuous\" || (dimension.kind === \"ordinal\" && typeof dimension.levels[0] === \"number\");\n}\n\n/** This function gives the low and the high end of a dimension on the numeric axis of a model. */\nexport function axisEnds(dimension: ResponseDimension): readonly [number, number] {\n if (!isNumberDimension(dimension)) return [0, dimension.levels.length - 1];\n const values = dimension.kind === \"continuous\" ? dimension.range : dimension.levels;\n const low = values[0] as number;\n const high = values[values.length - 1] as number;\n return dimension.log === true ? [Math.log10(low), Math.log10(high)] : [low, high];\n}\n\n/** This function gives true when a place has the condition of a dimension. A dimension with no condition is present. */\nexport function whenHolds(dimension: ResponseDimension, values: Readonly<Record<string, unknown>>): boolean {\n return dimension.when === undefined || dimension.when.levels.includes(values[dimension.when.dimension] as ResponseValue);\n}\n\n/** This function gives the reason that `value` is not a value of `dimension`. It gives `undefined` for a good value. */\nexport function valueFault(dimension: ResponseDimension, value: unknown): string | undefined {\n if (dimension.kind === \"continuous\") {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return `the value ${JSON.stringify(value)} is not a finite number`;\n const [low, high] = dimension.range;\n return value < low || value > high ? `the value ${value} is outside the range ${low} to ${high}` : undefined;\n }\n return (dimension.levels as readonly unknown[]).includes(value) ? undefined : `the value ${JSON.stringify(value)} is not a level of the dimension`;\n}\n\n/**\n * This function gives the input of a dimension, for each kind of model. It reads only a field of the object, not of\n * its prototype. It refuses `null` at a dimension with no condition, so a mistake of a caller cannot give a quiet value.\n */\nfunction inputValue(inputs: Readonly<Record<string, ResponseInputValue>>, dimension: string, conditional: boolean): ResponseInputValue {\n if (!Object.hasOwn(inputs, dimension)) throw new RangeError(`predictResponse: the inputs have no value of the dimension \"${dimension}\".`);\n const value = inputs[dimension] as ResponseInputValue;\n if (value === null && !conditional) throw new RangeError(`predictResponse: the dimension \"${dimension}\" has no condition, so it needs a value, not null.`);\n return value;\n}\n\n/** This function gives the coordinate of one input of a ridge model. An absent input has `null`, and a level has 0. */\nfunction coordinate(input: RidgeInput, value: ResponseInputValue): number | null {\n if (value === null) return null;\n const bad = (reason: string): RangeError => new RangeError(`predictResponse: the value ${JSON.stringify(value)} of the dimension \"${input.dimension}\" ${reason}.`);\n if (input.kind === \"number\") {\n if (typeof value !== \"number\" || !Number.isFinite(value)) throw bad(\"is not a finite number\");\n if (input.log === true && value <= 0) throw bad(\"is not above 0, and the dimension has a log scale\");\n return ((input.log === true ? Math.log10(value) : value) - input.center) / input.spread;\n }\n const position = input.levels.indexOf(value as string);\n if (position < 0) throw bad(\"is not a level of the model\");\n return input.kind === \"rank\" ? (position - input.center) / input.spread : 0;\n}\n\n/** This function gives the coordinate of each input of a ridge model. */\nexport function coordinates(inputs: readonly RidgeInput[], values: Readonly<Record<string, ResponseInputValue>>): Map<string, number | null> {\n return new Map(inputs.map((input) => [input.dimension, coordinate(input, inputValue(values, input.dimension, input.conditional === true))]));\n}\n\n/**\n * This function gives the product of the factors of a term at a place. A power is a loop of multiplications. A term\n * with an absent dimension is 0, so the columns of the levels of the parent carry the mean of that place.\n */\nexport function product(factors: readonly ResponseFactor[], at: ReadonlyMap<string, number | null>, values: Readonly<Record<string, ResponseInputValue>>): number {\n let value = 1;\n for (const factor of factors) {\n const c = at.get(factor.dimension) as number | null;\n if (c === null) return 0;\n if (\"level\" in factor) {\n if (values[factor.dimension] !== factor.level) return 0;\n } else for (let i = 0; i < factor.power; i++) value *= c;\n }\n return value;\n}\n\n/** This function gives the prediction on the scale of the model. The sum with 0 removes a negative zero. */\nexport function predictScaled(model: ResponseModel, inputs: Readonly<Record<string, ResponseInputValue>>): number {\n if (model.kind === \"table\") {\n const at = model.dimensions.map((d) => inputValue(inputs, d, model.conditional?.includes(d) === true));\n return model.cells.find((cell) => cell.at.every((v, i) => v === at[i]))?.value ?? model.fallback;\n }\n const at = coordinates(model.inputs, inputs);\n let sum = model.intercept;\n for (const term of model.terms) sum += term.weight * product(term.factors, at, inputs);\n return sum + 0;\n}\n\n/** This function changes a measured value to the scale of a model. A log scale with a floor lifts each smaller value. */\nexport function toModelScale(value: number, log: boolean, floor: number | undefined): number {\n return log ? Math.log10(Math.max(value, floor ?? value)) : value;\n}\n\n/** This function changes a value from the scale of the model to the scale of the measure. */\nfunction unscale(model: ResponseModel, value: number): number {\n return model.scale === \"log\" ? 10 ** value : value;\n}\n\n/**\n * This function gives the value of a model at `inputs`, on the scale of the measure. The inputs have a value for each\n * dimension that the model reads. An absent conditional dimension has `null`. A table model gives its `fallback` for a\n * combination with no cell.\n *\n * The function throws a RangeError for a missing input and for a value that is not a number or a level of the model.\n * It throws for `null` at a dimension with no condition, for each kind of model. It also throws for a value at or below\n * 0 on a log scale. A number outside the range of the record is good, so the\n * function extrapolates.\n */\nexport function predictResponse(model: ResponseModel, inputs: Readonly<Record<string, ResponseInputValue>>): number {\n return unscale(model, predictScaled(model, inputs));\n}\n\n/**\n * This function gives the held-out error of a measure over all the folds. Each point has the same weight, so a small\n * fold has a small effect. The function throws a RangeError when no fold has the measure.\n */\nexport function heldOutError(record: Pick<ResponseRecord, \"folds\">, measure: string): ResponseHeldOutError {\n let n = 0;\n let folds = 0;\n let absolute = 0;\n let square = 0;\n let baseline = 0;\n for (const fold of record.folds) {\n if (!Object.hasOwn(fold.errors, measure)) continue;\n const error = fold.errors[measure] as ResponseFoldError;\n n += error.n;\n folds += 1;\n absolute += error.n * error.mae;\n square += error.n * error.rmse * error.rmse;\n baseline += error.n * error.baselineMae;\n }\n if (n === 0) throw new RangeError(`heldOutError: no fold has an error of the measure \"${measure}\".`);\n const mae = absolute / n;\n const baselineMae = baseline / n;\n return { n, folds, mae, rmse: Math.sqrt(square / n), baselineMae, skill: baselineMae > 0 ? 1 - mae / baselineMae : null };\n}\n\n/** This function gives the stored predictions of a measure in a fold. A fold with no predictions gives `undefined`. */\nfunction predictionsOf(fold: ResponseFold, measure: string): Readonly<Record<string, number>> | undefined {\n return fold.predictions !== undefined && Object.hasOwn(fold.predictions, measure) ? fold.predictions[measure] : undefined;\n}\n\n/**\n * This function gives the held-out error of a chosen set of points, on the scale of the model. It uses the stored\n * predictions of the option `outOfFold`. Thus a reader can get the error of one cell. The result has the fields of\n * `heldOutError`, and the set of all the points gives the same values to the rounding of the sums.\n *\n * Each point counts at most once. A point with no value of the measure, or with no prediction, adds nothing to `n`.\n * The baseline of a point is the mean of the training points of its fold.\n *\n * The function throws a RangeError for an unknown measure and for a record with no predictions of the measure. It\n * also throws for an unknown id, for a repeated id, and for a set with no point to score.\n */\nexport function heldOutErrorAt(record: ResponseRecord, measure: string, ids: readonly string[]): ResponseHeldOutError {\n const model = record.models.find((m) => m.measure === measure);\n if (model === undefined) throw new RangeError(`heldOutErrorAt: the record has no model of the measure \"${measure}\".`);\n if (!record.folds.some((fold) => predictionsOf(fold, measure) !== undefined)) throw new RangeError(`heldOutErrorAt: the record has no predictions of the measure \"${measure}\". Fit it with the option outOfFold.`);\n const chosen = new Set(ids);\n if (chosen.size !== ids.length) throw new RangeError(\"heldOutErrorAt: the list of ids has a repeated id.\");\n const points = new Map(record.points.map((p) => [p.id, p]));\n for (const id of ids) if (!points.has(id)) throw new RangeError(`heldOutErrorAt: the record has no point \"${id}\".`);\n const scaled = (point: ResponsePoint): number | undefined => {\n const value = point.measures[measure];\n return typeof value === \"number\" ? toModelScale(value, model.scale === \"log\", model.floor) : undefined;\n };\n let n = 0;\n let folds = 0;\n let absolute = 0;\n let square = 0;\n let baselineSum = 0;\n for (const fold of record.folds) {\n const predicted = predictionsOf(fold, measure);\n if (predicted === undefined) continue;\n const scored = fold.heldOut.filter((id) => chosen.has(id) && Object.hasOwn(predicted, id));\n if (scored.length === 0) continue;\n const held = new Set(fold.heldOut);\n const baseline = mean(record.points.flatMap((p) => (held.has(p.id) || scaled(p) === undefined ? [] : [scaled(p) as number])));\n folds += 1;\n for (const id of scored) {\n const y = scaled(points.get(id) as ResponsePoint) as number;\n const error = y - (predicted[id] as number);\n n += 1;\n absolute += Math.abs(error);\n square += error * error;\n baselineSum += Math.abs(y - baseline);\n }\n }\n if (n === 0) throw new RangeError(`heldOutErrorAt: no chosen point has a prediction of the measure \"${measure}\".`);\n const mae = absolute / n;\n const baselineMae = baselineSum / n;\n return { n, folds, mae, rmse: Math.sqrt(square / n), baselineMae, skill: baselineMae > 0 ? 1 - mae / baselineMae : null };\n}\n\n/** The parts of a slice or a surface that do not depend on the number of varied dimensions. */\ninterface Frame {\n readonly held: Readonly<Record<string, ResponseInputValue>>;\n readonly axes: readonly (readonly ResponseValue[])[];\n readonly matched: readonly ResponsePoint[];\n /** The points that match the held values and have no value of the measure. */\n readonly missing: readonly ResponsePoint[];\n readonly error: ResponseHeldOutError;\n readonly band: (inputs: Readonly<Record<string, ResponseInputValue>>) => ResponseBand;\n}\n\n/**\n * This function gives the usual value of a dimension: a measured median, or the most common level among `among`. A\n * tie gives the first level. A dimension with no measured value gives its low end or its first level.\n */\nfunction usualValue(dimension: ResponseDimension, points: readonly ResponsePoint[], among?: readonly ResponseValue[]): ResponseValue {\n const values = points.flatMap((p) => (p.values[dimension.id] === null ? [] : [p.values[dimension.id] as ResponseValue]));\n if (dimension.kind === \"continuous\") return values.length === 0 ? dimension.range[0] : quantile(values as number[], 0.5, \"nearest-rank\");\n const levels = (dimension.levels as readonly ResponseValue[]).filter((level) => among === undefined || among.includes(level));\n let best = levels[0] as ResponseValue;\n let most = 0;\n for (const level of levels) {\n const count = values.filter((v) => v === level).length;\n if (count > most) [best, most] = [level, count];\n }\n return best;\n}\n\n/** The place of a value on the axis of its dimension: a share of the axis, a categorical level, or `null`. */\ntype AxisPlace = number | string | null;\n\n/** This function gives the place of a value on its axis. A number or a rank is a share of the axis, from 0 to 1. */\nfunction axisPlace(dimension: ResponseDimension, value: ResponseInputValue): AxisPlace {\n if (value === null || dimension.kind === \"categorical\") return value;\n const [low, high] = axisEnds(dimension);\n if (high === low) return 0;\n if (!isNumberDimension(dimension)) return (dimension.levels as readonly ResponseValue[]).indexOf(value) / high;\n return ((dimension.log === true ? Math.log10(value as number) : (value as number)) - low) / (high - low);\n}\n\n/** This function gives the count of one dimension between two places: their distance, or 1 when they do not compare. */\nconst axisGap = (a: AxisPlace, b: AxisPlace): number => (a === b ? 0 : typeof a === \"number\" && typeof b === \"number\" ? Math.abs(a - b) : 1);\n\n/**\n * This function gives a function of the field `nearest` of a band. A place compares with each point that has a value\n * of the measure. A point stops at the first count that is not less than the best distance so far.\n */\nfunction nearestOf(dimensions: readonly ResponseDimension[], points: readonly ResponsePoint[], measure: string): (place: Readonly<Record<string, ResponseInputValue>>) => number {\n const rows = points.filter((p) => typeof p.measures[measure] === \"number\").map((p) => dimensions.map((d) => axisPlace(d, p.values[d.id] as ResponseInputValue)));\n return (place) => {\n const here = dimensions.map((d) => axisPlace(d, place[d.id] as ResponseInputValue));\n let best = 1;\n for (const row of rows) {\n let far = 0;\n for (let i = 0; i < here.length && far < best; i++) far = Math.max(far, axisGap(row[i] as AxisPlace, here[i] as AxisPlace));\n if (far < best) best = far;\n }\n return best;\n };\n}\n\n/** This function gives the levels that the parent of each varied conditional dimension needs. */\nfunction neededLevels(name: string, varied: readonly ResponseDimension[], vary: readonly string[]): ReadonlyMap<string, readonly ResponseValue[]> {\n const needed = new Map<string, readonly ResponseValue[]>();\n for (const { id, when } of varied) {\n if (when === undefined) continue;\n if (vary.includes(when.dimension)) throw new RangeError(`${name}: the dimension \"${id}\" has a value only at some levels of \"${when.dimension}\", so hold \"${when.dimension}\".`);\n const earlier = needed.get(when.dimension);\n needed.set(when.dimension, earlier === undefined ? when.levels : earlier.filter((level) => when.levels.includes(level)));\n }\n return needed;\n}\n\n/** This function gives the value of each dimension that does not vary. `sliceResponse` tells the rules. */\nfunction heldValues(name: string, record: ResponseRecord, vary: readonly string[], hold: Readonly<Record<string, ResponseInputValue>>, needed: ReadonlyMap<string, readonly ResponseValue[]>): Readonly<Record<string, ResponseInputValue>> {\n const others = record.dimensions.filter((d) => !vary.includes(d.id));\n const plain = new Map(others.filter((d) => d.when === undefined).map((d) => [d.id, (Object.hasOwn(hold, d.id) ? hold[d.id] : usualValue(d, record.points, needed.get(d.id))) as ResponseValue]));\n for (const [parent, levels] of needed) {\n const value = plain.get(parent) as ResponseValue;\n if (!levels.includes(value)) throw new RangeError(`${name}: a varied dimension needs \"${parent}\" at one of ${JSON.stringify(levels)}, not ${JSON.stringify(value)}.`);\n }\n const valueOf = ({ id, when }: ResponseDimension): ResponseInputValue => {\n if (when === undefined) return plain.get(id) as ResponseValue;\n if (!vary.includes(when.dimension) && !when.levels.includes(plain.get(when.dimension) as ResponseValue)) return null;\n const value = Object.hasOwn(hold, id) ? (hold[id] as ResponseInputValue) : usualValue(record.dimensions.find((d) => d.id === id) as ResponseDimension, record.points);\n if (value === null) throw new RangeError(`${name}: the held dimension \"${id}\" is null, and a level of \"${when.dimension}\" in this view needs a value.`);\n return value;\n };\n return Object.fromEntries(others.map((d) => [d.id, valueOf(d)]));\n}\n\n/** This function refuses a bad option `steps`. */\nfunction checkSteps(name: string, steps: number): void {\n if (!Number.isSafeInteger(steps) || steps < 2) throw new RangeError(`${name}: steps is a whole number of 2 or more, not ${steps}.`);\n}\n\n/** This function gives a value inside a range. */\nconst clip = (value: number, [low, high]: readonly [number, number]): number => Math.min(high, Math.max(low, value));\n\n/** This function gives the values of an axis: each level, or `steps` equal distances on the scale of the dimension. */\nfunction axisValues(dimension: ResponseDimension, steps: number): readonly ResponseValue[] {\n if (dimension.kind !== \"continuous\") return dimension.levels;\n const [low, high] = dimension.range;\n const [a, b] = axisEnds(dimension);\n return Array.from({ length: steps }, (_, i) => {\n if (i === 0) return low;\n if (i === steps - 1) return high;\n const x = a + ((b - a) * i) / (steps - 1);\n return dimension.log === true ? 10 ** x : x;\n });\n}\n\n/** This function gives true when the value of a point matches a held value of a dimension. */\nfunction matches(dimension: ResponseDimension, value: ResponseInputValue, held: ResponseInputValue, tolerance: number): boolean {\n if (typeof value !== \"number\" || typeof held !== \"number\") return value === held;\n const [low, high] = axisEnds(dimension);\n const log = dimension.kind !== \"categorical\" && dimension.log === true;\n return Math.abs(log ? Math.log10(value) - Math.log10(held) : value - held) <= tolerance * (high - low);\n}\n\n/** This function examines the request of a view, and it gives the parts that the two views share. */\nfunction frameOf(name: string, record: ResponseRecord, measure: string, vary: readonly string[], options: ResponseViewOptions): Frame {\n const { hold = {}, steps = 33, tolerance = 0, width = 1 } = options;\n checkSteps(name, steps);\n if (!(Number.isFinite(tolerance) && tolerance >= 0)) throw new RangeError(`${name}: tolerance is a finite number of 0 or more, not ${tolerance}.`);\n if (!(Number.isFinite(width) && width >= 0)) throw new RangeError(`${name}: width is a finite number of 0 or more, not ${width}.`);\n const model = record.models.find((m) => m.measure === measure);\n if (model === undefined) throw new RangeError(`${name}: the record has no model of the measure \"${measure}\".`);\n const known = (id: string): ResponseDimension => {\n const dimension = record.dimensions.find((d) => d.id === id);\n if (dimension === undefined) throw new RangeError(`${name}: the record has no dimension \"${id}\".`);\n return dimension;\n };\n const varied = vary.map(known);\n if (new Set(vary).size !== vary.length) throw new RangeError(`${name}: the two varied dimensions are one dimension, \"${vary[0]}\".`);\n for (const id of Object.keys(hold)) {\n if (vary.includes(id)) throw new RangeError(`${name}: the dimension \"${id}\" is both varied and held.`);\n const dimension = known(id);\n if (hold[id] === null && dimension.when !== undefined) continue;\n const fault = valueFault(dimension, hold[id]);\n if (fault !== undefined) throw new RangeError(`${name}: the held dimension \"${id}\": ${fault}.`);\n }\n const others = record.dimensions.filter((d) => !vary.includes(d.id));\n const held = heldValues(name, record, vary, hold, neededLevels(name, varied, vary));\n const placed = record.points.filter(\n (p) => vary.every((id) => p.values[id] !== null) && others.every((d) => matches(d, p.values[d.id] as ResponseInputValue, whenHolds(d, p.values) ? (held[d.id] as ResponseInputValue) : null, tolerance)),\n );\n const matched = placed.filter((p) => typeof p.measures[measure] === \"number\");\n const missing = placed.filter((p) => typeof p.measures[measure] !== \"number\");\n const error = heldOutError(record, measure);\n const nearest = nearestOf(record.dimensions, record.points, measure);\n const range = record.measures.find((m) => m.id === measure)?.range;\n const band = (inputs: Readonly<Record<string, ResponseInputValue>>): ResponseBand => {\n const place = Object.fromEntries(record.dimensions.map((d) => [d.id, whenHolds(d, inputs) ? (inputs[d.id] as ResponseInputValue) : null]));\n const value = predictScaled(model, place);\n const fitted = { value: unscale(model, value), low: unscale(model, value - width * error.rmse), high: unscale(model, value + width * error.rmse) };\n const inside = range === undefined ? fitted : { value: clip(fitted.value, range), low: clip(fitted.low, range), high: clip(fitted.high, range) };\n const moved = inside.value !== fitted.value || inside.low !== fitted.low || inside.high !== fitted.high;\n return { ...inside, nearest: nearest(place), ...(moved ? { clipped: true as const } : {}) };\n };\n return { held, axes: varied.map((d) => axisValues(d, steps)), matched, missing, error, band };\n}\n\n/** This function gives the group field of a measured point of a view. */\nconst groupOf = (point: ResponsePoint): { readonly group?: string } => (point.group === undefined ? {} : { group: point.group });\n\n/** This function gives the declared reason of a point with no value of a measure, or `null` for no stated reason. */\nconst reasonOf = (point: ResponsePoint, measure: string): string | null => (point.absent !== undefined && Object.hasOwn(point.absent, measure) ? (point.absent[measure] as string) : null);\n\n/**\n * This function gives a view of a measure over one dimension of a parsed record:\n * - `curve`: the fitted value at each level, or at `steps` values of a continuous dimension, with its band.\n * - `points`: the measured points that match the held values. This list is empty when no point matches them.\n * - `absent`: the points that match the held values and have no value of the measure, each with its reason. A chart\n * can draw each reason apart.\n * - `held`: the value of each other dimension.\n * - `error`: the held-out error.\n *\n * Each dimension with no value in `hold` takes its usual value. For a continuous dimension, this value is the median\n * of its measured values. For the other kinds, it is the most common level, and a tie gives the first level.\n *\n * A conditional dimension follows its parent:\n * - To vary a conditional dimension, the parent needs a level inside `when`. With no held value, the parent takes the\n * most common level inside `when`. A held level outside `when` is a RangeError.\n * - A held conditional dimension reads `null` in `held` when its parent is outside `when`, also with a value in `hold`.\n * The points that match have `null` at this dimension.\n * - When the parent varies, a held conditional dimension keeps its value in `held`. Each place outside `when` reads\n * `null` for the fit, and for the matching points.\n *\n * The band is the fitted value, plus and less `width` times the held-out root mean square error. On a log scale, this\n * distance is on the log scale of the model, so the band is a ratio. The band has one width along all the curve. The\n * band is the mean error of the model, and `nearest` tells how far the place is from a measurement.\n *\n * A measure with a `range` keeps each place inside it. The fields `value`, `low` and `high` move to the nearest end.\n * The place then has the field `clipped`, and the field `clipped` of the view counts these places. The function\n * `predictResponse` gives the value that the model fitted.\n *\n * The function throws a RangeError for an unknown measure or dimension, and for a held value that is not good for its\n * dimension. It also throws for a dimension that is both varied and held, and for a bad option.\n */\nexport function sliceResponse(record: ResponseRecord, measure: string, options: ResponseSliceOptions): ResponseSlice {\n const { vary } = options;\n const { held, axes, matched, missing, error, band } = frameOf(\"sliceResponse\", record, measure, [vary], options);\n const curve = (axes[0] as readonly ResponseValue[]).map((at) => ({ at, ...band({ ...held, [vary]: at }) }));\n return {\n measure,\n vary,\n held,\n curve,\n points: matched.map((p) => ({ id: p.id, at: p.values[vary] as ResponseValue, value: p.measures[measure] as number, ...groupOf(p) })),\n absent: missing.map((p) => ({ id: p.id, at: p.values[vary] as ResponseValue, reason: reasonOf(p, measure), ...groupOf(p) })),\n error,\n clipped: curve.filter((place) => place.clipped === true).length,\n };\n}\n\n/**\n * This function gives the view of `sliceResponse` over two dimensions. The fields `x` and `y` are the two axes, and\n * `cells` has one row for each value of `y`. The rules of the held values, of the matching points and of the band are\n * the rules of `sliceResponse`. The function also throws a RangeError when the two varied dimensions are one dimension.\n * It throws when a conditional dimension varies with its parent, and when two varied dimensions need no common level.\n */\nexport function surfaceResponse(record: ResponseRecord, measure: string, options: ResponseSurfaceOptions): ResponseSurface {\n const { vary } = options;\n const [xId, yId] = vary;\n const { held, axes, matched, missing, error, band } = frameOf(\"surfaceResponse\", record, measure, vary, options);\n const x = axes[0] as readonly ResponseValue[];\n const y = axes[1] as readonly ResponseValue[];\n const cells = y.map((b) => x.map((a) => band({ ...held, [xId]: a, [yId]: b })));\n return {\n measure,\n vary,\n held,\n x,\n y,\n cells,\n points: matched.map((p) => ({ id: p.id, at: [p.values[xId] as ResponseValue, p.values[yId] as ResponseValue], value: p.measures[measure] as number, ...groupOf(p) })),\n absent: missing.map((p) => ({ id: p.id, at: [p.values[xId] as ResponseValue, p.values[yId] as ResponseValue], reason: reasonOf(p, measure), ...groupOf(p) })),\n error,\n clipped: cells.flat().filter((place) => place.clipped === true).length,\n };\n}\n\n/**\n * This function gives the number of fitted places of a view before the view starts: the product of the lengths of its\n * axes. A level axis counts its levels, and a continuous axis counts `steps`. The field `nearest` reads each point at\n * each place, so the reads of a view are this count times the number of points. The default of `steps` is the default\n * of a view. The function throws a RangeError for an unknown dimension, for one dimension named two times, and for a\n * bad `steps`.\n */\nexport function responseCells(record: Pick<ResponseRecord, \"dimensions\">, vary: string | readonly [string, string], steps = 33): number {\n checkSteps(\"responseCells\", steps);\n const ids: readonly string[] = typeof vary === \"string\" ? [vary] : vary;\n if (new Set(ids).size !== ids.length) throw new RangeError(`responseCells: the two varied dimensions are one dimension, \"${ids[0]}\".`);\n return ids.reduce((count, id) => {\n const dimension = record.dimensions.find((d) => d.id === id);\n if (dimension === undefined) throw new RangeError(`responseCells: the record has no dimension \"${id}\".`);\n return count * (dimension.kind === \"continuous\" ? steps : dimension.levels.length);\n }, 1);\n}\n","/**\n * The validator of the format `response-records/1`. The functions here read unknown data and write faults. Thus a page\n * can show the reason that a file is bad.\n */\nimport { RESPONSE_RECORDS_SCHEMA, type ResponseData, type ResponseDimension, type ResponseMeasure, type ResponsePoint, type ResponseRecord, type RidgeInput, groupKey, isNumberDimension, valueFault, whenHolds } from \"./response.ts\";\n\n/** The largest power of a factor. A larger power of a coordinate from -1 to 1 adds almost nothing to a model. */\nexport const RESPONSE_MAX_POWER = 8;\n\n/** One fault of a record. */\nexport interface ResponseFault {\n /** The place of the fault, for example `points[3].values.size`. An empty string is the record itself. */\n readonly path: string;\n /** What is wrong, and what the format needs. */\n readonly message: string;\n}\n\n/** The result of `parseResponseRecord`: the record, or each fault that the validator found. */\nexport type ParsedResponseRecord = { readonly ok: true; readonly record: ResponseRecord } | { readonly ok: false; readonly faults: readonly ResponseFault[] };\n\ntype Fields = Readonly<Record<string, unknown>>;\n\n/** The list that the checks write to. */\ntype Faults = ResponseFault[];\n\n/** This function gives an unknown value as short text for a message. */\nfunction shown(value: unknown): string {\n if (value === undefined) return \"nothing\";\n const text = JSON.stringify(value) ?? String(value);\n return text.length > 60 ? `${text.slice(0, 60)}...` : text;\n}\n\n/** This function gives a path with one more key. */\nconst at = (path: string, key: string): string => (path === \"\" ? key : `${path}.${key}`);\n\nconst isNumber = (v: unknown): v is number => typeof v === \"number\" && Number.isFinite(v);\n\n/** This function gives the field `key` of an unknown value, or `undefined` for a value that is not an object. */\nconst peek = (value: unknown, key: string): unknown => (typeof value === \"object\" && value !== null ? (value as Fields)[key] : undefined);\n\n/** This function writes a fault when a test fails. */\nfunction need(ok: boolean, path: string, message: string, faults: Faults): void {\n if (!ok) faults.push({ path, message });\n}\n\n/** This function gives the fields of a plain object. It writes a fault for another value, and for each wrong key. */\nfunction fields(value: unknown, path: string, keys: readonly string[], optional: readonly string[], faults: Faults): Fields | undefined {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n faults.push({ path, message: `this is an object, not ${shown(value)}.` });\n return undefined;\n }\n const object = value as Fields;\n for (const key of keys) need(Object.hasOwn(object, key), at(path, key), \"this field is missing.\", faults);\n for (const key of Object.keys(object)) need(keys.includes(key) || optional.includes(key), at(path, key), `${RESPONSE_RECORDS_SCHEMA} has no such field.`, faults);\n return object;\n}\n\n/** This function gives the items of a list. It writes a fault for another value, and for a short list. */\nfunction list(value: unknown, path: string, least: number, faults: Faults): readonly unknown[] {\n if (!Array.isArray(value)) {\n faults.push({ path, message: `this is a list, not ${shown(value)}.` });\n return [];\n }\n need(value.length >= least, path, `this list has ${value.length} items, and it needs ${least} or more.`, faults);\n return value as readonly unknown[];\n}\n\n/** This function examines a field when it is present. A missing field already has a fault, or it is optional. */\nfunction check(object: Fields, key: string, path: string, test: (value: unknown) => boolean, wanted: string, faults: Faults): void {\n if (Object.hasOwn(object, key)) need(test(object[key]), at(path, key), `this is ${wanted}, not ${shown(object[key])}.`, faults);\n}\n\nconst isId = (v: unknown): boolean => typeof v === \"string\" && v !== \"\";\nconst isString = (v: unknown): boolean => typeof v === \"string\";\nconst isPositive = (v: unknown): boolean => isNumber(v) && v > 0;\nconst isNotNegative = (v: unknown): boolean => isNumber(v) && v >= 0;\n\n/** This function writes a fault for each id that is a duplicate, and it gives the set of the ids. */\nfunction uniqueIds(items: readonly unknown[], path: string, faults: Faults): Set<string> {\n const ids = new Set<string>();\n items.forEach((item, i) => {\n const id = peek(item, \"id\");\n if (typeof id !== \"string\") return;\n need(!ids.has(id), `${path}[${i}].id`, `an earlier item has the id ${shown(id)}.`, faults);\n ids.add(id);\n });\n return ids;\n}\n\n/** This function examines the levels of a categorical or ordinal dimension. */\nfunction checkLevels(value: unknown, path: string, numbersToo: boolean, log: boolean, faults: Faults): void {\n const levels = list(value, path, 1, faults);\n const numbers = numbersToo && levels.every(isNumber);\n need(numbers || levels.every(isString), path, numbersToo ? \"these levels are all text or all finite numbers.\" : \"these levels are all text.\", faults);\n need(new Set(levels).size === levels.length, path, \"these levels have a duplicate.\", faults);\n if (numbers) need(levels.every((v, i) => i === 0 || (levels[i - 1] as number) < (v as number)), path, \"these number levels are not in ascending order.\", faults);\n if (log) need(levels.every(isPositive), path, \"a log dimension has number levels above 0.\", faults);\n}\n\n/** This function examines one dimension. */\nfunction checkDimension(value: unknown, path: string, faults: Faults): void {\n const kind = peek(value, \"kind\");\n const object = fields(value, path, [\"id\", \"label\", \"kind\", \"unit\"], [\"range\", \"levels\", \"log\", \"when\"], faults);\n if (object === undefined) return;\n check(object, \"id\", path, isId, \"text with one character or more\", faults);\n check(object, \"label\", path, isString, \"text\", faults);\n check(object, \"unit\", path, isString, \"text\", faults);\n check(object, \"log\", path, (v) => typeof v === \"boolean\", \"true or false\", faults);\n const log = object[\"log\"] === true;\n if (kind === \"continuous\") {\n need(!Object.hasOwn(object, \"levels\"), at(path, \"levels\"), \"a continuous dimension has a range, not levels.\", faults);\n need(!Object.hasOwn(object, \"range\") || !log || !isNumber(peek(object[\"range\"], \"0\")) || (peek(object[\"range\"], \"0\") as number) > 0, at(path, \"range\"), \"a log dimension has a range above 0.\", faults);\n need(Object.hasOwn(object, \"range\"), at(path, \"range\"), \"this field is missing.\", faults);\n if (Object.hasOwn(object, \"range\")) checkRange(object[\"range\"], at(path, \"range\"), faults);\n } else if (kind === \"ordinal\" || kind === \"categorical\") {\n need(!Object.hasOwn(object, \"range\"), at(path, \"range\"), `a dimension of the kind ${kind} has levels, not a range.`, faults);\n need(kind === \"ordinal\" || !Object.hasOwn(object, \"log\"), at(path, \"log\"), \"a categorical dimension has no log scale.\", faults);\n need(Object.hasOwn(object, \"levels\"), at(path, \"levels\"), \"this field is missing.\", faults);\n if (Object.hasOwn(object, \"levels\")) checkLevels(object[\"levels\"], at(path, \"levels\"), kind === \"ordinal\", log, faults);\n } else if (Object.hasOwn(object, \"kind\")) faults.push({ path: at(path, \"kind\"), message: `this is \"continuous\", \"ordinal\" or \"categorical\", not ${shown(kind)}.` });\n}\n\n/** This function examines the condition of one dimension against all the dimensions. */\nfunction checkWhen(value: unknown, path: string, dimensions: readonly unknown[], faults: Faults): void {\n const object = fields(value, path, [\"dimension\", \"levels\"], [], faults);\n if (object === undefined) return;\n const levels = Object.hasOwn(object, \"levels\") ? list(object[\"levels\"], at(path, \"levels\"), 1, faults) : [];\n need(new Set(levels).size === levels.length, at(path, \"levels\"), \"these levels have a duplicate.\", faults);\n if (!Object.hasOwn(object, \"dimension\")) return;\n const id = object[\"dimension\"];\n const parent = dimensions.find((d) => peek(d, \"id\") === id);\n if (parent === undefined) {\n faults.push({ path: at(path, \"dimension\"), message: `the record has no dimension ${shown(id)}.` });\n return;\n }\n const kind = peek(parent, \"kind\");\n need(kind === \"categorical\" || kind === \"ordinal\", at(path, \"dimension\"), `the parent ${shown(id)} is ${shown(kind)}, and a parent is categorical or ordinal.`, faults);\n need(peek(parent, \"when\") === undefined, at(path, \"dimension\"), `the parent ${shown(id)} is itself conditional.`, faults);\n const known = peek(parent, \"levels\");\n if (!Array.isArray(known)) return;\n levels.forEach((level, i) => need(known.includes(level), `${at(path, \"levels\")}[${i}]`, `the dimension ${shown(id)} has no level ${shown(level)}.`, faults));\n}\n\n/** This function examines a range. */\nfunction checkRange(range: unknown, path: string, faults: Faults): void {\n const good = Array.isArray(range) && range.length === 2 && isNumber(range[0]) && isNumber(range[1]) && range[0] < range[1];\n need(good, path, `this is a low and a high finite number, with low less than high, not ${shown(range)}.`, faults);\n}\n\n/** This function examines one measure. */\nfunction checkMeasure(value: unknown, path: string, faults: Faults): void {\n const object = fields(value, path, [\"id\", \"label\", \"unit\", \"direction\"], [\"range\"], faults);\n if (object === undefined) return;\n check(object, \"id\", path, isId, \"text with one character or more\", faults);\n check(object, \"label\", path, isString, \"text\", faults);\n check(object, \"unit\", path, isString, \"text\", faults);\n check(object, \"direction\", path, (v) => v === \"higher\" || v === \"lower\" || v === \"none\", `\"higher\", \"lower\" or \"none\"`, faults);\n if (Object.hasOwn(object, \"range\")) checkRange(object[\"range\"], at(path, \"range\"), faults);\n}\n\n/** This function refuses a measured value outside the range of its measure. */\nfunction checkMeasured(point: unknown, path: string, measures: readonly ResponseMeasure[], faults: Faults): void {\n for (const { id, range } of measures) {\n const value = peek(peek(point, \"measures\"), id);\n if (range === undefined || typeof value !== \"number\") continue;\n need(value >= range[0] && value <= range[1], at(at(path, \"measures\"), id), `this value is outside the range of the measure, [${range[0]}, ${range[1]}].`, faults);\n }\n}\n\n/** This function examines one declared reason. */\nfunction checkReason(value: unknown, path: string, faults: Faults): void {\n const object = fields(value, path, [\"id\", \"label\"], [], faults);\n if (object === undefined) return;\n check(object, \"id\", path, isId, \"text with one character or more\", faults);\n check(object, \"label\", path, isString, \"text\", faults);\n}\n\n/** This function examines the reasons of a point: each has a declaration, and each is on a measure with no number. */\nfunction checkAbsent(value: unknown, path: string, measuresOfPoint: unknown, measures: ReadonlySet<string>, reasons: ReadonlySet<string>, faults: Faults): void {\n const absent = fields(value, path, [], [...measures], faults);\n if (absent === undefined) return;\n for (const measure of measures) {\n if (!Object.hasOwn(absent, measure)) continue;\n need(reasons.has(absent[measure] as string), at(path, measure), `the record declares no reason ${shown(absent[measure])}.`, faults);\n need(typeof peek(measuresOfPoint, measure) !== \"number\", at(path, measure), \"this measure has a number, so it has no reason.\", faults);\n }\n}\n\n/** This function examines one point, with the dimensions, the measures and the reasons of the record. */\nfunction checkPoint(value: unknown, path: string, dimensions: readonly ResponseDimension[], measures: ReadonlySet<string>, reasons: ReadonlySet<string>, faults: Faults): void {\n const object = fields(value, path, [\"id\", \"values\", \"measures\"], [\"group\", \"absent\"], faults);\n if (object === undefined) return;\n check(object, \"id\", path, isId, \"text with one character or more\", faults);\n check(object, \"group\", path, isId, \"text with one character or more\", faults);\n if (Object.hasOwn(object, \"values\")) {\n const inside = at(path, \"values\");\n const ids = dimensions.map((d) => d.id);\n const values = fields(object[\"values\"], inside, ids, [], faults);\n for (const dimension of dimensions) {\n if (values === undefined || !Object.hasOwn(values, dimension.id)) continue;\n const value = values[dimension.id];\n const present = whenHolds(dimension, values);\n const parent = dimension.when?.dimension as string;\n if (value === null && dimension.when !== undefined) {\n need(!present, at(inside, dimension.id), `this needs a value when the dimension \"${parent}\" is ${shown(values[parent])}.`, faults);\n continue;\n }\n const fault = valueFault(dimension, value);\n if (fault !== undefined) faults.push({ path: at(inside, dimension.id), message: `${fault}.` });\n else need(present, at(inside, dimension.id), `this is null when the dimension \"${parent}\" is ${shown(values[parent])}.`, faults);\n }\n }\n if (Object.hasOwn(object, \"absent\")) checkAbsent(object[\"absent\"], at(path, \"absent\"), object[\"measures\"], measures, reasons, faults);\n if (Object.hasOwn(object, \"measures\")) {\n const inside = at(path, \"measures\");\n const values = fields(object[\"measures\"], inside, [...measures], [], faults);\n if (values === undefined) return;\n for (const measure of measures) check(values, measure, inside, (v) => v === null || isNumber(v), \"a finite number or null\", faults);\n }\n}\n\n/**\n * This function examines the data of a record: all but its models and its folds. It gives each fault that it finds.\n * It examines the points only when the dimensions and the measures have no fault, because the points refer to them.\n * `required` and `optional` name the other top-level fields.\n */\nexport function responseDataFaults(value: unknown, required: readonly string[], optional: readonly string[]): readonly ResponseFault[] {\n const faults: Faults = [];\n const object = fields(value, \"\", [\"schema\", \"name\", \"dimensions\", \"measures\", \"points\", ...required], [\"reasons\", ...optional], faults);\n if (object === undefined) return faults;\n check(object, \"schema\", \"\", (v) => v === RESPONSE_RECORDS_SCHEMA, `\"${RESPONSE_RECORDS_SCHEMA}\"`, faults);\n check(object, \"name\", \"\", isId, \"text with one character or more\", faults);\n const dimensions = Object.hasOwn(object, \"dimensions\") ? list(object[\"dimensions\"], \"dimensions\", 1, faults) : [];\n dimensions.forEach((d, i) => checkDimension(d, `dimensions[${i}]`, faults));\n uniqueIds(dimensions, \"dimensions\", faults);\n dimensions.forEach((d, i) => {\n if (peek(d, \"when\") !== undefined) checkWhen(peek(d, \"when\"), `dimensions[${i}].when`, dimensions, faults);\n });\n const measures = Object.hasOwn(object, \"measures\") ? list(object[\"measures\"], \"measures\", 1, faults) : [];\n measures.forEach((m, i) => checkMeasure(m, `measures[${i}]`, faults));\n const measureIds = uniqueIds(measures, \"measures\", faults);\n const reasons = Object.hasOwn(object, \"reasons\") ? list(object[\"reasons\"], \"reasons\", 0, faults) : [];\n reasons.forEach((r, i) => checkReason(r, `reasons[${i}]`, faults));\n const reasonIds = uniqueIds(reasons, \"reasons\", faults);\n if (faults.length > 0) return faults;\n const points = list(object[\"points\"], \"points\", 1, faults);\n points.forEach((p, i) => checkPoint(p, `points[${i}]`, dimensions as readonly ResponseDimension[], measureIds, reasonIds, faults));\n uniqueIds(points, \"points\", faults);\n if (faults.length > 0) return faults;\n points.forEach((p, i) => checkMeasured(p, `points[${i}]`, measures as readonly ResponseMeasure[], faults));\n return faults;\n}\n\n/** This function examines one input of a ridge model against the dimensions of the record. */\nfunction checkInput(value: unknown, path: string, dimensions: ReadonlyMap<string, ResponseDimension>, faults: Faults): void {\n const kind = peek(value, \"kind\");\n if (kind !== \"number\" && kind !== \"rank\" && kind !== \"level\") {\n faults.push({ path: at(path, \"kind\"), message: `this is \"number\", \"rank\" or \"level\", not ${shown(kind)}.` });\n return;\n }\n const keys = { number: [\"center\", \"spread\"], rank: [\"levels\", \"center\", \"spread\"], level: [\"levels\"] }[kind];\n const object = fields(value, path, [\"kind\", \"dimension\", ...keys], kind === \"number\" ? [\"log\", \"conditional\"] : [\"conditional\"], faults);\n if (object === undefined) return;\n check(object, \"center\", path, isNumber, \"a finite number\", faults);\n check(object, \"spread\", path, isPositive, \"a finite number above 0\", faults);\n check(object, \"log\", path, (v) => typeof v === \"boolean\", \"true or false\", faults);\n check(object, \"conditional\", path, (v) => typeof v === \"boolean\", \"true or false\", faults);\n const dimension = dimensions.get(object[\"dimension\"] as string);\n if (dimension === undefined) {\n faults.push({ path: at(path, \"dimension\"), message: `the record has no dimension ${shown(object[\"dimension\"])}.` });\n return;\n }\n const want = isNumberDimension(dimension) ? \"number\" : dimension.kind === \"categorical\" ? \"level\" : \"rank\";\n need(kind === want, at(path, \"kind\"), `the dimension \"${dimension.id}\" needs an input of the kind \"${want}\".`, faults);\n need((object[\"conditional\"] ?? false) === (dimension.when !== undefined), at(path, \"conditional\"), `this does not agree with the condition of the dimension \"${dimension.id}\".`, faults);\n if (kind === \"number\" && dimension.kind !== \"categorical\") {\n need((object[\"log\"] ?? false) === (dimension.log ?? false), at(path, \"log\"), `this does not agree with the log scale of the dimension \"${dimension.id}\".`, faults);\n }\n if (kind !== \"number\" && dimension.kind !== \"continuous\") {\n need(JSON.stringify(object[\"levels\"]) === JSON.stringify(dimension.levels), at(path, \"levels\"), `these are not the levels of the dimension \"${dimension.id}\".`, faults);\n }\n}\n\n/** This function examines the factors of one term against the inputs of a model. `fitResponse` also uses it. */\nexport function factorFaults(value: unknown, path: string, inputs: ReadonlyMap<string, RidgeInput>, dimensions: ReadonlyMap<string, ResponseDimension>): readonly ResponseFault[] {\n const faults: Faults = [];\n list(value, path, 1, faults).forEach((item, i) => {\n const inside = `${path}[${i}]`;\n const isLevel = peek(item, \"level\") !== undefined;\n const factor = fields(item, inside, [\"dimension\", isLevel ? \"level\" : \"power\"], [], faults);\n if (factor === undefined) return;\n const input = inputs.get(factor[\"dimension\"] as string);\n if (input === undefined) {\n faults.push({ path: at(inside, \"dimension\"), message: `the model has no input ${shown(factor[\"dimension\"])}.` });\n } else if (isLevel) {\n const dimension = dimensions.get(input.dimension);\n const levels: readonly unknown[] = dimension === undefined || dimension.kind === \"continuous\" ? [] : dimension.levels;\n need(levels.includes(factor[\"level\"]), at(inside, \"level\"), `the input \"${input.dimension}\" has no level ${shown(factor[\"level\"])}.`, faults);\n } else {\n need(input.kind !== \"level\", inside, `the categorical input \"${input.dimension}\" takes a level, not a power.`, faults);\n const good = (v: unknown): boolean => Number.isSafeInteger(v) && (v as number) >= 1 && (v as number) <= RESPONSE_MAX_POWER;\n check(factor, \"power\", inside, good, `a whole number from 1 to ${RESPONSE_MAX_POWER}`, faults);\n }\n });\n return faults;\n}\n\n/** This function examines the fields of a ridge model after its common fields. */\nfunction checkRidge(object: Fields, path: string, dimensions: ReadonlyMap<string, ResponseDimension>, faults: Faults): void {\n check(object, \"lambda\", path, isNotNegative, \"a finite number of 0 or more\", faults);\n check(object, \"intercept\", path, isNumber, \"a finite number\", faults);\n const inputs = Object.hasOwn(object, \"inputs\") ? list(object[\"inputs\"], at(path, \"inputs\"), 0, faults) : [];\n const known = new Map<string, RidgeInput>();\n inputs.forEach((input, i) => {\n const inside = `${at(path, \"inputs\")}[${i}]`;\n checkInput(input, inside, dimensions, faults);\n const dimension = peek(input, \"dimension\");\n if (typeof dimension !== \"string\") return;\n need(!known.has(dimension), at(inside, \"dimension\"), `an earlier input has the dimension \"${dimension}\".`, faults);\n known.set(dimension, input as RidgeInput);\n });\n const terms = Object.hasOwn(object, \"terms\") ? list(object[\"terms\"], at(path, \"terms\"), 0, faults) : [];\n terms.forEach((term, i) => {\n const inside = `${at(path, \"terms\")}[${i}]`;\n const fieldsOfTerm = fields(term, inside, [\"factors\", \"weight\"], [], faults);\n if (fieldsOfTerm === undefined) return;\n check(fieldsOfTerm, \"weight\", inside, isNumber, \"a finite number\", faults);\n if (Object.hasOwn(fieldsOfTerm, \"factors\")) faults.push(...factorFaults(fieldsOfTerm[\"factors\"], at(inside, \"factors\"), known, dimensions));\n });\n}\n\n/** This function examines the dimensions of a table model, and it gives the good ones. */\nfunction tableDimensions(object: Fields, path: string, dimensions: ReadonlyMap<string, ResponseDimension>, faults: Faults): readonly ResponseDimension[] {\n const table: ResponseDimension[] = [];\n const ids = Object.hasOwn(object, \"dimensions\") ? list(object[\"dimensions\"], at(path, \"dimensions\"), 1, faults) : [];\n ids.forEach((id, i) => {\n const dimension = dimensions.get(id as string);\n const inside = `${at(path, \"dimensions\")}[${i}]`;\n if (dimension === undefined) faults.push({ path: inside, message: `the record has no dimension ${shown(id)}.` });\n else if (dimension.kind === \"continuous\") faults.push({ path: inside, message: `a table cannot read the continuous dimension \"${dimension.id}\".` });\n else {\n need(!table.includes(dimension), inside, `an earlier item is the dimension \"${dimension.id}\".`, faults);\n table.push(dimension);\n }\n });\n return table;\n}\n\n/** This function examines the fields of a table model after its common fields. */\nfunction checkTable(object: Fields, path: string, dimensions: ReadonlyMap<string, ResponseDimension>, faults: Faults): void {\n check(object, \"fallback\", path, isNumber, \"a finite number\", faults);\n const table = tableDimensions(object, path, dimensions, faults);\n const conditional = table.filter((d) => d.when !== undefined).map((d) => d.id);\n need(JSON.stringify(object[\"conditional\"] ?? []) === JSON.stringify(conditional), at(path, \"conditional\"), `this does not agree with the conditions of the dimensions of the table: ${shown(conditional)}.`, faults);\n const cells = Object.hasOwn(object, \"cells\") ? list(object[\"cells\"], at(path, \"cells\"), 1, faults) : [];\n const seen = new Set<string>();\n cells.forEach((cell, i) => {\n const inside = `${at(path, \"cells\")}[${i}]`;\n const fieldsOfCell = fields(cell, inside, [\"at\", \"value\", \"n\"], [], faults);\n if (fieldsOfCell === undefined) return;\n check(fieldsOfCell, \"value\", inside, isNumber, \"a finite number\", faults);\n check(fieldsOfCell, \"n\", inside, (v) => Number.isSafeInteger(v) && (v as number) >= 1, \"a whole number of 1 or more\", faults);\n if (!Object.hasOwn(fieldsOfCell, \"at\")) return;\n const values = list(fieldsOfCell[\"at\"], at(inside, \"at\"), 0, faults);\n need(values.length === table.length, at(inside, \"at\"), `this list has ${values.length} values, and the table has ${table.length} dimensions.`, faults);\n table.forEach((dimension, j) => {\n const absent = values[j] === null && dimension.when !== undefined;\n const fault = j < values.length && !absent ? valueFault(dimension, values[j]) : undefined;\n if (fault !== undefined) faults.push({ path: `${at(inside, \"at\")}[${j}]`, message: `${fault}.` });\n });\n const key = JSON.stringify(values);\n need(!seen.has(key), at(inside, \"at\"), `an earlier cell has the values ${shown(values)}.`, faults);\n seen.add(key);\n });\n}\n\n/** This function examines the list of models: one model for each measure. */\nfunction checkModels(value: unknown, data: ResponseData, faults: Faults): void {\n const dimensions = new Map(data.dimensions.map((d) => [d.id, d]));\n const measures = new Set(data.measures.map((m) => m.id));\n const covered = new Set<string>();\n list(value, \"models\", 0, faults).forEach((item, i) => {\n const path = `models[${i}]`;\n const kind = peek(item, \"kind\");\n if (kind !== \"ridge\" && kind !== \"table\") {\n faults.push({ path: at(path, \"kind\"), message: `this is \"ridge\" or \"table\", not ${shown(kind)}.` });\n return;\n }\n const keys = kind === \"ridge\" ? [\"lambda\", \"inputs\", \"intercept\", \"terms\"] : [\"dimensions\", \"cells\", \"fallback\"];\n const object = fields(item, path, [\"kind\", \"measure\", \"scale\", ...keys], kind === \"ridge\" ? [\"floor\"] : [\"floor\", \"conditional\"], faults);\n if (object === undefined) return;\n const measure = object[\"measure\"];\n if (typeof measure !== \"string\" || !measures.has(measure)) faults.push({ path: at(path, \"measure\"), message: `the record has no measure ${shown(measure)}.` });\n else {\n need(!covered.has(measure), at(path, \"measure\"), `an earlier model has the measure \"${measure}\".`, faults);\n covered.add(measure);\n }\n check(object, \"scale\", path, (v) => v === \"linear\" || v === \"log\", `\"linear\" or \"log\"`, faults);\n check(object, \"floor\", path, isPositive, \"a finite number above 0\", faults);\n need(!Object.hasOwn(object, \"floor\") || object[\"scale\"] === \"log\", at(path, \"floor\"), \"only a model with the scale log has a floor.\", faults);\n if (kind === \"ridge\") checkRidge(object, path, dimensions, faults);\n else checkTable(object, path, dimensions, faults);\n });\n for (const measure of measures) need(covered.has(measure), \"models\", `no model has the measure \"${measure}\".`, faults);\n}\n\n/** This function examines the error of one measure in one fold. */\nfunction checkFoldError(value: unknown, path: string, count: number, faults: Faults): void {\n const object = fields(value, path, [\"n\", \"mae\", \"rmse\", \"baselineMae\"], [], faults);\n if (object === undefined) return;\n check(object, \"n\", path, (v) => v === count, `${count}, the held-out points of the fold with a value of this measure`, faults);\n for (const key of [\"mae\", \"rmse\", \"baselineMae\"]) check(object, key, path, isNotNegative, \"a finite number of 0 or more\", faults);\n}\n\n/** This function examines the stored predictions of a fold against its held-out points and its errors. */\nfunction checkPredictions(value: unknown, path: string, held: readonly ResponsePoint[], errors: unknown, measures: readonly string[], faults: Faults): void {\n const predictions = fields(value, path, [], measures, faults);\n if (predictions === undefined) return;\n for (const measure of measures) {\n if (!Object.hasOwn(predictions, measure)) continue;\n const inside = at(path, measure);\n const stored = fields(predictions[measure], inside, [], Object.keys(peek(predictions, measure) ?? {}), faults);\n if (stored === undefined) continue;\n need(peek(errors, measure) !== undefined, inside, \"this fold has no error of this measure.\", faults);\n const scored = new Set(held.filter((p) => typeof p.measures[measure] === \"number\").map((p) => p.id));\n for (const id of Object.keys(stored)) {\n need(scored.has(id), at(inside, id), `this fold has no held-out point ${shown(id)} with a value of the measure.`, faults);\n check(stored, id, inside, isNumber, \"a finite number\", faults);\n }\n for (const id of scored) need(Object.hasOwn(stored, id), at(inside, id), \"this held-out point has no prediction.\", faults);\n }\n}\n\n/** This function adds the points of a fold to `foldOfPoint`, and it gives them. Each bad id gives a fault. */\nfunction heldPoints(value: unknown, path: string, f: number, points: ReadonlyMap<string, ResponsePoint>, foldOfPoint: Map<string, number>, faults: Faults): readonly ResponsePoint[] {\n const held: ResponsePoint[] = [];\n list(value, path, 1, faults).forEach((id, i) => {\n const inside = `${path}[${i}]`;\n const point = points.get(id as string);\n const earlier = foldOfPoint.get(id as string);\n if (point === undefined) faults.push({ path: inside, message: `the record has no point ${shown(id)}.` });\n else if (earlier !== undefined) faults.push({ path: inside, message: `the point \"${point.id}\" is also in fold ${earlier}.` });\n else {\n foldOfPoint.set(point.id, f);\n held.push(point);\n }\n });\n return held;\n}\n\n/** This function gives the number of points of each group in a list. */\nfunction groupSizes(points: readonly ResponsePoint[]): Map<string, number> {\n const sizes = new Map<string, number>();\n for (const p of points) sizes.set(groupKey(p), (sizes.get(groupKey(p)) ?? 0) + 1);\n return sizes;\n}\n\n/** This function examines the list of folds. `parseResponseRecord` tells the rules. */\nfunction checkFolds(value: unknown, data: ResponseData, faults: Faults): void {\n const points = new Map(data.points.map((p) => [p.id, p]));\n const measures = data.measures.map((m) => m.id);\n const sizes = groupSizes(data.points);\n const foldOfPoint = new Map<string, number>();\n const covered = new Set<string>();\n const folds = list(value, \"folds\", 1, faults);\n const predicted = measures.filter((m) => folds.some((fold) => peek(peek(fold, \"predictions\"), m) !== undefined));\n folds.forEach((item, f) => {\n const path = `folds[${f}]`;\n const object = fields(item, path, [\"heldOut\", \"errors\"], [\"predictions\"], faults);\n if (object === undefined) return;\n const held = Object.hasOwn(object, \"heldOut\") ? heldPoints(object[\"heldOut\"], at(path, \"heldOut\"), f, points, foldOfPoint, faults) : [];\n for (const [group, count] of groupSizes(held)) {\n const size = sizes.get(group) as number;\n need(count === size, at(path, \"heldOut\"), `the ${group} has ${count} of its ${size} points in this fold, so it is on both sides of the split.`, faults);\n }\n if (Object.hasOwn(object, \"predictions\")) checkPredictions(object[\"predictions\"], at(path, \"predictions\"), held, object[\"errors\"], measures, faults);\n if (!Object.hasOwn(object, \"errors\")) return;\n const errors = fields(object[\"errors\"], at(path, \"errors\"), [], measures, faults);\n if (errors === undefined) return;\n for (const measure of measures) {\n if (!Object.hasOwn(errors, measure)) continue;\n const count = held.filter((p) => p.measures[measure] !== null).length;\n checkFoldError(errors[measure], at(at(path, \"errors\"), measure), count, faults);\n if (count > 0) covered.add(measure);\n need(!predicted.includes(measure) || peek(object[\"predictions\"], measure) !== undefined, at(path, \"predictions\"), `another fold has predictions of the measure \"${measure}\", so this fold needs them too.`, faults);\n }\n });\n for (const measure of measures) need(covered.has(measure), \"folds\", `no fold has a held-out error of the measure \"${measure}\".`, faults);\n}\n\n/**\n * This function examines unknown data, for example the result of `JSON.parse`, against `response-records/1`. It gives\n * `{ ok: true, record }`, with the same object as the record, or `{ ok: false, faults }`. Each fault has the path of\n * the bad field and a message. The function does not throw. Data that the checks cannot read, for example an object\n * with a loop, gives one fault.\n *\n * A field that the format does not have is a fault. Thus a wrong spelling of an optional field cannot go unseen.\n *\n * The function examines the models and the folds only when the data has no fault, because they refer to the data.\n * Thus a correction of the data can show more faults. These rules apply to the folds:\n * - A point is in one fold or in no fold.\n * - All the points of a group are in one fold, or all are in no fold. Thus no group is on both sides of a split.\n * - The count `n` of an error is the number of held-out points with a value of the measure.\n * - Each measure has an error in one fold or more.\n *\n * These rules apply to the predictions of a fold:\n * - Each prediction is a finite number of a held-out point of the fold with a value of the measure.\n * - The fold has a prediction of each such point, and an error of the measure.\n * - When one fold has predictions of a measure, each fold with an error of the measure has them.\n *\n * These rules apply to the reasons of a point:\n * - Each reason is on a known measure with no number. A measure with `null` and no reason is good.\n * - Each reason has a declaration in the field `reasons` of the record.\n */\nexport function parseResponseRecord(value: unknown): ParsedResponseRecord {\n try {\n const faults: Faults = [...responseDataFaults(value, [\"models\", \"folds\"], [])];\n if (faults.length === 0) {\n const record = value as ResponseRecord;\n checkModels(record.models, record, faults);\n checkFolds(record.folds, record, faults);\n if (faults.length === 0) return { ok: true, record };\n }\n return { ok: false, faults };\n } catch (error) {\n return { ok: false, faults: [{ path: \"\", message: `the validator cannot read this data: ${String(error)}.` }] };\n }\n}\n","/**\n * The fit of `response-records/1`. The function `fitResponse` splits the groups into folds. For each fold, it fits a\n * model on the other folds and scores the model on the fold. Then it fits the model of the record on all the points.\n *\n * The coordinates of a ridge model come from the declared ranges, not from the points. Thus each fold has the same\n * design, and no fact of a held-out point goes into a fit. The penalty of a fold comes from the other folds only.\n */\nimport { random } from \"@mark1russell7/rigor-generators\";\nimport { mean } from \"./describe.ts\";\nimport { RESPONSE_MAX_POWER, factorFaults, responseDataFaults } from \"./response-parse.ts\";\nimport {\n RESPONSE_RECORDS_SCHEMA,\n type ResponseData,\n type ResponseDimension,\n type ResponseFactor,\n type ResponseFold,\n type ResponseFoldError,\n type ResponseInputValue,\n type ResponseMeasure,\n type ResponseModel,\n type ResponsePoint,\n type ResponseRecord,\n type ResponseTableCell,\n type ResponseValue,\n type RidgeInput,\n axisEnds,\n coordinates,\n groupKey,\n isNumberDimension,\n product,\n toModelScale,\n} from \"./response.ts\";\nimport { ridgeSolve } from \"./ridge.ts\";\n\n/** The options of `fitResponse`. */\nexport interface ResponseFitOptions {\n /** The number of folds, 3 or more. With fewer groups, each group is one fold. The default is 5. */\n readonly folds?: number;\n /** The seed of the split. The default is 1. */\n readonly seed?: number | string;\n /** The kind of model. The default `auto` gives a table when each dimension is categorical, and a ridge fit otherwise. */\n readonly model?: \"auto\" | \"ridge\" | \"table\";\n /** The largest total power of a term of a ridge fit, from 1 to 8. The default is 2. */\n readonly degree?: number;\n /**\n * When true, a ridge fit also has the products of two dimensions, up to `degree`. The default is true. The value\n * false also removes the products of a conditional dimension with the levels of its parent. Thus this option is the\n * way out of the limit `RESPONSE_MAX_TERMS`.\n *\n * The value `seen` is the expansion of true, with only the terms that are not 0 at one point or more. Thus a sparse\n * product of two large sets of levels keeps only the pairs with points. The limit applies after this choice.\n */\n readonly interactions?: boolean | \"seen\";\n /** The stated terms of a ridge fit, in place of `degree` and `interactions`. */\n readonly terms?: readonly (readonly ResponseFactor[])[];\n /** The penalties that a ridge fit chooses from, each above 0. The default is `RESPONSE_LAMBDAS`. */\n readonly lambdas?: readonly number[];\n /** The ids of the measures to fit on a log scale. */\n readonly log?: readonly string[];\n /** On a log scale, each smaller value takes this value. With no floor, a value of 0 or less is an error. */\n readonly logFloor?: number;\n /**\n * When true, each fold stores the prediction of each held-out point with a value. Then `heldOutErrorAt` gives the error of\n * a chosen set of points. The default is false, and the record then has no field `predictions`.\n */\n readonly outOfFold?: boolean;\n}\n\n/** The default penalties of a ridge fit. The coordinates are from -1 to 1, so one list suits each record. */\nexport const RESPONSE_LAMBDAS: readonly number[] = [1e-6, 1e-4, 1e-3, 1e-2, 1e-1, 1, 10, 100];\n\n/** The largest number of coefficients of a ridge fit. The memory of each fold grows as the square of this number. */\nexport const RESPONSE_MAX_TERMS = 1024;\n\n/** One value of a measure, on the scale of the model. */\ninterface Row {\n readonly point: ResponsePoint;\n readonly y: number;\n readonly fold: number;\n}\n\n/** A fit that leaves out one fold. Its result gives the prediction of a row, by the index of the row. */\ntype Learner = (fold: number) => (row: number) => number;\n\n/** The score of a measure in one fold. */\ninterface FoldScore {\n readonly error: ResponseFoldError;\n /** The prediction of each held-out point with a value, by the id of the point. */\n readonly predictions: Readonly<Record<string, number>>;\n}\n\n/** The terms and the other choices that apply to each measure. */\ninterface Plan {\n readonly ids: readonly string[];\n /** The ids of the dimensions with a condition. */\n readonly conditional: readonly string[];\n readonly kind: \"ridge\" | \"table\";\n readonly folds: number;\n readonly lambdas: readonly number[];\n readonly terms: readonly (readonly ResponseFactor[])[];\n readonly inputs: readonly RidgeInput[];\n}\n\n/** This function compares two texts by their code units, so the order does not depend on a locale. */\nconst byText = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);\n\n/** This function gives the input of a ridge model for a dimension. The coordinates run from -1 to 1 over the dimension. */\nfunction inputOf(dimension: ResponseDimension): RidgeInput {\n const conditional = dimension.when === undefined ? {} : { conditional: true };\n if (dimension.kind === \"categorical\") return { kind: \"level\", dimension: dimension.id, levels: dimension.levels, ...conditional };\n const [low, high] = axisEnds(dimension);\n const center = (low + high) / 2;\n const spread = high > low ? (high - low) / 2 : 1;\n if (!isNumberDimension(dimension)) return { kind: \"rank\", dimension: dimension.id, levels: dimension.levels as readonly string[], center, spread, ...conditional };\n return { kind: \"number\", dimension: dimension.id, center, spread, ...(dimension.log === true ? { log: true } : {}), ...conditional };\n}\n\n/** This function gives the factors of one dimension, each with its power. */\nfunction factorsOf(dimension: ResponseDimension, degree: number): readonly (readonly [ResponseFactor, number])[] {\n if (dimension.kind === \"categorical\") return dimension.levels.map((level) => [{ dimension: dimension.id, level }, 1] as const);\n return Array.from({ length: degree }, (_, i) => [{ dimension: dimension.id, power: i + 1 }, i + 1] as const);\n}\n\n/**\n * This function gives one column for each level of an ordinal parent inside a condition. An ordinal parent has no\n * one-hot columns of its own, so these columns carry the mean of each level with an absent child.\n */\nfunction parentColumns(dimensions: readonly ResponseDimension[]): readonly (readonly ResponseFactor[])[] {\n return dimensions.flatMap((parent) => {\n if (parent.kind !== \"ordinal\") return [];\n const conditions = dimensions.flatMap((d) => (d.when?.dimension === parent.id ? [d.when.levels] : []));\n const levels = (parent.levels as readonly ResponseValue[]).filter((level) => conditions.some((c) => c.includes(level)));\n return levels.map((level) => [{ dimension: parent.id, level }]);\n });\n}\n\n/** This function gives true when the general product of two dimensions adds nothing: a child with its parent, or two children with no common level. */\nfunction separate(a: ResponseDimension, b: ResponseDimension): boolean {\n if (a.when?.dimension === b.id || b.when?.dimension === a.id) return true;\n return a.when !== undefined && a.when.dimension === b.when?.dimension && !a.when.levels.some((level) => b.when?.levels.includes(level));\n}\n\n/**\n * This function gives the terms of the expansion: each factor, and each product of two dimensions up to `degree`. A\n * conditional dimension with two parent levels or more also has each power times each of these levels. Thus each\n * level has its own curve. With one parent level, the terms of the dimension are already the curve of this level.\n */\nfunction expansion(dimensions: readonly ResponseDimension[], degree: number, interactions: boolean): readonly (readonly ResponseFactor[])[] {\n const each = dimensions.map((d) => factorsOf(d, degree));\n const terms: (readonly ResponseFactor[])[] = [...each.flatMap((factors) => factors.map(([factor]) => [factor])), ...parentColumns(dimensions)];\n if (!interactions) return terms;\n each.forEach((first, a) => {\n each.slice(a + 1).forEach((second, offset) => {\n if (separate(dimensions[a] as ResponseDimension, dimensions[a + 1 + offset] as ResponseDimension)) return;\n for (const [f, p] of first) for (const [g, q] of second) if (p + q <= degree) terms.push([f, g]);\n });\n });\n dimensions.forEach(({ when }, a) => {\n if (when === undefined || when.levels.length < 2) return;\n for (const [factor] of each[a] as readonly (readonly [ResponseFactor, number])[]) {\n for (const level of when.levels) terms.push([factor, { dimension: when.dimension, level }]);\n }\n });\n return terms;\n}\n\n/** This function gives the terms that are not 0 at one point or more. A fold gives a term with no point the weight 0. */\nfunction seenTerms(terms: readonly (readonly ResponseFactor[])[], dimensions: readonly ResponseDimension[], points: readonly ResponsePoint[]): readonly (readonly ResponseFactor[])[] {\n const inputs = checkedInputs(dimensions, terms);\n const places = points.map((point) => ({ at: coordinates(inputs, point.values), values: point.values }));\n return terms.filter((term) => places.some(({ at, values }) => product(term, at, values) !== 0));\n}\n\n/** This function gives the inputs of a ridge fit: one for each dimension of a term. It throws for a bad term. */\nfunction checkedInputs(dimensions: readonly ResponseDimension[], terms: readonly (readonly ResponseFactor[])[]): readonly RidgeInput[] {\n const used = new Set(terms.flatMap((t) => t.map((f) => f.dimension)));\n const inputs = dimensions.filter((d) => used.has(d.id)).map(inputOf);\n const known = new Map(inputs.map((input) => [input.dimension, input]));\n const byId = new Map(dimensions.map((d) => [d.id, d]));\n terms.forEach((term, i) => {\n const [fault] = factorFaults(term, `terms[${i}]`, known, byId);\n if (fault !== undefined) throw new RangeError(`fitResponse: ${fault.path}: ${fault.message}`);\n });\n return inputs;\n}\n\n/**\n * This function gives the ridge fits of the rows of one measure. It keeps `X'X` and `X'y` of each fold, so a fit adds\n * the sums of its training folds. The first coefficient is the intercept, and it has no penalty.\n */\nfunction ridgeLearner(rows: readonly Row[], plan: Plan): { readonly learner: Learner; readonly final: () => { readonly lambda: number; readonly beta: readonly number[] } } {\n const { terms, inputs, folds, lambdas } = plan;\n const k = terms.length + 1;\n const design = new Float64Array(rows.length * k);\n const grams = Array.from({ length: folds }, () => new Float64Array(k * k));\n const moments = Array.from({ length: folds }, () => new Float64Array(k));\n rows.forEach((row, r) => {\n const at = coordinates(inputs, row.point.values);\n const offset = r * k;\n design[offset] = 1;\n terms.forEach((term, j) => {\n design[offset + j + 1] = product(term, at, row.point.values);\n });\n const gram = grams[row.fold] as Float64Array;\n const moment = moments[row.fold] as Float64Array;\n for (let a = 0; a < k; a++) {\n const value = design[offset + a] as number;\n moment[a] = (moment[a] as number) + value * row.y;\n for (let b = 0; b <= a; b++) gram[a * k + b] = (gram[a * k + b] as number) + value * (design[offset + b] as number);\n }\n });\n const predict = (beta: readonly number[], r: number): number => {\n let sum = 0;\n for (let j = 0; j < k; j++) sum += (beta[j] as number) * (design[r * k + j] as number);\n return sum;\n };\n const solve = (left: readonly (number | undefined)[], lambda: number): number[] => {\n const gram = new Float64Array(k * k);\n const moment = new Float64Array(k);\n for (let f = 0; f < folds; f++) {\n if (left.includes(f)) continue;\n const g = grams[f] as Float64Array;\n const m = moments[f] as Float64Array;\n for (let i = 0; i < k * k; i++) gram[i] = (gram[i] as number) + (g[i] as number);\n for (let i = 0; i < k; i++) moment[i] = (moment[i] as number) + (m[i] as number);\n }\n return ridgeSolve(gram, moment, lambda, { free: [0] });\n };\n // Each other fold scores a penalty on the rows outside `outer`. A tie or a singular fit keeps the larger penalty.\n const choose = (outer: number | undefined): number => {\n const descending = [...lambdas].sort((a, b) => b - a);\n let best = descending[0] as number;\n let bestError = Number.POSITIVE_INFINITY;\n for (const lambda of descending) {\n let error = 0;\n for (let f = 0; f < folds; f++) {\n if (f === outer) continue;\n const beta = solve([outer, f], lambda);\n rows.forEach((row, r) => {\n if (row.fold === f) error += (row.y - predict(beta, r)) ** 2;\n });\n }\n if (error < bestError) [best, bestError] = [lambda, error];\n }\n return best;\n };\n return {\n learner: (fold) => {\n const beta = solve([fold], choose(fold));\n return (r) => predict(beta, r);\n },\n final: () => {\n const lambda = choose(undefined);\n return { lambda, beta: solve([], lambda) };\n },\n };\n}\n\n/** This function gives the mean of the rows of each combination of levels, as cells in the order of their text. */\nfunction tableCells(rows: readonly Row[], dimensions: readonly string[]): readonly ResponseTableCell[] {\n const cells = new Map<string, { readonly at: readonly ResponseInputValue[]; readonly ys: number[] }>();\n for (const row of rows) {\n const at = dimensions.map((d) => row.point.values[d] as ResponseInputValue);\n const key = JSON.stringify(at);\n const cell = cells.get(key);\n if (cell === undefined) cells.set(key, { at, ys: [row.y] });\n else cell.ys.push(row.y);\n }\n return [...cells.keys()].sort(byText).map((key) => {\n const { at, ys } = cells.get(key) as { readonly at: readonly ResponseInputValue[]; readonly ys: number[] };\n return { at, value: mean(ys), n: ys.length };\n });\n}\n\n/** This function gives the fits of a table: the mean of each cell, or the mean of the rows for a cell with no row. */\nfunction tableLearner(rows: readonly Row[], dimensions: readonly string[]): Learner {\n const keys = rows.map((row) => JSON.stringify(dimensions.map((d) => row.point.values[d])));\n return (fold) => {\n const train = rows.filter((row) => row.fold !== fold);\n const cells = new Map(tableCells(train, dimensions).map((c) => [JSON.stringify(c.at), c.value]));\n const fallback = mean(train.map((row) => row.y));\n return (r) => cells.get(keys[r] as string) ?? fallback;\n };\n}\n\n/** This function gives the score of a fold. A fold with no held-out row or no training row has no score. */\nfunction foldScore(rows: readonly Row[], fold: number, learner: Learner): FoldScore | undefined {\n const train = rows.filter((row) => row.fold !== fold).map((row) => row.y);\n const held = rows.flatMap((row, r) => (row.fold === fold ? [r] : []));\n if (held.length === 0 || train.length === 0) return undefined;\n const predict = learner(fold);\n const baseline = mean(train);\n const predicted = held.map((r) => predict(r));\n const errors = held.map((r, i) => (rows[r] as Row).y - (predicted[i] as number));\n return {\n error: {\n n: held.length,\n mae: mean(errors.map(Math.abs)),\n rmse: Math.sqrt(mean(errors.map((e) => e * e))),\n baselineMae: mean(held.map((r) => Math.abs((rows[r] as Row).y - baseline))),\n },\n predictions: Object.fromEntries(held.map((r, i) => [(rows[r] as Row).point.id, predicted[i] as number])),\n };\n}\n\n/** This function gives the rows of a measure. It throws a RangeError for a value that a log scale cannot read. */\nfunction rowsOf(points: readonly ResponsePoint[], measure: string, log: boolean, floor: number | undefined, foldOf: ReadonlyMap<string, number>): readonly Row[] {\n return points.flatMap((point) => {\n const value = point.measures[measure];\n if (typeof value !== \"number\") return [];\n if (log && floor === undefined && value <= 0) throw new RangeError(`fitResponse: the point \"${point.id}\" has the value ${value} of the log measure \"${measure}\". Give logFloor.`);\n return [{ point, y: toModelScale(value, log, floor), fold: foldOf.get(groupKey(point)) as number }];\n });\n}\n\n/** This function gives the model of one measure on all its rows, and the score of each fold. */\nfunction fitMeasure(rows: readonly Row[], measure: ResponseMeasure, log: boolean, floor: number | undefined, plan: Plan): { readonly model: ResponseModel; readonly scores: readonly (FoldScore | undefined)[] } {\n if (rows.length === 0) throw new RangeError(`fitResponse: no point has a value of the measure \"${measure.id}\".`);\n const base = { measure: measure.id, scale: log ? (\"log\" as const) : (\"linear\" as const), ...(log && floor !== undefined ? { floor } : {}) };\n const ridge = plan.kind === \"ridge\" ? ridgeLearner(rows, plan) : undefined;\n const learner = ridge?.learner ?? tableLearner(rows, plan.ids);\n const scores = Array.from({ length: plan.folds }, (_, f) => foldScore(rows, f, learner));\n if (scores.every((s) => s === undefined)) throw new RangeError(`fitResponse: all the values of the measure \"${measure.id}\" are in one fold. Give more groups.`);\n const conditional = plan.conditional.length === 0 ? {} : { conditional: plan.conditional };\n if (ridge === undefined) return { model: { kind: \"table\", ...base, dimensions: plan.ids, ...conditional, cells: tableCells(rows, plan.ids), fallback: mean(rows.map((r) => r.y)) }, scores };\n const { lambda, beta } = ridge.final();\n if (!beta.every(Number.isFinite)) throw new RangeError(`fitResponse: the fit of the measure \"${measure.id}\" with lambda ${lambda} is singular. Give a larger lambda.`);\n const terms = plan.terms.map((factors, j) => ({ factors, weight: beta[j + 1] as number }));\n return { model: { kind: \"ridge\", ...base, lambda, inputs: plan.inputs, intercept: beta[0] as number, terms }, scores };\n}\n\n/** This function examines the options that do not depend on the data, and it gives the number of folds and the penalties. */\nfunction checkedOptions(options: ResponseFitOptions): { readonly folds: number; readonly degree: number; readonly lambdas: readonly number[] } {\n const { folds = 5, degree = 2, lambdas = RESPONSE_LAMBDAS, logFloor } = options;\n if (!Number.isSafeInteger(folds) || folds < 3) throw new RangeError(`fitResponse: folds is a whole number of 3 or more, not ${folds}.`);\n if (!Number.isSafeInteger(degree) || degree < 1 || degree > RESPONSE_MAX_POWER) throw new RangeError(`fitResponse: degree is a whole number from 1 to ${RESPONSE_MAX_POWER}, not ${degree}.`);\n if (lambdas.length === 0 || !lambdas.every((l) => Number.isFinite(l) && l > 0)) throw new RangeError(\"fitResponse: lambdas is a list of finite numbers above 0, with one item or more.\");\n if (logFloor !== undefined && !(Number.isFinite(logFloor) && logFloor > 0)) throw new RangeError(`fitResponse: logFloor is a finite number above 0, not ${logFloor}.`);\n return { folds, degree, lambdas };\n}\n\n/** This function gives the kind of model. It throws a RangeError when a table cannot read a dimension. */\nfunction kindOf(dimensions: readonly ResponseDimension[], model: \"auto\" | \"ridge\" | \"table\"): \"ridge\" | \"table\" {\n const continuous = dimensions.find((d) => d.kind === \"continuous\");\n if (model === \"table\" && continuous !== undefined) throw new RangeError(`fitResponse: a table cannot read the continuous dimension \"${continuous.id}\".`);\n if (model !== \"auto\") return model;\n return dimensions.every((d) => d.kind === \"categorical\") ? \"table\" : \"ridge\";\n}\n\n/**\n * This function fits each measure of `data`, and it gives a record with the models and the folds.\n *\n * The split: the groups, sorted and then shuffled with `seed`, go to the folds in turn. A point with no group is a\n * group of its own. Thus the repeats of one group are not on both sides of a split. The same split applies to each\n * measure. A record needs 3 groups or more.\n *\n * The model: a ridge fit over a stated expansion, or the mean of each cell of a table. The default expansion has\n * each power of each number dimension up to `degree`. It has one column for each level of a categorical dimension.\n * It also has the products of two dimensions up to `degree`. Each coordinate goes from -1 to 1 over the declared\n * range. The intercept has no penalty.\n *\n * A conditional dimension: a term with an absent dimension is 0. Thus the columns of the parent carry the mean of each\n * level with no value. A dimension with two parent levels or more also has each power times each of these levels, if\n * `interactions` is true. A table keeps `null` as a level of its cells.\n *\n * The penalty: each fold of a ridge fit chooses from `lambdas` with the other folds. Thus the held-out error of a\n * fold is not optimistic. The model of the record chooses with all the folds.\n *\n * The errors: a fold scores the model of the other folds on its held-out points, on the scale of the model. With the\n * option `outOfFold`, the fold also stores the prediction of each of these points.\n *\n * The reasons: a measure with a stated reason is `null` for the fit. The field `reasons` of the data stays in the record.\n *\n * The result does not depend on the order of the points, except for the field `points`, which keeps the order of\n * the data. The same data and options give the same bytes in one JavaScript engine.\n *\n * The function throws a RangeError for data with a fault, for a bad option, and for fewer than 3 groups. It also\n * throws for a measure with no value, and for a measure with all its values in one fold. It throws for a value of 0\n * or less on a log scale with no `logFloor`. It throws for more than `RESPONSE_MAX_TERMS` terms.\n */\nexport function fitResponse(data: ResponseData, options: ResponseFitOptions = {}): ResponseRecord {\n const [fault] = responseDataFaults(data, [], [\"models\", \"folds\"]);\n if (fault !== undefined) throw new RangeError(`fitResponse: ${fault.path === \"\" ? \"the data\" : fault.path}: ${fault.message}`);\n const { degree, lambdas, folds: wanted } = checkedOptions(options);\n const { dimensions, measures } = data;\n const log = new Set(options.log ?? []);\n for (const id of log) if (!measures.some((m) => m.id === id)) throw new RangeError(`fitResponse: the option log names the unknown measure \"${id}\".`);\n const kind = kindOf(dimensions, options.model ?? \"auto\");\n const interactions = options.interactions ?? true;\n const expanded = kind === \"table\" ? [] : (options.terms ?? expansion(dimensions, degree, interactions !== false));\n const terms = interactions === \"seen\" && options.terms === undefined ? seenTerms(expanded, dimensions, data.points) : expanded;\n if (terms.length + 1 > RESPONSE_MAX_TERMS) throw new RangeError(`fitResponse: the expansion has ${terms.length} terms, and the limit is ${RESPONSE_MAX_TERMS - 1}. Set interactions to false or \"seen\", or give terms.`);\n const inputs = checkedInputs(dimensions, terms);\n const points = [...data.points].sort((a, b) => byText(a.id, b.id));\n const groups = [...new Set(points.map(groupKey))].sort(byText);\n if (groups.length < 3) throw new RangeError(`fitResponse: the points have ${groups.length} groups, and a held-out split needs 3 or more.`);\n const folds = Math.min(wanted, groups.length);\n const shuffled = random(options.seed ?? 1).shuffle(groups);\n const foldOf = new Map(shuffled.map((group, i) => [group, i % folds]));\n const plan: Plan = { ids: dimensions.map((d) => d.id), conditional: dimensions.flatMap((d) => (d.when === undefined ? [] : [d.id])), kind, folds, lambdas, terms, inputs };\n const fits = measures.map((m) => fitMeasure(rowsOf(points, m.id, log.has(m.id), options.logFloor, foldOf), m, log.has(m.id), options.logFloor, plan));\n const foldRecords: readonly ResponseFold[] = Array.from({ length: folds }, (_, f) => {\n const scored = measures.flatMap((m, i) => {\n const score = fits[i]?.scores[f];\n return score === undefined ? [] : [[m.id, score] as const];\n });\n return {\n heldOut: points.filter((p) => foldOf.get(groupKey(p)) === f).map((p) => p.id),\n errors: Object.fromEntries(scored.map(([id, score]) => [id, score.error])),\n ...(options.outOfFold === true ? { predictions: Object.fromEntries(scored.map(([id, score]) => [id, score.predictions])) } : {}),\n };\n });\n const reasons = data.reasons === undefined ? {} : { reasons: data.reasons };\n return { schema: RESPONSE_RECORDS_SCHEMA, name: data.name, dimensions, measures, ...reasons, points: data.points, models: fits.map((fit) => fit.model), folds: foldRecords };\n}\n","/**\n * The Sobol indices of a fitted model of a record of the format `response-records/1`. The first-order index of a\n * dimension is the share of the variance of the prediction that the dimension causes alone. The total index also\n * includes each interaction of the dimension with the other dimensions.\n *\n * The method is Monte Carlo with two independent matrices A and B of N rows, and one matrix `AB_i` for each dimension `i`.\n * `AB_i` is A with the column `i` of B (Saltelli and others, 2010). The first-order index uses the estimator of Saltelli\n * (2010), and the total index uses the estimator of Jansen (1999). The model gets N * (d + 2) evaluations for d dimensions.\n *\n * This file uses no Node import, no clock and no `Math.random`, the same as `response.ts`.\n */\nimport { random, type Random } from \"@mark1russell7/rigor-generators\";\nimport { type BootstrapOptions, type Interval, percentiles } from \"./bootstrap.ts\";\nimport { type ResponseDimension, type ResponseInputValue, type ResponseRecord, predictScaled, predictResponse, whenHolds } from \"./response.ts\";\n\n/** The options of `sobolIndices`. */\nexport interface SobolOptions {\n /** The number N of rows of each base matrix. The default is 4096. */\n readonly n?: number;\n /** The seed of the draws. The default is 1. */\n readonly seed?: number | string;\n /**\n * The scale of the output. The value `measure` uses `predictResponse`. The value `model` uses the scale of the\n * model, so a model with a log scale gives the indices of the logarithm. The default is `measure`.\n */\n readonly scale?: \"measure\" | \"model\";\n /**\n * With this option, each index also gets a percentile bootstrap interval over the N rows. Each run draws N rows\n * with replacement, and it calculates all the indices from these rows. The default is no interval.\n */\n readonly interval?: BootstrapOptions;\n}\n\n/** The two Sobol indices of one dimension. */\nexport interface SobolIndex {\n /** The id of the dimension. */\n readonly dimension: string;\n /** The first-order index S_i: the estimator of Saltelli (2010). */\n readonly first: number;\n /** The total index ST_i: the estimator of Jansen (1999). */\n readonly total: number;\n /** The bootstrap interval of `first`. Only the option `interval` writes this field. */\n readonly firstInterval?: Interval;\n /** The bootstrap interval of `total`. Only the option `interval` writes this field. */\n readonly totalInterval?: Interval;\n}\n\n/** The result of `sobolIndices`. */\nexport interface SobolIndices {\n /** The id of the measure. */\n readonly measure: string;\n /** The scale of the output. */\n readonly scale: \"measure\" | \"model\";\n /** The number N of rows of each base matrix. */\n readonly n: number;\n /** The number of model evaluations: N * (d + 2). */\n readonly evaluations: number;\n /** The seed as a 32-bit number. */\n readonly seed: number;\n /** The mean of the outputs of A and B. */\n readonly mean: number;\n /** The variance of the outputs of A and B, with the divisor 2N. */\n readonly variance: number;\n /** The indices of each dimension of the record, in the order of the record. */\n readonly indices: readonly SobolIndex[];\n}\n\n/** This function draws one value of a dimension. Each dimension uses the same number of draws: one. */\nfunction drawValue(dimension: ResponseDimension, r: Random): number | string {\n if (dimension.kind !== \"continuous\") return dimension.levels[r.below(dimension.levels.length)] as number | string;\n const [low, high] = dimension.range;\n if (dimension.log !== true) return r.range(low, high);\n const value = 10 ** r.range(Math.log10(low), Math.log10(high));\n return Math.min(high, Math.max(low, value));\n}\n\n/** This function draws a matrix of `n` rows, row by row, with one draw for each dimension in the order of the record. */\nfunction drawMatrix(dimensions: readonly ResponseDimension[], n: number, r: Random): (number | string)[][] {\n return Array.from({ length: n }, () => dimensions.map((d) => drawValue(d, r)));\n}\n\n/** This function gives the inputs of a row. A conditional dimension gets `null` where its condition fails. */\nfunction inputsOf(dimensions: readonly ResponseDimension[], row: readonly (number | string)[]): Record<string, ResponseInputValue> {\n const drawn: Record<string, ResponseInputValue> = {};\n dimensions.forEach((d, i) => {\n drawn[d.id] = row[i] as number | string;\n });\n const inputs: Record<string, ResponseInputValue> = {};\n for (const d of dimensions) inputs[d.id] = whenHolds(d, drawn) ? (drawn[d.id] as ResponseInputValue) : null;\n return inputs;\n}\n\n/** The outputs of the matrices, as the model gives them. The estimators subtract the mean where they use it. */\ninterface Outputs {\n readonly a: Float64Array;\n readonly b: Float64Array;\n /** The outputs of `AB_i` for each dimension `i`. */\n readonly ab: readonly Float64Array[];\n}\n\n/**\n * This function gives the variance and the indices from the rows `rows`. A variance of 0 gives each index as 0.\n * The value `constant` is true when each output is equal to the first output.\n */\nfunction estimate(outputs: Outputs, rows: readonly number[] | null, n: number, constant: boolean): { mean: number; variance: number; first: number[]; total: number[] } {\n const d = outputs.ab.length;\n const at = (j: number): number => (rows === null ? j : (rows[j] as number));\n let sum = 0;\n for (let j = 0; j < n; j++) sum += (outputs.a[at(j)] as number) + (outputs.b[at(j)] as number);\n const mean = sum / (2 * n);\n let square = 0;\n for (let j = 0; j < n; j++) {\n const ea = (outputs.a[at(j)] as number) - mean;\n const eb = (outputs.b[at(j)] as number) - mean;\n square += ea * ea + eb * eb;\n }\n const variance = constant ? 0 : square / (2 * n);\n const first: number[] = [];\n const total: number[] = [];\n for (let i = 0; i < d; i++) {\n const abi = outputs.ab[i] as Float64Array;\n let s = 0;\n let t = 0;\n for (let j = 0; j < n; j++) {\n const fa = outputs.a[at(j)] as number;\n const fb = outputs.b[at(j)] as number;\n const fab = abi[at(j)] as number;\n s += (fb - mean) * (fab - fa);\n t += (fa - fab) * (fa - fab);\n }\n first.push(variance > 0 ? s / n / variance : 0);\n total.push(variance > 0 ? t / (2 * n) / variance : 0);\n }\n return { mean, variance, first, total };\n}\n\n/**\n * This function gives the first-order and the total Sobol index of each dimension of a record, for the model of\n * `measure`. The indices are of the prediction of the model, not of the measured points.\n *\n * The input distribution:\n * - Each dimension is independent of the other dimensions.\n * - A continuous dimension is uniform over its range. With `log`, the logarithm of the value is uniform.\n * - An ordinal or a categorical dimension is uniform over its levels.\n * - A conditional dimension gets an independent draw. The model gets `null` for it where `whenHolds` fails for the drawn parent.\n *\n * Thus the inputs stay independent, and the indices have their usual meaning. A parent gets the effect of the absence of its child.\n *\n * The estimators:\n * - The first-order index is `mean(f(B) * (f(AB_i) - f(A))) / V` (Saltelli, 2010).\n * - The total index is `mean((f(A) - f(AB_i)) ** 2) / 2 / V` (Jansen, 1999).\n * - V is the variance of the outputs of A and B together.\n * - The variance uses the outputs of A and B less their mean. The first-order sum uses `f(B)` less that mean.\n * - The total sum uses differences of outputs, so it uses no mean.\n * - This step keeps the estimators unbiased, and it decreases their error when the mean is large.\n *\n * A model with a constant output has the variance 0. Then each index is 0, not NaN. An estimate can be a little\n * below 0 or above 1, from the Monte Carlo error. The function does not clip it.\n *\n * The draws fill A row by row, then B row by row. Each row has one draw for each dimension, in the order of the\n * record. Thus the same seed gives the same indices. The model can ignore a dimension. Then that dimension gets 0 for both\n * indices exactly, unless it is the parent of a dimension that the model reads.\n *\n * The function throws a RangeError when the record has no model of `measure`, and when N is not a whole number of 2 or more.\n * `predictResponse` throws for a value that the model refuses, for example a level that the model does not know.\n */\nexport function sobolIndices(record: Pick<ResponseRecord, \"dimensions\" | \"models\">, measure: string, options: SobolOptions = {}): SobolIndices {\n const model = record.models.find((m) => m.measure === measure);\n if (model === undefined) throw new RangeError(`sobolIndices: the record has no model of the measure \"${measure}\".`);\n const n = options.n ?? 4096;\n if (!Number.isSafeInteger(n) || n < 2) throw new RangeError(`sobolIndices: n is a whole number of 2 or more, not ${n}.`);\n const scale = options.scale ?? \"measure\";\n const dimensions = record.dimensions;\n const d = dimensions.length;\n const r = random(options.seed ?? 1);\n const a = drawMatrix(dimensions, n, r);\n const b = drawMatrix(dimensions, n, r);\n const f = (row: readonly (number | string)[]): number => {\n const inputs = inputsOf(dimensions, row);\n return scale === \"model\" ? predictScaled(model, inputs) : predictResponse(model, inputs);\n };\n const fa = Float64Array.from(a, f);\n const fb = Float64Array.from(b, f);\n const ab = dimensions.map((_, i) => Float64Array.from(a, (row, j) => f(row.map((v, k) => (k === i ? ((b[j] as (number | string)[])[i] as number | string) : v)))));\n const outputs: Outputs = { a: fa, b: fb, ab };\n const first = fa[0] as number;\n const constant = fa.every((v) => v === first) && fb.every((v) => v === first);\n const all = estimate(outputs, null, n, constant);\n let intervals: Interval[] | undefined;\n if (options.interval !== undefined) {\n const rows = new Array<number>(n);\n const flat = (e: { first: number[]; total: number[] }): number[] => [...e.first, ...e.total];\n intervals = percentiles(\n \"sobolIndices\",\n options.interval,\n 2 * d,\n (rr) => {\n for (let j = 0; j < n; j++) rows[j] = rr.below(n);\n return flat(estimate(outputs, rows, n, constant));\n },\n () => flat(all),\n );\n }\n const indices = dimensions.map((dimension, i): SobolIndex => {\n const index = { dimension: dimension.id, first: all.first[i] as number, total: all.total[i] as number };\n if (intervals === undefined) return index;\n return { ...index, firstInterval: intervals[i] as Interval, totalInterval: intervals[d + i] as Interval };\n });\n return { measure, scale, n, evaluations: n * (d + 2), seed: r.seed, mean: constant ? first : all.mean, variance: all.variance, indices };\n}\n","/**\n * The tests of a difference: the sign test, the paired permutation test, the Wilson interval of a proportion and\n * the Holm correction for several tests.\n */\nimport { random } from \"@mark1russell7/rigor-generators\";\nimport { mean, median } from \"./describe.ts\";\n\nfunction whole(name: string, value: number): void {\n if (!Number.isSafeInteger(value) || value < 0) throw new RangeError(`${name}: ${value} is not a whole number of 0 or more.`);\n}\n\n/** The log of each binomial term C(n, k) / 2^n, for each k from 0 to n. */\nfunction halfBinomialLogs(n: number): number[] {\n const logs: number[] = [];\n let logChoose = 0;\n for (let i = 0; i <= n; i++) {\n if (i > 0) logChoose += Math.log((n - i + 1) / i);\n logs.push(logChoose - n * Math.LN2);\n }\n return logs;\n}\n\n/** P(X >= k) for X ~ Binomial(n, 1/2), summed from the largest term so that a small tail keeps its digits. */\nfunction upperTail(k: number, n: number): number {\n if (k <= 0) return 1;\n if (k > n) return 0;\n const logs = halfBinomialLogs(n).slice(k);\n const top = Math.max(...logs);\n const sum = logs.reduce((s, l) => s + Math.exp(l - top), 0);\n return Math.min(1, Math.exp(top) * sum);\n}\n\n/**\n * The sign test of paired results: `better` inputs where the candidate wins and `worse` where it loses. The ties\n * do not count. One-sided (the default), it is the p of `better` wins or more if the two are equal. Two-sided, it is\n * two times the tail of the larger count, at most 1. The one-sided p is equal to `signTestP` of packing.\n */\nexport function signTest(better: number, worse: number, sides: 1 | 2 = 1): number {\n whole(\"signTest\", better);\n whole(\"signTest\", worse);\n const n = better + worse;\n if (n === 0) return 1;\n if (sides === 1) return upperTail(better, n);\n return Math.min(1, 2 * upperTail(Math.max(better, worse), n));\n}\n\n/**\n * The smallest number of wins out of `n` that the sign test calls significant at `level`. It is undefined when even\n * n wins out of n are not enough. Use it before a run, to know how many inputs a claim needs.\n */\nexport function signTestPower(n: number, level = 0.05, sides: 1 | 2 = 2): number | undefined {\n whole(\"signTestPower\", n);\n for (let k = Math.ceil(n / 2); k <= n; k++) if (signTest(k, n - k, sides) < level) return k;\n return undefined;\n}\n\n/** The z of a two-sided 95% interval. */\nexport const Z95 = 1.959963984540054;\n\n/** An interval of a proportion. */\nexport interface Proportion {\n readonly low: number;\n readonly high: number;\n}\n\n/**\n * The Wilson score interval of `k` successes in `n` trials (Wilson, 1927). It keeps its level for a small n and for\n * a proportion near 0 or 1, where the normal interval does not. For n = 0 the interval is 0 to 1.\n */\nexport function wilson(k: number, n: number, z: number = Z95): Proportion {\n whole(\"wilson\", k);\n whole(\"wilson\", n);\n if (k > n) throw new RangeError(`wilson: k ${k} is more than n ${n}.`);\n if (n === 0) return { low: 0, high: 1 };\n const p = k / n;\n const z2 = z * z;\n const denominator = 1 + z2 / n;\n const center = (p + z2 / (2 * n)) / denominator;\n const half = (z / denominator) * Math.sqrt((p * (1 - p)) / n + z2 / (4 * n * n));\n return { low: Math.max(0, center - half), high: Math.min(1, center + half) };\n}\n\n/** One test after the Holm correction. */\nexport interface Corrected {\n /** The p of the test. */\n readonly p: number;\n /** The p after the correction: compare it with the level of the whole family. */\n readonly adjusted: number;\n /** The adjusted p is less than the level. */\n readonly reject: boolean;\n}\n\n/**\n * The Holm step-down correction of a family of tests (Holm, 1979). It keeps the chance of one false claim or more\n * in the family at most `level`. It has no condition on how the tests depend on each other. The result is in the\n * order of the input.\n */\nexport function holm(pValues: readonly number[], level = 0.05): Corrected[] {\n for (const p of pValues) if (!(p >= 0 && p <= 1)) throw new RangeError(`holm: each p is from 0 to 1, not ${p}.`);\n const m = pValues.length;\n const order = pValues.map((p, i) => ({ p, i })).sort((a, b) => a.p - b.p || a.i - b.i);\n const adjusted = new Array<number>(m);\n let running = 0;\n order.forEach(({ p, i }, rank) => {\n running = Math.max(running, Math.min(1, (m - rank) * p));\n adjusted[i] = running;\n });\n return pValues.map((p, i) => ({ p, adjusted: adjusted[i] as number, reject: (adjusted[i] as number) < level }));\n}\n\n/**\n * The p of the claim \"at least `need` of these tests have a real effect\" (Benjamini and Heller, 2008). The value is\n * `(m - need + 1)` times the `need`-th smallest p, at most 1. It has no condition on how the tests depend on each other.\n * With 2 tests and `need` 2, the value is the larger p.\n */\nexport function partialConjunction(pValues: readonly number[], need: number): number {\n for (const p of pValues) if (!(p >= 0 && p <= 1)) throw new RangeError(`partialConjunction: each p is from 0 to 1, not ${p}.`);\n whole(\"partialConjunction\", need);\n const m = pValues.length;\n if (need < 1 || need > m) throw new RangeError(`partialConjunction: need is from 1 to the count of tests ${m}, not ${need}.`);\n const sorted = [...pValues].sort((a, b) => a - b);\n return Math.min(1, (m - need + 1) * (sorted[need - 1] as number));\n}\n\nexport interface PermutationOptions {\n /** The number of random sign flips. The default is 10 000. */\n readonly runs?: number;\n /** The default is 1. */\n readonly seed?: number | string;\n /** The statistic of the differences. The default is the mean. */\n readonly statistic?: (differences: readonly number[]) => number;\n}\n\nexport interface PermutationResult {\n /** The statistic of the observed differences `candidate[i] - baseline[i]`. */\n readonly observed: number;\n /** The two-sided p: (1 + the flips with a statistic as far from 0 or farther) / (1 + runs). */\n readonly p: number;\n readonly runs: number;\n}\n\n/**\n * The paired permutation test (a random sign flip of each difference). It needs no normal distribution and uses\n * the size of each difference, which the sign test does not. A pair with a difference of 0 adds nothing.\n */\nexport function pairedPermutation(candidate: readonly number[], baseline: readonly number[], options: PermutationOptions = {}): PermutationResult {\n if (candidate.length !== baseline.length) throw new RangeError(`pairedPermutation: the lists have ${candidate.length} and ${baseline.length} values.`);\n const differences = candidate.map((c, i) => c - (baseline[i] as number));\n const statistic = options.statistic ?? mean;\n const runs = options.runs ?? 10_000;\n if (!Number.isSafeInteger(runs) || runs < 1) throw new RangeError(`pairedPermutation: runs is a whole number of 1 or more, not ${runs}.`);\n const observed = statistic(differences);\n const r = random(options.seed ?? 1);\n const flipped = new Array<number>(differences.length);\n let extreme = 0;\n for (let run = 0; run < runs; run++) {\n for (let i = 0; i < differences.length; i++) flipped[i] = r.next() < 0.5 ? -(differences[i] as number) : (differences[i] as number);\n // A small tolerance, so that a flip with the same statistic up to rounding counts as extreme.\n if (Math.abs(statistic(flipped)) >= Math.abs(observed) * (1 - 1e-12)) extreme++;\n }\n return { observed, p: (1 + extreme) / (1 + runs), runs };\n}\n\n/** The default of the option `exactMax` of `signFlipTest`. */\nexport const SIGN_FLIP_EXACT_MAX = 16;\n\n/** The largest value of the option `exactMax` of `signFlipTest`: 2^24 sign sets. */\nexport const SIGN_FLIP_EXACT_LIMIT = 24;\n\n/** The options of `signFlipTest`. */\nexport interface SignFlipOptions {\n /** The largest count of terms for which the test reads each of the `2^n` sign sets. The default is 16. The most is 24. */\n readonly exactMax?: number;\n /** The count of random sign sets above `exactMax`. The default is 10 000. */\n readonly runs?: number;\n /** The default is 1. */\n readonly seed?: number | string;\n}\n\n/** The result of `signFlipTest`. */\nexport interface SignFlipResult {\n /** The absolute value of the sum of the terms. */\n readonly observed: number;\n /** The two-sided p. */\n readonly p: number;\n /** This field is true when the test read each sign set, so the p has no noise from the draws. */\n readonly exact: boolean;\n /** The count of the sign sets that the test read: `2^n` when it is exact, otherwise the count of the draws. */\n readonly runs: number;\n}\n\n/**\n * The sign-flip test of a sum of terms. Under the null, each term has the sign + or - with equal chance. The statistic\n * is the absolute value of the sum. A weighted mean of paired differences is such a sum: give the terms `w[i] * d[i]`.\n *\n * Up to `exactMax` terms, the test reads each sign set. The p is the share of the sets that are as far from 0 or\n * farther. The observed set is one of them. Above `exactMax`, the test draws `runs` sets, and the p is (1 + the extreme\n * draws) / (1 + runs). A sum within `1e-12` of the sum of the absolute terms counts as extreme, so rounding does not\n * hide a tie.\n */\nexport function signFlipTest(terms: readonly number[], options: SignFlipOptions = {}): SignFlipResult {\n const exactMax = options.exactMax ?? SIGN_FLIP_EXACT_MAX;\n if (!Number.isInteger(exactMax) || exactMax < 0 || exactMax > SIGN_FLIP_EXACT_LIMIT) {\n throw new RangeError(`signFlipTest: exactMax is a whole number from 0 to ${SIGN_FLIP_EXACT_LIMIT}, not ${exactMax}.`);\n }\n for (const [i, t] of terms.entries()) if (!Number.isFinite(t)) throw new RangeError(`signFlipTest: the term ${i} is ${t}, not a finite number.`);\n const n = terms.length;\n const observed = Math.abs(terms.reduce((sum, t) => sum + t, 0));\n const slack = 1e-12 * terms.reduce((sum, t) => sum + Math.abs(t), 0);\n if (n <= exactMax) {\n const total = 2 ** n;\n let hits = 0;\n for (let mask = 0; mask < total; mask++) {\n let sum = 0;\n for (let i = 0; i < n; i++) sum += mask & (1 << i) ? -(terms[i] as number) : (terms[i] as number);\n if (Math.abs(sum) >= observed - slack) hits++;\n }\n return { observed, p: hits / total, exact: true, runs: total };\n }\n const runs = options.runs ?? 10_000;\n if (!Number.isSafeInteger(runs) || runs < 1) throw new RangeError(`signFlipTest: runs is a whole number of 1 or more, not ${runs}.`);\n const r = random(options.seed ?? 1);\n let hits = 0;\n for (let run = 0; run < runs; run++) {\n let sum = 0;\n for (let i = 0; i < n; i++) sum += r.next() < 0.5 ? -(terms[i] as number) : (terms[i] as number);\n if (Math.abs(sum) >= observed - slack) hits++;\n }\n return { observed, p: (1 + hits) / (1 + runs), exact: false, runs };\n}\n\n/** The options of `twoSamplePermutation`. */\nexport interface TwoSamplePermutationOptions {\n /** The largest number of splits that the test reads. The default is 10 000. */\n readonly runs?: number;\n /** The default is 1. */\n readonly seed?: number | string;\n /** The statistic of the two groups. The default is the median of `a` minus the median of `b`. */\n readonly statistic?: (a: readonly number[], b: readonly number[]) => number;\n}\n\n/** The result of `twoSamplePermutation`. */\nexport interface TwoSamplePermutationResult extends PermutationResult {\n /** This field is true when the test read each split, so the p has no noise from the draws. */\n readonly exact: boolean;\n}\n\n/** This function gives the count of the ways to choose `k` of `n`, or Infinity when the count is over `limit`. */\nfunction choices(n: number, k: number, limit: number): number {\n const small = Math.min(k, n - k);\n let count = 1;\n for (let i = 1; i <= small; i++) {\n // The product of i consecutive whole numbers divides by i!, so each step gives a whole number.\n count = (count * (n - small + i)) / i;\n if (count > limit) return Number.POSITIVE_INFINITY;\n }\n return count;\n}\n\n/** This function counts the splits of `pool` into a first group of `size` values that pass the test `extreme`, over each split. */\nfunction countEachSplit(pool: readonly number[], size: number, extreme: (a: readonly number[], b: readonly number[]) => boolean): number {\n const chosen = Array.from({ length: size }, (_, i) => i);\n let count = 0;\n for (;;) {\n const a: number[] = [];\n const b: number[] = [];\n for (const [i, value] of pool.entries()) (chosen[a.length] === i ? a : b).push(value);\n if (extreme(a, b)) count++;\n let place = size - 1;\n while (place >= 0 && chosen[place] === pool.length - size + place) place--;\n if (place < 0) return count;\n let index = (chosen[place] as number) + 1;\n for (let j = place; j < size; j++) chosen[j] = index++;\n }\n}\n\n/**\n * The two-sample permutation test (a split of the pooled values). It needs no normal distribution and no pairs, so it\n * compares groups of different sizes. The p holds only if the values of the two groups can change places under the null.\n *\n * When the count of the splits is `runs` or less, the test reads each split, and the p is exact. Otherwise it draws `runs`\n * random splits. A drawn p has noise: a level of 0.001 is 10 counts at 10 000 runs. So give enough runs for a small level.\n */\nexport function twoSamplePermutation(a: readonly number[], b: readonly number[], options: TwoSamplePermutationOptions = {}): TwoSamplePermutationResult {\n if (a.length === 0 || b.length === 0) throw new RangeError(`twoSamplePermutation: the groups have ${a.length} and ${b.length} values, and each group needs one or more.`);\n const statistic = options.statistic ?? ((x: readonly number[], y: readonly number[]): number => median(x) - median(y));\n const runs = options.runs ?? 10_000;\n if (!Number.isSafeInteger(runs) || runs < 1) throw new RangeError(`twoSamplePermutation: runs is a whole number of 1 or more, not ${runs}.`);\n const observed = statistic(a, b);\n const pool = [...a, ...b];\n // The same tolerance as `pairedPermutation`: a split with the same statistic up to rounding counts as extreme.\n const isExtreme = (x: readonly number[], y: readonly number[]): boolean => Math.abs(statistic(x, y)) >= Math.abs(observed) * (1 - 1e-12);\n const splits = choices(pool.length, a.length, runs);\n if (Number.isFinite(splits)) return { observed, p: countEachSplit(pool, a.length, isExtreme) / splits, runs: splits, exact: true };\n const r = random(options.seed ?? 1);\n let extreme = 0;\n for (let run = 0; run < runs; run++) {\n // The first a.length places of a partial Fisher-Yates shuffle are a uniform choice of the first group.\n for (let i = 0; i < a.length; i++) {\n const j = i + Math.floor(r.next() * (pool.length - i));\n const held = pool[i] as number;\n pool[i] = pool[j] as number;\n pool[j] = held;\n }\n if (isExtreme(pool.slice(0, a.length), pool.slice(a.length))) extreme++;\n }\n return { observed, p: (1 + extreme) / (1 + runs), runs, exact: false };\n}\n\n/**\n * The smallest number of trials `n` at which the Wilson lower end reaches `target`, when the true proportion is\n * `expected`. Each `n` takes `round(expected × n)` successes. The function gives `undefined` when `expected` is not\n * above `target`, or when no `n` up to `max` reaches it. An audit of an agreement uses it to fix its size.\n */\nexport function wilsonSampleSize(target: number, expected: number, z: number = Z95, max = 1_000_000): number | undefined {\n if (!(target >= 0 && target <= 1 && expected >= 0 && expected <= 1)) throw new RangeError(`wilsonSampleSize: target ${target} and expected ${expected} must be from 0 to 1.`);\n whole(\"wilsonSampleSize\", max);\n if (expected <= target) return undefined;\n for (let n = 1; n <= max; n++) if (wilson(Math.round(expected * n), n, z).low >= target) return n;\n return undefined;\n}\n","/** The agreement of two raters that give one category to each item. */\nexport interface Kappa {\n /** The number of items. */\n readonly n: number;\n /** The part of the items where the two raters give the same category. */\n readonly observed: number;\n /** The part of agreement that two independent raters with the same frequencies of categories give. */\n readonly chance: number;\n /** Cohen's kappa: `(observed − chance) / (1 − chance)`. It is `undefined` when `chance` is 1. */\n readonly kappa: number | undefined;\n}\n\n/**\n * Cohen's kappa of two raters (Cohen, 1960). Item `i` has the category `a[i]` from one rater and `b[i]` from the\n * other. Two categories are the same when they are `===`. A kappa of 1 is full agreement, and 0 is the agreement of chance.\n */\nexport function cohenKappa<T>(a: readonly T[], b: readonly T[]): Kappa {\n if (a.length !== b.length) throw new RangeError(`cohenKappa: the raters have ${a.length} and ${b.length} items.`);\n const n = a.length;\n if (n === 0) throw new RangeError(\"cohenKappa: there are no items.\");\n const countA = new Map<T, number>();\n const countB = new Map<T, number>();\n let same = 0;\n for (let i = 0; i < n; i++) {\n const x = a[i] as T;\n const y = b[i] as T;\n if (x === y) same++;\n countA.set(x, (countA.get(x) ?? 0) + 1);\n countB.set(y, (countB.get(y) ?? 0) + 1);\n }\n let chance = 0;\n for (const [category, count] of countA) chance += (count / n) * ((countB.get(category) ?? 0) / n);\n const observed = same / n;\n return { n, observed, chance, kappa: chance === 1 ? undefined : (observed - chance) / (1 - chance) };\n}\n","/**\n * Rank correlation: do two measures put the same items in the same order? Use it to test that a cheap proxy (a\n * predicted cost, a fast measure) orders the items as the real measure does.\n */\nimport { random } from \"@mark1russell7/rigor-generators\";\n\nfunction samePairs(name: string, a: readonly number[], b: readonly number[]): void {\n if (a.length !== b.length) throw new RangeError(`${name}: the lists have ${a.length} and ${b.length} values.`);\n for (const v of a) if (Number.isNaN(v)) throw new RangeError(`${name}: the first list has a NaN.`);\n for (const v of b) if (Number.isNaN(v)) throw new RangeError(`${name}: the second list has a NaN.`);\n}\n\n/** The ranks of the values, from 1. Equal values get the mean of their ranks. */\nexport function ranks(values: readonly number[]): number[] {\n const order = values.map((x, i) => [x, i] as const).sort((p, q) => p[0] - q[0]);\n const out = new Array<number>(values.length);\n for (let i = 0; i < order.length; ) {\n let j = i;\n while (j + 1 < order.length && (order[j + 1] as readonly [number, number])[0] === (order[i] as readonly [number, number])[0]) j++;\n for (let k = i; k <= j; k++) out[(order[k] as readonly [number, number])[1]] = (i + j) / 2 + 1;\n i = j + 1;\n }\n return out;\n}\n\n/**\n * The Spearman rank correlation: the Pearson correlation of the ranks, with mean ranks for ties. The value is from\n * -1 to 1. When one list has no spread, the value is 0. It is equal to the copy in the backtest of highways.\n */\nexport function spearman(a: readonly number[], b: readonly number[]): number {\n samePairs(\"spearman\", a, b);\n const ra = ranks(a);\n const rb = ranks(b);\n const mean = (xs: readonly number[]): number => xs.reduce((s, x) => s + x, 0) / xs.length;\n const ma = mean(ra);\n const mb = mean(rb);\n let num = 0;\n let da = 0;\n let db = 0;\n for (let i = 0; i < ra.length; i++) {\n num += ((ra[i] as number) - ma) * ((rb[i] as number) - mb);\n da += ((ra[i] as number) - ma) ** 2;\n db += ((rb[i] as number) - mb) ** 2;\n }\n return da === 0 || db === 0 ? 0 : num / Math.sqrt(da * db);\n}\n\n/** The largest number of values for which `kendallTau` examines each pair. Above it, a seeded sample of pairs. */\nexport const KENDALL_EXACT = 1500;\nconst KENDALL_SAMPLE = 200_000;\n\n/**\n * The Kendall tau-b of two lists (Kendall, 1938). The value is from -1 to 1. A pair with a tie in both lists does\n * not count. When the lists have fewer than 2 values, or no pair counts, the value is 1. Above `KENDALL_EXACT`\n * values, a seeded sample of 200 000 pairs gives an estimate. It is equal to the copy in highways.\n */\nexport function kendallTau(a: readonly number[], b: readonly number[], seed: number | string = 1): number {\n samePairs(\"kendallTau\", a, b);\n const n = a.length;\n if (n < 2) return 1;\n let concordant = 0;\n let discordant = 0;\n let tieA = 0;\n let tieB = 0;\n const visit = (i: number, j: number): void => {\n const da = Math.sign((a[i] as number) - (a[j] as number));\n const db = Math.sign((b[i] as number) - (b[j] as number));\n if (da === 0 && db === 0) return;\n if (da === 0) tieA++;\n else if (db === 0) tieB++;\n else if (da === db) concordant++;\n else discordant++;\n };\n if (n <= KENDALL_EXACT) {\n for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) visit(i, j);\n } else {\n const r = random(seed);\n for (let k = 0; k < KENDALL_SAMPLE; k++) {\n const i = r.below(n);\n const j = r.below(n);\n if (i !== j) visit(i, j);\n }\n }\n const den = Math.sqrt((concordant + discordant + tieA) * (concordant + discordant + tieB));\n return den === 0 ? 1 : (concordant - discordant) / den;\n}\n","/**\n * The intervals that come from a discrete distribution. The interval of a median or of a quantile comes from the order\n * statistics. The central interval of a count comes from a binomial or a negative binomial distribution.\n */\nimport { sorted } from \"./describe.ts\";\n\nfunction whole(name: string, value: number): void {\n if (!Number.isSafeInteger(value) || value < 0) throw new RangeError(`${name}: ${value} is not a whole number of 0 or more.`);\n}\n\nfunction levelOf(name: string, level: number): number {\n if (!(level > 0 && level < 1)) throw new RangeError(`${name}: the level is more than 0 and less than 1, not ${level}.`);\n return (1 - level) / 2;\n}\n\n/** The chance of each count k from 0 to n of X ~ Binomial(n, p), from the logs of the terms. */\nfunction binomialTerms(n: number, p: number): number[] {\n if (p === 0) return Array.from({ length: n + 1 }, (_, k) => (k === 0 ? 1 : 0));\n if (p === 1) return Array.from({ length: n + 1 }, (_, k) => (k === n ? 1 : 0));\n const [logP, logQ] = [Math.log(p), Math.log1p(-p)];\n const terms: number[] = [];\n let logChoose = 0;\n for (let k = 0; k <= n; k++) {\n if (k > 0) logChoose += Math.log((n - k + 1) / k);\n terms.push(Math.exp(logChoose + k * logP + (n - k) * logQ));\n }\n return terms;\n}\n\n/** The distribution-free interval of a median, from two order statistics of the sample. */\nexport interface MedianInterval {\n readonly low: number;\n readonly high: number;\n /** The rank k of `low`, from 1. The interval is from x_(k) to x_(n + 1 - k) of the sorted values. */\n readonly rank: number;\n /** The chance that the interval holds the median of the population: 1 - 2 P(X <= k - 1), for X ~ Binomial(n, 1/2). */\n readonly coverage: number;\n}\n\n/**\n * The distribution-free interval of the median of a sample. It needs no assumption about the shape of the\n * distribution. It is x_(k) to x_(n + 1 - k), for the largest k whose two tails each hold (1 - level) / 2 or less.\n * For 11 values at the level 0.95, it is x_(2) to x_(10), with the coverage 0.988.\n *\n * A sample of 5 values or fewer has no rank with that coverage. Then the interval is the full range, and `coverage`\n * is less than `level`.\n */\nexport function medianInterval(values: readonly number[], level = 0.95): MedianInterval {\n if (values.length === 0) throw new RangeError(\"medianInterval: the list is empty.\");\n for (const v of values) if (Number.isNaN(v)) throw new RangeError(\"medianInterval: the list has a NaN.\");\n const tail = levelOf(\"medianInterval\", level);\n const s = sorted(values);\n const n = s.length;\n const terms = binomialTerms(n, 0.5);\n // The rank k + 1 is possible if P(X <= k), the tail that it leaves out on each side, is the tail or less.\n let k = 0;\n let below = terms[0] as number;\n while (k + 1 <= n / 2 && below <= tail) {\n k += 1;\n below += terms[k] as number;\n }\n const rank = Math.max(1, k);\n let left = 0;\n for (let i = 0; i < rank; i++) left += terms[i] as number;\n return { low: s[rank - 1] as number, high: s[n - rank] as number, rank, coverage: Math.max(0, 1 - 2 * left) };\n}\n\n/** The distribution-free interval of a quantile, from two order statistics of the sample. */\nexport interface QuantileInterval {\n /** The value x_(lowRank), or `-Infinity` when the sample has no rank for a lower bound. */\n readonly low: number;\n /** The value x_(highRank), or `Infinity` when the sample has no rank for an upper bound. */\n readonly high: number;\n /** The rank of `low`, from 1, or 0 when `low` is `-Infinity`. */\n readonly lowRank: number;\n /** The rank of `high`, from 1, or n + 1 when `high` is `Infinity`. */\n readonly highRank: number;\n /** The chance that the interval holds the quantile of the population. */\n readonly coverage: number;\n}\n\n/**\n * This function gives the distribution-free interval of the quantile `p` of a sample. Each tail outside the interval holds\n * (1 - level) / 2 or less. Let X ~ Binomial(n, p). The lower rank is the largest l with P(X <= l - 1) in the tail. The upper\n * rank is the smallest u with P(X >= u) in the tail. The values must be independent draws, or the coverage is false.\n *\n * A side with no such rank is infinite. Thus a small sample gives no upper bound: refer to `quantileSamples`.\n */\nexport function quantileInterval(values: readonly number[], p: number, level = 0.95): QuantileInterval {\n if (values.length === 0) throw new RangeError(\"quantileInterval: the list is empty.\");\n for (const v of values) if (Number.isNaN(v)) throw new RangeError(\"quantileInterval: the list has a NaN.\");\n if (!(p > 0 && p < 1)) throw new RangeError(`quantileInterval: p is more than 0 and less than 1, not ${p}.`);\n const tail = levelOf(\"quantileInterval\", level);\n const s = sorted(values);\n const n = s.length;\n const terms = binomialTerms(n, p);\n let lowRank = 0;\n let left = 0;\n let below = terms[0] as number;\n while (lowRank < n && below <= tail) {\n lowRank += 1;\n left = below;\n below += terms[lowRank] as number;\n }\n let highRank = n + 1;\n let right = 0;\n let above = terms[n] as number;\n while (highRank > 1 && above <= tail) {\n highRank -= 1;\n right = above;\n above += terms[highRank - 1] as number;\n }\n return {\n low: lowRank === 0 ? -Infinity : (s[lowRank - 1] as number),\n high: highRank === n + 1 ? Infinity : (s[highRank - 1] as number),\n lowRank,\n highRank,\n coverage: Math.max(0, 1 - left - right),\n };\n}\n\n/**\n * This function gives the fewest independent values that give the quantile `p` an upper bound at `level`: the smallest n with\n * p^n <= (1 - level) / 2. With that n, the upper bound is the largest value. At the level 0.95, p95 needs 72 values, p99 needs\n * 368 values and p99.9 needs 3,688 values.\n */\nexport function quantileSamples(p: number, level = 0.95): number {\n if (!(p > 0 && p < 1)) throw new RangeError(`quantileSamples: p is more than 0 and less than 1, not ${p}.`);\n const tail = levelOf(\"quantileSamples\", level);\n const [logTail, logP] = [Math.log(tail), Math.log(p)];\n let n = Math.max(1, Math.ceil(logTail / logP));\n // A float error in the ratio can give one value too many.\n while (n > 1 && (n - 1) * logP <= logTail) n -= 1;\n return n;\n}\n\n/** A central interval of a count, from `low` to `high`, both included. */\nexport interface CountInterval {\n readonly low: number;\n readonly high: number;\n /** The chance of a count from `low` to `high`. It is `level` or more. */\n readonly coverage: number;\n}\n\n/**\n * The central interval of a count X ~ Binomial(n, p). `low` is the smallest k with P(X <= k) > (1 - level) / 2.\n * `high` is the largest k with P(X >= k) > (1 - level) / 2. Each tail outside the interval holds (1 - level) / 2\n * or less. The two tails are separate sums, so that a small upper tail keeps its digits.\n */\nexport function binomialInterval(n: number, p: number, level = 0.95): CountInterval {\n whole(\"binomialInterval\", n);\n if (!(p >= 0 && p <= 1)) throw new RangeError(`binomialInterval: p is from 0 to 1, not ${p}.`);\n const tail = levelOf(\"binomialInterval\", level);\n const terms = binomialTerms(n, p);\n let low = 0;\n let below = terms[0] as number;\n while (low < n && below <= tail) {\n low += 1;\n below += terms[low] as number;\n }\n let high = n;\n let above = terms[n] as number;\n while (high > 0 && above <= tail) {\n high -= 1;\n above += terms[high] as number;\n }\n let coverage = 0;\n for (let k = low; k <= high; k++) coverage += terms[k] as number;\n return { low, high, coverage: Math.min(1, coverage) };\n}\n\n/** The side of `binomialTest`: `\"less\"` gives `P(X <= k)`, and `\"greater\"` gives `P(X >= k)`. */\nexport type BinomialSide = \"less\" | \"greater\";\n\n/**\n * This function gives the p of the exact one-sided binomial test of `k` successes in `n` trials, with\n * X ~ Binomial(n, p). The side `\"less\"` gives `P(X <= k)`. A small value rejects the claim \"the chance is `p` or\n * more\". The side `\"greater\"` gives `P(X >= k)`. A small value rejects the claim \"the chance is `p` or less\".\n *\n * The sum starts at the largest term of the tail, so a small tail keeps its digits. At `p = 1/2`, the side\n * `\"greater\"` is equal to the one-sided `signTest(k, n - k)`.\n *\n * @param k - The count of successes, a whole number from 0 to `n`.\n * @param n - The count of trials, a whole number of 0 or more.\n * @param p - The chance of a success under the claim, from 0 to 1.\n * @param side - The side of the tail.\n * @returns The p of the test, from 0 to 1.\n */\nexport function binomialTest(k: number, n: number, p: number, side: BinomialSide): number {\n whole(\"binomialTest\", k);\n whole(\"binomialTest\", n);\n if (k > n) throw new RangeError(`binomialTest: k ${k} is more than n ${n}.`);\n if (!(p >= 0 && p <= 1)) throw new RangeError(`binomialTest: p is from 0 to 1, not ${p}.`);\n if (side !== \"less\" && side !== \"greater\") throw new RangeError(`binomialTest: side is \"less\" or \"greater\", not ${String(side)}.`);\n const [from, to] = side === \"less\" ? [0, k] : [k, n];\n if (from === 0 && to === n) return 1;\n if (p === 0) return from === 0 ? 1 : 0;\n if (p === 1) return to === n ? 1 : 0;\n const [logP, logQ] = [Math.log(p), Math.log1p(-p)];\n const logs: number[] = [];\n let logChoose = 0;\n for (let i = 0; i <= to; i++) {\n if (i > 0) logChoose += Math.log((n - i + 1) / i);\n if (i >= from) logs.push(logChoose + i * logP + (n - i) * logQ);\n }\n const top = Math.max(...logs);\n const sum = logs.reduce((s, l) => s + Math.exp(l - top), 0);\n return Math.min(1, Math.exp(top) * sum);\n}\n\n/**\n * The central interval of a negative binomial count. X is the count of failures before `successes` successes, and\n * `p` is the chance of a success at each try. `low` is the smallest k with P(X <= k) > (1 - level) / 2.\n * `high` is the smallest k with P(X <= k) >= 1 - (1 - level) / 2.\n */\nexport function negativeBinomialInterval(successes: number, p: number, level = 0.95): CountInterval {\n whole(\"negativeBinomialInterval\", successes);\n if (!(p > 0 && p <= 1)) throw new RangeError(`negativeBinomialInterval: p is more than 0 and 1 or less, not ${p}.`);\n const tail = levelOf(\"negativeBinomialInterval\", level);\n const logQ = Math.log1p(-p);\n let logChance = successes * Math.log(p);\n let below = 0;\n let low = 0;\n for (let k = 0; ; k += 1) {\n const chance = Math.exp(logChance);\n if (below <= tail) low = k;\n if (below + chance >= 1 - tail) {\n let coverage = 0;\n let at = successes * Math.log(p);\n for (let i = 0; i <= k; i++) {\n if (i >= low) coverage += Math.exp(at);\n at += Math.log((i + successes) / (i + 1)) + logQ;\n }\n return { low, high: k, coverage: Math.min(1, coverage) };\n }\n below += chance;\n logChance += Math.log((k + successes) / (k + 1)) + logQ;\n }\n}\n","/**\n * The comparison of a candidate with a baseline, and the calibration of predictions. These functions make two fleet\n * rules into code. First, a change of a default is judged against the current default. The measure is the inputs that\n * gain and the inputs that lose beyond the noise, with the effect size. A sign test alone is not enough. Second, each\n * prediction states a probability, and the Brier score measures how good the stated probabilities were.\n */\nimport { allEqual, median, quantileSorted, sd, sorted } from \"./describe.ts\";\nimport { type Proportion, signTest, wilson } from \"./tests.ts\";\n\nexport interface NoiseOptions {\n /** The number of standard deviations. The default is 2. */\n readonly k?: number;\n /** The fewest values (seeds or folds) that give a floor. The default is 5, the 5-seed rule. */\n readonly minimum?: number;\n /**\n * The margin of practical effect, in the units of the values. A difference that is real but smaller than the margin\n * is too small to matter, so it is not a result. Give the reason of the margin from the problem of the user. The\n * default is 0: no margin.\n */\n readonly margin?: number;\n}\n\n/** The checks of the options of the noise rule. It gives k, the minimum and the margin. */\nfunction noiseOptions(name: string, values: readonly number[], options: NoiseOptions): { k: number; margin: number } {\n const minimum = options.minimum ?? 5;\n if (values.length < minimum) throw new RangeError(`${name}: ${values.length} values; the rule needs ${minimum} or more seeds or folds.`);\n const margin = options.margin ?? 0;\n if (!Number.isFinite(margin) || margin < 0) throw new RangeError(`${name}: the margin is a finite number of 0 or more, not ${margin}.`);\n return { k: options.k ?? 2, margin };\n}\n\n/**\n * The noise floor of a measure: k sample standard deviations of its value over independent seeds or folds. When the\n * margin of practical effect is larger, the floor is the margin. A difference smaller than the floor is not a result.\n */\nexport function noiseFloor(values: readonly number[], options: NoiseOptions = {}): number {\n const { k, margin } = noiseOptions(\"noiseFloor\", values, options);\n return Math.max(k * sd(values), margin);\n}\n\n/**\n * The state of a difference over the seeds. \"gain\" and \"loss\": the mean is beyond the threshold. \"noise\": it is not.\n * \"no-spread\": each seed gives the same value, so the seeds do not sample the noise and the rule tests nothing.\n */\nexport type NoiseState = \"gain\" | \"loss\" | \"noise\" | \"no-spread\";\n\n/** The noise rule of a difference over independent seeds or folds. */\nexport interface NoiseVerdict {\n /** The number of values. */\n readonly n: number;\n readonly mean: number;\n /** The sample standard deviation of the values. */\n readonly sd: number;\n /** k times the standard deviation. */\n readonly spread: number;\n readonly margin: number;\n /** The larger of `spread` and `margin`. The absolute mean must be above it. */\n readonly threshold: number;\n readonly state: NoiseState;\n}\n\n/**\n * The noise rule of a difference (candidate minus baseline) over independent seeds or folds: the mean against\n * max(k standard deviations, margin). With `better: \"lower\"`, a negative mean is the gain. When each value is equal,\n * the state is \"no-spread\" and not a result, also when the mean is beyond the margin. Find out why the seeds do not\n * change the value before you read the difference.\n */\nexport function noiseVerdict(values: readonly number[], options: NoiseOptions & { readonly better?: \"higher\" | \"lower\" } = {}): NoiseVerdict {\n const { k, margin } = noiseOptions(\"noiseVerdict\", values, options);\n const s = sd(values);\n const m = values.reduce((sum, v) => sum + v, 0) / values.length;\n const spread = k * s;\n const threshold = Math.max(spread, margin);\n const up = (options.better ?? \"higher\") === \"higher\" ? m : -m;\n const state: NoiseState = allEqual(values) ? \"no-spread\" : Math.abs(m) <= threshold ? \"noise\" : up > 0 ? \"gain\" : \"loss\";\n return { n: values.length, mean: m, sd: s, spread, margin, threshold, state };\n}\n\nexport interface CompareOptions {\n /** \"higher\" (the default): a ratio above 1 is a gain. \"lower\": a ratio below 1 is a gain, as for a time or a cost. */\n readonly better?: \"higher\" | \"lower\";\n /** A ratio at this distance from 1 or nearer is a tie. The default is 0: only a ratio of exactly 1 is a tie. */\n readonly tie?: number;\n /** A gain or a loss counts only beyond this distance from 1. The default is 0. Use noiseFloor. */\n readonly noise?: number;\n}\n\n/** The effect on the inputs that are not ties. */\nexport interface Effect {\n readonly n: number;\n readonly median: number;\n /** The 0.1 quantile (linear). */\n readonly p10: number;\n /** The 0.9 quantile (linear). */\n readonly p90: number;\n}\n\nexport interface Comparison {\n /** The number of inputs. */\n readonly n: number;\n readonly ties: number;\n /** The inputs where the candidate is better, by any amount. */\n readonly wins: number;\n /** The inputs where the candidate is worse, by any amount. */\n readonly losses: number;\n /** The one-sided sign test of wins against losses. */\n readonly signP: number;\n /** The ratios of the inputs that are not ties, or undefined when each input is a tie. */\n readonly effect: Effect | undefined;\n /** The inputs that gain beyond the noise. */\n readonly gains: number;\n /** The inputs that lose beyond the noise. */\n readonly drops: number;\n /** gains / n, with its Wilson interval. */\n readonly gainShare: number;\n readonly gainInterval: Proportion;\n /** drops / n, with its Wilson interval. */\n readonly dropShare: number;\n readonly dropInterval: Proportion;\n}\n\n/**\n * The comparison of a candidate with a baseline, from the ratio candidate / baseline of each input. It answers the\n * three questions of a promotion. How often is the candidate better? By how much? How often is it worse beyond the\n * noise? A promotion reads `gains` against `drops` and `effect`, not `signP` alone, because a sign test counts a\n * win of any size.\n */\nexport function compareRatios(ratios: readonly number[], options: CompareOptions = {}): Comparison {\n if (ratios.length === 0) throw new RangeError(\"compareRatios: the list is empty.\");\n const sign = (options.better ?? \"higher\") === \"higher\" ? 1 : -1;\n const tie = options.tie ?? 0;\n const noise = options.noise ?? 0;\n if (!(tie >= 0) || !(noise >= 0)) throw new RangeError(\"compareRatios: tie and noise are 0 or more.\");\n let ties = 0;\n let wins = 0;\n let losses = 0;\n let gains = 0;\n let drops = 0;\n const changed: number[] = [];\n for (const ratio of ratios) {\n if (!Number.isFinite(ratio)) throw new RangeError(`compareRatios: each ratio is a finite number, not ${ratio}.`);\n const d = sign * (ratio - 1);\n if (Math.abs(ratio - 1) <= tie) {\n ties++;\n continue;\n }\n changed.push(ratio);\n if (d > 0) wins++;\n else losses++;\n if (d > noise) gains++;\n else if (-d > noise) drops++;\n }\n const n = ratios.length;\n const s = sorted(changed);\n const effect = s.length === 0 ? undefined : { n: s.length, median: median(s), p10: quantileSorted(s, 0.1), p90: quantileSorted(s, 0.9) };\n return {\n n,\n ties,\n wins,\n losses,\n signP: signTest(wins, losses),\n effect,\n gains,\n drops,\n gainShare: gains / n,\n gainInterval: wilson(gains, n),\n dropShare: drops / n,\n dropInterval: wilson(drops, n),\n };\n}\n\n/** A prediction: the stated probability that the claim holds, and if it held. */\nexport interface Forecast {\n readonly p: number;\n readonly hit: boolean;\n}\n\nfunction checkedForecasts(name: string, forecasts: readonly Forecast[]): void {\n if (forecasts.length === 0) throw new RangeError(`${name}: the list is empty.`);\n for (const f of forecasts) if (!(f.p >= 0 && f.p <= 1)) throw new RangeError(`${name}: each p is from 0 to 1, not ${f.p}.`);\n}\n\n/** The Brier score: the mean of (p - outcome)^2. 0 is perfect, and 0.25 is a constant 0.5. Lower is better. */\nexport function brier(forecasts: readonly Forecast[]): number {\n checkedForecasts(\"brier\", forecasts);\n let sum = 0;\n for (const f of forecasts) sum += (f.p - (f.hit ? 1 : 0)) ** 2;\n return sum / forecasts.length;\n}\n\n/**\n * The log-loss of predictions: the mean of `-ln(p)` for a hit and `-ln(1 - p)` for a miss. 0 is perfect, and\n * `ln(2)` is a constant 0.5. Lower is better. A p of 0 for a hit gives Infinity. For an outcome of three values,\n * give the probability of the observed outcome as `p`, with `hit` true.\n */\nexport function logLoss(forecasts: readonly Forecast[]): number {\n checkedForecasts(\"logLoss\", forecasts);\n let sum = 0;\n for (const f of forecasts) sum -= Math.log(f.hit ? f.p : 1 - f.p);\n return sum / forecasts.length;\n}\n\n/** The predictions of one stated level. */\nexport interface CalibrationLevel {\n readonly stated: number;\n readonly n: number;\n readonly hits: number;\n /** hits / n. A calibrated level has a rate near `stated`. */\n readonly rate: number;\n /** The Wilson interval of the rate. A level is overconfident when `stated` is above it. */\n readonly interval: Proportion;\n}\n\n/** The hit rate of each stated level, from the lowest level. */\nexport function calibration(forecasts: readonly Forecast[]): CalibrationLevel[] {\n checkedForecasts(\"calibration\", forecasts);\n const levels = new Map<number, { n: number; hits: number }>();\n for (const f of forecasts) {\n const level = levels.get(f.p) ?? { n: 0, hits: 0 };\n level.n++;\n if (f.hit) level.hits++;\n levels.set(f.p, level);\n }\n return [...levels]\n .sort((a, b) => a[0] - b[0])\n .map(([stated, { n, hits }]) => ({ stated, n, hits, rate: hits / n, interval: wilson(hits, n) }));\n}\n","/**\n * The count of values that a comparison of options needs before it starts. The Student t law gives this count, because the\n * normal formula is too low at a small count. These functions make no draws, so a caller reads the count with no bench.\n */\n\n/** The log of the gamma function, by the form of Lanczos with 6 terms. The argument is above 0. */\nfunction logGamma(x: number): number {\n const terms = [76.18009172947146, -86.50532032941677, 24.01409824083091, -1.231739572450155, 0.1208650973866179e-2, -0.5395239384953e-5];\n const base = x + 5.5 - (x + 0.5) * Math.log(x + 5.5);\n let series = 1.000000000190015;\n terms.forEach((term, i) => {\n series += term / (x + i + 1);\n });\n return -base + Math.log((2.5066282746310007 * series) / x);\n}\n\n/** The continued fraction of the incomplete beta function, by the method of Lentz. */\nfunction betaFraction(x: number, a: number, b: number): number {\n const tiny = 1e-300;\n const guard = (value: number): number => (Math.abs(value) < tiny ? tiny : value);\n let c = 1;\n let d = 1 / guard(1 - ((a + b) * x) / (a + 1));\n let h = d;\n for (let m = 1; m <= 500; m++) {\n const twice = 2 * m;\n const even = (m * (b - m) * x) / ((a + twice - 1) * (a + twice));\n d = 1 / guard(1 + even * d);\n c = guard(1 + even / c);\n h *= d * c;\n const odd = (-(a + m) * (a + b + m) * x) / ((a + twice) * (a + twice + 1));\n d = 1 / guard(1 + odd * d);\n c = guard(1 + odd / c);\n const step = d * c;\n h *= step;\n if (Math.abs(step - 1) < 1e-15) return h;\n }\n return h;\n}\n\n/** The regularized incomplete beta function at `x`, from 0 to 1. */\nfunction incompleteBeta(x: number, a: number, b: number): number {\n if (x <= 0) return 0;\n if (x >= 1) return 1;\n const front = Math.exp(logGamma(a + b) - logGamma(a) - logGamma(b) + a * Math.log(x) + b * Math.log(1 - x));\n return x < (a + 1) / (a + b + 2) ? (front * betaFraction(x, a, b)) / a : 1 - (front * betaFraction(1 - x, b, a)) / b;\n}\n\n/** The share of the Student t law with `df` degrees of freedom below `t`, for `t` of 0 or more. */\nfunction upperHalf(t: number, df: number): number {\n return 1 - 0.5 * incompleteBeta(df / (df + t * t), df / 2, 0.5);\n}\n\n/**\n * This function gives the quantile of the Student t law, from a bisection of its distribution function.\n *\n * @param p - The share of the law below the result, above 0 and below 1.\n * @param df - The degrees of freedom, above 0.\n */\nexport function tQuantile(p: number, df: number): number {\n if (!(p > 0 && p < 1)) throw new RangeError(`tQuantile: p is above 0 and below 1, not ${p}.`);\n if (!(df > 0 && Number.isFinite(df))) throw new RangeError(`tQuantile: df is a finite number above 0, not ${df}.`);\n if (p < 0.5) return -tQuantile(1 - p, df);\n let high = 1;\n while (upperHalf(high, df) < p) high *= 2;\n let low = 0;\n for (let step = 0; step < 200 && high - low > 1e-12 * high; step++) {\n const middle = (low + high) / 2;\n if (upperHalf(middle, df) < p) low = middle;\n else high = middle;\n }\n return (low + high) / 2;\n}\n\n/** The options of `optionFloor`. */\nexport interface OptionFloorOptions {\n /** The standard deviation of one value about the mean of its option. All options have the same value. */\n readonly sigma: number;\n /** The smallest difference between the means of two options that the comparison finds. */\n readonly delta: number;\n /** The count of tests in the family. The level of each test is `alpha / tests`. */\n readonly tests: number;\n /** The two-sided level of the family. The default is 0.05. */\n readonly alpha?: number;\n /** The share of comparisons that find a difference of `delta`. The default is 0.8. */\n readonly power?: number;\n}\n\n/**\n * This function gives the smallest count of values for each of two options. With it, one test finds a difference of\n * `delta` with the stated power. The form is `n = 2 ((t(1 - alpha / (2 tests), df) + t(power, df)) sigma / delta)^2`,\n * with `df = 2 n - 2`. The count is on both sides of that form, so the function takes the first count that meets it.\n *\n * The function assumes independent values, unpaired groups of equal size, equal `sigma`, and a Bonferroni family.\n * Holm gives each test a level of `alpha / tests` or more. Thus for a Holm family the count is an upper bound, not the exact count.\n * The tests read the power by simulation: 2,000 draws at the floor for 1, 5 and 67 tests, from the fixed seeds `rigor-statistics/optionFloor/at/<tests>`.\n * Each read gives 0.78 or more, and one count below the floor gives less.\n * A value of `sigma` from an older run gives a count for that run. Read `sigma` again on the new values.\n *\n * @param options - The spread, the difference, the family and the targets.\n * @returns A whole number of 2 or more.\n */\nexport function optionFloor(options: OptionFloorOptions): number {\n const { sigma, delta, tests, alpha = 0.05, power = 0.8 } = options;\n if (!(sigma > 0 && Number.isFinite(sigma))) throw new RangeError(`optionFloor: sigma is a finite number above 0, not ${sigma}.`);\n if (!(delta > 0 && Number.isFinite(delta))) throw new RangeError(`optionFloor: delta is a finite number above 0, not ${delta}.`);\n if (!Number.isSafeInteger(tests) || tests < 1) throw new RangeError(`optionFloor: tests is a whole number of 1 or more, not ${tests}.`);\n if (!(alpha > 0 && alpha < 1)) throw new RangeError(`optionFloor: alpha is above 0 and below 1, not ${alpha}.`);\n if (!(power > 0.5 && power < 1)) throw new RangeError(`optionFloor: power is above 0.5 and below 1, not ${power}.`);\n const level = 1 - alpha / (2 * tests);\n for (let n = 2; n < 1e7; n++) {\n const df = 2 * n - 2;\n const need = 2 * (((tQuantile(level, df) + tQuantile(power, df)) * sigma) / delta) ** 2;\n if (n >= need) return n;\n }\n throw new RangeError(`optionFloor: no count under 10,000,000 for sigma ${sigma} and delta ${delta}.`);\n}\n","/**\n * The standard normal law: its distribution function `normalCdf` and its quantile `normalQuantile`. The two functions\n * keep their relative digits in the far tails, so a small tail probability does not become 0.\n */\n\nconst SQRT_PI = Math.sqrt(Math.PI);\n\n/** The series of `erf(z)` with positive terms, `2/√π · e^(-z²) · Σ (2z²)^n · z / (1·3·…·(2n+1))`, for a small `z` of 0 or more. */\nfunction erfSeries(z: number): number {\n const twoZ2 = 2 * z * z;\n let term = z;\n let sum = z;\n for (let n = 1; n < 500 && term > sum * 1e-17; n++) {\n term *= twoZ2 / (2 * n + 1);\n sum += term;\n }\n return (2 / SQRT_PI) * expMinusSquare(z) * sum;\n}\n\n/**\n * The continued fraction of `erfc(z)`, `e^(-z²)/√π · 1/(z + (1/2)/(z + 1/(z + (3/2)/(z + …))))`, by the method of\n * Lentz, for a `z` of 1.5 or more.\n */\nfunction erfcFraction(z: number): number {\n const tiny = 1e-300;\n let f = z;\n let c = z;\n let d = 0;\n for (let n = 1; n < 5000; n++) {\n const a = n / 2;\n d = z + a * d;\n d = 1 / (Math.abs(d) < tiny ? tiny : d);\n c = z + a / c;\n if (Math.abs(c) < tiny) c = tiny;\n const delta = c * d;\n f *= delta;\n if (Math.abs(delta - 1) < 1e-16) break;\n }\n return expMinusSquare(z) / (SQRT_PI * f);\n}\n\n/**\n * The value of `e^(-z²)` with its relative digits for a large `z`. The rounding of `z²` costs `z²` ulps, so the\n * function splits `z` into `hi + lo`. `hi` has 4 bits after the point, so `hi²` is exact.\n */\nfunction expMinusSquare(z: number): number {\n const hi = Math.round(z * 16) / 16;\n const lo = z - hi;\n return Math.exp(-hi * hi) * Math.exp(-lo * (z + hi));\n}\n\n/** The complementary error function `erfc(z) = 1 - erf(z)`, with its relative digits for a large `z`. */\nfunction erfc(z: number): number {\n if (z < 0) return 2 - erfc(-z);\n return z < 1.5 ? 1 - erfSeries(z) : erfcFraction(z);\n}\n\n/**\n * This function gives the distribution function of the standard normal law, `P(Z <= x)`. Its relative error is below\n * 1e-14, also in the lower tail: `normalCdf(-37)` is approximately 5.7e-300, not 0.\n *\n * @param x - A number. `-Infinity` gives 0 and `Infinity` gives 1.\n */\nexport function normalCdf(x: number): number {\n if (Number.isNaN(x)) throw new RangeError(\"normalCdf: x is NaN.\");\n if (x === Number.NEGATIVE_INFINITY) return 0;\n if (x === Number.POSITIVE_INFINITY) return 1;\n return erfc(-x / Math.SQRT2) / 2;\n}\n\n// The coefficients of PPND16 of Wichura (1988), algorithm AS 241. The first set is for |p - 0.5| <= 0.425.\nconst A = [\n 3.387132872796366608, 133.14166789178437745, 1971.5909503065514427, 13731.693765509461125, 45921.953931549871457,\n 67265.770927008700853, 33430.575583588128105, 2509.0809287301226727,\n];\nconst B = [\n 1, 42.313330701600911252, 687.1870074920579083, 5394.1960214247511077, 21213.794301586595867, 39307.89580009271061,\n 28729.085735721942674, 5226.495278852854561,\n];\n// The second set is for a tail with r = sqrt(-ln(tail)) of 5 or less.\nconst C = [\n 1.42343711074968357734, 4.6303378461565452959, 5.7694972214606914055, 3.64784832476320460504, 1.27045825245236838258,\n 0.24178072517745061177, 0.0227238449892691845833, 7.7454501427834140764e-4,\n];\nconst D = [\n 1, 2.05319162663775882187, 1.6763848301838038494, 0.68976733498510000455, 0.14810397642748007459,\n 0.0151986665636164571966, 5.475938084995344946e-4, 1.05075007164441684324e-9,\n];\n// The third set is for a far tail, with r above 5.\nconst E = [\n 6.6579046435011037772, 5.4637849111641143699, 1.7848265399172913358, 0.29656057182850489123, 0.026532189526576123093,\n 0.0012426609473880784386, 2.71155556874348757815e-5, 2.01033439929228813265e-7,\n];\nconst F = [\n 1, 0.59983220655588793769, 0.13692988092273580531, 0.0148753612908506148525, 7.868691311456132591e-4,\n 1.8463183175100546818e-5, 1.4215117583164458887e-7, 2.04426310338993978564e-15,\n];\n\n/** The value of a polynomial with the coefficients `c[0] + c[1] x + …`, by the rule of Horner. */\nfunction poly(c: readonly number[], x: number): number {\n let value = 0;\n for (let i = c.length - 1; i >= 0; i--) value = value * x + (c[i] as number);\n return value;\n}\n\n/**\n * This function gives the quantile of the standard normal law, the `x` with `normalCdf(x) = p`. It uses PPND16 of\n * Wichura (algorithm AS 241). Its relative error is near 1e-16 for each `p` from 1e-300 to 1 - 1e-16.\n *\n * @param p - The share of the law below the result, from 0 to 1. A `p` of 0 gives `-Infinity` and 1 gives `Infinity`.\n */\nexport function normalQuantile(p: number): number {\n if (!(p >= 0 && p <= 1)) throw new RangeError(`normalQuantile: p is from 0 to 1, not ${p}.`);\n if (p === 0) return Number.NEGATIVE_INFINITY;\n if (p === 1) return Number.POSITIVE_INFINITY;\n const q = p - 0.5;\n if (Math.abs(q) <= 0.425) {\n const r = 0.180625 - q * q;\n return (q * poly(A, r)) / poly(B, r);\n }\n let r = Math.sqrt(-Math.log(q < 0 ? p : 1 - p));\n let value: number;\n if (r <= 5) {\n r -= 1.6;\n value = poly(C, r) / poly(D, r);\n } else {\n r -= 5;\n value = poly(E, r) / poly(F, r);\n }\n return q < 0 ? -value : value;\n}\n","/**\n * The rule that finds the smallest sample at which an interval method keeps its level. The input is the hits of the\n * method on the true value in seeded cells. The bar is fixed before the run.\n */\nimport { binomialTest } from \"./discrete.ts\";\nimport { type Proportion, Z95, holm, wilson } from \"./tests.ts\";\n\n/** One cell of a coverage study: the hits of a method on the true value in `draws` seeded samples of size `sample`. */\nexport interface CoverageCell {\n /** The name of the cell, for example `\"skewed 120/108\"`. The result names the rejected cells with it. */\n readonly name: string;\n /** The sample size `m` of the cell, a whole number of 1 or more. */\n readonly sample: number;\n /** The count of samples whose interval holds the true value, a whole number from 0 to `draws`. */\n readonly hits: number;\n /** The count of samples of the cell, a whole number of 1 or more. */\n readonly draws: number;\n}\n\n/** The bar of `coverageMinSample`. Fix it before the run, and do not change it after the run. */\nexport interface CoverageBar {\n /** The coverage that the method claims, for example 0.95. Each cell has a one-sided exact binomial test of it. */\n readonly level: number;\n /** The level of the Holm family of the cell tests, for example 0.05. */\n readonly alpha: number;\n /** The smallest Wilson lower end of the pooled coverage, for example 0.94. */\n readonly pooledLow: number;\n /** The z of the Wilson interval. The default is `Z95`. */\n readonly z?: number;\n}\n\n/** The reason of one step: `\"qualifies\"`, or the test or tests that failed. */\nexport type CoverageReason = \"qualifies\" | \"cell-rejected\" | \"pooled-low\" | \"cell-rejected-and-pooled-low\";\n\n/** The result of the bar at one sample size `m`, over each cell with a sample of `m` or more. */\nexport interface CoverageStep {\n /** The sample size `m` of the step. */\n readonly sample: number;\n /** The count of cells with a sample of `m` or more. */\n readonly cells: number;\n /** The names of the cells that reject the coverage `level`, after the Holm correction. */\n readonly rejected: readonly string[];\n /** The smallest Holm-adjusted p of the cells of the step. */\n readonly smallestAdjusted: number;\n /** The sum of the hits of the cells of the step. */\n readonly hits: number;\n /** The sum of the draws of the cells of the step. */\n readonly draws: number;\n /** The Wilson interval of the pooled coverage `hits / draws`. */\n readonly pooled: Proportion;\n /** The sample size `m` passes the two tests of the bar. */\n readonly qualifies: boolean;\n readonly reason: CoverageReason;\n}\n\n/** The result of `coverageMinSample`. */\nexport interface CoverageMinSample {\n /**\n * The smallest sample size `m` of the cells such that each size of `m` or more passes the bar. It is infinite when\n * the largest size fails.\n */\n readonly minSample: number;\n /** The largest sample size that fails the bar. It blocks each smaller size. The result has no `blocking` when each size passes. */\n readonly blocking?: number;\n /** One step for each sample size of the cells, from the smallest to the largest. */\n readonly steps: readonly CoverageStep[];\n}\n\nfunction whole(name: string, value: number, min: number): void {\n if (!Number.isSafeInteger(value) || value < min) throw new RangeError(`coverageMinSample: ${name} is a whole number of ${min} or more, not ${value}.`);\n}\n\n/**\n * This function applies a fixed bar of coverage to the cells of a study. It gives the smallest sample size `m` from\n * which an interval method keeps its level. The method qualifies at `m` when the cells with a sample of `m` or more\n * pass two tests:\n *\n * 1. No cell rejects the coverage `level`. Each cell has the exact one-sided binomial test `P(X <= hits)`, with\n * X ~ Binomial(draws, level). The family of these tests gets the Holm correction at `alpha`.\n * 2. The Wilson lower end of the pooled coverage, the sum of the hits over the sum of the draws, is `pooledLow`\n * or more.\n *\n * Each step tells the result of the two tests at its `m`. A step does not depend on the steps of other sizes. At a\n * small `m`, the pool also holds the cells of the larger sizes. Thus a small `m` can pass while a larger `m` fails\n * alone, for example near `m = n`.\n *\n * Thus the set of sizes is closed upward. The result is the smallest `m` of the cells such that each size of `m` or\n * more qualifies. The field `blocking` gives the largest size that fails. When the largest size fails, the result is\n * infinite.\n *\n * @param cells - The hits and the draws of each cell. Each cell has its own sample size.\n * @param bar - The level, the alpha of the Holm family and the pooled lower end.\n * @returns The smallest size from which each size qualifies, the size that blocks, and the result at each size.\n */\nexport function coverageMinSample(cells: readonly CoverageCell[], bar: CoverageBar): CoverageMinSample {\n const { level, alpha, pooledLow } = bar;\n const z = bar.z ?? Z95;\n if (!(level > 0 && level < 1)) throw new RangeError(`coverageMinSample: level is more than 0 and less than 1, not ${level}.`);\n if (!(alpha > 0 && alpha < 1)) throw new RangeError(`coverageMinSample: alpha is more than 0 and less than 1, not ${alpha}.`);\n if (!(pooledLow >= 0 && pooledLow <= 1)) throw new RangeError(`coverageMinSample: pooledLow is from 0 to 1, not ${pooledLow}.`);\n if (!(z > 0 && Number.isFinite(z))) throw new RangeError(`coverageMinSample: z is a finite number more than 0, not ${z}.`);\n for (const cell of cells) {\n whole(\"sample\", cell.sample, 1);\n whole(\"draws\", cell.draws, 1);\n whole(\"hits\", cell.hits, 0);\n if (cell.hits > cell.draws) throw new RangeError(`coverageMinSample: the hits ${cell.hits} of the cell ${cell.name} are more than its draws ${cell.draws}.`);\n }\n const p = cells.map((cell) => binomialTest(cell.hits, cell.draws, level, \"less\"));\n const sizes = [...new Set(cells.map((cell) => cell.sample))].sort((a, b) => a - b);\n const steps = sizes.map((m): CoverageStep => {\n const at = cells.map((cell, i) => ({ cell, p: p[i] as number })).filter(({ cell }) => cell.sample >= m);\n const corrected = holm(\n at.map(({ p: value }) => value),\n alpha,\n );\n const rejected = at.filter((_, i) => corrected[i]?.reject === true).map(({ cell }) => cell.name);\n const smallestAdjusted = Math.min(...corrected.map((c) => c.adjusted));\n let hits = 0;\n let draws = 0;\n for (const { cell } of at) {\n hits += cell.hits;\n draws += cell.draws;\n }\n const pooled = wilson(hits, draws, z);\n const cellOk = rejected.length === 0;\n const pooledOk = pooled.low >= pooledLow;\n const reason: CoverageReason = cellOk ? (pooledOk ? \"qualifies\" : \"pooled-low\") : pooledOk ? \"cell-rejected\" : \"cell-rejected-and-pooled-low\";\n return { sample: m, cells: at.length, rejected, smallestAdjusted, hits, draws, pooled, qualifies: cellOk && pooledOk, reason };\n });\n // The set is closed upward: read the steps from the largest size down, and stop at the first size that fails.\n let minSample = Number.POSITIVE_INFINITY;\n let blocking: number | undefined;\n for (let i = steps.length - 1; i >= 0; i--) {\n const step = steps[i] as CoverageStep;\n if (!step.qualifies) {\n blocking = step.sample;\n break;\n }\n minSample = step.sample;\n }\n return blocking === undefined ? { minSample, steps } : { minSample, blocking, steps };\n}\n","/**\n * The interval of a U-statistic from a uniform sample of `m` of `n` units, drawn without replacement. A kernel `h`\n * gives a value to each set of `r` units. The total of the population is the sum of `h` over all its sets of `r`.\n */\nimport { tQuantile } from \"./power.ts\";\n\n/** The methods of `uStatisticInterval`. The method `\"auto\"` selects one of the other two for each sample. */\nexport type UStatisticMethod = \"conservative\" | \"tight\" | \"auto\";\n\n/**\n * The smallest sample `m` at which the method `\"auto\"` uses the method `\"tight\"`. The calibration study\n * `u-statistic-interval` gives the value with `coverageMinSample`. The value is the smallest `m` of the grid such that\n * each `m` of the grid from this value up passes the bar. Until a run of the study gives a value, the value is\n * infinite. The TSDoc of `uStatisticInterval` gives the bar of the study.\n */\nexport const U_STATISTIC_TIGHT_MIN_SAMPLE: number = Number.POSITIVE_INFINITY;\n\n/** The options of `uStatisticInterval`. */\nexport interface UStatisticOptions {\n /** The order `r` of the kernel: the number of units in each set. It is a whole number of 1 or more. */\n readonly order: number;\n /** The number of units in the whole population, `n`. It is a whole number, and it is not less than the sample. */\n readonly population: number;\n /** The method of the interval. The methods `\"conservative\"` and `\"auto\"` need `range`. */\n readonly method: UStatisticMethod;\n /** The level of the interval. The default is 0.95. */\n readonly level?: number;\n /** The smallest and the largest value of the kernel. With it, the interval stays in this range. */\n readonly range?: readonly [low: number, high: number];\n}\n\n/** The mean of the kernel over all the sets of `r` units of the population, with its interval. */\nexport interface UStatisticMean {\n /** The U-statistic: the mean of the kernel over the sets of `r` units of the sample. */\n readonly estimate: number;\n readonly low: number;\n readonly high: number;\n}\n\n/** The result of `uStatisticInterval`. The total is the mean of the kernel times `subsets`. */\nexport interface UStatisticInterval {\n /** The estimate of the total of the population: `S * C(n, r) / C(m, r)`, with `S` the total of the sample. */\n readonly estimate: number;\n readonly low: number;\n readonly high: number;\n readonly level: number;\n /** The method that made the interval. It is not `requested` after a fallback or a choice of the method `\"auto\"`. */\n readonly method: \"conservative\" | \"tight\";\n /** The method of the options. */\n readonly requested: UStatisticMethod;\n /** The mean of the kernel, with its interval. */\n readonly mean: UStatisticMean;\n /** The number of sets of `r` units in the population, `C(n, r)`. */\n readonly subsets: number;\n /** The standard error of the total. Only an interval of the method `\"tight\"` has it. */\n readonly standardError?: number;\n /** The degrees of freedom of the t quantile, `m - 1`. Only an interval of the method `\"tight\"` has it. */\n readonly df?: number;\n}\n\n/**\n * This function gives the interval of a total over all the sets of `r` units of a population. The data is a uniform\n * sample of `m` of the `n` units, without replacement. An example is the count of crossings between all pairs of\n * routes. The input is the total of each sampled unit: the sum of the kernel over the sets of `r` sampled units\n * that hold the unit. Thus the sum of the totals is `r * S`, with `S` the total of the sample. The kernel is\n * symmetric.\n *\n * The estimate is `S * C(n, r) / C(m, r)`. It is the U-statistic `U = S / C(m, r)` times `C(n, r)`. At `r = 1`,\n * the estimate is `n / m` times the sum of the sample. When `m` is `n`, the interval is the estimate.\n *\n * The method `\"conservative\"` uses the inequality of Hoeffding (1963) for U-statistics, with `k = floor(m / r)`. The\n * half width of the mean is `(b - a) * sqrt(ln(2 / (1 - level)) / (2 k))`, with `[a, b]` the range of the kernel.\n * The bound is also true for a sample without replacement (Ai, Kuželka and Wang 2022, Blanc 2023 Theorem 6).\n * Thus the interval holds at each `m`. It is wide at a small `m`.\n *\n * The method `\"tight\"` uses the jackknife variance of `U`, from the totals only, times the finite population\n * correction `1 - m / n`. The interval is `U` plus or minus the t quantile with `m - 1` degrees of freedom, times\n * the standard error.\n *\n * The correction comes from the inclusion probabilities of a sample without replacement. The variance of the linear\n * part of `U` (its Hájek projection) gets exactly the factor `1 - m / n`. The variance of the remainder gets a\n * smaller factor, near `(1 - m / n)^2`, relative to an independent sample. For `r = 2` this factor is\n * `(n - m)(n - m - 1) / ((n - 2)(n - 3))`. Thus this estimate of the variance is exact for a linear kernel, and\n * larger than the variance for other kernels. The tests read the two facts over all samples of small populations.\n *\n * The method `\"tight\"` does not give an interval of width 0 when `m` is less than `n`. When all the totals are\n * equal, the jackknife variance is 0. Then the function uses the method `\"conservative\"` for the sample, and the\n * result has `method: \"conservative\"`. Without `range`, the function throws a `RangeError` for this sample.\n *\n * The method `\"tight\"` has no proof of its coverage. The tests use 200 samples of made-up populations at the level\n * 0.95. The table gives the hits of 200 for each population `n` and sample `m`. Each count includes the fallback.\n *\n * | n / m | sparse | crossings | skewed |\n * | --- | --- | --- | --- |\n * | 40 / 8 | 200 | 200 | 183 |\n * | 40 / 10 | 200 | 200 | 187 |\n * | 40 / 12 | 200 | 183 | 189 |\n * | 40 / 20 | 180 | 183 | 188 |\n * | 40 / 36 | 192 | 189 | 193 |\n * | 60 / 8 | 200 | 200 | 181 |\n * | 60 / 10 | 200 | 200 | 180 |\n * | 60 / 12 | 200 | 195 | 186 |\n * | 60 / 20 | 184 | 190 | 183 |\n * | 60 / 40 | 186 | 193 | 180 |\n * | 120 / 8 | 200 | 200 | 177 |\n * | 120 / 10 | 200 | 192 | 175 |\n * | 120 / 12 | 200 | 189 | 178 |\n * | 120 / 20 | 191 | 193 | 182 |\n * | 120 / 40 | 194 | 192 | 185 |\n * | 120 / 60 | 195 | 189 | 185 |\n * | 120 / 108 | 187 | 185 | 190 |\n *\n * The sparse kernel holds 2% to 3% of the pairs. The skewed kernel has a few large values. At `m = 8`, the skewed\n * kernel gets 177 to 183 of 200, a coverage of 0.885 to 0.915. No row has 190 or more in each kernel.\n *\n * The method `\"auto\"` needs `range`. It uses the method `\"tight\"` when `m` is `U_STATISTIC_TIGHT_MIN_SAMPLE` or more\n * and the variance is more than 0. Otherwise, it uses the method `\"conservative\"`.\n *\n * The calibration study `u-statistic-interval` sets `U_STATISTIC_TIGHT_MIN_SAMPLE`. Its bar was fixed before its run.\n * The study draws 1000 samples in each cell of the 3 kernels and the 17 cells of the table. The method `\"tight\"`\n * qualifies at `m` when the cells with a sample of `m` or more pass two tests.\n *\n * First, no cell rejects the coverage 0.95 in a one-sided exact binomial test at alpha 0.05, with the Holm\n * correction over these cells. Second, the Wilson lower end of the pooled coverage of these cells is 0.94 or more.\n * `coverageMinSample` applies this bar.\n *\n * The set of sizes is closed upward. The constant is the smallest `m` of the grid such that each `m` of the grid from\n * this value up qualifies. A small `m` pools the good cells of the larger sizes, so it can pass while a larger `m`\n * fails alone. The upward rule keeps the method `\"auto\"` away from a size that failed.\n *\n * When the largest `m` fails, the constant is infinite. Until a run of the study gives a value, the constant is infinite. Thus the method `\"auto\"`\n * uses the method `\"conservative\"` at each `m` less than `n`.\n *\n * With `range`, the interval of the mean stays in `[a, b]`, and each total is in the range of a sum of\n * `C(m - 1, r - 1)` kernel values.\n *\n * @param totals - The total of each unit of the sample. The sample has more units than `r`.\n * @param options - The order, the population, the method, the level and the range of the kernel.\n * @returns The estimate and the interval of the total, and of the mean of the kernel.\n */\nexport function uStatisticInterval(totals: readonly number[], options: UStatisticOptions): UStatisticInterval {\n const name = \"uStatisticInterval\";\n const { order: r, population: n, method: requested } = options;\n const m = totals.length;\n const level = options.level ?? 0.95;\n if (!Number.isSafeInteger(r) || r < 1) throw new RangeError(`${name}: order is a whole number of 1 or more, not ${r}.`);\n if (m <= r) throw new RangeError(`${name}: the sample has more units than the order ${r}, not ${m}.`);\n if (!Number.isSafeInteger(n) || n < m) throw new RangeError(`${name}: population is a whole number of ${m} (the sample) or more, not ${n}.`);\n if (requested !== \"conservative\" && requested !== \"tight\" && requested !== \"auto\") {\n throw new RangeError(`${name}: method is \"conservative\", \"tight\" or \"auto\", not ${String(requested)}.`);\n }\n if (!(level > 0 && level < 1)) throw new RangeError(`${name}: level is more than 0 and less than 1, not ${level}.`);\n for (const t of totals) if (!Number.isFinite(t)) throw new RangeError(`${name}: each total is a finite number, not ${t}.`);\n const range = options.range;\n if (range !== undefined) {\n const [a, b] = range;\n if (!(Number.isFinite(a) && Number.isFinite(b) && a < b)) throw new RangeError(`${name}: range is two finite numbers a < b, not ${a} and ${b}.`);\n const sets = choose(m - 1, r - 1);\n const slack = 1e-9 * Math.max(Math.abs(a), Math.abs(b)) * sets;\n for (const t of totals) {\n if (t < a * sets - slack || t > b * sets + slack) throw new RangeError(`${name}: each total is from ${a * sets} to ${b * sets} for this range, not ${t}.`);\n }\n } else if (requested !== \"tight\") {\n throw new RangeError(`${name}: the method \"${requested}\" needs the range of the kernel.`);\n }\n\n let sum = 0;\n for (const t of totals) sum += t;\n const s = sum / r;\n const subsets = choose(n, r);\n const sampleSets = choose(m, r);\n const estimate = (s * subsets) / sampleSets;\n const u = s / sampleSets;\n const base = { estimate, level, requested, subsets };\n\n // The jackknife variance of U. It is 0 when all the totals are equal.\n const centre = sum / m;\n let squares = 0;\n for (const t of totals) squares += (t - centre) ** 2;\n const equal = totals.every((t) => t === totals[0]);\n const variance = equal ? 0 : ((1 - m / n) * ((m - 1) / m) * squares) / choose(m - 1, r) ** 2;\n\n if (m === n) {\n const method = requested === \"conservative\" || (requested === \"auto\" && m < U_STATISTIC_TIGHT_MIN_SAMPLE) ? \"conservative\" : \"tight\";\n return { ...base, low: estimate, high: estimate, method, mean: { estimate: u, low: u, high: u }, ...(method === \"tight\" ? { standardError: 0, df: m - 1 } : {}) };\n }\n const useTight = requested === \"tight\" || (requested === \"auto\" && m >= U_STATISTIC_TIGHT_MIN_SAMPLE);\n if (useTight && variance > 0) {\n const df = m - 1;\n const se = Math.sqrt(variance);\n const half = tQuantile(1 - (1 - level) / 2, df) * se;\n return { ...base, method: \"tight\", ...ends(u, u - half, u + half, range, subsets), standardError: se * subsets, df };\n }\n if (range === undefined) {\n throw new RangeError(`${name}: the jackknife variance is 0, because all the totals are equal. Give the range, or use the method \"conservative\".`);\n }\n const k = Math.floor(m / r);\n const half = (range[1] - range[0]) * Math.sqrt(Math.log(2 / (1 - level)) / (2 * k));\n return { ...base, method: \"conservative\", ...ends(u, u - half, u + half, range, subsets) };\n}\n\n/** This function gives the interval of the mean in the range, if there is a range, and scales it to the total. */\nfunction ends(\n u: number,\n lowMean: number,\n highMean: number,\n range: readonly [number, number] | undefined,\n subsets: number,\n): Pick<UStatisticInterval, \"low\" | \"high\" | \"mean\"> {\n const low = range ? Math.max(range[0], lowMean) : lowMean;\n const high = range ? Math.min(range[1], highMean) : highMean;\n return { low: low * subsets, high: high * subsets, mean: { estimate: u, low, high } };\n}\n\n/** The binomial coefficient `C(n, k)`, as a product. Each step is a whole number, so it is exact below 2^53. */\nfunction choose(n: number, k: number): number {\n let c = 1;\n for (let j = 0; j < k; j++) c = (c * (n - j)) / (j + 1);\n return c;\n}\n","/**\n * The ratings of pairwise results. This module gives the Elo update and the Glicko-2 update of one rating period. It\n * also gives the probabilities of a pair under the Bradley-Terry model with Davidson ties, and the conversion between\n * a log-strength and a rating. Each function is pure. It changes no input, and the same inputs give the same result.\n */\n\n/** The scale of a rating. A difference of `scale` points gives odds of `base` to 1. */\nexport interface RatingScale {\n /** The rating of the log-strength 0. The default is 1500. Elo uses only differences, so it does not read it. */\n readonly center?: number;\n /** The number of points that gives odds of `base` to 1. The default is 400. */\n readonly scale?: number;\n /** The base of the odds. The default is 10. */\n readonly base?: number;\n}\n\n/** The options of an Elo update. */\nexport interface EloOptions extends RatingScale {\n /** The largest change of a rating after one result (the K factor). The default is 32. */\n readonly k?: number;\n}\n\n/** The ratings of a pair after one result. */\nexport interface EloUpdate {\n /** The new rating of the first item. */\n readonly a: number;\n /** The new rating of the second item. */\n readonly b: number;\n /** The expected score of the first item before the result. */\n readonly expected: number;\n}\n\nfunction finite(name: string, label: string, value: number): void {\n if (!Number.isFinite(value)) throw new RangeError(`${name}: ${label} is a finite number, not ${value}.`);\n}\n\nfunction positive(name: string, label: string, value: number): void {\n if (!(value > 0 && Number.isFinite(value))) throw new RangeError(`${name}: ${label} is a finite number above 0, not ${value}.`);\n}\n\nfunction checkedScale(name: string, options: RatingScale): { center: number; scale: number; base: number } {\n const center = options.center ?? 1500;\n const scale = options.scale ?? 400;\n const base = options.base ?? 10;\n finite(name, \"the center\", center);\n positive(name, \"the scale\", scale);\n if (!(base > 1 && Number.isFinite(base))) throw new RangeError(`${name}: the base is a finite number above 1, not ${base}.`);\n return { center, scale, base };\n}\n\n/**\n * The expected score of the first item against the second item: `1 / (1 + base ** ((rb - ra) / scale))`. A win\n * counts 1, a tie 0.5 and a loss 0. The expected score of the second item is 1 minus this value.\n */\nexport function eloExpected(ra: number, rb: number, options: RatingScale = {}): number {\n finite(\"eloExpected\", \"the first rating\", ra);\n finite(\"eloExpected\", \"the second rating\", rb);\n const { scale, base } = checkedScale(\"eloExpected\", options);\n return 1 / (1 + base ** ((rb - ra) / scale));\n}\n\n/**\n * The Elo update of a pair after one result. The `score` is the score of the first item: 1 for a win, 0.5 for a tie\n * and 0 for a loss. Each rating moves by `k` times the difference between the score and the expected score. Thus\n * the sum of the two ratings does not change.\n */\nexport function eloUpdate(ra: number, rb: number, score: number, options: EloOptions = {}): EloUpdate {\n if (!(score >= 0 && score <= 1)) throw new RangeError(`eloUpdate: the score is from 0 to 1, not ${score}.`);\n const k = options.k ?? 32;\n if (!(k >= 0 && Number.isFinite(k))) throw new RangeError(`eloUpdate: k is a finite number of 0 or more, not ${k}.`);\n const expected = eloExpected(ra, rb, options);\n const change = k * (score - expected);\n return { a: ra + change, b: rb - change, expected };\n}\n\n/** A Glicko-2 rating on the Glicko scale: the rating, the rating deviation (RD) and the volatility. */\nexport interface Glicko2Rating {\n readonly rating: number;\n /** The rating deviation, in rating points. It is above 0. */\n readonly rd: number;\n /** The volatility: the expected size of a change of the true strength in one rating period. It is above 0. */\n readonly volatility: number;\n}\n\n/** One game of a rating period: the rating and the RD of the opponent, and the score of the player. */\nexport interface Glicko2Game {\n readonly rating: number;\n readonly rd: number;\n /** The score of the player: 1 for a win, 0.5 for a tie and 0 for a loss. */\n readonly score: number;\n}\n\n/** The options of a Glicko-2 update. */\nexport interface Glicko2Options {\n /** The constraint on the change of the volatility over time (tau). The default is 0.5. Glickman uses 0.3 to 1.2. */\n readonly tau?: number;\n /** The tolerance of the iteration for the new volatility (epsilon). The default is 0.000001, as in the paper. */\n readonly tolerance?: number;\n}\n\n/** The factor between the Glicko scale and the Glicko-2 scale: `400 / ln(10)`, to 4 places as in the paper. */\nconst GLICKO2_FACTOR = 173.7178;\nconst GLICKO2_CENTER = 1500;\nconst VOLATILITY_STEPS = 1000;\n\nfunction checkedRating(name: string, player: Glicko2Rating): void {\n finite(name, \"the rating\", player.rating);\n positive(name, \"the RD\", player.rd);\n positive(name, \"the volatility\", player.volatility);\n}\n\n/**\n * The Glicko-2 update of one player after one rating period (Glickman, \"Example of the Glicko-2 system\", 2012). The\n * function uses the Illinois algorithm for the new volatility. The games use the ratings of the opponents from the\n * start of the period. An empty list of games gives `glicko2Idle(player)`.\n */\nexport function glicko2Update(player: Glicko2Rating, games: readonly Glicko2Game[], options: Glicko2Options = {}): Glicko2Rating {\n checkedRating(\"glicko2Update\", player);\n const tau = options.tau ?? 0.5;\n const tolerance = options.tolerance ?? 1e-6;\n positive(\"glicko2Update\", \"tau\", tau);\n positive(\"glicko2Update\", \"the tolerance\", tolerance);\n for (const game of games) {\n finite(\"glicko2Update\", \"the rating of an opponent\", game.rating);\n positive(\"glicko2Update\", \"the RD of an opponent\", game.rd);\n if (!(game.score >= 0 && game.score <= 1)) throw new RangeError(`glicko2Update: a score is from 0 to 1, not ${game.score}.`);\n }\n if (games.length === 0) return glicko2Idle(player);\n const mu = (player.rating - GLICKO2_CENTER) / GLICKO2_FACTOR;\n const phi = player.rd / GLICKO2_FACTOR;\n const sigma = player.volatility;\n let information = 0;\n let improvement = 0;\n for (const game of games) {\n const muJ = (game.rating - GLICKO2_CENTER) / GLICKO2_FACTOR;\n const phiJ = game.rd / GLICKO2_FACTOR;\n const g = 1 / Math.sqrt(1 + (3 * phiJ * phiJ) / (Math.PI * Math.PI));\n const e = 1 / (1 + Math.exp(-g * (mu - muJ)));\n information += g * g * e * (1 - e);\n improvement += g * (game.score - e);\n }\n const v = 1 / information;\n const delta = v * improvement;\n const newSigma = newVolatility(phi, sigma, v, delta, tau, tolerance);\n const phiStar = Math.sqrt(phi * phi + newSigma * newSigma);\n const newPhi = 1 / Math.sqrt(1 / (phiStar * phiStar) + 1 / v);\n const newMu = mu + newPhi * newPhi * improvement;\n return { rating: GLICKO2_FACTOR * newMu + GLICKO2_CENTER, rd: GLICKO2_FACTOR * newPhi, volatility: newSigma };\n}\n\n/** Step 5 of the paper: the new volatility, by the Illinois algorithm on `x = ln(sigma^2)`. */\nfunction newVolatility(phi: number, sigma: number, v: number, delta: number, tau: number, tolerance: number): number {\n const a = Math.log(sigma * sigma);\n const phi2 = phi * phi;\n const delta2 = delta * delta;\n const f = (x: number): number => {\n const ex = Math.exp(x);\n const sum = phi2 + v + ex;\n return (ex * (delta2 - phi2 - v - ex)) / (2 * sum * sum) - (x - a) / (tau * tau);\n };\n let lowEnd = a;\n let highEnd: number;\n if (delta2 > phi2 + v) highEnd = Math.log(delta2 - phi2 - v);\n else {\n let k = 1;\n while (f(a - k * tau) < 0 && k < VOLATILITY_STEPS) k++;\n highEnd = a - k * tau;\n }\n let fLow = f(lowEnd);\n let fHigh = f(highEnd);\n for (let step = 0; Math.abs(highEnd - lowEnd) > tolerance && step < VOLATILITY_STEPS; step++) {\n const c = lowEnd + ((lowEnd - highEnd) * fLow) / (fHigh - fLow);\n const fC = f(c);\n if (fC * fHigh <= 0) {\n lowEnd = highEnd;\n fLow = fHigh;\n } else fLow /= 2;\n highEnd = c;\n fHigh = fC;\n }\n return Math.exp(lowEnd / 2);\n}\n\n/**\n * The Glicko-2 rating of a player after a rating period with no games. The rating and the volatility stay the same.\n * The RD grows to `sqrt(RD^2 + (173.7178 * volatility)^2)`.\n */\nexport function glicko2Idle(player: Glicko2Rating): Glicko2Rating {\n checkedRating(\"glicko2Idle\", player);\n const phi = player.rd / GLICKO2_FACTOR;\n const rd = GLICKO2_FACTOR * Math.sqrt(phi * phi + player.volatility * player.volatility);\n return { rating: player.rating, rd, volatility: player.volatility };\n}\n\n/** The probabilities of the three outcomes of a pair. Their sum is 1. */\nexport interface PairProbabilities {\n /** The probability that the first item wins. */\n readonly a: number;\n /** The probability that the second item wins. */\n readonly b: number;\n /** The probability of a tie. It is 0 when the tie parameter is 0. */\n readonly tie: number;\n}\n\n/**\n * This function gives the three probabilities of a pair from the log-strengths `sa` and `sb` and the Davidson tie\n * parameter `nu`. The denominator is `exp(d / 2) + exp(-d / 2) + nu`, with `d = sa - sb`. The function does no\n * checks, because the fit uses it in its inner loop.\n */\nexport function pairOutcomes(sa: number, sb: number, nu: number): PairProbabilities {\n const half = (sa - sb) / 2;\n const top = Math.max(Math.abs(half), nu > 0 ? Math.log(nu) : Number.NEGATIVE_INFINITY);\n const ea = Math.exp(half - top);\n const eb = Math.exp(-half - top);\n const et = nu > 0 ? Math.exp(Math.log(nu) - top) : 0;\n const sum = ea + eb + et;\n return { a: ea / sum, b: eb / sum, tie: et / sum };\n}\n\n/**\n * The probabilities of a pair under the Bradley-Terry model with Davidson (1970) ties. The inputs are the\n * log-strengths of the two items and the tie parameter `tie` of `bradleyTerry`. With `tie` 0, the probability that\n * the first item wins is `1 / (1 + exp(sb - sa))`. A constant added to the two strengths changes no probability.\n */\nexport function pairProbabilities(sa: number, sb: number, tie = 0): PairProbabilities {\n finite(\"pairProbabilities\", \"the first strength\", sa);\n finite(\"pairProbabilities\", \"the second strength\", sb);\n if (!(tie >= 0 && Number.isFinite(tie))) throw new RangeError(`pairProbabilities: the tie parameter is a finite number of 0 or more, not ${tie}.`);\n return pairOutcomes(sa, sb, tie);\n}\n\n/**\n * The rating of a log-strength: `center + scale * strength / ln(base)`. The defaults give\n * `1500 + 400 * log10(e) * strength`. Thus `eloExpected` of two ratings is the Bradley-Terry win probability.\n */\nexport function strengthToRating(strength: number, options: RatingScale = {}): number {\n finite(\"strengthToRating\", \"the strength\", strength);\n const { center, scale, base } = checkedScale(\"strengthToRating\", options);\n return center + (scale * strength) / Math.log(base);\n}\n\n/** The log-strength of a rating. It is the inverse of `strengthToRating` with the same options. */\nexport function ratingToStrength(rating: number, options: RatingScale = {}): number {\n finite(\"ratingToStrength\", \"the rating\", rating);\n const { center, scale, base } = checkedScale(\"ratingToStrength\", options);\n return ((rating - center) * Math.log(base)) / scale;\n}\n","/**\n * The Bradley-Terry fit of pairwise comparisons among `n` items. Each item has a log-strength. The fit is the\n * maximum a posteriori estimate with a normal (ridge) prior on each log-strength. Thus an item with only wins has a\n * finite strength, and the strengths have one solution.\n *\n * Ties use the Davidson (1970) model, or count as half a win and half a loss. The fit uses Newton steps with a line search on the negative log posterior. This function is\n * convex, so the steps go to its one minimum.\n */\nimport { factor } from \"./ridge.ts\";\nimport { pairOutcomes } from \"./rating.ts\";\n\n/** The result of a comparison: the first item wins, the second item wins, or a tie. */\nexport type PairOutcome = \"a\" | \"b\" | \"tie\";\n\n/** One comparison of two items, by their indexes from 0. */\nexport interface PairComparison {\n readonly a: number;\n readonly b: number;\n readonly outcome: PairOutcome;\n /** The weight of the comparison. The default is 1. A weight of 2 counts as two equal comparisons. */\n readonly weight?: number;\n}\n\n/** The model of a tie. */\nexport type TieModel = \"davidson\" | \"half\";\n\n/** The options of `bradleyTerry`. */\nexport interface BradleyTerryOptions {\n /** The mean of the prior of each log-strength. The default is 0. */\n readonly priorMean?: number;\n /** The standard deviation of the prior of each log-strength. The default is 1. A smaller value pulls the strengths together. */\n readonly priorSd?: number;\n /**\n * The model of a tie. With `\"davidson\"` (the default), the fit also gives a tie parameter. With `\"half\"`, a tie\n * counts as half a win and half a loss of each item, and the tie parameter is 0.\n */\n readonly ties?: TieModel;\n /**\n * The standard deviation of the normal prior of the log of the tie parameter, with mean 0. The default is 10. The\n * prior is weak. It keeps the parameter finite when each comparison is a tie.\n */\n readonly tiePriorSd?: number;\n /** The largest number of Newton steps. The default is 100. */\n readonly maxIterations?: number;\n /** The fit stops when the full Newton step moves no parameter more than this value. The default is 1e-10. */\n readonly tolerance?: number;\n}\n\n/** The result of `bradleyTerry`. The lists have one value for each item, in the order of the indexes. */\nexport interface BradleyTerryFit {\n /** The log-strength of each item. An item with no comparison has the prior mean. */\n readonly strengths: number[];\n /**\n * The standard error of each log-strength: the square root of the diagonal of the inverse of the Hessian of the\n * negative log posterior. An item with no comparison has the prior SD.\n */\n readonly se: number[];\n /** The Davidson tie parameter. It is 0 with the model `\"half\"`, and when no comparison is a tie. */\n readonly tie: number;\n /** The log-likelihood of the comparisons at the fit, with no prior term. */\n readonly logLikelihood: number;\n /** The number of Newton steps. */\n readonly iterations: number;\n /** True when the last full Newton step moved no parameter more than the tolerance. */\n readonly converged: boolean;\n}\n\n/** A comparison as numbers: the indexes, the weight, the coefficient of the difference, and 1 for a Davidson tie. */\ninterface Term {\n readonly a: number;\n readonly b: number;\n readonly w: number;\n readonly c: number;\n readonly tie: number;\n}\n\nconst ARMIJO = 1e-4;\nconst HALVINGS = 60;\nconst ROUNDING = 64 * Number.EPSILON;\n\nfunction checkedTerms(n: number, comparisons: readonly PairComparison[], ties: TieModel): Term[] {\n const terms: Term[] = [];\n for (const [i, comparison] of comparisons.entries()) {\n const { a, b, outcome } = comparison;\n const w = comparison.weight ?? 1;\n for (const index of [a, b]) {\n if (!Number.isSafeInteger(index) || index < 0 || index >= n) {\n throw new RangeError(`bradleyTerry: comparison ${i} has the index ${index}, and the indexes are whole numbers from 0 to ${n - 1}.`);\n }\n }\n if (a === b) throw new RangeError(`bradleyTerry: comparison ${i} compares the item ${a} with itself.`);\n if (outcome !== \"a\" && outcome !== \"b\" && outcome !== \"tie\") throw new RangeError(`bradleyTerry: comparison ${i} has the outcome ${String(outcome)}.`);\n if (!(w >= 0 && Number.isFinite(w))) throw new RangeError(`bradleyTerry: comparison ${i} has the weight ${w}, and a weight is a finite number of 0 or more.`);\n if (w === 0) continue;\n const c = outcome === \"a\" ? 0.5 : outcome === \"b\" ? -0.5 : 0;\n terms.push({ a, b, w, c, tie: outcome === \"tie\" && ties === \"davidson\" ? 1 : 0 });\n }\n return terms;\n}\n\nfunction positiveOption(label: string, value: number): void {\n if (!(value > 0 && Number.isFinite(value))) throw new RangeError(`bradleyTerry: ${label} is a finite number above 0, not ${value}.`);\n}\n\n/**\n * The Bradley-Terry fit of `comparisons` among `items` items. The function does not sort or change its inputs. An\n * empty list of comparisons gives the prior for each item. The function throws a RangeError for a bad index, a bad\n * outcome, a bad weight and a bad option.\n */\nexport function bradleyTerry(items: number, comparisons: readonly PairComparison[], options: BradleyTerryOptions = {}): BradleyTerryFit {\n if (!Number.isSafeInteger(items) || items < 1) throw new RangeError(`bradleyTerry: the number of items is a whole number of 1 or more, not ${items}.`);\n const priorMean = options.priorMean ?? 0;\n const priorSd = options.priorSd ?? 1;\n const ties = options.ties ?? \"davidson\";\n const tiePriorSd = options.tiePriorSd ?? 10;\n const maxIterations = options.maxIterations ?? 100;\n const tolerance = options.tolerance ?? 1e-10;\n if (!Number.isFinite(priorMean)) throw new RangeError(`bradleyTerry: the prior mean is a finite number, not ${priorMean}.`);\n positiveOption(\"the prior SD\", priorSd);\n positiveOption(\"the tie prior SD\", tiePriorSd);\n positiveOption(\"the tolerance\", tolerance);\n if (ties !== \"davidson\" && ties !== \"half\") throw new RangeError(`bradleyTerry: the tie model is \"davidson\" or \"half\", not ${String(ties)}.`);\n if (!Number.isSafeInteger(maxIterations) || maxIterations < 1) {\n throw new RangeError(`bradleyTerry: maxIterations is a whole number of 1 or more, not ${maxIterations}.`);\n }\n const terms = checkedTerms(items, comparisons, ties);\n // The tie parameter is free only when a comparison is a Davidson tie. Else it is 0, and the model is plain Bradley-Terry.\n const fitTie = terms.some((t) => t.tie === 1);\n const k = fitTie ? items + 1 : items;\n const model: Model = { items, terms, fitTie, priorMean, priorPrecision: 1 / (priorSd * priorSd), tiePrecision: 1 / (tiePriorSd * tiePriorSd) };\n\n const x = new Float64Array(k).fill(priorMean);\n if (fitTie) x[items] = 0;\n let iterations = 0;\n let converged = false;\n let value = objective(model, x);\n while (iterations < maxIterations) {\n iterations++;\n const { gradient, hessian } = derivatives(model, x);\n const step = solve(hessian, gradient, k);\n let slope = 0;\n for (let i = 0; i < k; i++) slope += (gradient[i] as number) * (step[i] as number);\n let t = 1;\n let next = moved(x, step, t);\n let nextValue = objective(model, next);\n // Near the minimum, a full step changes the objective by less than its rounding. The slack accepts that step.\n const slack = ROUNDING * (Math.abs(value) + 1);\n for (let h = 0; h < HALVINGS && !(nextValue <= value + ARMIJO * t * slope + slack); h++) {\n t /= 2;\n next = moved(x, step, t);\n nextValue = objective(model, next);\n }\n // The full Newton step decides the convergence, so a stalled line search far from the minimum does not count.\n let largest = 0;\n for (let i = 0; i < k; i++) largest = Math.max(largest, Math.abs(step[i] as number));\n if (nextValue <= value + slack) {\n x.set(next);\n value = nextValue;\n }\n if (largest <= tolerance) {\n converged = true;\n break;\n }\n }\n\n const { hessian } = derivatives(model, x);\n const variance = inverseDiagonal(hessian, k);\n const nu = fitTie ? Math.exp(x[items] as number) : 0;\n let logLikelihood = 0;\n for (const term of terms) logLikelihood += term.w * termLogLikelihood(term, x[term.a] as number, x[term.b] as number, nu);\n return {\n strengths: Array.from(x.subarray(0, items)),\n se: Array.from(variance.subarray(0, items), (v) => Math.sqrt(v)),\n tie: nu,\n logLikelihood,\n iterations,\n converged,\n };\n}\n\ninterface Model {\n readonly items: number;\n readonly terms: readonly Term[];\n readonly fitTie: boolean;\n readonly priorMean: number;\n readonly priorPrecision: number;\n readonly tiePrecision: number;\n}\n\nfunction moved(x: Float64Array, step: Float64Array, t: number): Float64Array {\n const out = new Float64Array(x.length);\n for (let i = 0; i < x.length; i++) out[i] = (x[i] as number) + t * (step[i] as number);\n return out;\n}\n\n/** The log of the denominator `exp(d / 2) + exp(-d / 2) + nu`, with no overflow. */\nfunction logDenominator(d: number, logNu: number): number {\n const half = Math.abs(d) / 2;\n const top = Math.max(half, logNu);\n return top + Math.log(Math.exp(half - top) + Math.exp(-half - top) + Math.exp(logNu - top));\n}\n\n/** The log-likelihood of one comparison with weight 1. A `\"half\"` tie has the coefficient 0: the mean of the two log-probabilities of a win. */\nfunction termLogLikelihood(term: Term, sa: number, sb: number, nu: number): number {\n const d = sa - sb;\n const logNu = nu > 0 ? Math.log(nu) : Number.NEGATIVE_INFINITY;\n const logD = logDenominator(d, logNu);\n return term.tie === 1 ? logNu - logD : term.c * d - logD;\n}\n\n/** The negative log posterior at `x`. */\nfunction objective(model: Model, x: Float64Array): number {\n const logNu = model.fitTie ? (x[model.items] as number) : Number.NEGATIVE_INFINITY;\n let sum = 0;\n for (const term of model.terms) {\n const d = (x[term.a] as number) - (x[term.b] as number);\n sum += term.w * (logDenominator(d, logNu) - term.c * d - (term.tie === 1 ? logNu : 0));\n }\n for (let i = 0; i < model.items; i++) sum += (model.priorPrecision * ((x[i] as number) - model.priorMean) ** 2) / 2;\n if (model.fitTie) sum += (model.tiePrecision * logNu * logNu) / 2;\n return sum;\n}\n\n/** The gradient and the Hessian (in row order) of the negative log posterior at `x`. */\nfunction derivatives(model: Model, x: Float64Array): { gradient: Float64Array; hessian: Float64Array } {\n const k = x.length;\n const n = model.items;\n const gradient = new Float64Array(k);\n const hessian = new Float64Array(k * k);\n const nu = model.fitTie ? Math.exp(x[n] as number) : 0;\n for (const term of model.terms) {\n const { a, b, w } = term;\n const p = pairOutcomes(x[a] as number, x[b] as number, nu);\n const q = (p.a - p.b) / 2;\n const gd = w * (q - term.c);\n const hdd = w * ((p.a + p.b) / 4 - q * q);\n gradient[a] = (gradient[a] as number) + gd;\n gradient[b] = (gradient[b] as number) - gd;\n hessian[a * k + a] = (hessian[a * k + a] as number) + hdd;\n hessian[b * k + b] = (hessian[b * k + b] as number) + hdd;\n hessian[a * k + b] = (hessian[a * k + b] as number) - hdd;\n hessian[b * k + a] = (hessian[b * k + a] as number) - hdd;\n if (model.fitTie) {\n const hdl = -w * q * p.tie;\n gradient[n] = (gradient[n] as number) + w * (p.tie - term.tie);\n hessian[n * k + n] = (hessian[n * k + n] as number) + w * p.tie * (1 - p.tie);\n hessian[a * k + n] = (hessian[a * k + n] as number) + hdl;\n hessian[n * k + a] = (hessian[n * k + a] as number) + hdl;\n hessian[b * k + n] = (hessian[b * k + n] as number) - hdl;\n hessian[n * k + b] = (hessian[n * k + b] as number) - hdl;\n }\n }\n for (let i = 0; i < n; i++) {\n gradient[i] = (gradient[i] as number) + model.priorPrecision * ((x[i] as number) - model.priorMean);\n hessian[i * k + i] = (hessian[i * k + i] as number) + model.priorPrecision;\n }\n if (model.fitTie) {\n gradient[n] = (gradient[n] as number) + model.tiePrecision * (x[n] as number);\n hessian[n * k + n] = (hessian[n * k + n] as number) + model.tiePrecision;\n }\n return { gradient, hessian };\n}\n\n/** The Cholesky factor of a copy of the Hessian. The priors make the Hessian positive definite. */\nfunction factored(hessian: Float64Array, k: number): Float64Array {\n const l = Float64Array.from(hessian);\n if (!factor(l, k)) throw new RangeError(\"bradleyTerry: the Hessian is not positive definite. Make the prior SD smaller.\");\n return l;\n}\n\n/** The Newton step: the solution of `hessian * step = -gradient`. */\nfunction solve(hessian: Float64Array, gradient: Float64Array, k: number): Float64Array {\n const l = factored(hessian, k);\n const y = new Float64Array(k);\n for (let i = 0; i < k; i++) {\n let s = -(gradient[i] as number);\n for (let j = 0; j < i; j++) s -= (l[i * k + j] as number) * (y[j] as number);\n y[i] = s / (l[i * k + i] as number);\n }\n for (let i = k - 1; i >= 0; i--) {\n let s = y[i] as number;\n for (let j = i + 1; j < k; j++) s -= (l[j * k + i] as number) * (y[j] as number);\n y[i] = s / (l[i * k + i] as number);\n }\n return y;\n}\n\n/** The diagonal of the inverse of the Hessian: the column sums of the squares of the inverse of its Cholesky factor. */\nfunction inverseDiagonal(hessian: Float64Array, k: number): Float64Array {\n const l = factored(hessian, k);\n const out = new Float64Array(k);\n const column = new Float64Array(k);\n for (let c = 0; c < k; c++) {\n // Column c of the inverse of L, by forward substitution. Its entries above row c are 0.\n column.fill(0);\n for (let i = c; i < k; i++) {\n let s = i === c ? 1 : 0;\n for (let j = c; j < i; j++) s -= (l[i * k + j] as number) * (column[j] as number);\n column[i] = s / (l[i * k + i] as number);\n }\n // The inverse of the Hessian is inv(L)' inv(L), so its diagonal entry c is the sum over the rows of column c squared.\n let sum = 0;\n for (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C7B;EAEA,IAAI,MAAM;EACV,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KAAK,OAAQ,OAAO,MAAiB;EAC5D,IAAI,KAAK;CACX;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"index.js","names":["ends","whole","whole"],"sources":["../src/describe.ts","../src/running.ts","../src/regression.ts","../src/bootstrap.ts","../src/distribution.ts","../src/ridge.ts","../src/response.ts","../src/response-parse.ts","../src/response-fit.ts","../src/response-sobol.ts","../src/tests.ts","../src/agreement.ts","../src/rank.ts","../src/discrete.ts","../src/compare.ts","../src/power.ts","../src/coverage.ts","../src/u-statistic.ts","../src/rating.ts","../src/bradley-terry.ts"],"sourcesContent":["/**\n * The descriptive statistics: the mean, the standard deviation, the median, the quantiles and a summary of a list.\n * Each function throws a RangeError for an empty list or for a value that is NaN. Thus a missing value cannot make a\n * quiet NaN in a record.\n */\n\n/** The definitions of a quantile that the engines use (Hyndman and Fan, 1996, and the names of NumPy). */\nexport type QuantileMethod =\n /** Type 7: a linear step between the two nearest ranks. The default of R and NumPy. */\n | \"linear\"\n /** Type 1: the smallest value with at least the share `p` of the values at or below it. */\n | \"nearest-rank\"\n /**\n * The higher of the two nearest ranks of type 7: `sorted[Math.ceil(p * (n - 1))]`. This is the method `\"higher\"` of\n * NumPy. The 0.5 quantile is the upper median `sorted[Math.floor(n / 2)]`. The rank `p * (n - 1)` is rounded to\n * `1e-9` before the ceiling. Thus a float error, for example `0.55 * 100 = 55.00000000000001`, does not move the rank up.\n * The rounding keeps the exact rank while `p * (n - 1) * 1e9` is below `2 ** 53`, so for `n` up to approximately 9 million.\n */\n | \"higher\";\n\nfunction checked(name: string, values: readonly number[]): void {\n if (values.length === 0) throw new RangeError(`${name}: the list is empty.`);\n for (const v of values) if (Number.isNaN(v)) throw new RangeError(`${name}: the list has a NaN.`);\n}\n\n/** A new list with the values from the smallest to the largest. */\nexport function sorted(values: readonly number[]): number[] {\n return [...values].sort((a, b) => a - b);\n}\n\nexport function mean(values: readonly number[]): number {\n checked(\"mean\", values);\n let sum = 0;\n for (const v of values) sum += v;\n return sum / values.length;\n}\n\n/** This function tells if each value is equal to the first value. An empty list gives true. */\nexport function allEqual(values: readonly number[]): boolean {\n return values.every((v) => v === values[0]);\n}\n\n/**\n * The sample standard deviation (the divisor is n - 1). It needs 2 values or more. Equal values give exactly 0. The\n * rounding of the mean gives a small number that is not 0 for some equal values, so the function examines them first.\n */\nexport function sd(values: readonly number[]): number {\n checked(\"sd\", values);\n if (values.length < 2) throw new RangeError(\"sd: the list needs 2 values or more.\");\n if (allEqual(values)) return 0;\n const m = mean(values);\n let sum = 0;\n for (const v of values) sum += (v - m) ** 2;\n return Math.sqrt(sum / (values.length - 1));\n}\n\n/**\n * The `p` quantile of a list that is already sorted. Use it when you take several quantiles of one list.\n * The linear method gives the same numbers as the copies in highways, packing and layout-contract. The\n * nearest-rank method gives the same numbers as the copies in lag, lag-hud and the backtest of highways. The\n * higher method gives the upper median of the copies in highways with `p = 0.5`.\n */\nexport function quantileSorted(sortedValues: readonly number[], p: number, method: QuantileMethod = \"linear\"): number {\n checked(\"quantile\", sortedValues);\n if (!(p >= 0 && p <= 1)) throw new RangeError(`quantile: p is from 0 to 1, not ${p}.`);\n const n = sortedValues.length;\n if (method === \"nearest-rank\") return sortedValues[Math.min(n - 1, Math.max(0, Math.ceil(p * n) - 1))] as number;\n // The rank on a grid of 1e-9, so that a float error above a whole rank does not give the next rank.\n if (method === \"higher\") return sortedValues[Math.ceil(Math.round(p * (n - 1) * 1e9) / 1e9)] as number;\n const at = (n - 1) * p;\n const low = Math.floor(at);\n const part = at - low;\n const a = sortedValues[low] as number;\n if (part === 0) return a;\n const b = sortedValues[low + 1] as number;\n if (a === b) return a;\n return a + part * (b - a);\n}\n\n/** The `p` quantile of a list. */\nexport function quantile(values: readonly number[], p: number, method: QuantileMethod = \"linear\"): number {\n checked(\"quantile\", values);\n return quantileSorted(sorted(values), p, method);\n}\n\n/**\n * The median: the middle value, or the midpoint `(a + b) / 2` of the two middle values. The midpoint is correctly\n * rounded. `quantile(values, 0.5)` computes `a + 0.5 * (b - a)`, which can differ from it in the last bit.\n */\nexport function median(values: readonly number[]): number {\n checked(\"median\", values);\n const s = sorted(values);\n const middle = Math.floor(s.length / 2);\n return s.length % 2 === 1 ? (s[middle] as number) : ((s[middle - 1] as number) + (s[middle] as number)) / 2;\n}\n\n/** The summary of a list. The quartiles use the linear method. */\nexport interface Summary {\n readonly n: number;\n readonly mean: number;\n /** The sample standard deviation, or NaN for one value. */\n readonly sd: number;\n readonly min: number;\n /** The 0.25 quantile. */\n readonly q1: number;\n readonly median: number;\n /** The 0.75 quantile. */\n readonly q3: number;\n readonly max: number;\n /** The interquartile range: q3 - q1. */\n readonly iqr: number;\n}\n\nexport function summarize(values: readonly number[]): Summary {\n checked(\"summarize\", values);\n const s = sorted(values);\n const q1 = quantileSorted(s, 0.25);\n const q3 = quantileSorted(s, 0.75);\n return {\n n: s.length,\n // The mean and sd of the list in its own order, so that they are equal to mean(values) and sd(values).\n mean: mean(values),\n sd: s.length < 2 ? Number.NaN : sd(values),\n min: s[0] as number,\n q1,\n median: median(s),\n q3,\n max: s[s.length - 1] as number,\n iqr: q3 - q1,\n };\n}\n","/**\n * The running summary: the count, the sum, the extremes and the spread of a stream of values, one value at a time.\n * A collector, a reducer or a parallel job adds each value, or merges two summaries. The summary agrees with the\n * functions of a list: `runningMean` gives exactly `mean` of the values, and `runningSd` gives `sd` to a tolerance.\n */\n\n/**\n * A running summary of the values that were added. The record is immutable, so a fold can keep each step. The empty\n * summary is `EMPTY_RUNNING`.\n */\nexport interface RunningSummary {\n /** The count of the values. */\n readonly n: number;\n /** The sum of the values, added in their order. */\n readonly sum: number;\n /** The smallest value, or `Infinity` for no value. */\n readonly min: number;\n /** The largest value, or `-Infinity` for no value. */\n readonly max: number;\n /** The sum of the squares of the differences from the mean (Welford). `runningSd` reads it. */\n readonly m2: number;\n}\n\n/** The summary of no value. It is the unit of `mergeRunning`. */\nexport const EMPTY_RUNNING: RunningSummary = Object.freeze({ n: 0, sum: 0, min: Infinity, max: -Infinity, m2: 0 });\n\n/**\n * This function gives the summary with one more value. It throws a RangeError for NaN, as the functions of a list do.\n * The mean of each step is `sum / n`, so the mean of the fold is the mean of the list.\n */\nexport function addToRunning(s: RunningSummary, value: number): RunningSummary {\n if (Number.isNaN(value)) throw new RangeError(\"addToRunning: the value is NaN.\");\n // The sum starts at 0, as the sum of `mean` does. Thus a first value of -0 gives the sum 0 there too.\n const sum = s.sum + value;\n if (s.n === 0) return { n: 1, sum, min: value, max: value, m2: 0 };\n const n = s.n + 1;\n const m2 = s.m2 + (value - s.sum / s.n) * (value - sum / n);\n return { n, sum, min: Math.min(s.min, value), max: Math.max(s.max, value), m2 };\n}\n\n/** This function gives the summary of the values of a list or another iterable, in their order. */\nexport function runningOf(values: Iterable<number>): RunningSummary {\n let s = EMPTY_RUNNING;\n for (const v of values) s = addToRunning(s, v);\n return s;\n}\n\n/**\n * This function gives the summary of the values of two summaries (Chan, Golub and LeVeque, 1979). Thus parallel jobs\n * can each summarize a part. The sum of the merge adds the two sums, so it can differ from the fold in the last bits.\n */\nexport function mergeRunning(a: RunningSummary, b: RunningSummary): RunningSummary {\n if (a.n === 0) return b;\n if (b.n === 0) return a;\n const n = a.n + b.n;\n const delta = b.sum / b.n - a.sum / a.n;\n return {\n n,\n sum: a.sum + b.sum,\n min: Math.min(a.min, b.min),\n max: Math.max(a.max, b.max),\n m2: a.m2 + b.m2 + ((delta * delta * a.n) / n) * b.n,\n };\n}\n\n/** This function gives the mean of the values: `sum / n`. It throws a RangeError for the empty summary. */\nexport function runningMean(s: RunningSummary): number {\n if (s.n === 0) throw new RangeError(\"runningMean: the summary is empty.\");\n return s.sum / s.n;\n}\n\n/**\n * This function gives the sample standard deviation of the values (the divisor is n - 1). It needs 2 values or more.\n * Equal values give exactly 0, as `sd` gives. A rounding error cannot make the result NaN.\n */\nexport function runningSd(s: RunningSummary): number {\n if (s.n < 2) throw new RangeError(\"runningSd: the summary needs 2 values or more.\");\n if (s.min === s.max) return 0;\n return Math.sqrt(Math.max(0, s.m2) / (s.n - 1));\n}\n","/**\n * Ordinary least squares with a Householder QR decomposition. The QR decomposition does not square the condition\n * number of the design, as the normal equations do. A design without full rank gives NaN coefficients and does not\n * throw. Thus a bootstrap run with a singular draw is not finite, and it does not count.\n */\n\nexport interface LeastSquaresOptions {\n /** When true, the fit adds an intercept as coefficient 0. The default is true. */\n readonly intercept?: boolean;\n}\n\nexport interface LeastSquaresFit {\n /** The coefficients. With an intercept, coefficient 0 is the intercept and coefficient `j + 1` is predictor `j`. */\n readonly coefficients: number[];\n /** The residual standard deviation: the square root of the residual sum of squares divided by `n - k`. */\n readonly residualSd: number;\n /**\n * The coefficient of determination: 1 minus the residual sum of squares divided by the total sum of squares. With\n * an intercept, the total sum uses the distances from the mean of `y`. Without an intercept, it uses the values.\n */\n readonly r2: number;\n /** The number of rows. */\n readonly n: number;\n /** The number of coefficients, with the intercept. */\n readonly k: number;\n}\n\n/**\n * The relative tolerance of the rank test. A column is dependent when the part of it that is orthogonal to the\n * columns before it is shorter than this share of its length.\n */\nconst RANK_TOLERANCE = 1e-10;\n\n/**\n * The ordinary least-squares fit of `y` on the rows of `x`, with `k` coefficients. Each row has the same number of\n * predictors. The fit solves the problem with a Householder QR decomposition. When the design does not have full\n * rank, or when `n <= k`, the coefficients, `residualSd` and `r2` are NaN. When the total sum of squares is 0,\n * `r2` is NaN.\n *\n * This function throws a RangeError for an empty `x` and for rows of different lengths. It also throws\n * for `x` and `y` of different lengths, for a value that is not finite, and for a fit with no coefficient.\n */\nexport function leastSquares(x: readonly (readonly number[])[], y: readonly number[], options: LeastSquaresOptions = {}): LeastSquaresFit {\n const intercept = options.intercept ?? true;\n const k = checkedShape(\"leastSquares\", x, y, intercept);\n return fitRows(x, y, intercept, k);\n}\n\n/**\n * This function examines the shape and the values of a least-squares problem, and gives the number of\n * coefficients. It throws a RangeError for each fault.\n */\nexport function checkedShape(name: string, x: readonly (readonly number[])[], y: readonly number[], intercept: boolean): number {\n if (x.length === 0) throw new RangeError(`${name}: x is empty.`);\n if (x.length !== y.length) throw new RangeError(`${name}: x has ${x.length} rows and y has ${y.length} values. The two lengths must be equal.`);\n const p = (x[0] as readonly number[]).length;\n for (let i = 0; i < x.length; i++) {\n const row = x[i] as readonly number[];\n if (row.length !== p) throw new RangeError(`${name}: row ${i} of x has ${row.length} values, and row 0 has ${p}. Each row must have the same length.`);\n for (const v of row) if (!Number.isFinite(v)) throw new RangeError(`${name}: row ${i} of x has a value that is not finite.`);\n if (!Number.isFinite(y[i] as number)) throw new RangeError(`${name}: value ${i} of y is not finite.`);\n }\n const k = p + (intercept ? 1 : 0);\n if (k === 0) throw new RangeError(`${name}: the fit has no coefficient. Give a predictor or an intercept.`);\n return k;\n}\n\n/**\n * The fit of rows with a known shape. The caller examined the shape with `checkedShape`. The design is a matrix of\n * `n` rows and `k` columns, kept by column.\n */\nexport function fitRows(x: readonly (readonly number[])[], y: readonly number[], intercept: boolean, k: number): LeastSquaresFit {\n const n = x.length;\n const failed = (): LeastSquaresFit => ({ coefficients: new Array<number>(k).fill(Number.NaN), residualSd: Number.NaN, r2: Number.NaN, n, k });\n if (n <= k) return failed();\n const offset = intercept ? 1 : 0;\n const a = new Float64Array(n * k);\n for (let i = 0; i < n; i++) {\n const row = x[i] as readonly number[];\n if (intercept) a[i] = 1;\n for (let j = offset; j < k; j++) a[j * n + i] = row[j - offset] as number;\n }\n const qty = Float64Array.from(y);\n const diagonal = new Float64Array(k);\n for (let j = 0; j < k; j++) {\n const c = j * n;\n // A reflection keeps the length of a column. Thus the length of column j is the length of its first form.\n let head = 0;\n for (let i = 0; i < j; i++) head += (a[c + i] as number) ** 2;\n let tail2 = 0;\n for (let i = j; i < n; i++) tail2 += (a[c + i] as number) ** 2;\n // The tail is the part of column j that is orthogonal to the columns before it.\n const tail = Math.sqrt(tail2);\n if (!(tail > RANK_TOLERANCE * Math.sqrt(head + tail2))) return failed();\n const alpha = (a[c + j] as number) > 0 ? -tail : tail;\n // The Householder vector v is the tail of column j minus alpha times the first unit vector. It is kept in place.\n a[c + j] = (a[c + j] as number) - alpha;\n let vv = 0;\n for (let i = j; i < n; i++) vv += (a[c + i] as number) ** 2;\n const reflect = (target: Float64Array, start: number): void => {\n let dot = 0;\n for (let i = j; i < n; i++) dot += (a[c + i] as number) * (target[start + i] as number);\n const f = (2 * dot) / vv;\n for (let i = j; i < n; i++) target[start + i] = (target[start + i] as number) - f * (a[c + i] as number);\n };\n for (let m = j + 1; m < k; m++) reflect(a, m * n);\n reflect(qty, 0);\n diagonal[j] = alpha;\n }\n // The back substitution of R b = Q'y. Above the diagonal, R is in the columns of a.\n const b = new Array<number>(k).fill(0);\n for (let j = k - 1; j >= 0; j--) {\n let s = qty[j] as number;\n for (let m = j + 1; m < k; m++) s -= (a[m * n + j] as number) * (b[m] as number);\n b[j] = s / (diagonal[j] as number);\n }\n let center = 0;\n if (intercept) {\n for (const v of y) center += v;\n center /= n;\n }\n let rss = 0;\n let tss = 0;\n for (let i = 0; i < n; i++) {\n const row = x[i] as readonly number[];\n let fitted = intercept ? (b[0] as number) : 0;\n for (let j = offset; j < k; j++) fitted += (b[j] as number) * (row[j - offset] as number);\n rss += ((y[i] as number) - fitted) ** 2;\n tss += ((y[i] as number) - center) ** 2;\n }\n return { coefficients: b, residualSd: Math.sqrt(rss / (n - k)), r2: tss > 0 ? 1 - rss / tss : Number.NaN, n, k };\n}\n","/**\n * The percentile bootstrap. Each run draws n items with replacement (`below(n)` of rigor-generators, which is\n * `floor(next() * n)`), and computes the statistic of the sample. The interval is two quantiles of the statistics.\n * With the same seed, the draws are equal to the draws of the copies in highways, packing and layout-contract.\n * `bootstrapTwo` draws two independent samples in each run: first the items of `a`, then the items of `b`.\n * `bootstrapLeastSquares` draws whole rows, and gives one interval for each coefficient from the same draws.\n *\n * `sampleTotalInterval` gives the interval of a population total from a sample without replacement.\n */\nimport { type Random, random } from \"@mark1russell7/rigor-generators\";\nimport { type QuantileMethod, median, quantileSorted, sorted } from \"./describe.ts\";\nimport { type LeastSquaresOptions, checkedShape, fitRows } from \"./regression.ts\";\n\nexport interface BootstrapOptions {\n /** The number of samples. The default is 10 000. */\n readonly runs?: number;\n /** The level of the interval. The default is 0.95. */\n readonly level?: number;\n /** The seed of the draws. The default is 1. */\n readonly seed?: number | string;\n /** The quantile method of the two ends of the interval. The default is linear. */\n readonly method?: QuantileMethod;\n /**\n * The quantiles of the two ends, in place of `level`, for example [0.025, 0.975] or an interval with one side.\n * The default is from the level: (1 - level) / 2 and 1 - (1 - level) / 2. In floating point, (1 - 0.95) / 2 is\n * not 0.025, so a copy that writes 0.025 needs this option to give the same numbers.\n */\n readonly ends?: readonly [number, number];\n /**\n * The value of a claim to test, for example 0 for \"no difference\". With this option, the interval also gives `pAbove`\n * and `pBelow` from the same draws, so the ends do not change. The default is no value and no p.\n */\n readonly against?: number;\n}\n\n/** The two bootstrap p of the option `against`. The smallest p is 1 / (finite + 1), so a family correction needs enough runs. */\nexport interface SideP {\n /** The value of the option `against`. */\n readonly against: number;\n /** The p of the claim \"the statistic is above `against`\": (1 + the finite runs at or below `against`) / (finite + 1). */\n readonly pAbove: number;\n /** The p of the claim \"the statistic is below `against`\": (1 + the finite runs at or above `against`) / (finite + 1). */\n readonly pBelow: number;\n}\n\nexport interface Interval extends Partial<SideP> {\n /** The statistic of all the data. */\n readonly estimate: number;\n readonly low: number;\n readonly high: number;\n readonly level: number;\n readonly runs: number;\n /** The number of runs whose statistic is a finite number. Only these runs make the interval. */\n readonly finite: number;\n /** The seed as a 32-bit number. */\n readonly seed: number;\n}\n\n/**\n * A percentile bootstrap interval of `statistic` over `data`. A run whose statistic is not finite (NaN or an\n * infinity) does not count. When no run is finite, low and high are equal to the estimate.\n */\nexport function bootstrap<T>(data: readonly T[], statistic: (sample: readonly T[]) => number, options: BootstrapOptions = {}): Interval {\n if (data.length === 0) throw new RangeError(\"bootstrap: the data is empty.\");\n const n = data.length;\n const sample = new Array<T>(n);\n return percentile(\n \"bootstrap\",\n options,\n (r) => {\n for (let i = 0; i < n; i++) sample[i] = data[r.below(n)] as T;\n return statistic(sample);\n },\n () => statistic(data),\n );\n}\n\n/**\n * A percentile bootstrap interval of `statistic` over two independent samples `a` and `b`. Use it when the two\n * samples are not paired, for example two arms of a benchmark. Each run draws `a.length` items of `a` with\n * replacement, and then `b.length` items of `b` with replacement. All the draws come from one stream of\n * `random(seed)`. The statistic reads the two drawn samples. The estimate is the statistic of all of `a` and `b`. A\n * run whose statistic is not finite does not count. When no run is finite, low and high are equal to the estimate.\n */\nexport function bootstrapTwo<A, B>(\n a: readonly A[],\n b: readonly B[],\n statistic: (a: readonly A[], b: readonly B[]) => number,\n options: BootstrapOptions = {},\n): Interval {\n if (a.length === 0) throw new RangeError(\"bootstrapTwo: the first sample is empty.\");\n if (b.length === 0) throw new RangeError(\"bootstrapTwo: the second sample is empty.\");\n const na = a.length;\n const nb = b.length;\n const sampleA = new Array<A>(na);\n const sampleB = new Array<B>(nb);\n return percentile(\n \"bootstrapTwo\",\n options,\n (r) => {\n for (let i = 0; i < na; i++) sampleA[i] = a[r.below(na)] as A;\n for (let i = 0; i < nb; i++) sampleB[i] = b[r.below(nb)] as B;\n return statistic(sampleA, sampleB);\n },\n () => statistic(a, b),\n );\n}\n\n/**\n * A bootstrap interval of the ratio `median(numerator) / median(denominator)` of two independent samples. The\n * interval is the uncertainty of the ratio of the two medians. It is not the spread of the samples. A run whose\n * denominator median is 0 is not finite, so it does not count.\n */\nexport function bootstrapMedianRatio(numerator: readonly number[], denominator: readonly number[], options: BootstrapOptions = {}): Interval {\n return bootstrapTwo(numerator, denominator, (a, b) => median(a) / median(b), options);\n}\n\n/**\n * A percentile bootstrap interval of each coefficient of the least-squares fit of `y` on the rows of `x`. Each run\n * draws `n` row indexes with replacement, and fits the drawn rows and their `y` values. All the intervals come from\n * the same draws. The estimate of each interval is the coefficient of the fit of all the data. A run with a singular\n * design gives NaN coefficients, so it does not count. The shape errors are the errors of `leastSquares`.\n */\nexport function bootstrapLeastSquares(\n x: readonly (readonly number[])[],\n y: readonly number[],\n options: BootstrapOptions & LeastSquaresOptions = {},\n): Interval[] {\n const intercept = options.intercept ?? true;\n const k = checkedShape(\"bootstrapLeastSquares\", x, y, intercept);\n const n = x.length;\n const sampleX = new Array<readonly number[]>(n);\n const sampleY = new Array<number>(n);\n return percentiles(\n \"bootstrapLeastSquares\",\n options,\n k,\n (r) => {\n for (let i = 0; i < n; i++) {\n const row = r.below(n);\n sampleX[i] = x[row] as readonly number[];\n sampleY[i] = y[row] as number;\n }\n return fitRows(sampleX, sampleY, intercept, k).coefficients;\n },\n () => fitRows(x, y, intercept, k).coefficients,\n );\n}\n\ninterface Settings {\n readonly runs: number;\n readonly lowEnd: number;\n readonly highEnd: number;\n readonly level: number;\n readonly method: QuantileMethod;\n readonly against: number | undefined;\n}\n\n/** This function examines the options of a bootstrap, and gives the defaults. It throws a RangeError for each fault. */\nfunction settings(name: string, options: BootstrapOptions): Settings {\n const runs = options.runs ?? 10_000;\n if (!Number.isSafeInteger(runs) || runs < 1) throw new RangeError(`${name}: runs is a whole number of 1 or more, not ${runs}.`);\n const tail = (1 - (options.level ?? 0.95)) / 2;\n const [lowEnd, highEnd] = options.ends ?? [tail, 1 - tail];\n if (!(lowEnd >= 0 && lowEnd < highEnd && highEnd <= 1)) throw new RangeError(`${name}: the ends are 0 <= low < high <= 1, not ${lowEnd} and ${highEnd}.`);\n const level = options.ends ? highEnd - lowEnd : (options.level ?? 0.95);\n if (!(level > 0 && level < 1)) throw new RangeError(`${name}: level is more than 0 and less than 1, not ${level}.`);\n const against = options.against;\n if (against !== undefined && !Number.isFinite(against)) throw new RangeError(`${name}: against is a finite number, not ${against}.`);\n return { runs, lowEnd, highEnd, level, method: options.method ?? \"linear\", against };\n}\n\n/** This function gives the two p of the option `against`, or nothing without the option. With no finite run, each p is 1. */\nfunction sides(values: readonly number[], against: number | undefined): SideP | Record<string, never> {\n if (against === undefined) return {};\n let atOrBelow = 0;\n let atOrAbove = 0;\n for (const v of values) {\n if (v <= against) atOrBelow++;\n if (v >= against) atOrAbove++;\n }\n const n = values.length + 1;\n return { against, pAbove: (1 + atOrBelow) / n, pBelow: (1 + atOrAbove) / n };\n}\n\n/** The interval of the finite statistics of the runs. When no run is finite, low and high are equal to the estimate. */\nfunction ends(values: number[], estimate: number, s: Settings, seed: number): Interval {\n const { runs, level } = s;\n const p = sides(values, s.against);\n if (values.length === 0) return { estimate, low: estimate, high: estimate, level, runs, finite: 0, seed, ...p };\n const v = sorted(values);\n return { estimate, low: quantileSorted(v, s.lowEnd, s.method), high: quantileSorted(v, s.highEnd, s.method), level, runs, finite: v.length, seed, ...p };\n}\n\n/**\n * The shared part of each percentile bootstrap. It examines the options, and starts one stream of `random(seed)`.\n * Each run gives the stream to `run`, which draws the samples and returns their statistic. Then `all` gives the\n * estimate. The order of the draws is the order in `run`.\n */\nfunction percentile(name: string, options: BootstrapOptions, run: (r: Random) => number, all: () => number): Interval {\n const s = settings(name, options);\n const r = random(options.seed ?? 1);\n const values: number[] = [];\n for (let i = 0; i < s.runs; i++) {\n const v = run(r);\n if (Number.isFinite(v)) values.push(v);\n }\n return ends(values, all(), s, r.seed);\n}\n\n/**\n * The percentile bootstrap of `k` statistics from the same draws. Each run gives `k` statistics. Each statistic\n * has its own count of finite runs.\n */\nexport function percentiles(name: string, options: BootstrapOptions, k: number, run: (r: Random) => readonly number[], all: () => readonly number[]): Interval[] {\n const s = settings(name, options);\n const r = random(options.seed ?? 1);\n const values = Array.from({ length: k }, (): number[] => []);\n for (let i = 0; i < s.runs; i++) {\n const v = run(r);\n for (let j = 0; j < k; j++) if (Number.isFinite(v[j])) (values[j] as number[]).push(v[j] as number);\n }\n const estimate = all();\n return values.map((list, j) => ends(list, estimate[j] as number, s, r.seed));\n}\n\n/** A bootstrap interval of the median. */\nexport function bootstrapMedian(values: readonly number[], options: BootstrapOptions = {}): Interval {\n return bootstrap(values, median, options);\n}\n\n/**\n * A cluster bootstrap: each run draws whole clusters with replacement, and the statistic reads the rows of the drawn\n * clusters. Use it when the rows of one cluster (one board, one seed, one site) are not independent. The clusters\n * are in the order of their first row.\n */\nexport function bootstrapClusters<T>(\n rows: readonly T[],\n cluster: (row: T) => string,\n statistic: (rows: readonly T[]) => number,\n options: BootstrapOptions = {},\n): Interval {\n const groups = new Map<string, T[]>();\n for (const row of rows) {\n const key = cluster(row);\n const list = groups.get(key);\n if (list) list.push(row);\n else groups.set(key, [row]);\n }\n const clusters = [...groups.values()];\n const result = bootstrap(clusters, (drawn) => statistic(drawn.flat()), options);\n // The estimate of all the rows in their own order, not in the order of the clusters.\n const estimate = statistic(rows);\n return result.finite === 0 ? { ...result, estimate, low: estimate, high: estimate } : { ...result, estimate };\n}\n\n/**\n * A stratified bootstrap: each run draws, inside each stratum, as many items as the stratum has, with replacement.\n * So each sample keeps the size of each stratum. Use it when the strata are fixed by the design, for example the\n * families of the inputs of a benchmark. The draws of one run go through the strata in the order of the list. With one\n * stratum, the draws are equal to the draws of `bootstrap` with the same seed. The estimate is the statistic of all\n * the strata. A run whose statistic is not finite does not count.\n */\nexport function bootstrapStrata<T>(\n strata: readonly (readonly T[])[],\n statistic: (samples: readonly (readonly T[])[]) => number,\n options: BootstrapOptions = {},\n): Interval {\n if (strata.length === 0) throw new RangeError(\"bootstrapStrata: there is no stratum.\");\n for (const [i, stratum] of strata.entries()) if (stratum.length === 0) throw new RangeError(`bootstrapStrata: the stratum ${i} is empty.`);\n const samples = strata.map((stratum) => new Array<T>(stratum.length));\n return percentile(\n \"bootstrapStrata\",\n options,\n (r) => {\n for (const [k, stratum] of strata.entries()) {\n const sample = samples[k] as T[];\n const n = stratum.length;\n for (let i = 0; i < n; i++) sample[i] = stratum[r.below(n)] as T;\n }\n return statistic(samples);\n },\n () => statistic(strata),\n );\n}\n\nexport interface SampleTotalOptions extends BootstrapOptions {\n /** The number of items in the whole population, `n`. It is a whole number, and it is not less than the sample. */\n readonly population: number;\n /** The factor from the sum of the sample to the total of the population. The default is `population / values.length`. */\n readonly scale?: number;\n}\n\n/**\n * A bootstrap interval of the total of a population from a uniform sample of `m` of its `n` items, drawn without\n * replacement. The estimate is `scale * sum(values)`. Each run draws `m` values with replacement, as `bootstrap`\n * does. The deviation of each run from the sum of the sample gets the factor `scale * sqrt(1 - m / n)`, the finite\n * population correction. When `m` is `n`, the interval is the estimate.\n *\n * The sample has 2 values or more, and each value is finite. With the same seed, the result is equal to the\n * `bootstrap` of the same statistic, to the bit.\n *\n * The interval is narrow for a small sample. The draws give the variance of the sample with the divisor `m`, not\n * `m - 1`, so the width gets the factor `sqrt((m - 1) / m)`. The skew of the values adds to the miss. In the tests,\n * 400 samples of `m = 8` of `n = 40` hold the total 346 times (Wilson 0.828 to 0.895). At `m = 100` of `n = 200`,\n * the coverage agrees with 95%. For a total over the pairs of the items, use `uStatisticInterval`.\n */\nexport function sampleTotalInterval(values: readonly number[], options: SampleTotalOptions): Interval {\n const name = \"sampleTotalInterval\";\n const m = values.length;\n const n = options.population;\n if (m < 2) throw new RangeError(`${name}: the sample has 2 values or more, not ${m}.`);\n if (!Number.isSafeInteger(n) || n < m) throw new RangeError(`${name}: population is a whole number of ${m} (the sample) or more, not ${n}.`);\n for (const v of values) if (!Number.isFinite(v)) throw new RangeError(`${name}: each value is a finite number, not ${v}.`);\n const scale = options.scale ?? n / m;\n if (!(Number.isFinite(scale) && scale > 0)) throw new RangeError(`${name}: scale is a finite number more than 0, not ${scale}.`);\n const all = sum(values);\n const estimate = scale * all;\n const spread = Math.sqrt(1 - m / n) * scale;\n return bootstrap(values, (drawn) => estimate + spread * (sum(drawn) - all), options);\n}\n\n/** The sum of the values from the first to the last, as `values.reduce((s, t) => s + t, 0)`. */\nfunction sum(values: readonly number[]): number {\n let s = 0;\n for (const v of values) s += v;\n return s;\n}\n","/**\n * The shape of a sample: the count of its modes, and the smooth law with the highest likelihood. Use them to read the\n * law that a generator really emits, from its values and not from its label.\n */\nimport { mean, quantile, sd, sorted } from \"./describe.ts\";\n\n/** The smooth laws that `smoothLawScores` compares. Each law has 2 fitted numbers. */\nexport type SmoothLaw = \"uniform\" | \"normal\" | \"exponential\" | \"log-normal\" | \"pareto\";\n\n/** The value of one law at its fit. */\nexport interface SmoothLawScore {\n readonly law: SmoothLaw;\n /** The mean log density of the values at the fit of the law. A larger value is a better fit. */\n readonly meanLogDensity: number;\n}\n\n/** The options of `modeCount`. */\nexport interface ModeOptions {\n /**\n * The smallest share of the mass that makes a mode. The default is `0.1`. Half of the mass of the largest mode also\n * makes a mode, so many equal modes each count.\n */\n readonly minShare?: number;\n /** The valley between two peaks of the kernel is under this share of the lower peak. The default is `0.5`. */\n readonly valleyRatio?: number;\n}\n\n/** The points of the grid of the density estimate. */\nconst GRID = 96;\n/** The width of the kernel, in the factor of Silverman's rule. The value 0.9 of that rule hides close modes. */\nconst KERNEL_FACTOR = 0.45;\n/** The share of the values in a span of neighbours, as a factor of `n ** -0.2`. */\nconst SPAN_FACTOR = 0.1;\n/** The quantile of the spans. A low quantile stays in the clusters when most spans cross a gap. */\nconst SPAN_QUANTILE = 0.25;\n/**\n * The tight width replaces the width from the quartiles under this ratio. In seeded smooth samples the ratio stays over\n * 0.2, except for a heavy tail, and in tight clusters it stays under 0.02.\n */\nconst TIGHT_RATIO = 0.1;\n/** The kernels stop at this count of widths. */\nconst KERNEL_REACH = 3;\nconst HALF_LOG_2PI_E = 0.5 * Math.log(2 * Math.PI * Math.E);\n/** Two values closer than this share of the range are one value, so the noise of a float makes no new value. */\nconst SAME_VALUE = 1e-9;\n/** The most distinct values of a direct read of their counts. The grid resolves no more than this count of clusters. */\nconst FEW_VALUES = GRID / 4;\n/** The mean count of each value in a direct read. Under it the values are a small sample, and the kernel reads them. */\nconst MIN_REPEATS = 4;\n/** The fewest values that show the shape of a law. A sample with fewer values gives one mode for each value. */\nconst MIN_BELL_VALUES = 4;\n/** The ratio of the highest third of the counts to the lowest third, under which the counts are flat. */\nconst FLAT_RATIO = 3;\n/** The ratio of the means of the three parts of the list of counts, under which the counts have no shape. */\nconst SHAPE_RATIO = 1.75;\n/** A value with under this share of the sample is a tail. A rare value does not change the shape of the counts. */\nconst RARE_VALUE = 0.01;\n/** The fewest values of a hump of a rounded law. When most humps are narrower, the values are a discrete law. */\nconst MIN_HUMP_VALUES = 3;\n/** A count differs from another count at this z value. The two counts then differ by more than the noise of a sample. */\nconst COUNT_Z = 3;\n\n/** One hump of a series: its highest point, the sum of its points and the count of its points. */\ninterface Hump {\n readonly top: number;\n readonly mass: number;\n readonly points: number;\n}\n\n/**\n * This function gives the distances of the values from one end of the sample, in order. It takes the end that gives the\n * smaller list, so `x` and `-x` give one list and one count.\n */\nfunction fromOneEnd(values: readonly number[]): number[] {\n const order = sorted(values);\n const low = order[0]!;\n const high = order[order.length - 1]!;\n const rising = order.map((x) => x - low);\n const falling = order.map((x) => high - x).reverse();\n const first = rising.findIndex((x, i) => x !== falling[i]);\n return first >= 0 && falling[first]! < rising[first]! ? falling : rising;\n}\n\n/**\n * This function gives the width of the kernel. The width from the quartiles follows the distance between clusters, so\n * it hides many tight clusters. A low quantile of the spans of neighbouring values follows the width of a cluster.\n * The function uses the tight width only when it is far under the other width, so a smooth sample keeps its width.\n * The tight width stays over the grid step. No width goes under the median gap of the distinct values of a tight\n * sample. A step of rounding is no gap between clusters, so a rounded smooth sample keeps one mode at each size.\n */\nfunction kernelWidth(values: readonly number[], low: number, high: number): number {\n const count = values.length;\n const order = sorted(values);\n const scale = Math.min(quantile(values, 0.75) - quantile(values, 0.25), high - low) / 1.34;\n const wide = KERNEL_FACTOR * Math.max(scale, (high - low) / GRID) * count ** -0.2;\n const neighbours = Math.min(count - 1, Math.ceil(SPAN_FACTOR * count ** 0.8));\n const tight = quantile(order.slice(neighbours).map((x, i) => x - order[i]!), SPAN_QUANTILE);\n if (tight >= TIGHT_RATIO * wide) return wide;\n const distinct = order.filter((x, i) => i === 0 || x !== order[i - 1]);\n const resolution = quantile(distinct.slice(1).map((x, i) => x - distinct[i]!), 0.5);\n return Math.max(resolution, Math.min(wide, Math.max(tight, (high - low) / GRID)));\n}\n\n/** This function gives the Gaussian kernel density of the values on a grid. */\nfunction densityGrid(values: readonly number[], low: number, high: number): Float64Array {\n const width = kernelWidth(values, low, high);\n const start = low - KERNEL_REACH * width;\n const step = (high - low + 2 * KERNEL_REACH * width) / (GRID - 1);\n const density = new Float64Array(GRID);\n for (const x of values) {\n const first = Math.max(0, Math.floor((x - KERNEL_REACH * width - start) / step));\n const last = Math.min(GRID - 1, Math.ceil((x + KERNEL_REACH * width - start) / step));\n for (let i = first; i <= last; i++) {\n const u = (start + i * step - x) / width;\n density[i]! += Math.exp(-0.5 * u * u);\n }\n }\n return density;\n}\n\n/**\n * This function gives the humps of a series. It first gives each rise and fall one hump. Then it joins the two neighbours\n * with the closest valley, and again, until each valley has a closeness under the limit. The result has no direction,\n * because the order of the joins comes from the depth of the valleys and not from their position.\n */\nfunction humpsOf(series: ArrayLike<number>, closeness: (lower: number, valley: number) => number, limit: number): Hump[] {\n const humps: Hump[] = [];\n const valleys: number[] = [];\n let index = 0;\n while (index < series.length) {\n let top = index;\n while (top + 1 < series.length && series[top + 1]! >= series[top]!) top++;\n let end = top;\n while (end + 1 < series.length && series[end + 1]! < series[end]!) end++;\n let mass = 0;\n for (let i = index; i <= end; i++) mass += series[i]!;\n humps.push({ top: series[top]!, mass, points: end + 1 - index });\n if (end + 1 < series.length) valleys.push(series[end]!);\n index = end + 1;\n }\n while (valleys.length > 0) {\n const scores = valleys.map((valley, i) => closeness(Math.min(humps[i]!.top, humps[i + 1]!.top), valley));\n const closest = scores.indexOf(Math.max(...scores));\n if (scores[closest]! < limit) break;\n const [left, right] = [humps[closest]!, humps[closest + 1]!];\n humps.splice(closest, 2, { top: Math.max(left.top, right.top), mass: left.mass + right.mass, points: left.points + right.points });\n valleys.splice(closest, 1);\n }\n return humps;\n}\n\n/** This function gives the count of each distinct value, in the order of the values. */\nfunction valueCounts(values: readonly number[], low: number, high: number): number[] {\n const tie = SAME_VALUE * (high - low);\n const counts: number[] = [];\n let last = -Infinity;\n for (const x of sorted(values)) {\n if (x - last > tie) {\n counts.push(0);\n last = x;\n }\n counts[counts.length - 1]!++;\n }\n return counts;\n}\n\n/**\n * This function tells that the counts are flat. The highest third of the counts stays under `FLAT_RATIO` times the\n * lowest third, so a list of heavy and light values is not flat. The means of the first, the middle and the last third\n * of the list stay under `SHAPE_RATIO` of each other. The noise of a sample cancels in those means, and a bell does not.\n */\nfunction flatCounts(counts: readonly number[]): boolean {\n const order = [...counts].sort((a, b) => a - b);\n const third = Math.ceil(order.length / 3);\n if (mean(order.slice(-third)) >= FLAT_RATIO * mean(order.slice(0, third))) return false;\n const parts = [counts.slice(0, third), counts.slice(third, -third), counts.slice(-third)].filter((part) => part.length > 0).map((part) => mean(part));\n return Math.max(...parts) < SHAPE_RATIO * Math.min(...parts);\n}\n\n/** This function gives the closeness of a count to a valley: the negative of its height over the noise of a sample. */\nconst countCloseness = (lower: number, valley: number): number => -(lower - valley) / Math.sqrt(lower + valley);\n\n/**\n * This function counts the modes of a sample with few distinct values, from the counts of those values. The result does\n * not change with the size of the sample. Flat counts are a discrete law with one mode for each value, so the noise of\n * a sample does not take a value out. Counts with one rise and one fall are a rounded smooth law with one mode.\n */\nfunction fewValueModes(allCounts: readonly number[], total: number, minShare: number): number {\n const counts = allCounts.filter((count) => count / total >= RARE_VALUE);\n const each = counts.map((count) => count / total);\n const overLimit = (masses: readonly number[], limit: number): number => masses.filter((share) => share >= limit).length;\n if (counts.length < MIN_BELL_VALUES) return overLimit(each, Math.min(minShare, Math.max(...each) / 2));\n if (flatCounts(counts)) return overLimit(each, Math.min(minShare, quantile(each, 0.5) / FLAT_RATIO));\n const humps = humpsOf(counts, countCloseness, -COUNT_Z);\n const narrow = humps.filter((hump) => hump.points < MIN_HUMP_VALUES).length;\n const masses = 2 * narrow > humps.length ? each : humps.map((hump) => hump.mass / total);\n return overLimit(masses, Math.min(minShare, Math.max(...masses) / 2));\n}\n\n/**\n * This function gives the mass of each mode from a kernel estimate on a grid. Two peaks stay apart when the valley\n * between them is under `valleyRatio` of the lower peak.\n */\nfunction kernelMasses(values: readonly number[], low: number, high: number, valleyRatio: number): number[] {\n const density = densityGrid(values, low, high);\n const total = density.reduce((sum, d) => sum + d, 0);\n return humpsOf(density, (lower, valley) => valley / lower, valleyRatio).map((hump) => hump.mass / total);\n}\n\n/**\n * This function counts the modes of a sample. A mode counts when it holds `minShare` of the mass. The default counts the\n * modes that hold 10 percent, and a caller who needs all modes passes a smaller value. The result is at least 1. The\n * result is the same for `x` and `-x`.\n *\n * A sample with 24 or fewer distinct values, and 4 or more copies of each value on average, gets a direct read.\n * That read uses the counts of the values, and it does not change with the size of the sample.\n * It gives one mode for each value of a flat discrete law. So even groups give the count of the groups, and so does a\n * rounded uniform law with 24 or fewer steps. It gives one mode for each hump of a rounded smooth law.\n * The direct read of a sample with 3 or fewer values gives one mode for each value that holds the share.\n *\n * A kernel estimate on a grid reads each other sample. The grid has 96 points, so the kernel joins more than\n * approximately 24 evenly spaced clusters. A tight cluster also needs more than approximately `n ** 0.8 / 8` values for\n * a sample of `n` values. A cluster with an SD over 5 percent of the gap to the next cluster can join it.\n *\n * The function throws a RangeError for an empty list or for a value that is not finite.\n */\nexport function modeCount(values: readonly number[], options: ModeOptions = {}): number {\n const { minShare = 0.1, valleyRatio = 0.5 } = options;\n if (values.length === 0) throw new RangeError(\"modeCount: the list is empty.\");\n for (const v of values) if (!Number.isFinite(v)) throw new RangeError(\"modeCount: each value must be finite.\");\n const distances = fromOneEnd(values);\n const high = distances[distances.length - 1]!;\n if (high === 0) return 1;\n const counts = valueCounts(distances, 0, high);\n if (counts.length <= FEW_VALUES && values.length >= MIN_REPEATS * counts.length) return fewValueModes(counts, values.length, minShare);\n const masses = kernelMasses(distances, 0, high, valleyRatio);\n const limit = Math.min(minShare, Math.max(...masses) / 2);\n return masses.filter((share) => share >= limit).length;\n}\n\n/**\n * This function gives the mean log density of the values under each smooth law, at the closed-form fit of that law.\n * Each law has 2 fitted numbers, so the function adds no penalty. The uniform, the shifted exponential and the Pareto\n * law take the smallest value as their lower limit. This fitted end helps them at small sizes. All values are exact\n * maximum likelihoods.\n * The function throws a RangeError for an empty list, for a value that is not positive and finite, or for equal values.\n */\nexport function smoothLawScores(values: readonly number[]): readonly SmoothLawScore[] {\n if (values.length === 0) throw new RangeError(\"smoothLawScores: the list is empty.\");\n for (const v of values) if (!(v > 0 && Number.isFinite(v))) throw new RangeError(\"smoothLawScores: each value must be positive and finite.\");\n const logs = values.map((v) => Math.log(v));\n const low = quantile(values, 0);\n const high = quantile(values, 1);\n if (low === high) throw new RangeError(\"smoothLawScores: the values are equal, so no law has a density.\");\n const meanLog = mean(logs);\n const toExact = 0.5 * Math.log(values.length / (values.length - 1));\n const alpha = 1 / (meanLog - Math.log(low));\n return [\n { law: \"uniform\", meanLogDensity: -Math.log(high - low) },\n { law: \"normal\", meanLogDensity: -Math.log(sd(values)) - HALF_LOG_2PI_E + toExact },\n { law: \"exponential\", meanLogDensity: -Math.log(mean(values) - low) - 1 },\n { law: \"log-normal\", meanLogDensity: -Math.log(sd(logs)) - HALF_LOG_2PI_E - meanLog + toExact },\n { law: \"pareto\", meanLogDensity: Math.log(alpha) + alpha * Math.log(low) - (alpha + 1) * meanLog },\n ];\n}\n\n/**\n * This function gives the smooth law with the highest likelihood. Under 300 values the result is not reliable: the\n * normal and the log-normal law lose to the laws with a fitted end. The README gives the measured shares of correct\n * results. The function throws as `smoothLawScores` does.\n */\nexport function bestSmoothLaw(values: readonly number[]): SmoothLaw {\n return smoothLawScores(values).reduce((best, score) => (score.meanLogDensity > best.meanLogDensity ? score : best)).law;\n}\n","/**\n * The ridge solve of a least-squares problem from its normal equations. The caller gives the matrix `X'X` and the\n * vector `X'y`. Thus it can make them from sparse rows. It can also remove the sums of one fold of a cross-validation.\n * The solve uses a Cholesky factorization of `X'X + lambda * P`. The matrix `P` is the identity, with 0 on the\n * diagonal for each free coefficient, for example an intercept.\n */\n\nexport interface RidgeOptions {\n /** The indexes of the coefficients with no penalty, for example 0 for an intercept. The default is none. */\n readonly free?: readonly number[];\n}\n\n/**\n * The relative tolerance of the Cholesky pivots. A pivot is the squared length of the part of a column that is\n * orthogonal to the columns before it. The rounding error of a pivot is approximately 1e-16 times its diagonal value.\n * Thus a pivot of a dependent column is not exactly 0, and the tolerance is larger than that error.\n */\nconst PIVOT_TOLERANCE = 1e-12;\n\n/**\n * This function gives the coefficients `beta` that solve `(gram + lambda * P) beta = moment`.\n * - `gram` is the symmetric matrix `X'X` of size `k`, in row order. The function reads only its lower triangle.\n * - `moment` is the vector `X'y` of length `k`.\n * - With `lambda` 0, the result is the ordinary least-squares fit.\n *\n * The function does not change `gram` or `moment`. When the matrix is not positive definite, each coefficient is\n * NaN, as in `leastSquares`. The function throws a RangeError when `gram` does not have `k * k` values, and when\n * `k` is 0. It also throws for a value that is not finite, for a `lambda` below 0, and for a bad free index.\n */\nexport function ridgeSolve(gram: ArrayLike<number>, moment: ArrayLike<number>, lambda: number, options: RidgeOptions = {}): number[] {\n const k = moment.length;\n if (k === 0) throw new RangeError(\"ridgeSolve: the moment is empty.\");\n if (gram.length !== k * k) throw new RangeError(`ridgeSolve: the gram has ${gram.length} values, and a moment of length ${k} needs ${k * k}.`);\n if (!(lambda >= 0 && Number.isFinite(lambda))) throw new RangeError(`ridgeSolve: lambda is a finite number of 0 or more, not ${lambda}.`);\n const penalty = new Float64Array(k).fill(lambda);\n for (const i of options.free ?? []) {\n if (!Number.isSafeInteger(i) || i < 0 || i >= k) throw new RangeError(`ridgeSolve: a free index is a whole number from 0 to ${k - 1}, not ${i}.`);\n penalty[i] = 0;\n }\n const a = new Float64Array(k * k);\n for (let i = 0; i < k * k; i++) {\n const v = gram[i] as number;\n if (!Number.isFinite(v)) throw new RangeError(`ridgeSolve: the gram value ${i} is not finite.`);\n a[i] = v;\n }\n const x = new Float64Array(k);\n for (let i = 0; i < k; i++) {\n const v = moment[i] as number;\n if (!Number.isFinite(v)) throw new RangeError(`ridgeSolve: the moment value ${i} is not finite.`);\n x[i] = v;\n a[i * k + i] = (a[i * k + i] as number) + (penalty[i] as number);\n }\n if (!factor(a, k)) return new Array<number>(k).fill(Number.NaN);\n for (let i = 0; i < k; i++) {\n let s = x[i] as number;\n for (let j = 0; j < i; j++) s -= (a[i * k + j] as number) * (x[j] as number);\n x[i] = s / (a[i * k + i] as number);\n }\n for (let i = k - 1; i >= 0; i--) {\n let s = x[i] as number;\n for (let j = i + 1; j < k; j++) s -= (a[j * k + i] as number) * (x[j] as number);\n x[i] = s / (a[i * k + i] as number);\n }\n return Array.from(x);\n}\n\n/**\n * This function writes the Cholesky factor `L` of `a` into its lower triangle, with `a = L L'`. It returns false when\n * a pivot is not more than the tolerance times the diagonal value of its column.\n */\nexport function factor(a: Float64Array, k: number): boolean {\n for (let j = 0; j < k; j++) {\n const diagonal = a[j * k + j] as number;\n let d = diagonal;\n for (let m = 0; m < j; m++) d -= (a[j * k + m] as number) ** 2;\n if (!(d > PIVOT_TOLERANCE * Math.abs(diagonal)) || !(d > 0)) return false;\n const l = Math.sqrt(d);\n a[j * k + j] = l;\n for (let i = j + 1; i < k; i++) {\n let s = a[i * k + j] as number;\n for (let m = 0; m < j; m++) s -= (a[i * k + m] as number) * (a[j * k + m] as number);\n a[i * k + j] = s / l;\n }\n }\n return true;\n}\n","/**\n * The format `response-records/1`: the measured points of a function of many dimensions, with a fitted model and the\n * held-out error of each measure. A record is plain JSON. A browser reads it with `parseResponseRecord`, and it\n * evaluates the models with `predictResponse`. A view shows one dimension with `sliceResponse`, or two dimensions\n * with `surfaceResponse`, and it holds the other dimensions.\n *\n * This file has the types and the pure functions that read a record. `response-parse.ts` has the validator, and\n * `response-fit.ts` has the fit. The three files use no Node import, no clock and no `Math.random`.\n *\n * A model calculates integer powers with multiplication, so its terms are equal in each JavaScript engine. A log\n * scale uses `Math.log10` and `10 ** x`. An engine can give a different last bit for these two operations.\n */\nimport { mean, quantile } from \"./describe.ts\";\n\n/** The value of the field `schema` of a record. */\nexport const RESPONSE_RECORDS_SCHEMA = \"response-records/1\";\n\n/** The value of a dimension at a point: a number, or the text of a level. */\nexport type ResponseValue = number | string;\n\n/** The value of a dimension at a place. The value `null` means that a conditional dimension is absent there. */\nexport type ResponseInputValue = ResponseValue | null;\n\n/** The condition of a dimension: the dimension has a value only at these levels of its parent. */\nexport interface ResponseWhen {\n /** The id of the parent: a categorical or ordinal dimension with no condition. */\n readonly dimension: string;\n readonly levels: readonly ResponseValue[];\n}\n\n/** The fields of each kind of dimension. */\nexport interface ResponseDimensionBase {\n /** The key of the dimension in the values of a point. */\n readonly id: string;\n /** The name that a view shows. */\n readonly label: string;\n /** The unit. An empty string means that the dimension has no unit. */\n readonly unit: string;\n /** With this field, a point has a value only at the stated levels of the parent. Each other point has `null`. */\n readonly when?: ResponseWhen;\n}\n\n/** A dimension with each number in a range. */\nexport interface ContinuousDimension extends ResponseDimensionBase {\n readonly kind: \"continuous\";\n /** The smallest and the largest value. The first is less than the second. */\n readonly range: readonly [number, number];\n /** When true, a model and an axis use the base-10 logarithm of the value. All of the range is above 0. */\n readonly log?: boolean;\n}\n\n/** A dimension with levels in order. Number levels ascend. A model reads a text level as its position. */\nexport interface OrdinalDimension extends ResponseDimensionBase {\n readonly kind: \"ordinal\";\n readonly levels: readonly number[] | readonly string[];\n /** When true, a model uses the base-10 logarithm of the level. The levels are numbers above 0. */\n readonly log?: boolean;\n}\n\n/** A dimension with levels that have no order, for example the arms of a benchmark. */\nexport interface CategoricalDimension extends ResponseDimensionBase {\n readonly kind: \"categorical\";\n readonly levels: readonly string[];\n}\n\n/** A dimension of a record. */\nexport type ResponseDimension = ContinuousDimension | OrdinalDimension | CategoricalDimension;\n\n/** A measured value of each point. */\nexport interface ResponseMeasure {\n /** The key of the measure in the measures of a point. */\n readonly id: string;\n readonly label: string;\n /** The unit. An empty string means that the measure has no unit. */\n readonly unit: string;\n /** The better direction of the value. The value `none` means that no direction is better. */\n readonly direction: \"higher\" | \"lower\" | \"none\";\n /**\n * The low and the high end of the possible values, for example `[0, 1]` for a share. Each measured value is in this\n * range. A view clips its fitted values to it, and a fit does not use it.\n */\n readonly range?: readonly [number, number];\n}\n\n/** A declared reason that a measure is absent, for example infeasible, unsupported or out of budget. */\nexport interface ResponseReason {\n /** The key of the reason in the field `absent` of a point. */\n readonly id: string;\n /** The name that a view shows. */\n readonly label: string;\n}\n\n/** One measured point. */\nexport interface ResponsePoint {\n readonly id: string;\n /** The value of each dimension. */\n readonly values: Readonly<Record<string, ResponseInputValue>>;\n /** The value of each measure. The value `null` means that the run did not give the measure at this point. */\n readonly measures: Readonly<Record<string, number | null>>;\n /** The points of one group stay on one side of each split, for example the repeats of one seed. */\n readonly group?: string;\n /** The reason of a measure with `null`: a map from the id of the measure to the id of a declared reason. */\n readonly absent?: Readonly<Record<string, string>>;\n}\n\n/** One factor of a term: a power of a number dimension, or 1 at a level and 0 at each other level. */\nexport type ResponseFactor = { readonly dimension: string; readonly power: number } | { readonly dimension: string; readonly level: ResponseValue };\n\n/** The fields of each kind of input of a ridge model. */\nexport interface RidgeInputBase {\n readonly dimension: string;\n /** When true, the dimension is conditional, so `null` is a good value. Each term of an absent dimension is 0. */\n readonly conditional?: boolean;\n}\n\n/** The coordinate of a number dimension: the value (or its logarithm), less `center`, divided by `spread`. */\nexport interface RidgeNumberInput extends RidgeInputBase {\n readonly kind: \"number\";\n readonly center: number;\n readonly spread: number;\n readonly log?: boolean;\n}\n\n/** The coordinate of an ordinal dimension with text levels: the position of the level, as in `RidgeNumberInput`. */\nexport interface RidgeRankInput extends RidgeInputBase {\n readonly kind: \"rank\";\n readonly levels: readonly string[];\n readonly center: number;\n readonly spread: number;\n}\n\n/** A categorical dimension: the factors of its levels are the one-hot columns. */\nexport interface RidgeLevelInput extends RidgeInputBase {\n readonly kind: \"level\";\n readonly levels: readonly string[];\n}\n\n/** An input of a ridge model. The model holds it, so `predictResponse` needs no record. */\nexport type RidgeInput = RidgeNumberInput | RidgeRankInput | RidgeLevelInput;\n\n/** A term of a ridge model: the product of its factors, times the weight. */\nexport interface RidgeTerm {\n readonly factors: readonly ResponseFactor[];\n readonly weight: number;\n}\n\n/** The fields of each kind of model. */\nexport interface ResponseModelBase {\n /** The id of the measure of the model. */\n readonly measure: string;\n /** With `log`, the model and the held-out errors use the base-10 logarithm of the measure. */\n readonly scale: \"linear\" | \"log\";\n /** With the scale `log`, the fit gave this value to each smaller measured value. */\n readonly floor?: number;\n}\n\n/** A ridge fit over a stated expansion: the intercept, plus the sum of the terms. */\nexport interface RidgeResponseModel extends ResponseModelBase {\n readonly kind: \"ridge\";\n /** The penalty of the fit. */\n readonly lambda: number;\n readonly inputs: readonly RidgeInput[];\n readonly intercept: number;\n readonly terms: readonly RidgeTerm[];\n}\n\n/** One cell of a table model. */\nexport interface ResponseTableCell {\n /** The value of each dimension of the table, in the order of its `dimensions`. An absent dimension has `null`. */\n readonly at: readonly ResponseInputValue[];\n /** The mean of the measured values of the cell, on the scale of the model. */\n readonly value: number;\n /** The number of points of the cell. */\n readonly n: number;\n}\n\n/** The mean of each measured combination of levels. */\nexport interface TableResponseModel extends ResponseModelBase {\n readonly kind: \"table\";\n readonly dimensions: readonly string[];\n /** The ids of the dimensions of the table with a condition. Only these dimensions take `null`. */\n readonly conditional?: readonly string[];\n readonly cells: readonly ResponseTableCell[];\n /** The value of a combination with no cell: the mean of all the fitted points, on the scale of the model. */\n readonly fallback: number;\n}\n\n/** A model that a browser evaluates from plain JSON. */\nexport type ResponseModel = RidgeResponseModel | TableResponseModel;\n\n/** The held-out error of one measure in one fold, on the scale of the model. */\nexport interface ResponseFoldError {\n /** The number of held-out points with a value of the measure. */\n readonly n: number;\n /** The mean absolute error. */\n readonly mae: number;\n /** The root mean square error. */\n readonly rmse: number;\n /** The mean absolute error of the mean of the training points, used as the prediction. */\n readonly baselineMae: number;\n}\n\n/** One split of the points. The fold held out `heldOut`, and it fit a model on the other points. */\nexport interface ResponseFold {\n /** The ids of the held-out points. */\n readonly heldOut: readonly string[];\n /** The error of each measure. A measure with no held-out point or no training point has no entry. */\n readonly errors: Readonly<Record<string, ResponseFoldError>>;\n /**\n * The prediction of each held-out point with a value, on the scale of the model. The keys are the id of the measure,\n * then the id of the point. The model of this fold gave them. Only the option `outOfFold` of `fitResponse` writes this field.\n */\n readonly predictions?: Readonly<Record<string, Readonly<Record<string, number>>>>;\n}\n\n/** The data of a record, before a fit. */\nexport interface ResponseData {\n readonly schema: typeof RESPONSE_RECORDS_SCHEMA;\n readonly name: string;\n readonly dimensions: readonly ResponseDimension[];\n readonly measures: readonly ResponseMeasure[];\n /** The reasons that a measure of a point can be absent. Each id in the field `absent` of a point is in this list. */\n readonly reasons?: readonly ResponseReason[];\n readonly points: readonly ResponsePoint[];\n}\n\n/** A record: the data, one model for each measure, and the folds. */\nexport interface ResponseRecord extends ResponseData {\n readonly models: readonly ResponseModel[];\n readonly folds: readonly ResponseFold[];\n}\n\n/** The held-out error of one measure over all the folds, on the scale of the model. */\nexport interface ResponseHeldOutError {\n /** The number of held-out points. */\n readonly n: number;\n /** The number of folds with this measure. */\n readonly folds: number;\n /** The mean absolute error of all the held-out points. */\n readonly mae: number;\n /** The root mean square error of all the held-out points. */\n readonly rmse: number;\n /** The mean absolute error of the baseline. */\n readonly baselineMae: number;\n /** The value `1 - mae / baselineMae`. The value 0 is no better than the mean. A baseline of 0 gives `null`. */\n readonly skill: number | null;\n}\n\n/** The options of `sliceResponse` and `surfaceResponse`. */\nexport interface ResponseViewOptions {\n /** The value of each held dimension. Each other dimension takes its usual value, as `sliceResponse` tells. */\n readonly hold?: Readonly<Record<string, ResponseInputValue>>;\n /** The number of values on a continuous axis, 2 or more. The default is 33. */\n readonly steps?: number;\n /**\n * The share of the range of a held number dimension in which a point matches. A log dimension uses the log scale.\n * The default is 0: only an equal value matches.\n */\n readonly tolerance?: number;\n /** The half width of the band, as a multiple of the held-out root mean square error. The default is 1. */\n readonly width?: number;\n}\n\n/** The options of `sliceResponse`. */\nexport interface ResponseSliceOptions extends ResponseViewOptions {\n /** The id of the dimension of the curve. */\n readonly vary: string;\n}\n\n/** The options of `surfaceResponse`. */\nexport interface ResponseSurfaceOptions extends ResponseViewOptions {\n /** The ids of the two dimensions of the surface: first the x axis, then the y axis. */\n readonly vary: readonly [string, string];\n}\n\n/**\n * The fitted value at one place, with its band. The band is the mean error of the model, and `nearest` tells how far\n * the place is from a measurement.\n */\nexport interface ResponseBand {\n readonly value: number;\n readonly low: number;\n readonly high: number;\n /**\n * The distance from this place to the nearest measured point with a value of the measure, from 0 to 1. The value 0\n * means that a point was measured here. A number or rank dimension counts as its share of the axis. A different\n * categorical level counts 1, and an absent value against a present value counts 1. The distance is the largest\n * count over the dimensions.\n */\n readonly nearest: number;\n /** This field is true when the measure has a `range` and the view moved `value`, `low` or `high` into it. */\n readonly clipped?: true;\n}\n\n/** One place of a curve. */\nexport interface ResponseCurvePoint extends ResponseBand {\n /** The value of the varied dimension. */\n readonly at: ResponseValue;\n}\n\n/** A measured point of a slice. */\nexport interface ResponseSlicePoint {\n readonly id: string;\n /** The value of the varied dimension. */\n readonly at: ResponseValue;\n readonly value: number;\n readonly group?: string;\n}\n\n/** A point of a slice that matches the held values and has no value of the measure. */\nexport interface ResponseAbsentPoint {\n readonly id: string;\n /** The value of the varied dimension. */\n readonly at: ResponseValue;\n /** The id of the declared reason. The value `null` means that the point states no reason. */\n readonly reason: string | null;\n readonly group?: string;\n}\n\n/** The fitted curve over one dimension, and the measured points that match the held values. */\nexport interface ResponseSlice {\n readonly measure: string;\n readonly vary: string;\n /** The value of each other dimension. */\n readonly held: Readonly<Record<string, ResponseInputValue>>;\n readonly curve: readonly ResponseCurvePoint[];\n readonly points: readonly ResponseSlicePoint[];\n /** The points that match the held values and have no value of the measure, each with its reason. */\n readonly absent: readonly ResponseAbsentPoint[];\n readonly error: ResponseHeldOutError;\n /** The number of places of `curve` with the field `clipped`. */\n readonly clipped: number;\n}\n\n/** A measured point of a surface. */\nexport interface ResponseSurfacePoint {\n readonly id: string;\n /** The values of the two varied dimensions. */\n readonly at: readonly [ResponseValue, ResponseValue];\n readonly value: number;\n readonly group?: string;\n}\n\n/** A point of a surface that matches the held values and has no value of the measure. */\nexport interface ResponseSurfaceAbsentPoint {\n readonly id: string;\n /** The values of the two varied dimensions. */\n readonly at: readonly [ResponseValue, ResponseValue];\n /** The id of the declared reason. The value `null` means that the point states no reason. */\n readonly reason: string | null;\n readonly group?: string;\n}\n\n/** The fitted surface over two dimensions, and the measured points that match the held values. */\nexport interface ResponseSurface {\n readonly measure: string;\n readonly vary: readonly [string, string];\n /** The value of each other dimension. */\n readonly held: Readonly<Record<string, ResponseInputValue>>;\n readonly x: readonly ResponseValue[];\n readonly y: readonly ResponseValue[];\n /** One row for each value of `y`. Each row has one cell for each value of `x`. */\n readonly cells: readonly (readonly ResponseBand[])[];\n readonly points: readonly ResponseSurfacePoint[];\n /** The points that match the held values and have no value of the measure, each with its reason. */\n readonly absent: readonly ResponseSurfaceAbsentPoint[];\n readonly error: ResponseHeldOutError;\n /** The number of places of `cells` with the field `clipped`. */\n readonly clipped: number;\n}\n\n/** This function gives the key of the group of a point. A point without a group is a group of its own. */\nexport function groupKey(point: ResponsePoint): string {\n return point.group === undefined ? `point ${JSON.stringify(point.id)}` : `group ${JSON.stringify(point.group)}`;\n}\n\n/** This function gives true for a dimension whose value is a number. */\nexport function isNumberDimension(dimension: ResponseDimension): dimension is ContinuousDimension | (OrdinalDimension & { readonly levels: readonly number[] }) {\n return dimension.kind === \"continuous\" || (dimension.kind === \"ordinal\" && typeof dimension.levels[0] === \"number\");\n}\n\n/** This function gives the low and the high end of a dimension on the numeric axis of a model. */\nexport function axisEnds(dimension: ResponseDimension): readonly [number, number] {\n if (!isNumberDimension(dimension)) return [0, dimension.levels.length - 1];\n const values = dimension.kind === \"continuous\" ? dimension.range : dimension.levels;\n const low = values[0] as number;\n const high = values[values.length - 1] as number;\n return dimension.log === true ? [Math.log10(low), Math.log10(high)] : [low, high];\n}\n\n/** This function gives true when a place has the condition of a dimension. A dimension with no condition is present. */\nexport function whenHolds(dimension: ResponseDimension, values: Readonly<Record<string, unknown>>): boolean {\n return dimension.when === undefined || dimension.when.levels.includes(values[dimension.when.dimension] as ResponseValue);\n}\n\n/** This function gives the reason that `value` is not a value of `dimension`. It gives `undefined` for a good value. */\nexport function valueFault(dimension: ResponseDimension, value: unknown): string | undefined {\n if (dimension.kind === \"continuous\") {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return `the value ${JSON.stringify(value)} is not a finite number`;\n const [low, high] = dimension.range;\n return value < low || value > high ? `the value ${value} is outside the range ${low} to ${high}` : undefined;\n }\n return (dimension.levels as readonly unknown[]).includes(value) ? undefined : `the value ${JSON.stringify(value)} is not a level of the dimension`;\n}\n\n/**\n * This function gives the input of a dimension, for each kind of model. It reads only a field of the object, not of\n * its prototype. It refuses `null` at a dimension with no condition, so a mistake of a caller cannot give a quiet value.\n */\nfunction inputValue(inputs: Readonly<Record<string, ResponseInputValue>>, dimension: string, conditional: boolean): ResponseInputValue {\n if (!Object.hasOwn(inputs, dimension)) throw new RangeError(`predictResponse: the inputs have no value of the dimension \"${dimension}\".`);\n const value = inputs[dimension] as ResponseInputValue;\n if (value === null && !conditional) throw new RangeError(`predictResponse: the dimension \"${dimension}\" has no condition, so it needs a value, not null.`);\n return value;\n}\n\n/** This function gives the coordinate of one input of a ridge model. An absent input has `null`, and a level has 0. */\nfunction coordinate(input: RidgeInput, value: ResponseInputValue): number | null {\n if (value === null) return null;\n const bad = (reason: string): RangeError => new RangeError(`predictResponse: the value ${JSON.stringify(value)} of the dimension \"${input.dimension}\" ${reason}.`);\n if (input.kind === \"number\") {\n if (typeof value !== \"number\" || !Number.isFinite(value)) throw bad(\"is not a finite number\");\n if (input.log === true && value <= 0) throw bad(\"is not above 0, and the dimension has a log scale\");\n return ((input.log === true ? Math.log10(value) : value) - input.center) / input.spread;\n }\n const position = input.levels.indexOf(value as string);\n if (position < 0) throw bad(\"is not a level of the model\");\n return input.kind === \"rank\" ? (position - input.center) / input.spread : 0;\n}\n\n/** This function gives the coordinate of each input of a ridge model. */\nexport function coordinates(inputs: readonly RidgeInput[], values: Readonly<Record<string, ResponseInputValue>>): Map<string, number | null> {\n return new Map(inputs.map((input) => [input.dimension, coordinate(input, inputValue(values, input.dimension, input.conditional === true))]));\n}\n\n/**\n * This function gives the product of the factors of a term at a place. A power is a loop of multiplications. A term\n * with an absent dimension is 0, so the columns of the levels of the parent carry the mean of that place.\n */\nexport function product(factors: readonly ResponseFactor[], at: ReadonlyMap<string, number | null>, values: Readonly<Record<string, ResponseInputValue>>): number {\n let value = 1;\n for (const factor of factors) {\n const c = at.get(factor.dimension) as number | null;\n if (c === null) return 0;\n if (\"level\" in factor) {\n if (values[factor.dimension] !== factor.level) return 0;\n } else for (let i = 0; i < factor.power; i++) value *= c;\n }\n return value;\n}\n\n/** This function gives the prediction on the scale of the model. The sum with 0 removes a negative zero. */\nexport function predictScaled(model: ResponseModel, inputs: Readonly<Record<string, ResponseInputValue>>): number {\n if (model.kind === \"table\") {\n const at = model.dimensions.map((d) => inputValue(inputs, d, model.conditional?.includes(d) === true));\n return model.cells.find((cell) => cell.at.every((v, i) => v === at[i]))?.value ?? model.fallback;\n }\n const at = coordinates(model.inputs, inputs);\n let sum = model.intercept;\n for (const term of model.terms) sum += term.weight * product(term.factors, at, inputs);\n return sum + 0;\n}\n\n/** This function changes a measured value to the scale of a model. A log scale with a floor lifts each smaller value. */\nexport function toModelScale(value: number, log: boolean, floor: number | undefined): number {\n return log ? Math.log10(Math.max(value, floor ?? value)) : value;\n}\n\n/** This function changes a value from the scale of the model to the scale of the measure. */\nfunction unscale(model: ResponseModel, value: number): number {\n return model.scale === \"log\" ? 10 ** value : value;\n}\n\n/**\n * This function gives the value of a model at `inputs`, on the scale of the measure. The inputs have a value for each\n * dimension that the model reads. An absent conditional dimension has `null`. A table model gives its `fallback` for a\n * combination with no cell.\n *\n * The function throws a RangeError for a missing input and for a value that is not a number or a level of the model.\n * It throws for `null` at a dimension with no condition, for each kind of model. It also throws for a value at or below\n * 0 on a log scale. A number outside the range of the record is good, so the\n * function extrapolates.\n */\nexport function predictResponse(model: ResponseModel, inputs: Readonly<Record<string, ResponseInputValue>>): number {\n return unscale(model, predictScaled(model, inputs));\n}\n\n/**\n * This function gives the held-out error of a measure over all the folds. Each point has the same weight, so a small\n * fold has a small effect. The function throws a RangeError when no fold has the measure.\n */\nexport function heldOutError(record: Pick<ResponseRecord, \"folds\">, measure: string): ResponseHeldOutError {\n let n = 0;\n let folds = 0;\n let absolute = 0;\n let square = 0;\n let baseline = 0;\n for (const fold of record.folds) {\n if (!Object.hasOwn(fold.errors, measure)) continue;\n const error = fold.errors[measure] as ResponseFoldError;\n n += error.n;\n folds += 1;\n absolute += error.n * error.mae;\n square += error.n * error.rmse * error.rmse;\n baseline += error.n * error.baselineMae;\n }\n if (n === 0) throw new RangeError(`heldOutError: no fold has an error of the measure \"${measure}\".`);\n const mae = absolute / n;\n const baselineMae = baseline / n;\n return { n, folds, mae, rmse: Math.sqrt(square / n), baselineMae, skill: baselineMae > 0 ? 1 - mae / baselineMae : null };\n}\n\n/** This function gives the stored predictions of a measure in a fold. A fold with no predictions gives `undefined`. */\nfunction predictionsOf(fold: ResponseFold, measure: string): Readonly<Record<string, number>> | undefined {\n return fold.predictions !== undefined && Object.hasOwn(fold.predictions, measure) ? fold.predictions[measure] : undefined;\n}\n\n/**\n * This function gives the held-out error of a chosen set of points, on the scale of the model. It uses the stored\n * predictions of the option `outOfFold`. Thus a reader can get the error of one cell. The result has the fields of\n * `heldOutError`, and the set of all the points gives the same values to the rounding of the sums.\n *\n * Each point counts at most once. A point with no value of the measure, or with no prediction, adds nothing to `n`.\n * The baseline of a point is the mean of the training points of its fold.\n *\n * The function throws a RangeError for an unknown measure and for a record with no predictions of the measure. It\n * also throws for an unknown id, for a repeated id, and for a set with no point to score.\n */\nexport function heldOutErrorAt(record: ResponseRecord, measure: string, ids: readonly string[]): ResponseHeldOutError {\n const model = record.models.find((m) => m.measure === measure);\n if (model === undefined) throw new RangeError(`heldOutErrorAt: the record has no model of the measure \"${measure}\".`);\n if (!record.folds.some((fold) => predictionsOf(fold, measure) !== undefined)) throw new RangeError(`heldOutErrorAt: the record has no predictions of the measure \"${measure}\". Fit it with the option outOfFold.`);\n const chosen = new Set(ids);\n if (chosen.size !== ids.length) throw new RangeError(\"heldOutErrorAt: the list of ids has a repeated id.\");\n const points = new Map(record.points.map((p) => [p.id, p]));\n for (const id of ids) if (!points.has(id)) throw new RangeError(`heldOutErrorAt: the record has no point \"${id}\".`);\n const scaled = (point: ResponsePoint): number | undefined => {\n const value = point.measures[measure];\n return typeof value === \"number\" ? toModelScale(value, model.scale === \"log\", model.floor) : undefined;\n };\n let n = 0;\n let folds = 0;\n let absolute = 0;\n let square = 0;\n let baselineSum = 0;\n for (const fold of record.folds) {\n const predicted = predictionsOf(fold, measure);\n if (predicted === undefined) continue;\n const scored = fold.heldOut.filter((id) => chosen.has(id) && Object.hasOwn(predicted, id));\n if (scored.length === 0) continue;\n const held = new Set(fold.heldOut);\n const baseline = mean(record.points.flatMap((p) => (held.has(p.id) || scaled(p) === undefined ? [] : [scaled(p) as number])));\n folds += 1;\n for (const id of scored) {\n const y = scaled(points.get(id) as ResponsePoint) as number;\n const error = y - (predicted[id] as number);\n n += 1;\n absolute += Math.abs(error);\n square += error * error;\n baselineSum += Math.abs(y - baseline);\n }\n }\n if (n === 0) throw new RangeError(`heldOutErrorAt: no chosen point has a prediction of the measure \"${measure}\".`);\n const mae = absolute / n;\n const baselineMae = baselineSum / n;\n return { n, folds, mae, rmse: Math.sqrt(square / n), baselineMae, skill: baselineMae > 0 ? 1 - mae / baselineMae : null };\n}\n\n/** The parts of a slice or a surface that do not depend on the number of varied dimensions. */\ninterface Frame {\n readonly held: Readonly<Record<string, ResponseInputValue>>;\n readonly axes: readonly (readonly ResponseValue[])[];\n readonly matched: readonly ResponsePoint[];\n /** The points that match the held values and have no value of the measure. */\n readonly missing: readonly ResponsePoint[];\n readonly error: ResponseHeldOutError;\n readonly band: (inputs: Readonly<Record<string, ResponseInputValue>>) => ResponseBand;\n}\n\n/**\n * This function gives the usual value of a dimension: a measured median, or the most common level among `among`. A\n * tie gives the first level. A dimension with no measured value gives its low end or its first level.\n */\nfunction usualValue(dimension: ResponseDimension, points: readonly ResponsePoint[], among?: readonly ResponseValue[]): ResponseValue {\n const values = points.flatMap((p) => (p.values[dimension.id] === null ? [] : [p.values[dimension.id] as ResponseValue]));\n if (dimension.kind === \"continuous\") return values.length === 0 ? dimension.range[0] : quantile(values as number[], 0.5, \"nearest-rank\");\n const levels = (dimension.levels as readonly ResponseValue[]).filter((level) => among === undefined || among.includes(level));\n let best = levels[0] as ResponseValue;\n let most = 0;\n for (const level of levels) {\n const count = values.filter((v) => v === level).length;\n if (count > most) [best, most] = [level, count];\n }\n return best;\n}\n\n/** The place of a value on the axis of its dimension: a share of the axis, a categorical level, or `null`. */\ntype AxisPlace = number | string | null;\n\n/** This function gives the place of a value on its axis. A number or a rank is a share of the axis, from 0 to 1. */\nfunction axisPlace(dimension: ResponseDimension, value: ResponseInputValue): AxisPlace {\n if (value === null || dimension.kind === \"categorical\") return value;\n const [low, high] = axisEnds(dimension);\n if (high === low) return 0;\n if (!isNumberDimension(dimension)) return (dimension.levels as readonly ResponseValue[]).indexOf(value) / high;\n return ((dimension.log === true ? Math.log10(value as number) : (value as number)) - low) / (high - low);\n}\n\n/** This function gives the count of one dimension between two places: their distance, or 1 when they do not compare. */\nconst axisGap = (a: AxisPlace, b: AxisPlace): number => (a === b ? 0 : typeof a === \"number\" && typeof b === \"number\" ? Math.abs(a - b) : 1);\n\n/**\n * This function gives a function of the field `nearest` of a band. A place compares with each point that has a value\n * of the measure. A point stops at the first count that is not less than the best distance so far.\n */\nfunction nearestOf(dimensions: readonly ResponseDimension[], points: readonly ResponsePoint[], measure: string): (place: Readonly<Record<string, ResponseInputValue>>) => number {\n const rows = points.filter((p) => typeof p.measures[measure] === \"number\").map((p) => dimensions.map((d) => axisPlace(d, p.values[d.id] as ResponseInputValue)));\n return (place) => {\n const here = dimensions.map((d) => axisPlace(d, place[d.id] as ResponseInputValue));\n let best = 1;\n for (const row of rows) {\n let far = 0;\n for (let i = 0; i < here.length && far < best; i++) far = Math.max(far, axisGap(row[i] as AxisPlace, here[i] as AxisPlace));\n if (far < best) best = far;\n }\n return best;\n };\n}\n\n/** This function gives the levels that the parent of each varied conditional dimension needs. */\nfunction neededLevels(name: string, varied: readonly ResponseDimension[], vary: readonly string[]): ReadonlyMap<string, readonly ResponseValue[]> {\n const needed = new Map<string, readonly ResponseValue[]>();\n for (const { id, when } of varied) {\n if (when === undefined) continue;\n if (vary.includes(when.dimension)) throw new RangeError(`${name}: the dimension \"${id}\" has a value only at some levels of \"${when.dimension}\", so hold \"${when.dimension}\".`);\n const earlier = needed.get(when.dimension);\n needed.set(when.dimension, earlier === undefined ? when.levels : earlier.filter((level) => when.levels.includes(level)));\n }\n return needed;\n}\n\n/** This function gives the value of each dimension that does not vary. `sliceResponse` tells the rules. */\nfunction heldValues(name: string, record: ResponseRecord, vary: readonly string[], hold: Readonly<Record<string, ResponseInputValue>>, needed: ReadonlyMap<string, readonly ResponseValue[]>): Readonly<Record<string, ResponseInputValue>> {\n const others = record.dimensions.filter((d) => !vary.includes(d.id));\n const plain = new Map(others.filter((d) => d.when === undefined).map((d) => [d.id, (Object.hasOwn(hold, d.id) ? hold[d.id] : usualValue(d, record.points, needed.get(d.id))) as ResponseValue]));\n for (const [parent, levels] of needed) {\n const value = plain.get(parent) as ResponseValue;\n if (!levels.includes(value)) throw new RangeError(`${name}: a varied dimension needs \"${parent}\" at one of ${JSON.stringify(levels)}, not ${JSON.stringify(value)}.`);\n }\n const valueOf = ({ id, when }: ResponseDimension): ResponseInputValue => {\n if (when === undefined) return plain.get(id) as ResponseValue;\n if (!vary.includes(when.dimension) && !when.levels.includes(plain.get(when.dimension) as ResponseValue)) return null;\n const value = Object.hasOwn(hold, id) ? (hold[id] as ResponseInputValue) : usualValue(record.dimensions.find((d) => d.id === id) as ResponseDimension, record.points);\n if (value === null) throw new RangeError(`${name}: the held dimension \"${id}\" is null, and a level of \"${when.dimension}\" in this view needs a value.`);\n return value;\n };\n return Object.fromEntries(others.map((d) => [d.id, valueOf(d)]));\n}\n\n/** This function refuses a bad option `steps`. */\nfunction checkSteps(name: string, steps: number): void {\n if (!Number.isSafeInteger(steps) || steps < 2) throw new RangeError(`${name}: steps is a whole number of 2 or more, not ${steps}.`);\n}\n\n/** This function gives a value inside a range. */\nconst clip = (value: number, [low, high]: readonly [number, number]): number => Math.min(high, Math.max(low, value));\n\n/** This function gives the values of an axis: each level, or `steps` equal distances on the scale of the dimension. */\nfunction axisValues(dimension: ResponseDimension, steps: number): readonly ResponseValue[] {\n if (dimension.kind !== \"continuous\") return dimension.levels;\n const [low, high] = dimension.range;\n const [a, b] = axisEnds(dimension);\n return Array.from({ length: steps }, (_, i) => {\n if (i === 0) return low;\n if (i === steps - 1) return high;\n const x = a + ((b - a) * i) / (steps - 1);\n return dimension.log === true ? 10 ** x : x;\n });\n}\n\n/** This function gives true when the value of a point matches a held value of a dimension. */\nfunction matches(dimension: ResponseDimension, value: ResponseInputValue, held: ResponseInputValue, tolerance: number): boolean {\n if (typeof value !== \"number\" || typeof held !== \"number\") return value === held;\n const [low, high] = axisEnds(dimension);\n const log = dimension.kind !== \"categorical\" && dimension.log === true;\n return Math.abs(log ? Math.log10(value) - Math.log10(held) : value - held) <= tolerance * (high - low);\n}\n\n/** This function examines the request of a view, and it gives the parts that the two views share. */\nfunction frameOf(name: string, record: ResponseRecord, measure: string, vary: readonly string[], options: ResponseViewOptions): Frame {\n const { hold = {}, steps = 33, tolerance = 0, width = 1 } = options;\n checkSteps(name, steps);\n if (!(Number.isFinite(tolerance) && tolerance >= 0)) throw new RangeError(`${name}: tolerance is a finite number of 0 or more, not ${tolerance}.`);\n if (!(Number.isFinite(width) && width >= 0)) throw new RangeError(`${name}: width is a finite number of 0 or more, not ${width}.`);\n const model = record.models.find((m) => m.measure === measure);\n if (model === undefined) throw new RangeError(`${name}: the record has no model of the measure \"${measure}\".`);\n const known = (id: string): ResponseDimension => {\n const dimension = record.dimensions.find((d) => d.id === id);\n if (dimension === undefined) throw new RangeError(`${name}: the record has no dimension \"${id}\".`);\n return dimension;\n };\n const varied = vary.map(known);\n if (new Set(vary).size !== vary.length) throw new RangeError(`${name}: the two varied dimensions are one dimension, \"${vary[0]}\".`);\n for (const id of Object.keys(hold)) {\n if (vary.includes(id)) throw new RangeError(`${name}: the dimension \"${id}\" is both varied and held.`);\n const dimension = known(id);\n if (hold[id] === null && dimension.when !== undefined) continue;\n const fault = valueFault(dimension, hold[id]);\n if (fault !== undefined) throw new RangeError(`${name}: the held dimension \"${id}\": ${fault}.`);\n }\n const others = record.dimensions.filter((d) => !vary.includes(d.id));\n const held = heldValues(name, record, vary, hold, neededLevels(name, varied, vary));\n const placed = record.points.filter(\n (p) => vary.every((id) => p.values[id] !== null) && others.every((d) => matches(d, p.values[d.id] as ResponseInputValue, whenHolds(d, p.values) ? (held[d.id] as ResponseInputValue) : null, tolerance)),\n );\n const matched = placed.filter((p) => typeof p.measures[measure] === \"number\");\n const missing = placed.filter((p) => typeof p.measures[measure] !== \"number\");\n const error = heldOutError(record, measure);\n const nearest = nearestOf(record.dimensions, record.points, measure);\n const range = record.measures.find((m) => m.id === measure)?.range;\n const band = (inputs: Readonly<Record<string, ResponseInputValue>>): ResponseBand => {\n const place = Object.fromEntries(record.dimensions.map((d) => [d.id, whenHolds(d, inputs) ? (inputs[d.id] as ResponseInputValue) : null]));\n const value = predictScaled(model, place);\n const fitted = { value: unscale(model, value), low: unscale(model, value - width * error.rmse), high: unscale(model, value + width * error.rmse) };\n const inside = range === undefined ? fitted : { value: clip(fitted.value, range), low: clip(fitted.low, range), high: clip(fitted.high, range) };\n const moved = inside.value !== fitted.value || inside.low !== fitted.low || inside.high !== fitted.high;\n return { ...inside, nearest: nearest(place), ...(moved ? { clipped: true as const } : {}) };\n };\n return { held, axes: varied.map((d) => axisValues(d, steps)), matched, missing, error, band };\n}\n\n/** This function gives the group field of a measured point of a view. */\nconst groupOf = (point: ResponsePoint): { readonly group?: string } => (point.group === undefined ? {} : { group: point.group });\n\n/** This function gives the declared reason of a point with no value of a measure, or `null` for no stated reason. */\nconst reasonOf = (point: ResponsePoint, measure: string): string | null => (point.absent !== undefined && Object.hasOwn(point.absent, measure) ? (point.absent[measure] as string) : null);\n\n/**\n * This function gives a view of a measure over one dimension of a parsed record:\n * - `curve`: the fitted value at each level, or at `steps` values of a continuous dimension, with its band.\n * - `points`: the measured points that match the held values. This list is empty when no point matches them.\n * - `absent`: the points that match the held values and have no value of the measure, each with its reason. A chart\n * can draw each reason apart.\n * - `held`: the value of each other dimension.\n * - `error`: the held-out error.\n *\n * Each dimension with no value in `hold` takes its usual value. For a continuous dimension, this value is the median\n * of its measured values. For the other kinds, it is the most common level, and a tie gives the first level.\n *\n * A conditional dimension follows its parent:\n * - To vary a conditional dimension, the parent needs a level inside `when`. With no held value, the parent takes the\n * most common level inside `when`. A held level outside `when` is a RangeError.\n * - A held conditional dimension reads `null` in `held` when its parent is outside `when`, also with a value in `hold`.\n * The points that match have `null` at this dimension.\n * - When the parent varies, a held conditional dimension keeps its value in `held`. Each place outside `when` reads\n * `null` for the fit, and for the matching points.\n *\n * The band is the fitted value, plus and less `width` times the held-out root mean square error. On a log scale, this\n * distance is on the log scale of the model, so the band is a ratio. The band has one width along all the curve. The\n * band is the mean error of the model, and `nearest` tells how far the place is from a measurement.\n *\n * A measure with a `range` keeps each place inside it. The fields `value`, `low` and `high` move to the nearest end.\n * The place then has the field `clipped`, and the field `clipped` of the view counts these places. The function\n * `predictResponse` gives the value that the model fitted.\n *\n * The function throws a RangeError for an unknown measure or dimension, and for a held value that is not good for its\n * dimension. It also throws for a dimension that is both varied and held, and for a bad option.\n */\nexport function sliceResponse(record: ResponseRecord, measure: string, options: ResponseSliceOptions): ResponseSlice {\n const { vary } = options;\n const { held, axes, matched, missing, error, band } = frameOf(\"sliceResponse\", record, measure, [vary], options);\n const curve = (axes[0] as readonly ResponseValue[]).map((at) => ({ at, ...band({ ...held, [vary]: at }) }));\n return {\n measure,\n vary,\n held,\n curve,\n points: matched.map((p) => ({ id: p.id, at: p.values[vary] as ResponseValue, value: p.measures[measure] as number, ...groupOf(p) })),\n absent: missing.map((p) => ({ id: p.id, at: p.values[vary] as ResponseValue, reason: reasonOf(p, measure), ...groupOf(p) })),\n error,\n clipped: curve.filter((place) => place.clipped === true).length,\n };\n}\n\n/**\n * This function gives the view of `sliceResponse` over two dimensions. The fields `x` and `y` are the two axes, and\n * `cells` has one row for each value of `y`. The rules of the held values, of the matching points and of the band are\n * the rules of `sliceResponse`. The function also throws a RangeError when the two varied dimensions are one dimension.\n * It throws when a conditional dimension varies with its parent, and when two varied dimensions need no common level.\n */\nexport function surfaceResponse(record: ResponseRecord, measure: string, options: ResponseSurfaceOptions): ResponseSurface {\n const { vary } = options;\n const [xId, yId] = vary;\n const { held, axes, matched, missing, error, band } = frameOf(\"surfaceResponse\", record, measure, vary, options);\n const x = axes[0] as readonly ResponseValue[];\n const y = axes[1] as readonly ResponseValue[];\n const cells = y.map((b) => x.map((a) => band({ ...held, [xId]: a, [yId]: b })));\n return {\n measure,\n vary,\n held,\n x,\n y,\n cells,\n points: matched.map((p) => ({ id: p.id, at: [p.values[xId] as ResponseValue, p.values[yId] as ResponseValue], value: p.measures[measure] as number, ...groupOf(p) })),\n absent: missing.map((p) => ({ id: p.id, at: [p.values[xId] as ResponseValue, p.values[yId] as ResponseValue], reason: reasonOf(p, measure), ...groupOf(p) })),\n error,\n clipped: cells.flat().filter((place) => place.clipped === true).length,\n };\n}\n\n/**\n * This function gives the number of fitted places of a view before the view starts: the product of the lengths of its\n * axes. A level axis counts its levels, and a continuous axis counts `steps`. The field `nearest` reads each point at\n * each place, so the reads of a view are this count times the number of points. The default of `steps` is the default\n * of a view. The function throws a RangeError for an unknown dimension, for one dimension named two times, and for a\n * bad `steps`.\n */\nexport function responseCells(record: Pick<ResponseRecord, \"dimensions\">, vary: string | readonly [string, string], steps = 33): number {\n checkSteps(\"responseCells\", steps);\n const ids: readonly string[] = typeof vary === \"string\" ? [vary] : vary;\n if (new Set(ids).size !== ids.length) throw new RangeError(`responseCells: the two varied dimensions are one dimension, \"${ids[0]}\".`);\n return ids.reduce((count, id) => {\n const dimension = record.dimensions.find((d) => d.id === id);\n if (dimension === undefined) throw new RangeError(`responseCells: the record has no dimension \"${id}\".`);\n return count * (dimension.kind === \"continuous\" ? steps : dimension.levels.length);\n }, 1);\n}\n","/**\n * The validator of the format `response-records/1`. The functions here read unknown data and write faults. Thus a page\n * can show the reason that a file is bad.\n */\nimport { RESPONSE_RECORDS_SCHEMA, type ResponseData, type ResponseDimension, type ResponseMeasure, type ResponsePoint, type ResponseRecord, type RidgeInput, groupKey, isNumberDimension, valueFault, whenHolds } from \"./response.ts\";\n\n/** The largest power of a factor. A larger power of a coordinate from -1 to 1 adds almost nothing to a model. */\nexport const RESPONSE_MAX_POWER = 8;\n\n/** One fault of a record. */\nexport interface ResponseFault {\n /** The place of the fault, for example `points[3].values.size`. An empty string is the record itself. */\n readonly path: string;\n /** What is wrong, and what the format needs. */\n readonly message: string;\n}\n\n/** The result of `parseResponseRecord`: the record, or each fault that the validator found. */\nexport type ParsedResponseRecord = { readonly ok: true; readonly record: ResponseRecord } | { readonly ok: false; readonly faults: readonly ResponseFault[] };\n\ntype Fields = Readonly<Record<string, unknown>>;\n\n/** The list that the checks write to. */\ntype Faults = ResponseFault[];\n\n/** This function gives an unknown value as short text for a message. */\nfunction shown(value: unknown): string {\n if (value === undefined) return \"nothing\";\n const text = JSON.stringify(value) ?? String(value);\n return text.length > 60 ? `${text.slice(0, 60)}...` : text;\n}\n\n/** This function gives a path with one more key. */\nconst at = (path: string, key: string): string => (path === \"\" ? key : `${path}.${key}`);\n\nconst isNumber = (v: unknown): v is number => typeof v === \"number\" && Number.isFinite(v);\n\n/** This function gives the field `key` of an unknown value, or `undefined` for a value that is not an object. */\nconst peek = (value: unknown, key: string): unknown => (typeof value === \"object\" && value !== null ? (value as Fields)[key] : undefined);\n\n/** This function writes a fault when a test fails. */\nfunction need(ok: boolean, path: string, message: string, faults: Faults): void {\n if (!ok) faults.push({ path, message });\n}\n\n/** This function gives the fields of a plain object. It writes a fault for another value, and for each wrong key. */\nfunction fields(value: unknown, path: string, keys: readonly string[], optional: readonly string[], faults: Faults): Fields | undefined {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n faults.push({ path, message: `this is an object, not ${shown(value)}.` });\n return undefined;\n }\n const object = value as Fields;\n for (const key of keys) need(Object.hasOwn(object, key), at(path, key), \"this field is missing.\", faults);\n for (const key of Object.keys(object)) need(keys.includes(key) || optional.includes(key), at(path, key), `${RESPONSE_RECORDS_SCHEMA} has no such field.`, faults);\n return object;\n}\n\n/** This function gives the items of a list. It writes a fault for another value, and for a short list. */\nfunction list(value: unknown, path: string, least: number, faults: Faults): readonly unknown[] {\n if (!Array.isArray(value)) {\n faults.push({ path, message: `this is a list, not ${shown(value)}.` });\n return [];\n }\n need(value.length >= least, path, `this list has ${value.length} items, and it needs ${least} or more.`, faults);\n return value as readonly unknown[];\n}\n\n/** This function examines a field when it is present. A missing field already has a fault, or it is optional. */\nfunction check(object: Fields, key: string, path: string, test: (value: unknown) => boolean, wanted: string, faults: Faults): void {\n if (Object.hasOwn(object, key)) need(test(object[key]), at(path, key), `this is ${wanted}, not ${shown(object[key])}.`, faults);\n}\n\nconst isId = (v: unknown): boolean => typeof v === \"string\" && v !== \"\";\nconst isString = (v: unknown): boolean => typeof v === \"string\";\nconst isPositive = (v: unknown): boolean => isNumber(v) && v > 0;\nconst isNotNegative = (v: unknown): boolean => isNumber(v) && v >= 0;\n\n/** This function writes a fault for each id that is a duplicate, and it gives the set of the ids. */\nfunction uniqueIds(items: readonly unknown[], path: string, faults: Faults): Set<string> {\n const ids = new Set<string>();\n items.forEach((item, i) => {\n const id = peek(item, \"id\");\n if (typeof id !== \"string\") return;\n need(!ids.has(id), `${path}[${i}].id`, `an earlier item has the id ${shown(id)}.`, faults);\n ids.add(id);\n });\n return ids;\n}\n\n/** This function examines the levels of a categorical or ordinal dimension. */\nfunction checkLevels(value: unknown, path: string, numbersToo: boolean, log: boolean, faults: Faults): void {\n const levels = list(value, path, 1, faults);\n const numbers = numbersToo && levels.every(isNumber);\n need(numbers || levels.every(isString), path, numbersToo ? \"these levels are all text or all finite numbers.\" : \"these levels are all text.\", faults);\n need(new Set(levels).size === levels.length, path, \"these levels have a duplicate.\", faults);\n if (numbers) need(levels.every((v, i) => i === 0 || (levels[i - 1] as number) < (v as number)), path, \"these number levels are not in ascending order.\", faults);\n if (log) need(levels.every(isPositive), path, \"a log dimension has number levels above 0.\", faults);\n}\n\n/** This function examines one dimension. */\nfunction checkDimension(value: unknown, path: string, faults: Faults): void {\n const kind = peek(value, \"kind\");\n const object = fields(value, path, [\"id\", \"label\", \"kind\", \"unit\"], [\"range\", \"levels\", \"log\", \"when\"], faults);\n if (object === undefined) return;\n check(object, \"id\", path, isId, \"text with one character or more\", faults);\n check(object, \"label\", path, isString, \"text\", faults);\n check(object, \"unit\", path, isString, \"text\", faults);\n check(object, \"log\", path, (v) => typeof v === \"boolean\", \"true or false\", faults);\n const log = object[\"log\"] === true;\n if (kind === \"continuous\") {\n need(!Object.hasOwn(object, \"levels\"), at(path, \"levels\"), \"a continuous dimension has a range, not levels.\", faults);\n need(!Object.hasOwn(object, \"range\") || !log || !isNumber(peek(object[\"range\"], \"0\")) || (peek(object[\"range\"], \"0\") as number) > 0, at(path, \"range\"), \"a log dimension has a range above 0.\", faults);\n need(Object.hasOwn(object, \"range\"), at(path, \"range\"), \"this field is missing.\", faults);\n if (Object.hasOwn(object, \"range\")) checkRange(object[\"range\"], at(path, \"range\"), faults);\n } else if (kind === \"ordinal\" || kind === \"categorical\") {\n need(!Object.hasOwn(object, \"range\"), at(path, \"range\"), `a dimension of the kind ${kind} has levels, not a range.`, faults);\n need(kind === \"ordinal\" || !Object.hasOwn(object, \"log\"), at(path, \"log\"), \"a categorical dimension has no log scale.\", faults);\n need(Object.hasOwn(object, \"levels\"), at(path, \"levels\"), \"this field is missing.\", faults);\n if (Object.hasOwn(object, \"levels\")) checkLevels(object[\"levels\"], at(path, \"levels\"), kind === \"ordinal\", log, faults);\n } else if (Object.hasOwn(object, \"kind\")) faults.push({ path: at(path, \"kind\"), message: `this is \"continuous\", \"ordinal\" or \"categorical\", not ${shown(kind)}.` });\n}\n\n/** This function examines the condition of one dimension against all the dimensions. */\nfunction checkWhen(value: unknown, path: string, dimensions: readonly unknown[], faults: Faults): void {\n const object = fields(value, path, [\"dimension\", \"levels\"], [], faults);\n if (object === undefined) return;\n const levels = Object.hasOwn(object, \"levels\") ? list(object[\"levels\"], at(path, \"levels\"), 1, faults) : [];\n need(new Set(levels).size === levels.length, at(path, \"levels\"), \"these levels have a duplicate.\", faults);\n if (!Object.hasOwn(object, \"dimension\")) return;\n const id = object[\"dimension\"];\n const parent = dimensions.find((d) => peek(d, \"id\") === id);\n if (parent === undefined) {\n faults.push({ path: at(path, \"dimension\"), message: `the record has no dimension ${shown(id)}.` });\n return;\n }\n const kind = peek(parent, \"kind\");\n need(kind === \"categorical\" || kind === \"ordinal\", at(path, \"dimension\"), `the parent ${shown(id)} is ${shown(kind)}, and a parent is categorical or ordinal.`, faults);\n need(peek(parent, \"when\") === undefined, at(path, \"dimension\"), `the parent ${shown(id)} is itself conditional.`, faults);\n const known = peek(parent, \"levels\");\n if (!Array.isArray(known)) return;\n levels.forEach((level, i) => need(known.includes(level), `${at(path, \"levels\")}[${i}]`, `the dimension ${shown(id)} has no level ${shown(level)}.`, faults));\n}\n\n/** This function examines a range. */\nfunction checkRange(range: unknown, path: string, faults: Faults): void {\n const good = Array.isArray(range) && range.length === 2 && isNumber(range[0]) && isNumber(range[1]) && range[0] < range[1];\n need(good, path, `this is a low and a high finite number, with low less than high, not ${shown(range)}.`, faults);\n}\n\n/** This function examines one measure. */\nfunction checkMeasure(value: unknown, path: string, faults: Faults): void {\n const object = fields(value, path, [\"id\", \"label\", \"unit\", \"direction\"], [\"range\"], faults);\n if (object === undefined) return;\n check(object, \"id\", path, isId, \"text with one character or more\", faults);\n check(object, \"label\", path, isString, \"text\", faults);\n check(object, \"unit\", path, isString, \"text\", faults);\n check(object, \"direction\", path, (v) => v === \"higher\" || v === \"lower\" || v === \"none\", `\"higher\", \"lower\" or \"none\"`, faults);\n if (Object.hasOwn(object, \"range\")) checkRange(object[\"range\"], at(path, \"range\"), faults);\n}\n\n/** This function refuses a measured value outside the range of its measure. */\nfunction checkMeasured(point: unknown, path: string, measures: readonly ResponseMeasure[], faults: Faults): void {\n for (const { id, range } of measures) {\n const value = peek(peek(point, \"measures\"), id);\n if (range === undefined || typeof value !== \"number\") continue;\n need(value >= range[0] && value <= range[1], at(at(path, \"measures\"), id), `this value is outside the range of the measure, [${range[0]}, ${range[1]}].`, faults);\n }\n}\n\n/** This function examines one declared reason. */\nfunction checkReason(value: unknown, path: string, faults: Faults): void {\n const object = fields(value, path, [\"id\", \"label\"], [], faults);\n if (object === undefined) return;\n check(object, \"id\", path, isId, \"text with one character or more\", faults);\n check(object, \"label\", path, isString, \"text\", faults);\n}\n\n/** This function examines the reasons of a point: each has a declaration, and each is on a measure with no number. */\nfunction checkAbsent(value: unknown, path: string, measuresOfPoint: unknown, measures: ReadonlySet<string>, reasons: ReadonlySet<string>, faults: Faults): void {\n const absent = fields(value, path, [], [...measures], faults);\n if (absent === undefined) return;\n for (const measure of measures) {\n if (!Object.hasOwn(absent, measure)) continue;\n need(reasons.has(absent[measure] as string), at(path, measure), `the record declares no reason ${shown(absent[measure])}.`, faults);\n need(typeof peek(measuresOfPoint, measure) !== \"number\", at(path, measure), \"this measure has a number, so it has no reason.\", faults);\n }\n}\n\n/** This function examines one point, with the dimensions, the measures and the reasons of the record. */\nfunction checkPoint(value: unknown, path: string, dimensions: readonly ResponseDimension[], measures: ReadonlySet<string>, reasons: ReadonlySet<string>, faults: Faults): void {\n const object = fields(value, path, [\"id\", \"values\", \"measures\"], [\"group\", \"absent\"], faults);\n if (object === undefined) return;\n check(object, \"id\", path, isId, \"text with one character or more\", faults);\n check(object, \"group\", path, isId, \"text with one character or more\", faults);\n if (Object.hasOwn(object, \"values\")) {\n const inside = at(path, \"values\");\n const ids = dimensions.map((d) => d.id);\n const values = fields(object[\"values\"], inside, ids, [], faults);\n for (const dimension of dimensions) {\n if (values === undefined || !Object.hasOwn(values, dimension.id)) continue;\n const value = values[dimension.id];\n const present = whenHolds(dimension, values);\n const parent = dimension.when?.dimension as string;\n if (value === null && dimension.when !== undefined) {\n need(!present, at(inside, dimension.id), `this needs a value when the dimension \"${parent}\" is ${shown(values[parent])}.`, faults);\n continue;\n }\n const fault = valueFault(dimension, value);\n if (fault !== undefined) faults.push({ path: at(inside, dimension.id), message: `${fault}.` });\n else need(present, at(inside, dimension.id), `this is null when the dimension \"${parent}\" is ${shown(values[parent])}.`, faults);\n }\n }\n if (Object.hasOwn(object, \"absent\")) checkAbsent(object[\"absent\"], at(path, \"absent\"), object[\"measures\"], measures, reasons, faults);\n if (Object.hasOwn(object, \"measures\")) {\n const inside = at(path, \"measures\");\n const values = fields(object[\"measures\"], inside, [...measures], [], faults);\n if (values === undefined) return;\n for (const measure of measures) check(values, measure, inside, (v) => v === null || isNumber(v), \"a finite number or null\", faults);\n }\n}\n\n/**\n * This function examines the data of a record: all but its models and its folds. It gives each fault that it finds.\n * It examines the points only when the dimensions and the measures have no fault, because the points refer to them.\n * `required` and `optional` name the other top-level fields.\n */\nexport function responseDataFaults(value: unknown, required: readonly string[], optional: readonly string[]): readonly ResponseFault[] {\n const faults: Faults = [];\n const object = fields(value, \"\", [\"schema\", \"name\", \"dimensions\", \"measures\", \"points\", ...required], [\"reasons\", ...optional], faults);\n if (object === undefined) return faults;\n check(object, \"schema\", \"\", (v) => v === RESPONSE_RECORDS_SCHEMA, `\"${RESPONSE_RECORDS_SCHEMA}\"`, faults);\n check(object, \"name\", \"\", isId, \"text with one character or more\", faults);\n const dimensions = Object.hasOwn(object, \"dimensions\") ? list(object[\"dimensions\"], \"dimensions\", 1, faults) : [];\n dimensions.forEach((d, i) => checkDimension(d, `dimensions[${i}]`, faults));\n uniqueIds(dimensions, \"dimensions\", faults);\n dimensions.forEach((d, i) => {\n if (peek(d, \"when\") !== undefined) checkWhen(peek(d, \"when\"), `dimensions[${i}].when`, dimensions, faults);\n });\n const measures = Object.hasOwn(object, \"measures\") ? list(object[\"measures\"], \"measures\", 1, faults) : [];\n measures.forEach((m, i) => checkMeasure(m, `measures[${i}]`, faults));\n const measureIds = uniqueIds(measures, \"measures\", faults);\n const reasons = Object.hasOwn(object, \"reasons\") ? list(object[\"reasons\"], \"reasons\", 0, faults) : [];\n reasons.forEach((r, i) => checkReason(r, `reasons[${i}]`, faults));\n const reasonIds = uniqueIds(reasons, \"reasons\", faults);\n if (faults.length > 0) return faults;\n const points = list(object[\"points\"], \"points\", 1, faults);\n points.forEach((p, i) => checkPoint(p, `points[${i}]`, dimensions as readonly ResponseDimension[], measureIds, reasonIds, faults));\n uniqueIds(points, \"points\", faults);\n if (faults.length > 0) return faults;\n points.forEach((p, i) => checkMeasured(p, `points[${i}]`, measures as readonly ResponseMeasure[], faults));\n return faults;\n}\n\n/** This function examines one input of a ridge model against the dimensions of the record. */\nfunction checkInput(value: unknown, path: string, dimensions: ReadonlyMap<string, ResponseDimension>, faults: Faults): void {\n const kind = peek(value, \"kind\");\n if (kind !== \"number\" && kind !== \"rank\" && kind !== \"level\") {\n faults.push({ path: at(path, \"kind\"), message: `this is \"number\", \"rank\" or \"level\", not ${shown(kind)}.` });\n return;\n }\n const keys = { number: [\"center\", \"spread\"], rank: [\"levels\", \"center\", \"spread\"], level: [\"levels\"] }[kind];\n const object = fields(value, path, [\"kind\", \"dimension\", ...keys], kind === \"number\" ? [\"log\", \"conditional\"] : [\"conditional\"], faults);\n if (object === undefined) return;\n check(object, \"center\", path, isNumber, \"a finite number\", faults);\n check(object, \"spread\", path, isPositive, \"a finite number above 0\", faults);\n check(object, \"log\", path, (v) => typeof v === \"boolean\", \"true or false\", faults);\n check(object, \"conditional\", path, (v) => typeof v === \"boolean\", \"true or false\", faults);\n const dimension = dimensions.get(object[\"dimension\"] as string);\n if (dimension === undefined) {\n faults.push({ path: at(path, \"dimension\"), message: `the record has no dimension ${shown(object[\"dimension\"])}.` });\n return;\n }\n const want = isNumberDimension(dimension) ? \"number\" : dimension.kind === \"categorical\" ? \"level\" : \"rank\";\n need(kind === want, at(path, \"kind\"), `the dimension \"${dimension.id}\" needs an input of the kind \"${want}\".`, faults);\n need((object[\"conditional\"] ?? false) === (dimension.when !== undefined), at(path, \"conditional\"), `this does not agree with the condition of the dimension \"${dimension.id}\".`, faults);\n if (kind === \"number\" && dimension.kind !== \"categorical\") {\n need((object[\"log\"] ?? false) === (dimension.log ?? false), at(path, \"log\"), `this does not agree with the log scale of the dimension \"${dimension.id}\".`, faults);\n }\n if (kind !== \"number\" && dimension.kind !== \"continuous\") {\n need(JSON.stringify(object[\"levels\"]) === JSON.stringify(dimension.levels), at(path, \"levels\"), `these are not the levels of the dimension \"${dimension.id}\".`, faults);\n }\n}\n\n/** This function examines the factors of one term against the inputs of a model. `fitResponse` also uses it. */\nexport function factorFaults(value: unknown, path: string, inputs: ReadonlyMap<string, RidgeInput>, dimensions: ReadonlyMap<string, ResponseDimension>): readonly ResponseFault[] {\n const faults: Faults = [];\n list(value, path, 1, faults).forEach((item, i) => {\n const inside = `${path}[${i}]`;\n const isLevel = peek(item, \"level\") !== undefined;\n const factor = fields(item, inside, [\"dimension\", isLevel ? \"level\" : \"power\"], [], faults);\n if (factor === undefined) return;\n const input = inputs.get(factor[\"dimension\"] as string);\n if (input === undefined) {\n faults.push({ path: at(inside, \"dimension\"), message: `the model has no input ${shown(factor[\"dimension\"])}.` });\n } else if (isLevel) {\n const dimension = dimensions.get(input.dimension);\n const levels: readonly unknown[] = dimension === undefined || dimension.kind === \"continuous\" ? [] : dimension.levels;\n need(levels.includes(factor[\"level\"]), at(inside, \"level\"), `the input \"${input.dimension}\" has no level ${shown(factor[\"level\"])}.`, faults);\n } else {\n need(input.kind !== \"level\", inside, `the categorical input \"${input.dimension}\" takes a level, not a power.`, faults);\n const good = (v: unknown): boolean => Number.isSafeInteger(v) && (v as number) >= 1 && (v as number) <= RESPONSE_MAX_POWER;\n check(factor, \"power\", inside, good, `a whole number from 1 to ${RESPONSE_MAX_POWER}`, faults);\n }\n });\n return faults;\n}\n\n/** This function examines the fields of a ridge model after its common fields. */\nfunction checkRidge(object: Fields, path: string, dimensions: ReadonlyMap<string, ResponseDimension>, faults: Faults): void {\n check(object, \"lambda\", path, isNotNegative, \"a finite number of 0 or more\", faults);\n check(object, \"intercept\", path, isNumber, \"a finite number\", faults);\n const inputs = Object.hasOwn(object, \"inputs\") ? list(object[\"inputs\"], at(path, \"inputs\"), 0, faults) : [];\n const known = new Map<string, RidgeInput>();\n inputs.forEach((input, i) => {\n const inside = `${at(path, \"inputs\")}[${i}]`;\n checkInput(input, inside, dimensions, faults);\n const dimension = peek(input, \"dimension\");\n if (typeof dimension !== \"string\") return;\n need(!known.has(dimension), at(inside, \"dimension\"), `an earlier input has the dimension \"${dimension}\".`, faults);\n known.set(dimension, input as RidgeInput);\n });\n const terms = Object.hasOwn(object, \"terms\") ? list(object[\"terms\"], at(path, \"terms\"), 0, faults) : [];\n terms.forEach((term, i) => {\n const inside = `${at(path, \"terms\")}[${i}]`;\n const fieldsOfTerm = fields(term, inside, [\"factors\", \"weight\"], [], faults);\n if (fieldsOfTerm === undefined) return;\n check(fieldsOfTerm, \"weight\", inside, isNumber, \"a finite number\", faults);\n if (Object.hasOwn(fieldsOfTerm, \"factors\")) faults.push(...factorFaults(fieldsOfTerm[\"factors\"], at(inside, \"factors\"), known, dimensions));\n });\n}\n\n/** This function examines the dimensions of a table model, and it gives the good ones. */\nfunction tableDimensions(object: Fields, path: string, dimensions: ReadonlyMap<string, ResponseDimension>, faults: Faults): readonly ResponseDimension[] {\n const table: ResponseDimension[] = [];\n const ids = Object.hasOwn(object, \"dimensions\") ? list(object[\"dimensions\"], at(path, \"dimensions\"), 1, faults) : [];\n ids.forEach((id, i) => {\n const dimension = dimensions.get(id as string);\n const inside = `${at(path, \"dimensions\")}[${i}]`;\n if (dimension === undefined) faults.push({ path: inside, message: `the record has no dimension ${shown(id)}.` });\n else if (dimension.kind === \"continuous\") faults.push({ path: inside, message: `a table cannot read the continuous dimension \"${dimension.id}\".` });\n else {\n need(!table.includes(dimension), inside, `an earlier item is the dimension \"${dimension.id}\".`, faults);\n table.push(dimension);\n }\n });\n return table;\n}\n\n/** This function examines the fields of a table model after its common fields. */\nfunction checkTable(object: Fields, path: string, dimensions: ReadonlyMap<string, ResponseDimension>, faults: Faults): void {\n check(object, \"fallback\", path, isNumber, \"a finite number\", faults);\n const table = tableDimensions(object, path, dimensions, faults);\n const conditional = table.filter((d) => d.when !== undefined).map((d) => d.id);\n need(JSON.stringify(object[\"conditional\"] ?? []) === JSON.stringify(conditional), at(path, \"conditional\"), `this does not agree with the conditions of the dimensions of the table: ${shown(conditional)}.`, faults);\n const cells = Object.hasOwn(object, \"cells\") ? list(object[\"cells\"], at(path, \"cells\"), 1, faults) : [];\n const seen = new Set<string>();\n cells.forEach((cell, i) => {\n const inside = `${at(path, \"cells\")}[${i}]`;\n const fieldsOfCell = fields(cell, inside, [\"at\", \"value\", \"n\"], [], faults);\n if (fieldsOfCell === undefined) return;\n check(fieldsOfCell, \"value\", inside, isNumber, \"a finite number\", faults);\n check(fieldsOfCell, \"n\", inside, (v) => Number.isSafeInteger(v) && (v as number) >= 1, \"a whole number of 1 or more\", faults);\n if (!Object.hasOwn(fieldsOfCell, \"at\")) return;\n const values = list(fieldsOfCell[\"at\"], at(inside, \"at\"), 0, faults);\n need(values.length === table.length, at(inside, \"at\"), `this list has ${values.length} values, and the table has ${table.length} dimensions.`, faults);\n table.forEach((dimension, j) => {\n const absent = values[j] === null && dimension.when !== undefined;\n const fault = j < values.length && !absent ? valueFault(dimension, values[j]) : undefined;\n if (fault !== undefined) faults.push({ path: `${at(inside, \"at\")}[${j}]`, message: `${fault}.` });\n });\n const key = JSON.stringify(values);\n need(!seen.has(key), at(inside, \"at\"), `an earlier cell has the values ${shown(values)}.`, faults);\n seen.add(key);\n });\n}\n\n/** This function examines the list of models: one model for each measure. */\nfunction checkModels(value: unknown, data: ResponseData, faults: Faults): void {\n const dimensions = new Map(data.dimensions.map((d) => [d.id, d]));\n const measures = new Set(data.measures.map((m) => m.id));\n const covered = new Set<string>();\n list(value, \"models\", 0, faults).forEach((item, i) => {\n const path = `models[${i}]`;\n const kind = peek(item, \"kind\");\n if (kind !== \"ridge\" && kind !== \"table\") {\n faults.push({ path: at(path, \"kind\"), message: `this is \"ridge\" or \"table\", not ${shown(kind)}.` });\n return;\n }\n const keys = kind === \"ridge\" ? [\"lambda\", \"inputs\", \"intercept\", \"terms\"] : [\"dimensions\", \"cells\", \"fallback\"];\n const object = fields(item, path, [\"kind\", \"measure\", \"scale\", ...keys], kind === \"ridge\" ? [\"floor\"] : [\"floor\", \"conditional\"], faults);\n if (object === undefined) return;\n const measure = object[\"measure\"];\n if (typeof measure !== \"string\" || !measures.has(measure)) faults.push({ path: at(path, \"measure\"), message: `the record has no measure ${shown(measure)}.` });\n else {\n need(!covered.has(measure), at(path, \"measure\"), `an earlier model has the measure \"${measure}\".`, faults);\n covered.add(measure);\n }\n check(object, \"scale\", path, (v) => v === \"linear\" || v === \"log\", `\"linear\" or \"log\"`, faults);\n check(object, \"floor\", path, isPositive, \"a finite number above 0\", faults);\n need(!Object.hasOwn(object, \"floor\") || object[\"scale\"] === \"log\", at(path, \"floor\"), \"only a model with the scale log has a floor.\", faults);\n if (kind === \"ridge\") checkRidge(object, path, dimensions, faults);\n else checkTable(object, path, dimensions, faults);\n });\n for (const measure of measures) need(covered.has(measure), \"models\", `no model has the measure \"${measure}\".`, faults);\n}\n\n/** This function examines the error of one measure in one fold. */\nfunction checkFoldError(value: unknown, path: string, count: number, faults: Faults): void {\n const object = fields(value, path, [\"n\", \"mae\", \"rmse\", \"baselineMae\"], [], faults);\n if (object === undefined) return;\n check(object, \"n\", path, (v) => v === count, `${count}, the held-out points of the fold with a value of this measure`, faults);\n for (const key of [\"mae\", \"rmse\", \"baselineMae\"]) check(object, key, path, isNotNegative, \"a finite number of 0 or more\", faults);\n}\n\n/** This function examines the stored predictions of a fold against its held-out points and its errors. */\nfunction checkPredictions(value: unknown, path: string, held: readonly ResponsePoint[], errors: unknown, measures: readonly string[], faults: Faults): void {\n const predictions = fields(value, path, [], measures, faults);\n if (predictions === undefined) return;\n for (const measure of measures) {\n if (!Object.hasOwn(predictions, measure)) continue;\n const inside = at(path, measure);\n const stored = fields(predictions[measure], inside, [], Object.keys(peek(predictions, measure) ?? {}), faults);\n if (stored === undefined) continue;\n need(peek(errors, measure) !== undefined, inside, \"this fold has no error of this measure.\", faults);\n const scored = new Set(held.filter((p) => typeof p.measures[measure] === \"number\").map((p) => p.id));\n for (const id of Object.keys(stored)) {\n need(scored.has(id), at(inside, id), `this fold has no held-out point ${shown(id)} with a value of the measure.`, faults);\n check(stored, id, inside, isNumber, \"a finite number\", faults);\n }\n for (const id of scored) need(Object.hasOwn(stored, id), at(inside, id), \"this held-out point has no prediction.\", faults);\n }\n}\n\n/** This function adds the points of a fold to `foldOfPoint`, and it gives them. Each bad id gives a fault. */\nfunction heldPoints(value: unknown, path: string, f: number, points: ReadonlyMap<string, ResponsePoint>, foldOfPoint: Map<string, number>, faults: Faults): readonly ResponsePoint[] {\n const held: ResponsePoint[] = [];\n list(value, path, 1, faults).forEach((id, i) => {\n const inside = `${path}[${i}]`;\n const point = points.get(id as string);\n const earlier = foldOfPoint.get(id as string);\n if (point === undefined) faults.push({ path: inside, message: `the record has no point ${shown(id)}.` });\n else if (earlier !== undefined) faults.push({ path: inside, message: `the point \"${point.id}\" is also in fold ${earlier}.` });\n else {\n foldOfPoint.set(point.id, f);\n held.push(point);\n }\n });\n return held;\n}\n\n/** This function gives the number of points of each group in a list. */\nfunction groupSizes(points: readonly ResponsePoint[]): Map<string, number> {\n const sizes = new Map<string, number>();\n for (const p of points) sizes.set(groupKey(p), (sizes.get(groupKey(p)) ?? 0) + 1);\n return sizes;\n}\n\n/** This function examines the list of folds. `parseResponseRecord` tells the rules. */\nfunction checkFolds(value: unknown, data: ResponseData, faults: Faults): void {\n const points = new Map(data.points.map((p) => [p.id, p]));\n const measures = data.measures.map((m) => m.id);\n const sizes = groupSizes(data.points);\n const foldOfPoint = new Map<string, number>();\n const covered = new Set<string>();\n const folds = list(value, \"folds\", 1, faults);\n const predicted = measures.filter((m) => folds.some((fold) => peek(peek(fold, \"predictions\"), m) !== undefined));\n folds.forEach((item, f) => {\n const path = `folds[${f}]`;\n const object = fields(item, path, [\"heldOut\", \"errors\"], [\"predictions\"], faults);\n if (object === undefined) return;\n const held = Object.hasOwn(object, \"heldOut\") ? heldPoints(object[\"heldOut\"], at(path, \"heldOut\"), f, points, foldOfPoint, faults) : [];\n for (const [group, count] of groupSizes(held)) {\n const size = sizes.get(group) as number;\n need(count === size, at(path, \"heldOut\"), `the ${group} has ${count} of its ${size} points in this fold, so it is on both sides of the split.`, faults);\n }\n if (Object.hasOwn(object, \"predictions\")) checkPredictions(object[\"predictions\"], at(path, \"predictions\"), held, object[\"errors\"], measures, faults);\n if (!Object.hasOwn(object, \"errors\")) return;\n const errors = fields(object[\"errors\"], at(path, \"errors\"), [], measures, faults);\n if (errors === undefined) return;\n for (const measure of measures) {\n if (!Object.hasOwn(errors, measure)) continue;\n const count = held.filter((p) => p.measures[measure] !== null).length;\n checkFoldError(errors[measure], at(at(path, \"errors\"), measure), count, faults);\n if (count > 0) covered.add(measure);\n need(!predicted.includes(measure) || peek(object[\"predictions\"], measure) !== undefined, at(path, \"predictions\"), `another fold has predictions of the measure \"${measure}\", so this fold needs them too.`, faults);\n }\n });\n for (const measure of measures) need(covered.has(measure), \"folds\", `no fold has a held-out error of the measure \"${measure}\".`, faults);\n}\n\n/**\n * This function examines unknown data, for example the result of `JSON.parse`, against `response-records/1`. It gives\n * `{ ok: true, record }`, with the same object as the record, or `{ ok: false, faults }`. Each fault has the path of\n * the bad field and a message. The function does not throw. Data that the checks cannot read, for example an object\n * with a loop, gives one fault.\n *\n * A field that the format does not have is a fault. Thus a wrong spelling of an optional field cannot go unseen.\n *\n * The function examines the models and the folds only when the data has no fault, because they refer to the data.\n * Thus a correction of the data can show more faults. These rules apply to the folds:\n * - A point is in one fold or in no fold.\n * - All the points of a group are in one fold, or all are in no fold. Thus no group is on both sides of a split.\n * - The count `n` of an error is the number of held-out points with a value of the measure.\n * - Each measure has an error in one fold or more.\n *\n * These rules apply to the predictions of a fold:\n * - Each prediction is a finite number of a held-out point of the fold with a value of the measure.\n * - The fold has a prediction of each such point, and an error of the measure.\n * - When one fold has predictions of a measure, each fold with an error of the measure has them.\n *\n * These rules apply to the reasons of a point:\n * - Each reason is on a known measure with no number. A measure with `null` and no reason is good.\n * - Each reason has a declaration in the field `reasons` of the record.\n */\nexport function parseResponseRecord(value: unknown): ParsedResponseRecord {\n try {\n const faults: Faults = [...responseDataFaults(value, [\"models\", \"folds\"], [])];\n if (faults.length === 0) {\n const record = value as ResponseRecord;\n checkModels(record.models, record, faults);\n checkFolds(record.folds, record, faults);\n if (faults.length === 0) return { ok: true, record };\n }\n return { ok: false, faults };\n } catch (error) {\n return { ok: false, faults: [{ path: \"\", message: `the validator cannot read this data: ${String(error)}.` }] };\n }\n}\n","/**\n * The fit of `response-records/1`. The function `fitResponse` splits the groups into folds. For each fold, it fits a\n * model on the other folds and scores the model on the fold. Then it fits the model of the record on all the points.\n *\n * The coordinates of a ridge model come from the declared ranges, not from the points. Thus each fold has the same\n * design, and no fact of a held-out point goes into a fit. The penalty of a fold comes from the other folds only.\n */\nimport { random } from \"@mark1russell7/rigor-generators\";\nimport { mean } from \"./describe.ts\";\nimport { RESPONSE_MAX_POWER, factorFaults, responseDataFaults } from \"./response-parse.ts\";\nimport {\n RESPONSE_RECORDS_SCHEMA,\n type ResponseData,\n type ResponseDimension,\n type ResponseFactor,\n type ResponseFold,\n type ResponseFoldError,\n type ResponseInputValue,\n type ResponseMeasure,\n type ResponseModel,\n type ResponsePoint,\n type ResponseRecord,\n type ResponseTableCell,\n type ResponseValue,\n type RidgeInput,\n axisEnds,\n coordinates,\n groupKey,\n isNumberDimension,\n product,\n toModelScale,\n} from \"./response.ts\";\nimport { ridgeSolve } from \"./ridge.ts\";\n\n/** The options of `fitResponse`. */\nexport interface ResponseFitOptions {\n /** The number of folds, 3 or more. With fewer groups, each group is one fold. The default is 5. */\n readonly folds?: number;\n /** The seed of the split. The default is 1. */\n readonly seed?: number | string;\n /** The kind of model. The default `auto` gives a table when each dimension is categorical, and a ridge fit otherwise. */\n readonly model?: \"auto\" | \"ridge\" | \"table\";\n /** The largest total power of a term of a ridge fit, from 1 to 8. The default is 2. */\n readonly degree?: number;\n /**\n * When true, a ridge fit also has the products of two dimensions, up to `degree`. The default is true. The value\n * false also removes the products of a conditional dimension with the levels of its parent. Thus this option is the\n * way out of the limit `RESPONSE_MAX_TERMS`.\n *\n * The value `seen` is the expansion of true, with only the terms that are not 0 at one point or more. Thus a sparse\n * product of two large sets of levels keeps only the pairs with points. The limit applies after this choice.\n */\n readonly interactions?: boolean | \"seen\";\n /** The stated terms of a ridge fit, in place of `degree` and `interactions`. */\n readonly terms?: readonly (readonly ResponseFactor[])[];\n /** The penalties that a ridge fit chooses from, each above 0. The default is `RESPONSE_LAMBDAS`. */\n readonly lambdas?: readonly number[];\n /** The ids of the measures to fit on a log scale. */\n readonly log?: readonly string[];\n /** On a log scale, each smaller value takes this value. With no floor, a value of 0 or less is an error. */\n readonly logFloor?: number;\n /**\n * When true, each fold stores the prediction of each held-out point with a value. Then `heldOutErrorAt` gives the error of\n * a chosen set of points. The default is false, and the record then has no field `predictions`.\n */\n readonly outOfFold?: boolean;\n}\n\n/** The default penalties of a ridge fit. The coordinates are from -1 to 1, so one list suits each record. */\nexport const RESPONSE_LAMBDAS: readonly number[] = [1e-6, 1e-4, 1e-3, 1e-2, 1e-1, 1, 10, 100];\n\n/** The largest number of coefficients of a ridge fit. The memory of each fold grows as the square of this number. */\nexport const RESPONSE_MAX_TERMS = 1024;\n\n/** One value of a measure, on the scale of the model. */\ninterface Row {\n readonly point: ResponsePoint;\n readonly y: number;\n readonly fold: number;\n}\n\n/** A fit that leaves out one fold. Its result gives the prediction of a row, by the index of the row. */\ntype Learner = (fold: number) => (row: number) => number;\n\n/** The score of a measure in one fold. */\ninterface FoldScore {\n readonly error: ResponseFoldError;\n /** The prediction of each held-out point with a value, by the id of the point. */\n readonly predictions: Readonly<Record<string, number>>;\n}\n\n/** The terms and the other choices that apply to each measure. */\ninterface Plan {\n readonly ids: readonly string[];\n /** The ids of the dimensions with a condition. */\n readonly conditional: readonly string[];\n readonly kind: \"ridge\" | \"table\";\n readonly folds: number;\n readonly lambdas: readonly number[];\n readonly terms: readonly (readonly ResponseFactor[])[];\n readonly inputs: readonly RidgeInput[];\n}\n\n/** This function compares two texts by their code units, so the order does not depend on a locale. */\nconst byText = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);\n\n/** This function gives the input of a ridge model for a dimension. The coordinates run from -1 to 1 over the dimension. */\nfunction inputOf(dimension: ResponseDimension): RidgeInput {\n const conditional = dimension.when === undefined ? {} : { conditional: true };\n if (dimension.kind === \"categorical\") return { kind: \"level\", dimension: dimension.id, levels: dimension.levels, ...conditional };\n const [low, high] = axisEnds(dimension);\n const center = (low + high) / 2;\n const spread = high > low ? (high - low) / 2 : 1;\n if (!isNumberDimension(dimension)) return { kind: \"rank\", dimension: dimension.id, levels: dimension.levels as readonly string[], center, spread, ...conditional };\n return { kind: \"number\", dimension: dimension.id, center, spread, ...(dimension.log === true ? { log: true } : {}), ...conditional };\n}\n\n/** This function gives the factors of one dimension, each with its power. */\nfunction factorsOf(dimension: ResponseDimension, degree: number): readonly (readonly [ResponseFactor, number])[] {\n if (dimension.kind === \"categorical\") return dimension.levels.map((level) => [{ dimension: dimension.id, level }, 1] as const);\n return Array.from({ length: degree }, (_, i) => [{ dimension: dimension.id, power: i + 1 }, i + 1] as const);\n}\n\n/**\n * This function gives one column for each level of an ordinal parent inside a condition. An ordinal parent has no\n * one-hot columns of its own, so these columns carry the mean of each level with an absent child.\n */\nfunction parentColumns(dimensions: readonly ResponseDimension[]): readonly (readonly ResponseFactor[])[] {\n return dimensions.flatMap((parent) => {\n if (parent.kind !== \"ordinal\") return [];\n const conditions = dimensions.flatMap((d) => (d.when?.dimension === parent.id ? [d.when.levels] : []));\n const levels = (parent.levels as readonly ResponseValue[]).filter((level) => conditions.some((c) => c.includes(level)));\n return levels.map((level) => [{ dimension: parent.id, level }]);\n });\n}\n\n/** This function gives true when the general product of two dimensions adds nothing: a child with its parent, or two children with no common level. */\nfunction separate(a: ResponseDimension, b: ResponseDimension): boolean {\n if (a.when?.dimension === b.id || b.when?.dimension === a.id) return true;\n return a.when !== undefined && a.when.dimension === b.when?.dimension && !a.when.levels.some((level) => b.when?.levels.includes(level));\n}\n\n/**\n * This function gives the terms of the expansion: each factor, and each product of two dimensions up to `degree`. A\n * conditional dimension with two parent levels or more also has each power times each of these levels. Thus each\n * level has its own curve. With one parent level, the terms of the dimension are already the curve of this level.\n */\nfunction expansion(dimensions: readonly ResponseDimension[], degree: number, interactions: boolean): readonly (readonly ResponseFactor[])[] {\n const each = dimensions.map((d) => factorsOf(d, degree));\n const terms: (readonly ResponseFactor[])[] = [...each.flatMap((factors) => factors.map(([factor]) => [factor])), ...parentColumns(dimensions)];\n if (!interactions) return terms;\n each.forEach((first, a) => {\n each.slice(a + 1).forEach((second, offset) => {\n if (separate(dimensions[a] as ResponseDimension, dimensions[a + 1 + offset] as ResponseDimension)) return;\n for (const [f, p] of first) for (const [g, q] of second) if (p + q <= degree) terms.push([f, g]);\n });\n });\n dimensions.forEach(({ when }, a) => {\n if (when === undefined || when.levels.length < 2) return;\n for (const [factor] of each[a] as readonly (readonly [ResponseFactor, number])[]) {\n for (const level of when.levels) terms.push([factor, { dimension: when.dimension, level }]);\n }\n });\n return terms;\n}\n\n/** This function gives the terms that are not 0 at one point or more. A fold gives a term with no point the weight 0. */\nfunction seenTerms(terms: readonly (readonly ResponseFactor[])[], dimensions: readonly ResponseDimension[], points: readonly ResponsePoint[]): readonly (readonly ResponseFactor[])[] {\n const inputs = checkedInputs(dimensions, terms);\n const places = points.map((point) => ({ at: coordinates(inputs, point.values), values: point.values }));\n return terms.filter((term) => places.some(({ at, values }) => product(term, at, values) !== 0));\n}\n\n/** This function gives the inputs of a ridge fit: one for each dimension of a term. It throws for a bad term. */\nfunction checkedInputs(dimensions: readonly ResponseDimension[], terms: readonly (readonly ResponseFactor[])[]): readonly RidgeInput[] {\n const used = new Set(terms.flatMap((t) => t.map((f) => f.dimension)));\n const inputs = dimensions.filter((d) => used.has(d.id)).map(inputOf);\n const known = new Map(inputs.map((input) => [input.dimension, input]));\n const byId = new Map(dimensions.map((d) => [d.id, d]));\n terms.forEach((term, i) => {\n const [fault] = factorFaults(term, `terms[${i}]`, known, byId);\n if (fault !== undefined) throw new RangeError(`fitResponse: ${fault.path}: ${fault.message}`);\n });\n return inputs;\n}\n\n/**\n * This function gives the ridge fits of the rows of one measure. It keeps `X'X` and `X'y` of each fold, so a fit adds\n * the sums of its training folds. The first coefficient is the intercept, and it has no penalty.\n */\nfunction ridgeLearner(rows: readonly Row[], plan: Plan): { readonly learner: Learner; readonly final: () => { readonly lambda: number; readonly beta: readonly number[] } } {\n const { terms, inputs, folds, lambdas } = plan;\n const k = terms.length + 1;\n const design = new Float64Array(rows.length * k);\n const grams = Array.from({ length: folds }, () => new Float64Array(k * k));\n const moments = Array.from({ length: folds }, () => new Float64Array(k));\n rows.forEach((row, r) => {\n const at = coordinates(inputs, row.point.values);\n const offset = r * k;\n design[offset] = 1;\n terms.forEach((term, j) => {\n design[offset + j + 1] = product(term, at, row.point.values);\n });\n const gram = grams[row.fold] as Float64Array;\n const moment = moments[row.fold] as Float64Array;\n for (let a = 0; a < k; a++) {\n const value = design[offset + a] as number;\n moment[a] = (moment[a] as number) + value * row.y;\n for (let b = 0; b <= a; b++) gram[a * k + b] = (gram[a * k + b] as number) + value * (design[offset + b] as number);\n }\n });\n const predict = (beta: readonly number[], r: number): number => {\n let sum = 0;\n for (let j = 0; j < k; j++) sum += (beta[j] as number) * (design[r * k + j] as number);\n return sum;\n };\n const solve = (left: readonly (number | undefined)[], lambda: number): number[] => {\n const gram = new Float64Array(k * k);\n const moment = new Float64Array(k);\n for (let f = 0; f < folds; f++) {\n if (left.includes(f)) continue;\n const g = grams[f] as Float64Array;\n const m = moments[f] as Float64Array;\n for (let i = 0; i < k * k; i++) gram[i] = (gram[i] as number) + (g[i] as number);\n for (let i = 0; i < k; i++) moment[i] = (moment[i] as number) + (m[i] as number);\n }\n return ridgeSolve(gram, moment, lambda, { free: [0] });\n };\n // Each other fold scores a penalty on the rows outside `outer`. A tie or a singular fit keeps the larger penalty.\n const choose = (outer: number | undefined): number => {\n const descending = [...lambdas].sort((a, b) => b - a);\n let best = descending[0] as number;\n let bestError = Number.POSITIVE_INFINITY;\n for (const lambda of descending) {\n let error = 0;\n for (let f = 0; f < folds; f++) {\n if (f === outer) continue;\n const beta = solve([outer, f], lambda);\n rows.forEach((row, r) => {\n if (row.fold === f) error += (row.y - predict(beta, r)) ** 2;\n });\n }\n if (error < bestError) [best, bestError] = [lambda, error];\n }\n return best;\n };\n return {\n learner: (fold) => {\n const beta = solve([fold], choose(fold));\n return (r) => predict(beta, r);\n },\n final: () => {\n const lambda = choose(undefined);\n return { lambda, beta: solve([], lambda) };\n },\n };\n}\n\n/** This function gives the mean of the rows of each combination of levels, as cells in the order of their text. */\nfunction tableCells(rows: readonly Row[], dimensions: readonly string[]): readonly ResponseTableCell[] {\n const cells = new Map<string, { readonly at: readonly ResponseInputValue[]; readonly ys: number[] }>();\n for (const row of rows) {\n const at = dimensions.map((d) => row.point.values[d] as ResponseInputValue);\n const key = JSON.stringify(at);\n const cell = cells.get(key);\n if (cell === undefined) cells.set(key, { at, ys: [row.y] });\n else cell.ys.push(row.y);\n }\n return [...cells.keys()].sort(byText).map((key) => {\n const { at, ys } = cells.get(key) as { readonly at: readonly ResponseInputValue[]; readonly ys: number[] };\n return { at, value: mean(ys), n: ys.length };\n });\n}\n\n/** This function gives the fits of a table: the mean of each cell, or the mean of the rows for a cell with no row. */\nfunction tableLearner(rows: readonly Row[], dimensions: readonly string[]): Learner {\n const keys = rows.map((row) => JSON.stringify(dimensions.map((d) => row.point.values[d])));\n return (fold) => {\n const train = rows.filter((row) => row.fold !== fold);\n const cells = new Map(tableCells(train, dimensions).map((c) => [JSON.stringify(c.at), c.value]));\n const fallback = mean(train.map((row) => row.y));\n return (r) => cells.get(keys[r] as string) ?? fallback;\n };\n}\n\n/** This function gives the score of a fold. A fold with no held-out row or no training row has no score. */\nfunction foldScore(rows: readonly Row[], fold: number, learner: Learner): FoldScore | undefined {\n const train = rows.filter((row) => row.fold !== fold).map((row) => row.y);\n const held = rows.flatMap((row, r) => (row.fold === fold ? [r] : []));\n if (held.length === 0 || train.length === 0) return undefined;\n const predict = learner(fold);\n const baseline = mean(train);\n const predicted = held.map((r) => predict(r));\n const errors = held.map((r, i) => (rows[r] as Row).y - (predicted[i] as number));\n return {\n error: {\n n: held.length,\n mae: mean(errors.map(Math.abs)),\n rmse: Math.sqrt(mean(errors.map((e) => e * e))),\n baselineMae: mean(held.map((r) => Math.abs((rows[r] as Row).y - baseline))),\n },\n predictions: Object.fromEntries(held.map((r, i) => [(rows[r] as Row).point.id, predicted[i] as number])),\n };\n}\n\n/** This function gives the rows of a measure. It throws a RangeError for a value that a log scale cannot read. */\nfunction rowsOf(points: readonly ResponsePoint[], measure: string, log: boolean, floor: number | undefined, foldOf: ReadonlyMap<string, number>): readonly Row[] {\n return points.flatMap((point) => {\n const value = point.measures[measure];\n if (typeof value !== \"number\") return [];\n if (log && floor === undefined && value <= 0) throw new RangeError(`fitResponse: the point \"${point.id}\" has the value ${value} of the log measure \"${measure}\". Give logFloor.`);\n return [{ point, y: toModelScale(value, log, floor), fold: foldOf.get(groupKey(point)) as number }];\n });\n}\n\n/** This function gives the model of one measure on all its rows, and the score of each fold. */\nfunction fitMeasure(rows: readonly Row[], measure: ResponseMeasure, log: boolean, floor: number | undefined, plan: Plan): { readonly model: ResponseModel; readonly scores: readonly (FoldScore | undefined)[] } {\n if (rows.length === 0) throw new RangeError(`fitResponse: no point has a value of the measure \"${measure.id}\".`);\n const base = { measure: measure.id, scale: log ? (\"log\" as const) : (\"linear\" as const), ...(log && floor !== undefined ? { floor } : {}) };\n const ridge = plan.kind === \"ridge\" ? ridgeLearner(rows, plan) : undefined;\n const learner = ridge?.learner ?? tableLearner(rows, plan.ids);\n const scores = Array.from({ length: plan.folds }, (_, f) => foldScore(rows, f, learner));\n if (scores.every((s) => s === undefined)) throw new RangeError(`fitResponse: all the values of the measure \"${measure.id}\" are in one fold. Give more groups.`);\n const conditional = plan.conditional.length === 0 ? {} : { conditional: plan.conditional };\n if (ridge === undefined) return { model: { kind: \"table\", ...base, dimensions: plan.ids, ...conditional, cells: tableCells(rows, plan.ids), fallback: mean(rows.map((r) => r.y)) }, scores };\n const { lambda, beta } = ridge.final();\n if (!beta.every(Number.isFinite)) throw new RangeError(`fitResponse: the fit of the measure \"${measure.id}\" with lambda ${lambda} is singular. Give a larger lambda.`);\n const terms = plan.terms.map((factors, j) => ({ factors, weight: beta[j + 1] as number }));\n return { model: { kind: \"ridge\", ...base, lambda, inputs: plan.inputs, intercept: beta[0] as number, terms }, scores };\n}\n\n/** This function examines the options that do not depend on the data, and it gives the number of folds and the penalties. */\nfunction checkedOptions(options: ResponseFitOptions): { readonly folds: number; readonly degree: number; readonly lambdas: readonly number[] } {\n const { folds = 5, degree = 2, lambdas = RESPONSE_LAMBDAS, logFloor } = options;\n if (!Number.isSafeInteger(folds) || folds < 3) throw new RangeError(`fitResponse: folds is a whole number of 3 or more, not ${folds}.`);\n if (!Number.isSafeInteger(degree) || degree < 1 || degree > RESPONSE_MAX_POWER) throw new RangeError(`fitResponse: degree is a whole number from 1 to ${RESPONSE_MAX_POWER}, not ${degree}.`);\n if (lambdas.length === 0 || !lambdas.every((l) => Number.isFinite(l) && l > 0)) throw new RangeError(\"fitResponse: lambdas is a list of finite numbers above 0, with one item or more.\");\n if (logFloor !== undefined && !(Number.isFinite(logFloor) && logFloor > 0)) throw new RangeError(`fitResponse: logFloor is a finite number above 0, not ${logFloor}.`);\n return { folds, degree, lambdas };\n}\n\n/** This function gives the kind of model. It throws a RangeError when a table cannot read a dimension. */\nfunction kindOf(dimensions: readonly ResponseDimension[], model: \"auto\" | \"ridge\" | \"table\"): \"ridge\" | \"table\" {\n const continuous = dimensions.find((d) => d.kind === \"continuous\");\n if (model === \"table\" && continuous !== undefined) throw new RangeError(`fitResponse: a table cannot read the continuous dimension \"${continuous.id}\".`);\n if (model !== \"auto\") return model;\n return dimensions.every((d) => d.kind === \"categorical\") ? \"table\" : \"ridge\";\n}\n\n/**\n * This function fits each measure of `data`, and it gives a record with the models and the folds.\n *\n * The split: the groups, sorted and then shuffled with `seed`, go to the folds in turn. A point with no group is a\n * group of its own. Thus the repeats of one group are not on both sides of a split. The same split applies to each\n * measure. A record needs 3 groups or more.\n *\n * The model: a ridge fit over a stated expansion, or the mean of each cell of a table. The default expansion has\n * each power of each number dimension up to `degree`. It has one column for each level of a categorical dimension.\n * It also has the products of two dimensions up to `degree`. Each coordinate goes from -1 to 1 over the declared\n * range. The intercept has no penalty.\n *\n * A conditional dimension: a term with an absent dimension is 0. Thus the columns of the parent carry the mean of each\n * level with no value. A dimension with two parent levels or more also has each power times each of these levels, if\n * `interactions` is true. A table keeps `null` as a level of its cells.\n *\n * The penalty: each fold of a ridge fit chooses from `lambdas` with the other folds. Thus the held-out error of a\n * fold is not optimistic. The model of the record chooses with all the folds.\n *\n * The errors: a fold scores the model of the other folds on its held-out points, on the scale of the model. With the\n * option `outOfFold`, the fold also stores the prediction of each of these points.\n *\n * The reasons: a measure with a stated reason is `null` for the fit. The field `reasons` of the data stays in the record.\n *\n * The result does not depend on the order of the points, except for the field `points`, which keeps the order of\n * the data. The same data and options give the same bytes in one JavaScript engine.\n *\n * The function throws a RangeError for data with a fault, for a bad option, and for fewer than 3 groups. It also\n * throws for a measure with no value, and for a measure with all its values in one fold. It throws for a value of 0\n * or less on a log scale with no `logFloor`. It throws for more than `RESPONSE_MAX_TERMS` terms.\n */\nexport function fitResponse(data: ResponseData, options: ResponseFitOptions = {}): ResponseRecord {\n const [fault] = responseDataFaults(data, [], [\"models\", \"folds\"]);\n if (fault !== undefined) throw new RangeError(`fitResponse: ${fault.path === \"\" ? \"the data\" : fault.path}: ${fault.message}`);\n const { degree, lambdas, folds: wanted } = checkedOptions(options);\n const { dimensions, measures } = data;\n const log = new Set(options.log ?? []);\n for (const id of log) if (!measures.some((m) => m.id === id)) throw new RangeError(`fitResponse: the option log names the unknown measure \"${id}\".`);\n const kind = kindOf(dimensions, options.model ?? \"auto\");\n const interactions = options.interactions ?? true;\n const expanded = kind === \"table\" ? [] : (options.terms ?? expansion(dimensions, degree, interactions !== false));\n const terms = interactions === \"seen\" && options.terms === undefined ? seenTerms(expanded, dimensions, data.points) : expanded;\n if (terms.length + 1 > RESPONSE_MAX_TERMS) throw new RangeError(`fitResponse: the expansion has ${terms.length} terms, and the limit is ${RESPONSE_MAX_TERMS - 1}. Set interactions to false or \"seen\", or give terms.`);\n const inputs = checkedInputs(dimensions, terms);\n const points = [...data.points].sort((a, b) => byText(a.id, b.id));\n const groups = [...new Set(points.map(groupKey))].sort(byText);\n if (groups.length < 3) throw new RangeError(`fitResponse: the points have ${groups.length} groups, and a held-out split needs 3 or more.`);\n const folds = Math.min(wanted, groups.length);\n const shuffled = random(options.seed ?? 1).shuffle(groups);\n const foldOf = new Map(shuffled.map((group, i) => [group, i % folds]));\n const plan: Plan = { ids: dimensions.map((d) => d.id), conditional: dimensions.flatMap((d) => (d.when === undefined ? [] : [d.id])), kind, folds, lambdas, terms, inputs };\n const fits = measures.map((m) => fitMeasure(rowsOf(points, m.id, log.has(m.id), options.logFloor, foldOf), m, log.has(m.id), options.logFloor, plan));\n const foldRecords: readonly ResponseFold[] = Array.from({ length: folds }, (_, f) => {\n const scored = measures.flatMap((m, i) => {\n const score = fits[i]?.scores[f];\n return score === undefined ? [] : [[m.id, score] as const];\n });\n return {\n heldOut: points.filter((p) => foldOf.get(groupKey(p)) === f).map((p) => p.id),\n errors: Object.fromEntries(scored.map(([id, score]) => [id, score.error])),\n ...(options.outOfFold === true ? { predictions: Object.fromEntries(scored.map(([id, score]) => [id, score.predictions])) } : {}),\n };\n });\n const reasons = data.reasons === undefined ? {} : { reasons: data.reasons };\n return { schema: RESPONSE_RECORDS_SCHEMA, name: data.name, dimensions, measures, ...reasons, points: data.points, models: fits.map((fit) => fit.model), folds: foldRecords };\n}\n","/**\n * The Sobol indices of a fitted model of a record of the format `response-records/1`. The first-order index of a\n * dimension is the share of the variance of the prediction that the dimension causes alone. The total index also\n * includes each interaction of the dimension with the other dimensions.\n *\n * The method is Monte Carlo with two independent matrices A and B of N rows, and one matrix `AB_i` for each dimension `i`.\n * `AB_i` is A with the column `i` of B (Saltelli and others, 2010). The first-order index uses the estimator of Saltelli\n * (2010), and the total index uses the estimator of Jansen (1999). The model gets N * (d + 2) evaluations for d dimensions.\n *\n * This file uses no Node import, no clock and no `Math.random`, the same as `response.ts`.\n */\nimport { random, type Random } from \"@mark1russell7/rigor-generators\";\nimport { type BootstrapOptions, type Interval, percentiles } from \"./bootstrap.ts\";\nimport { type ResponseDimension, type ResponseInputValue, type ResponseRecord, predictScaled, predictResponse, whenHolds } from \"./response.ts\";\n\n/** The options of `sobolIndices`. */\nexport interface SobolOptions {\n /** The number N of rows of each base matrix. The default is 4096. */\n readonly n?: number;\n /** The seed of the draws. The default is 1. */\n readonly seed?: number | string;\n /**\n * The scale of the output. The value `measure` uses `predictResponse`. The value `model` uses the scale of the\n * model, so a model with a log scale gives the indices of the logarithm. The default is `measure`.\n */\n readonly scale?: \"measure\" | \"model\";\n /**\n * With this option, each index also gets a percentile bootstrap interval over the N rows. Each run draws N rows\n * with replacement, and it calculates all the indices from these rows. The default is no interval.\n */\n readonly interval?: BootstrapOptions;\n}\n\n/** The two Sobol indices of one dimension. */\nexport interface SobolIndex {\n /** The id of the dimension. */\n readonly dimension: string;\n /** The first-order index S_i: the estimator of Saltelli (2010). */\n readonly first: number;\n /** The total index ST_i: the estimator of Jansen (1999). */\n readonly total: number;\n /** The bootstrap interval of `first`. Only the option `interval` writes this field. */\n readonly firstInterval?: Interval;\n /** The bootstrap interval of `total`. Only the option `interval` writes this field. */\n readonly totalInterval?: Interval;\n}\n\n/** The result of `sobolIndices`. */\nexport interface SobolIndices {\n /** The id of the measure. */\n readonly measure: string;\n /** The scale of the output. */\n readonly scale: \"measure\" | \"model\";\n /** The number N of rows of each base matrix. */\n readonly n: number;\n /** The number of model evaluations: N * (d + 2). */\n readonly evaluations: number;\n /** The seed as a 32-bit number. */\n readonly seed: number;\n /** The mean of the outputs of A and B. */\n readonly mean: number;\n /** The variance of the outputs of A and B, with the divisor 2N. */\n readonly variance: number;\n /** The indices of each dimension of the record, in the order of the record. */\n readonly indices: readonly SobolIndex[];\n}\n\n/** This function draws one value of a dimension. Each dimension uses the same number of draws: one. */\nfunction drawValue(dimension: ResponseDimension, r: Random): number | string {\n if (dimension.kind !== \"continuous\") return dimension.levels[r.below(dimension.levels.length)] as number | string;\n const [low, high] = dimension.range;\n if (dimension.log !== true) return r.range(low, high);\n const value = 10 ** r.range(Math.log10(low), Math.log10(high));\n return Math.min(high, Math.max(low, value));\n}\n\n/** This function draws a matrix of `n` rows, row by row, with one draw for each dimension in the order of the record. */\nfunction drawMatrix(dimensions: readonly ResponseDimension[], n: number, r: Random): (number | string)[][] {\n return Array.from({ length: n }, () => dimensions.map((d) => drawValue(d, r)));\n}\n\n/** This function gives the inputs of a row. A conditional dimension gets `null` where its condition fails. */\nfunction inputsOf(dimensions: readonly ResponseDimension[], row: readonly (number | string)[]): Record<string, ResponseInputValue> {\n const drawn: Record<string, ResponseInputValue> = {};\n dimensions.forEach((d, i) => {\n drawn[d.id] = row[i] as number | string;\n });\n const inputs: Record<string, ResponseInputValue> = {};\n for (const d of dimensions) inputs[d.id] = whenHolds(d, drawn) ? (drawn[d.id] as ResponseInputValue) : null;\n return inputs;\n}\n\n/** The outputs of the matrices, as the model gives them. The estimators subtract the mean where they use it. */\ninterface Outputs {\n readonly a: Float64Array;\n readonly b: Float64Array;\n /** The outputs of `AB_i` for each dimension `i`. */\n readonly ab: readonly Float64Array[];\n}\n\n/**\n * This function gives the variance and the indices from the rows `rows`. A variance of 0 gives each index as 0.\n * The value `constant` is true when each output is equal to the first output.\n */\nfunction estimate(outputs: Outputs, rows: readonly number[] | null, n: number, constant: boolean): { mean: number; variance: number; first: number[]; total: number[] } {\n const d = outputs.ab.length;\n const at = (j: number): number => (rows === null ? j : (rows[j] as number));\n let sum = 0;\n for (let j = 0; j < n; j++) sum += (outputs.a[at(j)] as number) + (outputs.b[at(j)] as number);\n const mean = sum / (2 * n);\n let square = 0;\n for (let j = 0; j < n; j++) {\n const ea = (outputs.a[at(j)] as number) - mean;\n const eb = (outputs.b[at(j)] as number) - mean;\n square += ea * ea + eb * eb;\n }\n const variance = constant ? 0 : square / (2 * n);\n const first: number[] = [];\n const total: number[] = [];\n for (let i = 0; i < d; i++) {\n const abi = outputs.ab[i] as Float64Array;\n let s = 0;\n let t = 0;\n for (let j = 0; j < n; j++) {\n const fa = outputs.a[at(j)] as number;\n const fb = outputs.b[at(j)] as number;\n const fab = abi[at(j)] as number;\n s += (fb - mean) * (fab - fa);\n t += (fa - fab) * (fa - fab);\n }\n first.push(variance > 0 ? s / n / variance : 0);\n total.push(variance > 0 ? t / (2 * n) / variance : 0);\n }\n return { mean, variance, first, total };\n}\n\n/**\n * This function gives the first-order and the total Sobol index of each dimension of a record, for the model of\n * `measure`. The indices are of the prediction of the model, not of the measured points.\n *\n * The input distribution:\n * - Each dimension is independent of the other dimensions.\n * - A continuous dimension is uniform over its range. With `log`, the logarithm of the value is uniform.\n * - An ordinal or a categorical dimension is uniform over its levels.\n * - A conditional dimension gets an independent draw. The model gets `null` for it where `whenHolds` fails for the drawn parent.\n *\n * Thus the inputs stay independent, and the indices have their usual meaning. A parent gets the effect of the absence of its child.\n *\n * The estimators:\n * - The first-order index is `mean(f(B) * (f(AB_i) - f(A))) / V` (Saltelli, 2010).\n * - The total index is `mean((f(A) - f(AB_i)) ** 2) / 2 / V` (Jansen, 1999).\n * - V is the variance of the outputs of A and B together.\n * - The variance uses the outputs of A and B less their mean. The first-order sum uses `f(B)` less that mean.\n * - The total sum uses differences of outputs, so it uses no mean.\n * - This step keeps the estimators unbiased, and it decreases their error when the mean is large.\n *\n * A model with a constant output has the variance 0. Then each index is 0, not NaN. An estimate can be a little\n * below 0 or above 1, from the Monte Carlo error. The function does not clip it.\n *\n * The draws fill A row by row, then B row by row. Each row has one draw for each dimension, in the order of the\n * record. Thus the same seed gives the same indices. The model can ignore a dimension. Then that dimension gets 0 for both\n * indices exactly, unless it is the parent of a dimension that the model reads.\n *\n * The function throws a RangeError when the record has no model of `measure`, and when N is not a whole number of 2 or more.\n * `predictResponse` throws for a value that the model refuses, for example a level that the model does not know.\n */\nexport function sobolIndices(record: Pick<ResponseRecord, \"dimensions\" | \"models\">, measure: string, options: SobolOptions = {}): SobolIndices {\n const model = record.models.find((m) => m.measure === measure);\n if (model === undefined) throw new RangeError(`sobolIndices: the record has no model of the measure \"${measure}\".`);\n const n = options.n ?? 4096;\n if (!Number.isSafeInteger(n) || n < 2) throw new RangeError(`sobolIndices: n is a whole number of 2 or more, not ${n}.`);\n const scale = options.scale ?? \"measure\";\n const dimensions = record.dimensions;\n const d = dimensions.length;\n const r = random(options.seed ?? 1);\n const a = drawMatrix(dimensions, n, r);\n const b = drawMatrix(dimensions, n, r);\n const f = (row: readonly (number | string)[]): number => {\n const inputs = inputsOf(dimensions, row);\n return scale === \"model\" ? predictScaled(model, inputs) : predictResponse(model, inputs);\n };\n const fa = Float64Array.from(a, f);\n const fb = Float64Array.from(b, f);\n const ab = dimensions.map((_, i) => Float64Array.from(a, (row, j) => f(row.map((v, k) => (k === i ? ((b[j] as (number | string)[])[i] as number | string) : v)))));\n const outputs: Outputs = { a: fa, b: fb, ab };\n const first = fa[0] as number;\n const constant = fa.every((v) => v === first) && fb.every((v) => v === first);\n const all = estimate(outputs, null, n, constant);\n let intervals: Interval[] | undefined;\n if (options.interval !== undefined) {\n const rows = new Array<number>(n);\n const flat = (e: { first: number[]; total: number[] }): number[] => [...e.first, ...e.total];\n intervals = percentiles(\n \"sobolIndices\",\n options.interval,\n 2 * d,\n (rr) => {\n for (let j = 0; j < n; j++) rows[j] = rr.below(n);\n return flat(estimate(outputs, rows, n, constant));\n },\n () => flat(all),\n );\n }\n const indices = dimensions.map((dimension, i): SobolIndex => {\n const index = { dimension: dimension.id, first: all.first[i] as number, total: all.total[i] as number };\n if (intervals === undefined) return index;\n return { ...index, firstInterval: intervals[i] as Interval, totalInterval: intervals[d + i] as Interval };\n });\n return { measure, scale, n, evaluations: n * (d + 2), seed: r.seed, mean: constant ? first : all.mean, variance: all.variance, indices };\n}\n","/**\n * The tests of a difference: the sign test, the paired permutation test, the Wilson interval of a proportion and\n * the Holm correction for several tests.\n */\nimport { random } from \"@mark1russell7/rigor-generators\";\nimport { mean, median } from \"./describe.ts\";\n\nfunction whole(name: string, value: number): void {\n if (!Number.isSafeInteger(value) || value < 0) throw new RangeError(`${name}: ${value} is not a whole number of 0 or more.`);\n}\n\nconst TWO_512 = 2 ** 512;\n\n/** C(n, k) / 2^n, as one product of min(k, n - k) ratios, with the powers of 2 kept apart so that no step overflows. */\nfunction halfBinomial(k: number, n: number): number {\n const m = Math.min(k, n - k);\n let value = 1;\n let exponent = -n;\n for (let i = 1; i <= m; i++) {\n value *= (n - m + i) / i;\n if (value > TWO_512) {\n value /= TWO_512;\n exponent += 512;\n }\n }\n for (; exponent < -512; exponent += 512) value /= TWO_512;\n return value * 2 ** exponent;\n}\n\n/** The largest n for which the tail is an exact sum of whole numbers. Above it, the sum is in floating point. */\nconst SIGN_TEST_EXACT_LIMIT = 4096;\n\n/** num / 2^n as the nearest double: one rounding, also when num has more than 1024 bits. */\nfunction overPowerOfTwo(num: bigint, n: number): number {\n const shift = Math.max(0, num.toString(2).length - 1000);\n let value = Number(num >> BigInt(shift));\n let exponent = shift - n;\n for (; exponent < -512; exponent += 512) value /= TWO_512;\n return value * 2 ** exponent;\n}\n\n/**\n * P(X >= k) for X ~ Binomial(n, 1/2). For n up to SIGN_TEST_EXACT_LIMIT it adds C(n, i) as whole numbers (BigInt),\n * so the only error is the last rounding to a double. Above the limit and above the middle, it adds the terms as\n * ratios of term k in linear space. At or below the middle, it gives 1 - P(X >= n - k + 1), by symmetry. (An earlier form added\n * logs and called Math.exp, and its error grew with n: up to 2.5e-14 for n <= 80, rigor#158. The floating-point\n * form above the limit was at most 1.1e-14 relative at n = 4097 and 5000, above 2^-1000.)\n */\nfunction upperTail(k: number, n: number): number {\n if (k <= 0) return 1;\n if (k > n) return 0;\n if (n <= SIGN_TEST_EXACT_LIMIT) {\n const big = BigInt(n);\n let term = 1n;\n for (let i = 1n; i <= BigInt(k); i++) term = (term * (big - i + 1n)) / i;\n let sum = 0n;\n for (let i = BigInt(k); i <= big; i++) {\n sum += term;\n term = (term * (big - i)) / (i + 1n);\n }\n return Math.min(1, overPowerOfTwo(sum, n));\n }\n if (2 * k <= n) return 1 - upperTail(n - k + 1, n);\n let ratio = 1;\n let sum = 1;\n for (let i = k; i < n && ratio > 0; i++) {\n ratio *= (n - i) / (i + 1);\n sum += ratio;\n }\n return Math.min(1, halfBinomial(k, n) * sum);\n}\n\n/**\n * The sign test of paired results: `better` inputs where the candidate wins and `worse` where it loses. The ties\n * do not count. One-sided (the default), it is the p of `better` wins or more if the two are equal. Two-sided, it is\n * two times the tail of the larger count, at most 1. The one-sided p is equal to `signTestP` of packing.\n */\nexport function signTest(better: number, worse: number, sides: 1 | 2 = 1): number {\n whole(\"signTest\", better);\n whole(\"signTest\", worse);\n const n = better + worse;\n if (n === 0) return 1;\n if (sides === 1) return upperTail(better, n);\n return Math.min(1, 2 * upperTail(Math.max(better, worse), n));\n}\n\n/**\n * The smallest number of wins out of `n` that the sign test calls significant at `level`. It is undefined when even\n * n wins out of n are not enough. Use it before a run, to know how many inputs a claim needs.\n */\nexport function signTestPower(n: number, level = 0.05, sides: 1 | 2 = 2): number | undefined {\n whole(\"signTestPower\", n);\n // The p falls as k grows above the middle, so a binary search finds the first k under the level.\n if (n === 0 || signTest(n, 0, sides) >= level) return undefined;\n let low = Math.ceil(n / 2);\n let high = n;\n while (low < high) {\n const middle = Math.floor((low + high) / 2);\n if (signTest(middle, n - middle, sides) < level) high = middle;\n else low = middle + 1;\n }\n return low;\n}\n\n/** The z of a two-sided 95% interval. */\nexport const Z95 = 1.959963984540054;\n\n/** An interval of a proportion. */\nexport interface Proportion {\n readonly low: number;\n readonly high: number;\n}\n\n/**\n * The Wilson score interval of `k` successes in `n` trials (Wilson, 1927). It keeps its level for a small n and for\n * a proportion near 0 or 1, where the normal interval does not. For n = 0 the interval is 0 to 1.\n */\nexport function wilson(k: number, n: number, z: number = Z95): Proportion {\n whole(\"wilson\", k);\n whole(\"wilson\", n);\n if (k > n) throw new RangeError(`wilson: k ${k} is more than n ${n}.`);\n if (n === 0) return { low: 0, high: 1 };\n const p = k / n;\n const z2 = z * z;\n const denominator = 1 + z2 / n;\n const center = (p + z2 / (2 * n)) / denominator;\n const half = (z / denominator) * Math.sqrt((p * (1 - p)) / n + z2 / (4 * n * n));\n return { low: Math.max(0, center - half), high: Math.min(1, center + half) };\n}\n\n/** One test after the Holm correction. */\nexport interface Corrected {\n /** The p of the test. */\n readonly p: number;\n /** The p after the correction: compare it with the level of the whole family. */\n readonly adjusted: number;\n /** The adjusted p is less than the level. */\n readonly reject: boolean;\n}\n\n/**\n * The Holm step-down correction of a family of tests (Holm, 1979). It keeps the chance of one false claim or more\n * in the family at most `level`. It has no condition on how the tests depend on each other. The result is in the\n * order of the input.\n */\nexport function holm(pValues: readonly number[], level = 0.05): Corrected[] {\n for (const p of pValues) if (!(p >= 0 && p <= 1)) throw new RangeError(`holm: each p is from 0 to 1, not ${p}.`);\n const m = pValues.length;\n const order = pValues.map((p, i) => ({ p, i })).sort((a, b) => a.p - b.p || a.i - b.i);\n const adjusted = new Array<number>(m);\n let running = 0;\n order.forEach(({ p, i }, rank) => {\n running = Math.max(running, Math.min(1, (m - rank) * p));\n adjusted[i] = running;\n });\n return pValues.map((p, i) => ({ p, adjusted: adjusted[i] as number, reject: (adjusted[i] as number) < level }));\n}\n\n/**\n * The p of the claim \"at least `need` of these tests have a real effect\" (Benjamini and Heller, 2008). The value is\n * `(m - need + 1)` times the `need`-th smallest p, at most 1. It has no condition on how the tests depend on each other.\n * With 2 tests and `need` 2, the value is the larger p.\n */\nexport function partialConjunction(pValues: readonly number[], need: number): number {\n for (const p of pValues) if (!(p >= 0 && p <= 1)) throw new RangeError(`partialConjunction: each p is from 0 to 1, not ${p}.`);\n whole(\"partialConjunction\", need);\n const m = pValues.length;\n if (need < 1 || need > m) throw new RangeError(`partialConjunction: need is from 1 to the count of tests ${m}, not ${need}.`);\n const sorted = [...pValues].sort((a, b) => a - b);\n return Math.min(1, (m - need + 1) * (sorted[need - 1] as number));\n}\n\nexport interface PermutationOptions {\n /** The number of random sign flips. The default is 10 000. */\n readonly runs?: number;\n /** The default is 1. */\n readonly seed?: number | string;\n /** The statistic of the differences. The default is the mean. */\n readonly statistic?: (differences: readonly number[]) => number;\n}\n\nexport interface PermutationResult {\n /** The statistic of the observed differences `candidate[i] - baseline[i]`. */\n readonly observed: number;\n /** The two-sided p: (1 + the flips with a statistic as far from 0 or farther) / (1 + runs). */\n readonly p: number;\n readonly runs: number;\n}\n\n/**\n * The paired permutation test (a random sign flip of each difference). It needs no normal distribution and uses\n * the size of each difference, which the sign test does not. A pair with a difference of 0 adds nothing.\n */\nexport function pairedPermutation(candidate: readonly number[], baseline: readonly number[], options: PermutationOptions = {}): PermutationResult {\n if (candidate.length !== baseline.length) throw new RangeError(`pairedPermutation: the lists have ${candidate.length} and ${baseline.length} values.`);\n const differences = candidate.map((c, i) => c - (baseline[i] as number));\n const statistic = options.statistic ?? mean;\n const runs = options.runs ?? 10_000;\n if (!Number.isSafeInteger(runs) || runs < 1) throw new RangeError(`pairedPermutation: runs is a whole number of 1 or more, not ${runs}.`);\n const observed = statistic(differences);\n const r = random(options.seed ?? 1);\n const flipped = new Array<number>(differences.length);\n let extreme = 0;\n for (let run = 0; run < runs; run++) {\n for (let i = 0; i < differences.length; i++) flipped[i] = r.next() < 0.5 ? -(differences[i] as number) : (differences[i] as number);\n // A small tolerance, so that a flip with the same statistic up to rounding counts as extreme.\n if (Math.abs(statistic(flipped)) >= Math.abs(observed) * (1 - 1e-12)) extreme++;\n }\n return { observed, p: (1 + extreme) / (1 + runs), runs };\n}\n\n/** The default of the option `exactMax` of `signFlipTest`. */\nexport const SIGN_FLIP_EXACT_MAX = 16;\n\n/** The largest value of the option `exactMax` of `signFlipTest`: 2^24 sign sets. */\nexport const SIGN_FLIP_EXACT_LIMIT = 24;\n\n/** The options of `signFlipTest`. */\nexport interface SignFlipOptions {\n /** The largest count of terms for which the test reads each of the `2^n` sign sets. The default is 16. The most is 24. */\n readonly exactMax?: number;\n /** The count of random sign sets above `exactMax`. The default is 10 000. */\n readonly runs?: number;\n /** The default is 1. */\n readonly seed?: number | string;\n}\n\n/** The result of `signFlipTest`. */\nexport interface SignFlipResult {\n /** The absolute value of the sum of the terms. */\n readonly observed: number;\n /** The two-sided p. */\n readonly p: number;\n /** This field is true when the test read each sign set, so the p has no noise from the draws. */\n readonly exact: boolean;\n /** The count of the sign sets that the test read: `2^n` when it is exact, otherwise the count of the draws. */\n readonly runs: number;\n}\n\n/**\n * The sign-flip test of a sum of terms. Under the null, each term has the sign + or - with equal chance. The statistic\n * is the absolute value of the sum. A weighted mean of paired differences is such a sum: give the terms `w[i] * d[i]`.\n *\n * Up to `exactMax` terms, the test reads each sign set. The p is the share of the sets that are as far from 0 or\n * farther. The observed set is one of them. Above `exactMax`, the test draws `runs` sets, and the p is (1 + the extreme\n * draws) / (1 + runs). A sum within `1e-12` of the sum of the absolute terms counts as extreme, so rounding does not\n * hide a tie.\n */\nexport function signFlipTest(terms: readonly number[], options: SignFlipOptions = {}): SignFlipResult {\n const exactMax = options.exactMax ?? SIGN_FLIP_EXACT_MAX;\n if (!Number.isInteger(exactMax) || exactMax < 0 || exactMax > SIGN_FLIP_EXACT_LIMIT) {\n throw new RangeError(`signFlipTest: exactMax is a whole number from 0 to ${SIGN_FLIP_EXACT_LIMIT}, not ${exactMax}.`);\n }\n for (const [i, t] of terms.entries()) if (!Number.isFinite(t)) throw new RangeError(`signFlipTest: the term ${i} is ${t}, not a finite number.`);\n const n = terms.length;\n const observed = Math.abs(terms.reduce((sum, t) => sum + t, 0));\n const slack = 1e-12 * terms.reduce((sum, t) => sum + Math.abs(t), 0);\n if (n <= exactMax) {\n const total = 2 ** n;\n let hits = 0;\n for (let mask = 0; mask < total; mask++) {\n let sum = 0;\n for (let i = 0; i < n; i++) sum += mask & (1 << i) ? -(terms[i] as number) : (terms[i] as number);\n if (Math.abs(sum) >= observed - slack) hits++;\n }\n return { observed, p: hits / total, exact: true, runs: total };\n }\n const runs = options.runs ?? 10_000;\n if (!Number.isSafeInteger(runs) || runs < 1) throw new RangeError(`signFlipTest: runs is a whole number of 1 or more, not ${runs}.`);\n const r = random(options.seed ?? 1);\n let hits = 0;\n for (let run = 0; run < runs; run++) {\n let sum = 0;\n for (let i = 0; i < n; i++) sum += r.next() < 0.5 ? -(terms[i] as number) : (terms[i] as number);\n if (Math.abs(sum) >= observed - slack) hits++;\n }\n return { observed, p: (1 + hits) / (1 + runs), exact: false, runs };\n}\n\n/** The options of `twoSamplePermutation`. */\nexport interface TwoSamplePermutationOptions {\n /** The largest number of splits that the test reads. The default is 10 000. */\n readonly runs?: number;\n /** The default is 1. */\n readonly seed?: number | string;\n /** The statistic of the two groups. The default is the median of `a` minus the median of `b`. */\n readonly statistic?: (a: readonly number[], b: readonly number[]) => number;\n}\n\n/** The result of `twoSamplePermutation`. */\nexport interface TwoSamplePermutationResult extends PermutationResult {\n /** This field is true when the test read each split, so the p has no noise from the draws. */\n readonly exact: boolean;\n}\n\n/** This function gives the count of the ways to choose `k` of `n`, or Infinity when the count is over `limit`. */\nfunction choices(n: number, k: number, limit: number): number {\n const small = Math.min(k, n - k);\n let count = 1;\n for (let i = 1; i <= small; i++) {\n // The product of i consecutive whole numbers divides by i!, so each step gives a whole number.\n count = (count * (n - small + i)) / i;\n if (count > limit) return Number.POSITIVE_INFINITY;\n }\n return count;\n}\n\n/** This function counts the splits of `pool` into a first group of `size` values that pass the test `extreme`, over each split. */\nfunction countEachSplit(pool: readonly number[], size: number, extreme: (a: readonly number[], b: readonly number[]) => boolean): number {\n const chosen = Array.from({ length: size }, (_, i) => i);\n let count = 0;\n for (;;) {\n const a: number[] = [];\n const b: number[] = [];\n for (const [i, value] of pool.entries()) (chosen[a.length] === i ? a : b).push(value);\n if (extreme(a, b)) count++;\n let place = size - 1;\n while (place >= 0 && chosen[place] === pool.length - size + place) place--;\n if (place < 0) return count;\n let index = (chosen[place] as number) + 1;\n for (let j = place; j < size; j++) chosen[j] = index++;\n }\n}\n\n/**\n * The two-sample permutation test (a split of the pooled values). It needs no normal distribution and no pairs, so it\n * compares groups of different sizes. The p holds only if the values of the two groups can change places under the null.\n *\n * When the count of the splits is `runs` or less, the test reads each split, and the p is exact. Otherwise it draws `runs`\n * random splits. A drawn p has noise: a level of 0.001 is 10 counts at 10 000 runs. So give enough runs for a small level.\n */\nexport function twoSamplePermutation(a: readonly number[], b: readonly number[], options: TwoSamplePermutationOptions = {}): TwoSamplePermutationResult {\n if (a.length === 0 || b.length === 0) throw new RangeError(`twoSamplePermutation: the groups have ${a.length} and ${b.length} values, and each group needs one or more.`);\n const statistic = options.statistic ?? ((x: readonly number[], y: readonly number[]): number => median(x) - median(y));\n const runs = options.runs ?? 10_000;\n if (!Number.isSafeInteger(runs) || runs < 1) throw new RangeError(`twoSamplePermutation: runs is a whole number of 1 or more, not ${runs}.`);\n const observed = statistic(a, b);\n const pool = [...a, ...b];\n // The same tolerance as `pairedPermutation`: a split with the same statistic up to rounding counts as extreme.\n const isExtreme = (x: readonly number[], y: readonly number[]): boolean => Math.abs(statistic(x, y)) >= Math.abs(observed) * (1 - 1e-12);\n const splits = choices(pool.length, a.length, runs);\n if (Number.isFinite(splits)) return { observed, p: countEachSplit(pool, a.length, isExtreme) / splits, runs: splits, exact: true };\n const r = random(options.seed ?? 1);\n let extreme = 0;\n for (let run = 0; run < runs; run++) {\n // The first a.length places of a partial Fisher-Yates shuffle are a uniform choice of the first group.\n for (let i = 0; i < a.length; i++) {\n const j = i + Math.floor(r.next() * (pool.length - i));\n const held = pool[i] as number;\n pool[i] = pool[j] as number;\n pool[j] = held;\n }\n if (isExtreme(pool.slice(0, a.length), pool.slice(a.length))) extreme++;\n }\n return { observed, p: (1 + extreme) / (1 + runs), runs, exact: false };\n}\n\n/**\n * The smallest number of trials `n` at which the Wilson lower end reaches `target`, when the true proportion is\n * `expected`. Each `n` takes `round(expected × n)` successes. The function gives `undefined` when `expected` is not\n * above `target`, or when no `n` up to `max` reaches it. An audit of an agreement uses it to fix its size.\n */\nexport function wilsonSampleSize(target: number, expected: number, z: number = Z95, max = 1_000_000): number | undefined {\n if (!(target >= 0 && target <= 1 && expected >= 0 && expected <= 1)) throw new RangeError(`wilsonSampleSize: target ${target} and expected ${expected} must be from 0 to 1.`);\n whole(\"wilsonSampleSize\", max);\n if (expected <= target) return undefined;\n for (let n = 1; n <= max; n++) if (wilson(Math.round(expected * n), n, z).low >= target) return n;\n return undefined;\n}\n","/** The agreement of two raters that give one category to each item. */\nexport interface Kappa {\n /** The number of items. */\n readonly n: number;\n /** The part of the items where the two raters give the same category. */\n readonly observed: number;\n /** The part of agreement that two independent raters with the same frequencies of categories give. */\n readonly chance: number;\n /** Cohen's kappa: `(observed − chance) / (1 − chance)`. It is `undefined` when `chance` is 1. */\n readonly kappa: number | undefined;\n}\n\n/**\n * Cohen's kappa of two raters (Cohen, 1960). Item `i` has the category `a[i]` from one rater and `b[i]` from the\n * other. Two categories are the same when they are `===`. A kappa of 1 is full agreement, and 0 is the agreement of chance.\n */\nexport function cohenKappa<T>(a: readonly T[], b: readonly T[]): Kappa {\n if (a.length !== b.length) throw new RangeError(`cohenKappa: the raters have ${a.length} and ${b.length} items.`);\n const n = a.length;\n if (n === 0) throw new RangeError(\"cohenKappa: there are no items.\");\n const countA = new Map<T, number>();\n const countB = new Map<T, number>();\n let same = 0;\n for (let i = 0; i < n; i++) {\n const x = a[i] as T;\n const y = b[i] as T;\n if (x === y) same++;\n countA.set(x, (countA.get(x) ?? 0) + 1);\n countB.set(y, (countB.get(y) ?? 0) + 1);\n }\n let chance = 0;\n for (const [category, count] of countA) chance += (count / n) * ((countB.get(category) ?? 0) / n);\n const observed = same / n;\n return { n, observed, chance, kappa: chance === 1 ? undefined : (observed - chance) / (1 - chance) };\n}\n","/**\n * Rank correlation: do two measures put the same items in the same order? Use it to test that a cheap proxy (a\n * predicted cost, a fast measure) orders the items as the real measure does.\n */\nimport { random } from \"@mark1russell7/rigor-generators\";\n\nfunction samePairs(name: string, a: readonly number[], b: readonly number[]): void {\n if (a.length !== b.length) throw new RangeError(`${name}: the lists have ${a.length} and ${b.length} values.`);\n for (const v of a) if (Number.isNaN(v)) throw new RangeError(`${name}: the first list has a NaN.`);\n for (const v of b) if (Number.isNaN(v)) throw new RangeError(`${name}: the second list has a NaN.`);\n}\n\n/** The ranks of the values, from 1. Equal values get the mean of their ranks. */\nexport function ranks(values: readonly number[]): number[] {\n const order = values.map((x, i) => [x, i] as const).sort((p, q) => p[0] - q[0]);\n const out = new Array<number>(values.length);\n for (let i = 0; i < order.length; ) {\n let j = i;\n while (j + 1 < order.length && (order[j + 1] as readonly [number, number])[0] === (order[i] as readonly [number, number])[0]) j++;\n for (let k = i; k <= j; k++) out[(order[k] as readonly [number, number])[1]] = (i + j) / 2 + 1;\n i = j + 1;\n }\n return out;\n}\n\n/**\n * The Spearman rank correlation: the Pearson correlation of the ranks, with mean ranks for ties. The value is from\n * -1 to 1. When one list has no spread, the value is 0. It is equal to the copy in the backtest of highways.\n */\nexport function spearman(a: readonly number[], b: readonly number[]): number {\n samePairs(\"spearman\", a, b);\n const ra = ranks(a);\n const rb = ranks(b);\n const mean = (xs: readonly number[]): number => xs.reduce((s, x) => s + x, 0) / xs.length;\n const ma = mean(ra);\n const mb = mean(rb);\n let num = 0;\n let da = 0;\n let db = 0;\n for (let i = 0; i < ra.length; i++) {\n num += ((ra[i] as number) - ma) * ((rb[i] as number) - mb);\n da += ((ra[i] as number) - ma) ** 2;\n db += ((rb[i] as number) - mb) ** 2;\n }\n return da === 0 || db === 0 ? 0 : num / Math.sqrt(da * db);\n}\n\n/** The largest number of values for which `kendallTau` examines each pair. Above it, a seeded sample of pairs. */\nexport const KENDALL_EXACT = 1500;\nconst KENDALL_SAMPLE = 200_000;\n\n/**\n * The Kendall tau-b of two lists (Kendall, 1938). The value is from -1 to 1. A pair with a tie in both lists does\n * not count. When the lists have fewer than 2 values, or no pair counts, the value is 1. Above `KENDALL_EXACT`\n * values, a seeded sample of 200 000 pairs gives an estimate. It is equal to the copy in highways.\n */\nexport function kendallTau(a: readonly number[], b: readonly number[], seed: number | string = 1): number {\n samePairs(\"kendallTau\", a, b);\n const n = a.length;\n if (n < 2) return 1;\n let concordant = 0;\n let discordant = 0;\n let tieA = 0;\n let tieB = 0;\n const visit = (i: number, j: number): void => {\n const da = Math.sign((a[i] as number) - (a[j] as number));\n const db = Math.sign((b[i] as number) - (b[j] as number));\n if (da === 0 && db === 0) return;\n if (da === 0) tieA++;\n else if (db === 0) tieB++;\n else if (da === db) concordant++;\n else discordant++;\n };\n if (n <= KENDALL_EXACT) {\n for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) visit(i, j);\n } else {\n const r = random(seed);\n for (let k = 0; k < KENDALL_SAMPLE; k++) {\n const i = r.below(n);\n const j = r.below(n);\n if (i !== j) visit(i, j);\n }\n }\n const den = Math.sqrt((concordant + discordant + tieA) * (concordant + discordant + tieB));\n return den === 0 ? 1 : (concordant - discordant) / den;\n}\n","/**\n * The intervals that come from a discrete distribution. The interval of a median or of a quantile comes from the order\n * statistics. The central interval of a count comes from a binomial or a negative binomial distribution.\n */\nimport { sorted } from \"./describe.ts\";\n\nfunction whole(name: string, value: number): void {\n if (!Number.isSafeInteger(value) || value < 0) throw new RangeError(`${name}: ${value} is not a whole number of 0 or more.`);\n}\n\nfunction levelOf(name: string, level: number): number {\n if (!(level > 0 && level < 1)) throw new RangeError(`${name}: the level is more than 0 and less than 1, not ${level}.`);\n return (1 - level) / 2;\n}\n\n/** The chance of each count k from 0 to n of X ~ Binomial(n, p), from the logs of the terms. */\nfunction binomialTerms(n: number, p: number): number[] {\n if (p === 0) return Array.from({ length: n + 1 }, (_, k) => (k === 0 ? 1 : 0));\n if (p === 1) return Array.from({ length: n + 1 }, (_, k) => (k === n ? 1 : 0));\n const [logP, logQ] = [Math.log(p), Math.log1p(-p)];\n const terms: number[] = [];\n let logChoose = 0;\n for (let k = 0; k <= n; k++) {\n if (k > 0) logChoose += Math.log((n - k + 1) / k);\n terms.push(Math.exp(logChoose + k * logP + (n - k) * logQ));\n }\n return terms;\n}\n\n/** The distribution-free interval of a median, from two order statistics of the sample. */\nexport interface MedianInterval {\n readonly low: number;\n readonly high: number;\n /** The rank k of `low`, from 1. The interval is from x_(k) to x_(n + 1 - k) of the sorted values. */\n readonly rank: number;\n /** The chance that the interval holds the median of the population: 1 - 2 P(X <= k - 1), for X ~ Binomial(n, 1/2). */\n readonly coverage: number;\n}\n\n/**\n * The distribution-free interval of the median of a sample. It needs no assumption about the shape of the\n * distribution. It is x_(k) to x_(n + 1 - k), for the largest k whose two tails each hold (1 - level) / 2 or less.\n * For 11 values at the level 0.95, it is x_(2) to x_(10), with the coverage 0.988.\n *\n * A sample of 5 values or fewer has no rank with that coverage. Then the interval is the full range, and `coverage`\n * is less than `level`.\n */\nexport function medianInterval(values: readonly number[], level = 0.95): MedianInterval {\n if (values.length === 0) throw new RangeError(\"medianInterval: the list is empty.\");\n for (const v of values) if (Number.isNaN(v)) throw new RangeError(\"medianInterval: the list has a NaN.\");\n const tail = levelOf(\"medianInterval\", level);\n const s = sorted(values);\n const n = s.length;\n const terms = binomialTerms(n, 0.5);\n // The rank k + 1 is possible if P(X <= k), the tail that it leaves out on each side, is the tail or less.\n let k = 0;\n let below = terms[0] as number;\n while (k + 1 <= n / 2 && below <= tail) {\n k += 1;\n below += terms[k] as number;\n }\n const rank = Math.max(1, k);\n let left = 0;\n for (let i = 0; i < rank; i++) left += terms[i] as number;\n return { low: s[rank - 1] as number, high: s[n - rank] as number, rank, coverage: Math.max(0, 1 - 2 * left) };\n}\n\n/** The distribution-free interval of a quantile, from two order statistics of the sample. */\nexport interface QuantileInterval {\n /** The value x_(lowRank), or `-Infinity` when the sample has no rank for a lower bound. */\n readonly low: number;\n /** The value x_(highRank), or `Infinity` when the sample has no rank for an upper bound. */\n readonly high: number;\n /** The rank of `low`, from 1, or 0 when `low` is `-Infinity`. */\n readonly lowRank: number;\n /** The rank of `high`, from 1, or n + 1 when `high` is `Infinity`. */\n readonly highRank: number;\n /** The chance that the interval holds the quantile of the population. */\n readonly coverage: number;\n}\n\n/**\n * This function gives the distribution-free interval of the quantile `p` of a sample. Each tail outside the interval holds\n * (1 - level) / 2 or less. Let X ~ Binomial(n, p). The lower rank is the largest l with P(X <= l - 1) in the tail. The upper\n * rank is the smallest u with P(X >= u) in the tail. The values must be independent draws, or the coverage is false.\n *\n * A side with no such rank is infinite. Thus a small sample gives no upper bound: refer to `quantileSamples`.\n */\nexport function quantileInterval(values: readonly number[], p: number, level = 0.95): QuantileInterval {\n if (values.length === 0) throw new RangeError(\"quantileInterval: the list is empty.\");\n for (const v of values) if (Number.isNaN(v)) throw new RangeError(\"quantileInterval: the list has a NaN.\");\n if (!(p > 0 && p < 1)) throw new RangeError(`quantileInterval: p is more than 0 and less than 1, not ${p}.`);\n const tail = levelOf(\"quantileInterval\", level);\n const s = sorted(values);\n const n = s.length;\n const terms = binomialTerms(n, p);\n let lowRank = 0;\n let left = 0;\n let below = terms[0] as number;\n while (lowRank < n && below <= tail) {\n lowRank += 1;\n left = below;\n below += terms[lowRank] as number;\n }\n let highRank = n + 1;\n let right = 0;\n let above = terms[n] as number;\n while (highRank > 1 && above <= tail) {\n highRank -= 1;\n right = above;\n above += terms[highRank - 1] as number;\n }\n return {\n low: lowRank === 0 ? -Infinity : (s[lowRank - 1] as number),\n high: highRank === n + 1 ? Infinity : (s[highRank - 1] as number),\n lowRank,\n highRank,\n coverage: Math.max(0, 1 - left - right),\n };\n}\n\n/**\n * This function gives the fewest independent values that give the quantile `p` an upper bound at `level`: the smallest n with\n * p^n <= (1 - level) / 2. With that n, the upper bound is the largest value. At the level 0.95, p95 needs 72 values, p99 needs\n * 368 values and p99.9 needs 3,688 values.\n */\nexport function quantileSamples(p: number, level = 0.95): number {\n if (!(p > 0 && p < 1)) throw new RangeError(`quantileSamples: p is more than 0 and less than 1, not ${p}.`);\n const tail = levelOf(\"quantileSamples\", level);\n const [logTail, logP] = [Math.log(tail), Math.log(p)];\n let n = Math.max(1, Math.ceil(logTail / logP));\n // A float error in the ratio can give one value too many.\n while (n > 1 && (n - 1) * logP <= logTail) n -= 1;\n return n;\n}\n\n/** A central interval of a count, from `low` to `high`, both included. */\nexport interface CountInterval {\n readonly low: number;\n readonly high: number;\n /** The chance of a count from `low` to `high`. It is `level` or more. */\n readonly coverage: number;\n}\n\n/**\n * The central interval of a count X ~ Binomial(n, p). `low` is the smallest k with P(X <= k) > (1 - level) / 2.\n * `high` is the largest k with P(X >= k) > (1 - level) / 2. Each tail outside the interval holds (1 - level) / 2\n * or less. The two tails are separate sums, so that a small upper tail keeps its digits.\n */\nexport function binomialInterval(n: number, p: number, level = 0.95): CountInterval {\n whole(\"binomialInterval\", n);\n if (!(p >= 0 && p <= 1)) throw new RangeError(`binomialInterval: p is from 0 to 1, not ${p}.`);\n const tail = levelOf(\"binomialInterval\", level);\n const terms = binomialTerms(n, p);\n let low = 0;\n let below = terms[0] as number;\n while (low < n && below <= tail) {\n low += 1;\n below += terms[low] as number;\n }\n let high = n;\n let above = terms[n] as number;\n while (high > 0 && above <= tail) {\n high -= 1;\n above += terms[high] as number;\n }\n let coverage = 0;\n for (let k = low; k <= high; k++) coverage += terms[k] as number;\n return { low, high, coverage: Math.min(1, coverage) };\n}\n\n/** The side of `binomialTest`: `\"less\"` gives `P(X <= k)`, and `\"greater\"` gives `P(X >= k)`. */\nexport type BinomialSide = \"less\" | \"greater\";\n\n/**\n * This function gives the p of the exact one-sided binomial test of `k` successes in `n` trials, with\n * X ~ Binomial(n, p). The side `\"less\"` gives `P(X <= k)`. A small value rejects the claim \"the chance is `p` or\n * more\". The side `\"greater\"` gives `P(X >= k)`. A small value rejects the claim \"the chance is `p` or less\".\n *\n * The sum starts at the largest term of the tail, so a small tail keeps its digits. At `p = 1/2`, the side\n * `\"greater\"` is equal to the one-sided `signTest(k, n - k)`.\n *\n * @param k - The count of successes, a whole number from 0 to `n`.\n * @param n - The count of trials, a whole number of 0 or more.\n * @param p - The chance of a success under the claim, from 0 to 1.\n * @param side - The side of the tail.\n * @returns The p of the test, from 0 to 1.\n */\nexport function binomialTest(k: number, n: number, p: number, side: BinomialSide): number {\n whole(\"binomialTest\", k);\n whole(\"binomialTest\", n);\n if (k > n) throw new RangeError(`binomialTest: k ${k} is more than n ${n}.`);\n if (!(p >= 0 && p <= 1)) throw new RangeError(`binomialTest: p is from 0 to 1, not ${p}.`);\n if (side !== \"less\" && side !== \"greater\") throw new RangeError(`binomialTest: side is \"less\" or \"greater\", not ${String(side)}.`);\n const [from, to] = side === \"less\" ? [0, k] : [k, n];\n if (from === 0 && to === n) return 1;\n if (p === 0) return from === 0 ? 1 : 0;\n if (p === 1) return to === n ? 1 : 0;\n const [logP, logQ] = [Math.log(p), Math.log1p(-p)];\n const logs: number[] = [];\n let logChoose = 0;\n for (let i = 0; i <= to; i++) {\n if (i > 0) logChoose += Math.log((n - i + 1) / i);\n if (i >= from) logs.push(logChoose + i * logP + (n - i) * logQ);\n }\n const top = Math.max(...logs);\n const sum = logs.reduce((s, l) => s + Math.exp(l - top), 0);\n return Math.min(1, Math.exp(top) * sum);\n}\n\n/**\n * The central interval of a negative binomial count. X is the count of failures before `successes` successes, and\n * `p` is the chance of a success at each try. `low` is the smallest k with P(X <= k) > (1 - level) / 2.\n * `high` is the smallest k with P(X <= k) >= 1 - (1 - level) / 2.\n */\nexport function negativeBinomialInterval(successes: number, p: number, level = 0.95): CountInterval {\n whole(\"negativeBinomialInterval\", successes);\n if (!(p > 0 && p <= 1)) throw new RangeError(`negativeBinomialInterval: p is more than 0 and 1 or less, not ${p}.`);\n const tail = levelOf(\"negativeBinomialInterval\", level);\n const logQ = Math.log1p(-p);\n let logChance = successes * Math.log(p);\n let below = 0;\n let low = 0;\n for (let k = 0; ; k += 1) {\n const chance = Math.exp(logChance);\n if (below <= tail) low = k;\n if (below + chance >= 1 - tail) {\n let coverage = 0;\n let at = successes * Math.log(p);\n for (let i = 0; i <= k; i++) {\n if (i >= low) coverage += Math.exp(at);\n at += Math.log((i + successes) / (i + 1)) + logQ;\n }\n return { low, high: k, coverage: Math.min(1, coverage) };\n }\n below += chance;\n logChance += Math.log((k + successes) / (k + 1)) + logQ;\n }\n}\n","/**\n * The comparison of a candidate with a baseline, and the calibration of predictions. These functions make two fleet\n * rules into code. First, a change of a default is judged against the current default. The measure is the inputs that\n * gain and the inputs that lose beyond the noise, with the effect size. A sign test alone is not enough. Second, each\n * prediction states a probability, and the Brier score measures how good the stated probabilities were.\n */\nimport { allEqual, median, quantileSorted, sd, sorted } from \"./describe.ts\";\nimport { type Proportion, signTest, wilson } from \"./tests.ts\";\n\nexport interface NoiseOptions {\n /** The number of standard deviations. The default is 2. */\n readonly k?: number;\n /** The fewest values (seeds or folds) that give a floor. The default is 5, the 5-seed rule. */\n readonly minimum?: number;\n /**\n * The margin of practical effect, in the units of the values. A difference that is real but smaller than the margin\n * is too small to matter, so it is not a result. Give the reason of the margin from the problem of the user. The\n * default is 0: no margin.\n */\n readonly margin?: number;\n}\n\n/** The checks of the options of the noise rule. It gives k, the minimum and the margin. */\nfunction noiseOptions(name: string, values: readonly number[], options: NoiseOptions): { k: number; margin: number } {\n const minimum = options.minimum ?? 5;\n if (values.length < minimum) throw new RangeError(`${name}: ${values.length} values; the rule needs ${minimum} or more seeds or folds.`);\n const margin = options.margin ?? 0;\n if (!Number.isFinite(margin) || margin < 0) throw new RangeError(`${name}: the margin is a finite number of 0 or more, not ${margin}.`);\n return { k: options.k ?? 2, margin };\n}\n\n/**\n * The noise floor of a measure: k sample standard deviations of its value over independent seeds or folds. When the\n * margin of practical effect is larger, the floor is the margin. A difference smaller than the floor is not a result.\n */\nexport function noiseFloor(values: readonly number[], options: NoiseOptions = {}): number {\n const { k, margin } = noiseOptions(\"noiseFloor\", values, options);\n return Math.max(k * sd(values), margin);\n}\n\n/**\n * The state of a difference over the seeds. \"gain\" and \"loss\": the mean is beyond the threshold. \"noise\": it is not.\n * \"no-spread\": each seed gives the same value, so the seeds do not sample the noise and the rule tests nothing.\n */\nexport type NoiseState = \"gain\" | \"loss\" | \"noise\" | \"no-spread\";\n\n/** The noise rule of a difference over independent seeds or folds. */\nexport interface NoiseVerdict {\n /** The number of values. */\n readonly n: number;\n readonly mean: number;\n /** The sample standard deviation of the values. */\n readonly sd: number;\n /** k times the standard deviation. */\n readonly spread: number;\n readonly margin: number;\n /** The larger of `spread` and `margin`. The absolute mean must be above it. */\n readonly threshold: number;\n readonly state: NoiseState;\n}\n\n/**\n * The noise rule of a difference (candidate minus baseline) over independent seeds or folds: the mean against\n * max(k standard deviations, margin). With `better: \"lower\"`, a negative mean is the gain. When each value is equal,\n * the state is \"no-spread\" and not a result, also when the mean is beyond the margin. Find out why the seeds do not\n * change the value before you read the difference.\n */\nexport function noiseVerdict(values: readonly number[], options: NoiseOptions & { readonly better?: \"higher\" | \"lower\" } = {}): NoiseVerdict {\n const { k, margin } = noiseOptions(\"noiseVerdict\", values, options);\n const s = sd(values);\n const m = values.reduce((sum, v) => sum + v, 0) / values.length;\n const spread = k * s;\n const threshold = Math.max(spread, margin);\n const up = (options.better ?? \"higher\") === \"higher\" ? m : -m;\n const state: NoiseState = allEqual(values) ? \"no-spread\" : Math.abs(m) <= threshold ? \"noise\" : up > 0 ? \"gain\" : \"loss\";\n return { n: values.length, mean: m, sd: s, spread, margin, threshold, state };\n}\n\nexport interface CompareOptions {\n /** \"higher\" (the default): a ratio above 1 is a gain. \"lower\": a ratio below 1 is a gain, as for a time or a cost. */\n readonly better?: \"higher\" | \"lower\";\n /** A ratio at this distance from 1 or nearer is a tie. The default is 0: only a ratio of exactly 1 is a tie. */\n readonly tie?: number;\n /** A gain or a loss counts only beyond this distance from 1. The default is 0. Use noiseFloor. */\n readonly noise?: number;\n}\n\n/** The effect on the inputs that are not ties. */\nexport interface Effect {\n readonly n: number;\n readonly median: number;\n /** The 0.1 quantile (linear). */\n readonly p10: number;\n /** The 0.9 quantile (linear). */\n readonly p90: number;\n}\n\nexport interface Comparison {\n /** The number of inputs. */\n readonly n: number;\n readonly ties: number;\n /** The inputs where the candidate is better, by any amount. */\n readonly wins: number;\n /** The inputs where the candidate is worse, by any amount. */\n readonly losses: number;\n /** The one-sided sign test of wins against losses. */\n readonly signP: number;\n /** The ratios of the inputs that are not ties, or undefined when each input is a tie. */\n readonly effect: Effect | undefined;\n /** The inputs that gain beyond the noise. */\n readonly gains: number;\n /** The inputs that lose beyond the noise. */\n readonly drops: number;\n /** gains / n, with its Wilson interval. */\n readonly gainShare: number;\n readonly gainInterval: Proportion;\n /** drops / n, with its Wilson interval. */\n readonly dropShare: number;\n readonly dropInterval: Proportion;\n}\n\n/**\n * The comparison of a candidate with a baseline, from the ratio candidate / baseline of each input. It answers the\n * three questions of a promotion. How often is the candidate better? By how much? How often is it worse beyond the\n * noise? A promotion reads `gains` against `drops` and `effect`, not `signP` alone, because a sign test counts a\n * win of any size.\n */\nexport function compareRatios(ratios: readonly number[], options: CompareOptions = {}): Comparison {\n if (ratios.length === 0) throw new RangeError(\"compareRatios: the list is empty.\");\n const sign = (options.better ?? \"higher\") === \"higher\" ? 1 : -1;\n const tie = options.tie ?? 0;\n const noise = options.noise ?? 0;\n if (!(tie >= 0) || !(noise >= 0)) throw new RangeError(\"compareRatios: tie and noise are 0 or more.\");\n let ties = 0;\n let wins = 0;\n let losses = 0;\n let gains = 0;\n let drops = 0;\n const changed: number[] = [];\n for (const ratio of ratios) {\n if (!Number.isFinite(ratio)) throw new RangeError(`compareRatios: each ratio is a finite number, not ${ratio}.`);\n const d = sign * (ratio - 1);\n if (Math.abs(ratio - 1) <= tie) {\n ties++;\n continue;\n }\n changed.push(ratio);\n if (d > 0) wins++;\n else losses++;\n if (d > noise) gains++;\n else if (-d > noise) drops++;\n }\n const n = ratios.length;\n const s = sorted(changed);\n const effect = s.length === 0 ? undefined : { n: s.length, median: median(s), p10: quantileSorted(s, 0.1), p90: quantileSorted(s, 0.9) };\n return {\n n,\n ties,\n wins,\n losses,\n signP: signTest(wins, losses),\n effect,\n gains,\n drops,\n gainShare: gains / n,\n gainInterval: wilson(gains, n),\n dropShare: drops / n,\n dropInterval: wilson(drops, n),\n };\n}\n\n/** A prediction: the stated probability that the claim holds, and if it held. */\nexport interface Forecast {\n readonly p: number;\n readonly hit: boolean;\n}\n\nfunction checkedForecasts(name: string, forecasts: readonly Forecast[]): void {\n if (forecasts.length === 0) throw new RangeError(`${name}: the list is empty.`);\n for (const f of forecasts) if (!(f.p >= 0 && f.p <= 1)) throw new RangeError(`${name}: each p is from 0 to 1, not ${f.p}.`);\n}\n\n/** The Brier score: the mean of (p - outcome)^2. 0 is perfect, and 0.25 is a constant 0.5. Lower is better. */\nexport function brier(forecasts: readonly Forecast[]): number {\n checkedForecasts(\"brier\", forecasts);\n let sum = 0;\n for (const f of forecasts) sum += (f.p - (f.hit ? 1 : 0)) ** 2;\n return sum / forecasts.length;\n}\n\n/**\n * The log-loss of predictions: the mean of `-ln(p)` for a hit and `-ln(1 - p)` for a miss. 0 is perfect, and\n * `ln(2)` is a constant 0.5. Lower is better. A p of 0 for a hit gives Infinity. For an outcome of three values,\n * give the probability of the observed outcome as `p`, with `hit` true.\n */\nexport function logLoss(forecasts: readonly Forecast[]): number {\n checkedForecasts(\"logLoss\", forecasts);\n let sum = 0;\n for (const f of forecasts) sum -= Math.log(f.hit ? f.p : 1 - f.p);\n return sum / forecasts.length;\n}\n\n/** The predictions of one stated level. */\nexport interface CalibrationLevel {\n readonly stated: number;\n readonly n: number;\n readonly hits: number;\n /** hits / n. A calibrated level has a rate near `stated`. */\n readonly rate: number;\n /** The Wilson interval of the rate. A level is overconfident when `stated` is above it. */\n readonly interval: Proportion;\n}\n\n/** The hit rate of each stated level, from the lowest level. */\nexport function calibration(forecasts: readonly Forecast[]): CalibrationLevel[] {\n checkedForecasts(\"calibration\", forecasts);\n const levels = new Map<number, { n: number; hits: number }>();\n for (const f of forecasts) {\n const level = levels.get(f.p) ?? { n: 0, hits: 0 };\n level.n++;\n if (f.hit) level.hits++;\n levels.set(f.p, level);\n }\n return [...levels]\n .sort((a, b) => a[0] - b[0])\n .map(([stated, { n, hits }]) => ({ stated, n, hits, rate: hits / n, interval: wilson(hits, n) }));\n}\n","/**\n * The count of values that a comparison of options needs before it starts. The Student t law gives this count, because the\n * normal formula is too low at a small count. These functions make no draws, so a caller reads the count with no bench.\n */\n\n/** The log of the gamma function, by the form of Lanczos with 6 terms. The argument is above 0. */\nfunction logGamma(x: number): number {\n const terms = [76.18009172947146, -86.50532032941677, 24.01409824083091, -1.231739572450155, 0.1208650973866179e-2, -0.5395239384953e-5];\n const base = x + 5.5 - (x + 0.5) * Math.log(x + 5.5);\n let series = 1.000000000190015;\n terms.forEach((term, i) => {\n series += term / (x + i + 1);\n });\n return -base + Math.log((2.5066282746310007 * series) / x);\n}\n\n/** The continued fraction of the incomplete beta function, by the method of Lentz. */\nfunction betaFraction(x: number, a: number, b: number): number {\n const tiny = 1e-300;\n const guard = (value: number): number => (Math.abs(value) < tiny ? tiny : value);\n let c = 1;\n let d = 1 / guard(1 - ((a + b) * x) / (a + 1));\n let h = d;\n for (let m = 1; m <= 500; m++) {\n const twice = 2 * m;\n const even = (m * (b - m) * x) / ((a + twice - 1) * (a + twice));\n d = 1 / guard(1 + even * d);\n c = guard(1 + even / c);\n h *= d * c;\n const odd = (-(a + m) * (a + b + m) * x) / ((a + twice) * (a + twice + 1));\n d = 1 / guard(1 + odd * d);\n c = guard(1 + odd / c);\n const step = d * c;\n h *= step;\n if (Math.abs(step - 1) < 1e-15) return h;\n }\n return h;\n}\n\n/** The regularized incomplete beta function at `x`, from 0 to 1. */\nfunction incompleteBeta(x: number, a: number, b: number): number {\n if (x <= 0) return 0;\n if (x >= 1) return 1;\n const front = Math.exp(logGamma(a + b) - logGamma(a) - logGamma(b) + a * Math.log(x) + b * Math.log(1 - x));\n return x < (a + 1) / (a + b + 2) ? (front * betaFraction(x, a, b)) / a : 1 - (front * betaFraction(1 - x, b, a)) / b;\n}\n\n/** The share of the Student t law with `df` degrees of freedom below `t`, for `t` of 0 or more. */\nfunction upperHalf(t: number, df: number): number {\n return 1 - 0.5 * incompleteBeta(df / (df + t * t), df / 2, 0.5);\n}\n\n/**\n * This function gives the quantile of the Student t law, from a bisection of its distribution function.\n *\n * @param p - The share of the law below the result, above 0 and below 1.\n * @param df - The degrees of freedom, above 0.\n */\nexport function tQuantile(p: number, df: number): number {\n if (!(p > 0 && p < 1)) throw new RangeError(`tQuantile: p is above 0 and below 1, not ${p}.`);\n if (!(df > 0 && Number.isFinite(df))) throw new RangeError(`tQuantile: df is a finite number above 0, not ${df}.`);\n if (p < 0.5) return -tQuantile(1 - p, df);\n let high = 1;\n while (upperHalf(high, df) < p) high *= 2;\n let low = 0;\n for (let step = 0; step < 200 && high - low > 1e-12 * high; step++) {\n const middle = (low + high) / 2;\n if (upperHalf(middle, df) < p) low = middle;\n else high = middle;\n }\n return (low + high) / 2;\n}\n\n/** The options of `optionFloor`. */\nexport interface OptionFloorOptions {\n /** The standard deviation of one value about the mean of its option. All options have the same value. */\n readonly sigma: number;\n /** The smallest difference between the means of two options that the comparison finds. */\n readonly delta: number;\n /** The count of tests in the family. The level of each test is `alpha / tests`. */\n readonly tests: number;\n /** The two-sided level of the family. The default is 0.05. */\n readonly alpha?: number;\n /** The share of comparisons that find a difference of `delta`. The default is 0.8. */\n readonly power?: number;\n}\n\n/**\n * This function gives the smallest count of values for each of two options. With it, one test finds a difference of\n * `delta` with the stated power. The form is `n = 2 ((t(1 - alpha / (2 tests), df) + t(power, df)) sigma / delta)^2`,\n * with `df = 2 n - 2`. The count is on both sides of that form, so the function takes the first count that meets it.\n *\n * The function assumes independent values, unpaired groups of equal size, equal `sigma`, and a Bonferroni family.\n * Holm gives each test a level of `alpha / tests` or more. Thus for a Holm family the count is an upper bound, not the exact count.\n * The tests read the power by simulation: 2,000 draws at the floor for 1, 5 and 67 tests, from the fixed seeds `rigor-statistics/optionFloor/at/<tests>`.\n * Each read gives 0.78 or more, and one count below the floor gives less.\n * A value of `sigma` from an older run gives a count for that run. Read `sigma` again on the new values.\n *\n * @param options - The spread, the difference, the family and the targets.\n * @returns A whole number of 2 or more.\n */\nexport function optionFloor(options: OptionFloorOptions): number {\n const { sigma, delta, tests, alpha = 0.05, power = 0.8 } = options;\n if (!(sigma > 0 && Number.isFinite(sigma))) throw new RangeError(`optionFloor: sigma is a finite number above 0, not ${sigma}.`);\n if (!(delta > 0 && Number.isFinite(delta))) throw new RangeError(`optionFloor: delta is a finite number above 0, not ${delta}.`);\n if (!Number.isSafeInteger(tests) || tests < 1) throw new RangeError(`optionFloor: tests is a whole number of 1 or more, not ${tests}.`);\n if (!(alpha > 0 && alpha < 1)) throw new RangeError(`optionFloor: alpha is above 0 and below 1, not ${alpha}.`);\n if (!(power > 0.5 && power < 1)) throw new RangeError(`optionFloor: power is above 0.5 and below 1, not ${power}.`);\n const level = 1 - alpha / (2 * tests);\n for (let n = 2; n < 1e7; n++) {\n const df = 2 * n - 2;\n const need = 2 * (((tQuantile(level, df) + tQuantile(power, df)) * sigma) / delta) ** 2;\n if (n >= need) return n;\n }\n throw new RangeError(`optionFloor: no count under 10,000,000 for sigma ${sigma} and delta ${delta}.`);\n}\n","/**\n * The rule that finds the smallest sample at which an interval method keeps its level. The input is the hits of the\n * method on the true value in seeded cells. The bar is fixed before the run.\n */\nimport { binomialTest } from \"./discrete.ts\";\nimport { type Proportion, Z95, holm, wilson } from \"./tests.ts\";\n\n/** One cell of a coverage study: the hits of a method on the true value in `draws` seeded samples of size `sample`. */\nexport interface CoverageCell {\n /** The name of the cell, for example `\"skewed 120/108\"`. The result names the rejected cells with it. */\n readonly name: string;\n /** The sample size `m` of the cell, a whole number of 1 or more. */\n readonly sample: number;\n /** The count of samples whose interval holds the true value, a whole number from 0 to `draws`. */\n readonly hits: number;\n /** The count of samples of the cell, a whole number of 1 or more. */\n readonly draws: number;\n}\n\n/** The bar of `coverageMinSample`. Fix it before the run, and do not change it after the run. */\nexport interface CoverageBar {\n /** The coverage that the method claims, for example 0.95. Each cell has a one-sided exact binomial test of it. */\n readonly level: number;\n /** The level of the Holm family of the cell tests, for example 0.05. */\n readonly alpha: number;\n /** The smallest Wilson lower end of the pooled coverage, for example 0.94. */\n readonly pooledLow: number;\n /** The z of the Wilson interval. The default is `Z95`. */\n readonly z?: number;\n}\n\n/** The reason of one step: `\"qualifies\"`, or the test or tests that failed. */\nexport type CoverageReason = \"qualifies\" | \"cell-rejected\" | \"pooled-low\" | \"cell-rejected-and-pooled-low\";\n\n/** The result of the bar at one sample size `m`, over each cell with a sample of `m` or more. */\nexport interface CoverageStep {\n /** The sample size `m` of the step. */\n readonly sample: number;\n /** The count of cells with a sample of `m` or more. */\n readonly cells: number;\n /** The names of the cells that reject the coverage `level`, after the Holm correction. */\n readonly rejected: readonly string[];\n /** The smallest Holm-adjusted p of the cells of the step. */\n readonly smallestAdjusted: number;\n /** The sum of the hits of the cells of the step. */\n readonly hits: number;\n /** The sum of the draws of the cells of the step. */\n readonly draws: number;\n /** The Wilson interval of the pooled coverage `hits / draws`. */\n readonly pooled: Proportion;\n /** The sample size `m` passes the two tests of the bar. */\n readonly qualifies: boolean;\n readonly reason: CoverageReason;\n}\n\n/** The result of `coverageMinSample`. */\nexport interface CoverageMinSample {\n /**\n * The smallest sample size `m` of the cells such that each size of `m` or more passes the bar. It is infinite when\n * the largest size fails.\n */\n readonly minSample: number;\n /** The largest sample size that fails the bar. It blocks each smaller size. The result has no `blocking` when each size passes. */\n readonly blocking?: number;\n /** One step for each sample size of the cells, from the smallest to the largest. */\n readonly steps: readonly CoverageStep[];\n}\n\nfunction whole(name: string, value: number, min: number): void {\n if (!Number.isSafeInteger(value) || value < min) throw new RangeError(`coverageMinSample: ${name} is a whole number of ${min} or more, not ${value}.`);\n}\n\n/**\n * This function applies a fixed bar of coverage to the cells of a study. It gives the smallest sample size `m` from\n * which an interval method keeps its level. The method qualifies at `m` when the cells with a sample of `m` or more\n * pass two tests:\n *\n * 1. No cell rejects the coverage `level`. Each cell has the exact one-sided binomial test `P(X <= hits)`, with\n * X ~ Binomial(draws, level). The family of these tests gets the Holm correction at `alpha`.\n * 2. The Wilson lower end of the pooled coverage, the sum of the hits over the sum of the draws, is `pooledLow`\n * or more.\n *\n * Each step tells the result of the two tests at its `m`. A step does not depend on the steps of other sizes. At a\n * small `m`, the pool also holds the cells of the larger sizes. Thus a small `m` can pass while a larger `m` fails\n * alone, for example near `m = n`.\n *\n * Thus the set of sizes is closed upward. The result is the smallest `m` of the cells such that each size of `m` or\n * more qualifies. The field `blocking` gives the largest size that fails. When the largest size fails, the result is\n * infinite.\n *\n * @param cells - The hits and the draws of each cell. Each cell has its own sample size.\n * @param bar - The level, the alpha of the Holm family and the pooled lower end.\n * @returns The smallest size from which each size qualifies, the size that blocks, and the result at each size.\n */\nexport function coverageMinSample(cells: readonly CoverageCell[], bar: CoverageBar): CoverageMinSample {\n const { level, alpha, pooledLow } = bar;\n const z = bar.z ?? Z95;\n if (!(level > 0 && level < 1)) throw new RangeError(`coverageMinSample: level is more than 0 and less than 1, not ${level}.`);\n if (!(alpha > 0 && alpha < 1)) throw new RangeError(`coverageMinSample: alpha is more than 0 and less than 1, not ${alpha}.`);\n if (!(pooledLow >= 0 && pooledLow <= 1)) throw new RangeError(`coverageMinSample: pooledLow is from 0 to 1, not ${pooledLow}.`);\n if (!(z > 0 && Number.isFinite(z))) throw new RangeError(`coverageMinSample: z is a finite number more than 0, not ${z}.`);\n for (const cell of cells) {\n whole(\"sample\", cell.sample, 1);\n whole(\"draws\", cell.draws, 1);\n whole(\"hits\", cell.hits, 0);\n if (cell.hits > cell.draws) throw new RangeError(`coverageMinSample: the hits ${cell.hits} of the cell ${cell.name} are more than its draws ${cell.draws}.`);\n }\n const p = cells.map((cell) => binomialTest(cell.hits, cell.draws, level, \"less\"));\n const sizes = [...new Set(cells.map((cell) => cell.sample))].sort((a, b) => a - b);\n const steps = sizes.map((m): CoverageStep => {\n const at = cells.map((cell, i) => ({ cell, p: p[i] as number })).filter(({ cell }) => cell.sample >= m);\n const corrected = holm(\n at.map(({ p: value }) => value),\n alpha,\n );\n const rejected = at.filter((_, i) => corrected[i]?.reject === true).map(({ cell }) => cell.name);\n const smallestAdjusted = Math.min(...corrected.map((c) => c.adjusted));\n let hits = 0;\n let draws = 0;\n for (const { cell } of at) {\n hits += cell.hits;\n draws += cell.draws;\n }\n const pooled = wilson(hits, draws, z);\n const cellOk = rejected.length === 0;\n const pooledOk = pooled.low >= pooledLow;\n const reason: CoverageReason = cellOk ? (pooledOk ? \"qualifies\" : \"pooled-low\") : pooledOk ? \"cell-rejected\" : \"cell-rejected-and-pooled-low\";\n return { sample: m, cells: at.length, rejected, smallestAdjusted, hits, draws, pooled, qualifies: cellOk && pooledOk, reason };\n });\n // The set is closed upward: read the steps from the largest size down, and stop at the first size that fails.\n let minSample = Number.POSITIVE_INFINITY;\n let blocking: number | undefined;\n for (let i = steps.length - 1; i >= 0; i--) {\n const step = steps[i] as CoverageStep;\n if (!step.qualifies) {\n blocking = step.sample;\n break;\n }\n minSample = step.sample;\n }\n return blocking === undefined ? { minSample, steps } : { minSample, blocking, steps };\n}\n","/**\n * The interval of a U-statistic from a uniform sample of `m` of `n` units, drawn without replacement. A kernel `h`\n * gives a value to each set of `r` units. The total of the population is the sum of `h` over all its sets of `r`.\n */\nimport { tQuantile } from \"./power.ts\";\n\n/** The methods of `uStatisticInterval`. The method `\"auto\"` selects one of the other two for each sample. */\nexport type UStatisticMethod = \"conservative\" | \"tight\" | \"auto\";\n\n/**\n * The smallest sample `m` at which the method `\"auto\"` uses the method `\"tight\"`. The calibration study\n * `u-statistic-interval` gives the value with `coverageMinSample`. The value is the smallest `m` of the grid such that\n * each `m` of the grid from this value up passes the bar. Until a run of the study gives a value, the value is\n * infinite. The TSDoc of `uStatisticInterval` gives the bar of the study.\n */\nexport const U_STATISTIC_TIGHT_MIN_SAMPLE: number = Number.POSITIVE_INFINITY;\n\n/** The options of `uStatisticInterval`. */\nexport interface UStatisticOptions {\n /** The order `r` of the kernel: the number of units in each set. It is a whole number of 1 or more. */\n readonly order: number;\n /** The number of units in the whole population, `n`. It is a whole number, and it is not less than the sample. */\n readonly population: number;\n /** The method of the interval. The methods `\"conservative\"` and `\"auto\"` need `range`. */\n readonly method: UStatisticMethod;\n /** The level of the interval. The default is 0.95. */\n readonly level?: number;\n /** The smallest and the largest value of the kernel. With it, the interval stays in this range. */\n readonly range?: readonly [low: number, high: number];\n}\n\n/** The mean of the kernel over all the sets of `r` units of the population, with its interval. */\nexport interface UStatisticMean {\n /** The U-statistic: the mean of the kernel over the sets of `r` units of the sample. */\n readonly estimate: number;\n readonly low: number;\n readonly high: number;\n}\n\n/** The result of `uStatisticInterval`. The total is the mean of the kernel times `subsets`. */\nexport interface UStatisticInterval {\n /** The estimate of the total of the population: `S * C(n, r) / C(m, r)`, with `S` the total of the sample. */\n readonly estimate: number;\n readonly low: number;\n readonly high: number;\n readonly level: number;\n /** The method that made the interval. It is not `requested` after a fallback or a choice of the method `\"auto\"`. */\n readonly method: \"conservative\" | \"tight\";\n /** The method of the options. */\n readonly requested: UStatisticMethod;\n /** The mean of the kernel, with its interval. */\n readonly mean: UStatisticMean;\n /** The number of sets of `r` units in the population, `C(n, r)`. */\n readonly subsets: number;\n /** The standard error of the total. Only an interval of the method `\"tight\"` has it. */\n readonly standardError?: number;\n /** The degrees of freedom of the t quantile, `m - 1`. Only an interval of the method `\"tight\"` has it. */\n readonly df?: number;\n}\n\n/**\n * This function gives the interval of a total over all the sets of `r` units of a population. The data is a uniform\n * sample of `m` of the `n` units, without replacement. An example is the count of crossings between all pairs of\n * routes. The input is the total of each sampled unit: the sum of the kernel over the sets of `r` sampled units\n * that hold the unit. Thus the sum of the totals is `r * S`, with `S` the total of the sample. The kernel is\n * symmetric.\n *\n * The estimate is `S * C(n, r) / C(m, r)`. It is the U-statistic `U = S / C(m, r)` times `C(n, r)`. At `r = 1`,\n * the estimate is `n / m` times the sum of the sample. When `m` is `n`, the interval is the estimate.\n *\n * The method `\"conservative\"` uses the inequality of Hoeffding (1963) for U-statistics, with `k = floor(m / r)`. The\n * half width of the mean is `(b - a) * sqrt(ln(2 / (1 - level)) / (2 k))`, with `[a, b]` the range of the kernel.\n * The bound is also true for a sample without replacement (Ai, Kuželka and Wang 2022, Blanc 2023 Theorem 6).\n * Thus the interval holds at each `m`. It is wide at a small `m`.\n *\n * The method `\"tight\"` uses the jackknife variance of `U`, from the totals only, times the finite population\n * correction `1 - m / n`. The interval is `U` plus or minus the t quantile with `m - 1` degrees of freedom, times\n * the standard error.\n *\n * The correction comes from the inclusion probabilities of a sample without replacement. The variance of the linear\n * part of `U` (its Hájek projection) gets exactly the factor `1 - m / n`. The variance of the remainder gets a\n * smaller factor, near `(1 - m / n)^2`, relative to an independent sample. For `r = 2` this factor is\n * `(n - m)(n - m - 1) / ((n - 2)(n - 3))`. Thus this estimate of the variance is exact for a linear kernel, and\n * larger than the variance for other kernels. The tests read the two facts over all samples of small populations.\n *\n * The method `\"tight\"` does not give an interval of width 0 when `m` is less than `n`. When all the totals are\n * equal, the jackknife variance is 0. Then the function uses the method `\"conservative\"` for the sample, and the\n * result has `method: \"conservative\"`. Without `range`, the function throws a `RangeError` for this sample.\n *\n * The method `\"tight\"` has no proof of its coverage. The tests use 200 samples of made-up populations at the level\n * 0.95. The table gives the hits of 200 for each population `n` and sample `m`. Each count includes the fallback.\n *\n * | n / m | sparse | crossings | skewed |\n * | --- | --- | --- | --- |\n * | 40 / 8 | 200 | 200 | 183 |\n * | 40 / 10 | 200 | 200 | 187 |\n * | 40 / 12 | 200 | 183 | 189 |\n * | 40 / 20 | 180 | 183 | 188 |\n * | 40 / 36 | 192 | 189 | 193 |\n * | 60 / 8 | 200 | 200 | 181 |\n * | 60 / 10 | 200 | 200 | 180 |\n * | 60 / 12 | 200 | 195 | 186 |\n * | 60 / 20 | 184 | 190 | 183 |\n * | 60 / 40 | 186 | 193 | 180 |\n * | 120 / 8 | 200 | 200 | 177 |\n * | 120 / 10 | 200 | 192 | 175 |\n * | 120 / 12 | 200 | 189 | 178 |\n * | 120 / 20 | 191 | 193 | 182 |\n * | 120 / 40 | 194 | 192 | 185 |\n * | 120 / 60 | 195 | 189 | 185 |\n * | 120 / 108 | 187 | 185 | 190 |\n *\n * The sparse kernel holds 2% to 3% of the pairs. The skewed kernel has a few large values. At `m = 8`, the skewed\n * kernel gets 177 to 183 of 200, a coverage of 0.885 to 0.915. No row has 190 or more in each kernel.\n *\n * The method `\"auto\"` needs `range`. It uses the method `\"tight\"` when `m` is `U_STATISTIC_TIGHT_MIN_SAMPLE` or more\n * and the variance is more than 0. Otherwise, it uses the method `\"conservative\"`.\n *\n * The calibration study `u-statistic-interval` sets `U_STATISTIC_TIGHT_MIN_SAMPLE`. Its bar was fixed before its run.\n * The study draws 1000 samples in each cell of the 3 kernels and the 17 cells of the table. The method `\"tight\"`\n * qualifies at `m` when the cells with a sample of `m` or more pass two tests.\n *\n * First, no cell rejects the coverage 0.95 in a one-sided exact binomial test at alpha 0.05, with the Holm\n * correction over these cells. Second, the Wilson lower end of the pooled coverage of these cells is 0.94 or more.\n * `coverageMinSample` applies this bar.\n *\n * The set of sizes is closed upward. The constant is the smallest `m` of the grid such that each `m` of the grid from\n * this value up qualifies. A small `m` pools the good cells of the larger sizes, so it can pass while a larger `m`\n * fails alone. The upward rule keeps the method `\"auto\"` away from a size that failed.\n *\n * When the largest `m` fails, the constant is infinite. Until a run of the study gives a value, the constant is infinite. Thus the method `\"auto\"`\n * uses the method `\"conservative\"` at each `m` less than `n`.\n *\n * With `range`, the interval of the mean stays in `[a, b]`, and each total is in the range of a sum of\n * `C(m - 1, r - 1)` kernel values.\n *\n * @param totals - The total of each unit of the sample. The sample has more units than `r`.\n * @param options - The order, the population, the method, the level and the range of the kernel.\n * @returns The estimate and the interval of the total, and of the mean of the kernel.\n */\nexport function uStatisticInterval(totals: readonly number[], options: UStatisticOptions): UStatisticInterval {\n const name = \"uStatisticInterval\";\n const { order: r, population: n, method: requested } = options;\n const m = totals.length;\n const level = options.level ?? 0.95;\n if (!Number.isSafeInteger(r) || r < 1) throw new RangeError(`${name}: order is a whole number of 1 or more, not ${r}.`);\n if (m <= r) throw new RangeError(`${name}: the sample has more units than the order ${r}, not ${m}.`);\n if (!Number.isSafeInteger(n) || n < m) throw new RangeError(`${name}: population is a whole number of ${m} (the sample) or more, not ${n}.`);\n if (requested !== \"conservative\" && requested !== \"tight\" && requested !== \"auto\") {\n throw new RangeError(`${name}: method is \"conservative\", \"tight\" or \"auto\", not ${String(requested)}.`);\n }\n if (!(level > 0 && level < 1)) throw new RangeError(`${name}: level is more than 0 and less than 1, not ${level}.`);\n for (const t of totals) if (!Number.isFinite(t)) throw new RangeError(`${name}: each total is a finite number, not ${t}.`);\n const range = options.range;\n if (range !== undefined) {\n const [a, b] = range;\n if (!(Number.isFinite(a) && Number.isFinite(b) && a < b)) throw new RangeError(`${name}: range is two finite numbers a < b, not ${a} and ${b}.`);\n const sets = choose(m - 1, r - 1);\n const slack = 1e-9 * Math.max(Math.abs(a), Math.abs(b)) * sets;\n for (const t of totals) {\n if (t < a * sets - slack || t > b * sets + slack) throw new RangeError(`${name}: each total is from ${a * sets} to ${b * sets} for this range, not ${t}.`);\n }\n } else if (requested !== \"tight\") {\n throw new RangeError(`${name}: the method \"${requested}\" needs the range of the kernel.`);\n }\n\n let sum = 0;\n for (const t of totals) sum += t;\n const s = sum / r;\n const subsets = choose(n, r);\n const sampleSets = choose(m, r);\n const estimate = (s * subsets) / sampleSets;\n const u = s / sampleSets;\n const base = { estimate, level, requested, subsets };\n\n // The jackknife variance of U. It is 0 when all the totals are equal.\n const centre = sum / m;\n let squares = 0;\n for (const t of totals) squares += (t - centre) ** 2;\n const equal = totals.every((t) => t === totals[0]);\n const variance = equal ? 0 : ((1 - m / n) * ((m - 1) / m) * squares) / choose(m - 1, r) ** 2;\n\n if (m === n) {\n const method = requested === \"conservative\" || (requested === \"auto\" && m < U_STATISTIC_TIGHT_MIN_SAMPLE) ? \"conservative\" : \"tight\";\n return { ...base, low: estimate, high: estimate, method, mean: { estimate: u, low: u, high: u }, ...(method === \"tight\" ? { standardError: 0, df: m - 1 } : {}) };\n }\n const useTight = requested === \"tight\" || (requested === \"auto\" && m >= U_STATISTIC_TIGHT_MIN_SAMPLE);\n if (useTight && variance > 0) {\n const df = m - 1;\n const se = Math.sqrt(variance);\n const half = tQuantile(1 - (1 - level) / 2, df) * se;\n return { ...base, method: \"tight\", ...ends(u, u - half, u + half, range, subsets), standardError: se * subsets, df };\n }\n if (range === undefined) {\n throw new RangeError(`${name}: the jackknife variance is 0, because all the totals are equal. Give the range, or use the method \"conservative\".`);\n }\n const k = Math.floor(m / r);\n const half = (range[1] - range[0]) * Math.sqrt(Math.log(2 / (1 - level)) / (2 * k));\n return { ...base, method: \"conservative\", ...ends(u, u - half, u + half, range, subsets) };\n}\n\n/** This function gives the interval of the mean in the range, if there is a range, and scales it to the total. */\nfunction ends(\n u: number,\n lowMean: number,\n highMean: number,\n range: readonly [number, number] | undefined,\n subsets: number,\n): Pick<UStatisticInterval, \"low\" | \"high\" | \"mean\"> {\n const low = range ? Math.max(range[0], lowMean) : lowMean;\n const high = range ? Math.min(range[1], highMean) : highMean;\n return { low: low * subsets, high: high * subsets, mean: { estimate: u, low, high } };\n}\n\n/** The binomial coefficient `C(n, k)`, as a product. Each step is a whole number, so it is exact below 2^53. */\nfunction choose(n: number, k: number): number {\n let c = 1;\n for (let j = 0; j < k; j++) c = (c * (n - j)) / (j + 1);\n return c;\n}\n","/**\n * The ratings of pairwise results. This module gives the Elo update and the Glicko-2 update of one rating period. It\n * also gives the probabilities of a pair under the Bradley-Terry model with Davidson ties, and the conversion between\n * a log-strength and a rating. Each function is pure. It changes no input, and the same inputs give the same result.\n */\n\n/** The scale of a rating. A difference of `scale` points gives odds of `base` to 1. */\nexport interface RatingScale {\n /** The rating of the log-strength 0. The default is 1500. Elo uses only differences, so it does not read it. */\n readonly center?: number;\n /** The number of points that gives odds of `base` to 1. The default is 400. */\n readonly scale?: number;\n /** The base of the odds. The default is 10. */\n readonly base?: number;\n}\n\n/** The options of an Elo update. */\nexport interface EloOptions extends RatingScale {\n /** The largest change of a rating after one result (the K factor). The default is 32. */\n readonly k?: number;\n}\n\n/** The ratings of a pair after one result. */\nexport interface EloUpdate {\n /** The new rating of the first item. */\n readonly a: number;\n /** The new rating of the second item. */\n readonly b: number;\n /** The expected score of the first item before the result. */\n readonly expected: number;\n}\n\nfunction finite(name: string, label: string, value: number): void {\n if (!Number.isFinite(value)) throw new RangeError(`${name}: ${label} is a finite number, not ${value}.`);\n}\n\nfunction positive(name: string, label: string, value: number): void {\n if (!(value > 0 && Number.isFinite(value))) throw new RangeError(`${name}: ${label} is a finite number above 0, not ${value}.`);\n}\n\nfunction checkedScale(name: string, options: RatingScale): { center: number; scale: number; base: number } {\n const center = options.center ?? 1500;\n const scale = options.scale ?? 400;\n const base = options.base ?? 10;\n finite(name, \"the center\", center);\n positive(name, \"the scale\", scale);\n if (!(base > 1 && Number.isFinite(base))) throw new RangeError(`${name}: the base is a finite number above 1, not ${base}.`);\n return { center, scale, base };\n}\n\n/**\n * The expected score of the first item against the second item: `1 / (1 + base ** ((rb - ra) / scale))`. A win\n * counts 1, a tie 0.5 and a loss 0. The expected score of the second item is 1 minus this value.\n */\nexport function eloExpected(ra: number, rb: number, options: RatingScale = {}): number {\n finite(\"eloExpected\", \"the first rating\", ra);\n finite(\"eloExpected\", \"the second rating\", rb);\n const { scale, base } = checkedScale(\"eloExpected\", options);\n return 1 / (1 + base ** ((rb - ra) / scale));\n}\n\n/**\n * The Elo update of a pair after one result. The `score` is the score of the first item: 1 for a win, 0.5 for a tie\n * and 0 for a loss. Each rating moves by `k` times the difference between the score and the expected score. Thus\n * the sum of the two ratings does not change.\n */\nexport function eloUpdate(ra: number, rb: number, score: number, options: EloOptions = {}): EloUpdate {\n if (!(score >= 0 && score <= 1)) throw new RangeError(`eloUpdate: the score is from 0 to 1, not ${score}.`);\n const k = options.k ?? 32;\n if (!(k >= 0 && Number.isFinite(k))) throw new RangeError(`eloUpdate: k is a finite number of 0 or more, not ${k}.`);\n const expected = eloExpected(ra, rb, options);\n const change = k * (score - expected);\n return { a: ra + change, b: rb - change, expected };\n}\n\n/** A Glicko-2 rating on the Glicko scale: the rating, the rating deviation (RD) and the volatility. */\nexport interface Glicko2Rating {\n readonly rating: number;\n /** The rating deviation, in rating points. It is above 0. */\n readonly rd: number;\n /** The volatility: the expected size of a change of the true strength in one rating period. It is above 0. */\n readonly volatility: number;\n}\n\n/** One game of a rating period: the rating and the RD of the opponent, and the score of the player. */\nexport interface Glicko2Game {\n readonly rating: number;\n readonly rd: number;\n /** The score of the player: 1 for a win, 0.5 for a tie and 0 for a loss. */\n readonly score: number;\n}\n\n/** The options of a Glicko-2 update. */\nexport interface Glicko2Options {\n /** The constraint on the change of the volatility over time (tau). The default is 0.5. Glickman uses 0.3 to 1.2. */\n readonly tau?: number;\n /** The tolerance of the iteration for the new volatility (epsilon). The default is 0.000001, as in the paper. */\n readonly tolerance?: number;\n}\n\n/** The factor between the Glicko scale and the Glicko-2 scale: `400 / ln(10)`, to 4 places as in the paper. */\nconst GLICKO2_FACTOR = 173.7178;\nconst GLICKO2_CENTER = 1500;\nconst VOLATILITY_STEPS = 1000;\n\nfunction checkedRating(name: string, player: Glicko2Rating): void {\n finite(name, \"the rating\", player.rating);\n positive(name, \"the RD\", player.rd);\n positive(name, \"the volatility\", player.volatility);\n}\n\n/**\n * The Glicko-2 update of one player after one rating period (Glickman, \"Example of the Glicko-2 system\", 2012). The\n * function uses the Illinois algorithm for the new volatility. The games use the ratings of the opponents from the\n * start of the period. An empty list of games gives `glicko2Idle(player)`.\n */\nexport function glicko2Update(player: Glicko2Rating, games: readonly Glicko2Game[], options: Glicko2Options = {}): Glicko2Rating {\n checkedRating(\"glicko2Update\", player);\n const tau = options.tau ?? 0.5;\n const tolerance = options.tolerance ?? 1e-6;\n positive(\"glicko2Update\", \"tau\", tau);\n positive(\"glicko2Update\", \"the tolerance\", tolerance);\n for (const game of games) {\n finite(\"glicko2Update\", \"the rating of an opponent\", game.rating);\n positive(\"glicko2Update\", \"the RD of an opponent\", game.rd);\n if (!(game.score >= 0 && game.score <= 1)) throw new RangeError(`glicko2Update: a score is from 0 to 1, not ${game.score}.`);\n }\n if (games.length === 0) return glicko2Idle(player);\n const mu = (player.rating - GLICKO2_CENTER) / GLICKO2_FACTOR;\n const phi = player.rd / GLICKO2_FACTOR;\n const sigma = player.volatility;\n let information = 0;\n let improvement = 0;\n for (const game of games) {\n const muJ = (game.rating - GLICKO2_CENTER) / GLICKO2_FACTOR;\n const phiJ = game.rd / GLICKO2_FACTOR;\n const g = 1 / Math.sqrt(1 + (3 * phiJ * phiJ) / (Math.PI * Math.PI));\n const e = 1 / (1 + Math.exp(-g * (mu - muJ)));\n information += g * g * e * (1 - e);\n improvement += g * (game.score - e);\n }\n const v = 1 / information;\n const delta = v * improvement;\n const newSigma = newVolatility(phi, sigma, v, delta, tau, tolerance);\n const phiStar = Math.sqrt(phi * phi + newSigma * newSigma);\n const newPhi = 1 / Math.sqrt(1 / (phiStar * phiStar) + 1 / v);\n const newMu = mu + newPhi * newPhi * improvement;\n return { rating: GLICKO2_FACTOR * newMu + GLICKO2_CENTER, rd: GLICKO2_FACTOR * newPhi, volatility: newSigma };\n}\n\n/** Step 5 of the paper: the new volatility, by the Illinois algorithm on `x = ln(sigma^2)`. */\nfunction newVolatility(phi: number, sigma: number, v: number, delta: number, tau: number, tolerance: number): number {\n const a = Math.log(sigma * sigma);\n const phi2 = phi * phi;\n const delta2 = delta * delta;\n const f = (x: number): number => {\n const ex = Math.exp(x);\n const sum = phi2 + v + ex;\n return (ex * (delta2 - phi2 - v - ex)) / (2 * sum * sum) - (x - a) / (tau * tau);\n };\n let lowEnd = a;\n let highEnd: number;\n if (delta2 > phi2 + v) highEnd = Math.log(delta2 - phi2 - v);\n else {\n let k = 1;\n while (f(a - k * tau) < 0 && k < VOLATILITY_STEPS) k++;\n highEnd = a - k * tau;\n }\n let fLow = f(lowEnd);\n let fHigh = f(highEnd);\n for (let step = 0; Math.abs(highEnd - lowEnd) > tolerance && step < VOLATILITY_STEPS; step++) {\n const c = lowEnd + ((lowEnd - highEnd) * fLow) / (fHigh - fLow);\n const fC = f(c);\n if (fC * fHigh <= 0) {\n lowEnd = highEnd;\n fLow = fHigh;\n } else fLow /= 2;\n highEnd = c;\n fHigh = fC;\n }\n return Math.exp(lowEnd / 2);\n}\n\n/**\n * The Glicko-2 rating of a player after a rating period with no games. The rating and the volatility stay the same.\n * The RD grows to `sqrt(RD^2 + (173.7178 * volatility)^2)`.\n */\nexport function glicko2Idle(player: Glicko2Rating): Glicko2Rating {\n checkedRating(\"glicko2Idle\", player);\n const phi = player.rd / GLICKO2_FACTOR;\n const rd = GLICKO2_FACTOR * Math.sqrt(phi * phi + player.volatility * player.volatility);\n return { rating: player.rating, rd, volatility: player.volatility };\n}\n\n/** The probabilities of the three outcomes of a pair. Their sum is 1. */\nexport interface PairProbabilities {\n /** The probability that the first item wins. */\n readonly a: number;\n /** The probability that the second item wins. */\n readonly b: number;\n /** The probability of a tie. It is 0 when the tie parameter is 0. */\n readonly tie: number;\n}\n\n/**\n * This function gives the three probabilities of a pair from the log-strengths `sa` and `sb` and the Davidson tie\n * parameter `nu`. The denominator is `exp(d / 2) + exp(-d / 2) + nu`, with `d = sa - sb`. The function does no\n * checks, because the fit uses it in its inner loop.\n */\nexport function pairOutcomes(sa: number, sb: number, nu: number): PairProbabilities {\n const half = (sa - sb) / 2;\n const top = Math.max(Math.abs(half), nu > 0 ? Math.log(nu) : Number.NEGATIVE_INFINITY);\n const ea = Math.exp(half - top);\n const eb = Math.exp(-half - top);\n const et = nu > 0 ? Math.exp(Math.log(nu) - top) : 0;\n const sum = ea + eb + et;\n return { a: ea / sum, b: eb / sum, tie: et / sum };\n}\n\n/**\n * The probabilities of a pair under the Bradley-Terry model with Davidson (1970) ties. The inputs are the\n * log-strengths of the two items and the tie parameter `tie` of `bradleyTerry`. With `tie` 0, the probability that\n * the first item wins is `1 / (1 + exp(sb - sa))`. A constant added to the two strengths changes no probability.\n */\nexport function pairProbabilities(sa: number, sb: number, tie = 0): PairProbabilities {\n finite(\"pairProbabilities\", \"the first strength\", sa);\n finite(\"pairProbabilities\", \"the second strength\", sb);\n if (!(tie >= 0 && Number.isFinite(tie))) throw new RangeError(`pairProbabilities: the tie parameter is a finite number of 0 or more, not ${tie}.`);\n return pairOutcomes(sa, sb, tie);\n}\n\n/**\n * The rating of a log-strength: `center + scale * strength / ln(base)`. The defaults give\n * `1500 + 400 * log10(e) * strength`. Thus `eloExpected` of two ratings is the Bradley-Terry win probability.\n */\nexport function strengthToRating(strength: number, options: RatingScale = {}): number {\n finite(\"strengthToRating\", \"the strength\", strength);\n const { center, scale, base } = checkedScale(\"strengthToRating\", options);\n return center + (scale * strength) / Math.log(base);\n}\n\n/** The log-strength of a rating. It is the inverse of `strengthToRating` with the same options. */\nexport function ratingToStrength(rating: number, options: RatingScale = {}): number {\n finite(\"ratingToStrength\", \"the rating\", rating);\n const { center, scale, base } = checkedScale(\"ratingToStrength\", options);\n return ((rating - center) * Math.log(base)) / scale;\n}\n","/**\n * The Bradley-Terry fit of pairwise comparisons among `n` items. Each item has a log-strength. The fit is the\n * maximum a posteriori estimate with a normal (ridge) prior on each log-strength. Thus an item with only wins has a\n * finite strength, and the strengths have one solution.\n *\n * Ties use the Davidson (1970) model, or count as half a win and half a loss. The fit uses Newton steps with a line search on the negative log posterior. This function is\n * convex, so the steps go to its one minimum.\n */\nimport { factor } from \"./ridge.ts\";\nimport { pairOutcomes } from \"./rating.ts\";\n\n/** The result of a comparison: the first item wins, the second item wins, or a tie. */\nexport type PairOutcome = \"a\" | \"b\" | \"tie\";\n\n/** One comparison of two items, by their indexes from 0. */\nexport interface PairComparison {\n readonly a: number;\n readonly b: number;\n readonly outcome: PairOutcome;\n /** The weight of the comparison. The default is 1. A weight of 2 counts as two equal comparisons. */\n readonly weight?: number;\n}\n\n/** The model of a tie. */\nexport type TieModel = \"davidson\" | \"half\";\n\n/** The options of `bradleyTerry`. */\nexport interface BradleyTerryOptions {\n /** The mean of the prior of each log-strength. The default is 0. */\n readonly priorMean?: number;\n /** The standard deviation of the prior of each log-strength. The default is 1. A smaller value pulls the strengths together. */\n readonly priorSd?: number;\n /**\n * The model of a tie. With `\"davidson\"` (the default), the fit also gives a tie parameter. With `\"half\"`, a tie\n * counts as half a win and half a loss of each item, and the tie parameter is 0.\n */\n readonly ties?: TieModel;\n /**\n * The standard deviation of the normal prior of the log of the tie parameter, with mean 0. The default is 10. The\n * prior is weak. It keeps the parameter finite when each comparison is a tie.\n */\n readonly tiePriorSd?: number;\n /** The largest number of Newton steps. The default is 100. */\n readonly maxIterations?: number;\n /** The fit stops when the full Newton step moves no parameter more than this value. The default is 1e-10. */\n readonly tolerance?: number;\n}\n\n/** The result of `bradleyTerry`. The lists have one value for each item, in the order of the indexes. */\nexport interface BradleyTerryFit {\n /** The log-strength of each item. An item with no comparison has the prior mean. */\n readonly strengths: number[];\n /**\n * The standard error of each log-strength: the square root of the diagonal of the inverse of the Hessian of the\n * negative log posterior. An item with no comparison has the prior SD.\n */\n readonly se: number[];\n /** The Davidson tie parameter. It is 0 with the model `\"half\"`, and when no comparison is a tie. */\n readonly tie: number;\n /** The log-likelihood of the comparisons at the fit, with no prior term. */\n readonly logLikelihood: number;\n /** The number of Newton steps. */\n readonly iterations: number;\n /** True when the last full Newton step moved no parameter more than the tolerance. */\n readonly converged: boolean;\n}\n\n/** A comparison as numbers: the indexes, the weight, the coefficient of the difference, and 1 for a Davidson tie. */\ninterface Term {\n readonly a: number;\n readonly b: number;\n readonly w: number;\n readonly c: number;\n readonly tie: number;\n}\n\nconst ARMIJO = 1e-4;\nconst HALVINGS = 60;\nconst ROUNDING = 64 * Number.EPSILON;\n\nfunction checkedTerms(n: number, comparisons: readonly PairComparison[], ties: TieModel): Term[] {\n const terms: Term[] = [];\n for (const [i, comparison] of comparisons.entries()) {\n const { a, b, outcome } = comparison;\n const w = comparison.weight ?? 1;\n for (const index of [a, b]) {\n if (!Number.isSafeInteger(index) || index < 0 || index >= n) {\n throw new RangeError(`bradleyTerry: comparison ${i} has the index ${index}, and the indexes are whole numbers from 0 to ${n - 1}.`);\n }\n }\n if (a === b) throw new RangeError(`bradleyTerry: comparison ${i} compares the item ${a} with itself.`);\n if (outcome !== \"a\" && outcome !== \"b\" && outcome !== \"tie\") throw new RangeError(`bradleyTerry: comparison ${i} has the outcome ${String(outcome)}.`);\n if (!(w >= 0 && Number.isFinite(w))) throw new RangeError(`bradleyTerry: comparison ${i} has the weight ${w}, and a weight is a finite number of 0 or more.`);\n if (w === 0) continue;\n const c = outcome === \"a\" ? 0.5 : outcome === \"b\" ? -0.5 : 0;\n terms.push({ a, b, w, c, tie: outcome === \"tie\" && ties === \"davidson\" ? 1 : 0 });\n }\n return terms;\n}\n\nfunction positiveOption(label: string, value: number): void {\n if (!(value > 0 && Number.isFinite(value))) throw new RangeError(`bradleyTerry: ${label} is a finite number above 0, not ${value}.`);\n}\n\n/**\n * The Bradley-Terry fit of `comparisons` among `items` items. The function does not sort or change its inputs. An\n * empty list of comparisons gives the prior for each item. The function throws a RangeError for a bad index, a bad\n * outcome, a bad weight and a bad option.\n */\nexport function bradleyTerry(items: number, comparisons: readonly PairComparison[], options: BradleyTerryOptions = {}): BradleyTerryFit {\n if (!Number.isSafeInteger(items) || items < 1) throw new RangeError(`bradleyTerry: the number of items is a whole number of 1 or more, not ${items}.`);\n const priorMean = options.priorMean ?? 0;\n const priorSd = options.priorSd ?? 1;\n const ties = options.ties ?? \"davidson\";\n const tiePriorSd = options.tiePriorSd ?? 10;\n const maxIterations = options.maxIterations ?? 100;\n const tolerance = options.tolerance ?? 1e-10;\n if (!Number.isFinite(priorMean)) throw new RangeError(`bradleyTerry: the prior mean is a finite number, not ${priorMean}.`);\n positiveOption(\"the prior SD\", priorSd);\n positiveOption(\"the tie prior SD\", tiePriorSd);\n positiveOption(\"the tolerance\", tolerance);\n if (ties !== \"davidson\" && ties !== \"half\") throw new RangeError(`bradleyTerry: the tie model is \"davidson\" or \"half\", not ${String(ties)}.`);\n if (!Number.isSafeInteger(maxIterations) || maxIterations < 1) {\n throw new RangeError(`bradleyTerry: maxIterations is a whole number of 1 or more, not ${maxIterations}.`);\n }\n const terms = checkedTerms(items, comparisons, ties);\n // The tie parameter is free only when a comparison is a Davidson tie. Else it is 0, and the model is plain Bradley-Terry.\n const fitTie = terms.some((t) => t.tie === 1);\n const k = fitTie ? items + 1 : items;\n const model: Model = { items, terms, fitTie, priorMean, priorPrecision: 1 / (priorSd * priorSd), tiePrecision: 1 / (tiePriorSd * tiePriorSd) };\n\n const x = new Float64Array(k).fill(priorMean);\n if (fitTie) x[items] = 0;\n let iterations = 0;\n let converged = false;\n let value = objective(model, x);\n while (iterations < maxIterations) {\n iterations++;\n const { gradient, hessian } = derivatives(model, x);\n const step = solve(hessian, gradient, k);\n let slope = 0;\n for (let i = 0; i < k; i++) slope += (gradient[i] as number) * (step[i] as number);\n let t = 1;\n let next = moved(x, step, t);\n let nextValue = objective(model, next);\n // Near the minimum, a full step changes the objective by less than its rounding. The slack accepts that step.\n const slack = ROUNDING * (Math.abs(value) + 1);\n for (let h = 0; h < HALVINGS && !(nextValue <= value + ARMIJO * t * slope + slack); h++) {\n t /= 2;\n next = moved(x, step, t);\n nextValue = objective(model, next);\n }\n // The full Newton step decides the convergence, so a stalled line search far from the minimum does not count.\n let largest = 0;\n for (let i = 0; i < k; i++) largest = Math.max(largest, Math.abs(step[i] as number));\n if (nextValue <= value + slack) {\n x.set(next);\n value = nextValue;\n }\n if (largest <= tolerance) {\n converged = true;\n break;\n }\n }\n\n const { hessian } = derivatives(model, x);\n const variance = inverseDiagonal(hessian, k);\n const nu = fitTie ? Math.exp(x[items] as number) : 0;\n let logLikelihood = 0;\n for (const term of terms) logLikelihood += term.w * termLogLikelihood(term, x[term.a] as number, x[term.b] as number, nu);\n return {\n strengths: Array.from(x.subarray(0, items)),\n se: Array.from(variance.subarray(0, items), (v) => Math.sqrt(v)),\n tie: nu,\n logLikelihood,\n iterations,\n converged,\n };\n}\n\ninterface Model {\n readonly items: number;\n readonly terms: readonly Term[];\n readonly fitTie: boolean;\n readonly priorMean: number;\n readonly priorPrecision: number;\n readonly tiePrecision: number;\n}\n\nfunction moved(x: Float64Array, step: Float64Array, t: number): Float64Array {\n const out = new Float64Array(x.length);\n for (let i = 0; i < x.length; i++) out[i] = (x[i] as number) + t * (step[i] as number);\n return out;\n}\n\n/** The log of the denominator `exp(d / 2) + exp(-d / 2) + nu`, with no overflow. */\nfunction logDenominator(d: number, logNu: number): number {\n const half = Math.abs(d) / 2;\n const top = Math.max(half, logNu);\n return top + Math.log(Math.exp(half - top) + Math.exp(-half - top) + Math.exp(logNu - top));\n}\n\n/** The log-likelihood of one comparison with weight 1. A `\"half\"` tie has the coefficient 0: the mean of the two log-probabilities of a win. */\nfunction termLogLikelihood(term: Term, sa: number, sb: number, nu: number): number {\n const d = sa - sb;\n const logNu = nu > 0 ? Math.log(nu) : Number.NEGATIVE_INFINITY;\n const logD = logDenominator(d, logNu);\n return term.tie === 1 ? logNu - logD : term.c * d - logD;\n}\n\n/** The negative log posterior at `x`. */\nfunction objective(model: Model, x: Float64Array): number {\n const logNu = model.fitTie ? (x[model.items] as number) : Number.NEGATIVE_INFINITY;\n let sum = 0;\n for (const term of model.terms) {\n const d = (x[term.a] as number) - (x[term.b] as number);\n sum += term.w * (logDenominator(d, logNu) - term.c * d - (term.tie === 1 ? logNu : 0));\n }\n for (let i = 0; i < model.items; i++) sum += (model.priorPrecision * ((x[i] as number) - model.priorMean) ** 2) / 2;\n if (model.fitTie) sum += (model.tiePrecision * logNu * logNu) / 2;\n return sum;\n}\n\n/** The gradient and the Hessian (in row order) of the negative log posterior at `x`. */\nfunction derivatives(model: Model, x: Float64Array): { gradient: Float64Array; hessian: Float64Array } {\n const k = x.length;\n const n = model.items;\n const gradient = new Float64Array(k);\n const hessian = new Float64Array(k * k);\n const nu = model.fitTie ? Math.exp(x[n] as number) : 0;\n for (const term of model.terms) {\n const { a, b, w } = term;\n const p = pairOutcomes(x[a] as number, x[b] as number, nu);\n const q = (p.a - p.b) / 2;\n const gd = w * (q - term.c);\n const hdd = w * ((p.a + p.b) / 4 - q * q);\n gradient[a] = (gradient[a] as number) + gd;\n gradient[b] = (gradient[b] as number) - gd;\n hessian[a * k + a] = (hessian[a * k + a] as number) + hdd;\n hessian[b * k + b] = (hessian[b * k + b] as number) + hdd;\n hessian[a * k + b] = (hessian[a * k + b] as number) - hdd;\n hessian[b * k + a] = (hessian[b * k + a] as number) - hdd;\n if (model.fitTie) {\n const hdl = -w * q * p.tie;\n gradient[n] = (gradient[n] as number) + w * (p.tie - term.tie);\n hessian[n * k + n] = (hessian[n * k + n] as number) + w * p.tie * (1 - p.tie);\n hessian[a * k + n] = (hessian[a * k + n] as number) + hdl;\n hessian[n * k + a] = (hessian[n * k + a] as number) + hdl;\n hessian[b * k + n] = (hessian[b * k + n] as number) - hdl;\n hessian[n * k + b] = (hessian[n * k + b] as number) - hdl;\n }\n }\n for (let i = 0; i < n; i++) {\n gradient[i] = (gradient[i] as number) + model.priorPrecision * ((x[i] as number) - model.priorMean);\n hessian[i * k + i] = (hessian[i * k + i] as number) + model.priorPrecision;\n }\n if (model.fitTie) {\n gradient[n] = (gradient[n] as number) + model.tiePrecision * (x[n] as number);\n hessian[n * k + n] = (hessian[n * k + n] as number) + model.tiePrecision;\n }\n return { gradient, hessian };\n}\n\n/** The Cholesky factor of a copy of the Hessian. The priors make the Hessian positive definite. */\nfunction factored(hessian: Float64Array, k: number): Float64Array {\n const l = Float64Array.from(hessian);\n if (!factor(l, k)) throw new RangeError(\"bradleyTerry: the Hessian is not positive definite. Make the prior SD smaller.\");\n return l;\n}\n\n/** The Newton step: the solution of `hessian * step = -gradient`. */\nfunction solve(hessian: Float64Array, gradient: Float64Array, k: number): Float64Array {\n const l = factored(hessian, k);\n const y = new Float64Array(k);\n for (let i = 0; i < k; i++) {\n let s = -(gradient[i] as number);\n for (let j = 0; j < i; j++) s -= (l[i * k + j] as number) * (y[j] as number);\n y[i] = s / (l[i * k + i] as number);\n }\n for (let i = k - 1; i >= 0; i--) {\n let s = y[i] as number;\n for (let j = i + 1; j < k; j++) s -= (l[j * k + i] as number) * (y[j] as number);\n y[i] = s / (l[i * k + i] as number);\n }\n return y;\n}\n\n/** The diagonal of the inverse of the Hessian: the column sums of the squares of the inverse of its Cholesky factor. */\nfunction inverseDiagonal(hessian: Float64Array, k: number): Float64Array {\n const l = factored(hessian, k);\n const out = new Float64Array(k);\n const column = new Float64Array(k);\n for (let c = 0; c < k; c++) {\n // Column c of the inverse of L, by forward substitution. Its entries above row c are 0.\n column.fill(0);\n for (let i = c; i < k; i++) {\n let s = i === c ? 1 : 0;\n for (let j = c; j < i; j++) s -= (l[i * k + j] as number) * (column[j] as number);\n column[i] = s / (l[i * k + i] as number);\n }\n // The inverse of the Hessian is inv(L)' inv(L), so its diagonal entry c is the sum over the rows of column c squared.\n let sum = 0;\n for (let i = c; i < k; i++) sum += (column[i] as number) ** 2;\n out[c] = sum;\n }\n return out;\n}\n"],"mappings":";;AAoBA,SAAS,QAAQ,MAAc,QAAiC;CAC9D,IAAI,OAAO,WAAW,GAAG,MAAM,IAAI,WAAW,GAAG,KAAK,qBAAqB;CAC3E,KAAK,MAAM,KAAK,QAAQ,IAAI,OAAO,MAAM,CAAC,GAAG,MAAM,IAAI,WAAW,GAAG,KAAK,sBAAsB;AAClG;;AAGA,SAAgB,OAAO,QAAqC;CAC1D,OAAO,CAAC,GAAG,MAAM,CAAC,CAAC,MAAM,GAAG,MAAM,IAAI,CAAC;AACzC;AAEA,SAAgB,KAAK,QAAmC;CACtD,QAAQ,QAAQ,MAAM;CACtB,IAAI,MAAM;CACV,KAAK,MAAM,KAAK,QAAQ,OAAO;CAC/B,OAAO,MAAM,OAAO;AACtB;;AAGA,SAAgB,SAAS,QAAoC;CAC3D,OAAO,OAAO,OAAO,MAAM,MAAM,OAAO,EAAE;AAC5C;;;;;AAMA,SAAgB,GAAG,QAAmC;CACpD,QAAQ,MAAM,MAAM;CACpB,IAAI,OAAO,SAAS,GAAG,MAAM,IAAI,WAAW,sCAAsC;CAClF,IAAI,SAAS,MAAM,GAAG,OAAO;CAC7B,MAAM,IAAI,KAAK,MAAM;CACrB,IAAI,MAAM;CACV,KAAK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