@numero-uno-jpn/rstats 0.15.3 → 0.17.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 (322) hide show
  1. package/CHANGELOG.md +294 -0
  2. package/README.ja.md +68 -35
  3. package/README.md +65 -30
  4. package/dist/chunks/chunk-2C33MXSW.js +3 -0
  5. package/dist/chunks/chunk-34S5SQY6.js +2 -0
  6. package/dist/chunks/chunk-4WE3OO62.js +2 -0
  7. package/dist/chunks/chunk-5AYHCITP.js +2 -0
  8. package/dist/chunks/chunk-6JJQL6HL.js +2 -0
  9. package/dist/chunks/chunk-C7V2FH6L.js +3 -0
  10. package/dist/chunks/chunk-CZI7KUO3.js +2 -0
  11. package/dist/chunks/chunk-DXI5N2ET.js +2 -0
  12. package/dist/chunks/chunk-FY3FVOBM.js +2 -0
  13. package/dist/chunks/chunk-H3WVPZDL.js +2 -0
  14. package/dist/chunks/chunk-LHUIJQHY.js +2 -0
  15. package/dist/chunks/chunk-LV3W2F7N.js +2 -0
  16. package/dist/chunks/chunk-M4ITG7YR.js +2 -0
  17. package/dist/chunks/chunk-NSYZTS26.js +2 -0
  18. package/dist/chunks/chunk-ONY5CISH.js +2 -0
  19. package/dist/chunks/chunk-RFE7MVP7.js +2 -0
  20. package/dist/chunks/chunk-SE7V2KLO.js +2 -0
  21. package/dist/chunks/chunk-THIGHOKK.js +2 -0
  22. package/dist/chunks/chunk-TNMJPQPV.js +2 -0
  23. package/dist/chunks/chunk-WM7VFXTV.js +2 -0
  24. package/dist/chunks/chunk-WMDYDTVQ.js +2 -0
  25. package/dist/chunks/chunk-XLSFJTTK.js +2 -0
  26. package/dist/chunks/chunk-Z37NELOS.js +2 -0
  27. package/dist/chunks/chunk-ZFQWB222.js +2 -0
  28. package/dist/data/grouping.js +26 -7
  29. package/dist/descriptive/basic.js +110 -8
  30. package/dist/descriptive/cov.js +23 -4
  31. package/dist/descriptive/dataFrames.d.ts +4 -2
  32. package/dist/descriptive/dataFrames.js +69 -23
  33. package/dist/descriptive/factanal.d.ts +2 -0
  34. package/dist/descriptive/factanal.js +26 -9
  35. package/dist/descriptive/hist.d.ts +8 -5
  36. package/dist/descriptive/hist.js +77 -31
  37. package/dist/descriptive/missing.js +3 -1
  38. package/dist/descriptive/moments.js +86 -19
  39. package/dist/descriptive/omega.d.ts +1 -1
  40. package/dist/descriptive/omega.js +74 -10
  41. package/dist/descriptive/pivot.d.ts +25 -10
  42. package/dist/descriptive/pivot.js +182 -42
  43. package/dist/descriptive/quantile.js +10 -1
  44. package/dist/descriptive/rank.js +8 -1
  45. package/dist/descriptive/table.d.ts +23 -3
  46. package/dist/descriptive/table.js +36 -21
  47. package/dist/descriptive.js +2 -2
  48. package/dist/distributions/arcsine.js +27 -2
  49. package/dist/distributions/beta.js +33 -4
  50. package/dist/distributions/binomial.js +46 -14
  51. package/dist/distributions/bvnorm.js +11 -2
  52. package/dist/distributions/cauchy.js +21 -4
  53. package/dist/distributions/chisq.js +16 -3
  54. package/dist/distributions/exponential.js +14 -0
  55. package/dist/distributions/f.js +41 -17
  56. package/dist/distributions/gamma.js +35 -3
  57. package/dist/distributions/geometric.js +58 -13
  58. package/dist/distributions/hypergeometric.d.ts +5 -1
  59. package/dist/distributions/hypergeometric.js +101 -6
  60. package/dist/distributions/invgamma.js +10 -1
  61. package/dist/distributions/kumaraswamy.js +9 -0
  62. package/dist/distributions/laplace.js +36 -6
  63. package/dist/distributions/logistic.js +13 -1
  64. package/dist/distributions/lognormal.js +16 -2
  65. package/dist/distributions/multinomial.js +58 -11
  66. package/dist/distributions/nbeta.js +62 -11
  67. package/dist/distributions/nchisq.js +30 -6
  68. package/dist/distributions/negbinomial.js +102 -17
  69. package/dist/distributions/normal.js +17 -4
  70. package/dist/distributions/nt.js +392 -17
  71. package/dist/distributions/pareto.js +12 -1
  72. package/dist/distributions/poisson.js +37 -3
  73. package/dist/distributions/signrank.js +16 -4
  74. package/dist/distributions/summary.d.ts +2 -1
  75. package/dist/distributions/summary.js +481 -61
  76. package/dist/distributions/t.js +9 -0
  77. package/dist/distributions/triangular.js +19 -5
  78. package/dist/distributions/tukey.js +11 -2
  79. package/dist/distributions/uniform.js +8 -0
  80. package/dist/distributions/weibull.js +18 -0
  81. package/dist/distributions/wilcox.d.ts +9 -3
  82. package/dist/distributions/wilcox.js +164 -26
  83. package/dist/distributions.js +2 -2
  84. package/dist/entries/descriptive.d.ts +3 -1
  85. package/dist/entries/descriptive.js +1 -1
  86. package/dist/entries/distributions.d.ts +1 -0
  87. package/dist/entries/distributions.js +2 -0
  88. package/dist/entries/linalg.d.ts +3 -1
  89. package/dist/entries/mixed.d.ts +3 -0
  90. package/dist/entries/mixed.js +2 -0
  91. package/dist/entries/numerics.d.ts +2 -1
  92. package/dist/entries/tests.d.ts +8 -5
  93. package/dist/entries/tests.js +3 -1
  94. package/dist/htest/agreement.d.ts +16 -2
  95. package/dist/htest/agreement.js +122 -21
  96. package/dist/htest/ansariTest.d.ts +8 -2
  97. package/dist/htest/ansariTest.js +116 -18
  98. package/dist/htest/aov.d.ts +29 -23
  99. package/dist/htest/aov.js +90 -47
  100. package/dist/htest/binomTest.d.ts +5 -0
  101. package/dist/htest/binomTest.js +47 -17
  102. package/dist/htest/brunnerMunzelTest.d.ts +4 -3
  103. package/dist/htest/brunnerMunzelTest.js +12 -5
  104. package/dist/htest/chisqTest.d.ts +5 -2
  105. package/dist/htest/chisqTest.js +151 -46
  106. package/dist/htest/cor.d.ts +9 -2
  107. package/dist/htest/cor.js +57 -26
  108. package/dist/htest/core/ansari.d.ts +9 -0
  109. package/dist/htest/core/ansari.js +21 -1
  110. package/dist/htest/core/kolmogorov.d.ts +25 -0
  111. package/dist/htest/core/kolmogorov.js +123 -0
  112. package/dist/htest/core/mantelhaen.js +6 -4
  113. package/dist/htest/core/shapiro.d.ts +1 -1
  114. package/dist/htest/core/shapiro.js +5 -1
  115. package/dist/htest/core/simulate.d.ts +6 -0
  116. package/dist/htest/core/simulate.js +20 -0
  117. package/dist/htest/dunnett.js +14 -5
  118. package/dist/htest/effectSize.d.ts +5 -0
  119. package/dist/htest/effectSize.js +117 -35
  120. package/dist/htest/fisherTest.d.ts +4 -3
  121. package/dist/htest/fisherTest.js +88 -24
  122. package/dist/htest/groups.d.ts +7 -0
  123. package/dist/htest/groups.js +21 -4
  124. package/dist/htest/ksTest.d.ts +7 -1
  125. package/dist/htest/ksTest.js +36 -6
  126. package/dist/htest/leveneTest.d.ts +2 -0
  127. package/dist/htest/leveneTest.js +28 -6
  128. package/dist/htest/mantelhaenTest.js +132 -25
  129. package/dist/htest/mcnemarTest.js +40 -11
  130. package/dist/htest/multipleComparisons.d.ts +24 -26
  131. package/dist/htest/multipleComparisons.js +70 -64
  132. package/dist/htest/normalityTests.js +54 -14
  133. package/dist/htest/onewayTest.js +106 -5
  134. package/dist/htest/pAdjust.d.ts +3 -2
  135. package/dist/htest/pAdjust.js +42 -6
  136. package/dist/htest/pairwise.d.ts +3 -1
  137. package/dist/htest/pairwise.js +46 -21
  138. package/dist/htest/poissonTest.d.ts +1 -1
  139. package/dist/htest/poissonTest.js +117 -59
  140. package/dist/htest/polycor.js +47 -17
  141. package/dist/htest/power.d.ts +15 -1
  142. package/dist/htest/power.js +128 -10
  143. package/dist/htest/propTest.d.ts +3 -0
  144. package/dist/htest/propTest.js +44 -6
  145. package/dist/htest/pwr.d.ts +38 -1
  146. package/dist/htest/pwr.js +159 -39
  147. package/dist/htest/rankTests.js +36 -6
  148. package/dist/htest/tTest.d.ts +2 -0
  149. package/dist/htest/tTest.js +53 -21
  150. package/dist/htest/testFormula.js +11 -11
  151. package/dist/htest/trendTests.d.ts +28 -4
  152. package/dist/htest/trendTests.js +124 -35
  153. package/dist/htest/types.d.ts +7 -0
  154. package/dist/htest/types.js +7 -0
  155. package/dist/htest/varTest.js +52 -14
  156. package/dist/htest/wilcoxTest.js +164 -29
  157. package/dist/integrate/quadpack.js +27 -5
  158. package/dist/internal/checkOptions.d.ts +11 -0
  159. package/dist/internal/checkOptions.js +31 -0
  160. package/dist/internal/covmat.d.ts +5 -0
  161. package/dist/internal/covmat.js +20 -0
  162. package/dist/internal/ddexp.d.ts +15 -1
  163. package/dist/internal/ddexp.js +59 -6
  164. package/dist/internal/discrete.d.ts +14 -0
  165. package/dist/internal/discrete.js +78 -5
  166. package/dist/internal/extremes.d.ts +9 -0
  167. package/dist/internal/extremes.js +24 -0
  168. package/dist/internal/fround.js +13 -4
  169. package/dist/internal/integer.d.ts +9 -0
  170. package/dist/internal/integer.js +12 -0
  171. package/dist/internal/invert.js +15 -2
  172. package/dist/internal/optionalArgs.d.ts +12 -0
  173. package/dist/internal/optionalArgs.js +46 -0
  174. package/dist/internal/scaledInverse.d.ts +10 -0
  175. package/dist/internal/scaledInverse.js +22 -0
  176. package/dist/internal/seq.js +15 -2
  177. package/dist/internal/summary.d.ts +90 -0
  178. package/dist/internal/summary.js +458 -39
  179. package/dist/internal/uniroot.d.ts +7 -0
  180. package/dist/internal/uniroot.js +28 -3
  181. package/dist/internal/warnings.d.ts +66 -0
  182. package/dist/internal/warnings.js +122 -0
  183. package/dist/linalg/basic.d.ts +3 -1
  184. package/dist/linalg/basic.js +58 -7
  185. package/dist/linalg/chol.js +10 -1
  186. package/dist/linalg/dot.d.ts +29 -0
  187. package/dist/linalg/dot.js +132 -0
  188. package/dist/linalg/eigen.d.ts +6 -1
  189. package/dist/linalg/eigen.js +75 -14
  190. package/dist/linalg/expm.d.ts +3 -2
  191. package/dist/linalg/expm.js +113 -15
  192. package/dist/linalg/kappa.js +64 -10
  193. package/dist/linalg/lu.d.ts +2 -1
  194. package/dist/linalg/lu.js +40 -5
  195. package/dist/linalg/matrix.d.ts +14 -0
  196. package/dist/linalg/matrix.js +24 -0
  197. package/dist/linalg/norm.js +4 -0
  198. package/dist/linalg/ops.d.ts +27 -2
  199. package/dist/linalg/ops.js +74 -26
  200. package/dist/linalg/qr.d.ts +2 -1
  201. package/dist/linalg/qr.js +105 -23
  202. package/dist/linalg/schur.js +11 -3
  203. package/dist/linalg/solve.d.ts +6 -1
  204. package/dist/linalg/solve.js +156 -26
  205. package/dist/linalg/svd.d.ts +9 -2
  206. package/dist/linalg/svd.js +33 -11
  207. package/dist/linalg.js +2 -2
  208. package/dist/mixed.js +4 -4
  209. package/dist/models/anovaSequential.d.ts +32 -2
  210. package/dist/models/anovaSequential.js +170 -28
  211. package/dist/models/aovEz.js +154 -39
  212. package/dist/models/aovStrata.js +68 -24
  213. package/dist/models/carAnova.d.ts +1 -1
  214. package/dist/models/carAnova.js +78 -33
  215. package/dist/models/coxph.d.ts +6 -0
  216. package/dist/models/coxph.js +166 -69
  217. package/dist/models/estimable.d.ts +15 -0
  218. package/dist/models/estimable.js +68 -0
  219. package/dist/models/formula.d.ts +1 -1
  220. package/dist/models/formula.js +26 -8
  221. package/dist/models/glm.d.ts +57 -7
  222. package/dist/models/glm.js +427 -74
  223. package/dist/models/glmAnova.js +90 -14
  224. package/dist/models/glmConfint.d.ts +1 -1
  225. package/dist/models/glmConfint.js +121 -29
  226. package/dist/models/glmFamily.d.ts +11 -6
  227. package/dist/models/glmFamily.js +247 -62
  228. package/dist/models/lm.d.ts +12 -1
  229. package/dist/models/lm.js +246 -37
  230. package/dist/models/lmer.d.ts +31 -7
  231. package/dist/models/lmer.js +129 -42
  232. package/dist/models/lmerAnova.d.ts +3 -3
  233. package/dist/models/lmerAnova.js +47 -9
  234. package/dist/models/lmerHypotheses.d.ts +6 -2
  235. package/dist/models/lmerHypotheses.js +14 -2
  236. package/dist/models/lmerTest.d.ts +13 -6
  237. package/dist/models/lmerTest.js +82 -29
  238. package/dist/models/mauchly.d.ts +6 -1
  239. package/dist/models/mauchly.js +41 -15
  240. package/dist/models/mixedStructure.js +6 -0
  241. package/dist/models/modelFrame.js +10 -4
  242. package/dist/models/modelMatrix.d.ts +3 -1
  243. package/dist/models/modelMatrix.js +47 -17
  244. package/dist/models/scaledTables.d.ts +8 -0
  245. package/dist/models/scaledTables.js +6 -0
  246. package/dist/models/survival.d.ts +12 -1
  247. package/dist/models/survival.js +75 -28
  248. package/dist/models/tiedTimes.d.ts +2 -0
  249. package/dist/models/tiedTimes.js +34 -0
  250. package/dist/numerics/deriv.d.ts +1 -1
  251. package/dist/numerics/deriv.js +72 -8
  252. package/dist/numerics/integrate.d.ts +9 -1
  253. package/dist/numerics/integrate.js +111 -16
  254. package/dist/numerics/interp.d.ts +40 -9
  255. package/dist/numerics/interp.js +375 -55
  256. package/dist/numerics/ode.js +59 -1
  257. package/dist/numerics.js +2 -2
  258. package/dist/optim/localmin.js +4 -0
  259. package/dist/optim/optim.d.ts +3 -1
  260. package/dist/optim/optim.js +97 -10
  261. package/dist/random/beta.js +58 -4
  262. package/dist/random/binomial.d.ts +14 -3
  263. package/dist/random/binomial.js +59 -24
  264. package/dist/random/continuous.js +50 -5
  265. package/dist/random/extra.js +55 -9
  266. package/dist/random/gamma.d.ts +4 -1
  267. package/dist/random/gamma.js +47 -8
  268. package/dist/random/hyper.js +9 -6
  269. package/dist/random/mt.js +17 -2
  270. package/dist/random/poisson.js +31 -3
  271. package/dist/random/r2dtable.d.ts +8 -1
  272. package/dist/random/r2dtable.js +24 -3
  273. package/dist/random/rank.d.ts +2 -0
  274. package/dist/random/rank.js +44 -4
  275. package/dist/random/rng.js +4 -0
  276. package/dist/random/sample.d.ts +12 -2
  277. package/dist/random/sample.js +63 -20
  278. package/dist/random/streams.js +4 -2
  279. package/dist/rstats.js +17 -14
  280. package/dist/special/besselIK.d.ts +12 -0
  281. package/dist/special/besselIK.js +175 -23
  282. package/dist/special/besselJY.d.ts +11 -1
  283. package/dist/special/besselJY.js +127 -19
  284. package/dist/special/besselSeries.d.ts +27 -0
  285. package/dist/special/besselSeries.js +45 -2
  286. package/dist/special/beta.js +4 -1
  287. package/dist/special/choose.js +24 -8
  288. package/dist/special/dd.js +122 -18
  289. package/dist/special/extra.js +14 -2
  290. package/dist/special/gamma.js +11 -2
  291. package/dist/special/incbet.js +30 -4
  292. package/dist/special/incbetTemme.d.ts +7 -0
  293. package/dist/special/incbetTemme.js +45 -12
  294. package/dist/special/loader.d.ts +1 -1
  295. package/dist/special/loader.js +117 -20
  296. package/dist/special/log1pmx.js +4 -0
  297. package/dist/special/psigamma.js +7 -0
  298. package/dist/special.js +2 -2
  299. package/dist/tests.js +15 -11
  300. package/llms.txt +15 -6
  301. package/package.json +19 -10
  302. package/dist/chunks/chunk-3THFTB36.js +0 -2
  303. package/dist/chunks/chunk-3TSWYE5L.js +0 -2
  304. package/dist/chunks/chunk-3WPU6LGK.js +0 -2
  305. package/dist/chunks/chunk-5ITR67MB.js +0 -2
  306. package/dist/chunks/chunk-5NRFU6F6.js +0 -2
  307. package/dist/chunks/chunk-E2LCSVQV.js +0 -2
  308. package/dist/chunks/chunk-FCNVTIPJ.js +0 -2
  309. package/dist/chunks/chunk-FKAKALOZ.js +0 -2
  310. package/dist/chunks/chunk-HD73UKPT.js +0 -2
  311. package/dist/chunks/chunk-IUULP3LE.js +0 -2
  312. package/dist/chunks/chunk-JQG3YQOC.js +0 -2
  313. package/dist/chunks/chunk-KT66SB7R.js +0 -2
  314. package/dist/chunks/chunk-MAUAOQG3.js +0 -2
  315. package/dist/chunks/chunk-MDYE7QP2.js +0 -2
  316. package/dist/chunks/chunk-NM3Z2UBQ.js +0 -2
  317. package/dist/chunks/chunk-PMJI5QO6.js +0 -3
  318. package/dist/chunks/chunk-UF7KOTHF.js +0 -3
  319. package/dist/chunks/chunk-UOE57JGT.js +0 -2
  320. package/dist/chunks/chunk-USPEBXSR.js +0 -2
  321. package/dist/chunks/chunk-VLUL2HFW.js +0 -3
  322. package/dist/chunks/chunk-ZIX7NYQF.js +0 -2
