@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,394 @@
1
+ // Boschloo's exact unconditional test of two independent binomial proportions (2 x 2 table, rows fixed).
2
+ //
3
+ // Written for rStats.js from Boschloo (1970, Statistica Neerlandica 24, 1-9) and the description in
4
+ // oracle/contingency-behaviour.md section 4 (the behaviour of Exact::exact.test(method = "boschloo")):
5
+ // - Model: X1 ~ Bin(n1, pi1), X2 ~ Bin(n2, pi2) independent; H0 pi1 = pi2 = pi with pi unknown. The statistic of a
6
+ // table (i, j) is Fisher's conditional p-value T(i, j): one-sided P(X1 <= i | X1 + X2 = i + j) ("less", pi1 < pi2),
7
+ // P(X1 >= i | ...) ("greater"), or two-sided Fisher's p-value ("square", the sum of the conditional probabilities at
8
+ // most (1 + 1e-7) times that of the table, as fisher.test). The rejection region is every table with
9
+ // T <= (1 + 1e-7) T(observed) (the slack keeps tables whose statistic equals the observed one mathematically), and
10
+ // the p-value is the supremum over pi in [0, 1] of the probability of the region,
11
+ // P(pi) = sum over the region of b(i; n1, pi) b(j; n2, pi).
12
+ // - "central" (two-sided): the one-sided test in the direction of the data (greater where x1/n1 > x2/n2, else less),
13
+ // p doubled and capped at 1 (as Exact).
14
+ // - The region is evaluated table by table (Exact assumes Barnard's convexity and takes shortcuts, which for the
15
+ // two-sided "square" statistic can put tables with Fisher p-value 1 into the region: for 20/60 vs 9/25 its p-value
16
+ // 0.785623 exceeds the true 0.785614). The conditional distribution for each total s = i + j is formed once from log
17
+ // factorials and normalised; the one-sided statistics are its cumulative sums from the near end, the two-sided one
18
+ // the sum of both tails below the cut (the distribution is unimodal, so the tails are found by bisection).
19
+ // - The supremum: P(pi) is a polynomial of degree N = n1 + n2 that can have several local maxima, so neither Exact's
20
+ // 100-point grid with optimise (rounded to 12 digits) nor exact2x2's 98-point grid maximum gives it to more than about
21
+ // 8 digits. Here P is evaluated on a grid uniform in theta with pi = sin^2(theta) (the binomial's variance-stabilising
22
+ // scale, where every peak has a width of about 1/sqrt(2 N) or more) of max(1000, 32 sqrt(N)) points plus both ends,
23
+ // and every grid local maximum within 10% of the largest is refined by Brent's localmin (src/optim/localmin.ts) to
24
+ // the precision of the doubles.
25
+ // - Each evaluation uses the region as runs of j in each row i: runs that start at 0 or end at n2 are cumulative sums of
26
+ // b(.; n2, pi) from that end (one-sided regions are such tails), others are summed directly. The binomial vectors are
27
+ // dbinom at the mode and the ratios of neighbours from there (with p/(1 - p) in double-double), as far as they do not
28
+ // underflow.
29
+ import { dbinom1 } from "../distributions/binomial.js";
30
+ import { phyper1 } from "../distributions/hypergeometric.js";
31
+ import { reported, unreported } from "../internal/warnings.js";
32
+ import { localMin } from "../optim/localmin.js";
33
+ import { lfactorial } from "../special/choose.js";
34
+ import { ddDiv, twoSum } from "../special/dd.js";
35
+ import { checkCount } from "./binomCI.js";
36
+ import { fisherTest } from "./fisherTest.js";
37
+ import { matchChoice } from "./power.js";
38
+ import { matchAlternative } from "./types.js";
39
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
40
+ import { checkOptions } from "../internal/checkOptions.js";
41
+ const BOSCHLOO_TEST_KEYS = ["alternative", "tsmethod"];
42
+ const TS_METHODS = ["square", "central"];
43
+ /** Fine grid: at least this many interior points */
44
+ const MIN_GRID = 1000;
45
+ /** Points of the grid per sqrt(N): the spacing is about 1/14 of the narrowest peak width 1/sqrt(2 N) in theta (a grid of 60 points refined gives the same suprema to 1e-14 on 1600 random tables) */
46
+ const GRID_PER_SQRT_N = 32;
47
+ /** Grid local maxima within this fraction of the largest grid value are refined */
48
+ const CANDIDATE_RATIO = 0.9;
49
+ /** Relative slack of "T <= T(observed)" (fisher.test's for its two-sided p-value) */
50
+ const SLACK = 1 + 1e-7;
51
+ /** Largest number of tables (n1 + 1)(n2 + 1) (one array of the region; design rule 4) */
52
+ const MAX_TABLES = 2 ** 24;
53
+ /**
54
+ * Largest number of steps of the evaluations of P on the grid, the grid's points times the widths of the binomial
55
+ * vectors (design rule 4): about 8 s at the limit (131000 and 131000 events against one observation, 7.7 s; 2^32 steps
56
+ * counted as n1 + 3 n2 per point took 18 s for 262000 against 1)
57
+ */
58
+ const MAX_WORK = 3.4e8;
59
+ /**
60
+ * Boschloo's exact unconditional test (`method = "boschloo"`) for a 2 x 2 table whose rows are two independent
61
+ * binomial samples. Equivalent to `Exact::exact.test()` in R.
62
+ *
63
+ * The rows are the groups and column 1 counts the events: `[[x1, n1 - x1], [x2, n2 - x2]]`. The statistic is Fisher's
64
+ * exact p-value of each possible table (one-sided, or two-sided for `tsmethod: "square"`), and the p-value is the
65
+ * largest probability, over the common proportion pi under the null hypothesis, of the tables whose statistic is at
66
+ * most the observed one (Boschloo 1970). `alternative: "less"` means pi1 < pi2 (Exact's orientation; exact2x2's
67
+ * `boschloo()` uses the opposite one). `"central"` doubles the one-sided p-value in the direction of the data.
68
+ *
69
+ * The p-value is the true supremum, from a fine grid and a refinement of every candidate maximum; Exact maximises
70
+ * over 100 points refined by `optimise` and rounds to 12 digits (about 1e-9 relative off), and its two-sided
71
+ * `"square"` region can contain tables that do not belong there (docs/differences-from-r.md). `statistic` is the
72
+ * observed Fisher p-value (one-sided in the direction tested, or two-sided for `"square"`), `estimate` the difference
73
+ * of the proportions x1/n1 - x2/n2, and `nuisanceParameter` the pi at which the supremum is attained.
74
+ *
75
+ * A table with more than 2^24 possible outcomes ((n1 + 1)(n2 + 1)) is a RangeError, as is one whose grid would take
76
+ * more than about 10 seconds.
77
+ *
78
+ * @param table A 2 x 2 table of counts: rows are the groups, column 1 the events.
79
+ * @param options See {@link BoschlooTestOptions}.
80
+ * @returns The test result; see {@link BoschlooTestResult}.
81
+ *
82
+ * @example
83
+ * ```ts
84
+ * const r = boschlooTest([[3, 7], [8, 2]], { alternative: "less" });
85
+ * r.pValue; // 0.020694732666015625 (Exact: 0.020694732666)
86
+ * r.statistic; // 0.034889259347463675 (Fisher's one-sided p-value)
87
+ * r.estimate; // -0.5
88
+ * ```
89
+ *
90
+ * @category Hypothesis tests
91
+ */
92
+ export function boschlooTest(table, options = {}) {
93
+ checkOptions(options, BOSCHLOO_TEST_KEYS, "boschlooTest"); // generated: option-keys.mjs
94
+ if (table.length !== 2 || table.some((r) => r.length !== 2))
95
+ throw new TypeError("'table' must be a 2 x 2 table");
96
+ const alternative = matchAlternative(options.alternative);
97
+ const tsmethod = matchChoice(options.tsmethod, TS_METHODS);
98
+ const t = table.map((r, i) => Array.from(r, (v, j) => checkCount(v, `table[${i}][${j}]`)));
99
+ const [[x1, y1], [x2, y2]] = t;
100
+ const n1 = x1 + y1;
101
+ const n2 = x2 + y2;
102
+ if (n1 === 0 || n2 === 0)
103
+ throw new RangeError("each row (group) of 'table' must have at least one observation");
104
+ if ((n1 + 1) * (n2 + 1) > MAX_TABLES) {
105
+ throw new RangeError(`Boschloo's test of these group sizes has ${(n1 + 1) * (n2 + 1)} possible tables, more than 2^24`);
106
+ }
107
+ const N = n1 + n2;
108
+ const grid = Math.max(MIN_GRID, Math.ceil(GRID_PER_SQRT_N * Math.sqrt(N)));
109
+ // the binomial vectors are written where they do not underflow: at most about 40 sqrt(n) values (pi = 1/2)
110
+ const width = (n) => Math.min(n + 1, 40 * Math.sqrt(n));
111
+ if (grid * (width(n1) + width(n2) + 4) > MAX_WORK) {
112
+ throw new RangeError(`Boschloo's test of these group sizes (${n1} and ${n2}) would take too long`);
113
+ }
114
+ // the statistic: which tail of X1 given X1 + X2 (two-sided: both)
115
+ const estimate = x1 / n1 - x2 / n2;
116
+ let kind;
117
+ if (alternative !== "two.sided")
118
+ kind = alternative;
119
+ else if (tsmethod === "square")
120
+ kind = "square";
121
+ else
122
+ kind = estimate > 0 ? "greater" : "less";
123
+ const s0 = x1 + x2;
124
+ let statistic;
125
+ if (kind === "less")
126
+ statistic = phyper1(x1, n1, n2, s0, true, false);
127
+ else if (kind === "greater")
128
+ statistic = phyper1(x1 - 1, n1, n2, s0, false, false);
129
+ else
130
+ statistic = unreported(() => fisherTest(t)).pValue;
131
+ const region = rejectionRegion(n1, n2, x1, x2, kind);
132
+ const { value, at } = supremum(region, n1, n2, grid);
133
+ const pValue = alternative === "two.sided" && tsmethod === "central" ? Math.min(1, 2 * value) : value;
134
+ return reported("boschlooTest", {
135
+ method: "Boschloo's Exact Test",
136
+ alternative,
137
+ statistic,
138
+ statisticName: "test statistic",
139
+ pValue,
140
+ estimate,
141
+ estimateNames: "difference in proportion",
142
+ nullValue: 0,
143
+ nullValueName: "difference in proportion",
144
+ nuisanceParameter: at,
145
+ warnings: [],
146
+ });
147
+ }
148
+ /**
149
+ * The tables (i, j) whose statistic T(i, j) is at most (1 + 1e-7) T(x1, x2). For each total s the conditional
150
+ * distribution of X1 (hypergeometric) is formed from log factorials (relative error about 1e-12 for the sizes allowed,
151
+ * far within the slack) and normalised by its sum
152
+ */
153
+ function rejectionRegion(n1, n2, x1, x2, kind) {
154
+ const N = n1 + n2;
155
+ const lf = new Float64Array(N + 1);
156
+ for (let k = 2; k <= N; k++)
157
+ lf[k] = lfactorial(k);
158
+ const w1 = n2 + 1;
159
+ // statistics of every table, column by column of totals; T[i * w1 + j]
160
+ const T = new Float64Array((n1 + 1) * w1);
161
+ const len = Math.min(n1, n2) + 1;
162
+ const d = new Float64Array(len);
163
+ const left = new Float64Array(len);
164
+ const right = new Float64Array(len);
165
+ for (let s = 0; s <= N; s++) {
166
+ const lo = Math.max(0, s - n2);
167
+ const hi = Math.min(s, n1);
168
+ const m = hi - lo + 1;
169
+ let top = -Infinity;
170
+ for (let k = 0; k < m; k++) {
171
+ const i = lo + k;
172
+ const v = -lf[i] - lf[n1 - i] - lf[s - i] - lf[n2 - s + i];
173
+ d[k] = v;
174
+ if (v > top)
175
+ top = v;
176
+ }
177
+ let total = 0;
178
+ for (let k = 0; k < m; k++) {
179
+ d[k] = Math.exp(d[k] - top);
180
+ total += d[k];
181
+ }
182
+ for (let k = 0; k < m; k++)
183
+ d[k] = d[k] / total;
184
+ // cumulative sums from each end (each tail summed from its own end keeps small tails accurate)
185
+ let acc = 0;
186
+ for (let k = 0; k < m; k++)
187
+ left[k] = acc += d[k];
188
+ acc = 0;
189
+ for (let k = m - 1; k >= 0; k--)
190
+ right[k] = acc += d[k];
191
+ if (kind === "less")
192
+ for (let k = 0; k < m; k++)
193
+ T[(lo + k) * w1 + s - lo - k] = left[k];
194
+ else if (kind === "greater")
195
+ for (let k = 0; k < m; k++)
196
+ T[(lo + k) * w1 + s - lo - k] = right[k];
197
+ else {
198
+ // the mode (the first largest value): d increases up to it and decreases after it
199
+ let mode = 0;
200
+ for (let k = 1; k < m; k++)
201
+ if (d[k] > d[mode])
202
+ mode = k;
203
+ for (let k = 0; k < m; k++) {
204
+ const cut = d[k] * SLACK;
205
+ // the last a < mode with d[a] <= cut (-1 if none), the first b > mode with d[b] <= cut (m if none)
206
+ let a0 = -1;
207
+ let a1 = mode;
208
+ while (a1 - a0 > 1) {
209
+ const mid = (a0 + a1) >> 1;
210
+ if (d[mid] <= cut)
211
+ a0 = mid;
212
+ else
213
+ a1 = mid;
214
+ }
215
+ let b0 = mode;
216
+ let b1 = m;
217
+ while (b1 - b0 > 1) {
218
+ const mid = (b0 + b1) >> 1;
219
+ if (d[mid] <= cut)
220
+ b1 = mid;
221
+ else
222
+ b0 = mid;
223
+ }
224
+ const p = d[mode] <= cut ? 1 : (a0 >= 0 ? left[a0] : 0) + (b1 < m ? right[b1] : 0);
225
+ T[(lo + k) * w1 + s - lo - k] = Math.min(1, p);
226
+ }
227
+ }
228
+ }
229
+ const cut = T[x1 * w1 + x2] * SLACK;
230
+ // runs of the region in each row
231
+ const starts = new Int32Array(n1 + 2);
232
+ const from = [];
233
+ const to = [];
234
+ for (let i = 0; i <= n1; i++) {
235
+ starts[i] = from.length;
236
+ let j = 0;
237
+ while (j <= n2) {
238
+ if (T[i * w1 + j] <= cut) {
239
+ const begin = j;
240
+ while (j + 1 <= n2 && T[i * w1 + j + 1] <= cut)
241
+ j++;
242
+ from.push(begin);
243
+ to.push(j);
244
+ }
245
+ j++;
246
+ }
247
+ }
248
+ starts[n1 + 1] = from.length;
249
+ return { starts, from: Int32Array.from(from), to: Int32Array.from(to) };
250
+ }
251
+ /**
252
+ * b(.; n, p) into out, written on [lo, hi] (returned) outside which the values underflow to 0: dbinom at the mode and
253
+ * the ratios of neighbours outward. The ratios p/(1 - p) and (1 - p)/p rounded once enter every step, so their rounding
254
+ * compounds (70 ulps at n = 300: 2^-599 came out 4.819839730205692e-181 for 4.819839730205768e-181); they are formed
255
+ * in double-double (1 - p exactly) and the vector is corrected by (1 + c)^k = 1 + k c, c the relative low part and k
256
+ * the steps from the mode (k c is below 1e-10, so the square terms are below the last bit). The walk stops where a
257
+ * value underflows: every later one would be 0 (the time of long groups then follows sqrt(n), not n)
258
+ */
259
+ function binomialVector(n, p, out) {
260
+ if (p === 0 || p === 1) {
261
+ const at = p === 0 ? 0 : n;
262
+ out[at] = 1;
263
+ return [at, at];
264
+ }
265
+ const mode = Math.min(n, Math.floor((n + 1) * p));
266
+ out[mode] = dbinom1(mode, n, p, false);
267
+ const q = twoSum(1, -p);
268
+ const upDD = ddDiv([p, 0], q);
269
+ const downDD = ddDiv(q, [p, 0]);
270
+ const up = upDD[0];
271
+ const down = downDD[0];
272
+ let hi = mode;
273
+ for (let i = mode + 1; i <= n; i++) {
274
+ const v = out[i - 1] * (((n - i + 1) / i) * up);
275
+ if (v === 0)
276
+ break;
277
+ out[i] = v;
278
+ hi = i;
279
+ }
280
+ let lo = mode;
281
+ for (let i = mode - 1; i >= 0; i--) {
282
+ const v = out[i + 1] * (((i + 1) / (n - i)) * down);
283
+ if (v === 0)
284
+ break;
285
+ out[i] = v;
286
+ lo = i;
287
+ }
288
+ const cu = upDD[1] / up;
289
+ const cd = downDD[1] / down;
290
+ for (let i = mode + 1; i <= hi; i++)
291
+ out[i] = out[i] * (1 + (i - mode) * cu);
292
+ for (let i = lo; i < mode; i++)
293
+ out[i] = out[i] * (1 + (mode - i) * cd);
294
+ return [lo, hi];
295
+ }
296
+ /** The supremum over pi in [0, 1] of the probability of the region, and a pi where it is attained */
297
+ function supremum(region, n1, n2, grid) {
298
+ const { starts, from, to } = region;
299
+ const b1 = new Float64Array(n1 + 1);
300
+ const b2 = new Float64Array(n2 + 1);
301
+ const below = new Float64Array(n2 + 1);
302
+ const above = new Float64Array(n2 + 1);
303
+ // (b1 and b2 are read on the ranges written by binomialVector only: 0 outside, as the cumulative sums there)
304
+ const probability = (p) => {
305
+ const [lo1, hi1] = binomialVector(n1, p, b1);
306
+ const [lo2, hi2] = binomialVector(n2, p, b2);
307
+ let acc = 0;
308
+ for (let j = lo2; j <= hi2; j++)
309
+ below[j] = acc += b2[j];
310
+ acc = 0;
311
+ for (let j = hi2; j >= lo2; j--)
312
+ above[j] = acc += b2[j];
313
+ let total = 0;
314
+ for (let i = lo1; i <= hi1; i++) {
315
+ const w = b1[i];
316
+ if (w === 0)
317
+ continue;
318
+ let row = 0;
319
+ for (let r = starts[i]; r < starts[i + 1]; r++) {
320
+ const f = from[r];
321
+ const e = to[r];
322
+ if (e < lo2 || f > hi2)
323
+ continue;
324
+ if (f === 0)
325
+ row += below[Math.min(e, hi2)];
326
+ else if (e === n2)
327
+ row += above[Math.max(f, lo2)];
328
+ else
329
+ for (let j = Math.max(f, lo2); j <= Math.min(e, hi2); j++)
330
+ row += b2[j];
331
+ }
332
+ total += w * row;
333
+ }
334
+ return Math.min(1, total);
335
+ };
336
+ const half = Math.PI / 2;
337
+ const piOf = (theta) => (theta <= 0 ? 0 : theta >= half ? 1 : Math.sin(theta) ** 2);
338
+ // theta_k = (pi / 2) k / (grid + 1), k = 0..grid + 1 (the ends pi = 0 and 1 included: the supremum over the open
339
+ // interval is the maximum of the continuous P on the closed one)
340
+ const values = new Float64Array(grid + 2);
341
+ let best = 0;
342
+ for (let k = 0; k <= grid + 1; k++) {
343
+ values[k] = probability(piOf((half * k) / (grid + 1)));
344
+ if (values[k] > values[best])
345
+ best = k;
346
+ }
347
+ let value = values[best];
348
+ let bestAt = piOf((half * best) / (grid + 1));
349
+ if (value >= 1)
350
+ return { value: 1, at: bestAt };
351
+ const threshold = CANDIDATE_RATIO * value;
352
+ for (let k = 0; k <= grid + 1; k++) {
353
+ const v = values[k];
354
+ if (v < threshold)
355
+ continue;
356
+ // a local maximum (strict on the left, so that a plateau is refined once)
357
+ if ((k > 0 && !(v > values[k - 1])) || (k <= grid && !(v >= values[k + 1])))
358
+ continue;
359
+ const lower = (half * Math.max(0, k - 1)) / (grid + 1);
360
+ const upper = (half * Math.min(grid + 1, k + 1)) / (grid + 1);
361
+ const m = localMin((theta) => -probability(piOf(theta)), lower, upper, 1e-14);
362
+ let theta = m.x;
363
+ let refined = probability(piOf(theta));
364
+ // Brent's localmin stops within about sqrt(eps) of the maximum, where the value has dropped by the curvature times
365
+ // that squared (about 2N (1e-8)^2 relative: 25 ulps at [[300, 0], [0, 300]]). Two steps to the vertex of the
366
+ // parabola through theta - h, theta, theta + h, with h a 1e-4 and then 1e-6 part of the peak width 1/sqrt(2N)
367
+ // (the vertex's error from the rounding of P is then about eps / (2N h), from the cubic term h^2 sqrt(2N)), each
368
+ // kept only where it raises P by more than its rounding (4 ulps: [[3, 7], [8, 2]] would otherwise move 1.5 ulps
369
+ // above the true 0.020694732666015625)
370
+ let h = 1e-4 / Math.sqrt(2 * (n1 + n2));
371
+ for (let step = 0; step < 2; step++, h *= 1e-2) {
372
+ if (!(theta - h > lower && theta + h < upper))
373
+ break;
374
+ const vl = probability(piOf(theta - h));
375
+ const vr = probability(piOf(theta + h));
376
+ const den = vl - 2 * refined + vr;
377
+ if (!(den < 0))
378
+ break;
379
+ const shift = (h * (vl - vr)) / (2 * den);
380
+ if (!(Math.abs(shift) < h))
381
+ break;
382
+ const v = probability(piOf(theta + shift));
383
+ if (v > refined * (1 + 2 ** -50)) {
384
+ theta += shift;
385
+ refined = v;
386
+ }
387
+ }
388
+ if (refined > value) {
389
+ value = refined;
390
+ bestAt = piOf(theta);
391
+ }
392
+ }
393
+ return { value, at: bestAt };
394
+ }
@@ -18,6 +18,13 @@ export interface ChisqTestOptions {
18
18
  simulatePValue?: boolean;
19
19
  /** Number of replicates for `simulatePValue`. Default `2000`. */
20
20
  B?: number;
21
+ /**
22
+ * The 'N - 1' chi-squared test (Campbell 2007; not in R): Pearson's statistic times `(N - 1) / N`, without continuity
23
+ * correction, for a contingency table (2 x 2 or larger). Default `false`. An error for goodness of fit (a vector or
24
+ * a matrix with one row or column), with `simulatePValue`, and with `correct: true` given explicitly (the default
25
+ * correction is not applied).
26
+ */
27
+ nMinus1?: boolean;
21
28
  }
