@numero-uno-jpn/rstats 1.1.0 → 1.3.0

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.
Files changed (97) hide show
  1. package/CHANGELOG.md +142 -0
  2. package/README.ja.md +33 -15
  3. package/README.md +32 -14
  4. package/dist/chunks/{chunk-4KCSBTR5.js → chunk-2VZW4XPK.js} +2 -2
  5. package/dist/chunks/chunk-4OOTEXZU.js +2 -0
  6. package/dist/chunks/{chunk-Z2HGLFZN.js → chunk-6TZVS6WC.js} +2 -2
  7. package/dist/chunks/{chunk-U7BRXOUS.js → chunk-6X2ZMPF5.js} +2 -2
  8. package/dist/chunks/{chunk-GJEKNJP7.js → chunk-AJZV2SVY.js} +2 -2
  9. package/dist/chunks/{chunk-GRUQRNX7.js → chunk-BNTBZ5W3.js} +3 -3
  10. package/dist/chunks/{chunk-DR4GQ7PW.js → chunk-EBRTF7RM.js} +1 -1
  11. package/dist/chunks/{chunk-OG7UORIX.js → chunk-FFNHG5SB.js} +1 -1
  12. package/dist/chunks/{chunk-N5BDSMXS.js → chunk-GUM57VVM.js} +1 -1
  13. package/dist/chunks/{chunk-GGJA3JRO.js → chunk-HBRSUHSU.js} +2 -2
  14. package/dist/chunks/{chunk-HRA7PCQT.js → chunk-I5NWGQOQ.js} +2 -2
  15. package/dist/chunks/chunk-IJV43Y7Q.js +2 -0
  16. package/dist/chunks/{chunk-YN5MLKDL.js → chunk-IOGQEMDE.js} +2 -2
  17. package/dist/chunks/{chunk-GYGQUYEP.js → chunk-JJRZ2TTF.js} +2 -2
  18. package/dist/chunks/{chunk-X4J6UJHN.js → chunk-LA4H6ZSC.js} +2 -2
  19. package/dist/chunks/{chunk-DTJG2IL2.js → chunk-LMNU4NHZ.js} +2 -2
  20. package/dist/chunks/{chunk-4VRMAYPY.js → chunk-LNUNKFIH.js} +3 -3
  21. package/dist/chunks/chunk-MJXETGT2.js +2 -0
  22. package/dist/chunks/chunk-P7ZHH2SF.js +2 -0
  23. package/dist/chunks/{chunk-HUWOSLKE.js → chunk-PDHBRDTF.js} +2 -2
  24. package/dist/chunks/{chunk-7KJ24LYK.js → chunk-RCGW2DCK.js} +2 -2
  25. package/dist/chunks/{chunk-QUTJEYDX.js → chunk-TZTVDVP4.js} +2 -2
  26. package/dist/chunks/{chunk-HZLSNJQM.js → chunk-UJYRU37Z.js} +2 -2
  27. package/dist/chunks/{chunk-EJYCDE4Z.js → chunk-UMDXXT3M.js} +1 -1
  28. package/dist/chunks/{chunk-7IJCUSA5.js → chunk-UOAFEB64.js} +2 -2
  29. package/dist/chunks/{chunk-JNWWLNE3.js → chunk-Z74ZOTUN.js} +2 -2
  30. package/dist/descriptive.js +2 -2
  31. package/dist/distributions.js +2 -2
  32. package/dist/entries/tests.d.ts +14 -0
  33. package/dist/entries/tests.js +14 -0
  34. package/dist/htest/agreement.d.ts +2 -2
  35. package/dist/htest/binomCI.d.ts +116 -0
  36. package/dist/htest/binomCI.js +252 -0
  37. package/dist/htest/blandAltman.d.ts +100 -0
  38. package/dist/htest/blandAltman.js +159 -0
  39. package/dist/htest/boschlooTest.d.ts +65 -0
  40. package/dist/htest/boschlooTest.js +394 -0
  41. package/dist/htest/chisqTest.d.ts +19 -0
  42. package/dist/htest/chisqTest.js +30 -2
  43. package/dist/htest/core/twoProportions.d.ts +48 -0
  44. package/dist/htest/core/twoProportions.js +476 -0
  45. package/dist/htest/diagnosticTests.d.ts +91 -0
  46. package/dist/htest/diagnosticTests.js +116 -0
  47. package/dist/htest/equivalence.d.ts +172 -0
  48. package/dist/htest/equivalence.js +189 -0
  49. package/dist/htest/fisherTest.d.ts +49 -0
  50. package/dist/htest/fisherTest.js +136 -13
  51. package/dist/htest/iccPsych.d.ts +106 -0
  52. package/dist/htest/iccPsych.js +332 -0
  53. package/dist/htest/ksTest.d.ts +1 -1
  54. package/dist/htest/mcreg.d.ts +209 -0
  55. package/dist/htest/mcreg.js +735 -0
  56. package/dist/htest/roc.d.ts +287 -0
  57. package/dist/htest/roc.js +635 -0
  58. package/dist/htest/rocTest.d.ts +139 -0
  59. package/dist/htest/rocTest.js +444 -0
  60. package/dist/htest/tTOST.d.ts +202 -0
  61. package/dist/htest/tTOST.js +558 -0
  62. package/dist/htest/tableTests.d.ts +216 -0
  63. package/dist/htest/tableTests.js +650 -0
  64. package/dist/htest/trendTests.d.ts +1 -1
  65. package/dist/htest/trendTests.js +1 -1
  66. package/dist/htest/twoByTwo.d.ts +203 -0
  67. package/dist/htest/twoByTwo.js +385 -0
  68. package/dist/internal/summary.js +5 -0
  69. package/dist/linalg/qr.d.ts +3 -0
  70. package/dist/linalg/qr.js +3 -0
  71. package/dist/linalg.js +2 -2
  72. package/dist/mixed.js +2 -2
  73. package/dist/models/coeftest.d.ts +139 -0
  74. package/dist/models/coeftest.js +237 -0
  75. package/dist/models/coxph.d.ts +60 -9
  76. package/dist/models/coxph.js +367 -38
  77. package/dist/models/glm.d.ts +11 -1
  78. package/dist/models/glm.js +19 -2
  79. package/dist/models/inputRows.d.ts +10 -0
  80. package/dist/models/inputRows.js +23 -0
  81. package/dist/models/lm.d.ts +8 -0
  82. package/dist/models/lm.js +14 -2
  83. package/dist/models/sandwich.d.ts +177 -0
  84. package/dist/models/sandwich.js +923 -0
  85. package/dist/numerics.js +2 -2
  86. package/dist/random/rng.d.ts +8 -1
  87. package/dist/random/rng.js +14 -1
  88. package/dist/rstats.js +16 -16
  89. package/dist/special/igam.js +140 -23
  90. package/dist/special/loader.js +8 -0
  91. package/dist/special.js +2 -2
  92. package/dist/tests.js +13 -13
  93. package/llms.txt +25 -0
  94. package/package.json +1 -1
  95. package/dist/chunks/chunk-NDTJ23A6.js +0 -2
  96. package/dist/chunks/chunk-UMLMY4XS.js +0 -2
  97. package/dist/chunks/chunk-Y4YWLSWU.js +0 -2