@@ -8,21 +8,30 @@
8
8
  // for all cells, min(0.5, min |O - E|) (from R's output; scipy uses min(0.5, |O - E|) per cell).
9
9
  // If that amount is 0, the result is labelled as uncorrected
10
10
  // - A matrix with a single row or column becomes a goodness-of-fit test
11
- // - Count checks depend on the shape: a matrix rejects negative, NaN and Inf; a vector (and a
12
- // 1-row or 1-column matrix) rejects only negative and NaN (Inf just makes the statistic NaN).
13
- // Fractional counts are accepted in both cases
11
+ // - Counts that are negative, NaN or Inf are errors in every shape (R lets Inf through in a vector or a 1-row or
12
+ // 1-column matrix and returns NaN; docs, "Inputs without meaning"). Fractional counts are accepted
14
13
  // - Sums are taken in double-double (R's sum accumulates in extended precision)
15
14
  // - Simulated p-values (Hope 1968; R's documented behaviour): (1 + #{simulated statistics >= (1 - 64 eps) times the
16
- // observed one}) / (B + 1). Goodness of fit draws the B samples of size n = sum(x) at once with sampleInt (R's
17
- // sample.int with prob) and counts them n at a time; contingency tables are drawn with Patefield's algorithm
15
+ // observed one}) / (B + 1). Goodness of fit draws the B samples of size n = sum(x) one at a time (the uniforms of
16
+ // R's sample.int with prob) and counts them n at a time; contingency tables are drawn with Patefield's algorithm
18
17
  // (src/random/r2dtable.ts). The statistic is then the uncorrected one, and the parameter is NaN (R's NA). Tables