22
29
  /**
23
30
  * Result of {@link chisqTest}. Has no `alternative`, because R's `chisq.test()` does not return one.
@@ -40,6 +47,11 @@ export interface ChisqTestResult extends Omit<HTest, "alternative"> {
40
47
  * sums over the total, and the residual and `V` are computed in double-double.
41
48
  */
42
49
  stdres: number[] | number[][];
50
+ /**
51
+ * Freeman-Tukey deviates `sqrt(O) + sqrt(O + 1) - sqrt(4E + 1)` (Bishop, Fienberg and Holland 1975; not in R),
52
+ * approximately standard normal under the null hypothesis; their sum of squares is the Freeman-Tukey statistic.
53
+ */
54
+ ftResiduals: number[] | number[][];
43
55
  }
44
56
  /**
45
57
  * Result of {@link chisqTest} with two factor vectors: also the levels that label the rows and columns.
@@ -51,6 +63,7 @@ export interface ChisqTestFactorsResult extends ChisqTestResult {
51
63
  expected: number[][];
52
64
  residuals: number[][];
53
65
  stdres: number[][];
66
+ ftResiduals: number[][];
54
67
  /** Levels of `x` (rows of the table), sorted by code point. */
55
68
  rowLevels: string[];
56
69
  /** Levels of `y` (columns of the table), sorted by code point. */
