@numero-uno-jpn/rstats 0.6.1 → 0.7.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 (49) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.ja.md +9 -9
  3. package/README.md +9 -9
  4. package/dist/chunks/chunk-6R7YDHA2.js +2 -0
  5. package/dist/chunks/chunk-AFKYWGKN.js +2 -0
  6. package/dist/chunks/{chunk-QNAIK4PY.js → chunk-ANYGLFT4.js} +2 -2
  7. package/dist/chunks/chunk-BI5RSUZ2.js +2 -0
  8. package/dist/chunks/chunk-J3SNI7KY.js +2 -0
  9. package/dist/chunks/{chunk-Y4IZV7XK.js → chunk-JCZAB6C5.js} +2 -2
  10. package/dist/chunks/{chunk-7NK4SA6B.js → chunk-MVG5LUZU.js} +2 -2
  11. package/dist/chunks/chunk-PTPPP4TI.js +2 -0
  12. package/dist/chunks/{chunk-TPC6MTYC.js → chunk-QNQJA6KZ.js} +2 -2
  13. package/dist/chunks/{chunk-AJYQNFXK.js → chunk-SXSJXDD3.js} +2 -2
  14. package/dist/chunks/{chunk-ZWJ42QN6.js → chunk-UIOAWLAN.js} +1 -1
  15. package/dist/chunks/{chunk-NOCEAM44.js → chunk-XYXHHF5L.js} +1 -1
  16. package/dist/chunks/{chunk-2JCIB5H2.js → chunk-YKN6OGJL.js} +2 -2
  17. package/dist/chunks/{chunk-UGUQYWRQ.js → chunk-ZW52Z3GY.js} +1 -1
  18. package/dist/chunks/{chunk-DRNMIEYH.js → chunk-ZYA4ISAT.js} +1 -1
  19. package/dist/descriptive.js +2 -2
  20. package/dist/distributions.js +2 -2
  21. package/dist/entries/distributions.d.ts +1 -0
  22. package/dist/entries/distributions.js +1 -0
  23. package/dist/entries/special.d.ts +1 -0
  24. package/dist/entries/special.js +1 -0
  25. package/dist/entries/tests.d.ts +1 -1
  26. package/dist/entries/tests.js +1 -1
  27. package/dist/htest/ansariTest.d.ts +18 -1
  28. package/dist/htest/ansariTest.js +181 -8
  29. package/dist/htest/chisqTest.d.ts +34 -2
  30. package/dist/htest/chisqTest.js +140 -37
  31. package/dist/htest/core/ansari.d.ts +7 -0
  32. package/dist/htest/core/ansari.js +65 -0
  33. package/dist/htest/core/simulate.d.ts +2 -0
  34. package/dist/htest/core/simulate.js +16 -0
  35. package/dist/htest/fisherTest.d.ts +12 -1
  36. package/dist/htest/fisherTest.js +53 -7
  37. package/dist/linalg.js +2 -2
  38. package/dist/numerics.js +2 -2
  39. package/dist/random/r2dtable.d.ts +26 -0
  40. package/dist/random/r2dtable.js +153 -0
  41. package/dist/rstats.js +3 -2
  42. package/dist/special/log1p.d.ts +53 -0
  43. package/dist/special/log1p.js +93 -0
  44. package/dist/special.js +2 -2
  45. package/dist/tests.js +3 -2
  46. package/package.json +1 -1
  47. package/dist/chunks/chunk-7JVSDGQQ.js +0 -2
  48. package/dist/chunks/chunk-NAYDS7CL.js +0 -2
  49. package/dist/chunks/chunk-XM2TVD63.js +0 -2
@@ -1,4 +1,4 @@
1
- // Ansari-Bradley two-sample test of scale (R's ansari.test, without the optional confidence interval).
1
+ // Ansari-Bradley two-sample test of scale (R's ansari.test), with the confidence interval for the ratio of scales.
2
2
  //
3
3
  // Written for rStats.js from the published test (Ansari and Bradley, Ann. Math. Stat. 31, 1960; no ported code).
4
4
  // Scores min(r, N + 1 - r) of the pooled ranks r (average ranks for ties); the statistic is the sum over the first
@@ -7,13 +7,36 @@
7
7
  // follows R's ansari.test behaviour). Otherwise the statistic is standardised and compared with the normal, with Ansari
