@numero-uno-jpn/rstats 0.6.1 → 0.8.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 (69) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/README.ja.md +18 -12
  3. package/README.md +18 -12
  4. package/THIRD_PARTY_NOTICES.md +30 -0
  5. package/dist/chunks/{chunk-DRNMIEYH.js → chunk-32PRRONF.js} +1 -1
  6. package/dist/chunks/chunk-3I6EKGB6.js +2 -0
  7. package/dist/chunks/chunk-EJRCDJ76.js +2 -0
  8. package/dist/chunks/{chunk-Y4IZV7XK.js → chunk-I3LAZE6C.js} +2 -2
  9. package/dist/chunks/chunk-JERGQKZM.js +2 -0
  10. package/dist/chunks/{chunk-ZWJ42QN6.js → chunk-JVYV4633.js} +1 -1
  11. package/dist/chunks/chunk-LXMMKO26.js +2 -0
  12. package/dist/chunks/{chunk-2JCIB5H2.js → chunk-MJQLKEO5.js} +2 -2
  13. package/dist/chunks/{chunk-UGUQYWRQ.js → chunk-OHPHNE3O.js} +1 -1
  14. package/dist/chunks/chunk-RZ7SBJEG.js +2 -0
  15. package/dist/chunks/{chunk-TPC6MTYC.js → chunk-SPQC445Q.js} +2 -2
  16. package/dist/chunks/{chunk-AJYQNFXK.js → chunk-U633VFH3.js} +2 -2
  17. package/dist/chunks/{chunk-7NK4SA6B.js → chunk-VIPSPG3Y.js} +2 -2
  18. package/dist/chunks/chunk-XU4BGFZ6.js +2 -0
  19. package/dist/chunks/{chunk-NOCEAM44.js → chunk-YGWPU67I.js} +1 -1
  20. package/dist/descriptive.js +2 -2
  21. package/dist/distributions/beta.js +21 -5
  22. package/dist/distributions.js +2 -2
  23. package/dist/entries/distributions.d.ts +3 -1
  24. package/dist/entries/distributions.js +3 -1
  25. package/dist/entries/special.d.ts +1 -0
  26. package/dist/entries/special.js +1 -0
  27. package/dist/entries/tests.d.ts +2 -1
  28. package/dist/entries/tests.js +2 -1
  29. package/dist/htest/ansariTest.d.ts +18 -1
  30. package/dist/htest/ansariTest.js +181 -8
  31. package/dist/htest/brunnerMunzelTest.d.ts +28 -0
  32. package/dist/htest/brunnerMunzelTest.js +86 -0
  33. package/dist/htest/chisqTest.d.ts +34 -2
  34. package/dist/htest/chisqTest.js +140 -37
  35. package/dist/htest/core/ansari.d.ts +7 -0
  36. package/dist/htest/core/ansari.js +65 -0
  37. package/dist/htest/core/simulate.d.ts +2 -0
  38. package/dist/htest/core/simulate.js +16 -0
  39. package/dist/htest/fisherTest.d.ts +12 -1
  40. package/dist/htest/fisherTest.js +53 -7
  41. package/dist/linalg.js +2 -2
  42. package/dist/numerics.js +2 -2
  43. package/dist/random/lecuyer.d.ts +20 -0
  44. package/dist/random/lecuyer.js +71 -0
  45. package/dist/random/r2dtable.d.ts +26 -0
  46. package/dist/random/r2dtable.js +153 -0
  47. package/dist/random/rng.d.ts +78 -11
  48. package/dist/random/rng.js +128 -26
  49. package/dist/random/sample.js +24 -7
  50. package/dist/random/streams.d.ts +34 -0
  51. package/dist/random/streams.js +75 -0
  52. package/dist/rstats.js +3 -2
  53. package/dist/special/igam.d.ts +1 -0
  54. package/dist/special/igam.js +1 -1
  55. package/dist/special/incbet.js +487 -6
  56. package/dist/special/incbetLargeA.d.ts +15 -0
  57. package/dist/special/incbetLargeA.js +200 -0
  58. package/dist/special/incbetTemme.d.ts +19 -0
  59. package/dist/special/incbetTemme.js +216 -0
  60. package/dist/special/loader.js +151 -118
  61. package/dist/special/log1p.d.ts +53 -0
  62. package/dist/special/log1p.js +93 -0
  63. package/dist/special.js +2 -2
  64. package/dist/tests.js +3 -2
  65. package/package.json +1 -1
  66. package/dist/chunks/chunk-7JVSDGQQ.js +0 -2
  67. package/dist/chunks/chunk-NAYDS7CL.js +0 -2
  68. package/dist/chunks/chunk-QNAIK4PY.js +0 -2
  69. package/dist/chunks/chunk-XM2TVD63.js +0 -2