@@ -78,6 +91,10 @@ export type Factor = readonly (string | null | undefined)[];
78
91
  * Given two factor vectors (arrays of labels of the same length), tests independence in their contingency table, as
79
92
  * R's `chisq.test(x, y)`; pairs with a missing label are dropped and the levels are sorted by code point.
80
93
  *
94
+ * With `nMinus1: true` (not in R) the statistic is Campbell's (2007) 'N - 1' chi-squared, Pearson's statistic without
95
+ * continuity correction times `(N - 1) / N`, for 2 x 2 and larger tables with a total N above 1. The result also has
96
+ * the Freeman-Tukey deviates `ftResiduals` (not in R).
97
+ *
81
98
  * As R, `warnings` has "Chi-squared approximation may be incorrect" where an expected count is below 5 (unless the
82
99
  * p-value is simulated), and "cannot compute simulated p-value with zero marginals" where `simulatePValue` is asked for
83
100
  * a table with a zero row or column sum (the ordinary test is done).
@@ -98,6 +115,8 @@ export type Factor = readonly (string | null | undefined)[];
98
115
  * chisqTest([20, 15, 25], { simulatePValue: true }).pValue; // 0.296351824087956 (R: set.seed(1); chisq.test(...))
99
116
  *
100
117
  * chisqTest(["a", "b", "a", "b"], ["u", "u", "v", "v"]).rowLevels; // ["a", "b"]
