@numero-uno-jpn/rstats 0.5.0 → 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 (179) hide show
  1. package/CHANGELOG.md +125 -0
  2. package/README.ja.md +36 -20
  3. package/README.md +34 -18
  4. package/THIRD_PARTY_NOTICES.md +25 -5
  5. package/dist/chunks/chunk-6R7YDHA2.js +2 -0
  6. package/dist/chunks/chunk-AFKYWGKN.js +2 -0
  7. package/dist/chunks/chunk-ANYGLFT4.js +2 -0
  8. package/dist/chunks/chunk-BI5RSUZ2.js +2 -0
  9. package/dist/chunks/chunk-J3SNI7KY.js +2 -0
  10. package/dist/chunks/chunk-JCZAB6C5.js +2 -0
  11. package/dist/chunks/chunk-MVG5LUZU.js +2 -0
  12. package/dist/chunks/chunk-PTPPP4TI.js +2 -0
  13. package/dist/chunks/chunk-QNQJA6KZ.js +2 -0
  14. package/dist/chunks/chunk-SXSJXDD3.js +2 -0
  15. package/dist/chunks/chunk-UIOAWLAN.js +2 -0
  16. package/dist/chunks/chunk-XYXHHF5L.js +2 -0
  17. package/dist/chunks/chunk-YKN6OGJL.js +2 -0
  18. package/dist/chunks/chunk-ZW52Z3GY.js +2 -0
  19. package/dist/chunks/chunk-ZYA4ISAT.js +2 -0
  20. package/dist/descriptive/basic.d.ts +73 -0
  21. package/dist/descriptive/basic.js +256 -0
  22. package/dist/descriptive/cov.d.ts +39 -0
  23. package/dist/descriptive/cov.js +105 -0
  24. package/dist/descriptive/hist.d.ts +64 -0
  25. package/dist/descriptive/hist.js +304 -0
  26. package/dist/descriptive/moments.d.ts +63 -0
  27. package/dist/descriptive/moments.js +158 -0
  28. package/dist/descriptive/quantile.d.ts +50 -0
  29. package/dist/descriptive/quantile.js +131 -0
  30. package/dist/descriptive/rank.d.ts +23 -0
  31. package/dist/descriptive/rank.js +72 -0
  32. package/dist/descriptive/table.d.ts +54 -0
  33. package/dist/descriptive/table.js +160 -0
  34. package/dist/descriptive.js +2 -0
  35. package/dist/distributions/arcsine.d.ts +24 -0
  36. package/dist/distributions/arcsine.js +73 -0
  37. package/dist/distributions/invgamma.d.ts +29 -0
  38. package/dist/distributions/invgamma.js +85 -0
  39. package/dist/distributions/kumaraswamy.d.ts +17 -0
  40. package/dist/distributions/kumaraswamy.js +96 -0
  41. package/dist/distributions/laplace.d.ts +23 -0
  42. package/dist/distributions/laplace.js +69 -0
  43. package/dist/distributions/multinomial.d.ts +24 -0
  44. package/dist/distributions/multinomial.js +70 -0
  45. package/dist/distributions/nbeta.js +28 -10
  46. package/dist/distributions/nchisq.js +20 -3
  47. package/dist/distributions/pareto.d.ts +23 -0
  48. package/dist/distributions/pareto.js +76 -0
  49. package/dist/distributions/summary.d.ts +25 -0
  50. package/dist/distributions/summary.js +289 -0
  51. package/dist/distributions/triangular.d.ts +25 -0
  52. package/dist/distributions/triangular.js +87 -0
  53. package/dist/distributions.js +2 -0
  54. package/dist/entries/descriptive.d.ts +7 -0
  55. package/dist/entries/descriptive.js +8 -0
  56. package/dist/entries/distributions.d.ts +42 -0
  57. package/dist/entries/distributions.js +42 -0
  58. package/dist/entries/linalg.d.ts +11 -0
  59. package/dist/entries/linalg.js +11 -0
  60. package/dist/entries/numerics.d.ts +8 -0
  61. package/dist/entries/numerics.js +6 -0
  62. package/dist/entries/special.d.ts +10 -0
  63. package/dist/entries/special.js +10 -0
  64. package/dist/entries/tests.d.ts +21 -0
  65. package/dist/entries/tests.js +20 -0
  66. package/dist/htest/ansariTest.d.ts +30 -0
  67. package/dist/htest/ansariTest.js +253 -0
  68. package/dist/htest/aov.d.ts +85 -0
  69. package/dist/htest/aov.js +178 -0
  70. package/dist/htest/binomTest.d.ts +36 -0
  71. package/dist/htest/binomTest.js +121 -0
  72. package/dist/htest/chisqTest.d.ts +34 -2
  73. package/dist/htest/chisqTest.js +140 -37
  74. package/dist/htest/cor.d.ts +14 -0
  75. package/dist/htest/cor.js +4 -3
  76. package/dist/htest/core/ansari.d.ts +25 -0
  77. package/dist/htest/core/ansari.js +186 -0
  78. package/dist/htest/core/kolmogorov.d.ts +26 -0
  79. package/dist/htest/core/kolmogorov.js +221 -0
  80. package/dist/htest/core/mantelhaen.d.ts +26 -0
  81. package/dist/htest/core/mantelhaen.js +145 -0
  82. package/dist/htest/core/shapiro.d.ts +24 -0
  83. package/dist/htest/core/shapiro.js +142 -0
  84. package/dist/htest/core/simulate.d.ts +2 -0
  85. package/dist/htest/core/simulate.js +16 -0
  86. package/dist/htest/core/smirnov.d.ts +20 -0
  87. package/dist/htest/core/smirnov.js +75 -0
  88. package/dist/htest/fisherTest.d.ts +12 -1
  89. package/dist/htest/fisherTest.js +187 -127
  90. package/dist/htest/groups.d.ts +20 -0
  91. package/dist/htest/groups.js +62 -0
  92. package/dist/htest/ksTest.d.ts +31 -0
  93. package/dist/htest/ksTest.js +106 -0
  94. package/dist/htest/mantelhaenTest.d.ts +26 -0
  95. package/dist/htest/mantelhaenTest.js +196 -0
  96. package/dist/htest/mcnemarTest.d.ts +26 -0
  97. package/dist/htest/mcnemarTest.js +99 -0
  98. package/dist/htest/onewayTest.d.ts +26 -0
  99. package/dist/htest/onewayTest.js +97 -0
  100. package/dist/htest/pairwise.d.ts +64 -0
  101. package/dist/htest/pairwise.js +152 -0
  102. package/dist/htest/poissonTest.d.ts +35 -0
  103. package/dist/htest/poissonTest.js +170 -0
  104. package/dist/htest/propTest.d.ts +37 -0
  105. package/dist/htest/propTest.js +164 -0
  106. package/dist/htest/rankTests.d.ts +52 -0
  107. package/dist/htest/rankTests.js +234 -0
  108. package/dist/htest/types.d.ts +2 -0
  109. package/dist/htest/types.js +6 -0
  110. package/dist/htest/varTest.d.ts +48 -0
  111. package/dist/htest/varTest.js +118 -0
  112. package/dist/htest/wilcoxTest.js +136 -174
  113. package/dist/index.d.ts +6 -50
  114. package/dist/index.js +8 -50
  115. package/dist/integrate/quadpack.d.ts +29 -0
  116. package/dist/integrate/quadpack.js +525 -0
  117. package/dist/internal/seq.d.ts +5 -0
  118. package/dist/internal/seq.js +14 -0
  119. package/dist/internal/uniroot.js +10 -71
  120. package/dist/linalg/lu.d.ts +45 -0
  121. package/dist/linalg/lu.js +88 -0
  122. package/dist/linalg/ops.d.ts +90 -0
  123. package/dist/linalg/ops.js +320 -0
  124. package/dist/linalg.js +2 -0
  125. package/dist/models/lm.d.ts +98 -0
  126. package/dist/models/lm.js +187 -0
  127. package/dist/numerics/deriv.d.ts +37 -0
  128. package/dist/numerics/deriv.js +150 -0
  129. package/dist/numerics/integrate.d.ts +91 -0
  130. package/dist/numerics/integrate.js +264 -0
  131. package/dist/numerics/interp.d.ts +103 -0
  132. package/dist/numerics/interp.js +581 -0
  133. package/dist/numerics/ode.d.ts +23 -0
  134. package/dist/numerics/ode.js +59 -0
  135. package/dist/numerics.js +2 -0
  136. package/dist/optim/localmin.d.ts +16 -0
  137. package/dist/optim/localmin.js +97 -0
  138. package/dist/random/beta.js +1 -1
  139. package/dist/random/binomial.js +1 -1
  140. package/dist/random/continuous.js +1 -1
  141. package/dist/random/extra.d.ts +33 -0
  142. package/dist/random/extra.js +62 -0
  143. package/dist/random/gamma.js +1 -1
  144. package/dist/random/hyper.js +1 -1
  145. package/dist/random/mt.js +0 -1
  146. package/dist/random/poisson.js +0 -1
  147. package/dist/random/r2dtable.d.ts +26 -0
  148. package/dist/random/r2dtable.js +153 -0
  149. package/dist/random/rank.js +1 -1
  150. package/dist/random/rng.js +1 -1
  151. package/dist/random/sample.js +1 -1
  152. package/dist/rstats.js +3 -2
  153. package/dist/special/besselIK.d.ts +38 -0
  154. package/dist/special/besselIK.js +315 -0
  155. package/dist/special/besselJY.d.ts +32 -0
  156. package/dist/special/besselJY.js +508 -0
  157. package/dist/special/besselSeries.d.ts +8 -0
  158. package/dist/special/besselSeries.js +24 -0
  159. package/dist/special/beta.js +22 -5
  160. package/dist/special/choose.d.ts +75 -0
  161. package/dist/special/choose.js +233 -0
  162. package/dist/special/erf.d.ts +28 -2
  163. package/dist/special/erf.js +37 -10
  164. package/dist/special/extra.d.ts +47 -0
  165. package/dist/special/extra.js +220 -0
  166. package/dist/special/igam.d.ts +4 -0
  167. package/dist/special/igam.js +57 -2
  168. package/dist/special/incbet.js +77 -22
  169. package/dist/special/lgammaDiff.d.ts +7 -0
  170. package/dist/special/lgammaDiff.js +16 -3
  171. package/dist/special/log1p.d.ts +53 -0
  172. package/dist/special/log1p.js +93 -0
  173. package/dist/special/psigamma.d.ts +48 -0
  174. package/dist/special/psigamma.js +318 -0
  175. package/dist/special/rCompatible.d.ts +8 -0
  176. package/dist/special/rCompatible.js +1 -0
  177. package/dist/special.js +2 -0
  178. package/dist/tests.js +3 -0
  179. package/package.json +26 -1
