@numero-uno-jpn/rstats 0.15.3 → 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 (285) hide show
  1. package/CHANGELOG.md +166 -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-VLUL2HFW.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 +24 -4
  47. package/dist/distributions/binomial.js +37 -14
  48. package/dist/distributions/bvnorm.js +11 -2
  49. package/dist/distributions/cauchy.js +12 -4
  50. package/dist/distributions/chisq.js +7 -3
  51. package/dist/distributions/exponential.js +5 -0
  52. package/dist/distributions/f.js +32 -17
  53. package/dist/distributions/gamma.js +27 -3
  54. package/dist/distributions/geometric.js +49 -13
  55. package/dist/distributions/hypergeometric.d.ts +5 -1
  56. package/dist/distributions/hypergeometric.js +93 -6
  57. package/dist/distributions/invgamma.js +2 -1
  58. package/dist/distributions/laplace.js +27 -6
  59. package/dist/distributions/logistic.js +4 -1
  60. package/dist/distributions/lognormal.js +8 -2
  61. package/dist/distributions/multinomial.js +54 -11
  62. package/dist/distributions/nbeta.js +62 -11
  63. package/dist/distributions/nchisq.js +30 -6
  64. package/dist/distributions/negbinomial.js +94 -17
  65. package/dist/distributions/normal.js +9 -4
  66. package/dist/distributions/nt.js +392 -17
  67. package/dist/distributions/pareto.js +4 -1
  68. package/dist/distributions/poisson.js +28 -3
  69. package/dist/distributions/signrank.js +7 -4
  70. package/dist/distributions/summary.js +450 -60
  71. package/dist/distributions/triangular.js +10 -5
  72. package/dist/distributions/tukey.js +5 -2
  73. package/dist/distributions/weibull.js +10 -0
  74. package/dist/distributions/wilcox.d.ts +9 -3
  75. package/dist/distributions/wilcox.js +155 -26
  76. package/dist/distributions.js +2 -2
  77. package/dist/htest/agreement.d.ts +3 -2
  78. package/dist/htest/agreement.js +76 -14
  79. package/dist/htest/ansariTest.d.ts +6 -1
  80. package/dist/htest/ansariTest.js +75 -8
  81. package/dist/htest/aov.d.ts +1 -1
  82. package/dist/htest/aov.js +48 -34
  83. package/dist/htest/binomTest.d.ts +5 -0
  84. package/dist/htest/binomTest.js +41 -17
  85. package/dist/htest/brunnerMunzelTest.d.ts +4 -3
  86. package/dist/htest/brunnerMunzelTest.js +7 -5
  87. package/dist/htest/chisqTest.d.ts +2 -1
  88. package/dist/htest/chisqTest.js +130 -43
  89. package/dist/htest/cor.d.ts +2 -1
  90. package/dist/htest/cor.js +17 -19
  91. package/dist/htest/core/ansari.d.ts +9 -0
  92. package/dist/htest/core/ansari.js +21 -1
  93. package/dist/htest/core/kolmogorov.d.ts +25 -0
  94. package/dist/htest/core/kolmogorov.js +123 -0
  95. package/dist/htest/core/mantelhaen.js +6 -4
  96. package/dist/htest/core/shapiro.d.ts +1 -1
  97. package/dist/htest/core/shapiro.js +5 -1
  98. package/dist/htest/dunnett.js +14 -5
  99. package/dist/htest/effectSize.d.ts +2 -0
  100. package/dist/htest/effectSize.js +91 -29
  101. package/dist/htest/fisherTest.d.ts +2 -2
  102. package/dist/htest/fisherTest.js +36 -18
  103. package/dist/htest/groups.d.ts +7 -0
  104. package/dist/htest/groups.js +21 -4
  105. package/dist/htest/ksTest.d.ts +3 -1
  106. package/dist/htest/ksTest.js +23 -2
  107. package/dist/htest/leveneTest.js +19 -3
  108. package/dist/htest/mantelhaenTest.js +125 -25
  109. package/dist/htest/mcnemarTest.js +32 -11
  110. package/dist/htest/multipleComparisons.d.ts +8 -1
  111. package/dist/htest/multipleComparisons.js +44 -21
  112. package/dist/htest/normalityTests.js +44 -10
  113. package/dist/htest/onewayTest.js +96 -5
  114. package/dist/htest/pAdjust.d.ts +3 -2
  115. package/dist/htest/pAdjust.js +38 -6
  116. package/dist/htest/pairwise.d.ts +1 -1
  117. package/dist/htest/pairwise.js +17 -15
  118. package/dist/htest/poissonTest.d.ts +1 -1
  119. package/dist/htest/poissonTest.js +111 -59
  120. package/dist/htest/polycor.js +27 -7
  121. package/dist/htest/power.d.ts +11 -1
  122. package/dist/htest/power.js +112 -8
  123. package/dist/htest/propTest.js +21 -4
  124. package/dist/htest/pwr.js +121 -24
  125. package/dist/htest/rankTests.js +29 -5
  126. package/dist/htest/tTest.js +44 -21
  127. package/dist/htest/trendTests.d.ts +7 -3
  128. package/dist/htest/trendTests.js +114 -20
  129. package/dist/htest/types.d.ts +5 -0
  130. package/dist/htest/types.js +7 -0
  131. package/dist/htest/varTest.js +45 -14
  132. package/dist/htest/wilcoxTest.js +114 -21
  133. package/dist/integrate/quadpack.js +27 -5
  134. package/dist/internal/covmat.d.ts +5 -0
  135. package/dist/internal/covmat.js +20 -0
  136. package/dist/internal/ddexp.d.ts +15 -1
  137. package/dist/internal/ddexp.js +59 -6
  138. package/dist/internal/discrete.d.ts +14 -0
  139. package/dist/internal/discrete.js +78 -5
  140. package/dist/internal/extremes.d.ts +9 -0
  141. package/dist/internal/extremes.js +24 -0
  142. package/dist/internal/fround.js +13 -4
  143. package/dist/internal/integer.d.ts +9 -0
  144. package/dist/internal/integer.js +12 -0
  145. package/dist/internal/invert.js +15 -2
  146. package/dist/internal/scaledInverse.d.ts +10 -0
  147. package/dist/internal/scaledInverse.js +22 -0
  148. package/dist/internal/seq.js +15 -2
  149. package/dist/internal/summary.d.ts +90 -0
  150. package/dist/internal/summary.js +458 -39
  151. package/dist/internal/uniroot.d.ts +7 -0
  152. package/dist/internal/uniroot.js +28 -3
  153. package/dist/linalg/basic.d.ts +3 -1
  154. package/dist/linalg/basic.js +51 -7
  155. package/dist/linalg/chol.js +4 -1
  156. package/dist/linalg/dot.d.ts +29 -0
  157. package/dist/linalg/dot.js +132 -0
  158. package/dist/linalg/eigen.d.ts +6 -1
  159. package/dist/linalg/eigen.js +71 -14
  160. package/dist/linalg/expm.d.ts +3 -2
  161. package/dist/linalg/expm.js +109 -15
  162. package/dist/linalg/kappa.js +58 -10
  163. package/dist/linalg/lu.d.ts +2 -1
  164. package/dist/linalg/lu.js +35 -5
  165. package/dist/linalg/matrix.d.ts +14 -0
  166. package/dist/linalg/matrix.js +24 -0
  167. package/dist/linalg/ops.js +60 -13
  168. package/dist/linalg/qr.d.ts +2 -1
  169. package/dist/linalg/qr.js +91 -23
  170. package/dist/linalg/schur.js +11 -3
  171. package/dist/linalg/solve.d.ts +6 -1
  172. package/dist/linalg/solve.js +147 -26
  173. package/dist/linalg/svd.d.ts +9 -2
  174. package/dist/linalg/svd.js +29 -11
  175. package/dist/linalg.js +2 -2
  176. package/dist/mixed.js +4 -4
  177. package/dist/models/anovaSequential.d.ts +16 -1
  178. package/dist/models/anovaSequential.js +124 -25
  179. package/dist/models/aovEz.js +140 -30
  180. package/dist/models/aovStrata.js +55 -22
  181. package/dist/models/carAnova.d.ts +1 -1
  182. package/dist/models/carAnova.js +83 -32
  183. package/dist/models/coxph.js +148 -66
  184. package/dist/models/estimable.d.ts +15 -0
  185. package/dist/models/estimable.js +68 -0
  186. package/dist/models/formula.d.ts +1 -1
  187. package/dist/models/formula.js +26 -8
  188. package/dist/models/glm.d.ts +35 -5
  189. package/dist/models/glm.js +398 -55
  190. package/dist/models/glmAnova.js +84 -13
  191. package/dist/models/glmConfint.d.ts +1 -1
  192. package/dist/models/glmConfint.js +115 -27
  193. package/dist/models/glmFamily.d.ts +10 -0
  194. package/dist/models/glmFamily.js +244 -40
  195. package/dist/models/lm.d.ts +12 -1
  196. package/dist/models/lm.js +235 -36
  197. package/dist/models/lmer.d.ts +20 -1
  198. package/dist/models/lmer.js +109 -27
  199. package/dist/models/lmerAnova.js +37 -4
  200. package/dist/models/lmerHypotheses.d.ts +6 -2
  201. package/dist/models/lmerHypotheses.js +14 -2
  202. package/dist/models/lmerTest.d.ts +9 -2
  203. package/dist/models/lmerTest.js +64 -19
  204. package/dist/models/mauchly.d.ts +4 -1
  205. package/dist/models/mauchly.js +34 -13
  206. package/dist/models/mixedStructure.js +6 -0
  207. package/dist/models/modelFrame.js +8 -2
  208. package/dist/models/modelMatrix.d.ts +3 -1
  209. package/dist/models/modelMatrix.js +40 -15
  210. package/dist/models/scaledTables.d.ts +8 -0
  211. package/dist/models/scaledTables.js +6 -0
  212. package/dist/models/survival.d.ts +6 -1
  213. package/dist/models/survival.js +67 -27
  214. package/dist/models/tiedTimes.d.ts +2 -0
  215. package/dist/models/tiedTimes.js +34 -0
  216. package/dist/numerics/deriv.d.ts +1 -1
  217. package/dist/numerics/deriv.js +64 -8
  218. package/dist/numerics/integrate.d.ts +9 -1
  219. package/dist/numerics/integrate.js +103 -16
  220. package/dist/numerics/interp.d.ts +8 -2
  221. package/dist/numerics/interp.js +352 -50
  222. package/dist/numerics/ode.js +55 -1
  223. package/dist/numerics.js +2 -2
  224. package/dist/optim/localmin.js +4 -0
  225. package/dist/optim/optim.d.ts +3 -1
  226. package/dist/optim/optim.js +80 -8
  227. package/dist/random/beta.js +53 -4
  228. package/dist/random/binomial.d.ts +14 -3
  229. package/dist/random/binomial.js +59 -24
  230. package/dist/random/continuous.js +33 -5
  231. package/dist/random/extra.js +42 -9
  232. package/dist/random/gamma.d.ts +4 -1
  233. package/dist/random/gamma.js +36 -8
  234. package/dist/random/hyper.js +9 -6
  235. package/dist/random/mt.js +17 -2
  236. package/dist/random/poisson.js +26 -3
  237. package/dist/random/r2dtable.d.ts +8 -1
  238. package/dist/random/r2dtable.js +24 -3
  239. package/dist/random/rank.d.ts +2 -0
  240. package/dist/random/rank.js +44 -4
  241. package/dist/random/sample.d.ts +12 -2
  242. package/dist/random/sample.js +57 -20
  243. package/dist/random/streams.js +4 -2
  244. package/dist/rstats.js +14 -14
  245. package/dist/special/besselIK.d.ts +12 -0
  246. package/dist/special/besselIK.js +168 -23
  247. package/dist/special/besselJY.d.ts +11 -1
  248. package/dist/special/besselJY.js +127 -19
  249. package/dist/special/besselSeries.d.ts +27 -0
  250. package/dist/special/besselSeries.js +45 -2
  251. package/dist/special/beta.js +4 -1
  252. package/dist/special/choose.js +17 -8
  253. package/dist/special/dd.js +122 -18
  254. package/dist/special/extra.js +14 -2
  255. package/dist/special/gamma.js +11 -2
  256. package/dist/special/incbet.js +30 -4
  257. package/dist/special/incbetTemme.d.ts +7 -0
  258. package/dist/special/incbetTemme.js +45 -12
  259. package/dist/special/loader.d.ts +1 -1
  260. package/dist/special/loader.js +117 -20
  261. package/dist/special/log1pmx.js +4 -0
  262. package/dist/special.js +2 -2
  263. package/dist/tests.js +11 -11
  264. package/llms.txt +12 -6
  265. package/package.json +1 -1
  266. package/dist/chunks/chunk-3THFTB36.js +0 -2
  267. package/dist/chunks/chunk-3TSWYE5L.js +0 -2
  268. package/dist/chunks/chunk-3WPU6LGK.js +0 -2
  269. package/dist/chunks/chunk-5ITR67MB.js +0 -2
  270. package/dist/chunks/chunk-5NRFU6F6.js +0 -2
  271. package/dist/chunks/chunk-E2LCSVQV.js +0 -2
  272. package/dist/chunks/chunk-FCNVTIPJ.js +0 -2
  273. package/dist/chunks/chunk-FKAKALOZ.js +0 -2
  274. package/dist/chunks/chunk-HD73UKPT.js +0 -2
  275. package/dist/chunks/chunk-IUULP3LE.js +0 -2
  276. package/dist/chunks/chunk-JQG3YQOC.js +0 -2
  277. package/dist/chunks/chunk-KT66SB7R.js +0 -2
  278. package/dist/chunks/chunk-MAUAOQG3.js +0 -2
  279. package/dist/chunks/chunk-MDYE7QP2.js +0 -2
  280. package/dist/chunks/chunk-NM3Z2UBQ.js +0 -2
  281. package/dist/chunks/chunk-PMJI5QO6.js +0 -3
  282. package/dist/chunks/chunk-UF7KOTHF.js +0 -3
  283. package/dist/chunks/chunk-UOE57JGT.js +0 -2
  284. package/dist/chunks/chunk-USPEBXSR.js +0 -2
  285. package/dist/chunks/chunk-ZIX7NYQF.js +0 -2