@@ -0,0 +1,86 @@
1
+ // Brunner-Munzel test for the relative effect of two samples (lawstat's brunner.munzel.test).
2
+ //
3
+ // Written for rStats.js from the published test (E. Brunner and U. Munzel, "The nonparametric Behrens-Fisher problem:
4
+ // asymptotic theory and a small-sample approximation", Biometrical Journal 42 (2000) 17-25; no ported code).
5
+ // With R_k the pooled (mid)ranks, R^(i)_k the ranks within sample i and m_i the mean pooled rank of sample i, the
6
+ // relative effect p = P(X < Y) + P(X = Y)/2 is estimated by (m_2 - (n_2 + 1)/2) / n_1, the variances by
7
+ // S_i^2 = sum_k (R_k - R^(i)_k - m_i + (n_i + 1)/2)^2 / (n_i - 1), and the statistic
8
+ // W = n_1 n_2 (m_2 - m_1) / ((n_1 + n_2) sqrt(n_1 S_1^2 + n_2 S_2^2))
9
+ // is compared with a t distribution with Satterthwaite's degrees of freedom
10
+ // (n_1 S_1^2 + n_2 S_2^2)^2 / ((n_1 S_1^2)^2 / (n_1 - 1) + (n_2 S_2^2)^2 / (n_2 - 1)).
11
+ // The interval for p is two-sided, p ± t sqrt(S_1^2 / (n_1 n_2^2) + S_2^2 / (n_2 n_1^2)), whatever the alternative.
12
+ // The direction of the alternative, the interval, and NaN / ±Inf where a variance estimate is 0 follow lawstat's
13
+ // documented and observed behaviour; the p-values use the upper tail directly (lawstat's 1 - pt loses small ones).
14
+ import { pt1, qt1 } from "../distributions/t.js";
15
+ import { rank } from "../internal/summary.js";
16
+ import { checkConfLevel, matchAlternative } from "./types.js";
17
+ /**
18
+ * Brunner-Munzel test that two samples have the relative effect P(X < Y) + P(X = Y)/2 = 1/2, without assuming equal
19
+ * variances or shapes. Equivalent to `lawstat::brunner.munzel.test()`. `NaN` values are dropped.
20
+ *
21
+ * `estimate` is the estimated relative effect and `confInt` its two-sided interval (not clipped to [0, 1]). When a
22
+ * sample has one value, or when the variance estimates are 0 (for example completely separated samples), the
23
+ * statistic, degrees of freedom and p-value are `NaN` or ±Infinity, as in lawstat.
24
+ *
25
+ * @example
26
+ * ```ts
27
+ * const r = brunnerMunzelTest([1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 4, 1, 1], [3, 3, 4, 3, 1, 2, 3, 1, 1, 5, 4]);
28
+ * r.statistic; // 3.1374674823029509
29
+ * r.pValue; // 0.0057862086661515377
30
+ * r.estimate; // 0.78896103896103909
31
+ * ```
32
+ */
33
+ export function brunnerMunzelTest(x, y, options = {}) {
34
+ const xs = Array.from(x).filter((v) => !Number.isNaN(v));
35
+ const ys = Array.from(y).filter((v) => !Number.isNaN(v));
36
+ const n1 = xs.length;
37
+ const n2 = ys.length;
38
+ if (n1 < 1)
39
+ throw new RangeError("not enough 'x' observations");
40
+ if (n2 < 1)
41
+ throw new RangeError("not enough 'y' observations");
42
+ const alternative = matchAlternative(options.alternative);
43
+ const confLevel = options.confLevel ?? 0.95;
44
+ checkConfLevel(confLevel);
45
+ const pooled = rank(xs.concat(ys));
46
+ const r1 = pooled.slice(0, n1);
47
+ const r2 = pooled.slice(n1);
48
+ const mean = (v) => v.reduce((s, e) => s + e, 0) / v.length;
49
+ const m1 = mean(r1);
50
+ const m2 = mean(r2);
51
+ // S_i^2 from the pooled ranks minus the ranks within the sample (the placements)
52
+ const variance = (r, within, m) => {
53
+ const c = (r.length + 1) / 2;
54
+ let s = 0;
55
+ for (let k = 0; k < r.length; k++)
56
+ s += (r[k] - within[k] - m + c) ** 2;
57
+ return s / (r.length - 1);
58
+ };
59
+ const v1 = variance(r1, rank(xs), m1);
60
+ const v2 = variance(r2, rank(ys), m2);
61
+ const estimate = (m2 - (n2 + 1) / 2) / n1;
62
+ const s = n1 * v1 + n2 * v2;
63
+ const statistic = (n1 * n2 * (m2 - m1)) / (n1 + n2) / Math.sqrt(s);
64
+ const df = s ** 2 / ((n1 * v1) ** 2 / (n1 - 1) + (n2 * v2) ** 2 / (n2 - 1));
65
+ let pValue;
66
+ if (alternative === "greater")
67
+ pValue = pt1(statistic, df, true, false);
68
+ else if (alternative === "less")
69
+ pValue = pt1(statistic, df, false, false);
70
+ else
71
+ pValue = 2 * pt1(-Math.abs(statistic), df, true, false);
72
+ const half = qt1((1 - confLevel) / 2, df, false, false) * Math.sqrt(v1 / (n1 * n2 ** 2) + v2 / (n2 * n1 ** 2));
73
+ return {
74
+ method: "Brunner-Munzel Test",
75
+ alternative,
76
+ statistic,
77
+ statisticName: "Brunner-Munzel Test Statistic",
78
+ parameter: df,
79
+ parameterName: "df",
80
+ pValue,
81
+ confInt: [estimate - half, estimate + half],
82
+ confLevel,
83
+ estimate,
84
+ estimateNames: "P(X<Y)+.5*P(X=Y)",
85
+ };
86
+ }
@@ -7,6 +7,13 @@ export interface ChisqTestOptions {
7
7
  p?: readonly number[];
8
8
  /** Rescale `p` to sum to 1. Default `false`, in which case `p` must sum to 1. */
9
9
  rescaleP?: boolean;
10
+ /**
11
+ * Compute the p-value by Monte Carlo simulation with `B` replicates (R's `simulate.p.value`), using the random
12
+ * stream of {@link setSeed} as R does. Default `false`.
13
+ */
14
+ simulatePValue?: boolean;
15
+ /** Number of replicates for `simulatePValue`. Default `2000`. */
16
+ B?: number;
10
17
  }