19
- // with a zero margin are not simulated (ordinary test), as in R
18
+ // with a zero margin are not simulated (ordinary test), as in R, with R's warning "cannot compute simulated p-value
19
+ // with zero marginals"
20
+ // - R's warning "Chi-squared approximation may be incorrect" where an expected count is below 5 and the p-value is
21
+ // not simulated
20
22
  // - Two factor vectors: the table of the complete pairs, with the distinct values sorted by code point (C locale)
21
23
  import { pgamma1 } from "../distributions/gamma.js";
22
- import { logFactorialTable, rcont2 } from "../random/r2dtable.js";
23
- import { sampleInt } from "../random/sample.js";
24
- import { ddAdd } from "../special/dd.js";
24
+ import { logFactorialTable, MAX_TABLE_TOTAL, rcont2 } from "../random/r2dtable.js";
25
+ import { sampleIntReplaceDrawer } from "../random/sample.js";
26
+ import { ldexp, productOver, squareOver } from "../internal/summary.js";
27
+ import { compareCodePoints } from "../models/modelFrame.js";
28
+ import { ddAdd, ddDiv, ddMul, ddSub } from "../special/dd.js";
25
29
  import { simulatedMethod } from "./core/simulate.js";
30
+ import { reported } from "../internal/warnings.js";
31
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
32
+ import { checkOptions } from "../internal/checkOptions.js";
33
+ import { isOptionsObject } from "../internal/optionalArgs.js";
34
+ const CHISQ_TEST_KEYS = ["correct", "p", "rescaleP", "simulatePValue", "B"];
26
35
  /** Sum (accumulated in double-double, then rounded; with Inf present, the double sum = ±Inf or NaN) */