8
8
  // and Bradley's mean and the variance of a linear rank statistic from the observed sum of squared scores (the form
9
9
  // scipy.stats.ansari also uses).
10
- import { pnorm } from "../distributions/normal.js";
10
+ //
11
+ // Interval and estimate (Bauer, JASA 67, 1972, section 5): with the locations taken as 0, AB(s) is the statistic of
12
+ // x / s against y, a step function of the ratio of scales s. Exact: AB(s) is evaluated between consecutive
13
+ // candidate ratios x_i / y_j >= 0 (and beyond the largest), and the limits are the candidate ratios where it crosses
14
+ // the exact quantiles; the estimate is the midpoint of the crossing of the median. Normal approximation: the limits and
15
+ // the estimate are where the standardised AB(s) (standardised as for the test: R 4.5.2's ansari.test) crosses the normal
16
+ // quantiles (and 0), found with R's uniroot conventions (tolerance 1e-4) in the range of the ratios of the positive
17
+ // values and of the negative values. The candidate sets, evaluation points, search range, tolerance and the cases
18
+ // returned as NaN (R's NA) follow R's documented and observed behaviour.
19
+ import { pnorm, qnorm } from "../distributions/normal.js";
11
20
  import { rank } from "../internal/summary.js";
12
- import { pansariExact } from "./core/ansari.js";
13
- import { matchAlternative } from "./types.js";
21
+ import { uniroot } from "../internal/uniroot.js";
22
+ import { pansariExact, qansariR } from "./core/ansari.js";
23
+ import { checkConfLevelOpen, matchAlternative } from "./types.js";
14
24
  /**
15
- * Ansari-Bradley test that two samples differ in scale. Equivalent to R's `ansari.test()` (without `conf.int`).
25
+ * Ansari-Bradley test that two samples differ in scale. Equivalent to R's `ansari.test()`.
16
26
  * `NaN` values are dropped.
27
+ *
28
+ * With `confInt: true`, `confInt` is the interval for the ratio of the scales of `x` and `y` and `estimate` its
29
+ * estimate, both computed with the locations taken as 0 (exact without ties when both samples have fewer than 50
30
+ * values, otherwise by the normal approximation, whose limits are roots found to a tolerance of 1e-4 as in R). Limits
31
+ * that cannot be formed (the samples differ in location) are `NaN`. With ties and `exact` unset or `true`, R fails
32
+ * ("object 'cint' not found"); rStats.js returns the normal-approximation interval, as with `exact: false`.
33
+ *
34
+ * @example
35
+ * ```ts
36
+ * const r = ansariTest([-2, -1, 1, 2], [-4, -3, 3, 4], { confInt: true });
37
+ * r.confInt; // [0.25, 0.6666666666666666]
38
+ * r.estimate; // 0.41666666666666663
39
+ * ```
17
40
  */
