@numero-uno-jpn/rstats 1.0.0 → 1.2.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 (79) hide show
  1. package/CHANGELOG.md +101 -0
  2. package/README.ja.md +12 -11
  3. package/README.md +12 -11
  4. package/THIRD_PARTY_NOTICES.md +3 -2
  5. package/dist/chunks/{chunk-UJ66VQIG.js → chunk-2NNBUYHJ.js} +2 -2
  6. package/dist/chunks/{chunk-YHNMBYSW.js → chunk-47IIPUFN.js} +2 -2
  7. package/dist/chunks/{chunk-WIBKS73G.js → chunk-4AOTAT3O.js} +2 -2
  8. package/dist/chunks/{chunk-4F2IALD4.js → chunk-5SGTWSCB.js} +3 -3
  9. package/dist/chunks/{chunk-F7YGX7PN.js → chunk-6FZHTD5G.js} +2 -2
  10. package/dist/chunks/{chunk-NSWENS3S.js → chunk-73LNRWU3.js} +1 -1
  11. package/dist/chunks/{chunk-BQSIBJVX.js → chunk-7INBXTVV.js} +2 -2
  12. package/dist/chunks/chunk-7WG7X2UI.js +2 -0
  13. package/dist/chunks/{chunk-H7I32ZZE.js → chunk-A66M3ZEA.js} +2 -2
  14. package/dist/chunks/{chunk-BWKHYRM6.js → chunk-BI7NYJWP.js} +1 -1
  15. package/dist/chunks/{chunk-QZK3CCBA.js → chunk-BKV3FINA.js} +2 -2
  16. package/dist/chunks/{chunk-QQX46TCI.js → chunk-CQB4BJBR.js} +2 -2
  17. package/dist/chunks/{chunk-3W5NFFAA.js → chunk-EEU7D4RU.js} +1 -1
  18. package/dist/chunks/{chunk-DCAWMF4K.js → chunk-F3EQLL4F.js} +2 -2
  19. package/dist/chunks/{chunk-IEOD5GWC.js → chunk-HBHMEPGY.js} +2 -2
  20. package/dist/chunks/{chunk-4OLDGML4.js → chunk-IAWXF73N.js} +2 -2
  21. package/dist/chunks/{chunk-CKV4JWW2.js → chunk-IMPRIQE5.js} +1 -1
  22. package/dist/chunks/chunk-JWBSEL3V.js +2 -0
  23. package/dist/chunks/{chunk-LROMWFAK.js → chunk-L23RSC2N.js} +2 -2
  24. package/dist/chunks/{chunk-UKNDX4BA.js → chunk-NSU6U3ET.js} +2 -2
  25. package/dist/chunks/{chunk-WQWZ7FND.js → chunk-ORE5ZRCY.js} +2 -2
  26. package/dist/chunks/{chunk-YG5S5AVP.js → chunk-RRO4LMCB.js} +2 -2
  27. package/dist/chunks/{chunk-6XJBCRBV.js → chunk-T5DRIITM.js} +2 -2
  28. package/dist/chunks/{chunk-63OPBEYO.js → chunk-TNETWBF5.js} +1 -1
  29. package/dist/chunks/{chunk-O2SQMGE3.js → chunk-VERBXW6E.js} +2 -2
  30. package/dist/descriptive.js +2 -2
  31. package/dist/distributions/signrank.js +2 -2
  32. package/dist/distributions.js +2 -2
  33. package/dist/entries/tests.d.ts +6 -1
  34. package/dist/entries/tests.js +5 -0
  35. package/dist/htest/ansariTest.js +32 -34
  36. package/dist/htest/binomCI.d.ts +116 -0
  37. package/dist/htest/binomCI.js +252 -0
  38. package/dist/htest/boschlooTest.d.ts +65 -0
  39. package/dist/htest/boschlooTest.js +394 -0
  40. package/dist/htest/chisqTest.d.ts +19 -0
  41. package/dist/htest/chisqTest.js +30 -2
  42. package/dist/htest/cor.d.ts +2 -2
  43. package/dist/htest/cor.js +2 -1
  44. package/dist/htest/core/scoreDistribution.d.ts +39 -0
  45. package/dist/htest/core/scoreDistribution.js +151 -0
  46. package/dist/htest/core/twoProportions.d.ts +48 -0
  47. package/dist/htest/core/twoProportions.js +476 -0
  48. package/dist/htest/equivalence.d.ts +172 -0
  49. package/dist/htest/equivalence.js +189 -0
  50. package/dist/htest/fisherTest.d.ts +49 -0
  51. package/dist/htest/fisherTest.js +136 -13
  52. package/dist/htest/tableTests.d.ts +216 -0
  53. package/dist/htest/tableTests.js +650 -0
  54. package/dist/htest/twoByTwo.d.ts +203 -0
  55. package/dist/htest/twoByTwo.js +385 -0
  56. package/dist/htest/wilcoxTest.d.ts +23 -8
  57. package/dist/htest/wilcoxTest.js +521 -199
  58. package/dist/linalg/chol.d.ts +3 -3
  59. package/dist/linalg/chol.js +10 -2
  60. package/dist/linalg/qr.js +39 -15
  61. package/dist/linalg.js +2 -2
  62. package/dist/mixed.js +2 -2
  63. package/dist/models/anovaSequential.d.ts +16 -1
  64. package/dist/models/anovaSequential.js +40 -5
  65. package/dist/models/aovStrata.js +21 -4
  66. package/dist/models/glm.d.ts +15 -4
  67. package/dist/models/glm.js +13 -6
  68. package/dist/models/survival.d.ts +4 -1
  69. package/dist/models/survival.js +7 -1
  70. package/dist/numerics.js +2 -2
  71. package/dist/rstats.js +16 -16
  72. package/dist/special/igam.js +140 -23
  73. package/dist/special/loader.js +8 -0
  74. package/dist/special.js +2 -2
  75. package/dist/tests.js +13 -13
  76. package/llms.txt +9 -1
  77. package/package.json +1 -1
  78. package/dist/chunks/chunk-KICBQGFN.js +0 -2
  79. package/dist/chunks/chunk-WWVMVZUL.js +0 -2