@@ -1,15 +1,19 @@
1
1
  // Fisher's exact test (R's fisher.test).
2
2
  //
3
- // 2x2 tables: with the margins fixed, the (1, 1) cell follows a noncentral hypergeometric distribution
4
- // (noncentrality = odds ratio; Fisher 1935). The conditional MLE is the noncentrality whose mean equals the
5
- // cell value; the confidence limits are the noncentralities at which a one-sided probability equals α. This construction
6
- // is the same as scipy.stats.contingency.odds_ratio (scipy/stats/_odds_ratio.py; SciPy commit a087e61,
7
- // BSD-3-Clause, see THIRD_PARTY_NOTICES.md). The root finding and defaults follow observed R output.
8
- // - Roots are found with uniroot (Brent, tolerance eps^0.25): if the noncentrality ψ is below 1, search
9
- // ψ ∈ [0, 1]; if above 1, search 1/ψ ∈ [ε, 1] (R's estimate and interval endpoints are 1e-6 to 1e-2 away
10
- // from the true roots, but this procedure reproduces them to the last few digits)
11
- // - The two-sided p-value is the sum of probabilities of tables whose probability is at most (1 + 1e-7) times the observed one
3
+ // 2x2 tables, written for rStats.js from the textbook construction and R's documented behaviour: with the margins
4
+ // fixed, the (1, 1) cell follows Fisher's noncentral hypergeometric distribution, the central hypergeometric density
5
+ // tilted by psi^x (noncentrality psi = odds ratio; Fisher 1935, Cornfield 1956). The conditional MLE is the psi whose
6
+ // mean equals the observed cell; the confidence limits are the psi at which a one-sided tail probability equals α.
7
+ // - Densities are formed in logs from the accurate log dhyper (evaluated every 16 points, exact ratios in
8
+ // between) and normalised with double-double sums, so the root
9
+ // search sees accurate function values; at psi = 1 the tails are the central hypergeometric distribution function
10
+ // - Roots are found with R's uniroot conventions (Brent, tolerance eps^0.25; src/internal/uniroot.ts): if the root
11
+ // lies below 1, on psi in [0, 1]; otherwise on s = 1/psi in [eps, 1]. R's estimate and limits are where this
12
+ // iteration stops (1e-6 to 1e-2 from the true roots), so the brackets and tolerance are part of the result
13
+ // - The two-sided p-value is the sum of probabilities of tables whose probability is at most (1 + 1e-7) times the
14
+ // observed one (R's convention); for or = 0 or Inf the distribution is a point mass at the end of the support
12
15
  // - Counts are made integer by rounding half to even (R rounds with a warning)