11
18
  /**
12
19
  * Result of {@link chisqTest}. Has no `alternative`, because R's `chisq.test()` does not return one.
@@ -27,6 +34,19 @@ export interface ChisqTestResult extends Omit<HTest, "alternative"> {
27
34
  */
28
35
  stdres: number[] | number[][];
29
36
  }
37
+ /** Result of {@link chisqTest} with two factor vectors: also the levels that label the rows and columns. */
38
+ export interface ChisqTestFactorsResult extends ChisqTestResult {
39
+ observed: number[][];
40
+ expected: number[][];
41
+ residuals: number[][];
42
+ stdres: number[][];
43
+ /** Levels of `x` (rows of the table), sorted by code point. */
44
+ rowLevels: string[];
45
+ /** Levels of `y` (columns of the table), sorted by code point. */
46
+ colLevels: string[];
47
+ }
48
+ /** A factor: category labels, with `null` or `undefined` for missing values (R's NA). */
49
+ export type Factor = readonly (string | null | undefined)[];
30
50
  /**
31
51
  * Pearson's chi-squared test. Equivalent to R's `chisq.test()`.
32
52
  *
@@ -36,10 +56,16 @@ export interface ChisqTestResult extends Omit<HTest, "alternative"> {
36
56
  * 2 x 2 tables by default; as in R, the amount subtracted is `min(0.5, min |O - E|)` over
37
57
  * all cells. Sums are computed in extended precision, like R.
38
58
  *
39
- * Not implemented: `simulate.p.value` (Monte Carlo p-values) and passing two factor vectors.
59
+ * With `simulatePValue: true` the p-value is computed from `B` simulated samples (multinomial for goodness of fit,
60
+ * random tables with the observed margins otherwise), drawn from the random stream of {@link setSeed} exactly as in
61
+ * R, so `setSeed(s)` before the call gives R's p-value after `set.seed(s)`.
62
+ *
63
+ * Given two factor vectors (arrays of labels of the same length), tests independence in their contingency table, as
64
+ * R's `chisq.test(x, y)`; pairs with a missing label are dropped and the levels are sorted by code point.
65
+ *
40
66
  * R's warning for expected counts below 5 is not issued.
41
67
  *
42
- * @param x Counts, or a contingency table as an array of rows.
68
+ * @param x Counts, or a contingency table as an array of rows (or a factor, with `y`).
43
69
  * @param options See {@link ChisqTestOptions}.
44
70
  * @returns The test result, with `statisticName` `"X-squared"`; see {@link ChisqTestResult}.
45
71
  *
@@ -50,6 +76,12 @@ export interface ChisqTestResult extends Omit<HTest, "alternative"> {
50
76
  * r.pValue; // 0.03762001663483994
51
77
  *
52
78
  * chisqTest([20, 30, 50]).pValue; // 0.0009118819655545154 (goodness of fit, equal p)
79
+ *
80
+ * setSeed(1);
81
+ * chisqTest([20, 15, 25], { simulatePValue: true }).pValue; // 0.296351824087956 (R: set.seed(1); chisq.test(...))
82
+ *
83
+ * chisqTest(["a", "b", "a", "b"], ["u", "u", "v", "v"]).rowLevels; // ["a", "b"]
53
84
  * ```
54
85
  */
55
86
  export declare function chisqTest(x: Counts | readonly Counts[], options?: ChisqTestOptions): ChisqTestResult;
87
+ export declare function chisqTest(x: Factor, y: Factor, options?: ChisqTestOptions): ChisqTestFactorsResult;
@@ -12,9 +12,17 @@
12
12
  // 1-row or 1-column matrix) rejects only negative and NaN (Inf just makes the statistic NaN).
13
13
  // Fractional counts are accepted in both cases
14
14
  // - Sums are taken in double-double (R's sum accumulates in extended precision)
