@numero-uno-jpn/rstats 0.15.2 → 0.16.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 (297) hide show
  1. package/CHANGELOG.md +280 -0
  2. package/README.ja.md +40 -33
  3. package/README.md +36 -28
  4. package/dist/chunks/chunk-2D2IQWUQ.js +2 -0
  5. package/dist/chunks/chunk-5UQCRBAG.js +2 -0
  6. package/dist/chunks/chunk-6CSTWA5E.js +2 -0
  7. package/dist/chunks/chunk-72Y3HZID.js +2 -0
  8. package/dist/chunks/chunk-BG2KLEHM.js +2 -0
  9. package/dist/chunks/chunk-CMEKBNHQ.js +2 -0
  10. package/dist/chunks/chunk-FLJNSXSW.js +2 -0
  11. package/dist/chunks/chunk-GM53LWSR.js +2 -0
  12. package/dist/chunks/chunk-JBCA56ZS.js +3 -0
  13. package/dist/chunks/chunk-K3RJAD2T.js +2 -0
  14. package/dist/chunks/chunk-KAZRWIB5.js +2 -0
  15. package/dist/chunks/chunk-KBVVIMXX.js +3 -0
  16. package/dist/chunks/chunk-N3SIFCZX.js +2 -0
  17. package/dist/chunks/chunk-QNNL7AZ3.js +2 -0
  18. package/dist/chunks/chunk-SC6CV4Z3.js +2 -0
  19. package/dist/chunks/chunk-SYWOBOTR.js +2 -0
  20. package/dist/chunks/chunk-URIO5LY5.js +2 -0
  21. package/dist/chunks/chunk-VTUGG2SV.js +2 -0
  22. package/dist/chunks/chunk-W26LRYOJ.js +2 -0
  23. package/dist/chunks/chunk-XHETEYVC.js +2 -0
  24. package/dist/chunks/{chunk-PWVQVJTP.js → chunk-YRZWONZB.js} +1 -1
  25. package/dist/chunks/chunk-ZGABZMWX.js +2 -0
  26. package/dist/data/grouping.js +20 -5
  27. package/dist/descriptive/basic.js +90 -8
  28. package/dist/descriptive/cov.js +12 -4
  29. package/dist/descriptive/dataFrames.d.ts +4 -2
  30. package/dist/descriptive/dataFrames.js +56 -18
  31. package/dist/descriptive/factanal.js +16 -7
  32. package/dist/descriptive/hist.d.ts +8 -5
  33. package/dist/descriptive/hist.js +71 -31
  34. package/dist/descriptive/missing.js +3 -1
  35. package/dist/descriptive/moments.js +72 -19
  36. package/dist/descriptive/omega.d.ts +1 -1
  37. package/dist/descriptive/omega.js +68 -9
  38. package/dist/descriptive/pivot.d.ts +21 -9
  39. package/dist/descriptive/pivot.js +161 -35
  40. package/dist/descriptive/quantile.js +2 -1
  41. package/dist/descriptive/rank.js +4 -1
  42. package/dist/descriptive/table.d.ts +3 -2
  43. package/dist/descriptive/table.js +24 -9
  44. package/dist/descriptive.js +2 -2
  45. package/dist/distributions/arcsine.js +19 -2
  46. package/dist/distributions/beta.js +35 -5
  47. package/dist/distributions/binomial.js +37 -14
  48. package/dist/distributions/bvnorm.js +11 -2
  49. package/dist/distributions/cauchy.js +87 -8
  50. package/dist/distributions/chisq.js +7 -3
  51. package/dist/distributions/exponential.js +11 -1
  52. package/dist/distributions/f.js +73 -22
  53. package/dist/distributions/gamma.js +61 -6
  54. package/dist/distributions/geometric.js +53 -14
  55. package/dist/distributions/hypergeometric.d.ts +5 -1
  56. package/dist/distributions/hypergeometric.js +93 -6
  57. package/dist/distributions/invgamma.js +6 -1
  58. package/dist/distributions/kumaraswamy.js +22 -4
  59. package/dist/distributions/laplace.js +31 -7
  60. package/dist/distributions/logistic.js +11 -2
  61. package/dist/distributions/lognormal.js +20 -3
  62. package/dist/distributions/multinomial.js +54 -11
  63. package/dist/distributions/nbeta.js +128 -35
  64. package/dist/distributions/nchisq.js +85 -14
  65. package/dist/distributions/negbinomial.js +100 -18
  66. package/dist/distributions/normal.js +35 -5
  67. package/dist/distributions/nt.d.ts +28 -3
  68. package/dist/distributions/nt.js +536 -35
  69. package/dist/distributions/pareto.js +9 -1
  70. package/dist/distributions/poisson.js +28 -3
  71. package/dist/distributions/signrank.js +7 -4
  72. package/dist/distributions/summary.js +450 -60
  73. package/dist/distributions/t.js +55 -3
  74. package/dist/distributions/triangular.js +45 -13
  75. package/dist/distributions/tukey.js +21 -2
  76. package/dist/distributions/uniform.js +2 -0
  77. package/dist/distributions/weibull.js +33 -3
  78. package/dist/distributions/wilcox.d.ts +9 -3
  79. package/dist/distributions/wilcox.js +155 -26
  80. package/dist/distributions.js +2 -2
  81. package/dist/htest/agreement.d.ts +3 -2
  82. package/dist/htest/agreement.js +76 -14
  83. package/dist/htest/ansariTest.d.ts +6 -1
  84. package/dist/htest/ansariTest.js +75 -8
  85. package/dist/htest/aov.d.ts +1 -1
  86. package/dist/htest/aov.js +48 -34
  87. package/dist/htest/binomTest.d.ts +5 -0
  88. package/dist/htest/binomTest.js +41 -17
  89. package/dist/htest/brunnerMunzelTest.d.ts +4 -3
  90. package/dist/htest/brunnerMunzelTest.js +7 -5
  91. package/dist/htest/chisqTest.d.ts +2 -1
  92. package/dist/htest/chisqTest.js +130 -43
  93. package/dist/htest/cor.d.ts +2 -1
  94. package/dist/htest/cor.js +17 -19
  95. package/dist/htest/core/ansari.d.ts +9 -0
  96. package/dist/htest/core/ansari.js +21 -1
  97. package/dist/htest/core/kolmogorov.d.ts +25 -0
  98. package/dist/htest/core/kolmogorov.js +123 -0
  99. package/dist/htest/core/mantelhaen.js +6 -4
  100. package/dist/htest/core/shapiro.d.ts +1 -1
  101. package/dist/htest/core/shapiro.js +5 -1
  102. package/dist/htest/dunnett.js +14 -5
  103. package/dist/htest/effectSize.d.ts +2 -0
  104. package/dist/htest/effectSize.js +91 -29
  105. package/dist/htest/fisherTest.d.ts +2 -2
  106. package/dist/htest/fisherTest.js +36 -18
  107. package/dist/htest/groups.d.ts +7 -0
  108. package/dist/htest/groups.js +21 -4
  109. package/dist/htest/ksTest.d.ts +3 -1
  110. package/dist/htest/ksTest.js +23 -2
  111. package/dist/htest/leveneTest.js +19 -3
  112. package/dist/htest/mantelhaenTest.js +125 -25
  113. package/dist/htest/mcnemarTest.js +32 -11
  114. package/dist/htest/multipleComparisons.d.ts +8 -1
  115. package/dist/htest/multipleComparisons.js +44 -21
  116. package/dist/htest/normalityTests.js +44 -10
  117. package/dist/htest/onewayTest.js +96 -5
  118. package/dist/htest/pAdjust.d.ts +3 -2
  119. package/dist/htest/pAdjust.js +38 -6
  120. package/dist/htest/pairwise.d.ts +1 -1
  121. package/dist/htest/pairwise.js +17 -15
  122. package/dist/htest/poissonTest.d.ts +1 -1
  123. package/dist/htest/poissonTest.js +111 -59
  124. package/dist/htest/polycor.js +27 -7
  125. package/dist/htest/power.d.ts +11 -1
  126. package/dist/htest/power.js +112 -8
  127. package/dist/htest/propTest.js +21 -4
  128. package/dist/htest/pwr.js +121 -24
  129. package/dist/htest/rankTests.js +29 -5
  130. package/dist/htest/tTest.js +44 -21
  131. package/dist/htest/trendTests.d.ts +7 -3
  132. package/dist/htest/trendTests.js +114 -20
  133. package/dist/htest/types.d.ts +5 -0
  134. package/dist/htest/types.js +7 -0
  135. package/dist/htest/varTest.js +45 -14
  136. package/dist/htest/wilcoxTest.js +114 -21
  137. package/dist/integrate/quadpack.js +27 -5
  138. package/dist/internal/covmat.d.ts +5 -0
  139. package/dist/internal/covmat.js +20 -0
  140. package/dist/internal/ddexp.d.ts +23 -1
  141. package/dist/internal/ddexp.js +86 -6
  142. package/dist/internal/discrete.d.ts +14 -0
  143. package/dist/internal/discrete.js +78 -5
  144. package/dist/internal/extremes.d.ts +9 -0
  145. package/dist/internal/extremes.js +24 -0
  146. package/dist/internal/fround.js +13 -4
  147. package/dist/internal/integer.d.ts +9 -0
  148. package/dist/internal/integer.js +12 -0
  149. package/dist/internal/invert.d.ts +5 -0
  150. package/dist/internal/invert.js +25 -7
  151. package/dist/internal/noncentral.d.ts +7 -0
  152. package/dist/internal/noncentral.js +9 -0
  153. package/dist/internal/poissonMixture.js +29 -6
  154. package/dist/internal/scaledInverse.d.ts +10 -0
  155. package/dist/internal/scaledInverse.js +22 -0
  156. package/dist/internal/seq.js +15 -2
  157. package/dist/internal/summary.d.ts +90 -0
  158. package/dist/internal/summary.js +458 -39
  159. package/dist/internal/uniroot.d.ts +7 -0
  160. package/dist/internal/uniroot.js +28 -3
  161. package/dist/linalg/basic.d.ts +3 -1
  162. package/dist/linalg/basic.js +51 -7
  163. package/dist/linalg/chol.js +4 -1
  164. package/dist/linalg/dot.d.ts +29 -0
  165. package/dist/linalg/dot.js +132 -0
  166. package/dist/linalg/eigen.d.ts +6 -1
  167. package/dist/linalg/eigen.js +71 -14
  168. package/dist/linalg/expm.d.ts +3 -2
  169. package/dist/linalg/expm.js +109 -15
  170. package/dist/linalg/kappa.js +58 -10
  171. package/dist/linalg/lu.d.ts +2 -1
  172. package/dist/linalg/lu.js +35 -5
  173. package/dist/linalg/matrix.d.ts +14 -0
  174. package/dist/linalg/matrix.js +24 -0
  175. package/dist/linalg/ops.js +60 -13
  176. package/dist/linalg/qr.d.ts +2 -1
  177. package/dist/linalg/qr.js +91 -23
  178. package/dist/linalg/schur.js +11 -3
  179. package/dist/linalg/solve.d.ts +6 -1
  180. package/dist/linalg/solve.js +147 -26
  181. package/dist/linalg/svd.d.ts +9 -2
  182. package/dist/linalg/svd.js +29 -11
  183. package/dist/linalg.js +2 -2
  184. package/dist/mixed.js +4 -4
  185. package/dist/models/anovaSequential.d.ts +16 -1
  186. package/dist/models/anovaSequential.js +124 -25
  187. package/dist/models/aovEz.js +140 -30
  188. package/dist/models/aovStrata.js +55 -22
  189. package/dist/models/carAnova.d.ts +1 -1
  190. package/dist/models/carAnova.js +83 -32
  191. package/dist/models/coxph.js +148 -66
  192. package/dist/models/estimable.d.ts +15 -0
  193. package/dist/models/estimable.js +68 -0
  194. package/dist/models/formula.d.ts +1 -1
  195. package/dist/models/formula.js +26 -8
  196. package/dist/models/glm.d.ts +35 -5
  197. package/dist/models/glm.js +398 -55
  198. package/dist/models/glmAnova.js +84 -13
  199. package/dist/models/glmConfint.d.ts +1 -1
  200. package/dist/models/glmConfint.js +115 -27
  201. package/dist/models/glmFamily.d.ts +10 -0
  202. package/dist/models/glmFamily.js +244 -40
  203. package/dist/models/lm.d.ts +12 -1
  204. package/dist/models/lm.js +235 -36
  205. package/dist/models/lmer.d.ts +20 -1
  206. package/dist/models/lmer.js +109 -27
  207. package/dist/models/lmerAnova.js +37 -4
  208. package/dist/models/lmerHypotheses.d.ts +6 -2
  209. package/dist/models/lmerHypotheses.js +14 -2
  210. package/dist/models/lmerTest.d.ts +9 -2
  211. package/dist/models/lmerTest.js +64 -19
  212. package/dist/models/mauchly.d.ts +4 -1
  213. package/dist/models/mauchly.js +34 -13
  214. package/dist/models/mixedStructure.js +6 -0
  215. package/dist/models/modelFrame.js +8 -2
  216. package/dist/models/modelMatrix.d.ts +3 -1
  217. package/dist/models/modelMatrix.js +40 -15
  218. package/dist/models/scaledTables.d.ts +8 -0
  219. package/dist/models/scaledTables.js +6 -0
  220. package/dist/models/survival.d.ts +6 -1
  221. package/dist/models/survival.js +67 -27
  222. package/dist/models/tiedTimes.d.ts +2 -0
  223. package/dist/models/tiedTimes.js +34 -0
  224. package/dist/numerics/deriv.d.ts +1 -1
  225. package/dist/numerics/deriv.js +64 -8
  226. package/dist/numerics/integrate.d.ts +9 -1
  227. package/dist/numerics/integrate.js +103 -16
  228. package/dist/numerics/interp.d.ts +8 -2
  229. package/dist/numerics/interp.js +352 -50
  230. package/dist/numerics/ode.js +55 -1
  231. package/dist/numerics.js +2 -2
  232. package/dist/optim/localmin.js +4 -0
  233. package/dist/optim/optim.d.ts +3 -1
  234. package/dist/optim/optim.js +80 -8
  235. package/dist/random/beta.js +53 -4
  236. package/dist/random/binomial.d.ts +14 -3
  237. package/dist/random/binomial.js +59 -24
  238. package/dist/random/continuous.js +33 -5
  239. package/dist/random/extra.js +42 -9
  240. package/dist/random/gamma.d.ts +4 -1
  241. package/dist/random/gamma.js +36 -8
  242. package/dist/random/hyper.js +9 -6
  243. package/dist/random/mt.js +17 -2
  244. package/dist/random/poisson.js +26 -3
  245. package/dist/random/r2dtable.d.ts +8 -1
  246. package/dist/random/r2dtable.js +24 -3
  247. package/dist/random/rank.d.ts +2 -0
  248. package/dist/random/rank.js +44 -4
  249. package/dist/random/sample.d.ts +12 -2
  250. package/dist/random/sample.js +57 -20
  251. package/dist/random/streams.js +4 -2
  252. package/dist/rstats.js +14 -14
  253. package/dist/special/besselIK.d.ts +12 -0
  254. package/dist/special/besselIK.js +168 -23
  255. package/dist/special/besselJY.d.ts +11 -1
  256. package/dist/special/besselJY.js +127 -19
  257. package/dist/special/besselSeries.d.ts +27 -0
  258. package/dist/special/besselSeries.js +45 -2
  259. package/dist/special/beta.js +11 -1
  260. package/dist/special/choose.js +17 -8
  261. package/dist/special/dd.js +122 -18
  262. package/dist/special/extra.js +14 -2
  263. package/dist/special/gamma.js +15 -2
  264. package/dist/special/igam.js +33 -6
  265. package/dist/special/incbet.js +100 -10
  266. package/dist/special/incbetLargeA.js +7 -2
  267. package/dist/special/incbetPrefactor.d.ts +5 -0
  268. package/dist/special/incbetPrefactor.js +14 -3
  269. package/dist/special/incbetTemme.d.ts +7 -0
  270. package/dist/special/incbetTemme.js +45 -12
  271. package/dist/special/loader.d.ts +1 -1
  272. package/dist/special/loader.js +179 -33
  273. package/dist/special/log1pmx.js +4 -0
  274. package/dist/special.js +2 -2
  275. package/dist/tests.js +11 -11
  276. package/llms.txt +12 -6
  277. package/package.json +1 -1
  278. package/dist/chunks/chunk-2CUKVVRO.js +0 -2
  279. package/dist/chunks/chunk-3WQCKGKP.js +0 -2
  280. package/dist/chunks/chunk-4Z2XDWKV.js +0 -2
  281. package/dist/chunks/chunk-AJBLCNZ7.js +0 -3
  282. package/dist/chunks/chunk-D4F7GQAY.js +0 -2
  283. package/dist/chunks/chunk-EBQMGCQZ.js +0 -2
  284. package/dist/chunks/chunk-HBMHR5SS.js +0 -2
  285. package/dist/chunks/chunk-IBPWRQIF.js +0 -2
  286. package/dist/chunks/chunk-JLAH3X77.js +0 -2
  287. package/dist/chunks/chunk-LG74QY5U.js +0 -2
  288. package/dist/chunks/chunk-PEYGUK32.js +0 -2
  289. package/dist/chunks/chunk-Q4PGYESP.js +0 -2
  290. package/dist/chunks/chunk-RCAL4VHM.js +0 -3
  291. package/dist/chunks/chunk-SREPSVTT.js +0 -2
  292. package/dist/chunks/chunk-UFT662QZ.js +0 -2
  293. package/dist/chunks/chunk-VWJ74UHC.js +0 -2
  294. package/dist/chunks/chunk-XNPU54NH.js +0 -2
  295. package/dist/chunks/chunk-XPLDEK6D.js +0 -2
  296. package/dist/chunks/chunk-YGT4P7EU.js +0 -2
  297. package/dist/chunks/chunk-YVREYVI2.js +0 -2