@@ -7,6 +7,7 @@
7
7
  // of lengths (each at most 1), so that wide and narrow intervals neither overflow nor underflow on the way.
8
8
  import { vectorize } from "../internal/vectorize.js";
9
9
  import { d0, dt0, dt1, quantileBoundaries } from "../internal/dpq.js";
10
+ import { midpoint } from "../internal/extremes.js";
10
11
  const MIN_NORMAL = 2 ** -1022;
11
12
  const valid = (a, b, c) => Number.isFinite(a) && Number.isFinite(b) && a < b && a <= c && c <= b;
12
13
  /** 1/2 when b - a overflows (x, a, b and c are all halved then; the probabilities do not change), else 1 */
@@ -110,20 +111,24 @@ export function qtriang1(p, a, b, c, lowerTail, logP) {
110
111
  // put x at the mode: qtriang(1.6e-8, { a: 0, b: 1.03e-316, c: 8.7e-317, lowerTail: false }))
111
112
  const cl = (c - a) / w;
112
113
  const cr = (b - c) / w;
114
+ // For a mode at an end the distance from it is w times the tail given (c = a: the lower one), which was 0 where that
115
+ // tail, exp(p), underflows: w exp(p / 2)^2 then, exp(p / 2) being normal (qtriang(-1000, { a: 0, b: 1e308, c: 0,
116
+ // logP: true }) was 0 for 2.5e-127; issue #121)
117
+ const tinyTail = logP && pv < 2 ** -1022;
113
118
  let x;
114
119
  if (cl > 0 && lower <= cl) {
115
120
  const t = lower / cl;
116
121
  x =
117
122
  t <= 0.5
118
123
  ? a + (lowerTail ? sqrtP : Math.sqrt(lower)) * Math.sqrt(w) * Math.sqrt(c - a)
119
- : c - ((c - a) * ((upper - cr) / cl)) / (1 + Math.sqrt(t));
124
+ : c - (cr === 0 && !lowerTail && tinyTail ? w * sqrtP * sqrtP : (c - a) * ((upper - cr) / cl)) / (1 + Math.sqrt(t));
120
125
  }
121
126
  else {
122
127
  const t = upper / cr;
123
128
  x =
124
129
  t <= 0.5
125
130
  ? b - (lowerTail ? Math.sqrt(upper) : sqrtP) * Math.sqrt(w) * Math.sqrt(b - c)
126
- : c + ((b - c) * ((lower - cl) / cr)) / (1 + Math.sqrt(t));
131
+ : c + (cl === 0 && lowerTail && tinyTail ? w * sqrtP * sqrtP : (b - c) * ((lower - cl) / cr)) / (1 + Math.sqrt(t));
127
132
  }
128
133
  // Rounding must not take x out of the support
129
134
  return Math.min(Math.max(x, a), b);
@@ -144,7 +149,7 @@ export function qtriang1(p, a, b, c, lowerTail, logP) {
144
149
  */
145
150
  export function dtriang(x, options = {}) {
146
151
  const { a = -1, b = 1, log = false } = options;
147
- const c = options.c ?? (a + b) / 2;
152
+ const c = options.c ?? midpoint(a, b);
148
153
  return vectorize(x, (v) => dtriang1(v, a, b, c, log));
149
154
  }
150
155
  /**
@@ -160,7 +165,7 @@ export function dtriang(x, options = {}) {
160
165
  */
161
166
  export function ptriang(q, options = {}) {
162
167
  const { a = -1, b = 1, lowerTail = true, logP = false } = options;
163
- const c = options.c ?? (a + b) / 2;
168
+ const c = options.c ?? midpoint(a, b);
164
169
  return vectorize(q, (v) => ptriang1(v, a, b, c, lowerTail, logP));
165
170
  }
166
171
  /**
@@ -176,6 +181,6 @@ export function ptriang(q, options = {}) {
176
181
  */
177
182
  export function qtriang(p, options = {}) {
178
183
  const { a = -1, b = 1, lowerTail = true, logP = false } = options;
179
- const c = options.c ?? (a + b) / 2;
184
+ const c = options.c ?? midpoint(a, b);
180
185
  return vectorize(p, (v) => qtriang1(v, a, b, c, lowerTail, logP));
181
186
  }
@@ -475,8 +475,11 @@ function logRangeCdf(w, k) {
475
475
  * (the range exceeds w essentially only when a single pair differs by more than w; the correction is below e^-833)
476
476
  */
477
477
  function logRangeCdfC(w, k) {
478
- if (w > 100)
479
- return Math.log(k * (k - 1)) + logPhiC(w / Math.SQRT2);
478
+ if (w > 100) {
479
+ // the number of pairs overflows above k ≈ 1.3e154: the sum of the logs only then (the same bits below)
480
+ const pairs = k * (k - 1);
481
+ return (Number.isFinite(pairs) ? Math.log(pairs) : Math.log(k) + Math.log(k - 1)) + logPhiC(w / Math.SQRT2);
482
+ }
480
483
  const lf = (z) => {
481
484
  const lP = logPhi(z);
482
485
  const lt = logPhiShift(z, w) - lP; // log(a / P)
@@ -34,6 +34,12 @@ function mulLarge(a, s) {
34
34
  }
35
35
  /** log(a / b) for positive finite a, b, also when a / b over- or underflows */
36
36
  function logRatio(a, b) {
37
+ // a and b within 2^-20 of each other: log1p of their exact difference (log(a / b) took the rounding of the ratio,
38
+ // half an ulp of 1, for its value of the order of the difference: dweibull(2^52 - 0.5, 2^52, { scale: 2^52 - 0.5,
39
+ // log: true }) was an ulp off, as R; issue #111). Elsewhere as R
40
+ const d = a - b;
41
+ if (Math.abs(d) <= b * 2 ** -20)
42
+ return Math.log1p(d / b);
37
43
  const r = a / b;
38
44
  return r >= MIN_NORMAL && r < Infinity ? Math.log(r) : Math.log(a) - Math.log(b);
39
45
  }
@@ -50,6 +56,10 @@ export function dweibull1(x, shape, scale, log) {
50
56
  if (x === 0 && shape < 1)
51
57
  return Infinity;
52
58
  if (!allFinite(shape, scale)) {
59
+ // scale = Inf moves all the probability out to infinity: the density at a finite x > 0 is 0 in the limit (shape
60
+ // (x / scale)^(shape - 1) / scale -> 0), where the formula gives Inf * 0 = NaN (as R does)
61
+ if (scale === Infinity && x > 0)
62
+ return d0(log);
53
63
  // The defining formula as is
54
64
  const t1 = cpow(x / scale, shape - 1);
55
65
  const t2 = t1 * (x / scale);
@@ -8,7 +8,9 @@ export declare function qwilcox1(p: number, m: number, n: number, lowerTail: boo
8
8
  *
9
9
  * Unlike R, memory use grows only with the range of the statistic (at most `m * n / 2`), so large samples such as `m = n = 500` work.
10
10
  *
11
- * @throws RangeError if `m` and `n` are so large that the required table cannot be allocated.
11
+ * @throws RangeError if `m` and `n` are so large that the required table cannot be allocated or would take more than
12
+ * 2^29 steps to build (min(m, n) times its length; about 6 to 8 s), or that the table loses its accuracy (near the
13
+ * center for m = n >= 550 or so; the tails stay available).
12
14
  *
13
15
  * @param x - Value(s) at which to evaluate: a number, `number[]` or `Float64Array`. The result has the same shape.
14
16
  * @param m - Size of the first sample.
@@ -30,7 +32,9 @@ export declare function dwilcox<T extends Vectorizable>(x: T, m: number, n: numb
30
32
  *
31
33
  * Unlike R, memory use grows only with the range of the statistic (at most `m * n / 2`), so large samples such as `m = n = 500` work.
32
34
  *
33
- * @throws RangeError if `m` and `n` are so large that the required table cannot be allocated.
35
+ * @throws RangeError if `m` and `n` are so large that the required table cannot be allocated or would take more than
36
+ * 2^29 steps to build (min(m, n) times its length; about 6 to 8 s), or that the table loses its accuracy (near the
37
+ * center for m = n >= 550 or so; the tails stay available).
34
38
  *
35
39
  * @param q - Quantile(s): a number, `number[]` or `Float64Array`. The result has the same shape.
36
40
  * @param m - Size of the first sample.
@@ -52,7 +56,9 @@ export declare function pwilcox<T extends Vectorizable>(q: T, m: number, n: numb
52
56
  *
53
57
  * Unlike R, memory use grows only with the range of the statistic (at most `m * n / 2`), so large samples such as `m = n = 500` work.
54
58
  *
55
- * @throws RangeError if `m` and `n` are so large that the required table cannot be allocated.
59
+ * @throws RangeError if `m` and `n` are so large that the required table cannot be allocated or would take more than
60
+ * 2^29 steps to build (min(m, n) times its length; about 6 to 8 s), or that the table loses its accuracy (near the
61
+ * center for m = n >= 550 or so; the tails stay available).
56
62
  *
57
63
  * @param p - Probability (or log probability with `logP`): a number, `number[]` or `Float64Array`. The result has the same shape.
58
64
  * @param m - Size of the first sample.
@@ -15,15 +15,37 @@
15
15
  // m = n = 150. The coefficients are kept in double-double (within 2.2e-16 relative of exact BigInt values up to
16
16
  // m = n = 300). Each step multiplies by i / (n + i) to stay on the probability scale (no division by
17
17
  // C(m+n, m) needed), and everything is scaled by 2^960 (so tail probabilities below 1e-308 are less likely to underflow).
18
+ // Where the largest entry of a pass falls below 2^760 (tables of the lower tail only, for large m and n), the table is
19
+ // multiplied by 2^200 (exact) and its scale kept, as for signrank: P[W = 0] = 1 / C(2100, 1050), about 1e-630,
20
+ // underflowed at the fixed scale (dwilcox(0, 1050, 1050, log = TRUE) was -Inf).
21
+ //
22
+ // Above the center of each pass the entries drift far from their true values (the cumulative sums amplify the
23
+ // errors pass after pass); the drift cancels in the final values as long as the entries stay representable, but beyond
24
+ // about m = n = 510 they overflow near the center. The entries below the first that overflows keep their accuracy
25
+ // (each depends only on those below it), so the table ends there and reading beyond it is a RangeError. Copying the
26
+ // lower side onto the upper one (the passes are symmetric) breaks the cancellation and loses accuracy (3.5e-8 at the
27
+ // center for m = n = 400); a method stable for large samples near the center remains to be found.
18
28
  import { vectorize } from "../internal/vectorize.js";
19
29
  import { d0, dt0, dt1, quantileBoundaries } from "../internal/dpq.js";
20
30
  import { discreteQuantile } from "../internal/discrete.js";
21
- import { nonInt, roundHalfEven } from "../internal/integer.js";
31
+ import { countAtMost, nonInt, roundHalfEven } from "../internal/integer.js";
22
32
  import { qnorm } from "./normal.js";
23
33
  /** Scale 2^STORE_SCALE applied to the coefficients (small enough that the 2^27 factor of Veltkamp splitting does not overflow) */
24
34
  const STORE_SCALE = 960;
35
+ /** Largest table entry the passes can take (2^27 + 1 times it, in Veltkamp splitting, must not overflow) */
36
+ const MAX_ENTRY = 2 ** 996;
25
37
  /** Maximum table length (computations needing more throw RangeError; about 800 MB for the three arrays during construction) */
26
38
  const MAX_LEN = 2 ** 25;
39
+ /**
40
+ * Maximum work of a table, its length times the m passes (m <= n): about 10 to 15 ns per entry and pass on the
41
+ * development machine, so about 6 to 8 s (pwilcox(2e5, 3000, 3000) took 5 s; m = n = 1e5 at q = 1e6 about 20 minutes)
42
+ */
43
+ const MAX_WORK = 2 ** 29;
44
+ /** Where the largest entry of a pass falls below RESCALE_BELOW, the table is multiplied by 2^RESCALE_STEP */
45
+ const RESCALE_BELOW = 2 ** 760;
46
+ const RESCALE_STEP = 200;
47
+ /** An entry below this has lost digits (its low part, 2^-53 of it, is below the smallest normal number) */
48
+ const LOST_BELOW = 2 ** -969;
27
49
  const SPLITTER = 134217729; // 2^27 + 1
28
50
  /**
29
51
  * Tables are cached per (m, n). When the total number of entries exceeds CACHE_BUDGET, the oldest are evicted
@@ -37,11 +59,19 @@ function buildTable(m, n, J) {
37
59
  if (J + 1 > MAX_LEN) {
38
60
  throw new RangeError(`wilcox: m = ${m}, n = ${n} needs too large a table (${J + 1} entries)`);
39
61
  }
62
+ if (m * (J + 1) > MAX_WORK) {
63
+ throw new RangeError(`wilcox: m = ${m}, n = ${n} needs ${m * (J + 1)} steps for a table of ${J + 1} entries (at most 2^29)`);
64
+ }
40
65
  const H = new Float64Array(J + 1);
41
66
  const L = new Float64Array(J + 1);
42
67
  H[0] = 2 ** STORE_SCALE;
68
+ let scale = STORE_SCALE;
69
+ // scale at the first pass where an entry lost digits
70
+ let lossScale = NaN;
71
+ // entries from end on broke down (see below) and are no longer computed
72
+ let end = J + 1;
43
73
  for (let i = 1; i <= m; i++) {
44
- const top = Math.min(J, i * n);
74
+ let top = Math.min(end - 1, i * n);
45
75
  // Multiply by i / (n + i) (double-double; i is an integer, so the product splits exactly)
46
76
  const d = n + i;
47
77
  let t = SPLITTER * i;
@@ -54,6 +84,16 @@ function buildTable(m, n, J) {
54
84
  const a = H[j];
55
85
  if (a === 0)
56
86
  continue;
87
+ // Above the center of a pass the entries are far off the true (small) values: the errors of the cumulative sums
88
+ // grow pass after pass, and cancel only in the final values, as long as they stay representable (m = n = 500,
89
+ // the table to the center: up to 2^990.7, the results within 1e-15 of the exact ones). Beyond 2^996 the splitting
90
+ // below overflows and the values become NaN (m = n >= 550 near the center). Each entry depends only on those
91
+ // below it, so the entries below j keep their accuracy: the table ends there (reading beyond it is an error)
92
+ if (!(Math.abs(a) <= MAX_ENTRY)) {
93
+ end = j;
94
+ top = j - 1;
95
+ break;
96
+ }
57
97
  // (a + L[j]) × i
58
98
  const ph = a * i;
59
99
  t = SPLITTER * a;
@@ -71,6 +111,8 @@ function buildTable(m, n, J) {
71
111
  const s = q1 + q2;
72
112
  L[j] = q2 - (s - q1);
73
113
  H[j] = s;
114
+ if (Math.abs(s) < LOST_BELOW && Number.isNaN(lossScale))
115
+ lossScale = scale;
74
116
  }
75
117
  // Multiply by (1 - q^{n+i}): in descending order P[j] -= P[j - n - i] (the right side still holds old values)
76
118
  const sh = n + i;
@@ -79,13 +121,28 @@ function buildTable(m, n, J) {
79
121
  // Divide by (1 - q^i): in ascending order P[j] += P[j - i] (the right side already holds new values)
80
122
  for (let j = i; j <= top; j++)
81
123
  ddAddInto(H, L, j, j - i, 1);
124
+ // The coefficients of a pass are unimodal: keep the largest within range (exact powers of 2)
125
+ const center = Math.min(top, Math.floor((i * n) / 2));
126
+ while (center >= 0 && H[center] > 0 && H[center] < RESCALE_BELOW) {
127
+ const f = 2 ** RESCALE_STEP;
128
+ for (let j = 0; j <= top; j++) {
129
+ H[j] *= f;
130
+ L[j] *= f;
131
+ }
132
+ scale += RESCALE_STEP;
133
+ }
82
134
  }
83
135
  const cum = new Float64Array(J + 1);
84
136
  let ch = 0;
85
137
  let cl = 0;
86
- for (let j = 0; j <= J; j++) {
138
+ for (let j = 0; j < end; j++) {
87
139
  // (ch, cl) += (H[j], L[j])
88
140
  const a = H[j];
141
+ // (the last pass, which no multiplication checks)
142
+ if (!(Math.abs(a) <= MAX_ENTRY)) {
143
+ end = j;
144
+ break;
145
+ }
89
146
  const s = ch + a;
90
147
  const bb = s - ch;
91
148
  let e = ch - (s - bb) + (a - bb);
@@ -94,7 +151,12 @@ function buildTable(m, n, J) {
94
151
  cl = e - (ch - s);
95
152
  cum[j] = ch;
96
153
  }
97
- return { m, n, len: J + 1, prob: H, cum };
154
+ // The loss of an entry (below 2^-1022 absolute, at the scale of its pass) is propagated by the later passes, which
155
+ // amplify relative errors by up to about 2^53 (the accuracy of the double-double table); 2^60 more for a margin
156
+ const minTrusted = Number.isNaN(lossScale)
157
+ ? 0
158
+ : 2 ** Math.min(1023, -1022 + 113 + Math.ceil(Math.log2(m * (J + 1))) + scale - lossScale);
159
+ return { m, n, len: J + 1, prob: H, cum, scale, minTrusted, valid: end };
98
160
  }
99
161
  /** (H[j], L[j]) += sign × (H[k], L[k]) */
100
162
  function ddAddInto(H, L, j, k, sign) {
@@ -108,11 +170,9 @@ function ddAddInto(H, L, j, k, sign) {
108
170
  L[j] = e - (r - s);
109
171
  H[j] = r;
110
172
  }
111
- /** Table for (m, n) usable for s <= J */
112
- function table(m, n, J) {
113
- if (m > n)
114
- [m, n] = [n, m];
115
- const key = `${m},${n}`;
173
+ /** Table for (m, n) (m <= n) usable for s <= J; with low, the low table (see tableValue) */
174
+ function table(m, n, J, low = false) {
175
+ const key = `${m},${n}${low ? ",low" : ""}`;
116
176
  const old = cache.get(key);
117
177
  if (old !== undefined && old.len > J) {
118
178
  cache.delete(key);
@@ -120,9 +180,14 @@ function table(m, n, J) {
120
180
  return old;
121
181
  }
122
182
  const half = Math.floor((m * n) / 2);
123
- // Growing a little at a time would cause repeated rebuilds, so double the size
124
- const want = Math.min(half, Math.max(J, old === undefined ? 0 : 2 * old.len));
125
- const t = buildTable(m, n, want);
183
+ // Growing a little at a time would cause repeated rebuilds, so double the size (not beyond MAX_WORK, where s <= J
184
+ // alone is within it)
185
+ const grown = old === undefined ? 0 : Math.min(2 * old.len, Math.floor(MAX_WORK / m) - 1);
186
+ const want = Math.min(half, Math.max(J, grown));
187
+ return store(key, buildTable(m, n, want), old);
188
+ }
189
+ /** Put t in the cache under key (replacing old) and evict the oldest tables beyond the budget */
190
+ function store(key, t, old) {
126
191
  if (old !== undefined) {
127
192
  cache.delete(key);
128
193
  cached -= old.len;
@@ -137,12 +202,60 @@ function table(m, n, J) {
137
202
  }
138
203
  return t;
139
204
  }
140
- function toProb(v, log) {
141
- const p = v * 2 ** -(STORE_SCALE / 2) * 2 ** -(STORE_SCALE / 2);
205
+ /**
206
+ * The probability (cum false) or cumulative probability (cum true) at s for (m, n), as a table value with its table.
207
+ * A table built far beyond s may have lost the digits of its low entries (it was rescaled for its large ones), so a
208
+ * value outside the bound of buildTable is read from the low table of (m, n) instead, built only as far as needed,
209
+ * and failing that from a table rebuilt up to s: its last entry is the largest of the last pass.
210
+ */
211
+ function tableValue(m, n, s, cum) {
212
+ if (m > n)
213
+ [m, n] = [n, m];
214
+ const read = (t) => {
215
+ if (s >= t.valid) {
216
+ throw new RangeError(`wilcox: the exact distribution for m = ${m}, n = ${n} cannot be computed accurately at ${s} (from ${t.valid} on, near the center of large samples)`);
217
+ }
218
+ return (cum ? t.cum : t.prob)[s];
219
+ };
220
+ const trusted = (t, v) => s === t.len - 1 || v >= (cum ? (s + 1) * t.minTrusted : t.minTrusted);
221
+ let t = table(m, n, s);
222
+ let v = read(t);
223
+ if (trusted(t, v))
224
+ return [v, t];
225
+ t = table(m, n, s, true);
226
+ v = read(t);
227
+ if (trusted(t, v))
228
+ return [v, t];
229
+ const key = `${m},${n},low`;
230
+ t = store(key, buildTable(m, n, s), cache.get(key));
231
+ return [read(t), t];
232
+ }
233
+ /** ln 2 in two parts, the first with 32 trailing zero bits (k ln 2 exact in the first part for abs(k) < 2^20) */
234
+ const LN2_HI = 6.93147180369123816490e-1;
235
+ const LN2_LO = 1.90821492927058770002e-10;
236
+ /** The probability v 2^-scale of the table value v (underflow only at the final step) */
237
+ function toProb(v, t, log) {
238
+ const e = -t.scale;
239
+ const e1 = Math.trunc(e / 2);
240
+ const p = v * 2 ** e1 * 2 ** (e - e1);
142
241
  if (!log)
143
242
  return p;
144
- // log(v) - 960 log 2 loses digits since both terms are large, so use log(p) if the probability is a normal number
145
- return p >= 1e-300 ? Math.log(p) : Math.log(v) - STORE_SCALE * Math.LN2;
243
+ if (p >= 1e-300)
244
+ return Math.log(p);
245
+ // Otherwise from the significand m in [1, 2) and the exponent k of v: log m + (k + e) log 2, the last in two parts
246
+ // (log(v) - scale log 2 lost digits to the cancellation of large terms), the same bits whatever the table's scale
247
+ let k = Math.floor(Math.log2(v));
248
+ const k1 = Math.trunc(k / 2);
249
+ let mv = v * 2 ** -k1 * 2 ** -(k - k1);
250
+ if (mv >= 2) {
251
+ mv /= 2;
252
+ k++;
253
+ }
254
+ else if (mv < 1) {
255
+ mv *= 2;
256
+ k--;
257
+ }
258
+ return (k + e) * LN2_HI + (Math.log(mv) + (k + e) * LN2_LO);
146
259
  }
147
260
  /** Check and round m, n. undefined if invalid */
148
261
  function wilcoxParams(m, n) {
@@ -150,7 +263,13 @@ function wilcoxParams(m, n) {
150
263
  return undefined;
151
264
  m = roundHalfEven(m);
152
265
  n = roundHalfEven(n);
153
- return m <= 0 || n <= 0 ? undefined : [m, n];
266
+ // The statistic ranges over 0..mn: beyond 2^53 its values are not all doubles (NaN, as other integer supports past
267
+ // 2^53). This also bounds the smaller of m and n by 2^26.5, the number of passes of the table (dwilcox(0, 1e12,
268
+ // 1e12) ran 1e12 of them for a table of one entry). An exact product of 2^53 + 1 rounds down to 2^53 (and would be
269
+ // taken as the end of the support), so a rounded 2^53 is checked exactly
270
+ if (m <= 0 || n <= 0 || m * n > 2 ** 53)
271
+ return undefined;
272
+ return m * n === 2 ** 53 && BigInt(m) * BigInt(n) !== 2n ** 53n ? undefined : [m, n];
154
273
  }
155
274
  export function dwilcox1(x, m, n, log) {
156
275
  if (Number.isNaN(x) || Number.isNaN(m) || Number.isNaN(n))
@@ -166,7 +285,8 @@ export function dwilcox1(x, m, n, log) {
166
285
  if (x < 0 || x > total)
167
286
  return d0(log);
168
287
  const s = Math.min(x, total - x);
169
- return toProb(table(m, n, s).prob[s], log);
288
+ const [v, t] = tableValue(m, n, s, false);
289
+ return toProb(v, t, log);
170
290
  }
171
291
  /** P[W <= x] (lower) / P[W > x] (0 <= x < mn, x an integer) */
172
292
  function pwilcoxRaw(x, m, n, lowerTail, logP) {
@@ -174,10 +294,13 @@ function pwilcoxRaw(x, m, n, lowerTail, logP) {
174
294
  // P[W > x] = P[W <= mn - x - 1] (symmetry). Read the smaller tail directly from the table
175
295
  const direct = lowerTail ? x : total - x - 1;
176
296
  const other = lowerTail ? total - x - 1 : x;
177
- if (direct <= other)
178
- return toProb(table(m, n, direct).cum[direct], logP);
179
- const v = toProb(table(m, n, other).cum[other], false);
180
- return logP ? Math.log1p(-v) : 1 - v;
297
+ if (direct <= other) {
298
+ const [v, t] = tableValue(m, n, direct, true);
299
+ return toProb(v, t, logP);
300
+ }
301
+ const [v, t] = tableValue(m, n, other, true);
302
+ const p = toProb(v, t, false);
303
+ return logP ? Math.log1p(-p) : 1 - p;
181
304
  }
182
305
  export function pwilcox1(q, m, n, lowerTail, logP) {
183
306
  if (Number.isNaN(q) || Number.isNaN(m) || Number.isNaN(n))
@@ -186,7 +309,7 @@ export function pwilcox1(q, m, n, lowerTail, logP) {
186
309
  if (params === undefined)
187
310
  return NaN;
188
311
  [m, n] = params;
189
- const x = Math.floor(q + 1e-7);
312
+ const x = countAtMost(q);
190
313
  if (x < 0)
191
314
  return dt0(lowerTail, logP);
192
315
  if (x >= m * n)
@@ -222,7 +345,9 @@ export function qwilcox1(p, m, n, lowerTail, logP) {
222
345
  *
223
346
  * Unlike R, memory use grows only with the range of the statistic (at most `m * n / 2`), so large samples such as `m = n = 500` work.
224
347
  *
225
- * @throws RangeError if `m` and `n` are so large that the required table cannot be allocated.
348
+ * @throws RangeError if `m` and `n` are so large that the required table cannot be allocated or would take more than
349
+ * 2^29 steps to build (min(m, n) times its length; about 6 to 8 s), or that the table loses its accuracy (near the
350
+ * center for m = n >= 550 or so; the tails stay available).
226
351
  *
227
352
  * @param x - Value(s) at which to evaluate: a number, `number[]` or `Float64Array`. The result has the same shape.
228
353
  * @param m - Size of the first sample.
@@ -247,7 +372,9 @@ export function dwilcox(x, m, n, options = {}) {
247
372
  *
248
373
  * Unlike R, memory use grows only with the range of the statistic (at most `m * n / 2`), so large samples such as `m = n = 500` work.
249
374
  *
250
- * @throws RangeError if `m` and `n` are so large that the required table cannot be allocated.
375
+ * @throws RangeError if `m` and `n` are so large that the required table cannot be allocated or would take more than
376
+ * 2^29 steps to build (min(m, n) times its length; about 6 to 8 s), or that the table loses its accuracy (near the
377
+ * center for m = n >= 550 or so; the tails stay available).
251
378
  *
252
379
  * @param q - Quantile(s): a number, `number[]` or `Float64Array`. The result has the same shape.
253
380
  * @param m - Size of the first sample.
@@ -272,7 +399,9 @@ export function pwilcox(q, m, n, options = {}) {
272
399
  *
273
400
  * Unlike R, memory use grows only with the range of the statistic (at most `m * n / 2`), so large samples such as `m = n = 500` work.
274
401
  *
275
- * @throws RangeError if `m` and `n` are so large that the required table cannot be allocated.
402
+ * @throws RangeError if `m` and `n` are so large that the required table cannot be allocated or would take more than
403
+ * 2^29 steps to build (min(m, n) times its length; about 6 to 8 s), or that the table loses its accuracy (near the
404
+ * center for m = n >= 550 or so; the tails stay available).
276
405
  *
277
406
  * @param p - Probability (or log probability with `logP`): a number, `number[]` or `Float64Array`. The result has the same shape.
278
407
  * @param m - Size of the first sample.