15
- // - simulate.p.value (Monte Carlo) and the two-factor-vector form are not implemented
15
+ // - Simulated p-values (Hope 1968; R's documented behaviour): (1 + #{simulated statistics >= (1 - 64 eps) times the
16
+ // observed one}) / (B + 1). Goodness of fit draws the B samples of size n = sum(x) at once with sampleInt (R's
17
+ // sample.int with prob) and counts them n at a time; contingency tables are drawn with Patefield's algorithm
18
+ // (src/random/r2dtable.ts). The statistic is then the uncorrected one, and the parameter is NaN (R's NA). Tables
19
+ // with a zero margin are not simulated (ordinary test), as in R
20
+ // - Two factor vectors: the table of the complete pairs, with the distinct values sorted by code point (C locale)
16
21
  import { pgamma1 } from "../distributions/gamma.js";
22
+ import { logFactorialTable, rcont2 } from "../random/r2dtable.js";
23
+ import { sampleInt } from "../random/sample.js";
17
24
  import { ddAdd } from "../special/dd.js";
25
+ import { simulatedMethod } from "./core/simulate.js";
18
26
  /** Sum (accumulated in double-double, then rounded; with Inf present, the double sum = ±Inf or NaN) */
19
27
  function ddSum(x) {
20
28
  let s = [0, 0];
@@ -25,33 +33,42 @@ function ddSum(x) {
25
33
  }
26
34
  return Number.isFinite(plain) ? s[0] : plain;
27
35
  }