27
36
  function ddSum(x) {
28
37
  let s = [0, 0];
@@ -34,12 +43,15 @@ function ddSum(x) {
34
43
  return Number.isFinite(plain) ? s[0] : plain;
35
44
  }
36
45
  export function chisqTest(x, yOrOptions, maybeOptions) {
46
+ if (isOptionsObject(yOrOptions))
47
+ checkOptions(yOrOptions, CHISQ_TEST_KEYS, "chisqTest"); // generated: option-keys.mjs
48
+ checkOptions(maybeOptions, CHISQ_TEST_KEYS, "chisqTest"); // generated: option-keys.mjs
37
49
  if (Array.isArray(yOrOptions))
38
- return chisqFactors(x, yOrOptions, maybeOptions ?? {});
39
- return chisqCounts(x, yOrOptions ?? {});
50
+ return reported("chisqTest", chisqFactors(x, yOrOptions, maybeOptions ?? {}));
51
+ return reported("chisqTest", chisqCounts(x, yOrOptions ?? {}));
40
52
  }
41
- /** Code-point order (the C locale) */
42
- const byCodePoint = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
53
+ /** R's warning where an expected count is below 5 and the p-value is not simulated */
54
+ const APPROXIMATION = "Chi-squared approximation may be incorrect";
43
55
  function chisqFactors(x, y, options) {
44
56
  if (x.length !== y.length)
45
57
  throw new RangeError("'x' and 'y' must have the same length");
@@ -57,8 +69,8 @@ function chisqFactors(x, y, options) {
57
69
  ys.push(w);
58
70
  }
59
71
  });
60
- const rowLevels = [...new Set(xs)].sort(byCodePoint);
61
- const colLevels = [...new Set(ys)].sort(byCodePoint);
72
+ const rowLevels = [...new Set(xs)].sort(compareCodePoints);
73
+ const colLevels = [...new Set(ys)].sort(compareCodePoints);
62
74
  if (rowLevels.length < 2 || colLevels.length < 2)
63
75
  throw new RangeError("'x' and 'y' must have at least 2 levels");
64
76
  const ri = new Map(rowLevels.map((v, i) => [v, i]));