@@ -16,6 +16,12 @@
16
16
  // - Counts are made integer by rounding half to even, with R's warning "'x' has been rounded to integer: " and the text
17
17
  // of all.equal(original, rounded) (allEqualMessage)
18
18
  // The same distribution and root conventions are used for the exact Mantel-Haenszel test (src/htest/core/mantelhaen.ts).
19
+ // - midp (exact2x2's fisher.exact(midp = TRUE), from oracle/contingency-behaviour.md section 3; the mid-p idea is
20
+ // Lancaster 1961, JASA 56, 223-234): the tails P(X < x) + P(X = x)/2 and P(X > x) + P(X = x)/2 replace the ordinary
21
+ // ones in the p-value and the limits; two-sided is the central test, min(1, 2 min(tails)). At psi = 0 and Infinity
22
+ // the distribution is a point mass at the end of the support (a tail of 1/2 there), so a limit at an end of the
23
+ // support is 0 or Infinity, and where x is at an end and alpha >= 1/2 the other limit is that end too. The roots are
24
+ // those of the tails (exact2x2's uniroot stops up to 1% from them; 1/eps where the limit is large)
19
25
  //
20
26
  // rxc tables: the probabilities of tables with fixed margins (multivariate hypergeometric) are
21
27
  // traversed via a network that fixes one column at a time (Mehta & Patel 1983, JASA 78, 427-434),
@@ -45,7 +51,7 @@ import { matchAlternative } from "./types.js";
45
51
  import { maxOf, minOf } from "../internal/extremes.js";
46
52
  // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
47
53
  import { checkOptions } from "../internal/checkOptions.js";
48
- const FISHER_TEST_KEYS = ["alternative", "confInt", "confLevel", "or", "simulatePValue", "B"];
54
+ const FISHER_TEST_KEYS = ["alternative", "confInt", "confLevel", "or", "simulatePValue", "B", "midp"];
49
55
  /**
50
56
  * Fisher's exact test for count data. Equivalent to R's `fisher.test()`.
51
57
  *
@@ -60,6 +66,11 @@ const FISHER_TEST_KEYS = ["alternative", "confInt", "confLevel", "or", "simulate
60
66
  * With `simulatePValue: true`, the p-value of a table larger than 2 x 2 is computed from `B` random tables with the
61
67
  * observed margins, drawn from the random stream of {@link setSeed} exactly as in R.
62
68
  *
69
+ * With `midp: true` (2 x 2 only), the mid-p version of exact2x2's `fisher.exact()`: the p-value and the interval come
70
+ * from the mid-p tails (two-sided: the central test, twice the smaller tail, at most 1), the limits are the roots of
71
+ * the mid-p tails to the precision of the doubles (exact2x2's search stops up to 1% from them), and `method` is
72
+ * `"Central Fisher's Exact Test (mid-p version)"` or `"One-sided Fisher's Exact Test (mid-p version)"`.
73
+ *
63
74
  * Not implemented: R's `hybrid` option.
64
75
  *
65
76
  * @param x Contingency table as an array of rows (at least 2 x 2).
@@ -72,6 +83,9 @@ const FISHER_TEST_KEYS = ["alternative", "confInt", "confLevel", "or", "simulate
72
83
  * r.pValue; // 0.4857142857142857
73
84
  * r.estimate; // 6.408319658199675 (conditional MLE of the odds ratio; R: 6.408309)
74
85
  * r.confInt; // [0.2117355954465785, 626.2435305888127] (R: 0.2117329, 621.93)
86
+ * const m = fisherTest([[3, 1], [1, 3]], { midp: true });
87
+ * m.pValue; // 0.2571428571428571
88
+ * m.confInt; // [0.31005488171907974, 308.5567715811547] (exact2x2: 0.3100451, 311.4363)
75
89
  * ```
76
90
  *
77
91
  * @category Hypothesis tests
@@ -99,6 +113,10 @@ export function fisherTest(x, options = {}) {
99
113
  if (rounding !== null)
100
114
  warnings.push(`'x' has been rounded to integer: ${rounding}`);
101
115
  const method = "Fisher's Exact Test for Count Data";
116
+ if (options.midp !== undefined && typeof options.midp !== "boolean")
117
+ throw new TypeError("'midp' must be true or false");
118
+ if ((options.midp ?? false) && !(nr === 2 && nc === 2))
119
+ throw new RangeError("the mid-p version ('midp') needs a 2 x 2 table");
102
120
  if (nr === 2 && nc === 2)
103
121
  return reported("fisherTest", { ...fisher2x2(t, options, method), warnings });
104
122
  // For rxc, alternative etc. are not validated and are returned as given (as in R)
@@ -205,7 +223,7 @@ function accurateSum(v, from, to) {
205
223
  * Fisher's noncentral hypergeometric distribution of the (1, 1) cell of a 2 x 2 table with margins fixed:
206
224
  * P(X = i; psi) proportional to dhyper(i; m, n, k) psi^i on lo..hi
207
225
  */