@@ -8,7 +8,7 @@ export declare function swilkCoefficients(n: number): Float64Array;
8
8
  * r^2 = sum a_i^2 sum (x_i - mean)^2, so that it keeps its relative accuracy when W is close to 1 (the p-value
9
9
  * depends on log(1 - W)). The data are scaled by their range first.
10
10
  */
11
- export declare function swilkOneMinusW(sorted: readonly number[]): number;
11
+ export declare function swilkOneMinusW(data: readonly number[]): number;
12
12
  /**
13
13
  * The W statistic of a sample sorted in increasing order:
14
14
  * W = (sum a_i x_(i))^2 / sum (x_i - mean)^2.
@@ -11,6 +11,7 @@
11
11
  // Beyond the range of Royston's approximation for 4 <= n <= 11 the p-value is 1e-99: 1e-99 is the value R reports
12
12
  // here (observed behaviour).
13
13
  import { pnorm, qnorm } from "../../distributions/normal.js";
14
+ import { scaleToUnit } from "../../internal/summary.js";
14
15
  /** Polynomial c[0] + c[1] x + c[2] x^2 + ... */
15
16
  function poly(c, x) {
16
17
  let s = 0;
@@ -79,7 +80,10 @@ export function swilkCoefficients(n) {
79
80
  * r^2 = sum a_i^2 sum (x_i - mean)^2, so that it keeps its relative accuracy when W is close to 1 (the p-value
80
81
  * depends on log(1 - W)). The data are scaled by their range first.
81
82
  */
82
- export function swilkOneMinusW(sorted) {
83
+ export function swilkOneMinusW(data) {
84
+ // divided by a power of 2 first (exact, so the ratios to the range are unchanged): the range of finite data can
85
+ // overflow (shapiroTest([-1e308, 0, 1e308]) was NaN)
86
+ const sorted = scaleToUnit([data]).groups[0];
83
87
  const n = sorted.length;
84
88
  const a = swilkCoefficients(n);
85
89
  const range = sorted[n - 1] - sorted[0];
@@ -27,10 +27,17 @@ function phi(z) {
27
27
  function logPhi(x) {
28
28
  return pnorm(x, { logP: true });
29
29
  }
30
- /** Integral over the whole line with QUADPACK's dqagi at full precision */
31
- function wholeLine(f, lower = -Infinity) {
30
+ /**
31
+ * Integral over the whole line with QUADPACK's dqagi at full precision. With `checked` (the outer integral, the
32
+ * p-value itself), NaN when QUADPACK reports no convergence (ier 1: subdivisions used up, 3: bad integrand, 5:
33
+ * divergence) and its error estimate exceeds 1e-6 of it: no p-value rather than a wrong one. ier 2 and 4 (roundoff
34
+ * detected at this tight tolerance) leave the result usable. The inner integrals are not checked: conditional
35
+ * probabilities far below the p-value may carry a large relative error that does not reach it
36
+ */
37
+ function wholeLine(f, lower = -Infinity, checked = false) {
32
38
  const r = lower === -Infinity ? dqagie(f, 0, 2, 0, REL_TOL, LIMIT) : dqagie(f, lower, 1, 0, REL_TOL, LIMIT);
33
- return r.result;
39
+ const failed = r.ier === 1 || r.ier === 3 || r.ier === 5;
40
+ return checked && failed && !(r.abserr <= 1e-6 * Math.abs(r.result)) ? NaN : r.result;
34
41
  }
35
42
  /**
36
43
  * Inner probability given w = c u: P(max T_i >= c | U = u) (twoSided false) or P(max |T_i| >= c | U = u) (twoSided
@@ -53,8 +60,10 @@ function conditionalUpper(w, lambda, twoSided) {
53
60
  const q = pnorm(b) + pnorm(a, { lowerTail: false });
54
61
  if (q < 0.5)
55
62
  logIn += Math.log1p(-q);
63
+ // (b, a) is narrower than the rounding of the tail probabilities when w is tiny: their difference may come out
64
+ // below 0 (it gave NaN, and a NaN p-value: glhtDunnett two-sided at t = 1.55); it is at least 0
56
65
  else
57
- logIn += Math.log(a + b < 0 ? pnorm(a) - pnorm(b) : pnorm(b, { lowerTail: false }) - pnorm(a, { lowerTail: false }));
66
+ logIn += Math.log(Math.max(0, a + b < 0 ? pnorm(a) - pnorm(b) : pnorm(b, { lowerTail: false }) - pnorm(a, { lowerTail: false })));
58
67
  }
59
68
  return phi(z) * -Math.expm1(logIn);
60
69
  };
@@ -85,5 +94,5 @@ export function pDunnettUpper(c, lambda, df, twoSided) {
85
94
  return 0;
86
95
  return Math.exp(ld) * conditionalUpper(c * Math.exp(v), lambda, twoSided);
87
96
  };
88
- return Math.min(1, wholeLine(g));
97
+ return Math.min(1, wholeLine(g, -Infinity, true));
89
98
  }
@@ -41,6 +41,8 @@ export interface CohensDResult {
41
41
  /** effectsize's warnings. */
42
42
  warnings: string[];
43
43
  }
44
+ /** Hedges' correction J(df) = Γ(df/2) / (sqrt(df/2) Γ((df − 1)/2)) (exported for the tests) */
45
+ export declare function hedgesJ(df: number): number;
44
46
  /**
45
47
  * Cohen's d: the standardized difference of means of two samples (pooled or averaged standard deviation), of paired
46
48
  * samples, or of one sample against `mu`, with a confidence interval from the noncentral t distribution.
@@ -8,47 +8,71 @@
8
8
  // the exact roots (Brent's method run to the resolution of doubles).
9
9
  import { pf, qf } from "../distributions/f.js";
10
10
  import { pt } from "../distributions/t.js";
11
- import { completePairs, dropNaN, mean, variance } from "../internal/summary.js";
11
+ import { completePairs, dropNaN, groupMoments, ldexp, mean, pairedDifferences, satterthwaiteDfSe, scaleToUnit, variance } from "../internal/summary.js";
12
12
  import { anova, aovSummary } from "../models/anovaSequential.js";
13
- import { uniroot } from "../numerics/integrate.js";
14
- import { lgamma } from "../special/gamma.js";
13
+ import { scaledTables } from "../models/scaledTables.js";
14
+ import { unirootCore as uniroot } from "../numerics/integrate.js";
15
+ import { lgammaDiff } from "../special/lgammaDiff.js";
15
16
  import { matchChoice } from "./power.js";
17
+ /** The confidence level of an interval, null for none: as effectsize, strictly between 0 and 1 */
18
+ function checkCi(ci) {
19
+ if (ci !== null && !(ci > 0 && ci < 1))
20
+ throw new RangeError("ci must be a single numeric value between (0, 1)");
21
+ }
16
22
  const NA_WARNING = "Missing values detected. NAs dropped.";
17
23
  /** Brent's method run until the bracket is as narrow as doubles allow */
18
24
  const EXACT = { tol: 0, maxiter: 5000 };
19
- /** Hedges' correction J(df) = Γ(df/2) / (sqrt(df/2) Γ((df − 1)/2)) */
20
- function hedgesJ(df) {
21
- return Math.exp(lgamma(df / 2) - Math.log(Math.sqrt(df / 2)) - lgamma((df - 1) / 2));
25
+ /** Hedges' correction J(df) = Γ(df/2) / (sqrt(df/2) Γ((df − 1)/2)) (exported for the tests) */
26
+ export function hedgesJ(df) {
27
+ if (df === Infinity)
28
+ return 1;
29
+ // log J = lgamma((df - 1)/2 + 1/2) - lgamma((df - 1)/2) - log(df/2)/2, the difference of the lgammas formed directly
30
+ // (two lgammas near df log df cancel: J was 0.99997 at df = 1e10, 1.28 at 1e14, as effectsize's, where it is
31
+ // 1 - 3/(4 df - 1) to within 1e-20)
32
+ return Math.exp(lgammaDiff(0.5, (df - 1) / 2) - 0.5 * Math.log(df / 2));
22
33
  }
23
34
  /** The noncentrality parameter with pt(t, df, ncp) = p (pt decreases in ncp) */
24
35
  function ncpOfT(t, df, p) {
25
- return uniroot((ncp) => pt(t, df, { ncp }) - p, t - 1, t + 1, { ...EXACT, extendInt: "downX" }).root;
36
+ // (where t ± 1 both round to t, a step of 1 to 2 ulp of t: the empty interval [t, t] was an error; issue #143)
37
+ const h = t - 1 < t + 1 ? 1 : Math.abs(t) * Number.EPSILON;
38
+ return uniroot((ncp) => pt(t, df, { ncp }) - p, t - h, t + h, { ...EXACT, extendInt: "downX" }).root;
26
39
  }
27
40
  function standardizedDifference(x, y, options, adjust) {
28
41
  const pooled = options.pooledSd ?? true;
29
42
  const mu = options.mu ?? 0;
30
43
  const paired = options.paired ?? false;
31
44
  const ci = options.ci === undefined ? 0.95 : options.ci;
45
+ checkCi(ci);
32
46
  const alt = matchChoice(options.alternative, ["two.sided", "less", "greater"]);
33
47
  const xs = Array.from(x);
34
48
  const ys = y === undefined ? undefined : Array.from(y);
35
49
  const warnings = [];
36
50
  if (xs.some(Number.isNaN) || (ys?.some(Number.isNaN) ?? false))
37
51
  warnings.push(NA_WARNING);
52
+ // (an infinite value, or too few observations, ended in the root search of the interval: "lower < upper is not
53
+ // fulfilled"; effectsize gives NA)
54
+ const infinite = (v) => v === Infinity || v === -Infinity;
55
+ if (xs.some(infinite) || (ys?.some(infinite) ?? false))
56
+ throw new RangeError("the observations must be finite (NaN is dropped as missing)");
57
+ // Everything is computed on the data scaled by one power of 2, 2^-k (exact; paired values before their differences
58
+ // are taken), with mu scaled alike: the effect size and its interval have no units, so nothing is scaled back
38
59
  let d;
39
60
  let s;
40
61
  let se;
41
62
  let h;
42
63
  let df;
64
+ let k;
43
65
  if (ys === undefined || paired) {
44
66
  let v;
45
67
  if (ys === undefined)
46
- v = dropNaN(xs);
68
+ ({ groups: [v], k } = scaleToUnit([dropNaN(xs)]));
47
69
  else {
48
70
  const [a, b] = completePairs(xs, ys);
49
- v = a.map((ai, i) => ai - b[i]);
71
+ ({ d: v, k } = pairedDifferences(a, b));
50
72
  }
51
73
  const n = v.length;
74
+ if (n < 2)
75
+ throw new RangeError(ys === undefined ? "not enough observations: at least 2 are needed" : "not enough complete pairs: at least 2 are needed");
52
76
  d = mean(v);
53
77
  s = Math.sqrt(variance(v));
54
78
  se = s / Math.sqrt(n);
@@ -56,13 +80,14 @@ function standardizedDifference(x, y, options, adjust) {
56
80
  df = n - 1;
57
81
  }
58
82
  else {
59
- const a = dropNaN(xs);
60
- const b = dropNaN(ys);
61
- const n1 = a.length;
62
- const n2 = b.length;
63
- d = mean(a) - mean(b);
64
- const s1 = Math.sqrt(variance(a));
65
- const s2 = Math.sqrt(variance(b));
83
+ const gm = groupMoments([dropNaN(xs), dropNaN(ys)]);
84
+ k = gm.k;
85
+ const [n1, n2] = gm.n;
86
+ if (n1 < 2 || n2 < 2)
87
+ throw new RangeError("not enough observations: at least 2 are needed in each group");
88
+ d = gm.mean[0] - gm.mean[1];
89
+ const s1 = Math.sqrt(gm.variance[0]);
90
+ const s2 = Math.sqrt(gm.variance[1]);
66
91
  if (pooled) {
67
92
  s = Math.sqrt(((n1 - 1) * s1 ** 2 + (n2 - 1) * s2 ** 2) / (n1 + n2 - 2));
68
93
  se = s * Math.sqrt(1 / n1 + 1 / n2);
@@ -72,17 +97,19 @@ function standardizedDifference(x, y, options, adjust) {
72
97
  else {
73
98
  s = Math.sqrt((s1 ** 2 + s2 ** 2) / 2);
74
99
  h = (2 * (n2 * s1 ** 2 + n1 * s2 ** 2)) / (n1 * n2 * (s1 ** 2 + s2 ** 2));
75
- se = Math.sqrt(s1 ** 2 / n1 + s2 ** 2 / n2);
76
- df = se ** 4 / ((s1 ** 2 / n1) ** 2 / (n1 - 1) + (s2 ** 2 / n2) ** 2 / (n2 - 1));
100
+ // effectsize's se = sqrt(se1^2 + se2^2) with se_i = sqrt(s_i^2 / n_i), and its df from them
101
+ se = Math.sqrt(Math.sqrt(s1 ** 2 / n1) ** 2 + Math.sqrt(s2 ** 2 / n2) ** 2);
102
+ df = satterthwaiteDfSe([s1 ** 2 / n1, s2 ** 2 / n2], [n1 - 1, n2 - 1]);
77
103
  }
78
104
  }
79
105
  const j = adjust ? hedgesJ(df) : 1;
80
- const value = ((d - mu) / s) * j;
106
+ const muS = ldexp(mu, -k);
107
+ const value = ((d - muS) / s) * j;
81
108
  const name = adjust ? "Hedges_g" : "Cohens_d";
82
109
  if (ci === null)
83
110
  return { name, value, warnings };
84
111
  const level = alt === "two.sided" ? ci : 2 * ci - 1;
85
- const t = (d - mu) / se;
112
+ const t = (d - muS) / se;
86
113
  let ciLow = ncpOfT(t, df, (1 + level) / 2) * Math.sqrt(h) * j;
87
114
  let ciHigh = ncpOfT(t, df, (1 - level) / 2) * Math.sqrt(h) * j;
88
115
  if (alt === "less")
@@ -127,9 +154,10 @@ const isEz = (m) => {
127
154
  const e = m;
128
155
  return typeof e.univariate === "object" && typeof e.anova === "object";
129
156
  };
130
- const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
131
157
  /** A name as a whole word */
132
- const word = (name) => new RegExp(`\\b${escapeRegExp(name)}\\b`);
158
+ // Whether a variable is one of the components of a term name such as "a:b" (compared as names, so that a name that is
159
+ // not a run of word characters, such as ".grp", is found too)
160
+ const word = (name) => ({ test: (term) => term.split(":").includes(name) });
133
161
  /** The strata of aov with Error() from its summary (intercept stratum left out), and the subject stratum */
134
162
  function summaryStrata(s) {
135
163
  const strata = s.strata
@@ -222,7 +250,11 @@ function observedTerms(gen, terms) {
222
250
  /** The noncentrality limits of an F value: ncp ≥ 0 with pf(F, df1, df2, ncp) = p (pf decreases in ncp), 0 if none */
223
251
  function ncpOfF(f, df1, df2, p) {
224
252
  const g = (ncp) => pf(f, df1, df2, { ncp }) - p;
225
- if (!(g(0) > 0))
253
+ // (NaN is no root of 0: it was taken as one)
254
+ const g0 = g(0);
255
+ if (Number.isNaN(g0))
256
+ return NaN;
257
+ if (!(g0 > 0))
226
258
  return 0;
227
259
  if (f === Infinity)
228
260
  return Infinity;
@@ -247,25 +279,40 @@ function withInterval(es, df, dfe, ci, alt) {
247
279
  ciHigh = 1;
248
280
  return [es, ci, ciLow, ciHigh];
249
281
  }
282
+ /** The sums of squares of rows divided by one power of 2, the largest in [1, 2) (exact; the effect sizes are ratios) */
283
+ function normalizeSS(rows) {
284
+ const k = scaleToUnit([rows.map((r) => r.ss)]).k;
285
+ if (k !== 0)
286
+ for (const r of rows)
287
+ r.ss = ldexp(r.ss, -k);
288
+ }
250
289
  const NEEDS = "needs a table of anova() or Anova(), a fit from lm() or aov() with a formula, its aovSummary(), or a result of aovEz()";
251
290
  function anovaEffectSize(model, kind, options) {
252
291
  if (typeof model !== "object" || model === null)
253
292
  throw new TypeError(NEEDS);
254
293
  if (isStrataFit(model) || isStrataSummary(model) || isEz(model))
255
294
  return strataEffectSize(model, kind, options);
256
- const tab = isFit(model) ? anova(model) : model;
257
- if (!Array.isArray(tab.colNames) || !Array.isArray(tab.table))
295
+ const given = isFit(model) ? anova(model) : model;
296
+ if (!Array.isArray(given.colNames) || !Array.isArray(given.table))
258
297
  throw new TypeError(NEEDS);
298
+ // the sums of squares as fitted where the table has them (those returned can overflow: scaledTables.ts)
299
+ const scaled = scaledTables.get(given);
300
+ const tab = scaled !== undefined && !Array.isArray(scaled) ? scaled : given;
259
301
  const ci = options.ci === undefined ? 0.95 : options.ci;
302
+ checkCi(ci);
260
303
  const alt = matchChoice(options.alternative ?? "greater", ["two.sided", "less", "greater"]);
261
304
  const iDf = tab.colNames.indexOf("Df");
262
305
  const iSS = tab.colNames.indexOf("Sum Sq");
263
306
  if (iDf < 0 || iSS < 0)
264
307
  throw new TypeError("the table needs the columns 'Df' and 'Sum Sq'");
265
308
  const rows = tab.rowNames.map((name, i) => ({ name, df: tab.table[i][iDf], ss: tab.table[i][iSS] })).filter((r) => r.name !== "(Intercept)");
309
+ normalizeSS(rows);
266
310
  const res = rows.find((r) => r.name === "Residuals");
267
311
  if (res === undefined)
268
312
  throw new TypeError("the table has no row 'Residuals'");
313
+ // (a saturated model: the effect sizes were 0 / 0 rounding noise, as effectsize's "No residuals data found")
314
+ if (!(res.df > 0))
315
+ throw new Error("the model has no residual degrees of freedom: the effect sizes are not defined");
269
316
  const terms = rows.filter((r) => r !== res);
270
317
  const dfe = res.df;
271
318
  const sse = res.ss;
@@ -298,7 +345,8 @@ function anovaEffectSize(model, kind, options) {
298
345
  colNames: ci === null ? [column] : [column, "CI", "CI_low", "CI_high"],
299
346
  rowNames: terms.map((t) => t.name),
300
347
  table: terms.map((t) => (ci === null ? [value(t)] : withInterval(value(t), t.df, dfe, ci, alt))),
301
- warnings: [],
348
+ // the warnings of the table (and so of the fit it came from), as for models with error strata
349
+ warnings: Array.isArray(given.warnings) ? [...given.warnings] : [],
302
350
  };
303
351
  }
304
352
  /**
@@ -307,20 +355,31 @@ function anovaEffectSize(model, kind, options) {
307
355
  */
308
356
  function strataEffectSize(model, kind, options) {
309
357
  const ci = options.ci === undefined ? 0.95 : options.ci;
358
+ checkCi(ci);
310
359
  const alt = matchChoice(options.alternative ?? "greater", ["two.sided", "less", "greater"]);
311
360
  const ez = isEz(model);
312
361
  let strata;
313
362
  let subject;
314
363
  let rows;
315
364
  if (ez) {
316
- const s = ezStrata(model);
365
+ const sc = scaledTables.get(model);
366
+ const s = ezStrata(sc !== undefined && !Array.isArray(sc) ? { ...model, univariate: sc } : model);
317
367
  ({ strata, subject } = s);
318
368
  rows = s.order.map((term) => ({ term, stratum: s.strata.find((st) => st.terms.includes(term)) }));
319
369
  }
320
370
  else {
321
- ({ strata, subject } = summaryStrata(isStrataFit(model) ? aovSummary(model) : model));
371
+ const summary = isStrataFit(model) ? aovSummary(model) : model;
372
+ const sc = scaledTables.get(summary);
373
+ ({ strata, subject } = summaryStrata(Array.isArray(sc) ? { ...summary, strata: sc.map((t, i) => ({ ...summary.strata[i], ...t })) } : summary));
322
374
  rows = strata.flatMap((stratum) => stratum.terms.map((term) => ({ term, stratum })));
323
375
  }
376
+ // one power of 2 for all sums of squares (their sums can overflow; the effect sizes are ratios of them)
377
+ const k = scaleToUnit([[...strata.flatMap((st) => st.terms.map((t) => t.ss)), ...strata.map((st) => st.sse)]]).k;
378
+ for (const st of strata) {
379
+ st.sse = ldexp(st.sse, -k);
380
+ for (const t of st.terms)
381
+ t.ss = ldexp(t.ss, -k);
382
+ }
324
383
  const allTerms = strata.flatMap((st) => st.terms);
325
384
  const sseAll = strata.reduce((a, st) => a + st.sse, 0);
326
385
  const ssTot = allTerms.reduce((a, t) => a + t.ss, 0) + sseAll;
@@ -356,8 +415,11 @@ function strataEffectSize(model, kind, options) {
356
415
  }),
357
416
  warnings: [],
358
417
  };
359
- if (!ez)
418
+ if (!ez) {
360
419
  out.groups = rows.map((r) => r.stratum.name);
420
+ // the warnings of the fit (or of its summary), such as "Error() model is singular"
421
+ out.warnings = [...(isStrataFit(model) || isStrataSummary(model) ? model.warnings : [])];
422
+ }
361
423
  return out;
362
424
  }
363
425
  /**
@@ -58,8 +58,8 @@ export interface FisherTestResult extends Omit<HTest, "statistic" | "statisticNa
58
58
  * ```ts
59
59
  * const r = fisherTest([[3, 1], [1, 3]]);
60
60
  * r.pValue; // 0.4857142857142857
61
- * r.estimate; // 6.408308867005792 (conditional MLE of the odds ratio)
62
- * r.confInt; // [0.2117329153055031, 621.9337505454175]
61
+ * r.estimate; // 6.408319658199675 (conditional MLE of the odds ratio; R: 6.408309)
62
+ * r.confInt; // [0.2117355954465785, 626.2435305888127] (R: 0.2117329, 621.93)
63
63
  * ```
64
64
  *
65
65
  * @category Hypothesis tests
@@ -7,9 +7,10 @@
7
7
  // - Densities are formed in logs from the accurate log dhyper (evaluated every 16 points, exact ratios in
8
8
  // between) and normalised with double-double sums, so the root
9
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
10
+ // - Roots are found on the log scale of psi to the precision of the doubles (logScaleRoot, src/internal/uniroot.ts).
11
+ // R solves on psi in [0, 1] or 1/psi in [eps, 1] with the absolute tolerance eps^0.25 and stops 1e-6 to 1e-2 from
12
+ // the true roots (0.7% for the 95% upper limit of [[3, 1], [1, 3]], 6% at 99%, and the end 1/eps at 99.99%); the
13
+ // values here are the roots (review 58)
13
14
  // - The two-sided p-value is the sum of probabilities of tables whose probability is at most (1 + 1e-7) times the
14
15
  // observed one (R's convention); for or = 0 or Inf the distribution is a point mass at the end of the support
15
16
  // - Counts are made integer by rounding half to even (R rounds with a warning)
@@ -33,12 +34,13 @@
33
34
  // R's hybrid is not implemented.
34
35
  import { dhyper1, phyper1 } from "../distributions/hypergeometric.js";
35
36
  import { roundHalfEven } from "../internal/integer.js";
36
- import { logFactorialTable, rcont2 } from "../random/r2dtable.js";
37
+ import { logFactorialTable, MAX_TABLE_TOTAL, rcont2 } from "../random/r2dtable.js";
37
38
  import { lfactorial } from "../special/choose.js";
38
- import { uniroot } from "../internal/uniroot.js";
39
+ import { logScaleRoot } from "../internal/uniroot.js";
39
40
  import { ddAdd, ddLog, ddNeg, ddSub } from "../special/dd.js";
40
41
  import { simulatedMethod } from "./core/simulate.js";
41
42
  import { matchAlternative } from "./types.js";
43
+ import { maxOf, minOf } from "../internal/extremes.js";
42
44
  /**
43
45
  * Fisher's exact test for count data. Equivalent to R's `fisher.test()`.
44
46
  *
@@ -62,8 +64,8 @@ import { matchAlternative } from "./types.js";
62
64
  * ```ts
63
65
  * const r = fisherTest([[3, 1], [1, 3]]);
64
66
  * r.pValue; // 0.4857142857142857
65
- * r.estimate; // 6.408308867005792 (conditional MLE of the odds ratio)
66
- * r.confInt; // [0.2117329153055031, 621.9337505454175]
67
+ * r.estimate; // 6.408319658199675 (conditional MLE of the odds ratio; R: 6.408309)
68
+ * r.confInt; // [0.2117355954465785, 626.2435305888127] (R: 0.2117329, 621.93)
67
69
  * ```
68
70
  *
69
71
  * @category Hypothesis tests
@@ -82,6 +84,9 @@ export function fisherTest(x, options = {}) {
82
84
  if (raw.flat().some((v) => v === Infinity))
83
85
  throw new RangeError("'x' has entries too large to be integer");
84
86
  const t = raw.map((r) => r.map(roundHalfEven));
87
+ // as in R, counts beyond the largest integer (2^31 - 1) are rejected (the 2 x 2 support would also be huge)
88
+ if (t.flat().some((v) => v > 2147483647))
89
+ throw new RangeError("'x' has entries too large to be integer");
85
90
  const method = "Fisher's Exact Test for Count Data";
86
91
  if (nr === 2 && nc === 2)
87
92
  return fisher2x2(t, options, method);
@@ -89,8 +94,10 @@ export function fisherTest(x, options = {}) {
89
94
  const alternative = (options.alternative ?? "two.sided");
90
95
  if (options.simulatePValue ?? false) {
91
96
  const B = options.B ?? 2000;
92
- if (!(B >= 0 && B < 2 ** 31))
93
- throw new RangeError("'B' must be a non-negative number");
97
+ // a fractional B ran trunc(B) simulations but was reported as B (#278); an error, as in chisqTest. B = 0 simulates
98
+ // nothing (R's p = (1 + 0) / (0 + 1) = 1): an error too (#488)
99
+ if (!(Number.isInteger(B) && B >= 1 && B < 2 ** 31))
100
+ throw new RangeError("'B' must be a positive integer");
94
101
  return { method: method + simulatedMethod(B), alternative, pValue: fisherSimulated(t, B) };
95
102
  }
96
103
  return { method, alternative, pValue: fisherRxC(t) };
@@ -113,7 +120,11 @@ function fisherSimulated(t, B) {
113
120
  for (const v of x.flat())
114
121
  acc = ddAdd(acc, [-lfactorial(v), 0]);
115
122
  const threshold = acc[0] / (1 + 64 * Number.EPSILON);
116
- const fact = logFactorialTable(sr.reduce((a, b) => a + b, 0));
123
+ const total = sr.reduce((a, b) => a + b, 0);
124
+ // the table of log factorials has total + 1 entries: limited as in r2dtable (#286)
125
+ if (total > MAX_TABLE_TOTAL)
126
+ throw new RangeError("the simulation needs a total count of at most 16777216 (2^24)");
127
+ const fact = logFactorialTable(total);
117
128
  const table = new Int32Array(nr * nc);
118
129
  let count = 0;
119
130
  const reps = Math.trunc(B);
@@ -125,13 +136,18 @@ function fisherSimulated(t, B) {
125
136
  if (s <= threshold)
126
137
  count++;
127
138
  }
128
- return Math.max(0, Math.min(1, (1 + count) / (B + 1)));
139
+ return Math.max(0, Math.min(1, (1 + count) / (reps + 1)));
129
140
  }
130
141
  // ---- 2×2 ----
131
142
  /** Relative slack for counting a table as "no more likely than the observed one" in the two-sided p-value */
132
143
  const SLACK = 1 + 1e-7;
133
144
  /** Spacing of the points at which the central log density is evaluated directly */
134
145
  const ANCHOR = 16;
146
+ /**
147
+ * Largest support (number of values of the (1, 1) cell) of the exact 2 x 2 distribution: 2^24 values take about
148
+ * 12 s and 0.4 GB; R allocates the whole support whatever its size (counts of 1e9 would take 16 GB per array)
149
+ */
150
+ const MAX_SUPPORT = 2 ** 24;
135
151
  /** Double-double sum of v[from..to] (inclusive, clipped to the array) */
136
152
  function accurateSum(v, from, to) {
137
153
  let acc = [0, 0];
@@ -225,12 +241,9 @@ class OddsRatioDistribution {
225
241
  return upper ? accurateSum(d, j, d.length - 1) : accurateSum(d, 0, j);
226
242
  }
227
243
  }
228
- /**
229
- * Root of f, monotone in the odds ratio psi: searched for as psi in [0, 1] when it lies below 1, otherwise as
230
- * s = 1/psi in [eps, 1] (uniroot with its default tolerance in both cases)
231
- */
244
+ /** Root of f, monotone in the odds ratio psi, to the precision of the doubles (on the log scale, see logScaleRoot) */
232
245
  function oddsRatioRoot(f, belowOne) {
233
- return belowOne ? uniroot(f, 0, 1) : 1 / uniroot((s) => f(1 / s), Number.EPSILON, 1);
246
+ return logScaleRoot(f, belowOne);
234
247
  }
235
248
  function fisher2x2(t, options, method) {
236
249
  const alternative = matchAlternative(options.alternative);
@@ -242,6 +255,11 @@ function fisher2x2(t, options, method) {
242
255
  throw new RangeError("confLevel must be a single number between 0 and 1");
243
256
  const [[a, b], [c, d]] = t;
244
257
  const x = a;
258
+ // the support lo..hi has min(a, d) + min(b, c) + 1 values; checked before it is allocated
259
+ const size = Math.min(a, d) + Math.min(b, c) + 1;
260
+ if (size > MAX_SUPPORT) {
261
+ throw new RangeError(`the exact distribution of the 2 x 2 table has ${size} values, more than 2^24`);
262
+ }
245
263
  const dist = new OddsRatioDistribution(a + c, b + d, a + b);
246
264
  const { lo, hi } = dist;
247
265
  let pValue;
@@ -430,8 +448,8 @@ function fisherRxC(t) {
430
448
  };
431
449
  rec(0, colSums[j], [0, 0]);
432
450
  node.edges = [...groups.values()];
433
- node.max = Math.max(...node.edges.map((e) => e.hi + e.to.max));
434
- node.min = Math.min(...node.edges.map((e) => e.hi + e.to.min));
451
+ node.max = maxOf(node.edges.map((e) => e.hi + e.to.max));
452
+ node.min = minOf(node.edges.map((e) => e.hi + e.to.min));
435
453
  if (j === ncol - 2) {
436
454
  // With two columns left, the rest of the table is determined by a single edge. Sort by value and take cumulative sums,
437
455
  // then find the threshold position per path by binary search (reducing paths × edges work to paths × log(edges))
@@ -5,6 +5,13 @@ import type { Sample } from "./types.js";
5
5
  * @category Hypothesis tests
6
6
  */
7
7
  export type GroupLabel = number | string;
8
+ /**
9
+ * Labels as R's factor() takes them: numbers with the same 15-digit text as one (numberLevels), and all as text when
10
+ * any label is a string (R coerces a mixed vector to character). NaN stays missing
11
+ */
12
+ export declare function factorLabels(g: readonly GroupLabel[]): GroupLabel[];
13
+ /** Order of levels (of one type after factorLabels): numbers numerically, strings by code point (C locale) */
14
+ export declare function compareLabels(a: GroupLabel, b: GroupLabel): number;
8
15
  /** Groups with their labels: the sorted labels (x, g form) or the 1-based positions in the list (list form) */
9
16
  export interface LabelledGroups {
10
17
  labels: string[];
@@ -2,8 +2,25 @@
2
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
3
  // of the sorted labels (as R orders factor levels). Numeric labels with the same 15-digit text are one group, as in
4
4
  // R's factor() (src/internal/levels.ts); the group's label is the smallest of them, written as R writes it
5
- // ("1e+15", "0.333333333333333").
5
+ // ("1e+15", "0.333333333333333"). When the labels mix numbers and strings, all are text, as R coerces such a vector
6
+ // to character (2 and "2" are one group); levels are then ordered by code point.
6
7
  import { levelText, numberLevels } from "../internal/levels.js";
8
+ import { compareCodePoints } from "../models/modelFrame.js";
9
+ import { midpoint } from "../internal/extremes.js";
10
+ /**
11
+ * Labels as R's factor() takes them: numbers with the same 15-digit text as one (numberLevels), and all as text when
12
+ * any label is a string (R coerces a mixed vector to character). NaN stays missing
13
+ */
14
+ export function factorLabels(g) {
15
+ const gs = numberLevels(g);
16
+ if (!gs.some((l) => typeof l === "string"))
17
+ return gs;
18
+ return gs.map((l) => (typeof l === "number" && !Number.isNaN(l) ? levelText(l) : l));
19
+ }
20
+ /** Order of levels (of one type after factorLabels): numbers numerically, strings by code point (C locale) */
21
+ export function compareLabels(a, b) {
22
+ return typeof a === "number" && typeof b === "number" ? a - b : compareCodePoints(String(a), String(b));
23
+ }
7
24
  /**
8
25
  * Normalise the two input forms to groups with NaN removed, each with its label. In the x, g form a label whose
9
26
  * values are all missing has no group (as R drops an unused factor level). In the list form a group left empty is
@@ -30,7 +47,7 @@ export function labelledGroups(x, g, emptyGroups = "drop") {
30
47
  const xs = Array.from(x);
31
48
  if (xs.length !== g.length)
32
49
  throw new RangeError("'x' and 'g' must have the same length");
33
- const gs = numberLevels(g);
50
+ const gs = factorLabels(g);
34
51
  const byLabel = new Map();
35
52
  for (let i = 0; i < xs.length; i++) {
36
53
  const v = xs[i];
@@ -42,7 +59,7 @@ export function labelledGroups(x, g, emptyGroups = "drop") {
42
59
  byLabel.set(l, (arr = []));
43
60
  arr.push(v);
44
61
  }
45
- 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);
62
+ const labels = Array.from(byLabel.keys()).sort(compareLabels);
46
63
  return { labels: labels.map(levelText), groups: labels.map((l) => byLabel.get(l)) };
47
64
  }
48
65
  /** Normalise the two input forms to an array of non-empty groups with NaN removed (see {@link labelledGroups}) */
@@ -53,7 +70,7 @@ export function toGroups(x, g, emptyGroups = "drop") {
53
70
  export function median(x) {
54
71
  const s = [...x].sort((a, b) => a - b);
55
72
  const n = s.length;
56
- return n % 2 === 1 ? s[(n - 1) / 2] : (s[n / 2 - 1] + s[n / 2]) / 2;
73
+ return n % 2 === 1 ? s[(n - 1) / 2] : midpoint(s[n / 2 - 1], s[n / 2]);
57
74
  }
58
75
  /** Rows of a blocks x treatments table with any NaN dropped (R's complete.cases) */
59
76
  export function completeRows(y) {
@@ -13,7 +13,9 @@ export interface KsTestOptions {
13
13
  alternative?: Alternative | "two" | "l" | "g";
14
14
  /**
15
15
  * Exact p-value. Default: exact for one sample of fewer than 100 values without ties, and for two samples with
16
- * m n < 10000.
16
+ * m n < 10000. The exact two-sided one-sample p-value for D < 1/2 raises a matrix of size 2 floor(n D) + 1 to the
17
+ * n-th power; where that needs more than 2^33 multiply-adds (m 781 at n 1023, about 4 s) it is a RangeError (R
18
+ * computes it however long it takes).
17
19
  */
18
20
  exact?: boolean;
19
21
  }
@@ -6,7 +6,7 @@
6
6
  // Kolmogorov's limit and exp(-2 n D^2). Two samples: the largest differences of the empirical distribution functions,
7
7
  // taken only where the pooled sorted values change; exact p-values (by default for m n < 10000, with or without ties)
8
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";
9
+ import { checkKolmogorovExactSize, pkolmogorovExact, pkolmogorovExactUpper, pkolmogorovLimit, pkolmogorovOneSidedUpper, } from "./core/kolmogorov.js";
10
10
  import { psmirnovUpper } from "./core/smirnov.js";
11
11
  import { twoGroupData } from "./testFormula.js";
12
12
  import { matchAlternative } from "./types.js";
@@ -34,6 +34,9 @@ export function ksTest(x, y, options = {}) {
34
34
  let dminus = -Infinity;
35
35
  for (let i = 0; i < n; i++) {
36
36
  const f = y(xs[i]);
37
+ // a distribution function takes values in [0, 1] (R uses whatever it returns: D = 1.5 and p = 0 for 1.5)
38
+ if (!(f >= 0 && f <= 1))
39
+ throw new RangeError(`the distribution function returned ${f} at ${xs[i]}, not a value in [0, 1]`);
37
40
  dplus = Math.max(dplus, (i + 1) / n - f);
38
41
  dminus = Math.max(dminus, f - i / n);
39
42
  }
@@ -41,8 +44,26 @@ export function ksTest(x, y, options = {}) {
41
44
  const ties = new Set(xs).size < n;
42
45
  const exact = options.exact ?? (n < 100 && !ties);
43
46
  let pValue;
47
+ // (the matrix of the exact distribution grows with n D: a RangeError before it is built when too large, #307)
48
+ if (exact && alternative === "two.sided" && statistic < 0.5)
49
+ checkKolmogorovExactSize(n, statistic);
44
50
  if (alternative === "two.sided") {
45
- pValue = exact ? 1 - pkolmogorovExact(n, statistic) : pkolmogorovLimit(Math.sqrt(n) * statistic, false);
51
+ // For D >= 1/2 the two one-sided exceedances cannot both occur, so P(D >= d) = 2 P(D+ >= d) exactly, a sum of
52
+ // positive terms: 1 - P(D < d) lost all digits of small p-values (D = 0.9 gave 0 at n = 20 for 2e-20, and 3e-15
53
+ // at n = 99 for 2e-99; R too). For D < 1/2 and 2 P(D+ >= d) < 1e-2 (an upper bound of p), the upper tail as a sum of positive
54
+ // terms too (#483: 1e-22 was 3e-15 at n = 99, R 2e-15); 1 - P(D < d) where p may be larger (as R), or where the
55
+ // sum needs too much work
56
+ if (!exact)
57
+ pValue = pkolmogorovLimit(Math.sqrt(n) * statistic, false);
58
+ else {
59
+ const bound = 2 * pkolmogorovOneSidedUpper(n, statistic);
60
+ if (statistic >= 0.5)
61
+ pValue = Math.min(1, bound);
62
+ else {
63
+ const upper = bound < 1e-2 ? pkolmogorovExactUpper(n, statistic) : NaN;
64
+ pValue = Number.isNaN(upper) ? 1 - pkolmogorovExact(n, statistic) : upper;
65
+ }
66
+ }
46
67
  }
47
68
  else {
48
69
  pValue = exact ? pkolmogorovOneSidedUpper(n, statistic) : Math.exp(-2 * n * statistic * statistic);