118
+ *
119
+ * chisqTest([[12, 5], [7, 9]], { nMinus1: true }).statistic; // 2.3569217160548437 (the 'N - 1' test)
101
120
  * ```
102
121
  *
103
122
  * @category Hypothesis tests
@@ -20,6 +20,11 @@
20
20
  // - R's warning "Chi-squared approximation may be incorrect" where an expected count is below 5 and the p-value is
21
21
  // not simulated
22
22
  // - Two factor vectors: the table of the complete pairs, with the distinct values sorted by code point (C locale)
23
+ // - nMinus1 (not in R): the 'N - 1' chi-squared test of Campbell (Statistics in Medicine 26, 2007), Pearson's statistic
24
+ // without continuity correction times (N - 1)/N, for 2 x 2 and r x c tables (the r x c version is the same scaling;
25
+ // for 2 x 2 it is the Mantel-Haenszel statistic of one stratum and the linear-by-linear Z^2)
26
+ // - ftResiduals (not in R): the Freeman-Tukey deviates sqrt(O) + sqrt(O + 1) - sqrt(4E + 1) (Bishop, Fienberg and
27
+ // Holland 1975, section 14.7; src/htest/tableTests.ts)
23
28
  import { pgamma1 } from "../distributions/gamma.js";
24
29
  import { logFactorialTable, MAX_TABLE_TOTAL, rcont2 } from "../random/r2dtable.js";
25
30
  import { sampleIntReplaceDrawer } from "../random/sample.js";
@@ -28,10 +33,11 @@ import { compareCodePoints } from "../models/modelFrame.js";
28
33
  import { ddAdd, ddDiv, ddMul, ddSub } from "../special/dd.js";
29
34
  import { simulatedMethod } from "./core/simulate.js";
30
35
  import { reported } from "../internal/warnings.js";
36
+ import { freemanTukeyResiduals } from "./tableTests.js";
31
37
  // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
32
38
  import { checkOptions } from "../internal/checkOptions.js";
33
39
  import { isOptionsObject } from "../internal/optionalArgs.js";
34
- const CHISQ_TEST_KEYS = ["correct", "p", "rescaleP", "simulatePValue", "B"];
40
+ const CHISQ_TEST_KEYS = ["correct", "p", "rescaleP", "simulatePValue", "B", "nMinus1"];
35
41
  /** Sum (accumulated in double-double, then rounded; with Inf present, the double sum = ±Inf or NaN) */
36
42
  function ddSum(x) {
37
43
  let s = [0, 0];
@@ -127,6 +133,8 @@ function checkExpected(E) {
127
133
  throw new RangeError("missing value where TRUE/FALSE needed (the expected counts contain NaN)");
128
134
  }
129
135
  function goodnessOfFit(x, options) {
136
+ if (options.nMinus1 ?? false)
137
+ throw new RangeError("'nMinus1' requires a contingency table with at least two rows and columns");
130
138
  const k = x.length;
131
139
  // (R lets Infinity through and returns NaN)
132
140
  if (x.some((v) => !(v >= 0 && v < Infinity)))
@@ -194,6 +202,7 @@ function goodnessOfFit(x, options) {
194
202
  expected: E,
195
203
  residuals: xs.map((v, i) => ldexp((v - Es[i]) / Math.sqrt(Es[i]), s / 2)),
196
204
  stdres: xs.map((v, i) => ldexp((v - Es[i]) / Math.sqrt(Vs[i]), s / 2)),
205
+ ftResiduals: freemanTukeyResiduals(x, E),
197
206
  warnings: Number.isFinite(df) && E.some((e) => e < 5) ? [APPROXIMATION] : [],
198
207
  };
199
208
  }
@@ -247,7 +256,15 @@ function simulateTables(sr, sc, E, B) {
247
256
  return out;
248
257
  }
249
258
  function contingency(x, options) {
250
- const correct = options.correct ?? true;
259
+ const nMinus1 = options.nMinus1 ?? false;
260
+ if (typeof nMinus1 !== "boolean")
261
+ throw new TypeError("'nMinus1' must be a boolean");
262
+ if (nMinus1 && options.correct === true)
263
+ throw new RangeError("'nMinus1' uses no continuity correction: leave 'correct' out or set it to false");
264
+ if (nMinus1 && (options.simulatePValue ?? false))
265
+ throw new RangeError("'nMinus1' cannot be combined with 'simulatePValue'");
266
+ // the 'N - 1' statistic is Pearson's without correction
267
+ const correct = !nMinus1 && (options.correct ?? true);
251
268
  const nr = x.length;
252
269
  const nc = x[0].length;
253
270
  const all = x.flat();
@@ -256,6 +273,9 @@ function contingency(x, options) {
256
273
  const n = ddSum(all);
257
274
  if (!(n > 0))
258
275
  throw new RangeError("at least one entry of 'x' must be positive");
276
+ // (N - 1)/N would turn the statistic negative or make it 0 (choice 16, rule 1)
277
+ if (nMinus1 && !(n > 1))
278
+ throw new RangeError("'nMinus1' needs a table with a total above 1");
259
279
  const sr = x.map((r) => ddSum(r));
260
280
  const sc = x[0].map((_, j) => ddSum(x.map((r) => r[j])));
261
281
  const E = sr.map((a) => sc.map((b) => productOver(a, b, n)));
@@ -288,6 +308,13 @@ function contingency(x, options) {
288
308
  }
289
309
  else {
290
310
  stat = ddSum(diff.flatMap((r, i) => r.map((d, j) => squareOver(d, E[i][j]))));
311
+ if (nMinus1) {
312
+ // Campbell (2007): X^2 (N - 1) / N, in this order (as the statistic would be scaled by hand); X^2 ((N - 1) / N)
313
+ // where the product overflows ([[1e160, 1], [1, 1e160]]: Infinity for 2e160)
314
+ method = "Pearson's 'N-1' Chi-squared test";
315
+ const scaled = stat * (n - 1);
316
+ stat = Number.isFinite(scaled) ? scaled / n : stat * ((n - 1) / n);
317
+ }
291
318
  }
292
319
  return {
293
320
  method,
@@ -300,6 +327,7 @@ function contingency(x, options) {
300
327
  expected: E,
301
328
  residuals: diff.map((r, i) => r.map((d, j) => d / Math.sqrt(E[i][j]))),
302
329
  stdres: contingencyStdres(x, n, sr, sc, E, diff),
330
+ ftResiduals: freemanTukeyResiduals(x, E),
303
331
  warnings: Number.isFinite(df) && E.some((r) => r.some((e) => e < 5)) ? [...warnings, APPROXIMATION] : warnings,
304
332
  };
305
333
  }
@@ -94,8 +94,8 @@ export declare function kendall(x: readonly number[], y: readonly number[]): Ken
94
94
  * value is less accurate.
95
95
  *
96
96
  * As R, `warnings` has "the standard deviation is zero" where x or y is constant (the correlation is `NaN`), and
97
- * "Cannot compute exact p-value with ties" where Kendall's or Spearman's exact p-value is asked for or the default
98
- * but there are ties (the approximation is used), and "NaNs produced" where Spearman's t approximation has 2 pairs
97
+ * "cannot compute exact p-value with ties" (R 4.6's text) where Kendall's or Spearman's exact p-value is asked for or
98
+ * the default but there are ties (the approximation is used), and "NaNs produced" where Spearman's t approximation has 2 pairs
99
99
  * (0 degrees of freedom: the p-value is `NaN`).
100
100
  *
101
101
  * @param x First sample.
package/dist/htest/cor.js CHANGED
@@ -443,7 +443,8 @@ const SD_ZERO = "the standard deviation is zero";
443
443
  /** R's warning of pt where the p-value is NaN (Spearman's t approximation with n = 2) */
444
444
  const NANS = "NaNs produced";
445
445
  /** R's warning where the exact p-value cannot be used because of ties */
446
- const TIES = "Cannot compute exact p-value with ties";
446
+ // (lower case since R 4.6, as the other tests' warning; R 4.5: "Cannot ...")
447
+ const TIES = "cannot compute exact p-value with ties";
447
448
  /** Whether all values are equal and finite */
448
449
  function finiteConstant(v) {
449
450
  return Number.isFinite(v[0]) && v.every((a) => a === v[0]);
@@ -0,0 +1,39 @@
1
+ /** Probability function of a statistic on the grid offset, offset + 1 / f, ..., with both cumulative tails */
2
+ export interface ScoreDistribution {
3
+ /** 1 or 2: the grid step of the statistic is 1 / f */
4
+ f: number;
5
+ /** Statistic at index 0 */
6
+ offset: number;
7
+ /** lower[i] = P(index <= i) */
8
+ lower: Float64Array;
9
+ /** upper[i] = P(index >= i) */
10
+ upper: Float64Array;
11
+ }
12
+ /** Largest table (doubles in one array; CONTRIBUTING rule 4) */
13
+ export declare const MAX_SCORE_TABLE: number;
14
+ /** Key of the multiset of scores (for caching distributions) */
15
+ export declare function scoreKey(scores: readonly number[]): string;
16
+ /** Steps and table length of signedScoreDistribution for these scores */
17
+ export declare function signedScoreCost(scores: readonly number[]): {
18
+ steps: number;
19
+ size: number;
20
+ };
21
+ /** Distribution of the sum of the scores with random signs (the scores counted with probability 1/2 each) */
22
+ export declare function signedScoreDistribution(scores: readonly number[]): ScoreDistribution;
23
+ /** Steps and largest row of rankSumScoreDistribution for these scores and first-sample size m */
24
+ export declare function rankSumScoreCost(scores: readonly number[], m: number): {
25
+ steps: number;
26
+ size: number;
27
+ };
28
+ /**
29
+ * Distribution of W = (sum of the scores of a random m-subset) - m (m + 1) / 2, the rank sum statistic given the
30
+ * pooled scores
31
+ */
32
+ export declare function rankSumScoreDistribution(scores: readonly number[], m: number): ScoreDistribution;
33
+ /** P(S < q + 1e-8), at most 1 (R's tail convention for the conditional distributions) */
34
+ export declare function lowerTail(d: ScoreDistribution, q: number): number;
35
+ /**
36
+ * P(S >= q + 1e-8): as R 4.6.2, 1 - P(S < q + 1e-8), except within 1/64 of the upper end of the lower tail (R's
37
+ * absolute threshold), where it is summed directly and keeps the digits of a small upper tail
38
+ */
39
+ export declare function upperTail(d: ScoreDistribution, q: number): number;