18
41
  export function ansariTest(x, y, options = {}) {
19
42
  const xs = Array.from(x).filter((v) => !Number.isNaN(v));
@@ -25,6 +48,10 @@ export function ansariTest(x, y, options = {}) {
25
48
  if (n < 1)
26
49
  throw new RangeError("not enough 'y' observations");
27
50
  const alternative = matchAlternative(options.alternative);
51
+ const confInt = options.confInt ?? false;
52
+ const confLevel = options.confLevel ?? 0.95;
53
+ if (confInt)
54
+ checkConfLevelOpen(confLevel);
28
55
  const N = m + n;
29
56
  const r = rank(xs.concat(ys));
30
57
  const a = r.map((v) => Math.min(v, N - v + 1));
@@ -34,6 +61,7 @@ export function ansariTest(x, y, options = {}) {
34
61
  const ties = new Set(r).size < N;
35
62
  const exact = options.exact ?? (m < 50 && n < 50 && !ties);
36
63
  let pValue;
64
+ let ci;
37
65
  if (exact && !ties) {
38
66
  const upperFrom = (q) => pansariExact(q - 1, m, n, false); // P(AB >= q)
39
67
  const lowerTo = (q) => pansariExact(q, m, n, true); // P(AB <= q)
@@ -47,6 +75,8 @@ export function ansariTest(x, y, options = {}) {
47
75
  pValue = upperFrom(statistic);
48
76
  else
49
77
  pValue = lowerTo(statistic);
78
+ if (confInt)
79
+ ci = exactInterval(xs, ys, alternative, confLevel);
50
80
  }
51
81
  else {
52
82
  // mean and variance with the sum of the scores at its value without ties (N (N + 2) / 4 for even N,
@@ -67,14 +97,157 @@ export function ansariTest(x, y, options = {}) {
67
97
  : alternative === "less"
68
98
  ? pnorm(z, { lowerTail: false })
69
99
  : pnorm(z);
100
+ if (confInt)
101
+ ci = normalInterval(xs, ys, alternative, confLevel);
70
102
  }
71
- return {
103
+ const result = {
72
104
  method: "Ansari-Bradley test",
73
105
  alternative,
74
106
  statistic,
75
107
  statisticName: "AB",
76
108
  pValue,
77
- nullValue: 1,
78
- nullValueName: "ratio of scales",
79
109
  };
110
+ if (ci !== undefined) {
111
+ result.confInt = ci.confInt;
112
+ result.confLevel = confLevel;
113
+ result.estimate = ci.estimate;
114
+ result.estimateNames = "ratio of scales";
115
+ }
116
+ result.nullValue = 1;
117
+ result.nullValueName = "ratio of scales";
118
+ return result;
119
+ }
120
+ /** AB statistic of x / s against y, with the scores of all observations and whether there are ties */
121
+ function scaledStatistic(xs, ys, s) {
122
+ const m = xs.length;
123
+ const N = m + ys.length;
124
+ const r = rankNaNLast(xs.map((v) => v / s).concat(ys));
125
+ const a = r.map((v) => Math.min(v, N - v + 1));
126
+ let ab = 0;
127
+ for (let i = 0; i < m; i++)
128
+ ab += a[i];
129
+ return { ab, a, ties: new Set(r).size < N };
130
+ }
131
+ /** Average ranks with NaN (0 / 0 at s = 0) ranked last in order of appearance, as R's rank(na.last = TRUE) */
132
+ function rankNaNLast(v) {
133
+ const keep = v.filter((e) => !Number.isNaN(e));
134
+ if (keep.length === v.length)
135
+ return rank(v);
136
+ const rk = rank(keep);
137
+ let i = 0;
138
+ let next = keep.length;
139
+ return v.map((e) => (Number.isNaN(e) ? ++next : rk[i++]));
140
+ }
141
+ /** One-sided limits at level 1 - 2a for "greater" (lower limit) and "less" (upper limit), two-sided otherwise */
142
+ function shapeInterval(alternative, a, limits) {
143
+ if (alternative === "two.sided")
144
+ return limits(a);
145
+ if (alternative === "greater")
146
+ return [limits(2 * a)[0], Infinity];
147
+ return [0, limits(2 * a)[1]];
148
+ }
149
+ /** Exact interval and estimate from the candidate ratios x_i / y_j >= 0 */
150
+ function exactInterval(xs, ys, alternative, confLevel) {
151
+ const m = xs.length;
152
+ const n = ys.length;
153
+ const sigma = [];
154
+ for (const x of xs)
155
+ for (const y of ys)
156
+ if (x / y >= 0)
157
+ sigma.push(x / y);
158
+ sigma.sort((p, q) => p - q);
159
+ const L = sigma.length;
160
+ if (L === 0)
161
+ return { confInt: shapeInterval(alternative, 1 - confLevel, () => [NaN, NaN]), estimate: NaN };
162
+ // AB between consecutive candidates, and at 2.01 times the largest
163
+ const abs = sigma.map((v, k) => scaledStatistic(xs, ys, v + (k < L - 1 ? (sigma[k + 1] - v) / 2 : v * 1.01)).ab);
164
+ // the largest candidate with the smallest positive AB - q (or the smallest with the smallest AB - q >= 0)
165
+ const crossing = (q, strict, largest) => {
166
+ let best = Infinity;
167
+ for (const v of abs)
168
+ if ((strict ? v - q > 0 : v - q >= 0) && v - q < best)
169
+ best = v - q;
170
+ let out = largest ? -Infinity : Infinity;
171
+ abs.forEach((v, k) => {
172
+ if (v - q === best)
173
+ out = largest ? Math.max(out, sigma[k]) : Math.min(out, sigma[k]);
174
+ });
175
+ return out;
176
+ };
177
+ const limits = (alpha) => {
178
+ const qLow = qansariR(alpha / 2, m, n);
179
+ const qHigh = qansariR(1 - alpha / 2, m, n);
180
+ if (!abs.some((v) => v - qLow >= 0) || !abs.some((v) => v - qHigh > 0))
181
+ return [NaN, NaN];
182
+ const lower = crossing(qLow, false, false);
183
+ const upper = crossing(qHigh, true, true);
184
+ // AB need not be monotone in s: if the limits come out in the wrong order, the quantiles are interchanged
185
+ if (lower > upper)
186
+ return [crossing(qHigh, false, false), crossing(qLow, true, true)];
187
+ return [lower, upper];
188
+ };
189
+ const confInt = shapeInterval(alternative, 1 - confLevel, limits);
190
+ const qMed = qansariR(0.5, m, n);
191
+ let below = -Infinity;
192
+ let above = Infinity;
193
+ abs.forEach((v, k) => {
194
+ if (v - qMed <= 0)
195
+ below = Math.max(below, sigma[k]);
196
+ else
197
+ above = Math.min(above, sigma[k]);
198
+ });
199
+ const estimate = below === -Infinity || above === Infinity ? NaN : (above + below) / 2;
200
+ return { confInt, estimate };
201
+ }
202
+ /** Normal-approximation interval and estimate (undefined when the search range is not finite) */
203
+ function normalInterval(xs, ys, alternative, confLevel) {
204
+ const m = xs.length;
205
+ const n = ys.length;
206
+ const N = m + n;
207
+ const even = N % 2 === 0;
208
+ const z = (s, zq) => {
209
+ const { ab, a, ties } = scaledStatistic(xs, ys, s);
210
+ const centred = even ? ab - (m * (N + 2)) / 4 : ab - (m * (N + 1) ** 2) / (4 * N);
211
+ let sd;
212
+ if (!ties) {
213
+ sd = even
214
+ ? Math.sqrt((m * n * (N + 2) * (N - 2)) / (48 * (N - 1)))
215
+ : Math.sqrt((m * n * (N + 1) * (3 + N * N)) / (48 * N * N));
216
+ }
217
+ else {
218
+ let sq = 0;
219
+ for (const v of a)
220
+ sq += v * v;
221
+ sd = even
222
+ ? Math.sqrt((m * n * (16 * sq - N * (N + 2) ** 2)) / (16 * N * (N - 1)))
223
+ : Math.sqrt((m * n * (16 * N * sq - (N + 1) ** 4)) / (16 * N * N * (N - 1)));
224
+ }
225
+ return centred / sd - zq;
226
+ };
227
+ // search range: the ratios of the positive values, and of the non-positive x to the negative y
228
+ const ends = [];
229
+ const range = (xp, yp) => {
230
+ if (xp.length === 0 || yp.length === 0)
231
+ return;
232
+ ends.push(Math.min(...xp) / Math.max(...yp), Math.max(...xp) / Math.min(...yp));
233
+ };
234
+ range(xs.filter((v) => v > 0), ys.filter((v) => v > 0));
235
+ range(xs.filter((v) => v <= 0), ys.filter((v) => v < 0));
236
+ if (ends.some((v) => !Number.isFinite(v)))
237
+ return undefined;
238
+ const lo = Math.min(...ends);
239
+ const hi = Math.max(...ends);
240
+ const root = (zq) => uniroot((s) => z(s, zq), lo, hi, { tol: 1e-4 });
241
+ const limits = (alpha) => {
242
+ const zLow = qnorm(alpha / 2);
243
+ const zHigh = qnorm(alpha / 2, { lowerTail: false });
244
+ if (z(lo, zLow) > 0 || z(hi, zHigh) < 0)
245
+ return [NaN, NaN];
246
+ const u = root(zLow);
247
+ const l = root(zHigh);
248
+ return u <= l ? [u, l] : [l, u];
249
+ };
250
+ const confInt = shapeInterval(alternative, 1 - confLevel, limits);
251
+ const estimate = z(lo, 0) > 0 || z(hi, 0) < 0 ? NaN : root(0);
252
+ return { confInt, estimate };
80
253
  }
@@ -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
+ }