28
- /**
29
- * Pearson's chi-squared test. Equivalent to R's `chisq.test()`.
30
- *
31
- * Given an array of counts, tests goodness of fit to `options.p`. Given a matrix (an array
32
- * of rows), tests independence in the contingency table; a matrix with a single row or
33
- * column is treated as a goodness-of-fit test, as in R. Yates' correction is applied to
34
- * 2 x 2 tables by default; as in R, the amount subtracted is `min(0.5, min |O - E|)` over
35
- * all cells. Sums are computed in extended precision, like R.
36
- *
37
- * Not implemented: `simulate.p.value` (Monte Carlo p-values) and passing two factor vectors.
38
- * R's warning for expected counts below 5 is not issued.
39
- *
40
- * @param x Counts, or a contingency table as an array of rows.
41
- * @param options See {@link ChisqTestOptions}.
42
- * @returns The test result, with `statisticName` `"X-squared"`; see {@link ChisqTestResult}.
43
- *
44
- * @example
45
- * ```ts
46
- * const r = chisqTest([[12, 5], [7, 15]]);
47
- * r.statistic; // 4.322120391218687 (with Yates' continuity correction)
48
- * r.pValue; // 0.03762001663483994
49
- *
50
- * chisqTest([20, 30, 50]).pValue; // 0.0009118819655545154 (goodness of fit, equal p)
51
- * ```
52
- */
53
- export function chisqTest(x, options = {}) {
54
- const correct = options.correct ?? true;
36
+ export function chisqTest(x, yOrOptions, maybeOptions) {
37
+ if (Array.isArray(yOrOptions))
38
+ return chisqFactors(x, yOrOptions, maybeOptions ?? {});
39
+ return chisqCounts(x, yOrOptions ?? {});
40
+ }
41
+ /** Code-point order (the C locale) */
42
+ const byCodePoint = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
43
+ function chisqFactors(x, y, options) {
44
+ if (x.length !== y.length)
45
+ throw new RangeError("'x' and 'y' must have the same length");
46
+ const missing = (v) => v === null || v === undefined;
47
+ for (const v of [...x, ...y]) {
48
+ if (!missing(v) && typeof v !== "string")
49
+ throw new TypeError("factor values must be strings (or null for missing values)");
50
+ }
51
+ const xs = [];
52
+ const ys = [];
53
+ x.forEach((v, i) => {
54
+ const w = y[i];
55
+ if (!missing(v) && !missing(w)) {
56
+ xs.push(v);
57
+ ys.push(w);
58
+ }
59
+ });
60
+ const rowLevels = [...new Set(xs)].sort(byCodePoint);
61
+ const colLevels = [...new Set(ys)].sort(byCodePoint);
62
+ if (rowLevels.length < 2 || colLevels.length < 2)
63
+ throw new RangeError("'x' and 'y' must have at least 2 levels");
64
+ const ri = new Map(rowLevels.map((v, i) => [v, i]));
65
+ const ci = new Map(colLevels.map((v, i) => [v, i]));
66
+ const table = rowLevels.map(() => colLevels.map(() => 0));
67
+ xs.forEach((v, k) => table[ri.get(v)][ci.get(ys[k])]++);
68
+ const r = contingency(table, options);
69
+ return { ...r, rowLevels, colLevels };
70
+ }
71
+ function chisqCounts(x, options) {
55
72
  const isMatrix = x.length > 0 && typeof x[0] !== "number";
56
73
  if (isMatrix) {
57
74
  const rows = x.map((r) => Array.from(r));
@@ -63,10 +80,26 @@ export function chisqTest(x, options = {}) {
63
80
  return goodnessOfFit(rows[0], options);
64
81
  if (nc === 1)
65
82
  return goodnessOfFit(rows.map((r) => r[0]), options);
66
- return contingency(rows, correct);
83
+ return contingency(rows, options);
67
84
  }
68
85
  return goodnessOfFit(Array.from(x), options);
69
86
  }
87
+ /** Number of replicates, checked when a simulation is run */
88
+ function replicates(options) {
89
+ const B = options.B ?? 2000;
90
+ if (!(B >= 0 && B < 2 ** 31))
91
+ throw new RangeError("'B' must be a non-negative number");
92
+ return B;
93
+ }
94
+ /** (1 + #{sims >= (1 - 64 eps) stat}) / (B + 1) */
95
+ function monteCarloP(sims, stat, B) {
96
+ const threshold = (1 - 64 * Number.EPSILON) * stat;
97
+ let count = 0;
98
+ for (let i = 0; i < sims.length; i++)
99
+ if (sims[i] >= threshold)
100
+ count++;
101
+ return (1 + count) / (B + 1);
102
+ }
70
103
  function pValueOf(stat, df) {
71
104
  return Number.isNaN(stat) ? NaN : pgamma1(stat, df / 2, 2, false, false);
72
105
  }
@@ -105,21 +138,80 @@ function goodnessOfFit(x, options) {
105
138
  checkExpected(E);
106
139
  const V = p.map((v, i) => E[i] * (1 - v));
107
140
  const stat = ddSum(x.map((v, i) => (v - E[i]) ** 2 / E[i]));
108
- const df = k - 1;
141
+ let method = "Chi-squared test for given probabilities";
142
+ let df = k - 1;
143
+ let pValue;
144
+ if (options.simulatePValue ?? false) {
145
+ const B = replicates(options);
146
+ method += simulatedMethod(B);
147
+ df = NaN;
148
+ pValue = monteCarloP(simulateGoodnessOfFit(n, p, E, B), stat, B);
149
+ }
150
+ else
151
+ pValue = pValueOf(stat, df);
109
152
  return {
110
- method: "Chi-squared test for given probabilities",
153
+ method,
111
154
  statistic: stat,
112
155
  statisticName: "X-squared",
113
156
  parameter: df,
114
157
  parameterName: "df",
115
- pValue: pValueOf(stat, df),
158
+ pValue,
116
159
  observed: x,
117
160
  expected: E,
118
161
  residuals: x.map((v, i) => (v - E[i]) / Math.sqrt(E[i])),
119
162
  stdres: x.map((v, i) => (v - E[i]) / Math.sqrt(V[i])),
120
163
  };
121
164
  }
122
- function contingency(x, correct) {
165
+ /**
166
+ * Statistics of B multinomial samples: B n categories drawn at once with probabilities p (sampleInt, R's
167
+ * sample.int(k, B n, TRUE, prob = p)), laid out column by column in a matrix of floor(n) rows (recycled to fill the
168
+ * last column, as R's matrix() does when n is not an integer) and counted per column
169
+ */
170
+ function simulateGoodnessOfFit(n, p, E, B) {
171
+ const k = p.length;
172
+ const draws = sampleInt(k, { size: Math.trunc(B * n), replace: true, prob: p });
173
+ const rows = Math.trunc(n);
174
+ if (draws.length === 0)
175
+ return new Float64Array(0);
176
+ if (rows === 0)
177
+ throw new RangeError("invalid 'nrow' value (too large or NA)");
178
+ const cols = Math.ceil(draws.length / rows);
179
+ const out = new Float64Array(cols);
180
+ const counts = new Float64Array(k);
181
+ for (let j = 0; j < cols; j++) {
182
+ counts.fill(0);
183
+ for (let i = 0; i < rows; i++)
184
+ counts[draws[(j * rows + i) % draws.length]]++;
185
+ let s = 0;
186
+ for (let c = 0; c < k; c++)
187
+ s += (counts[c] - E[c]) ** 2 / E[c];
188
+ out[j] = s;
189
+ }
190
+ return out;
191
+ }
192
+ /** Statistics of B random tables with the margins sr, sc (Patefield's algorithm), summed column by column */
193
+ function simulateTables(sr, sc, E, B) {
194
+ const nr = sr.length;
195
+ const nc = sc.length;
196
+ const total = sr.reduce((a, b) => a + b, 0);
197
+ const fact = logFactorialTable(total);
198
+ const table = new Int32Array(nr * nc);
199
+ const out = new Float64Array(Math.trunc(B));
200
+ for (let b = 0; b < out.length; b++) {
201
+ rcont2(sr, sc, fact, table);
202
+ let s = 0;
203
+ for (let j = 0; j < nc; j++) {
204
+ for (let i = 0; i < nr; i++) {
205
+ const e = E[i][j];
206
+ s += (table[i + j * nr] - e) ** 2 / e;
207
+ }
208
+ }
209
+ out[b] = s;
210
+ }
211
+ return out;
212
+ }
213
+ function contingency(x, options) {
214
+ const correct = options.correct ?? true;
123
215
  const nr = x.length;
124
216
  const nc = x[0].length;
125
217
  const all = x.flat();
@@ -135,15 +227,26 @@ function contingency(x, correct) {
135
227
  const diff = x.map((r, i) => r.map((v, j) => v - E[i][j]));
136
228
  let method = "Pearson's Chi-squared test";
137
229
  let stat;
138
- const yates = correct && nr === 2 && nc === 2 ? Math.min(0.5, ...diff.flat().map(Math.abs)) : 0;
139
- if (yates > 0) {
230
+ let df = (nr - 1) * (nc - 1);
231
+ let pValue;
232
+ const simulate = (options.simulatePValue ?? false) && sr.every((v) => v > 0) && sc.every((v) => v > 0);
233
+ const yates = !simulate && correct && nr === 2 && nc === 2 ? Math.min(0.5, ...diff.flat().map(Math.abs)) : 0;
234
+ if (simulate) {
235
+ // counts are integers for the simulation (R's C code takes the margins as integers)
236
+ const B = replicates(options);
237
+ method += simulatedMethod(B);
238
+ stat = ddSum(diff.flatMap((r, i) => r.map((d, j) => (d * d) / E[i][j])));
239
+ df = NaN;
240
+ const sims = simulateTables(sr.map((v) => Math.trunc(v)), sc.map((v) => Math.trunc(v)), E, B);
241
+ pValue = monteCarloP(sims, stat, B);
242
+ }
243
+ else if (yates > 0) {
140
244
  method += " with Yates' continuity correction";
141
245
  stat = ddSum(diff.flatMap((r, i) => r.map((d, j) => (Math.abs(d) - yates) ** 2 / E[i][j])));
142
246
  }
143
247
  else {
144
248
  stat = ddSum(diff.flatMap((r, i) => r.map((d, j) => (d * d) / E[i][j])));
145
249
  }
146
- const df = (nr - 1) * (nc - 1);
147
250
  const V = E.map((r, i) => r.map((e, j) => e * (1 - sr[i] / n) * (1 - sc[j] / n)));
148
251
  return {
149
252
  method,
@@ -151,7 +254,7 @@ function contingency(x, correct) {
151
254
  statisticName: "X-squared",
152
255
  parameter: df,
153
256
  parameterName: "df",
154
- pValue: pValueOf(stat, df),
257
+ pValue: pValue ?? pValueOf(stat, df),
155
258
  observed: x,
156
259
  expected: E,
157
260
  residuals: diff.map((r, i) => r.map((d, j) => d / Math.sqrt(E[i][j]))),
@@ -16,3 +16,10 @@ export declare function dansariExact(x: number, m: number, n: number): number;
16
16
  * 64 ε on p keeps p = P(AB <= q) itself from being missed by rounding.
17
17
  */
18
18
  export declare function qansariExact(p: number, m: number, n: number): number;
19
+ /**
20
+ * R's qansari, used by ansari.test's exact interval and estimate: the smallest q at which the running sum of
21
+ * count(k) / C(N, m) over k = min, ..., q, accumulated in double, reaches p (p = 0 gives the minimum, p = 1 the
22
+ * maximum). Unlike {@link qansariExact} there is no slack, so a cumulative probability that equals p mathematically
23
+ * (such as 1/2) may be missed by rounding, as in R.
24
+ */
25
+ export declare function qansariR(p: number, m: number, n: number): number;
@@ -6,6 +6,7 @@
6
6
  // distribution follows from choosing a random m-subset position by position: at position t with r picks left among
7
7
  // N - t + 1 positions, the position is picked with probability r / (N - t + 1). The probabilities are kept directly
8
8
  // (counts overflow: C(100, 50) = 1e29), and tail probabilities are sums of positive terms.
9
+ import { choose } from "../../special/choose.js";
9
10
  const cache = new Map();
10
11
  function ansariDist(m, n) {
11
12
  const key = `${m},${n}`;
@@ -119,3 +120,67 @@ export function qansariExact(p, m, n) {
119
120
  }
120
121
  return min + probs.length - 1;
121
122
  }
123
+ const countCache = new Map();
124
+ /** Number of m-subsets of the N = m + n positions with each score sum (in double: exact up to 2^53), from min */
125
+ function ansariCounts(m, n) {
126
+ const key = `${m},${n}`;
127
+ const hit = countCache.get(key);
128
+ if (hit !== undefined)
129
+ return hit;
130
+ const N = m + n;
131
+ let maxSum = 0;
132
+ for (let i = 1; i <= N; i++)
133
+ maxSum += Math.min(i, N + 1 - i);
134
+ let P = Array.from({ length: m + 1 }, () => new Float64Array(maxSum + 1));
135
+ P[0][0] = 1;
136
+ for (let t = 0; t < N; t++) {
137
+ const a = Math.min(t + 1, N - t);
138
+ const Q = Array.from({ length: m + 1 }, () => new Float64Array(maxSum + 1));
139
+ for (let r = 0; r <= m; r++) {
140
+ if (m - r > N - t)
141
+ continue;
142
+ const row = P[r];
143
+ for (let s = 0; s <= maxSum; s++) {
144
+ const v = row[s];
145
+ if (v === 0)
146
+ continue;
147
+ if (r < m)
148
+ Q[r + 1][s + a] += v;
149
+ if (m - r < N - t)
150
+ Q[r][s] += v;
151
+ }
152
+ }
153
+ P = Q;
154
+ }
155
+ const full = P[m];
156
+ let lo = 0;
157
+ while (full[lo] === 0)
158
+ lo++;
159
+ let hi = full.length - 1;
160
+ while (full[hi] === 0)
161
+ hi--;
162
+ const out = { min: lo, counts: full.slice(lo, hi + 1) };
163
+ countCache.set(key, out);
164
+ return out;
165
+ }
166
+ /**
167
+ * R's qansari, used by ansari.test's exact interval and estimate: the smallest q at which the running sum of
168
+ * count(k) / C(N, m) over k = min, ..., q, accumulated in double, reaches p (p = 0 gives the minimum, p = 1 the
169
+ * maximum). Unlike {@link qansariExact} there is no slack, so a cumulative probability that equals p mathematically
170
+ * (such as 1/2) may be missed by rounding, as in R.
171
+ */
172
+ export function qansariR(p, m, n) {
173
+ const { min, counts } = ansariCounts(m, n);
174
+ if (p <= 0)
175
+ return min;
176
+ if (p >= 1)
177
+ return min + counts.length - 1;
178
+ const c = choose(m + n, m);
179
+ let s = 0;
180
+ for (let i = 0; i < counts.length; i++) {
181
+ s += counts[i] / c;
182
+ if (s >= p)
183
+ return min + i;
184
+ }
185
+ return min + counts.length - 1;
186
+ }
@@ -0,0 +1,2 @@
1
+ /** R's method suffix for a simulated p-value; B is printed as R's paste() prints a number */
2
+ export declare function simulatedMethod(B: number): string;
@@ -0,0 +1,16 @@
1
+ // Shared pieces of the Monte Carlo p-values of chisqTest and fisherTest.
2
+ /** R's method suffix for a simulated p-value; B is printed as R's paste() prints a number */
3
+ export function simulatedMethod(B) {
4
+ return ` with simulated p-value\n\t (based on ${formatR(B)} replicates)`;
5
+ }
6
+ /** A number as R's as.character prints it (15 significant digits, fixed or scientific, whichever is narrower) */
7
+ function formatR(v) {
8
+ if (!Number.isFinite(v) || v === 0)
9
+ return String(v);
10
+ const sci = v.toExponential(14).replace(/\.?0+e/, "e");
11
+ const [mant, exp] = sci.split("e");
12
+ const e = Number(exp);
13
+ const sciStr = `${mant}e${e < 0 ? "-" : "+"}${String(Math.abs(e)).padStart(2, "0")}`;
14
+ const fixed = String(Number(v.toPrecision(15)));
15
+ return fixed.length <= sciStr.length ? fixed : sciStr;
16
+ }
@@ -12,6 +12,14 @@ export interface FisherTestOptions {
12
12
  confLevel?: number;
13
13
  /** Odds ratio under the null hypothesis (2 x 2 tables only). Default `1`. */
14
14
  or?: number;
15
+ /**
16
+ * Compute the p-value of an r x c table (larger than 2 x 2) by Monte Carlo simulation with `B` replicates (R's
17
+ * `simulate.p.value`), using the random stream of {@link setSeed} as R does. Ignored for 2 x 2 tables. Default
18
+ * `false`.
19
+ */
20
+ simulatePValue?: boolean;
21
+ /** Number of replicates for `simulatePValue`. Default `2000`. */
22
+ B?: number;
15
23
  }
16
24
  /**
17
25
  * Result of {@link fisherTest}. Has no `statistic` or `statisticName`, because R's
@@ -31,7 +39,10 @@ export interface FisherTestResult extends Omit<HTest, "statistic" | "statisticNa
31
39
  * tolerance `1e-7`, as in R). Non-integer counts are rounded to the nearest integer
32
40
  * (ties to even), where R warns and rounds.
33
41
  *
34
- * Not implemented: R's `hybrid` and `simulate.p.value` options.
42
+ * With `simulatePValue: true`, the p-value of a table larger than 2 x 2 is computed from `B` random tables with the
43
+ * observed margins, drawn from the random stream of {@link setSeed} exactly as in R.
44
+ *
45
+ * Not implemented: R's `hybrid` option.
35
46
  *
36
47
  * @param x Contingency table as an array of rows (at least 2 x 2).
37
48
  * @param options See {@link FisherTestOptions}.
@@ -25,11 +25,19 @@
25
25
  // same probability are merged. For nodes with two columns left, a cumulative sum over the sorted
26
26
  // values of the remaining tables is prepared and each path is added via binary search.
27
27
  // Probabilities are held as double-double logarithms.
28
- // R's hybrid and simulate.p.value are not implemented.
28
+ //
29
+ // Simulated p-values (r x c only; R's documented behaviour): rows and columns that are all zero are dropped, B random
30
+ // tables with the observed margins are drawn with Patefield's algorithm (src/random/r2dtable.ts), and the p-value is
31
+ // (1 + #{simulated tables with -sum log(x_ij!) <= the observed one / (1 + 64 eps)}) / (B + 1). A 2 x 2 table is always
32
+ // tested exactly.
33
+ // R's hybrid is not implemented.
29
34
  import { dhyper1, phyper1 } from "../distributions/hypergeometric.js";
30
35
  import { roundHalfEven } from "../internal/integer.js";
36
+ import { logFactorialTable, rcont2 } from "../random/r2dtable.js";
37
+ import { lfactorial } from "../special/choose.js";
31
38
  import { uniroot } from "../internal/uniroot.js";
32
39
  import { ddAdd, ddLog, ddNeg, ddSub } from "../special/dd.js";
40
+ import { simulatedMethod } from "./core/simulate.js";
33
41
  import { matchAlternative } from "./types.js";
34
42
  /**
35
43
  * Fisher's exact test for count data. Equivalent to R's `fisher.test()`.
@@ -41,7 +49,10 @@ import { matchAlternative } from "./types.js";
41
49
  * tolerance `1e-7`, as in R). Non-integer counts are rounded to the nearest integer
42
50
  * (ties to even), where R warns and rounds.
43
51
  *
44
- * Not implemented: R's `hybrid` and `simulate.p.value` options.
52
+ * With `simulatePValue: true`, the p-value of a table larger than 2 x 2 is computed from `B` random tables with the
53
+ * observed margins, drawn from the random stream of {@link setSeed} exactly as in R.
54
+ *
55
+ * Not implemented: R's `hybrid` option.
45
56
  *
46
57
  * @param x Contingency table as an array of rows (at least 2 x 2).
47
58
  * @param options See {@link FisherTestOptions}.
@@ -73,11 +84,46 @@ export function fisherTest(x, options = {}) {
73
84
  if (nr === 2 && nc === 2)
74
85
  return fisher2x2(t, options, method);
75
86
  // For rxc, alternative etc. are not validated and are returned as given (as in R)
76
- return {
77
- method,
78
- alternative: (options.alternative ?? "two.sided"),
79
- pValue: fisherRxC(t),
80
- };
87
+ const alternative = (options.alternative ?? "two.sided");
88
+ if (options.simulatePValue ?? false) {
89
+ const B = options.B ?? 2000;
90
+ if (!(B >= 0 && B < 2 ** 31))
91
+ throw new RangeError("'B' must be a non-negative number");
92
+ return { method: method + simulatedMethod(B), alternative, pValue: fisherSimulated(t, B) };
93
+ }
94
+ return { method, alternative, pValue: fisherRxC(t) };
95
+ }
96
+ /** Monte Carlo p-value of an r x c table: tables with fixed margins drawn by Patefield's algorithm */
97
+ function fisherSimulated(t, B) {
98
+ const keepRows = t.filter((r) => r.some((v) => v > 0));
99
+ const keepCols = t[0].map((_, j) => j).filter((j) => t.some((r) => r[j] > 0));
100
+ if (keepRows.length <= 1)
101
+ throw new RangeError("need 2 or more non-zero row marginals");
102
+ if (keepCols.length <= 1)
103
+ throw new RangeError("need 2 or more non-zero column marginals");
104
+ const x = keepRows.map((r) => keepCols.map((j) => r[j]));
105
+ const sr = x.map((r) => r.reduce((a, b) => a + b, 0));
106
+ const sc = x[0].map((_, j) => x.reduce((a, r) => a + r[j], 0));
107
+ const nr = sr.length;
108
+ const nc = sc.length;
109
+ // the observed -sum log(x_ij!), summed in double-double
110
+ let acc = [0, 0];
111
+ for (const v of x.flat())
112
+ acc = ddAdd(acc, [-lfactorial(v), 0]);
113
+ const threshold = acc[0] / (1 + 64 * Number.EPSILON);
114
+ const fact = logFactorialTable(sr.reduce((a, b) => a + b, 0));
115
+ const table = new Int32Array(nr * nc);
116
+ let count = 0;
117
+ const reps = Math.trunc(B);
118
+ for (let b = 0; b < reps; b++) {
119
+ rcont2(sr, sc, fact, table);
120
+ let s = 0;
121
+ for (let k = 0; k < table.length; k++)
122
+ s -= fact[table[k]];
123
+ if (s <= threshold)
124
+ count++;
125
+ }
126
+ return Math.max(0, Math.min(1, (1 + count) / (B + 1)));
81
127
  }
82
128
  // ---- 2×2 ----
83
129
  /** Relative slack for counting a table as "no more likely than the observed one" in the two-sided p-value */