@@ -0,0 +1,650 @@
1
+ // Tests and measures of r x c tables: the G-test (DescTools' GTest), the Stuart-Maxwell test (DescTools'
2
+ // StuartMaxwellTest), Goodman and Kruskal's gamma (DescTools' GoodmanKruskalGamma), the linear-by-linear association
3
+ // test (coin's lbl_test, asymptotic) and the Freeman-Tukey deviates used by chisqTest and gTest.
4
+ //
5
+ // Written for rStats.js from the published statistics and the packages' documented behaviour (no R or package code;
6
+ // oracle/contingency-behaviour.md section 5):
7
+ // - G-test (Sokal and Rohlf, Biometry, 3rd ed. 1995, section 17.4; Williams, Biometrika 63, 1976, for the correction
8
+ // q): G = 2 sum x log(x / E) / q, chi-squared with (r - 1)(c - 1) df (k - 1 for goodness of fit). G is summed as the
9
+ // deviance 2 sum (x log(x / E) + E - x), whose terms are nonnegative (bd0, Loader 2000), with E in double-double:
10
+ // sum (E - x) is 0 for a table (exactly, for the unrounded E) and n (sum p - 1) for goodness of fit (added back). The
11
+ // plain sum of x log(x / E) cancels where G is small against the counts. The p-value is the upper tail (DescTools
12
+ // takes 1 - pchisq for a table, 0 below about 1.1e-16; rule 2)
13
+ // - Stuart-Maxwell (Stuart, Biometrika 42, 1955; Maxwell, Brit. J. Psychiatry 116, 1970): d' S^-1 d with d the
14
+ // differences of the margins and S their covariance, for all but the last category, after removing the categories
15
+ // without off-diagonal counts; df = K - 1 with K the categories left (choice 11; DescTools keeps the original size)
16
+ // - Goodman and Kruskal's gamma (Goodman and Kruskal, JASA 49, 1954) with the non-null asymptotic standard error ASE1
17
+ // (Agresti, Analysis of Ordinal Categorical Data, 2nd ed. 2010, section 7.1)
18
+ // - Linear-by-linear association (Agresti, Categorical Data Analysis, 3rd ed. 2013, section 3.4.1; Mantel, JASA 58,
19
+ // 1963): Z = sqrt(N - 1) r, r the Pearson correlation of the row and column scores over the N observations, the
20
+ // standardised linear statistic under the permutation (conditional) distribution; scores 1..k for every factor
21
+ // (choice 14: coin codes a two-level factor by an indicator of its first level, which turns the sign, and refuses
22
+ // 2 x 2 tables)
23
+ // - Freeman-Tukey deviates (Freeman and Tukey, Ann. Math. Statist. 21, 1950; Bishop, Fienberg and Holland, Discrete
24
+ // Multivariate Analysis, 1975, section 14.7): sqrt(O) + sqrt(O + 1) - sqrt(4E + 1), approximately N(0, 1)
25
+ import { pgamma1 } from "../distributions/gamma.js";
26
+ import { pnorm, qnorm } from "../distributions/normal.js";
27
+ import { ldexp } from "../internal/summary.js";
28
+ import { reported } from "../internal/warnings.js";
29
+ import { bd0dd } from "../special/loader.js";
30
+ import { ddAdd, ddDiv, ddMul, ddMulNum, ddSub } from "../special/dd.js";
31
+ import { matchChoice } from "./power.js";
32
+ import { matchAlternative } from "./types.js";
33
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
34
+ import { checkOptions } from "../internal/checkOptions.js";
35
+ const G_TEST_KEYS = ["correct", "p", "rescaleP"];
36
+ const GOODMAN_KRUSKAL_GAMMA_KEYS = ["confLevel"];
37
+ const LBL_TEST_KEYS = ["alternative", "rowScores", "colScores"];
38
+ // Generated by `node scripts/option-keys.mjs --write` (end)
39
+ // ---- shared ----
40
+ /** Double-double sum of doubles */
41
+ function ddSumOf(x) {
42
+ let s = [0, 0];
43
+ for (const v of x)
44
+ s = ddAdd(s, [v, 0]);
45
+ return s;
46
+ }
47
+ /** A matrix given as an array of rows: copied, with rows of equal length */
48
+ function matrixOf(x) {
49
+ const rows = x.map((r) => {
50
+ if (typeof r !== "object" || r === null || typeof r.length !== "number") {
51
+ throw new TypeError("'x' must be an array of numbers or an array of rows");
52
+ }
53
+ return Array.from(r);
54
+ });
55
+ const nc = rows[0].length;
56
+ if (rows.some((r) => r.length !== nc))
57
+ throw new TypeError("all rows of the matrix must have the same length");
58
+ if (rows.flat().some((v) => typeof v !== "number"))
59
+ throw new TypeError("the entries of 'x' must be numbers");
60
+ return rows;
61
+ }
62
+ /** Whether x is a matrix (an array of rows) rather than a vector */
63
+ const isMatrix = (x) => x.length > 0 && typeof x[0] !== "number";
64
+ /** p-value of the upper tail of chi-squared with df degrees of freedom */
65
+ const upperChisq = (stat, df) => (Number.isNaN(stat) ? NaN : pgamma1(stat, df / 2, 2, false, false));
66
+ /**
67
+ * Freeman-Tukey deviate sqrt(O) + sqrt(O + 1) - sqrt(4E + 1) (Bishop, Fienberg and Holland 1975, 14.7). The plain
68
+ * formula cancels for large counts (sqrt(O) + sqrt(O + 1) against sqrt(4E + 1), losing eps sqrt(O) absolute); here it
69
+ * is (a^2 - b^2) / (a + b) with a = sqrt(O) + sqrt(O + 1), b = sqrt(4E + 1) and
70
+ * a^2 - b^2 = 2(O - E) + 2 ((O - E)(O + E) + O) / (sqrt(O (O + 1)) + E), whose rounding is a few eps absolute
71
+ */
72
+ export function freemanTukeyDeviate(O, E) {
73
+ if (!(O >= 0 && E >= 0 && O < Infinity && E < Infinity))
74
+ return NaN;
75
+ const so = Math.sqrt(O);
76
+ const so1 = Math.sqrt(O + 1);
77
+ const den = so * so1 + E;
78
+ // O = E = 0: a = b = 1
79
+ const product = (O - E) * (O + E);
80
+ if (Number.isFinite(product)) {
81
+ const second = den === 0 ? 0 : (product + O) / den;
82
+ return (2 * (O - E) + 2 * second) / (so + so1 + Math.sqrt(4 * E + 1));
83
+ }
84
+ // counts above about 1e154: (O - E)(O + E) overflows (the deviates of [[1e200, 2e200], [3e200, 4e200]] were
85
+ // -Infinity and Infinity for values near 1e99). The same with (O + E) / den first, halves, and sqrt(4E + 1) as
86
+ // 2 sqrt(E + 1/4)
87
+ const second = (O - E) * ((O + E) / den) + O / den;
88
+ return (0.5 * (O - E) + 0.5 * second) / ((so + so1 + 2 * Math.sqrt(E + 0.25)) / 4);
89
+ }
90
+ export function freemanTukeyResiduals(O, E) {
91
+ if (O.length > 0 && Array.isArray(O[0])) {
92
+ return O.map((r, i) => r.map((v, j) => freemanTukeyDeviate(v, E[i][j])));
93
+ }
94
+ return O.map((v, i) => freemanTukeyDeviate(v, E[i]));
95
+ }
96
+ const G_CORRECTIONS = ["none", "williams", "yates"];
97
+ const G_METHOD = "Log likelihood ratio (G-test)";
98
+ /**
99
+ * Log-likelihood ratio (G) test of independence in a contingency table, or of goodness of fit of counts to given
100
+ * probabilities. Equivalent to `DescTools::GTest()` in R.
101
+ *
102
+ * For a table (an array of rows), `G = 2 sum x log(x / E) / q` with `E` the products of the margins over the total and
103
+ * `(r - 1)(c - 1)` degrees of freedom, counting empty rows and columns as DescTools; for a vector (or a table with one
104
+ * row or column), `E = n p` and `k - 1` degrees of freedom. `correct: "williams"` divides by Williams' q
105
+ * (`1 + (n sum 1/R_i - 1)(n sum 1/C_j - 1) / (6 n (r - 1)(c - 1))` for a table, which is not defined with an empty
106
+ * row or column: an error, where DescTools gives G = 0 and p = 1; and `1 + (k + 1) / (6n)` for a vector). `correct: "yates"` moves the counts of a 2 x 2 table by 0.5 toward
107
+ * independence as DescTools does: the off-diagonal cells up and the diagonal down when `x11 x22 - x12 x21 > 0`, and
108
+ * the other way otherwise, also when it is 0 (so that a table of exact independence gets a positive G), and without
109
+ * stopping at 0 (a cell that becomes negative makes G NaN, with the warning "NaNs produced"). For two counts it moves
110
+ * them by 0.5 toward `E` when they differ from it by more than 0.25.
111
+ *
112
+ * The p-value is the upper tail of chi-squared (DescTools computes `1 - pchisq` for a table, which is 0 below about
113
+ * 1e-16). G is summed as a deviance, without the cancellation of the plain sum. The result also has the Freeman-Tukey
114
+ * deviates `ftResiduals`.
115
+ *
116
+ * @param x Counts (nonnegative, finite; not all 0), or a contingency table as an array of rows.
117
+ * @param options See {@link GTestOptions}.
118
+ * @returns The test result, with `statisticName` `"G"`; see {@link GTestResult}.
119
+ * @throws RangeError for negative or non-finite counts, a total of 0, fewer than 2 counts, `p` of the wrong length,
120
+ * negative or not summing to 1, `"yates"` for anything but a 2 x 2 table or two counts, and `"williams"` for a
121
+ * table with an empty row or column.
122
+ *
123
+ * @example
124
+ * ```ts
125
+ * gTest([[12, 5], [7, 9]]).statistic; // 2.4600430077307167
126
+ * gTest([[12, 5], [7, 9]], { correct: "williams" }).pValue; // 0.12530270793206313
127
+ * gTest([10, 20, 30], { p: [0.2, 0.3, 0.5] }).pValue; // 0.7527706003419717
128
+ * ```
129
+ *
130
+ * @category Hypothesis tests
131
+ */
132
+ export function gTest(x, options = {}) {
133
+ checkOptions(options, G_TEST_KEYS, "gTest"); // generated: option-keys.mjs
134
+ const correct = matchChoice(options.correct, G_CORRECTIONS);
135
+ if (typeof x !== "object" || x === null || typeof x.length !== "number")
136
+ throw new TypeError("'x' must be an array of counts or of rows");
137
+ if (isMatrix(x)) {
138
+ const rows = matrixOf(x);
139
+ checkCounts(rows.flat());
140
+ // a matrix with one row or column is a vector, as DescTools
141
+ if (rows.length === 1)
142
+ return reported("gTest", gGoodnessOfFit(rows[0], correct, options));
143
+ if (rows[0].length === 1)
144
+ return reported("gTest", gGoodnessOfFit(rows.map((r) => r[0]), correct, options));
145
+ return reported("gTest", gIndependence(rows, correct));
146
+ }
147
+ const v = Array.from(x);
148
+ if (v.some((e) => typeof e !== "number"))
149
+ throw new TypeError("the entries of 'x' must be numbers");
150
+ checkCounts(v);
151
+ return reported("gTest", gGoodnessOfFit(v, correct, options));
152
+ }
153
+ /** Nonnegative finite counts with a positive total (DescTools' checks) */
154
+ function checkCounts(v) {
155
+ if (v.some((e) => !(e >= 0 && e < Infinity)))
156
+ throw new RangeError("all entries of 'x' must be nonnegative and finite");
157
+ if (!v.some((e) => e > 0))
158
+ throw new RangeError("at least one entry of 'x' must be positive");
159
+ }
160
+ /**
161
+ * The power of 2, s, by which counts whose total overflows are divided (0 when it is finite): G is homogeneous of
162
+ * degree 1 in the counts, so it is computed from x 2^-s and multiplied back
163
+ */
164
+ function overflowShift(total, m) {
165
+ return total < Infinity ? 0 : Math.ceil(Math.log2(m)) + 1;
166
+ }
167
+ /**
168
+ * sum x log(x / E) as sum bd0(x, E) (x log(x/E) + E - x >= 0), with the cells x < 0 (after Yates' correction) giving
169
+ * NaN and x > 0 with E = 0 Inf
170
+ */
171
+ function devianceSum(x, E) {
172
+ // a negative cell first: its log is NaN, which wins over an infinite term in the sum
173
+ if (x.some((o) => o < 0))
174
+ return NaN;
175
+ let s = [0, 0];
176
+ for (let i = 0; i < x.length; i++) {
177
+ const o = x[i];
178
+ const e = E[i];
179
+ if (o > 0 && e[0] === 0)
180
+ return Infinity;
181
+ s = ddAdd(s, bd0dd(o, e));
182
+ }
183
+ return s[0] + s[1];
184
+ }
185
+ function gIndependence(x0, correct) {
186
+ const nr = x0.length;
187
+ const nc = x0[0].length;
188
+ if (correct === "yates" && (nr !== 2 || nc !== 2))
189
+ throw new RangeError("Yates' correction requires a 2 x 2 matrix");
190
+ const total = ddSumOf(x0.flat());
191
+ const sh = overflowShift(total[0], nr * nc);
192
+ const xs = sh === 0 ? x0 : x0.map((r) => r.map((v) => ldexp(v, -sh)));
193
+ const n = sh === 0 ? total : ddSumOf(xs.flat());
194
+ const R = xs.map((r) => ddSumOf(r));
195
+ const C = xs[0].map((_, j) => ddSumOf(xs.map((r) => r[j])));
196
+ // E in double-double: sum E = n exactly in the mathematics, which the deviance form relies on. R (C / n): the product
197
+ // of two margins can overflow where E cannot
198
+ const Edd = R.map((a) => C.map((b) => ddMul(a, ddDiv(b, n))));
199
+ let obs = xs;
200
+ if (correct === "yates") {
201
+ const [[a, b], [c, d]] = xs;
202
+ // as DescTools: the diagonal moves down only when ad - bc > 0; at ad = bc (exact independence) it moves up too,
203
+ // away from independence ([[5, 5], [5, 5]] gets G = 0.2003), and no cell is stopped at 0
204
+ const s = a * d - b * c > 0 ? -0.5 : 0.5;
205
+ const h = ldexp(0.5, -sh);
206
+ const t = s < 0 ? -h : h;
207
+ obs = [
208
+ [a + t, b - t],
209
+ [c - t, d + t],
210
+ ];
211
+ }
212
+ const raw = devianceSum(obs.flat(), Edd.flat());
213
+ const warnings = Number.isNaN(raw) ? ["NaNs produced"] : [];
214
+ let q = 1;
215
+ if (correct === "williams") {
216
+ // an empty row or column makes 1/R_i infinite: q = Infinity and G = 0, p = 1 in DescTools; an error here (rule 1)
217
+ if (R.some((r) => r[0] === 0) || C.some((c) => c[0] === 0)) {
218
+ throw new RangeError("Williams' correction is not defined for a table with an empty row or column");
219
+ }
220
+ // n sum 1/R_i and n sum 1/C_j do not depend on the units; 6 n does (with the scaled n, 2^-sh back below)
221
+ const nn = n[0] + n[1];
222
+ const sr = R.reduce((acc, r) => acc + 1 / (r[0] + r[1]), 0);
223
+ const sc = C.reduce((acc, r) => acc + 1 / (r[0] + r[1]), 0);
224
+ q = 1 + ldexp(((nn * sr - 1) * (nn * sc - 1)) / (6 * nn * (nr - 1) * (nc - 1)), -sh);
225
+ }
226
+ const G = ldexp(2 * raw, sh) / q;
227
+ const df = (nr - 1) * (nc - 1);
228
+ const E = Edd.map((r) => r.map((e) => ldexp(e[0] + e[1], sh)));
229
+ const method = `${G_METHOD} test of independence ${correct === "none" ? "without correction" : correct === "williams" ? "with Williams' correction" : "with Yates' correction"}`;
230
+ return {
231
+ method,
232
+ statistic: G,
233
+ statisticName: "G",
234
+ parameter: df,
235
+ // as DescTools
236
+ parameterName: "X-squared df",
237
+ pValue: upperChisq(G, df),
238
+ observed: sh === 0 ? obs : obs.map((r) => r.map((v) => ldexp(v, sh))),
239
+ expected: E,
240
+ ftResiduals: freemanTukeyResiduals(x0, E),
241
+ warnings,
242
+ };
243
+ }
244
+ function gGoodnessOfFit(x0, correct, options) {
245
+ const k = x0.length;
246
+ if (k < 2)
247
+ throw new RangeError("'x' must have at least 2 elements");
248
+ if (correct === "yates" && k !== 2)
249
+ throw new RangeError("Yates' correction requires 2 data values");
250
+ const rescale = options.rescaleP ?? false;
251
+ if (typeof rescale !== "boolean")
252
+ throw new TypeError("'rescaleP' must be a boolean");
253
+ const p = options.p === undefined ? x0.map(() => 1 / k) : Array.from(options.p);
254
+ if (p.length !== k)
255
+ throw new RangeError("'x' and 'p' must have the same number of elements");
256
+ if (p.some((v) => typeof v !== "number" || Number.isNaN(v)))
257
+ throw new RangeError("'p' must not contain missing values");
258
+ if (p.some((v) => v < 0))
259
+ throw new RangeError("probabilities must be non-negative");
260
+ if (p.some((v) => v === Infinity))
261
+ throw new RangeError("probabilities must be finite");
262
+ const pSum = ddSumOf(p);
263
+ if (rescale) {
264
+ if (!(pSum[0] > 0 && pSum[0] < Infinity))
265
+ throw new RangeError("the probabilities to rescale must have a positive finite sum");
266
+ }
267
+ else if (Math.abs(pSum[0] - 1 + pSum[1]) > Math.sqrt(Number.EPSILON)) {
268
+ throw new RangeError("probabilities must sum to 1");
269
+ }
270
+ const total = ddSumOf(x0);
271
+ const sh = overflowShift(total[0], k);
272
+ const xs = sh === 0 ? x0 : x0.map((v) => ldexp(v, -sh));
273
+ const n = sh === 0 ? total : ddSumOf(xs);
274
+ // E = n p (rescaled: n p / sum p) in double-double
275
+ const Edd = p.map((v) => (rescale ? ddDiv(ddMulNum(n, v), pSum) : ddMulNum(n, v)));
276
+ const E = Edd.map((e) => e[0] + e[1]);
277
+ let obs = xs;
278
+ if (correct === "yates") {
279
+ // as DescTools: 0.5 toward E where the first count differs from it by more than 0.25
280
+ const h = ldexp(0.5, -sh);
281
+ const d = xs[0] - E[0];
282
+ if (d > ldexp(0.25, -sh))
283
+ obs = [xs[0] - h, xs[1] + h];
284
+ else if (-d > ldexp(0.25, -sh))
285
+ obs = [xs[0] + h, xs[1] - h];
286
+ }
287
+ let raw = devianceSum(obs, Edd);
288
+ // sum x log(x / E) = sum bd0(x, E) - (sum E - n), and sum E - n = n (sum p - 1) unless p is rescaled
289
+ if (!rescale && !Number.isNaN(raw)) {
290
+ const nn = n[0] + n[1];
291
+ raw -= nn * (pSum[0] - 1 + pSum[1]);
292
+ }
293
+ const warnings = Number.isNaN(raw) ? ["NaNs produced"] : [];
294
+ // Williams: 1 + (k + 1) / (6 n), with the n of the counts given
295
+ const q = correct === "williams" ? 1 + (k + 1) / (6 * ldexp(n[0] + n[1], sh)) : 1;
296
+ const G = ldexp(2 * raw, sh) / q;
297
+ const Eout = E.map((e) => ldexp(e, sh));
298
+ return {
299
+ method: `${G_METHOD} goodness of fit test`,
300
+ statistic: G,
301
+ statisticName: "G",
302
+ parameter: k - 1,
303
+ parameterName: "X-squared df",
304
+ pValue: upperChisq(G, k - 1),
305
+ observed: sh === 0 ? obs : obs.map((v) => ldexp(v, sh)),
306
+ expected: Eout,
307
+ ftResiduals: freemanTukeyResiduals(x0, Eout),
308
+ warnings,
309
+ };
310
+ }
311
+ /** A square table of nonnegative finite counts with at least two rows */
312
+ function squareTable(x) {
313
+ if (typeof x !== "object" || x === null || !isMatrix(x)) {
314
+ throw new RangeError("'x' must be square with at least two rows and columns");
315
+ }
316
+ const t = matrixOf(x);
317
+ const r = t.length;
318
+ if (r < 2 || t[0].length !== r)
319
+ throw new RangeError("'x' must be square with at least two rows and columns");
320
+ if (t.flat().some((v) => !(v >= 0 && v < Infinity)))
321
+ throw new RangeError("all entries of 'x' must be nonnegative and finite");
322
+ return t;
323
+ }
324
+ /**
325
+ * Stuart-Maxwell test of marginal homogeneity of a square table (paired classifications into the same categories).
326
+ * Equivalent to `DescTools::StuartMaxwellTest()` in R. The degrees of freedom differ where categories are removed.
327
+ *
328
+ * Categories with no counts off the diagonal (in their row and column) are removed. With the K categories left, `d`
329
+ * the differences of the row and column sums of the first K - 1 and `S` their covariance (`S_ii = r_i + c_i - 2 x_ii`,
330
+ * `S_ij = -(x_ij + x_ji)`), the statistic `d' S^-1 d` is chi-squared with K - 1 degrees of freedom (DescTools keeps the
331
+ * original number of categories less 1). For a 2 x 2 table it is McNemar's statistic without correction.
332
+ *
333
+ * @param table A square table of counts as an array of rows.
334
+ * @returns The test result, with `statisticName` `"chi-squared"`; see {@link StuartMaxwellTestResult}.
335
+ * @throws RangeError for a table that is not square with at least two rows, negative or non-finite counts, fewer
336
+ * than 2 categories left ("Too many equal marginals, cannot compute") and categories whose off-diagonal counts fall
337
+ * into unconnected groups (S is then singular).
338
+ *
339
+ * @example
340
+ * ```ts
341
+ * stuartMaxwellTest([[20, 3, 2], [4, 15, 6], [1, 5, 30]]).statistic; // 0.30534351145038163
342
+ * ```
343
+ *
344
+ * @category Hypothesis tests
345
+ */
346
+ export function stuartMaxwellTest(table) {
347
+ const t0 = squareTable(table);
348
+ // the statistic is of degree 1 in the counts: they are divided by a power of 2 near their total where that is beyond
349
+ // 2^±400, and the statistic multiplied back (d^2 / S overflowed for [[0, 1e200], [3e200, 0]], underflowed to 0 for
350
+ // [[0, 1e-200], [3e-200, 0]])
351
+ const total = ddSumOf(t0.flat())[0];
352
+ const k = total > 2 ** 400 || (total > 0 && total < 2 ** -400) ? Math.round(Math.log2(total)) : 0;
353
+ const t = k === 0 ? t0 : t0.map((row) => row.map((v) => ldexp(v, -k)));
354
+ const r = t.length;
355
+ const rs = t.map((row) => ddSumOf(row));
356
+ const cs = t.map((_, j) => ddSumOf(t.map((row) => row[j])));
357
+ // the categories with counts off the diagonal
358
+ const keep = t.map((_, i) => t[i].some((v, j) => j !== i && v > 0) || t.some((row, j) => j !== i && row[i] > 0)).flatMap((k, i) => (k ? [i] : []));
359
+ const K = keep.length;
360
+ if (K < 2)
361
+ throw new RangeError("Too many equal marginals, cannot compute");
362
+ // S is a reduced graph Laplacian with the weights x_ij + x_ji: positive definite exactly when the categories kept
363
+ // are connected through their off-diagonal counts (R's solve fails for unconnected groups, or gives rounding noise)
364
+ const parent = keep.map((_, a) => a);
365
+ const find = (a) => (parent[a] === a ? a : (parent[a] = find(parent[a])));
366
+ for (let a = 0; a < K; a++) {
367
+ for (let b = a + 1; b < K; b++)
368
+ if (t[keep[a]][keep[b]] + t[keep[b]][keep[a]] > 0)
369
+ parent[find(a)] = find(b);
370
+ }
371
+ if (keep.some((_, a) => find(a) !== find(0))) {
372
+ throw new RangeError("the categories fall into groups without counts between them: the covariance matrix is singular");
373
+ }
374
+ const m = K - 1;
375
+ const d = keep.slice(0, m).map((i) => {
376
+ const v = ddAdd(rs[i], [-cs[i][0], -cs[i][1]]);
377
+ return v[0] + v[1];
378
+ });
379
+ const S = keep.slice(0, m).map((i) => keep.slice(0, m).map((j) => {
380
+ if (i !== j)
381
+ return -(t[i][j] + t[j][i]);
382
+ // the off-diagonal counts of row and column i (r_i + c_i - 2 x_ii without the cancellation)
383
+ let s = 0;
384
+ for (let l = 0; l < r; l++)
385
+ if (l !== i)
386
+ s += t[i][l] + t[l][i];
387
+ return s;
388
+ }));
389
+ // d' S^-1 d by S = L D L' (S symmetric positive definite): sum z_k^2 / D_k with L z = d. For 2 x 2 this is
390
+ // d^2 / S, McNemar's statistic, to the last bit
391
+ const L = S.map((row) => row.map(() => 0));
392
+ const D = [];
393
+ for (let j = 0; j < m; j++) {
394
+ let dj = S[j][j];
395
+ for (let k = 0; k < j; k++)
396
+ dj -= L[j][k] * L[j][k] * D[k];
397
+ D.push(dj);
398
+ for (let i = j + 1; i < m; i++) {
399
+ let v = S[i][j];
400
+ for (let k = 0; k < j; k++)
401
+ v -= L[i][k] * L[j][k] * D[k];
402
+ L[i][j] = v / dj;
403
+ }
404
+ }
405
+ let stat = 0;
406
+ const z = [];
407
+ for (let i = 0; i < m; i++) {
408
+ let v = d[i];
409
+ for (let k = 0; k < i; k++)
410
+ v -= L[i][k] * z[k];
411
+ z.push(v);
412
+ stat += (v * v) / D[i];
413
+ }
414
+ const N = ddSumOf(keep.flatMap((i) => keep.map((j) => t0[i][j])));
415
+ const df = K - 1;
416
+ stat = ldexp(stat, k);
417
+ return reported("stuartMaxwellTest", {
418
+ method: "Stuart-Maxwell test",
419
+ statistic: stat,
420
+ statisticName: "chi-squared",
421
+ parameter: df,
422
+ parameterName: "df",
423
+ pValue: upperChisq(stat, df),
424
+ N: N[0] + N[1],
425
+ warnings: [],
426
+ });
427
+ }
428
+ /**
429
+ * Goodman and Kruskal's gamma of a table of two ordered classifications, with its asymptotic standard error and a
430
+ * Wald confidence interval. Equivalent to `DescTools::GoodmanKruskalGamma()` in R.
431
+ *
432
+ * `gamma = (C - D) / (C + D)` with C and D the numbers of concordant and discordant pairs. The standard error is the
433
+ * non-null ASE1 (Agresti 2010, section 7.1): `sqrt(sum x psi^2)` with `psi_ij = 2 (D Pc_ij - C Pd_ij) / (C + D)^2`,
434
+ * `Pc_ij` the counts above-left and below-right of cell (i, j) and `Pd_ij` those above-right and below-left. The
435
+ * interval is `[max(-1, gamma - z ase), min(1, gamma + z ase)]`, z the normal quantile of `1 - (1 - confLevel) / 2`.
436
+ * Without concordant or discordant pairs (a table with one row, for example) gamma and the interval are NaN, as
437
+ * DescTools. No test of gamma = 0 is given (it would need the null standard error).
438
+ *
439
+ * @param table A table of counts (nonnegative, finite) as an array of rows; rows and columns in their order.
440
+ * @param options See {@link GoodmanKruskalGammaOptions}.
441
+ * @returns See {@link GoodmanKruskalGammaResult}.
442
+ * @throws RangeError for negative or non-finite counts, or a level outside (0, 1).
443
+ *
444
+ * @example
445
+ * ```ts
446
+ * const g = goodmanKruskalGamma([[10, 5, 2], [3, 8, 6], [1, 4, 9]]);
447
+ * g.estimate; // 0.6703296703296703
448
+ * g.confInt; // [0.4241347346132843, 0.9165246060460562]
449
+ * ```
450
+ *
451
+ * @category Hypothesis tests
452
+ */
453
+ export function goodmanKruskalGamma(table, options = {}) {
454
+ checkOptions(options, GOODMAN_KRUSKAL_GAMMA_KEYS, "goodmanKruskalGamma"); // generated: option-keys.mjs
455
+ const confLevel = options.confLevel ?? 0.95;
456
+ if (!(typeof confLevel === "number" && confLevel > 0 && confLevel < 1))
457
+ throw new RangeError("'confLevel' must be a single number in (0, 1)");
458
+ const t0 = countTable(table);
459
+ // counts scaled by 2^-k (k even) where the total is beyond 2^±250: C and D grow as the square of the total and
460
+ // (C + D)^2 as its fourth power ([[1e80, 1e79], [1e79, 1e80]] overflowed to ase 0, [[1e160, 1], [1, 1e160]] to
461
+ // gamma NaN). Gamma does not depend on the scale and ase goes with its inverse square root
462
+ const total = ddSumOf(t0.flat())[0];
463
+ let k = 0;
464
+ if (total > 2 ** 250 || (total > 0 && total < 2 ** -250))
465
+ k = 2 * Math.round((Math.log2(total) - 250) / 2);
466
+ const t = k === 0 ? t0 : t0.map((row) => row.map((v) => ldexp(v, -k)));
467
+ const { pc, pd } = pairCounts(t);
468
+ // C and D, sums of x times its concordant (discordant) counts over 2, in double-double
469
+ let C = [0, 0];
470
+ let D = [0, 0];
471
+ t.forEach((row, i) => row.forEach((v, j) => {
472
+ C = ddAdd(C, ddMulNum(pc[i][j], v));
473
+ D = ddAdd(D, ddMulNum(pd[i][j], v));
474
+ }));
475
+ C = [C[0] / 2, C[1] / 2];
476
+ D = [D[0] / 2, D[1] / 2];
477
+ const CD = ddAdd(C, D);
478
+ const gamma = ddDiv(ddSub(C, D), CD)[0];
479
+ // sigma^2 = sum x psi^2 - (sum x psi)^2; the second sum is 0 in the mathematics (and below 1e-30 as DescTools
480
+ // computes it), so it is left out. psi = 2 (D Pc - C Pd) / (C + D)^2 in double-double: the difference cancels where
481
+ // one count dominates ([[1e17, 1, 2], [3, 4, 5], [6, 7, 8]] gave ase 0 for 4.0229e-17)
482
+ const den = ddMul(CD, CD);
483
+ const psi = t.map((row, i) => row.map((_, j) => 2 * ddDiv(ddSub(ddMul(D, pc[i][j]), ddMul(C, pd[i][j])), den)[0]));
484
+ // the squares relative to a power of 2 near the largest |psi| (they can fall below the doubles: ase 2.8e-320 of
485
+ // [[1e160, 1], [1, 1e160]])
486
+ const top = Math.max(...psi.flat().map(Math.abs));
487
+ const e = top > 0 && top < Infinity ? Math.floor(Math.log2(top)) : 0;
488
+ let v2 = 0;
489
+ t.forEach((row, i) => row.forEach((v, j) => {
490
+ const p = ldexp(psi[i][j], -e);
491
+ v2 += v * p * p;
492
+ }));
493
+ const ase = ldexp(Math.sqrt(v2), e - k / 2);
494
+ // (rule 10: for alpha/2 below 1e-8 the upper tail itself; at 1 - 1e-12 the lower limit of the table of the tests was
495
+ // 0.49697682431400764 for 0.4969760640579014)
496
+ const a2 = (1 - confLevel) / 2;
497
+ const z = a2 < 1e-8 ? qnorm(a2, { lowerTail: false }) : qnorm(1 - a2);
498
+ return reported("goodmanKruskalGamma", {
499
+ estimate: gamma,
500
+ confInt: [Math.max(-1, gamma - z * ase), Math.min(1, gamma + z * ase)],
501
+ confLevel,
502
+ ase,
503
+ warnings: [],
504
+ });
505
+ }
506
+ /** A table of nonnegative finite counts with at least one row and column */
507
+ function countTable(x) {
508
+ if (typeof x !== "object" || x === null || !isMatrix(x))
509
+ throw new TypeError("'table' must be an array of rows");
510
+ const t = matrixOf(x);
511
+ if (t[0].length === 0)
512
+ throw new RangeError("'table' must have at least one column");
513
+ if (t.flat().some((v) => !(v >= 0 && v < Infinity)))
514
+ throw new RangeError("all entries of 'table' must be nonnegative and finite");
515
+ return t;
516
+ }
517
+ /**
518
+ * For each cell, the counts concordant with it (above-left and below-right) and discordant (above-right, below-left),
519
+ * in double-double. Each quadrant is a sum of nonnegative row sums (no inclusion-exclusion of prefix sums, which lost
520
+ * the small rectangles next to a large count: 1e17 + 8 - 1e17)
521
+ */
522
+ function pairCounts(t) {
523
+ const nr = t.length;
524
+ const nc = t[0].length;
525
+ const zero = [0, 0];
526
+ // the row sums left of j (pre) and right of j (suf)
527
+ const pre = t.map((row) => {
528
+ const out = [];
529
+ let acc = zero;
530
+ for (let j = 0; j < nc; j++) {
531
+ out.push(acc);
532
+ acc = ddAdd(acc, [row[j], 0]);
533
+ }
534
+ return out;
535
+ });
536
+ const suf = t.map((row) => {
537
+ const out = new Array(nc);
538
+ let acc = zero;
539
+ for (let j = nc - 1; j >= 0; j--) {
540
+ out[j] = acc;
541
+ acc = ddAdd(acc, [row[j], 0]);
542
+ }
543
+ return out;
544
+ });
545
+ // the sums of a row quantity over the rows above (k < i) and below (k > i)
546
+ const above = (q) => {
547
+ const out = [];
548
+ let acc = new Array(nc).fill(zero);
549
+ for (let i = 0; i < nr; i++) {
550
+ out.push(acc);
551
+ acc = acc.map((a, j) => ddAdd(a, q[i][j]));
552
+ }
553
+ return out;
554
+ };
555
+ const below = (q) => {
556
+ const out = new Array(nr);
557
+ let acc = new Array(nc).fill(zero);
558
+ for (let i = nr - 1; i >= 0; i--) {
559
+ out[i] = acc;
560
+ acc = acc.map((a, j) => ddAdd(a, q[i][j]));
561
+ }
562
+ return out;
563
+ };
564
+ const ul = above(pre);
565
+ const lr = below(suf);
566
+ const ur = above(suf);
567
+ const ll = below(pre);
568
+ const pc = ul.map((row, i) => row.map((v, j) => ddAdd(v, lr[i][j])));
569
+ const pd = ur.map((row, i) => row.map((v, j) => ddAdd(v, ll[i][j])));
570
+ return { pc, pd };
571
+ }
572
+ /**
573
+ * Asymptotic linear-by-linear association test of a table of two ordered classifications (the Mantel test of trend).
574
+ * Equivalent to `coin::lbl_test()` in R. As coin's asymptotic test, except for tables with a two-level factor.
575
+ *
576
+ * `Z = sqrt(N - 1) r`, r the Pearson correlation of the row and column scores over the N observations: the linear
577
+ * statistic `sum x_ij u_i v_j` standardised by its permutation (conditional) mean and variance. The scores are 1..k
578
+ * by default for every factor (the level index; empty rows and columns keep their place). coin leaves a two-level
579
+ * factor unordered and codes it by an indicator of its first level, which turns the sign of Z, and refuses 2 x 2
580
+ * tables; here two-level factors are scored like the others and a 2 x 2 table is tested (Z^2 is then the 'N - 1'
581
+ * chi-squared statistic). p-values from the normal distribution: `"greater"` is positive association.
582
+ *
583
+ * @param table A table of counts (nonnegative, finite) as an array of rows.
584
+ * @param options See {@link LblTestOptions}.
585
+ * @returns The test result, with `statisticName` `"Z"`; see {@link LblTestResult}.
586
+ * @throws RangeError for negative or non-finite counts, a total of at most 1, scores of the wrong length or not
587
+ * finite, and tables whose row or column scores do not vary over the observations (Z undefined).
588
+ *
589
+ * @example
590
+ * ```ts
591
+ * lblTest([[10, 5, 2], [3, 8, 6], [1, 4, 9]]).statistic; // 3.601652214003794
592
+ * ```
593
+ *
594
+ * @category Hypothesis tests
595
+ */
596
+ export function lblTest(table, options = {}) {
597
+ checkOptions(options, LBL_TEST_KEYS, "lblTest"); // generated: option-keys.mjs
598
+ const alternative = matchAlternative(options.alternative);
599
+ const t = countTable(table);
600
+ const nr = t.length;
601
+ const nc = t[0].length;
602
+ const scores = (s, k, name) => {
603
+ if (s === undefined)
604
+ return Array.from({ length: k }, (_, i) => i + 1);
605
+ const v = Array.from(s);
606
+ if (v.length !== k)
607
+ throw new RangeError(`'${name}' must have one score for each ${name === "rowScores" ? "row" : "column"}`);
608
+ if (v.some((e) => typeof e !== "number" || !Number.isFinite(e)))
609
+ throw new RangeError(`'${name}' must be finite numbers`);
610
+ return v;
611
+ };
612
+ const u = scores(options.rowScores, nr, "rowScores");
613
+ const w = scores(options.colScores, nc, "colScores");
614
+ // r does not depend on the scale of the counts: where the total is beyond 2^1000 (it overflowed for
615
+ // [[1e308, 1], [1, 1e308]], whose sums of squares then gave "scores must vary"), they are divided by 2^k (k even)
616
+ // and N - 1 = 2^k (N' - 2^-k) in Z
617
+ const total = ddSumOf(t.flat())[0];
618
+ const k = total > 2 ** 1000 ? 2 * Math.ceil((Math.log2(Math.max(...t.flat())) - 990) / 2) : 0;
619
+ const ts = k === 0 ? t : t.map((row) => row.map((v) => ldexp(v, -k)));
620
+ const R = ts.map((row) => ddSumOf(row)).map((s) => s[0] + s[1]);
621
+ const C = ts[0].map((_, j) => ddSumOf(ts.map((row) => row[j]))).map((s) => s[0] + s[1]);
622
+ const N = R.reduce((a, b) => a + b, 0);
623
+ if (!(k > 0 || N > 1))
624
+ throw new RangeError("the table must have a total above 1");
625
+ const ubar = R.reduce((a, r, i) => a + r * u[i], 0) / N;
626
+ const wbar = C.reduce((a, c, j) => a + c * w[j], 0) / N;
627
+ const du = u.map((v) => v - ubar);
628
+ const dw = w.map((v) => v - wbar);
629
+ const Suu = R.reduce((a, r, i) => a + r * du[i] * du[i], 0);
630
+ const Sww = C.reduce((a, c, j) => a + c * dw[j] * dw[j], 0);
631
+ let Suw = 0;
632
+ ts.forEach((row, i) => row.forEach((v, j) => (Suw += v * du[i] * dw[j])));
633
+ if (!(Suu > 0 && Sww > 0))
634
+ throw new RangeError("the row and column scores must vary over the observations (the variance of the statistic is 0)");
635
+ const r = Suw / Math.sqrt(Suu) / Math.sqrt(Sww);
636
+ const Z = k === 0 ? Math.sqrt(N - 1) * r : ldexp(Math.sqrt(N - ldexp(1, -k)) * r, k / 2);
637
+ const pValue = alternative === "less"
638
+ ? pnorm(Z)
639
+ : alternative === "greater"
640
+ ? pnorm(Z, { lowerTail: false })
641
+ : 2 * pnorm(-Math.abs(Z));
642
+ return reported("lblTest", {
643
+ method: "Linear-by-Linear Association Test",
644
+ alternative,
645
+ statistic: Z,
646
+ statisticName: "Z",
647
+ pValue,
648
+ warnings: [],
649
+ });
650
+ }