/** * The statistics the Research posts use, written out in full so a reader can check every step. * Pure functions with no dependencies: the analysis scripts run them under Node, and the tests * compare them with worked examples and with Python's own implementations. */ function sorted(values: readonly number[]): number[] { return [...values].sort((a, b) => a - b); } /** * The q-quantile with linear interpolation between ranks (numpy's default, and Python's * statistics.quantiles with method='inclusive'): position (n - 1) * q in the sorted values. */ export function quantile(values: readonly number[], q: number): number { if (values.length === 0) throw new RangeError('quantile of an empty sample'); if (!(q >= 0 && q <= 1)) throw new RangeError('quantile level must be between 0 and 1'); const ordered = sorted(values); const position = (ordered.length - 1) * q; const below = Math.floor(position); const above = Math.min(below + 1, ordered.length - 1); const low = ordered[below]!; return low + (position - below) * (ordered[above]! - low); } export function median(values: readonly number[]): number { return quantile(values, 0.5); } /** * erfc(x) for x >= 0, from Numerical Recipes (2nd edition, section 6.2): a Chebyshev fit with a * fractional error below 1.2e-7 everywhere, which keeps tiny p-values right to six digits. */ function erfc(x: number): number { const t = 1 / (1 + 0.5 * x); const poly = -x * x - 1.26551223 + t * (1.00002368 + t * (0.37409196 + t * (0.09678418 + t * (-0.18628806 + t * (0.27886807 + t * (-1.13520398 + t * (1.48851587 + t * (-0.82215223 + t * 0.17087277)))))))); return t * Math.exp(poly); } /** The two-sided p-value of a standard normal statistic: P(|Z| >= |z|) = erfc(|z| / sqrt 2). */ export function twoSidedNormalP(z: number): number { return Math.min(1, erfc(Math.abs(z) / Math.SQRT2)); } export interface MannWhitneyResult { /** U for the first sample: pairs where the first value is larger, plus half the ties. */ u: number; n1: number; n2: number; /** Normal approximation, with the tie-corrected variance and a 0.5 continuity correction. */ z: number; /** Two-sided. */ p: number; /** P(a random first value < a random second value) + half P(tie): the probability of superiority. */ probabilityFirstSmaller: number; } /** * The Mann-Whitney U test of two independent samples, two-sided, by the normal approximation * with tie correction and continuity correction (as scipy.stats.mannwhitneyu with * method='asymptotic'). Tied values share their average rank. */ export function mannWhitneyU(first: readonly number[], second: readonly number[]): MannWhitneyResult { const n1 = first.length; const n2 = second.length; if (n1 === 0 || n2 === 0) throw new RangeError('Mann-Whitney U needs both samples to be non-empty'); const pooled = [ ...first.map((value) => ({ value, fromFirst: true })), ...second.map((value) => ({ value, fromFirst: false })), ].sort((a, b) => a.value - b.value); const n = pooled.length; let rankSumFirst = 0; let tieTerm = 0; for (let start = 0; start < n;) { let end = start; while (end + 1 < n && pooled[end + 1]!.value === pooled[start]!.value) end += 1; const averageRank = (start + end) / 2 + 1; const size = end - start + 1; tieTerm += size ** 3 - size; for (let index = start; index <= end; index += 1) if (pooled[index]!.fromFirst) rankSumFirst += averageRank; start = end + 1; } const u = rankSumFirst - (n1 * (n1 + 1)) / 2; const mean = (n1 * n2) / 2; const sigma = Math.sqrt(((n1 * n2) / 12) * (n + 1 - tieTerm / (n * (n - 1)))); const offset = u - mean; const z = sigma === 0 ? 0 : (offset - Math.sign(offset) * Math.min(0.5, Math.abs(offset))) / sigma; return { u, n1, n2, z, p: twoSidedNormalP(z), probabilityFirstSmaller: (n1 * n2 - u) / (n1 * n2) }; } /** A small, fast, seeded generator (mulberry32): the same seed always gives the same sequence. */ export function seededRandom(seed: number): () => number { let state = seed >>> 0; return () => { state = (state + 0x6d2b79f5) >>> 0; let t = state; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; } export interface Interval { estimate: number; low: number; high: number; } export interface BootstrapOptions { resamples: number; seed: number; /** For example 0.95 for a 95% percentile interval. */ level: number; } /** * A percentile bootstrap for the change in median between two independent samples: each resample * draws both samples again with replacement, from one seeded stream (`after` first, then `before`). * Returns the interval for median(after) - median(before) and for median(before) / median(after). */ export function bootstrapMedians(after: readonly number[], before: readonly number[], options: BootstrapOptions): { difference: Interval; ratio: Interval } { if (after.length === 0 || before.length === 0) throw new RangeError('the bootstrap needs both samples to be non-empty'); if (after.some((value) => !(value > 0)) || before.some((value) => !(value > 0))) throw new RangeError('the ratio of medians needs positive values'); const random = seededRandom(options.seed); const resample = (values: readonly number[]) => values.map(() => values[Math.floor(random() * values.length)]!); const differences: number[] = []; const ratios: number[] = []; for (let index = 0; index < options.resamples; index += 1) { const afterMedian = median(resample(after)); const beforeMedian = median(resample(before)); differences.push(afterMedian - beforeMedian); ratios.push(beforeMedian / afterMedian); } const tail = (1 - options.level) / 2; const interval = (estimate: number, values: number[]): Interval => ({ estimate, low: quantile(values, tail), high: quantile(values, 1 - tail) }); return { difference: interval(median(after) - median(before), differences), ratio: interval(median(before) / median(after), ratios), }; }