16
+ // The same distribution and root conventions are used for the exact Mantel-Haenszel test (src/htest/core/mantelhaen.ts).
13
17
  //
14
18
  // rxc tables: the probabilities of tables with fixed margins (multivariate hypergeometric) are
15
19
  // traversed via a network that fixes one column at a time (Mehta & Patel 1983, JASA 78, 427-434),
@@ -21,14 +25,20 @@
21
25
  // same probability are merged. For nodes with two columns left, a cumulative sum over the sorted
22
26
  // values of the remaining tables is prepared and each path is added via binary search.
23
27
  // Probabilities are held as double-double logarithms.
24
- // 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.
25
34
  import { dhyper1, phyper1 } from "../distributions/hypergeometric.js";
26
35
  import { roundHalfEven } from "../internal/integer.js";
36
+ import { logFactorialTable, rcont2 } from "../random/r2dtable.js";
37
+ import { lfactorial } from "../special/choose.js";
27
38
  import { uniroot } from "../internal/uniroot.js";
28
39
  import { ddAdd, ddLog, ddNeg, ddSub } from "../special/dd.js";
40
+ import { simulatedMethod } from "./core/simulate.js";
29
41
  import { matchAlternative } from "./types.js";
30
- /** Relative tolerance for treating a table as "equally probable as the observed table" in the two-sided p-value */
31
- const REL_ERR = 1 + 1e-7;
32
42
  /**
33
43
  * Fisher's exact test for count data. Equivalent to R's `fisher.test()`.
34
44
  *
@@ -39,7 +49,10 @@ const REL_ERR = 1 + 1e-7;
39
49
  * tolerance `1e-7`, as in R). Non-integer counts are rounded to the nearest integer
40
50
  * (ties to even), where R warns and rounds.
41
51
  *
42
- * 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.
43
56
  *
44
57
  * @param x Contingency table as an array of rows (at least 2 x 2).
45
58
  * @param options See {@link FisherTestOptions}.
@@ -71,100 +84,151 @@ export function fisherTest(x, options = {}) {
71
84
  if (nr === 2 && nc === 2)
72
85
  return fisher2x2(t, options, method);
73
86
  // For rxc, alternative etc. are not validated and are returned as given (as in R)
74
- return {
75
- method,
76
- alternative: (options.alternative ?? "two.sided"),
77
- pValue: fisherRxC(t),
78
- };
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)));
79
127
  }
80
128
  // ---- 2×2 ----
81
- /** Noncentral hypergeometric distribution (the (1, 1) cell of a 2x2 table) */
82
- class NoncentralHyper {
129
+ /** Relative slack for counting a table as "no more likely than the observed one" in the two-sided p-value */
130
+ const SLACK = 1 + 1e-7;
131
+ /** Spacing of the points at which the central log density is evaluated directly */
132
+ const ANCHOR = 16;
133
+ /** Double-double sum of v[from..to] (inclusive, clipped to the array) */
134
+ function accurateSum(v, from, to) {
135
+ let acc = [0, 0];
136
+ for (let i = Math.max(0, from); i <= Math.min(to, v.length - 1); i++)
137
+ if (v[i] !== 0)
138
+ acc = ddAdd(acc, [v[i], 0]);
139
+ return acc[0];
140
+ }
141
+ /**
142
+ * Fisher's noncentral hypergeometric distribution of the (1, 1) cell of a 2 x 2 table with margins fixed:
143
+ * P(X = i; psi) proportional to dhyper(i; m, n, k) psi^i on lo..hi
144
+ */
145
+ class OddsRatioDistribution {
83
146
  m;
84
147
  n;
85
148
  k;
86
149
  lo;
87
150
  hi;
88
- logdc;
151
+ /** log dhyper(i; m, n, k) for i = lo..hi */
152
+ logCentral;
89
153
  constructor(m, n, k) {
90
154
  this.m = m;
91
155
  this.n = n;
92
156
  this.k = k;
93
157
  this.lo = Math.max(0, k - n);
94
158
  this.hi = Math.min(k, m);
95
- // log P(X = x). Computed with dhyper every 64 points, linked in between by the ratio of neighbours
96
- // P(x + 1) / P(x) = (m - x)(k - x) / ((x + 1)(n - k + x + 1)) (the log-ratio error is about
97
- // 1 ulp, so 63 chained steps stay within 1e-14; calling dhyper at every point is slow for large tables)
98
- const len = this.hi - this.lo + 1;
99
- this.logdc = new Float64Array(len);
100
- for (let i = 0; i < len; i++) {
101
- const x = this.lo + i;
102
- if (i % 64 === 0)
103
- this.logdc[i] = dhyper1(x, m, n, k, true);
104
- else {
105
- const y = x - 1;
106
- this.logdc[i] = this.logdc[i - 1] + Math.log(((m - y) * (k - y)) / ((y + 1) * (n - k + y + 1)));
159
+ this.logCentral = new Float64Array(this.hi - this.lo + 1);
160
+ // dhyper1 at every ANCHOR-th point; in between, multiply by the exact ratio
161
+ // c(i+1)/c(i) = (m - i)(k - i) / ((i + 1)(n - k + i + 1)) (the product stays within a few ulps)
162
+ let anchor = 0;
163
+ let prod = 1;
164
+ for (let i = this.lo; i <= this.hi; i++) {
165
+ const j = i - this.lo;
166
+ if (j % ANCHOR === 0 || !(prod > 0 && prod < Infinity)) {
167
+ anchor = dhyper1(i, m, n, k, true);
168
+ prod = 1;
169
+ this.logCentral[j] = anchor;
107
170
  }
171
+ else
172
+ this.logCentral[j] = anchor + Math.log(prod);
173
+ prod *= ((m - i) * (k - i)) / ((i + 1) * (n - k + i + 1));
108
174
  }
109
175
  }
110
- /** Probabilities (in support order). The noncentrality ncp satisfies 0 < ncp < ∞ */
111
- density(ncp) {
112
- const lc = Math.log(ncp);
113
- const d = new Float64Array(this.logdc.length);
114
- let max = -Infinity;
115
- for (let i = 0; i < d.length; i++) {
116
- d[i] = this.logdc[i] + lc * (this.lo + i);
117
- if (d[i] > max)
118
- max = d[i];
176
+ /** Normalised density on lo..hi for 0 < psi < Infinity */
177
+ density(psi) {
178
+ const len = this.logCentral.length;
179
+ const lp = Math.log(psi);
180
+ const out = new Float64Array(len);
181
+ let top = -Infinity;
182
+ for (let j = 0; j < len; j++) {
183
+ const v = this.logCentral[j] + (this.lo + j) * lp;
184
+ out[j] = v;
185
+ if (v > top)
186
+ top = v;
119
187
  }
120
- // Skip exp where exp(d - max) underflows to 0 (R also gives 0 there)
121
- for (let i = 0; i < d.length; i++)
122
- d[i] = d[i] - max < -760 ? 0 : Math.exp(d[i] - max);
123
- const s = sumDD(d, 0, d.length);
124
- for (let i = 0; i < d.length; i++)
125
- d[i] = d[i] / s;
126
- return d;
188
+ // exp underflows to exactly 0 below -746; skipping those terms leaves every sum unchanged
189
+ for (let j = 0; j < len; j++) {
190
+ const e = out[j] - top;
191
+ out[j] = e < -746 ? 0 : Math.exp(e);
192
+ }
193
+ const total = accurateSum(out, 0, len - 1);
194
+ for (let j = 0; j < len; j++)
195
+ if (out[j] !== 0)
196
+ out[j] = out[j] / total;
197
+ return out;
127
198
  }
128
- mean(ncp) {
129
- if (ncp === 0)
199
+ /** E[X; psi] */
200
+ mean(psi) {
201
+ if (psi === 0)
130
202
  return this.lo;
131
- if (ncp === Infinity)
203
+ if (psi === Infinity)
132
204
  return this.hi;
133
- const d = this.density(ncp);
134
- let s = [0, 0];
135
- for (let i = 0; i < d.length; i++)
136
- s = ddAdd(s, [(this.lo + i) * d[i], 0]);
137
- return s[0];
205
+ const d = this.density(psi);
206
+ let acc = [0, 0];
207
+ for (let j = 0; j < d.length; j++)
208
+ if (d[j] !== 0)
209
+ acc = ddAdd(acc, [(this.lo + j) * d[j], 0]);
210
+ return acc[0];
138
211
  }
139
- /** P(X <= q) (P(X >= q) if upper) */
140
- cdf(q, ncp, upper) {
141
- if (ncp === 1) {
212
+ /** P(X <= q; psi), or P(X >= q; psi) when upper */
213
+ tail(q, psi, upper) {
214
+ if (psi === 1) {
142
215
  return upper ? phyper1(q - 1, this.m, this.n, this.k, false, false) : phyper1(q, this.m, this.n, this.k, true, false);
143
216
  }
144
- if (ncp === 0)
145
- return Number(upper ? q <= this.lo : q >= this.lo);
146
- if (ncp === Infinity)
147
- return Number(upper ? q <= this.hi : q >= this.hi);
148
- const d = this.density(ncp);
149
- const i = q - this.lo;
150
- return upper ? sumDD(d, i, d.length) : sumDD(d, 0, i + 1);
217
+ if (psi === 0 || psi === Infinity) {
218
+ const at = psi === 0 ? this.lo : this.hi;
219
+ return (upper ? q <= at : q >= at) ? 1 : 0;
220
+ }
221
+ const d = this.density(psi);
222
+ const j = q - this.lo;
223
+ return upper ? accurateSum(d, j, d.length - 1) : accurateSum(d, 0, j);
151
224
  }
152
225
  }
153
- function sumDD(d, from, to) {
154
- let s = [0, 0];
155
- for (let i = Math.max(0, from); i < Math.min(to, d.length); i++)
156
- s = ddAdd(s, [d[i], 0]);
157
- return s[0];
158
- }
159
226
  /**
160
- * Root of the increasing function f(ψ) = 0. If f(1) < 0 there is no root in ψ ∈ [0, 1], so search 1/ψ ∈ [ε, 1]
161
- * (the caller chooses the interval from the sign of f(1))
227
+ * Root of f, monotone in the odds ratio psi: searched for as psi in [0, 1] when it lies below 1, otherwise as
228
+ * s = 1/psi in [eps, 1] (uniroot with its default tolerance in both cases)
162
229
  */
163
- function rootBelowOne(f) {
164
- return uniroot(f, 0, 1);
165
- }
166
- function rootAboveOne(f) {
167
- return 1 / uniroot((t) => f(1 / t), Number.EPSILON, 1);
230
+ function oddsRatioRoot(f, belowOne) {
231
+ return belowOne ? uniroot(f, 0, 1) : 1 / uniroot((s) => f(1 / s), Number.EPSILON, 1);
168
232
  }
169
233
  function fisher2x2(t, options, method) {
170
234
  const alternative = matchAlternative(options.alternative);
@@ -174,39 +238,36 @@ function fisher2x2(t, options, method) {
174
238
  const confLevel = options.confLevel ?? 0.95;
175
239
  if (!(confLevel > 0 && confLevel < 1))
176
240
  throw new RangeError("confLevel must be a single number between 0 and 1");
177
- const x = t[0][0];
178
- const m = x + t[1][0];
179
- const n = t[0][1] + t[1][1];
180
- const k = x + t[0][1];
181
- const h = new NoncentralHyper(m, n, k);
241
+ const [[a, b], [c, d]] = t;
242
+ const x = a;
243
+ const dist = new OddsRatioDistribution(a + c, b + d, a + b);
244
+ const { lo, hi } = dist;
182
245
  let pValue;
183
246
  if (alternative === "less")
184
- pValue = h.cdf(x, or, false);
247
+ pValue = dist.tail(x, or, false);
185
248
  else if (alternative === "greater")
186
- pValue = h.cdf(x, or, true);
249
+ pValue = dist.tail(x, or, true);
187
250
  else if (or === 0)
188
- pValue = Number(x === h.lo);
251
+ pValue = x === lo ? 1 : 0;
189
252
  else if (or === Infinity)
190
- pValue = Number(x === h.hi);
253
+ pValue = x === hi ? 1 : 0;
191
254
  else {
192
- const d = h.density(or);
193
- const limit = d[x - h.lo] * REL_ERR;
194
- let s = [0, 0];
195
- for (const v of d)
196
- if (v <= limit)
197
- s = ddAdd(s, [v, 0]);
198
- pValue = s[0];
255
+ const dens = dist.density(or);
256
+ const cut = dens[x - lo] * SLACK;
257
+ let acc = [0, 0];
258
+ for (const v of dens)
259
+ if (v <= cut)
260
+ acc = ddAdd(acc, [v, 0]);
261
+ pValue = acc[0];
199
262
  }
200
- // Conditional MLE: the noncentrality whose mean is x
201
263
  let estimate;
202
- if (x === h.lo)
264
+ if (x === lo)
203
265
  estimate = 0;
204
- else if (x === h.hi)
266
+ else if (x === hi)
205
267
  estimate = Infinity;
206
268
  else {
207
- const mu = h.mean(1);
208
- const f = (psi) => h.mean(psi) - x;
209
- estimate = mu > x ? rootBelowOne(f) : mu < x ? rootAboveOne(f) : 1;
269
+ const mu1 = dist.mean(1);
270
+ estimate = mu1 === x ? 1 : oddsRatioRoot((psi) => dist.mean(psi) - x, mu1 > x);
210
271
  }
211
272
  const result = {
212
273
  method,
@@ -217,32 +278,31 @@ function fisher2x2(t, options, method) {
217
278
  nullValue: or,
218
279
  nullValueName: "odds ratio",
219
280
  };
220
- if (options.confInt ?? true) {
221
- // Upper limit: P(X <= x; ψ) = α (P is decreasing in ψ)
222
- const upper = (alpha) => {
223
- if (x === h.hi)
224
- return Infinity;
225
- const p = h.cdf(x, 1, false);
226
- const f = (psi) => alpha - h.cdf(x, psi, false);
227
- return p < alpha ? rootBelowOne(f) : p > alpha ? rootAboveOne(f) : 1;
228
- };
229
- // Lower limit: P(X >= x; ψ) = α (P is increasing in ψ)
230
- const lower = (alpha) => {
231
- if (x === h.lo)
232
- return 0;
233
- const p = h.cdf(x, 1, true);
234
- const f = (psi) => h.cdf(x, psi, true) - alpha;
235
- return p > alpha ? rootBelowOne(f) : p < alpha ? rootAboveOne(f) : 1;
236
- };
237
- result.confInt =
238
- alternative === "less"
239
- ? [0, upper(1 - confLevel)]
240
- : alternative === "greater"
241
- ? [lower(1 - confLevel), Infinity]
242
- : [lower((1 - confLevel) / 2), upper((1 - confLevel) / 2)];
243
- result.confLevel = confLevel;
281
+ if (!(options.confInt ?? true))
282
+ return result;
283
+ // P(X <= x; psi) decreases and P(X >= x; psi) increases in psi
284
+ const upperLimit = (level) => {
285
+ if (x === hi)
286
+ return Infinity;
287
+ const p1 = dist.tail(x, 1, false);
288
+ return p1 === level ? 1 : oddsRatioRoot((psi) => dist.tail(x, psi, false) - level, p1 < level);
289
+ };
290
+ const lowerLimit = (level) => {
291
+ if (x === lo)
292
+ return 0;
293
+ const p1 = dist.tail(x, 1, true);
294
+ return p1 === level ? 1 : oddsRatioRoot((psi) => dist.tail(x, psi, true) - level, p1 > level);
295
+ };
296
+ let confInt;
297
+ if (alternative === "less")
298
+ confInt = [0, upperLimit(1 - confLevel)];
299
+ else if (alternative === "greater")
300
+ confInt = [lowerLimit(1 - confLevel), Infinity];
301
+ else {
302
+ const alpha = (1 - confLevel) / 2;
303
+ confInt = [lowerLimit(alpha), upperLimit(alpha)];
244
304
  }
245
- return result;
305
+ return { ...result, confInt, confLevel };
246
306
  }
247
307
  // ---- r×c ----
248
308
  /** Table of log k! in double-double (extended as needed) */
@@ -0,0 +1,20 @@
1
+ import type { Sample } from "./types.js";
2
+ /** Group label: a number or a string. */
3
+ export type GroupLabel = number | string;
4
+ /** Groups with their labels: the sorted labels (x, g form) or the 1-based positions in the list (list form) */
5
+ export interface LabelledGroups {
6
+ labels: string[];
7
+ groups: number[][];
8
+ }
9
+ /**
10
+ * Normalise the two input forms to groups with NaN removed, each with its label. In the x, g form a label whose
11
+ * values are all missing has no group (as R drops an unused factor level). In the list form a group left empty is
12
+ * dropped, or rejected with R's message when `emptyGroups` is `"error"` (kruskal.test, fligner.test).
13
+ */
14
+ export declare function labelledGroups(x: Sample | readonly Sample[], g?: readonly GroupLabel[], emptyGroups?: "drop" | "error"): LabelledGroups;
15
+ /** Normalise the two input forms to an array of non-empty groups with NaN removed (see {@link labelledGroups}) */
16
+ export declare function toGroups(x: Sample | readonly Sample[], g?: readonly GroupLabel[], emptyGroups?: "drop" | "error"): number[][];
17
+ /** Median (the mean of the two middle values for an even count) */
18
+ export declare function median(x: readonly number[]): number;
19
+ /** Rows of a blocks x treatments table with any NaN dropped (R's complete.cases) */
20
+ export declare function completeRows(y: readonly (readonly number[])[]): number[][];
@@ -0,0 +1,62 @@
1
+ // Grouped data for the k-sample tests: either an array of samples (R's list form) or a sample with a parallel array
2
+ // of group labels (R's x, g form). Pairs with a missing value or label are dropped, and groups are kept in order
3
+ // of the sorted labels (as R orders factor levels).
4
+ /**
5
+ * Normalise the two input forms to groups with NaN removed, each with its label. In the x, g form a label whose
6
+ * values are all missing has no group (as R drops an unused factor level). In the list form a group left empty is
7
+ * dropped, or rejected with R's message when `emptyGroups` is `"error"` (kruskal.test, fligner.test).
8
+ */
9
+ export function labelledGroups(x, g, emptyGroups = "drop") {
10
+ if (g === undefined) {
11
+ const list = x;
12
+ if (list.length > 0 && typeof list[0] === "number")
13
+ throw new TypeError("'g' is required when 'x' is a single sample");
14
+ const all = list.map((s) => Array.from(s).filter((v) => !Number.isNaN(v)));
15
+ if (emptyGroups === "error" && all.some((s) => s.length === 0))
16
+ throw new RangeError("all groups must contain data");
17
+ const labels = [];
18
+ const groups = [];
19
+ all.forEach((s, i) => {
20
+ if (s.length === 0)
21
+ return;
22
+ labels.push(String(i + 1));
23
+ groups.push(s);
24
+ });
25
+ return { labels, groups };
26
+ }
27
+ const xs = Array.from(x);
28
+ if (xs.length !== g.length)
29
+ throw new RangeError("'x' and 'g' must have the same length");
30
+ const byLabel = new Map();
31
+ for (let i = 0; i < xs.length; i++) {
32
+ const v = xs[i];
33
+ const l = g[i];
34
+ if (Number.isNaN(v) || (typeof l === "number" && Number.isNaN(l)))
35
+ continue;
36
+ let arr = byLabel.get(l);
37
+ if (arr === undefined)
38
+ byLabel.set(l, (arr = []));
39
+ arr.push(v);
40
+ }
41
+ const labels = Array.from(byLabel.keys()).sort((a, b) => typeof a === "number" && typeof b === "number" ? a - b : String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0);
42
+ return { labels: labels.map(String), groups: labels.map((l) => byLabel.get(l)) };
43
+ }
44
+ /** Normalise the two input forms to an array of non-empty groups with NaN removed (see {@link labelledGroups}) */
45
+ export function toGroups(x, g, emptyGroups = "drop") {
46
+ return labelledGroups(x, g, emptyGroups).groups;
47
+ }
48
+ /** Median (the mean of the two middle values for an even count) */
49
+ export function median(x) {
50
+ const s = [...x].sort((a, b) => a - b);
51
+ const n = s.length;
52
+ return n % 2 === 1 ? s[(n - 1) / 2] : (s[n / 2 - 1] + s[n / 2]) / 2;
53
+ }
54
+ /** Rows of a blocks x treatments table with any NaN dropped (R's complete.cases) */
55
+ export function completeRows(y) {
56
+ if (y.length === 0)
57
+ throw new RangeError("'y' must have at least one row");
58
+ const k = y[0].length;
59
+ if (y.some((r) => r.length !== k))
60
+ throw new RangeError("all rows of 'y' must have the same length");
61
+ return y.filter((r) => r.every((v) => !Number.isNaN(v))).map((r) => Array.from(r));
62
+ }
@@ -0,0 +1,31 @@
1
+ import { type Alternative, type HTest, type Sample } from "./types.js";
2
+ /** Options for {@link ksTest}. */
3
+ export interface KsTestOptions {
4
+ /**
5
+ * Alternative hypothesis (unambiguous abbreviations accepted). `"greater"`: the distribution function of `x` lies
6
+ * above that of `y` (statistic D^+); `"less"`: below (D^-). Default `"two.sided"`.
7
+ */
8
+ alternative?: Alternative | "two" | "l" | "g";
9
+ /**
10
+ * Exact p-value. Default: exact for one sample of fewer than 100 values without ties, and for two samples with
11
+ * m n < 10000.
12
+ */
13
+ exact?: boolean;
14
+ }
15
+ /**
16
+ * Result of {@link ksTest}. As in R, `alternative` describes the hypothesis in words ("two-sided", "the CDF of x lies
17
+ * above the null hypothesis", ...), and `exact` tells whether the p-value is exact.
18
+ */
19
+ export interface KsTestResult extends Omit<HTest, "alternative"> {
20
+ alternative: string;
21
+ exact: boolean;
22
+ }
23
+ /**
24
+ * Kolmogorov-Smirnov test. Equivalent to R's `ks.test()`, with a distribution function given as a function (for
25
+ * example `(q) => pnorm(q)`) or a second sample. `NaN` values are dropped.
26
+ *
27
+ * @param x Sample.
28
+ * @param y A continuous distribution function, or a second sample.
29
+ * @param options See {@link KsTestOptions}.
30
+ */
31
+ export declare function ksTest(x: Sample, y: Sample | ((q: number) => number), options?: KsTestOptions): KsTestResult;
@@ -0,0 +1,106 @@
1
+ // Kolmogorov-Smirnov tests (R's ks.test): one sample against a continuous distribution function, or two samples.
2
+ //
3
+ // Written for rStats.js (no ported code); the distributions are in src/htest/core (kolmogorov.ts, smirnov.ts).
4
+ // One sample: D+ = max(i/n - F(x_(i))), D- = max(F(x_(i)) - (i - 1)/n); exact p-values (by default for n < 100
5
+ // without ties) from Marsaglia, Tsang and Wang (two-sided) and Birnbaum and Tingey (one-sided), asymptotic ones from
6
+ // Kolmogorov's limit and exp(-2 n D^2). Two samples: the largest differences of the empirical distribution functions,
7
+ // taken only where the pooled sorted values change; exact p-values (by default for m n < 10000, with or without ties)
8
+ // by counting lattice paths, asymptotic ones as for one sample with n replaced by m n / (m + n).
9
+ import { pkolmogorovExact, pkolmogorovLimit, pkolmogorovOneSidedUpper } from "./core/kolmogorov.js";
10
+ import { psmirnovUpper } from "./core/smirnov.js";
11
+ import { matchAlternative } from "./types.js";
12
+ function describe(alternative, oneSample) {
13
+ if (alternative === "two.sided")
14
+ return "two-sided";
15
+ const where = alternative === "less" ? "below" : "above";
16
+ return `the CDF of x lies ${where} ${oneSample ? "the null hypothesis" : "that of y"}`;
17
+ }
18
+ /**
19
+ * Kolmogorov-Smirnov test. Equivalent to R's `ks.test()`, with a distribution function given as a function (for
20
+ * example `(q) => pnorm(q)`) or a second sample. `NaN` values are dropped.
21
+ *
22
+ * @param x Sample.
23
+ * @param y A continuous distribution function, or a second sample.
24
+ * @param options See {@link KsTestOptions}.
25
+ */
26
+ export function ksTest(x, y, options = {}) {
27
+ const xs = Array.from(x)
28
+ .filter((v) => !Number.isNaN(v))
29
+ .sort((a, b) => a - b);
30
+ const n = xs.length;
31
+ if (n < 1)
32
+ throw new RangeError("not enough 'x' data");
33
+ const alternative = matchAlternative(options.alternative);
34
+ const statisticName = alternative === "two.sided" ? "D" : alternative === "greater" ? "D^+" : "D^-";
35
+ if (typeof y === "function") {
36
+ let dplus = -Infinity;
37
+ let dminus = -Infinity;
38
+ for (let i = 0; i < n; i++) {
39
+ const f = y(xs[i]);
40
+ dplus = Math.max(dplus, (i + 1) / n - f);
41
+ dminus = Math.max(dminus, f - i / n);
42
+ }
43
+ const statistic = alternative === "two.sided" ? Math.max(dplus, dminus) : alternative === "greater" ? dplus : dminus;
44
+ const ties = new Set(xs).size < n;
45
+ const exact = options.exact ?? (n < 100 && !ties);
46
+ let pValue;
47
+ if (alternative === "two.sided") {
48
+ pValue = exact ? 1 - pkolmogorovExact(n, statistic) : pkolmogorovLimit(Math.sqrt(n) * statistic, false);
49
+ }
50
+ else {
51
+ pValue = exact ? pkolmogorovOneSidedUpper(n, statistic) : Math.exp(-2 * n * statistic * statistic);
52
+ }
53
+ return {
54
+ method: `${exact ? "Exact" : "Asymptotic"} one-sample Kolmogorov-Smirnov test`,
55
+ alternative: describe(alternative, true),
56
+ exact,
57
+ statistic,
58
+ statisticName,
59
+ pValue: Math.min(1, Math.max(0, pValue)),
60
+ };
61
+ }
62
+ const ys = Array.from(y).filter((v) => !Number.isNaN(v));
63
+ const m = ys.length;
64
+ if (m < 1)
65
+ throw new RangeError("not enough 'y' data");
66
+ // walk the pooled sorted values, recording F_x - F_y after each run of equal values
67
+ const pooled = xs.map((v) => [v, 0]).concat(ys.map((v) => [v, 1]));
68
+ pooled.sort((a, b) => a[0] - b[0]);
69
+ let fx = 0;
70
+ let fy = 0;
71
+ let dplus = 0;
72
+ let dminus = 0;
73
+ for (let i = 0; i < pooled.length; i++) {
74
+ if (pooled[i][1] === 0)
75
+ fx++;
76
+ else
77
+ fy++;
78
+ if (i + 1 < pooled.length && pooled[i + 1][0] === pooled[i][0])
79
+ continue;
80
+ const diff = fx / n - fy / m;
81
+ dplus = Math.max(dplus, diff);
82
+ dminus = Math.max(dminus, -diff);
83
+ }
84
+ const statistic = alternative === "two.sided" ? Math.max(dplus, dminus) : alternative === "greater" ? dplus : dminus;
85
+ const ties = new Set(pooled.map((p) => p[0])).size < pooled.length;
86
+ const exact = options.exact ?? n * m < 10000;
87
+ let pValue;
88
+ if (exact) {
89
+ pValue = psmirnovUpper(statistic, n, m, ties ? { alternative, z: pooled.map((p) => p[0]) } : { alternative });
90
+ }
91
+ else {
92
+ const en = (n * m) / (n + m);
93
+ pValue =
94
+ alternative === "two.sided"
95
+ ? pkolmogorovLimit(Math.sqrt(en) * statistic, false)
96
+ : Math.exp(-2 * en * statistic * statistic);
97
+ }
98
+ return {
99
+ method: `${exact ? "Exact" : "Asymptotic"} two-sample Kolmogorov-Smirnov test`,
100
+ alternative: describe(alternative, false),
101
+ exact,
102
+ statistic,
103
+ statisticName,
104
+ pValue: Math.min(1, Math.max(0, pValue)),
105
+ };
106
+ }