208
- class OddsRatioDistribution {
226
+ export class OddsRatioDistribution {
209
227
  m;
210
228
  n;
211
229
  k;
@@ -285,6 +303,94 @@ class OddsRatioDistribution {
285
303
  const j = q - this.lo;
286
304
  return upper ? accurateSum(d, j, d.length - 1) : accurateSum(d, 0, j);
287
305
  }
306
+ /** The mid-p tail P(X < q; psi) + P(X = q; psi)/2, or P(X > q; psi) + P(X = q; psi)/2 when upper (lo <= q <= hi) */
307
+ midTail(q, psi, upper) {
308
+ if (psi === 1) {
309
+ const half = 0.5 * dhyper1(q, this.m, this.n, this.k, false);
310
+ return (upper ? phyper1(q, this.m, this.n, this.k, false, false) : phyper1(q - 1, this.m, this.n, this.k, true, false)) + half;
311
+ }
312
+ if (psi === 0 || psi === Infinity) {
313
+ const at = psi === 0 ? this.lo : this.hi;
314
+ if (q === at)
315
+ return 0.5;
316
+ return (upper ? q < at : q > at) ? 1 : 0;
317
+ }
318
+ const d = this.density(psi);
319
+ const j = q - this.lo;
320
+ return (upper ? accurateSum(d, j + 1, d.length - 1) : accurateSum(d, 0, j - 1)) + 0.5 * d[j];
321
+ }
322
+ }
323
+ /**
324
+ * The two-sided p-value of the count x at the odds ratio psi (0 < psi < Infinity): the sum of the probabilities at
325
+ * most P(X = x) (1 + 1e-7), as R
326
+ */
327
+ export function twoSidedPValue(dist, x, psi) {
328
+ const dens = dist.density(psi);
329
+ const cut = dens[x - dist.lo] * SLACK;
330
+ let acc = [0, 0];
331
+ for (const v of dens)
332
+ if (v <= cut)
333
+ acc = ddAdd(acc, [v, 0]);
334
+ return acc[0];
335
+ }
336
+ /**
337
+ * Fisher's two-sided p-value of the 2 x 2 table with the (1, 1) cell x and the margins m (column 1), n (column 2) and
338
+ * k (row 1), at the odds ratio 1, without the array of the support: the hypergeometric density is unimodal, so the
339
+ * values at most P(X = x) (1 + 1e-7) are the two tails below and above two cut points, found by bisection and summed
340
+ * by phyper. For supports beyond what twoSidedPValue allocates (oddsRatio's p-value of tables with counts of 1e9)
341
+ */
342
+ export function twoSidedPValueUnimodal(x, m, n, k) {
343
+ const lo = Math.max(0, k - n);
344
+ const hi = Math.min(k, m);
345
+ // (on the log scale: P(X = x) underflows far in the tails, and a cut of 0 would take in every value that underflows)
346
+ const d = (i) => dhyper1(i, m, n, k, true);
347
+ const cut = d(x) + Math.log(SLACK);
348
+ // a mode (the density increases up to it and decreases after; the formula may be one off where it rounds)
349
+ let mode = Math.min(hi, Math.max(lo, Math.floor(((k + 1) * (m + 1)) / (m + n + 2))));
350
+ while (mode < hi && d(mode + 1) > d(mode))
351
+ mode++;
352
+ while (mode > lo && d(mode - 1) > d(mode))
353
+ mode--;
354
+ // the last i in [from, to] with d(i) <= cut, d rising over [from, to] and d(from) <= cut
355
+ const risingLast = (from, to) => {
356
+ let a = from;
357
+ let b = to + 1;
358
+ while (b - a > 1) {
359
+ const mid = a + Math.floor((b - a) / 2);
360
+ if (d(mid) <= cut)
361
+ a = mid;
362
+ else
363
+ b = mid;
364
+ }
365
+ return a;
366
+ };
367
+ // the first i in [from, to] with d(i) <= cut, d falling over [from, to]; to + 1 if there is none
368
+ const fallingFirst = (from, to) => {
369
+ let a = from - 1;
370
+ let b = to + 1;
371
+ while (b - a > 1) {
372
+ const mid = a + Math.floor((b - a) / 2);
373
+ if (d(mid) <= cut)
374
+ b = mid;
375
+ else
376
+ a = mid;
377
+ }
378
+ return b;
379
+ };
380
+ // the p-value is P(X <= below) + P(X >= above)
381
+ let below;
382
+ let above;
383
+ if (x <= mode) {
384
+ below = risingLast(x, mode);
385
+ above = fallingFirst(mode + 1, hi);
386
+ }
387
+ else {
388
+ above = fallingFirst(mode, x);
389
+ below = mode - 1 < lo || d(lo) > cut ? lo - 1 : risingLast(lo, mode - 1);
390
+ }
391
+ const lower = below < lo ? 0 : phyper1(below, m, n, k, true, false);
392
+ const upper = above > hi ? 0 : phyper1(above - 1, m, n, k, false, false);
393
+ return lower + upper;
288
394
  }
289
395
  /** Root of f, monotone in the odds ratio psi, to the precision of the doubles (on the log scale, see logScaleRoot) */
290
396
  function oddsRatioRoot(f, belowOne) {
@@ -307,8 +413,19 @@ function fisher2x2(t, options, method) {
307
413
  }
308
414
  const dist = new OddsRatioDistribution(a + c, b + d, a + b);
309
415
  const { lo, hi } = dist;
416
+ const midp = options.midp ?? false;
310
417
  let pValue;
311
- if (alternative === "less")
418
+ if (midp) {
419
+ // the central test: twice the smaller mid-p tail (exact2x2 supports no other two-sided mid-p test)
420
+ if (alternative === "less")
421
+ pValue = dist.midTail(x, or, false);
422
+ else if (alternative === "greater")
423
+ pValue = dist.midTail(x, or, true);
424
+ else
425
+ pValue = Math.min(1, 2 * Math.min(dist.midTail(x, or, false), dist.midTail(x, or, true)));
426
+ method = alternative === "two.sided" ? "Central Fisher's Exact Test (mid-p version)" : "One-sided Fisher's Exact Test (mid-p version)";
427
+ }
428
+ else if (alternative === "less")
312
429
  pValue = dist.tail(x, or, false);
313
430
  else if (alternative === "greater")
314
431
  pValue = dist.tail(x, or, true);
@@ -316,15 +433,8 @@ function fisher2x2(t, options, method) {
316
433
  pValue = x === lo ? 1 : 0;
317
434
  else if (or === Infinity)
318
435
  pValue = x === hi ? 1 : 0;
319
- else {
320
- const dens = dist.density(or);
321
- const cut = dens[x - lo] * SLACK;
322
- let acc = [0, 0];
323
- for (const v of dens)
324
- if (v <= cut)
325
- acc = ddAdd(acc, [v, 0]);
326
- pValue = acc[0];
327
- }
436
+ else
437
+ pValue = twoSidedPValue(dist, x, or);
328
438
  let estimate;
329
439
  if (x === lo)
330
440
  estimate = 0;
@@ -346,16 +456,29 @@ function fisher2x2(t, options, method) {
346
456
  };
347
457
  if (!(options.confInt ?? true))
348
458
  return result;
349
- // P(X <= x; psi) decreases and P(X >= x; psi) increases in psi
459
+ // P(X <= x; psi) decreases and P(X >= x; psi) increases in psi, and so do the mid-p tails. At the ends of the support
460
+ // the mid-p tail is P(X = x; psi)/2 <= 1/2 (exact2x2's conventions: a limit of 0 or Infinity where alpha >= 1/2)
350
461
  const upperLimit = (level) => {
351
462
  if (x === hi)
352
463
  return Infinity;
464
+ if (midp) {
465
+ if (x === lo && level >= 0.5)
466
+ return 0;
467
+ const p1 = dist.midTail(x, 1, false);
468
+ return p1 === level ? 1 : oddsRatioRoot((psi) => dist.midTail(x, psi, false) - level, p1 < level);
469
+ }
353
470
  const p1 = dist.tail(x, 1, false);
354
471
  return p1 === level ? 1 : oddsRatioRoot((psi) => dist.tail(x, psi, false) - level, p1 < level);
355
472
  };
356
473
  const lowerLimit = (level) => {
357
474
  if (x === lo)
358
475
  return 0;
476
+ if (midp) {
477
+ if (x === hi && level >= 0.5)
478
+ return Infinity;
479
+ const p1 = dist.midTail(x, 1, true);
480
+ return p1 === level ? 1 : oddsRatioRoot((psi) => dist.midTail(x, psi, true) - level, p1 > level);
481
+ }
359
482
  const p1 = dist.tail(x, 1, true);
360
483
  return p1 === level ? 1 : oddsRatioRoot((psi) => dist.tail(x, psi, true) - level, p1 > level);
361
484
  };
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Options for {@link ICC}.
3
+ *
4
+ * @category Agreement, reliability and factor analysis
5
+ */
6
+ export interface ICCOptions {
7
+ /** One minus the confidence level of the intervals, in (0, 1) (psych's `alpha`). Default `0.05`; overrides
8
+ * `confLevel`. */
9
+ alpha?: number;
10
+ /** Confidence level of the intervals, in (0, 1). Default `0.95`. */
11
+ confLevel?: number;
12
+ /**
13
+ * `true` (default, as psych): the mean squares from the REML estimates of the variance components, which are not
14
+ * negative (where a component would be negative, it is 0 and the coefficients that depend on it are 0, F 1);
15
+ * `false`: the ANOVA mean squares (coefficients may be negative).
16
+ */
17
+ lmer?: boolean;
18
+ }
19
+ /**
20
+ * One of the six forms in {@link ICCResult}.
21
+ *
22
+ * @category Agreement, reliability and factor analysis
23
+ */
24
+ export interface ICCRow {
25
+ /** `"ICC1"`, `"ICC2"`, `"ICC3"`, `"ICC1k"`, `"ICC2k"` or `"ICC3k"`. */
26
+ type: "ICC1" | "ICC2" | "ICC3" | "ICC1k" | "ICC2k" | "ICC3k";
27
+ /** psych's row name: `"Single_raters_absolute"`, `"Single_random_raters"`, ... */
28
+ name: string;
29
+ /** The intraclass correlation. */
30
+ ICC: number;
31
+ /** F statistic of the test of ICC = 0. */
32
+ F: number;
33
+ /** Numerator degrees of freedom. */
34
+ df1: number;
35
+ /** Denominator degrees of freedom. */
36
+ df2: number;
37
+ /** Upper-tail p-value of the F test. */
38
+ pValue: number;
39
+ /** Lower confidence limit. */
40
+ lower: number;
41
+ /** Upper confidence limit. */
42
+ upper: number;
43
+ }
44
+ /**
45
+ * Result of {@link ICC}.
46
+ *
47
+ * @category Agreement, reliability and factor analysis
48
+ */
49
+ export interface ICCResult {
50
+ /** The six forms, in psych's order ICC1, ICC2, ICC3, ICC1k, ICC2k, ICC3k. */
51
+ results: ICCRow[];
52
+ /** Mean square of subjects (REML: `k σ²_subject + σ²_e`). */
53
+ MSB: number;
54
+ /** Mean square of raters (REML: `n σ²_rater + σ²_e`). */
55
+ MSJ: number;
56
+ /** Residual mean square (REML: `σ²_e`). */
57
+ MSE: number;
58
+ /** Mean square within subjects, used by ICC1 and ICC1k (REML: `σ²_e + σ²_rater`). */
59
+ MSW: number;
60
+ /** Number of subjects (rows). */
61
+ n: number;
62
+ /** Number of raters (columns). */
63
+ k: number;
64
+ /** Confidence level of the intervals, `1 - alpha`. */
65
+ confLevel: number;
66
+ /** Whether the REML path was used. */
67
+ lmer: boolean;
68
+ /** R's warnings (aov's `essentially perfect fit` where the residual mean square is 0 on the ANOVA path). */
69
+ warnings: string[];
70
+ }
71
+ /**
72
+ * The six intraclass correlations of Shrout and Fleiss (1979), with their F tests and confidence intervals.
73
+ * Equivalent to `psych::ICC(x, alpha, lmer)` in R. Only complete data are accepted.
74
+ *
75
+ * `x` is an n × k matrix (an array of rows): the ratings of the k raters for each of the n subjects. The forms are
76
+ * ICC1 = (MSB − MSW)/(MSB + (k − 1)MSW) (one-way), ICC2 = (MSB − MSE)/(MSB + (k − 1)MSE + k(MSJ − MSE)/n) (two-way
77
+ * random raters, absolute agreement), ICC3 = (MSB − MSE)/(MSB + (k − 1)MSE) (two-way fixed raters, consistency), and
78
+ * their averages over k raters ICC1k, ICC2k, ICC3k. With `lmer: true` (the default, as psych) the mean squares are
79
+ * rebuilt from the REML estimates of the variance components of the two-way random model, which are not negative;
80
+ * where both ANOVA components are not negative they equal the ANOVA mean squares. psych fits that model with lme4,
81
+ * whose optimiser stops early (results about 1e-5 relative off); here the REML estimates are computed exactly, in
82
+ * closed form.
83
+ *
84
+ * ICC1, ICC3, ICC1k and ICC3k agree with {@link icc} (irr's forms); the interval of ICC2k is psych's (ICC2's bounds
85
+ * transformed by Spearman-Brown), not irr's (McGraw and Wong's average-agreement interval).
86
+ *
87
+ * Where the residual mean square is 0 (ratings that differ between raters by constants), the F statistics of ICC2 and
88
+ * ICC3 are Infinity with p-value 0, and ICC3, ICC3k and their bounds are 1.
89
+ *
90
+ * @param x An n × k matrix of ratings (array of rows), without missing values.
91
+ * @param options See {@link ICCOptions}.
92
+ * @returns See {@link ICCResult}.
93
+ * @throws TypeError if x is not a matrix of numbers; RangeError for missing or infinite ratings (psych's REML path
94
+ * accepts missing ratings; here they are an error), fewer than 2 subjects or raters, ratings that are all equal or
95
+ * identical for every subject, or a level out of range.
96
+ *
97
+ * @example
98
+ * ```ts
99
+ * const r = ICC([[9, 2, 5, 8], [6, 1, 3, 2], [8, 4, 6, 8], [7, 1, 2, 6], [10, 5, 6, 9], [6, 2, 4, 7]]);
100
+ * r.results[1]!.ICC; // 0.28976377952755905 (ICC2)
101
+ * r.results[4]!.lower; // 0.07113681530250335 (ICC2k)
102
+ * ```
103
+ *
104
+ * @category Agreement, reliability and factor analysis
105
+ */
106
+ export declare function ICC(x: readonly (readonly number[])[], options?: ICCOptions): ICCResult;
@@ -0,0 +1,332 @@
1
+ // The six intraclass correlations of Shrout and Fleiss (psych's ICC): one-way and two-way, single and average
2
+ // raters, with their F tests and confidence intervals, from the ANOVA mean squares or from REML variance components.
3
+ //
4
+ // Written for rStats.js from oracle/methodcomparison-behaviour.md, section 3 (no R or package code), and the papers:
5
+ // - Shrout PE, Fleiss JL (1979) Intraclass correlations: uses in assessing rater reliability. Psychological Bulletin
6
+ // 86:420-428: the six forms, their F tests and intervals, ICC2's interval with Satterthwaite's df v.
7
+ // - The REML estimates of the balanced crossed model y = mu + s_i + r_j + e_ij: the REML likelihood of balanced data is
8
+ // that of the three independent mean squares MS_t ~ lambda_t chi^2(df_t)/df_t, lambda_B = k s2_s + s2_e, lambda_J =
9
+ // n s2_r + s2_e, lambda_E = s2_e (Searle, Casella and McCulloch 1992, Variance Components, ch. 6). The constraints
10
+ // s2_s, s2_r >= 0 are lambda_E <= lambda_B and lambda_E <= lambda_J, and the maximum under this order is the
11
+ // weighted isotonic regression of the mean squares with weights df_t (Robertson, Wright and Dykstra 1988, Order
12
+ // Restricted Statistical Inference, ch. 1): the residual mean square is pooled with each of the others, smallest
13
+ // first, that lies below the pooled value. Without pooling these are the ANOVA mean squares.
14
+ import { pf1, qf1 } from "../distributions/f.js";
15
+ import { ldexp, ldexpWide, scaleToUnit } from "../internal/summary.js";
16
+ import { reported } from "../internal/warnings.js";
17
+ import { ddAdd, ddDivNum, ddMul, ddSub } from "../special/dd.js";
18
+ import { checkConfLevelOpen } from "./types.js";
19
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
20
+ import { checkOptions } from "../internal/checkOptions.js";
21
+ const ICC_KEYS = ["alpha", "confLevel", "lmer"];
22
+ const NAMES = {
23
+ ICC1: "Single_raters_absolute",
24
+ ICC2: "Single_random_raters",
25
+ ICC3: "Single_fixed_raters",
26
+ ICC1k: "Average_raters_absolute",
27
+ ICC2k: "Average_random_raters",
28
+ ICC3k: "Average_fixed_raters",
29
+ };
30
+ /** a - b exactly, as an unevaluated sum [s, e] (Knuth's two-sum; error-free whatever the double-double switch) */
31
+ function exactDiff(a, b) {
32
+ const s = a - b;
33
+ const bb = s - a;
34
+ return [s, a - (s - bb) + (-b - bb)];
35
+ }
36
+ /** Whether the ratings are additive, x_ij - x_i1 = x_1j - x_11 for all i, j (the residual mean square is then 0) */
37
+ function isAdditive(rows) {
38
+ const r0 = rows[0];
39
+ return rows.every((r) => r.every((v, j) => {
40
+ const [s1, e1] = exactDiff(v, r[0]);
41
+ const [s2, e2] = exactDiff(r0[j], r0[0]);
42
+ return s1 === s2 && e1 === e2;
43
+ }));
44
+ }
45
+ const sameArray = (a, b) => a.every((v, i) => v === b[i]);
46
+ /** Mean of double-doubles */
47
+ function meanOfDD(v) {
48
+ let s = [0, 0];
49
+ for (const u of v)
50
+ s = ddAdd(s, u);
51
+ return ddDivNum(s, v.length);
52
+ }
53
+ const sDiv = (s, d) => ({ v: ddDivNum(s.v, d), e: s.e });
54
+ /**
55
+ * The values brought to the largest scale among them (zeros do not count), as doubles `at` in units 2^E: the smaller
56
+ * ones lose only the digits (or the whole value) that are negligible beside the largest
57
+ */
58
+ function inCommon(...s) {
59
+ const nz = s.filter((t) => t.v[0] !== 0);
60
+ const E = nz.length === 0 ? 0 : Math.max(...nz.map((t) => t.e));
61
+ return s.map((t) => ({ at: ldexpWide(t.v[0], t.e - E), E }));
62
+ }
63
+ /** a + b, at the larger of their scales (in double-double) */
64
+ function sAdd(a, b) {
65
+ if (b.v[0] === 0)
66
+ return a;
67
+ if (a.v[0] === 0)
68
+ return b;
69
+ const E = Math.max(a.e, b.e);
70
+ const to = (t) => [ldexpWide(t.v[0], t.e - E), ldexpWide(t.v[1], t.e - E)];
71
+ return { v: ddAdd(to(a), to(b)), e: E };
72
+ }
73
+ /** a/b (Infinity for b = 0 < a, NaN for 0/0), formed from the ratio of the parts and one power of 2 */
74
+ const sRatio = (a, b) => ldexpWide(a.v[0] / b.v[0], a.e - b.e);
75
+ const sLess = (a, b) => {
76
+ const [x, y] = inCommon(a, b);
77
+ return x.at < y.at;
78
+ };
79
+ const sLessEq = (a, b) => {
80
+ const [x, y] = inCommon(a, b);
81
+ return x.at <= y.at;
82
+ };
83
+ /** Sum of squared deviations of the means m from g, times w, in double-double */
84
+ function ssOfMeans(m, g, w) {
85
+ let s = [0, 0];
86
+ for (const v of m) {
87
+ const d = ddSub(v, g);
88
+ s = ddAdd(s, ddMul(d, d));
89
+ }
90
+ return ddMul(s, [w, 0]);
91
+ }
92
+ /**
93
+ * The six intraclass correlations of Shrout and Fleiss (1979), with their F tests and confidence intervals.
94
+ * Equivalent to `psych::ICC(x, alpha, lmer)` in R. Only complete data are accepted.
95
+ *
96
+ * `x` is an n × k matrix (an array of rows): the ratings of the k raters for each of the n subjects. The forms are
97
+ * ICC1 = (MSB − MSW)/(MSB + (k − 1)MSW) (one-way), ICC2 = (MSB − MSE)/(MSB + (k − 1)MSE + k(MSJ − MSE)/n) (two-way
98
+ * random raters, absolute agreement), ICC3 = (MSB − MSE)/(MSB + (k − 1)MSE) (two-way fixed raters, consistency), and
99
+ * their averages over k raters ICC1k, ICC2k, ICC3k. With `lmer: true` (the default, as psych) the mean squares are
100
+ * rebuilt from the REML estimates of the variance components of the two-way random model, which are not negative;
101
+ * where both ANOVA components are not negative they equal the ANOVA mean squares. psych fits that model with lme4,
102
+ * whose optimiser stops early (results about 1e-5 relative off); here the REML estimates are computed exactly, in
103
+ * closed form.
104
+ *
105
+ * ICC1, ICC3, ICC1k and ICC3k agree with {@link icc} (irr's forms); the interval of ICC2k is psych's (ICC2's bounds
106
+ * transformed by Spearman-Brown), not irr's (McGraw and Wong's average-agreement interval).
107
+ *
108
+ * Where the residual mean square is 0 (ratings that differ between raters by constants), the F statistics of ICC2 and
109
+ * ICC3 are Infinity with p-value 0, and ICC3, ICC3k and their bounds are 1.
110
+ *
111
+ * @param x An n × k matrix of ratings (array of rows), without missing values.
112
+ * @param options See {@link ICCOptions}.
113
+ * @returns See {@link ICCResult}.
114
+ * @throws TypeError if x is not a matrix of numbers; RangeError for missing or infinite ratings (psych's REML path
115
+ * accepts missing ratings; here they are an error), fewer than 2 subjects or raters, ratings that are all equal or
116
+ * identical for every subject, or a level out of range.
117
+ *
118
+ * @example
119
+ * ```ts
120
+ * const r = ICC([[9, 2, 5, 8], [6, 1, 3, 2], [8, 4, 6, 8], [7, 1, 2, 6], [10, 5, 6, 9], [6, 2, 4, 7]]);
121
+ * r.results[1]!.ICC; // 0.28976377952755905 (ICC2)
122
+ * r.results[4]!.lower; // 0.07113681530250335 (ICC2k)
123
+ * ```
124
+ *
125
+ * @category Agreement, reliability and factor analysis
126
+ */
127
+ export function ICC(x, options = {}) {
128
+ checkOptions(options, ICC_KEYS, "ICC"); // generated: option-keys.mjs
129
+ const lmer = options.lmer ?? true;
130
+ if (typeof lmer !== "boolean")
131
+ throw new TypeError("'lmer' must be true or false");
132
+ let alpha;
133
+ let confLevel;
134
+ if (options.alpha !== undefined) {
135
+ alpha = options.alpha;
136
+ if (!(typeof alpha === "number" && alpha > 0 && alpha < 1))
137
+ throw new RangeError("'alpha' must be a single number in (0, 1)");
138
+ confLevel = 1 - alpha;
139
+ }
140
+ else {
141
+ confLevel = options.confLevel ?? 0.95;
142
+ checkConfLevelOpen(confLevel);
143
+ alpha = 1 - confLevel;
144
+ }
145
+ if (!Array.isArray(x) || x.length === 0 || !x.every((r) => Array.isArray(r))) {
146
+ throw new TypeError("'x' must be a matrix (an array of rows)");
147
+ }
148
+ const k = x[0].length;
149
+ if (x.some((r) => r.length !== k))
150
+ throw new TypeError("'x' must be a matrix (rows of equal length)");
151
+ if (x.some((r) => r.some((v) => typeof v !== "number")))
152
+ throw new TypeError("'x' must contain numbers");
153
+ if (x.some((r) => r.some(Number.isNaN)))
154
+ throw new RangeError("'x' contains missing ratings (only complete data are supported)");
155
+ if (x.some((r) => r.some((v) => !Number.isFinite(v))))
156
+ throw new RangeError("'x' contains infinite ratings");
157
+ const n = x.length;
158
+ if (n < 2 || k < 2)
159
+ throw new RangeError("at least 2 subjects and 2 raters are needed");
160
+ // the ratings scaled by one power of 2 (exact), for the checks below
161
+ const { groups: rows } = scaleToUnit(x);
162
+ if (rows.every((r) => sameArray(r, rows[0]))) {
163
+ throw new RangeError(rows[0].every((v) => v === rows[0][0]) ? "all ratings are equal" : "every subject has the same ratings: the coefficients are undefined");
164
+ }
165
+ const cols = Array.from({ length: k }, (_, j) => rows.map((r) => r[j]));
166
+ // SSB and SSE do not change when a constant is added to a column, SSJ and SSE not when one is added to a row: the
167
+ // sums of squares come from the ratings minus the first row (SSB), minus the first column (SSJ) and minus both
168
+ // (SSE), so that a rater or subject offset far beyond the spread of the ratings does not swamp them. Each difference
169
+ // is exact (a double-double); they are formed from the unscaled ratings (divided by 8 where a difference could
170
+ // overflow: the double differences x_ij - x_i1 - x_1j + x_11 reach 4 max|x|) and then scaled by one power of 2 of
171
+ // their own
172
+ let big = 0;
173
+ for (const r of x)
174
+ for (const v of r)
175
+ big = Math.max(big, Math.abs(v));
176
+ const shift = big > 2 ** 1020 ? 3 : 0;
177
+ const raw = shift > 0 ? x.map((r) => r.map((v) => v / 8)) : x;
178
+ const byCol = raw.map((r) => r.map((v, j) => exactDiff(v, raw[0][j])));
179
+ const byRow = raw.map((r) => r.map((v) => exactDiff(v, r[0])));
180
+ const both = byRow.map((r) => r.map((v, j) => ddSub(v, byRow[0][j])));
181
+ // each scaled by its own power of 2, so that the squares of the small ones do not underflow beside a large offset
182
+ const expOf = (m) => {
183
+ let big = 0;
184
+ for (const r of m)
185
+ for (const v of r)
186
+ big = Math.max(big, Math.abs(v[0]));
187
+ return big === 0 ? 0 : Math.floor(Math.log2(big));
188
+ };
189
+ const unit = (m, e) => m.map((r) => r.map((v) => [ldexp(v[0], -e), ldexp(v[1], -e)]));
190
+ const [kB, kJ, kE] = [expOf(byCol), expOf(byRow), expOf(both)];
191
+ const [yB, yJ, yE] = [unit(byCol, kB), unit(byRow, kJ), unit(both, kE)];
192
+ const colsOf = (m) => Array.from({ length: k }, (_, j) => m.map((r) => r[j]));
193
+ const ssB = ssOfMeans(yB.map(meanOfDD), meanOfDD(yB.flat()), k);
194
+ // (identical columns: SSJ is exactly 0, which the double-double means need not give)
195
+ const ssJ = cols.every((c) => sameArray(c, cols[0])) ? [0, 0] : ssOfMeans(colsOf(yJ).map(meanOfDD), meanOfDD(yJ.flat()), n);
196
+ let ssE = [0, 0];
197
+ if (!isAdditive(rows)) {
198
+ // the residuals x - row mean - column mean + grand mean, in double-double (no cancellation of SST - SSB - SSJ)
199
+ const rm = yE.map(meanOfDD);
200
+ const cm = colsOf(yE).map(meanOfDD);
201
+ const grand = meanOfDD(yE.flat());
202
+ yE.forEach((r, i) => r.forEach((v, j) => {
203
+ const e = ddAdd(ddSub(ddSub(v, rm[i]), cm[j]), grand);
204
+ ssE = ddAdd(ssE, ddMul(e, e));
205
+ }));
206
+ }
207
+ // Each sum of squares stays in its own units, 2^(2kB), 2^(2kJ), 2^(2kE) (times 64 where the ratings were divided by 8): a
208
+ // quantity brings only the mean squares it uses to the larger of their scales, so that it underflows only where its
209
+ // true value does (a rater offset far beyond the spread makes SSJ huge, but MSB, MSE, ICC3 and F3 do not change)
210
+ const scaled = (ss, kx) => ({ v: ss, e: 2 * (kx + shift) });
211
+ const SB = scaled(ssB, kB);
212
+ const SJ = scaled(ssJ, kJ);
213
+ const SE = scaled(ssE, kE);
214
+ const dfB = n - 1;
215
+ const dfJ = k - 1;
216
+ const dfE = (n - 1) * (k - 1);
217
+ let MSB = sDiv(SB, dfB);
218
+ let MSJ = sDiv(SJ, dfJ);
219
+ let MSE = sDiv(SE, dfE);
220
+ let MSW = sDiv(sAdd(SJ, SE), dfJ + dfE);
221
+ const warnings = [];
222
+ if (lmer) {
223
+ // REML: the isotonic regression of (MSB, MSJ) >= MSE with weights df (see the header)
224
+ const parts = {
225
+ B: { ss: SB, df: dfB, ms: MSB, pooled: false },
226
+ J: { ss: SJ, df: dfJ, ms: MSJ, pooled: false },
227
+ };
228
+ let pooledSS = SE;
229
+ let pooledDf = dfE;
230
+ for (const t of sLessEq(MSB, MSJ) ? ["B", "J"] : ["J", "B"]) {
231
+ const part = parts[t];
232
+ if (sLess(part.ms, sDiv(pooledSS, pooledDf))) {
233
+ pooledSS = sAdd(pooledSS, part.ss);
234
+ pooledDf += part.df;
235
+ part.pooled = true;
236
+ }
237
+ }
238
+ const lambdaE = sDiv(pooledSS, pooledDf);
239
+ if (parts.B.pooled)
240
+ MSB = lambdaE;
241
+ if (parts.J.pooled)
242
+ MSJ = lambdaE;
243
+ MSE = lambdaE;
244
+ // sigma2_e + sigma2_rater = MSE + (MSJ - MSE)/n: the ANOVA MSW unless the subjects' mean square was pooled
245
+ // (pooling the raters' gives (SSJ + SSE)/(dfJ + dfE) = MSW itself)
246
+ if (parts.B.pooled) {
247
+ const [e, j] = inCommon(MSE, MSJ);
248
+ MSW = { v: [e.at + (j.at - e.at) / n, 0], e: e.E };
249
+ }
250
+ }
251
+ else if (ssE[0] === 0)
252
+ warnings.push("essentially perfect fit for ‘1’: summary may be unreliable");
253
+ // the upper alpha/2 quantile of F (rule 10: from the upper tail itself below 1e-8, as 1 - alpha/2 loses its digits)
254
+ const q = (d1, d2) => alpha / 2 < 1e-8 ? qf1(alpha / 2, d1, d2, false, false) : qf1(1 - alpha / 2, d1, d2, true, false);
255
+ const upperP = (F, d1, d2) => pf1(F, d1, d2, false, false);
256
+ // (F - 1)/(F + k - 1) and 1 - 1/F, with their limit 1 at F = Infinity
257
+ const single = (f) => (f === Infinity ? 1 : (f - 1) / (f + k - 1));
258
+ const average = (f) => 1 - 1 / f;
259
+ const dfW = n * (k - 1);
260
+ const F1 = sRatio(MSB, MSW);
261
+ const F3 = sRatio(MSB, MSE);
262
+ const [F1L, F1U] = [F1 / q(dfB, dfW), F1 * q(dfW, dfB)];
263
+ const [F3L, F3U] = [F3 / q(dfB, dfE), F3 * q(dfE, dfB)];
264
+ // ICC1 and ICC1k need MSB and MSW, ICC3 and ICC3k MSB and MSE, ICC2, ICC2k and ICC2's interval all three: each in
265
+ // the units of the largest of those it uses
266
+ const [b1, w1] = inCommon(MSB, MSW).map((t) => t.at);
267
+ const [b3, e3] = inCommon(MSB, MSE).map((t) => t.at);
268
+ const [b2, j2, e2] = inCommon(MSB, MSJ, MSE).map((t) => t.at);
269
+ const icc1 = (b1 - w1) / (b1 + (k - 1) * w1);
270
+ const icc2 = (b2 - e2) / (b2 + (k - 1) * e2 + (k * (j2 - e2)) / n);
271
+ const icc3 = (b3 - e3) / (b3 + (k - 1) * e3);
272
+ // ICC2's interval (Shrout and Fleiss 1979, eq. for case 2): Satterthwaite's v of the combination k ICC2 MSJ + (n(1 +
273
+ // (k - 1) ICC2) - k ICC2) MSE, written with MSE multiplied through (Fj = MSJ/MSE in the paper), so that MSE = 0 gives
274
+ // its limit k - 1 (and MSJ = MSE = 0, where any v gives the bounds 1, k - 1 too)
275
+ // v does not change when a and c are scaled together: both are divided by the power of 2 of the larger, so that
276
+ // their squares neither overflow nor underflow (MSJ far beyond MSB and MSE made (n - 1) a^2 + c^2 underflow to 0)
277
+ const a0 = k * icc2 * j2;
278
+ const c0 = (n * (1 + (k - 1) * icc2) - k * icc2) * e2;
279
+ const top = Math.max(Math.abs(a0), Math.abs(c0));
280
+ const ka = top > 0 && Number.isFinite(top) ? Math.floor(Math.log2(top)) : 0;
281
+ const a = ldexp(a0, -ka);
282
+ const c = ldexp(c0, -ka);
283
+ const vDen = (n - 1) * a * a + c * c;
284
+ const v = vDen === 0 ? k - 1 : ((k - 1) * (n - 1) * (a + c) ** 2) / vDen;
285
+ const G1 = q(dfB, v);
286
+ const G2 = q(v, dfB);
287
+ // the bounds with numerator and denominator divided by G1 (and by G2 where it is above 1), so that a quantile that
288
+ // overflows (a tiny v, where ICC2 < 0 makes a and c nearly cancel) gives the limit G -> Infinity, not -Inf/Inf.
289
+ // Above 1/2 a bound is formed as 1 minus its complement, (n MSE + kJE)/(kJE + n MSB/G), which keeps it <= 1
290
+ const kJE = k * j2 + (k * n - k - n) * e2;
291
+ const bound = (b, den) => (b > 0.5 ? 1 - (n * e2 + kJE) / den : b);
292
+ const l2 = bound((n * (b2 / G1 - e2)) / (kJE + (n * b2) / G1), kJE + (n * b2) / G1);
293
+ const u2 = G2 > 1
294
+ ? bound((n * (b2 - e2 / G2)) / (kJE / G2 + n * b2), kJE + n * G2 * b2)
295
+ : bound((n * (G2 * b2 - e2)) / (kJE + n * G2 * b2), kJE + n * G2 * b2);
296
+ const sb = (r) => (r * k) / (1 + r * (k - 1));
297
+ const p1 = upperP(F1, dfB, dfW);
298
+ const p3 = upperP(F3, dfB, dfE);
299
+ const row = (type, ICCv, F, df2, p, lower, upper) => ({
300
+ type,
301
+ name: NAMES[type],
302
+ ICC: ICCv,
303
+ F,
304
+ df1: dfB,
305
+ df2,
306
+ pValue: p,
307
+ lower,
308
+ upper,
309
+ });
310
+ const results = [
311
+ row("ICC1", icc1, F1, dfW, p1, single(F1L), single(F1U)),
312
+ row("ICC2", icc2, F3, dfE, p3, l2, u2),
313
+ row("ICC3", icc3, F3, dfE, p3, single(F3L), single(F3U)),
314
+ row("ICC1k", (b1 - w1) / b1, F1, dfW, p1, average(F1L), average(F1U)),
315
+ row("ICC2k", (b2 - e2) / (b2 + (j2 - e2) / n), F3, dfE, p3, sb(l2), sb(u2)),
316
+ row("ICC3k", (b3 - e3) / b3, F3, dfE, p3, average(F3L), average(F3U)),
317
+ ];
318
+ // each mean square scaled back on its own
319
+ const back = (ms) => ldexpWide(ms.v[0], ms.e);
320
+ return reported("ICC", {
321
+ results,
322
+ MSB: back(MSB),
323
+ MSJ: back(MSJ),
324
+ MSE: back(MSE),
325
+ MSW: back(MSW),
326
+ n,
327
+ k,
328
+ confLevel,
329
+ lmer,
330
+ warnings,
331
+ });
332
+ }
@@ -14,7 +14,7 @@ export interface KsTestOptions {
14
14
  /**
15
15
  * Exact p-value. Default: exact for one sample of fewer than 100 values without ties, and for two samples with
16
16
  * m n < 10000. The exact two-sided one-sample p-value for D < 1/2 raises a matrix of size 2 floor(n D) + 1 to the
17
- * n-th power; where that needs more than 2^33 multiply-adds (m 781 at n 1023, about 4 s) it is a RangeError (R
17
+ * n-th power; where that needs more than 2^33 multiply-adds (m 783 at n 1023, about 4 s) it is a RangeError (R
18
18
  * computes it however long it takes).
19
19
  */
20
20
  exact?: boolean;