@@ -87,8 +99,10 @@ function chisqCounts(x, options) {
87
99
  /** Number of replicates, checked when a simulation is run */
88
100
  function replicates(options) {
89
101
  const B = options.B ?? 2000;
90
- if (!(B >= 0 && B < 2 ** 31))
91
- throw new RangeError("'B' must be a non-negative number");
102
+ // a fractional B ran more simulations than B + 1 counts (R divides by B + 1 as well): p-values above 1 (B = 2.1 gave
103
+ // 1.33, R 1.29). B = 0 simulates nothing (R's p = (1 + 0) / (0 + 1) = 1): an error too (#489)
104
+ if (!(Number.isInteger(B) && B >= 1 && B < 2 ** 31))
105
+ throw new RangeError("'B' must be a positive integer");
92
106
  return B;
93
107
  }
94
108
  /** (1 + #{sims >= (1 - 64 eps) stat}) / (B + 1) */
@@ -98,7 +112,8 @@ function monteCarloP(sims, stat, B) {
98
112
  for (let i = 0; i < sims.length; i++)
99
113
  if (sims[i] >= threshold)
100
114
  count++;
101
- return (1 + count) / (B + 1);
115
+ // the simulations actually made (R divides by B + 1 with a fractional B, of which only the integer part is run)
116
+ return (1 + count) / (Math.trunc(B) + 1);
102
117
  }
103
118
  function pValueOf(stat, df) {
104
119
  return Number.isNaN(stat) ? NaN : pgamma1(stat, df / 2, 2, false, false);
@@ -113,7 +128,8 @@ function checkExpected(E) {
113
128
  }
114
129
  function goodnessOfFit(x, options) {
115
130
  const k = x.length;
116
- if (x.some((v) => Number.isNaN(v) || v < 0))
131
+ // (R lets Infinity through and returns NaN)
132
+ if (x.some((v) => !(v >= 0 && v < Infinity)))
117
133
  throw new RangeError("all entries of 'x' must be non-negative and finite");
118
134
  if (k < 2)
119
135
  throw new TypeError("'x' must have at least 2 elements");
@@ -127,22 +143,40 @@ function goodnessOfFit(x, options) {
127
143
  throw new RangeError("p contains missing values");
128
144
  if (p.some((v) => v < 0))
129
145
  throw new RangeError("probabilities must be non-negative");
146
+ if (p.some((v) => v === Infinity))
147
+ throw new RangeError("probabilities must be finite");
130
148
  if (options.rescaleP ?? false) {
131
- const s = ddSum(p);
132
- p = p.map((v) => v / s);
149
+ // where the total of the finite weights overflows, the weights in units of 2^e, 2^e >= k, first (each weight was
150
+ // divided by Inf and became 0: p = c(1e308, 1e308) gave statistic Inf, p-value 0; R too; issue #303)
151
+ const total = ddSum(p);
152
+ const e = total < Infinity ? 0 : Math.ceil(Math.log2(k));
153
+ const ps = e === 0 ? p : p.map((v) => ldexp(v, -e));
154
+ const s = e === 0 ? total : ddSum(ps);
155
+ p = ps.map((v) => v / s);
133
156
  }
134
157
  else if (Math.abs(ddSum(p) - 1) > Math.sqrt(Number.EPSILON)) {
135
158
  throw new RangeError("probabilities must sum to 1");
136
159
  }
137
- const E = p.map((v) => n * v);
160
+ // where the total overflows (each count finite), the counts in units of 2^s, 2^s >= k and s even, so that their total
161
+ // cannot overflow; the statistic is scaled back by 2^s and the residuals by 2^(s/2). With s = 0 (the total finite)
162
+ // the values are those of the plain counts
163
+ const s = n < Infinity ? 0 : 2 * Math.ceil(Math.log2(k) / 2);
164
+ const xs = s === 0 ? x : x.map((v) => ldexp(v, -s));
165
+ const ns = s === 0 ? n : ddSum(xs);
166
+ const Es = p.map((v) => ns * v);
167
+ const E = s === 0 ? Es : Es.map((e) => ldexp(e, s));
138
168
  checkExpected(E);
139
- const V = p.map((v, i) => E[i] * (1 - v));
140
- const stat = ddSum(x.map((v, i) => (v - E[i]) ** 2 / E[i]));
169
+ const Vs = p.map((v, i) => Es[i] * (1 - v));
170
+ const stat = ldexp(ddSum(xs.map((v, i) => squareOver(v - Es[i], Es[i]))), s);
141
171
  let method = "Chi-squared test for given probabilities";
142
172
  let df = k - 1;
143
173
  let pValue;
144
174
  if (options.simulatePValue ?? false) {
145
175
  const B = replicates(options);
176
+ // a fractional total cannot be drawn as a sample: the columns of draws then outnumbered B and the p-value exceeded
177
+ // 1 (c(3.5, 4, 5) with B = 2 gave 1.33; R too)
178
+ if (!Number.isInteger(n))
179
+ throw new RangeError("the simulation needs counts summing to an integer");
146
180
  method += simulatedMethod(B);
147
181
  df = NaN;
148
182
  pValue = monteCarloP(simulateGoodnessOfFit(n, p, E, B), stat, B);
@@ -158,30 +192,29 @@ function goodnessOfFit(x, options) {
158
192
  pValue,
159
193
  observed: x,
160
194
  expected: E,
161
- residuals: x.map((v, i) => (v - E[i]) / Math.sqrt(E[i])),
162
- stdres: x.map((v, i) => (v - E[i]) / Math.sqrt(V[i])),
195
+ residuals: xs.map((v, i) => ldexp((v - Es[i]) / Math.sqrt(Es[i]), s / 2)),
196
+ stdres: xs.map((v, i) => ldexp((v - Es[i]) / Math.sqrt(Vs[i]), s / 2)),
197
+ warnings: Number.isFinite(df) && E.some((e) => e < 5) ? [APPROXIMATION] : [],
163
198
  };
164
199
  }
165
200
  /**
166
- * Statistics of B multinomial samples: B n categories drawn at once with probabilities p (sampleInt, R's
167
- * sample.int(k, B n, TRUE, prob = p)), laid out column by column in a matrix of floor(n) rows (recycled to fill the
168
- * last column, as R's matrix() does when n is not an integer) and counted per column
201
+ * Statistics of B multinomial samples: the B n categories of R's sample.int(k, B n, TRUE, prob = p), taken column by
202
+ * column of the n-row matrix, are drawn n at a time and counted (n is an integer here), without keeping the B n draws
203
+ * (#287): the same uniforms in the same order, so the same statistics. B n is limited to 2^27 draws (tens of seconds)
169
204
  */
170
205
  function simulateGoodnessOfFit(n, p, E, B) {
171
206
  const k = p.length;
172
- const draws = sampleInt(k, { size: Math.trunc(B * n), replace: true, prob: p });
173
- const rows = Math.trunc(n);
174
- if (draws.length === 0)
207
+ if (B * n > 2 ** 27)
208
+ throw new RangeError("the simulation needs B * sum(x) <= 2^27 (134217728) draws");
209
+ const draw = sampleIntReplaceDrawer(k, p);
210
+ if (B * n === 0)
175
211
  return new Float64Array(0);
176
- if (rows === 0)
177
- throw new RangeError("invalid 'nrow' value (too large or NA)");
178
- const cols = Math.ceil(draws.length / rows);
179
- const out = new Float64Array(cols);
212
+ const out = new Float64Array(B);
180
213
  const counts = new Float64Array(k);
181
- for (let j = 0; j < cols; j++) {
214
+ for (let j = 0; j < B; j++) {
182
215
  counts.fill(0);
183
- for (let i = 0; i < rows; i++)
184
- counts[draws[(j * rows + i) % draws.length]]++;
216
+ for (let i = 0; i < n; i++)
217
+ counts[draw()]++;
185
218
  let s = 0;
186
219
  for (let c = 0; c < k; c++)
187
220
  s += (counts[c] - E[c]) ** 2 / E[c];
@@ -194,6 +227,9 @@ function simulateTables(sr, sc, E, B) {
194
227
  const nr = sr.length;
195
228
  const nc = sc.length;
196
229
  const total = sr.reduce((a, b) => a + b, 0);
230
+ // the table of log factorials has total + 1 entries: limited as in r2dtable (#285)
231
+ if (total > MAX_TABLE_TOTAL)
232
+ throw new RangeError("the simulation needs a total count of at most 16777216 (2^24)");
197
233
  const fact = logFactorialTable(total);
198
234
  const table = new Int32Array(nr * nc);
199
235
  const out = new Float64Array(Math.trunc(B));
@@ -222,7 +258,7 @@ function contingency(x, options) {
222
258
  throw new RangeError("at least one entry of 'x' must be positive");
223
259
  const sr = x.map((r) => ddSum(r));
224
260
  const sc = x[0].map((_, j) => ddSum(x.map((r) => r[j])));
225
- const E = sr.map((a) => sc.map((b) => (a * b) / n));
261
+ const E = sr.map((a) => sc.map((b) => productOver(a, b, n)));
226
262
  checkExpected(E.flat());
227
263
  const diff = x.map((r, i) => r.map((v, j) => v - E[i][j]));
228
264
  let method = "Pearson's Chi-squared test";
@@ -231,23 +267,28 @@ function contingency(x, options) {
231
267
  let pValue;
232
268
  const simulate = (options.simulatePValue ?? false) && sr.every((v) => v > 0) && sc.every((v) => v > 0);
233
269
  const yates = !simulate && correct && nr === 2 && nc === 2 ? Math.min(0.5, ...diff.flat().map(Math.abs)) : 0;
270
+ const warnings = [];
271
+ if ((options.simulatePValue ?? false) && !simulate)
272
+ warnings.push("cannot compute simulated p-value with zero marginals");
234
273
  if (simulate) {
235
- // counts are integers for the simulation (R's C code takes the margins as integers)
274
+ // counts are integers for the simulation: the simulated tables have integer margins, and fractional observed
275
+ // counts would be compared with them (R truncates the margins and runs it)
276
+ if (x.some((r) => r.some((v) => !Number.isInteger(v))))
277
+ throw new RangeError("the simulation needs integer counts");
236
278
  const B = replicates(options);
237
279
  method += simulatedMethod(B);
238
- stat = ddSum(diff.flatMap((r, i) => r.map((d, j) => (d * d) / E[i][j])));
280
+ stat = ddSum(diff.flatMap((r, i) => r.map((d, j) => squareOver(d, E[i][j]))));
239
281
  df = NaN;
240
282
  const sims = simulateTables(sr.map((v) => Math.trunc(v)), sc.map((v) => Math.trunc(v)), E, B);
241
283
  pValue = monteCarloP(sims, stat, B);
242
284
  }
243
285
  else if (yates > 0) {
244
286
  method += " with Yates' continuity correction";
245
- stat = ddSum(diff.flatMap((r, i) => r.map((d, j) => (Math.abs(d) - yates) ** 2 / E[i][j])));
287
+ stat = ddSum(diff.flatMap((r, i) => r.map((d, j) => squareOver(Math.abs(d) - yates, E[i][j]))));
246
288
  }
247
289
  else {
248
- stat = ddSum(diff.flatMap((r, i) => r.map((d, j) => (d * d) / E[i][j])));
290
+ stat = ddSum(diff.flatMap((r, i) => r.map((d, j) => squareOver(d, E[i][j]))));
249
291
  }
250
- const V = E.map((r, i) => r.map((e, j) => e * (1 - sr[i] / n) * (1 - sc[j] / n)));
251
292
  return {
252
293
  method,
253
294
  statistic: stat,
@@ -258,6 +299,70 @@ function contingency(x, options) {
258
299
  observed: x,
259
300
  expected: E,
260
301
  residuals: diff.map((r, i) => r.map((d, j) => d / Math.sqrt(E[i][j]))),
261
- stdres: diff.map((r, i) => r.map((d, j) => d / Math.sqrt(V[i][j]))),
302
+ stdres: contingencyStdres(x, n, sr, sc, E, diff),
303
+ warnings: Number.isFinite(df) && E.some((r) => r.some((e) => e < 5)) ? [...warnings, APPROXIMATION] : warnings,
262
304
  };
263
305
  }
306
+ /**
307
+ * Standardized residuals (O - E) / sqrt(E (1 - row proportion) (1 - column proportion)) of a contingency table
308
+ * (#382). The complements 1 - row proportion and 1 - column proportion are the sums of the other rows and columns
309
+ * over n, and the margins, E, O - E and the variance are in double-double, rounded once at the end: 1 - sr / n in
310
+ * double lost the small margins (2^52 and 0.1: 0 for the complement, so -Infinity; integer tables such as
311
+ * [[1e15, 7], [3, 11]] were off by 8e-4), and O - E with E rounded to double was 0 in the cell of 2^52. A total
312
+ * beyond the double range keeps the old formula
313
+ */
314
+ function contingencyStdres(x, n, sr, sc, E, diff) {
315
+ if (!Number.isFinite(n)) {
316
+ return diff.map((r, i) => r.map((d, j) => d / Math.sqrt(E[i][j] * (1 - sr[i] / n) * (1 - sc[j] / n))));
317
+ }
318
+ const srD = x.map((r) => ddSumOf(r));
319
+ const scD = x[0].map((_, j) => ddSumOf(x.map((r) => r[j])));
320
+ const nD = ddSumOfDD(srD);
321
+ const cr = othersSums(srD);
322
+ const cc = othersSums(scD);
323
+ const rowC = cr.map((c) => ddDiv(c, nD));
324
+ const colP = scD.map((c) => ddDiv(c, nD));
325
+ const colC = cc.map((c) => ddDiv(c, nD));
326
+ return x.map((r, i) => r.map((v, j) => {
327
+ const e = ddMul(srD[i], colP[j]);
328
+ const d = ddSub([v, 0], e);
329
+ const dd = d[0] + d[1];
330
+ const V = ddMul(ddMul(e, rowC[i]), colC[j]);
331
+ const vv = V[0] + V[1];
332
+ if (vv >= MIN_NORMAL || dd === 0)
333
+ return dd / Math.sqrt(vv);
334
+ // a variance below the normal range: divide by the square roots in turn
335
+ const ee = e[0] + e[1];
336
+ const rc = rowC[i][0] + rowC[i][1];
337
+ const ccj = colC[j][0] + colC[j][1];
338
+ return dd / Math.sqrt(ee) / Math.sqrt(rc) / Math.sqrt(ccj);
339
+ }));
340
+ }
341
+ const MIN_NORMAL = 2 ** -1022;
342
+ function ddSumOf(x) {
343
+ let s = [0, 0];
344
+ for (const v of x)
345
+ s = ddAdd(s, [v, 0]);
346
+ return s;
347
+ }
348
+ function ddSumOfDD(x) {
349
+ let s = [0, 0];
350
+ for (const v of x)
351
+ s = ddAdd(s, v);
352
+ return s;
353
+ }
354
+ /** For each i, the double-double sum of the entries other than x[i] (prefix and suffix sums) */
355
+ function othersSums(x) {
356
+ const m = x.length;
357
+ const suffix = new Array(m + 1);
358
+ suffix[m] = [0, 0];
359
+ for (let i = m - 1; i >= 0; i--)
360
+ suffix[i] = ddAdd(x[i], suffix[i + 1]);
361
+ const out = [];
362
+ let prefix = [0, 0];
363
+ for (let i = 0; i < m; i++) {
364
+ out.push(ddAdd(prefix, suffix[i + 1]));
365
+ prefix = ddAdd(prefix, x[i]);
366
+ }
367
+ return out;
368
+ }
@@ -8,7 +8,8 @@ import { type Alternative, type HTest, type Sample } from "./types.js";
8
8
  */
9
9
  export type CorMethod = "pearson" | "kendall" | "spearman";
10
10
  /**
11
- * Options for {@link cor}.
11
+ * The base of {@link CorTestOptions}: the options {@link corTest} shares with the coefficient. The options of the
12
+ * exported `cor` (descriptive statistics) are {@link CovOptions}.
12
13
  *
13
14
  * @category Hypothesis tests
14
15
  */
@@ -30,7 +31,8 @@ export interface CorTestOptions extends CorOptions {
30
31
  /**
31
32
  * Compute an exact p-value (Kendall and Spearman). Default: as in R, exact when there are
32
33
  * no ties and n < 50 (Kendall) or n <= 1290 (Spearman). With ties the approximation is
33
- * always used.
34
+ * always used. Kendall's exact distribution takes about n^3 / 2 steps: for n above 1290 (about 5 s)
35
+ * `exact: true` without ties is a RangeError (R computes it however long it takes).
34
36
  */
35
37
  exact?: boolean;
36
38
  /** Confidence level of the interval (Pearson only; the interval needs at least 4 pairs). Default `0.95`. */
@@ -91,6 +93,11 @@ export declare function kendall(x: readonly number[], y: readonly number[]): Ken
91
93
  * arithmetic, so results can differ from R's when r is very close to ±1, where R's own
92
94
  * value is less accurate.
93
95
  *
96
+ * As R, `warnings` has "the standard deviation is zero" where x or y is constant (the correlation is `NaN`), and
97
+ * "Cannot compute exact p-value with ties" where Kendall's or Spearman's exact p-value is asked for or the default
98
+ * but there are ties (the approximation is used), and "NaNs produced" where Spearman's t approximation has 2 pairs
99
+ * (0 degrees of freedom: the p-value is `NaN`).
100
+ *
94
101
  * @param x First sample.
95
102
  * @param y Second sample, of the same length as `x`.
96
103
  * @param options See {@link CorTestOptions}.
package/dist/htest/cor.js CHANGED
@@ -19,6 +19,10 @@
19
19
  // replaces rho with (rho + 6 / (n^3 - n)) / (1 + 6 / (n^3 - n)) (regardless of sign or alternative; R's behaviour)
20
20
  // - When the correlation is undefined (constant data), the statistic, p-value, estimate and interval are NaN. Kendall's
21
21
  // statistic is then always named "T"
22
+ // - R's warnings: "the standard deviation is zero" where the correlation is NaN because x or y is constant (R's cor;
23
+ // for Pearson finite values, as R, whose sd of an infinite constant is NaN), and "Cannot compute exact p-value with
24
+ // ties" where the exact p-value is asked for or the default (Kendall n < 50; Spearman always, as R's exact = TRUE)
25
+ // but there are ties, and "NaNs produced" of R's pt with 0 degrees of freedom (Spearman's t approximation, n = 2)
22
26
  // - confLevel is validated only for Pearson. The interval is only reported with 4 or more pairs
23
27
  // More accurate than R: the correlation coefficient, 1 - r^2 and the continuity-corrected rho are computed in double-double.
24
28
  // R's cor is off by about 1e-10 for data with a large mean (1e8 + small spread), and does not give 1 even for perfect correlation (1 - 2 ulp).
@@ -26,9 +30,13 @@
26
30
  import { pt1 } from "../distributions/t.js";
27
31
  import { pnorm, qnorm } from "../distributions/normal.js";
28
32
  import { ddAdd, ddDiv, ddMul, ddSub, twoProd, twoSum } from "../special/dd.js";
29
- import { completePairs, meanDD, rank, tieCounts } from "../internal/summary.js";
33
+ import { centered, completePairs, rank, tieCounts } from "../internal/summary.js";
30
34
  import { correlationData } from "./testFormula.js";
35
+ import { reported } from "../internal/warnings.js";
31
36
  import { checkConfLevel, matchAlternative } from "./types.js";
37
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
38
+ import { checkOptions } from "../internal/checkOptions.js";
39
+ const COR_TEST_KEYS = ["alternative", "exact", "confLevel", "continuity", "method"];
32
40
  const METHODS = ["pearson", "kendall", "spearman"];
33
41
  function matchMethod(m) {
34
42
  if (m === undefined)
@@ -73,27 +81,14 @@ function ddSqrt(a) {
73
81
  const e = ddSub(a, twoProd(s, s));
74
82
  return twoSum(s, e[0] / (2 * s));
75
83
  }
76
- /** Deviations (mean subtracted in double-double, scaled by a power of 2 to be near 1). Correlation is scale-invariant */
77
- function scaledDeviations(x) {
78
- const m = meanDD(x);
79
- if (!Number.isFinite(m[0]))
80
- return undefined;
81
- const d = x.map((v) => ddSub([v, 0], m));
82
- let mx = 0;
83
- for (const v of d)
84
- mx = Math.max(mx, Math.abs(v[0]));
85
- if (mx === 0)
86
- return d;
87
- const f = 2 ** -Math.max(-1022, Math.floor(Math.log2(mx)));
88
- return d.map((v) => [v[0] * f, v[1] * f]);
89
- }
90
84
  /** Pearson's correlation coefficient in double-double (so 1 - r is computed without cancellation near perfect correlation) */
91
85
  export function pearsonDD(x, y) {
92
86
  const n = x.length;
93
87
  if (n < 2)
94
88
  return [NaN, 0];
95
- const dx = scaledDeviations(x);
96
- const dy = scaledDeviations(y);
89
+ // deviations of the values scaled by a power of 2 first (the correlation does not depend on the scales)
90
+ const dx = centered(x)?.d;
91
+ const dy = centered(y)?.d;
97
92
  if (dx === undefined || dy === undefined)
98
93
  return [NaN, 0];
99
94
  let sxy = [0, 0];
@@ -160,6 +155,8 @@ export function kendall(x, y) {
160
155
  const tau = n < 2 || px === pairs || py === pairs ? NaN : px === 0 && py === 0 ? s / pairs : s / Math.sqrt((pairs - px) * (pairs - py));
161
156
  return { s, tau, ties: tx.length > 0 || ty.length > 0, tx, ty };
162
157
  }
158
+ /** Largest n for Kendall's exact p-value (#316) */
159
+ const MAX_KENDALL_EXACT_N = 1290;
163
160
  /**
164
161
  * Probability that a permutation of n distinct elements has at most c inversions. The inversion
165
162
  * distribution is symmetric, so the upper tail P(T >= q) is computed as P(T <= N - q) (N = n(n-1)/2).
@@ -286,6 +283,7 @@ function spearmanTail(n, q, lower) {
286
283
  return spearmanEdgeworth(n, q, false);
287
284
  }
288
285
  export function corTest(x, y, options = {}) {
286
+ checkOptions(options, COR_TEST_KEYS, "corTest"); // generated: option-keys.mjs
289
287
  if (typeof x === "string") {
290
288
  const d = correlationData(x, y);
291
289
  return corTest(d.x, d.y, options);
@@ -321,6 +319,7 @@ function corTestSamples(x, y, options) {
321
319
  estimateNames: "cor",
322
320
  nullValue: 0,
323
321
  nullValueName: "correlation",
322
+ warnings: Number.isNaN(r[0]) && (finiteConstant(xs) || finiteConstant(ys)) ? [SD_ZERO] : [],
324
323
  };
325
324
  if (n > 3) {
326
325
  const z = atanhDD(r);
@@ -334,13 +333,15 @@ function corTestSamples(x, y, options) {
334
333
  else if (alternative === "greater")
335
334
  ci = [end(-sigma * qnorm(confLevel)), 1];
336
335
  else {
337
- const c = sigma * qnorm((1 + confLevel) / 2);
336
+ // (for alpha below 1e-8 the upper probability itself: 1 - alpha loses its digits and rounds to 1 below 1.1e-16; review 58)
337
+ const a2 = (1 - confLevel) / 2;
338
+ const c = sigma * (a2 < 1e-8 ? qnorm(a2, { lowerTail: false }) : qnorm((1 + confLevel) / 2));
338
339
  ci = [end(-c), end(c)];
339
340
  }
340
341
  result.confInt = ci;
341
342
  result.confLevel = confLevel;
342
343
  }
343
- return result;
344
+ return reported("corTest", result);
344
345
  }
345
346
  if (n < 2)
346
347
  throw new Error("not enough finite observations");
@@ -353,30 +354,41 @@ function corTestSamples(x, y, options) {
353
354
  estimateNames: "tau",
354
355
  nullValue: 0,
355
356
  nullValueName: "tau",
357
+ warnings: [],
356
358
  };
359
+ // tau is NaN only where x or y is constant (n >= 2)
357
360
  if (Number.isNaN(k.tau))
358
- return { ...base, statistic: NaN, statisticName: "T", pValue: NaN };
361
+ return reported("corTest", { ...base, statistic: NaN, statisticName: "T", pValue: NaN, warnings: [SD_ZERO] });
359
362
  const exact = options.exact ?? n < 50;
360
363
  if (exact && !k.ties) {
364
+ // the two runs of kendallCdf below take n (q + 1) + n (total - q + 1) steps, about n^3 / 2: limited to n <= 1290
365
+ // (the same number as the Spearman exact limit; about 5 s), checked before they allocate (#316)
366
+ if (n > MAX_KENDALL_EXACT_N) {
367
+ throw new RangeError(`the exact distribution of T for n = ${n} takes too long (at most ${MAX_KENDALL_EXACT_N}): use exact: false`);
368
+ }
361
369
  const total = (n * (n - 1)) / 2;
362
370
  const q = (k.s + total) / 2;
363
371
  // P(T <= q) and P(T >= q) = P(T <= total - q)
364
372
  const lowerP = kendallCdf(n, q);
365
373
  const upperP = kendallCdf(n, total - q);
366
374
  const p = alternative === "less" ? lowerP : alternative === "greater" ? upperP : Math.min(1, 2 * Math.min(lowerP, upperP));
367
- return { ...base, statistic: q, statisticName: "T", pValue: p };
375
+ return reported("corTest", { ...base, statistic: q, statisticName: "T", pValue: p });
368
376
  }
369
377
  // Normal approximation (tie-corrected variance)
370
378
  const v = (f, ts) => ts.reduce((a, t) => a + f(t), 0);
371
379
  const a2 = (t) => t * (t - 1);
372
380
  const a3 = (t) => t * (t - 1) * (t - 2);
373
381
  const a5 = (t) => t * (t - 1) * (2 * t + 5);
382
+ // For n = 2 every tie group has t <= 2, so the sums of t (t - 1) (t - 2)
383
+ // are 0 and the second term is 0 (its denominator is also 0: R gives 0/0).
374
384
  const varS = (n * (n - 1) * (2 * n + 5) - v(a5, k.tx) - v(a5, k.ty)) / 18 +
375
- (v(a3, k.tx) * v(a3, k.ty)) / (9 * n * (n - 1) * (n - 2)) +
385
+ (n < 3 ? 0 : (v(a3, k.tx) * v(a3, k.ty)) / (9 * n * (n - 1) * (n - 2))) +
376
386
  (v(a2, k.tx) * v(a2, k.ty)) / (2 * n * (n - 1));
377
387
  const s = continuity ? Math.sign(k.s) * (Math.abs(k.s) - 1) : k.s;
378
388
  const z = s / Math.sqrt(varS);
379
- return { ...base, statistic: z, statisticName: "z", pValue: pFromZ(z, alternative) };
389
+ if (exact)
390
+ base.warnings = [TIES];
391
+ return reported("corTest", { ...base, statistic: z, statisticName: "z", pValue: pFromZ(z, alternative) });
380
392
  }
381
393
  // spearman
382
394
  const rx = rank(xs);
@@ -393,10 +405,15 @@ function corTestSamples(x, y, options) {
393
405
  estimateNames: "rho",
394
406
  nullValue: 0,
395
407
  nullValueName: "rho",
408
+ warnings: [],
396
409
  };
410
+ // rho is NaN only where the ranks of x or y are constant (n >= 2)
397
411
  if (Number.isNaN(rho[0]))
398
- return { ...base, pValue: NaN };
412
+ return reported("corTest", { ...base, pValue: NaN, warnings: [SD_ZERO] });
399
413
  const ties = tieCounts(xs).length > 0 || tieCounts(ys).length > 0;
414
+ // R's exact is TRUE by default for Spearman, whatever n (above 1290 its pspearman takes the t approximation)
415
+ if (ties && (options.exact ?? true))
416
+ base.warnings = [TIES];
400
417
  const exact = options.exact ?? n <= 1290;
401
418
  if (exact && !ties && n <= 1290) {
402
419
  const q = Math.round(S);
@@ -404,7 +421,7 @@ function corTestSamples(x, y, options) {
404
421
  const upperP = spearmanTail(n, q, false);
405
422
  // Smaller S means positive correlation
406
423
  const p = alternative === "greater" ? lowerP : alternative === "less" ? upperP : Math.min(1, 2 * Math.min(lowerP, upperP));
407
- return { ...base, pValue: p };
424
+ return reported("corTest", { ...base, pValue: p });
408
425
  }
409
426
  // t approximation. The continuity-corrected rho is also in double-double (1 - rho^2 cancels when rho is near ±1)
410
427
  let r = rho;
@@ -415,5 +432,19 @@ function corTestSamples(x, y, options) {
415
432
  r = [Math.sign(r[0]), 0];
416
433
  }
417
434
  const t = tFromR(r, n - 2);
418
- return { ...base, pValue: pFromT(t, n - 2, alternative) };
435
+ // n = 2: R's pt with 0 degrees of freedom gives NaN with its warning (R's rho of the two ranks is ±(1 - 2^-52), so
436
+ // its t is finite)
437
+ if (n === 2)
438
+ base.warnings = [...base.warnings, NANS];
439
+ return reported("corTest", { ...base, pValue: pFromT(t, n - 2, alternative) });
440
+ }
441
+ /** R's warning of cor where x or y is constant */
442
+ const SD_ZERO = "the standard deviation is zero";
443
+ /** R's warning of pt where the p-value is NaN (Spearman's t approximation with n = 2) */
444
+ const NANS = "NaNs produced";
445
+ /** R's warning where the exact p-value cannot be used because of ties */
446
+ const TIES = "Cannot compute exact p-value with ties";
447
+ /** Whether all values are equal and finite */
448
+ function finiteConstant(v) {
449
+ return Number.isFinite(v[0]) && v.every((a) => a === v[0]);
419
450
  }
@@ -1,3 +1,12 @@
1
+ /**
2
+ * Throws a RangeError when the exact distribution for sample sizes m and n is too large to build: the two layers of
3
+ * ansariDist hold 2 (m + 1) (maxSum + 1) doubles (maxSum = floor((N + 1)^2 / 4), N = m + n) and the N passes take
4
+ * N (m + 1) (maxSum + 1) steps (m = n = 1000 asked for 16 GB). Checked before any allocation.
5
+ *
6
+ * @param m - Size of the first sample.
7
+ * @param n - Size of the second sample.
8
+ */
9
+ export declare function checkAnsariExactSize(m: number, n: number): void;
1
10
  /**
2
11
  * P(AB <= q) (lowerTail) or P(AB > q) for the Ansari-Bradley statistic with sample sizes m and n, without ties.
3
12
  *
@@ -7,7 +7,27 @@
7
7
  // N - t + 1 positions, the position is picked with probability r / (N - t + 1). The probabilities are kept directly
8
8
  // (counts overflow: C(100, 50) = 1e29), and tail probabilities are sums of positive terms.
9
9
  import { choose } from "../../special/choose.js";
10
+ import { countAtMost } from "../../internal/integer.js";
10
11
  const cache = new Map();
12
+ /** Largest number of doubles the two layers of ansariDist may hold (as #232's 2^24; 128 MB, #308) */
13
+ const MAX_EXACT_SIZE = 2 ** 24;
14
+ /** Largest work N (m + 1) (maxSum + 1) of ansariDist (m = n = 202 is about 5 s) */
15
+ const MAX_EXACT_WORK = 2 ** 32;
16
+ /**
17
+ * Throws a RangeError when the exact distribution for sample sizes m and n is too large to build: the two layers of
18
+ * ansariDist hold 2 (m + 1) (maxSum + 1) doubles (maxSum = floor((N + 1)^2 / 4), N = m + n) and the N passes take
19
+ * N (m + 1) (maxSum + 1) steps (m = n = 1000 asked for 16 GB). Checked before any allocation.
20
+ *
21
+ * @param m - Size of the first sample.
22
+ * @param n - Size of the second sample.
23
+ */
24
+ export function checkAnsariExactSize(m, n) {
25
+ const N = m + n;
26
+ const cells = (m + 1) * (Math.floor((N + 1) ** 2 / 4) + 1);
27
+ if (2 * cells > MAX_EXACT_SIZE || N * cells > MAX_EXACT_WORK) {
28
+ throw new RangeError(`the exact distribution for m = ${m} and n = ${n} is too large to compute: use exact: false`);
29
+ }
30
+ }
11
31
  function ansariDist(m, n) {
12
32
  const key = `${m},${n}`;
13
33
  const hit = cache.get(key);
@@ -66,7 +86,7 @@ export function pansariExact(q, m, n, lowerTail = true) {
66
86
  if (Number.isNaN(q) || !(m >= 1) || !(n >= 1) || m !== Math.floor(m) || n !== Math.floor(n))
67
87
  return NaN;
68
88
  const { min, probs } = ansariDist(m, n);
69
- const k = Math.floor(q + 1e-7) - min; // index of the largest value <= q
89
+ const k = countAtMost(q) - min; // index of the largest value <= q
70
90
  let s = 0;
71
91
  if (lowerTail) {
72
92
  for (let i = 0; i <= Math.min(k, probs.length - 1); i++)
@@ -1,3 +1,12 @@
1
+ /**
2
+ * Throws a RangeError when pkolmogorovExact(n, d) would need more than MAX_EXACT_WORK: the m x m matrix
3
+ * (m = 2 floor(n d) + 1) is raised to the n-th power with floor(log2 n) squarings and popcount(n) - 1 products, each
4
+ * m^3 multiply-adds (n 1e4 with d 0.4999 asked for an 800 MB matrix and hours of work). Checked before any allocation.
5
+ *
6
+ * @param n - Sample size.
7
+ * @param d - Value of the statistic.
8
+ */
9
+ export declare function checkKolmogorovExactSize(n: number, d: number): void;
1
10
  /**
2
11
  * P(D_n < d), the exact distribution of the two-sided one-sample Kolmogorov-Smirnov statistic for a continuous
3
12
  * distribution (Marsaglia, Tsang and Wang 2003). The matrix has size 2 floor(n d) + 1, so the cost grows like
@@ -24,3 +33,19 @@ export declare function pkolmogorovLimit(x: number, lowerTail?: boolean): number
24
33
  * @param d - Value of the statistic.
25
34
  */
26
35
  export declare function pkolmogorovOneSidedUpper(n: number, d: number): number;
36
+ /**
37
+ * P(D_n >= d), the upper tail of the two-sided one-sample statistic, as a sum of positive terms (#483), or NaN where
38
+ * that needs more than MAX_CHAIN_WORK terms. 1 - P(D_n < d) from pkolmogorovExact has absolute accuracy only (1e-22
39
+ * came out as 3e-15 at n = 99).
40
+ *
41
+ * N(t), the number of points at or below t, is a Markov chain: given N(t_k) = s, the count in (t_k, t_(k+1)] is
42
+ * Binomial(n - s, (t_(k+1) - t_k) / (1 - t_k)). D+ >= d when N(i/n - d) >= i for some i, D- >= d when
43
+ * N(j/n + d) <= j for some j (N(t-) = N(t) almost surely). Between the at most 2n breakpoints i/n - d and j/n + d the
44
+ * thresholds are constant, so the chain is stepped from one breakpoint to the next and the probability that leaves it
45
+ * across a threshold is added up. Each binomial row starts from dbinom1 at its mode and follows the ratio recurrence
46
+ * both ways until it underflows.
47
+ *
48
+ * @param n - Sample size, a positive integer.
49
+ * @param d - Value of the statistic, in (0, 1).
50
+ */
51
+ export declare function pkolmogorovExactUpper(n: number, d: number): number;