@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
package/dist/htest/aov.js CHANGED
@@ -12,32 +12,13 @@
12
12
  import { pf1 } from "../distributions/f.js";
13
13
  import { pnorm, qnorm } from "../distributions/normal.js";
14
14
  import { ptukey, qtukey } from "../distributions/tukey.js";
15
- import { meanDD } from "../internal/summary.js";
16
- import { ddAdd, ddMul, ddSub } from "../special/dd.js";
15
+ import { groupMoments, ldexp, meanDD, scaleToUnit } from "../internal/summary.js";
17
16
  import { parseFormula, splitErrorTerms } from "../models/formula.js";
18
17
  import { aovStrataFit } from "../models/aovStrata.js";
19
18
  import { lmFormulaFit } from "../models/lm.js";
20
19
  import { design } from "../models/modelMatrix.js";
21
20
  import { labelledGroups, toGroups } from "./groups.js";
22
- import { matchAlternative } from "./types.js";
23
- function sums(groups) {
24
- const all = groups.flat();
25
- const m = meanDD(all);
26
- let ssb = [0, 0];
27
- let ssw = [0, 0];
28
- const means = [];
29
- for (const g of groups) {
30
- const mi = meanDD(g);
31
- means.push(mi[0]);
32
- const d = ddSub(mi, m);
33
- ssb = ddAdd(ssb, ddMul(ddMul(d, d), [g.length, 0]));
34
- for (const v of g) {
35
- const e = ddSub([v, 0], mi);
36
- ssw = ddAdd(ssw, ddMul(e, e));
37
- }
38
- }
39
- return { ssb: ssb[0], ssw: ssw[0], means };
40
- }
21
+ import { checkConfLevel, matchAlternative } from "./types.js";
41
22
  export function aov(x, g, options = {}) {
42
23
  if (typeof x === "string")
43
24
  return aovFormula(x, g, options);
@@ -59,16 +40,18 @@ function aovOneway(x, g) {
59
40
  if (k < 2)
60
41
  throw new RangeError("contrasts can be applied only to factors with 2 or more levels");
61
42
  const N = groups.reduce((a, s) => a + s.length, 0);
62
- const { ssb, ssw } = sums(groups);
43
+ // sums of squares of the data scaled by 2^-k (groupMoments): F from them, the sums of squares scaled back
44
+ const { ssBetween: ssb, ssWithin: ssw, k: e } = groupMoments(groups);
63
45
  const df1 = k - 1;
64
46
  const df2 = N - k;
65
47
  const msb = ssb / df1;
66
48
  const msw = ssw / df2;
67
49
  const fValue = msb / msw;
50
+ const back = (v) => ldexp(v, 2 * e);
68
51
  return {
69
52
  df: [df1, df2],
70
- sumSq: [ssb, ssw],
71
- meanSq: [msb, msw],
53
+ sumSq: [back(ssb), back(ssw)],
54
+ meanSq: [back(msb), back(msw)],
72
55
  fValue,
73
56
  pValue: df2 > 0 ? pf1(fValue, df1, df2, false, false) : NaN,
74
57
  };
@@ -104,9 +87,19 @@ export function TukeyHSD(x, g, options = {}) {
104
87
  if (k < 2)
105
88
  throw new RangeError("contrasts can be applied only to factors with 2 or more levels");
106
89
  const confLevel = options.confLevel ?? 0.95;
90
+ // R accepts 0 and 1 (limits diff and ±Inf) but returns NaN limits outside [0, 1]: that is rejected
91
+ checkConfLevel(confLevel);
107
92
  const N = groups.reduce((a, s) => a + s.length, 0);
108
93
  const df = N - k;
109
- const { ssw, means } = sums(groups);
94
+ // No residual variance without residual degrees of freedom (one value per group): the limits and p-values were NaN
95
+ // (R's too). The message is tukeyTest's (#315)
96
+ if (df === 0)
97
+ throw new RangeError("no residual degrees of freedom");
98
+ // ptukey and qtukey (R's too) are defined from 2 df: with 1 the limits and p-values were NaN (#315)
99
+ if (df < 2)
100
+ throw new RangeError("the studentized range needs at least 2 residual degrees of freedom");
101
+ // means and MSE of the data scaled by 2^-e (groupMoments): the differences and limits are scaled back
102
+ const { ssWithin: ssw, mean: means, k: e } = groupMoments(groups);
110
103
  const mse = ssw / df;
111
104
  const q = qtukey(confLevel, k, df);
112
105
  const out = { names: [], i: [], j: [], diff: [], lwr: [], upr: [], pAdj: [] };
@@ -117,9 +110,9 @@ export function TukeyHSD(x, g, options = {}) {
117
110
  out.names.push(`${names[a]}-${names[b]}`);
118
111
  out.i.push(a + 1);
119
112
  out.j.push(b + 1);
120
- out.diff.push(diff);
121
- out.lwr.push(diff - q * se);
122
- out.upr.push(diff + q * se);
113
+ out.diff.push(ldexp(diff, e));
114
+ out.lwr.push(ldexp(diff - q * se, e));
115
+ out.upr.push(ldexp(diff + q * se, e));
123
116
  out.pAdj.push(ptukey(Math.abs(diff) / se, k, df, { lowerTail: false }));
124
117
  }
125
118
  }
@@ -150,6 +143,10 @@ export function zTest(x, y, options = {}) {
150
143
  if (sigmaX === undefined || (ys !== undefined && sigmaY === undefined)) {
151
144
  throw new RangeError("sigmaX and sigmaY are both required for two samples");
152
145
  }
146
+ for (const sd of [sigmaX, sigmaY]) {
147
+ if (sd !== undefined && !(sd > 0 && sd < Infinity))
148
+ throw new RangeError("sigmaX and sigmaY must be positive finite numbers");
149
+ }
153
150
  if (Number.isNaN(mu))
154
151
  throw new RangeError("mu must be a number");
155
152
  const alternative = matchAlternative(options.alternative);
@@ -162,11 +159,16 @@ export function zTest(x, y, options = {}) {
162
159
  throw new RangeError("x needs at least 3 non-missing values");
163
160
  if (yv !== undefined && yv.length < 3)
164
161
  throw new RangeError("y needs at least 3 non-missing values");
165
- const meanX = meanDD(xs)[0];
166
- const meanY = yv === undefined ? NaN : meanDD(yv)[0];
167
- const se = yv === undefined ? sigmaX / Math.sqrt(xs.length) : Math.sqrt(sigmaX ** 2 / xs.length + sigmaY ** 2 / yv.length);
162
+ // the data, the known standard deviations and mu scaled by one power of 2 (exact), so that the squared standard
163
+ // deviations stay in range; the estimates and interval are scaled back
164
+ const sc = scaleToUnit([xs, yv ?? [], [sigmaX, sigmaY ?? 0]]);
165
+ const k = sc.k;
166
+ const [xS, yS, [sxS, syS]] = sc.groups;
167
+ const meanX = meanDD(xS)[0];
168
+ const meanY = yv === undefined ? NaN : meanDD(yS)[0];
169
+ const se = yv === undefined ? sxS / Math.sqrt(xs.length) : Math.sqrt(sxS ** 2 / xs.length + syS ** 2 / yv.length);
168
170
  const target = yv === undefined ? meanX : meanX - meanY;
169
- const z = (target - mu) / se;
171
+ const z = (target - ldexp(mu, -k)) / se;
170
172
  let pValue;
171
173
  let confInt;
172
174
  if (alternative === "less") {
@@ -179,10 +181,22 @@ export function zTest(x, y, options = {}) {
179
181
  }
180
182
  else {
181
183
  pValue = 2 * pnorm(-Math.abs(z));
182
- const half = qnorm(1 - (1 - confLevel) / 2) * se;
184
+ // (for alpha below 1e-8 the upper probability itself: 1 - alpha loses its digits and rounds to 1 below 1.1e-16; review 58)
185
+ const a2 = (1 - confLevel) / 2;
186
+ const half = (a2 < 1e-8 ? qnorm(a2, { lowerTail: false }) : qnorm(1 - (1 - confLevel) / 2)) * se;
183
187
  confInt = [target - half, target + half];
184
188
  }
189
+ confInt = [ldexp(confInt[0], k), ldexp(confInt[1], k)];
185
190
  const twoSample = yv !== undefined;
191
+ // The reported means. Where the common scale, set by sigma, divides a nonzero value below the normal range (#192: x
192
+ // around 1e-308 with sigma 1e308 gave the mean 0), the mean of that sample in its own scale instead, but never scaled
193
+ // up: small data are averaged as they are, so that a subnormal mean is rounded once. Elsewhere the same bits
194
+ const reported = (v, vS) => {
195
+ if (!(k > 0 && v.some((t, j) => t !== 0 && Math.abs(vS[j]) < 2 ** -1022)))
196
+ return ldexp(meanDD(vS)[0], k);
197
+ const own = Math.max(scaleToUnit([v]).k, 0);
198
+ return ldexp(meanDD(own === 0 ? v : v.map((t) => ldexp(t, -own)))[0], own);
199
+ };
186
200
  return {
187
201
  method: twoSample ? "Two-sample z-Test" : "One-sample z-Test",
188
202
  alternative,
@@ -191,7 +205,7 @@ export function zTest(x, y, options = {}) {
191
205
  pValue,
192
206
  confInt,
193
207
  confLevel,
194
- estimate: twoSample ? [meanX, meanY] : meanX,
208
+ estimate: twoSample ? [reported(xs, xS), reported(yv, yS)] : reported(xs, xS),
195
209
  estimateNames: twoSample ? ["mean of x", "mean of y"] : "mean of x",
196
210
  nullValue: mu,
197
211
  nullValueName: twoSample ? "difference in means" : "mean",
@@ -44,3 +44,8 @@ export interface BinomTestResult extends HTest {
44
44
  * @category Hypothesis tests
45
45
  */
46
46
  export declare function binomTest(x: number | readonly [number, number], n?: number | BinomTestOptions, options?: BinomTestOptions): BinomTestResult;
47
+ /**
48
+ * The exact binomial test of xs successes in ns trials, without the check of ns > 0 (poissonTest compares two counts
49
+ * of 0 as R does: p-value 1, interval [0, 1])
50
+ */
51
+ export declare function binomTestCounts(xs: number, ns: number, options?: BinomTestOptions): BinomTestResult;
@@ -8,16 +8,29 @@
8
8
  // quantiles.
9
9
  import { dbinom1, pbinom1 } from "../distributions/binomial.js";
10
10
  import { qbeta1 } from "../distributions/beta.js";
11
- import { checkConfLevelOpen, matchAlternative } from "./types.js";
11
+ import { firstTrue, lastTrue } from "../internal/discrete.js";
12
+ import { twoSum } from "../special/dd.js";
13
+ import { checkConfLevelOpen, isCount, matchAlternative } from "./types.js";
12
14
  /** Relative slack when comparing outcome probabilities with the observed one */
13
15
  const SLACK = 1 + 1e-7;
14
- function isCount(v) {
15
- return Number.isFinite(v) && v >= 0 && Math.abs(v - Math.round(v)) <= 1e-7 * Math.max(1, Math.abs(v));
16
+ /**
17
+ * P[X >= x] under Binomial(n, p). Where x - 1 or n - (x - 1) is not exact (beyond 2^53), P[X > x] + dbinom(x):
18
+ * pbinom(x - 1, upper) took a rounded x - 1 or n - (x - 1) (x = 2^53, n = 2^54, p = 1/2 gave 0.5, true
19
+ * 0.5000000029724; issue #324)
20
+ */
21
+ function atLeast(x, n, p) {
22
+ const xm = x - 1;
23
+ if (x === 0 || (x - xm === 1 && twoSum(n, -xm)[1] === 0))
24
+ return pbinom1(xm, n, p, false, false);
25
+ return pbinom1(x, n, p, false, false) + dbinom1(x, n, p, false);
16
26
  }
17
27
  /**
18
28
  * Two-sided p-value: the total probability of the outcomes no more likely than x (within the relative slack). The
19
- * observed side is one tail of the distribution function; on the opposite side the qualifying outcomes are counted,
20
- * and as they are the most extreme ones there, their mass is again a tail probability.
29
+ * observed side is one tail of the distribution function; on the opposite side the qualifying outcomes are the most
30
+ * extreme ones there, so their mass is again a tail probability. The density decreases from ceil(np) upwards and
31
+ * increases up to floor(np) (the ratio f(i + 1) / f(i) = (n - i) p / ((i + 1)(1 - p)) is below 1 exactly for
32
+ * i > (n + 1) p - 1), so the boundary of the qualifying outcomes is found by search in O(log n) evaluations instead of
33
+ * testing each of the outcomes on that side (which took seconds for n around 1e8).
21
34
  */
22
35
  function twoSidedP(x, n, p) {
23
36
  if (p === 0)
@@ -28,19 +41,17 @@ function twoSidedP(x, n, p) {
28
41
  if (x === mean)
29
42
  return 1;
30
43
  const cut = dbinom1(x, n, p, false) * SLACK;
31
- let count = 0;
44
+ const qualifies = (i) => dbinom1(i, n, p, false) <= cut;
32
45
  if (x < mean) {
33
- for (let i = Math.ceil(mean); i <= n; i++)
34
- if (dbinom1(i, n, p, false) <= cut)
35
- count++;
36
- const other = count === 0 ? 0 : pbinom1(n - count, n, p, false, false);
46
+ // the first qualifying outcome above the mean; those from it to n qualify
47
+ const j = firstTrue(qualifies, Math.ceil(mean), n);
48
+ const other = j > n ? 0 : atLeast(j, n, p);
37
49
  return Math.min(1, pbinom1(x, n, p, true, false) + other);
38
50
  }
39
- for (let i = 0; i <= Math.floor(mean); i++)
40
- if (dbinom1(i, n, p, false) <= cut)
41
- count++;
42
- const other = count === 0 ? 0 : pbinom1(count - 1, n, p, true, false);
43
- return Math.min(1, pbinom1(x - 1, n, p, false, false) + other);
51
+ // the last qualifying outcome below the mean; those from 0 to it qualify
52
+ const j = lastTrue(qualifies, 0, Math.floor(mean));
53
+ const other = j < 0 ? 0 : pbinom1(j, n, p, true, false);
54
+ return Math.min(1, atLeast(x, n, p) + other);
44
55
  }
45
56
  /**
46
57
  * Exact test of a simple null hypothesis about the probability of success in Bernoulli trials. Equivalent to R's
@@ -70,6 +81,10 @@ export function binomTest(x, n, options = {}) {
70
81
  throw new RangeError("'x' must be nonnegative and integer");
71
82
  xs = Math.round(x[0]);
72
83
  ns = Math.round(x[0]) + Math.round(x[1]);
84
+ // no trials: neither the estimate nor the test is defined (R returns a p-value of 1), as for binomTest(0, 0)
85
+ // no trials, or a total that overflows (binomTest([1e308, 1e308]) gave NaN; a scalar n = Infinity is rejected too)
86
+ if (ns === 0 || ns === Infinity)
87
+ throw new RangeError("'n' must be a positive integer >= 'x'");
73
88
  }
74
89
  else {
75
90
  if (typeof n !== "number")
@@ -81,6 +96,13 @@ export function binomTest(x, n, options = {}) {
81
96
  throw new RangeError("'n' must be a positive integer >= 'x'");
82
97
  ns = Math.round(n);
83
98
  }
99
+ return binomTestCounts(xs, ns, options);
100
+ }
101
+ /**
102
+ * The exact binomial test of xs successes in ns trials, without the check of ns > 0 (poissonTest compares two counts
103
+ * of 0 as R does: p-value 1, interval [0, 1])
104
+ */
105
+ export function binomTestCounts(xs, ns, options = {}) {
84
106
  const p = options.p ?? 0.5;
85
107
  if (!(p >= 0 && p <= 1))
86
108
  throw new RangeError("'p' must be a single number between 0 and 1");
@@ -91,11 +113,13 @@ export function binomTest(x, n, options = {}) {
91
113
  if (alternative === "less")
92
114
  pValue = pbinom1(xs, ns, p, true, false);
93
115
  else if (alternative === "greater")
94
- pValue = pbinom1(xs - 1, ns, p, false, false);
116
+ pValue = atLeast(xs, ns, p);
95
117
  else
96
118
  pValue = twoSidedP(xs, ns, p);
97
119
  const lower = (alpha) => (xs === 0 ? 0 : qbeta1(alpha, xs, ns - xs + 1, true, false));
98
- const upper = (alpha) => (xs === ns ? 1 : qbeta1(1 - alpha, xs + 1, ns - xs, true, false));
120
+ // (for alpha below 1e-8 the upper probability itself: 1 - alpha loses its digits, and is 1 below 1.1e-16, which gave
121
+ // the limit 1 at confLevel = 0.9999999999999999)
122
+ const upper = (alpha) => xs === ns ? 1 : alpha < 1e-8 ? qbeta1(alpha, xs + 1, ns - xs, false, false) : qbeta1(1 - alpha, xs + 1, ns - xs, true, false);
99
123
  let confInt;
100
124
  if (alternative === "less")
101
125
  confInt = [0, upper(1 - confLevel)];
@@ -17,9 +17,10 @@ export interface BrunnerMunzelTestOptions {
17
17
  * Brunner-Munzel test that two samples have the relative effect P(X < Y) + P(X = Y)/2 = 1/2, without assuming equal
18
18
  * variances or shapes. Equivalent to `lawstat::brunner.munzel.test()` in R. `NaN` values are dropped.
19
19
  *
20
- * `estimate` is the estimated relative effect and `confInt` its two-sided interval (not clipped to [0, 1]). When a
21
- * sample has one value, or when the variance estimates are 0 (for example completely separated samples), the
22
- * statistic, degrees of freedom and p-value are `NaN` or ±Infinity, as in lawstat.
20
+ * `estimate` is the estimated relative effect and `confInt` its two-sided interval (not clipped to [0, 1]). Each
21
+ * sample needs at least 2 values (lawstat returns NaN for a sample of one). When the variance estimates are 0 (for
22
+ * example completely separated samples), the statistic, degrees of freedom and p-value are `NaN` or ±Infinity, as in
23
+ * lawstat.
23
24
  *
24
25
  * @example
25
26
  * ```ts
@@ -18,9 +18,10 @@ import { checkConfLevel, matchAlternative } from "./types.js";
18
18
  * Brunner-Munzel test that two samples have the relative effect P(X < Y) + P(X = Y)/2 = 1/2, without assuming equal
19
19
  * variances or shapes. Equivalent to `lawstat::brunner.munzel.test()` in R. `NaN` values are dropped.
20
20
  *
21
- * `estimate` is the estimated relative effect and `confInt` its two-sided interval (not clipped to [0, 1]). When a
22
- * sample has one value, or when the variance estimates are 0 (for example completely separated samples), the
23
- * statistic, degrees of freedom and p-value are `NaN` or ±Infinity, as in lawstat.
21
+ * `estimate` is the estimated relative effect and `confInt` its two-sided interval (not clipped to [0, 1]). Each
22
+ * sample needs at least 2 values (lawstat returns NaN for a sample of one). When the variance estimates are 0 (for
23
+ * example completely separated samples), the statistic, degrees of freedom and p-value are `NaN` or ±Infinity, as in
24
+ * lawstat.
24
25
  *
25
26
  * @example
26
27
  * ```ts
@@ -37,9 +38,10 @@ export function brunnerMunzelTest(x, y, options = {}) {
37
38
  const ys = Array.from(y).filter((v) => !Number.isNaN(v));
38
39
  const n1 = xs.length;
39
40
  const n2 = ys.length;
40
- if (n1 < 1)
41
+ // S_i^2 divides by n_i - 1 (lawstat returns NaN for a sample of one)
42
+ if (n1 < 2)
41
43
  throw new RangeError("not enough 'x' observations");
42
- if (n2 < 1)
44
+ if (n2 < 2)
43
45
  throw new RangeError("not enough 'y' observations");
44
46
  const alternative = matchAlternative(options.alternative);
45
47
  const confLevel = options.confLevel ?? 0.95;
@@ -36,7 +36,8 @@ export interface ChisqTestResult extends Omit<HTest, "alternative"> {
36
36
  /**
37
37
  * Standardized residuals `(O - E) / sqrt(V)`, where `V` is
38
38
  * `E (1 - row proportion) (1 - column proportion)` for a contingency table and
39
- * `n p (1 - p)` for goodness of fit.
39
+ * `n p (1 - p)` for goodness of fit. For a contingency table the complements are the other rows' and columns'
40
+ * sums over the total, and the residual and `V` are computed in double-double.
40
41
  */
41
42
  stdres: number[] | number[][];
42
43
  }
@@ -8,20 +8,21 @@
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
18
  // with a zero margin are not simulated (ordinary test), as in R
20
19
  // - Two factor vectors: the table of the complete pairs, with the distinct values sorted by code point (C locale)
21
20
  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";
21
+ import { logFactorialTable, MAX_TABLE_TOTAL, rcont2 } from "../random/r2dtable.js";
22
+ import { sampleIntReplaceDrawer } from "../random/sample.js";
23
+ import { ldexp, productOver, squareOver } from "../internal/summary.js";
24
+ import { compareCodePoints } from "../models/modelFrame.js";
25
+ import { ddAdd, ddDiv, ddMul, ddSub } from "../special/dd.js";
25
26
  import { simulatedMethod } from "./core/simulate.js";
26
27
  /** Sum (accumulated in double-double, then rounded; with Inf present, the double sum = ±Inf or NaN) */
27
28
  function ddSum(x) {
@@ -38,8 +39,6 @@ export function chisqTest(x, yOrOptions, maybeOptions) {
38
39
  return chisqFactors(x, yOrOptions, maybeOptions ?? {});
39
40
  return chisqCounts(x, yOrOptions ?? {});
40
41
  }
41
- /** Code-point order (the C locale) */
42
- const byCodePoint = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
43
42
  function chisqFactors(x, y, options) {
44
43
  if (x.length !== y.length)
45
44
  throw new RangeError("'x' and 'y' must have the same length");
@@ -57,8 +56,8 @@ function chisqFactors(x, y, options) {
57
56
  ys.push(w);
58
57
  }
59
58
  });
60
- const rowLevels = [...new Set(xs)].sort(byCodePoint);
61
- const colLevels = [...new Set(ys)].sort(byCodePoint);
59
+ const rowLevels = [...new Set(xs)].sort(compareCodePoints);
60
+ const colLevels = [...new Set(ys)].sort(compareCodePoints);
62
61
  if (rowLevels.length < 2 || colLevels.length < 2)
63
62
  throw new RangeError("'x' and 'y' must have at least 2 levels");
64
63
  const ri = new Map(rowLevels.map((v, i) => [v, i]));
@@ -87,8 +86,10 @@ function chisqCounts(x, options) {
87
86
  /** Number of replicates, checked when a simulation is run */
88
87
  function replicates(options) {
89
88
  const B = options.B ?? 2000;
90
- if (!(B >= 0 && B < 2 ** 31))
91
- throw new RangeError("'B' must be a non-negative number");
89
+ // 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
90
+ // 1.33, R 1.29). B = 0 simulates nothing (R's p = (1 + 0) / (0 + 1) = 1): an error too (#489)
91
+ if (!(Number.isInteger(B) && B >= 1 && B < 2 ** 31))
92
+ throw new RangeError("'B' must be a positive integer");
92
93
  return B;
93
94
  }
94
95
  /** (1 + #{sims >= (1 - 64 eps) stat}) / (B + 1) */
@@ -98,7 +99,8 @@ function monteCarloP(sims, stat, B) {
98
99
  for (let i = 0; i < sims.length; i++)
99
100
  if (sims[i] >= threshold)
100
101
  count++;
101
- return (1 + count) / (B + 1);
102
+ // the simulations actually made (R divides by B + 1 with a fractional B, of which only the integer part is run)
103
+ return (1 + count) / (Math.trunc(B) + 1);
102
104
  }
103
105
  function pValueOf(stat, df) {
104
106
  return Number.isNaN(stat) ? NaN : pgamma1(stat, df / 2, 2, false, false);
@@ -113,7 +115,8 @@ function checkExpected(E) {
113
115
  }
114
116
  function goodnessOfFit(x, options) {
115
117
  const k = x.length;
116
- if (x.some((v) => Number.isNaN(v) || v < 0))
118
+ // (R lets Infinity through and returns NaN)
119
+ if (x.some((v) => !(v >= 0 && v < Infinity)))
117
120
  throw new RangeError("all entries of 'x' must be non-negative and finite");
118
121
  if (k < 2)
119
122
  throw new TypeError("'x' must have at least 2 elements");
@@ -127,22 +130,40 @@ function goodnessOfFit(x, options) {
127
130
  throw new RangeError("p contains missing values");
128
131
  if (p.some((v) => v < 0))
129
132
  throw new RangeError("probabilities must be non-negative");
133
+ if (p.some((v) => v === Infinity))
134
+ throw new RangeError("probabilities must be finite");
130
135
  if (options.rescaleP ?? false) {
131
- const s = ddSum(p);
132
- p = p.map((v) => v / s);
136
+ // where the total of the finite weights overflows, the weights in units of 2^e, 2^e >= k, first (each weight was
137
+ // divided by Inf and became 0: p = c(1e308, 1e308) gave statistic Inf, p-value 0; R too; issue #303)
138
+ const total = ddSum(p);
139
+ const e = total < Infinity ? 0 : Math.ceil(Math.log2(k));
140
+ const ps = e === 0 ? p : p.map((v) => ldexp(v, -e));
141
+ const s = e === 0 ? total : ddSum(ps);
142
+ p = ps.map((v) => v / s);
133
143
  }
134
144
  else if (Math.abs(ddSum(p) - 1) > Math.sqrt(Number.EPSILON)) {
135
145
  throw new RangeError("probabilities must sum to 1");
136
146
  }
137
- const E = p.map((v) => n * v);
147
+ // where the total overflows (each count finite), the counts in units of 2^s, 2^s >= k and s even, so that their total
148
+ // cannot overflow; the statistic is scaled back by 2^s and the residuals by 2^(s/2). With s = 0 (the total finite)
149
+ // the values are those of the plain counts
150
+ const s = n < Infinity ? 0 : 2 * Math.ceil(Math.log2(k) / 2);
151
+ const xs = s === 0 ? x : x.map((v) => ldexp(v, -s));
152
+ const ns = s === 0 ? n : ddSum(xs);
153
+ const Es = p.map((v) => ns * v);
154
+ const E = s === 0 ? Es : Es.map((e) => ldexp(e, s));
138
155
  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]));
156
+ const Vs = p.map((v, i) => Es[i] * (1 - v));
157
+ const stat = ldexp(ddSum(xs.map((v, i) => squareOver(v - Es[i], Es[i]))), s);
141
158
  let method = "Chi-squared test for given probabilities";
142
159
  let df = k - 1;
143
160
  let pValue;
144
161
  if (options.simulatePValue ?? false) {
145
162
  const B = replicates(options);
163
+ // a fractional total cannot be drawn as a sample: the columns of draws then outnumbered B and the p-value exceeded
164
+ // 1 (c(3.5, 4, 5) with B = 2 gave 1.33; R too)
165
+ if (!Number.isInteger(n))
166
+ throw new RangeError("the simulation needs counts summing to an integer");
146
167
  method += simulatedMethod(B);
147
168
  df = NaN;
148
169
  pValue = monteCarloP(simulateGoodnessOfFit(n, p, E, B), stat, B);
@@ -158,30 +179,28 @@ function goodnessOfFit(x, options) {
158
179
  pValue,
159
180
  observed: x,
160
181
  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])),
182
+ residuals: xs.map((v, i) => ldexp((v - Es[i]) / Math.sqrt(Es[i]), s / 2)),
183
+ stdres: xs.map((v, i) => ldexp((v - Es[i]) / Math.sqrt(Vs[i]), s / 2)),
163
184
  };
164
185
  }
165
186
  /**
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
187
+ * Statistics of B multinomial samples: the B n categories of R's sample.int(k, B n, TRUE, prob = p), taken column by
188
+ * 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
189
+ * (#287): the same uniforms in the same order, so the same statistics. B n is limited to 2^27 draws (tens of seconds)
169
190
  */
170
191
  function simulateGoodnessOfFit(n, p, E, B) {
171
192
  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)
193
+ if (B * n > 2 ** 27)
194
+ throw new RangeError("the simulation needs B * sum(x) <= 2^27 (134217728) draws");
195
+ const draw = sampleIntReplaceDrawer(k, p);
196
+ if (B * n === 0)
175
197
  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);
198
+ const out = new Float64Array(B);
180
199
  const counts = new Float64Array(k);
181
- for (let j = 0; j < cols; j++) {
200
+ for (let j = 0; j < B; j++) {
182
201
  counts.fill(0);
183
- for (let i = 0; i < rows; i++)
184
- counts[draws[(j * rows + i) % draws.length]]++;
202
+ for (let i = 0; i < n; i++)
203
+ counts[draw()]++;
185
204
  let s = 0;
186
205
  for (let c = 0; c < k; c++)
187
206
  s += (counts[c] - E[c]) ** 2 / E[c];
@@ -194,6 +213,9 @@ function simulateTables(sr, sc, E, B) {
194
213
  const nr = sr.length;
195
214
  const nc = sc.length;
196
215
  const total = sr.reduce((a, b) => a + b, 0);
216
+ // the table of log factorials has total + 1 entries: limited as in r2dtable (#285)
217
+ if (total > MAX_TABLE_TOTAL)
218
+ throw new RangeError("the simulation needs a total count of at most 16777216 (2^24)");
197
219
  const fact = logFactorialTable(total);
198
220
  const table = new Int32Array(nr * nc);
199
221
  const out = new Float64Array(Math.trunc(B));
@@ -222,7 +244,7 @@ function contingency(x, options) {
222
244
  throw new RangeError("at least one entry of 'x' must be positive");
223
245
  const sr = x.map((r) => ddSum(r));
224
246
  const sc = x[0].map((_, j) => ddSum(x.map((r) => r[j])));
225
- const E = sr.map((a) => sc.map((b) => (a * b) / n));
247
+ const E = sr.map((a) => sc.map((b) => productOver(a, b, n)));
226
248
  checkExpected(E.flat());
227
249
  const diff = x.map((r, i) => r.map((v, j) => v - E[i][j]));
228
250
  let method = "Pearson's Chi-squared test";
@@ -232,22 +254,24 @@ function contingency(x, options) {
232
254
  const simulate = (options.simulatePValue ?? false) && sr.every((v) => v > 0) && sc.every((v) => v > 0);
233
255
  const yates = !simulate && correct && nr === 2 && nc === 2 ? Math.min(0.5, ...diff.flat().map(Math.abs)) : 0;
234
256
  if (simulate) {
235
- // counts are integers for the simulation (R's C code takes the margins as integers)
257
+ // counts are integers for the simulation: the simulated tables have integer margins, and fractional observed
258
+ // counts would be compared with them (R truncates the margins and runs it)
259
+ if (x.some((r) => r.some((v) => !Number.isInteger(v))))
260
+ throw new RangeError("the simulation needs integer counts");
236
261
  const B = replicates(options);
237
262
  method += simulatedMethod(B);
238
- stat = ddSum(diff.flatMap((r, i) => r.map((d, j) => (d * d) / E[i][j])));
263
+ stat = ddSum(diff.flatMap((r, i) => r.map((d, j) => squareOver(d, E[i][j]))));
239
264
  df = NaN;
240
265
  const sims = simulateTables(sr.map((v) => Math.trunc(v)), sc.map((v) => Math.trunc(v)), E, B);
241
266
  pValue = monteCarloP(sims, stat, B);
242
267
  }
243
268
  else if (yates > 0) {
244
269
  method += " with Yates' continuity correction";
245
- stat = ddSum(diff.flatMap((r, i) => r.map((d, j) => (Math.abs(d) - yates) ** 2 / E[i][j])));
270
+ stat = ddSum(diff.flatMap((r, i) => r.map((d, j) => squareOver(Math.abs(d) - yates, E[i][j]))));
246
271
  }
247
272
  else {
248
- stat = ddSum(diff.flatMap((r, i) => r.map((d, j) => (d * d) / E[i][j])));
273
+ stat = ddSum(diff.flatMap((r, i) => r.map((d, j) => squareOver(d, E[i][j]))));
249
274
  }
250
- const V = E.map((r, i) => r.map((e, j) => e * (1 - sr[i] / n) * (1 - sc[j] / n)));
251
275
  return {
252
276
  method,
253
277
  statistic: stat,
@@ -258,6 +282,69 @@ function contingency(x, options) {
258
282
  observed: x,
259
283
  expected: E,
260
284
  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]))),
285
+ stdres: contingencyStdres(x, n, sr, sc, E, diff),
262
286
  };
263
287
  }
288
+ /**
289
+ * Standardized residuals (O - E) / sqrt(E (1 - row proportion) (1 - column proportion)) of a contingency table
290
+ * (#382). The complements 1 - row proportion and 1 - column proportion are the sums of the other rows and columns
291
+ * over n, and the margins, E, O - E and the variance are in double-double, rounded once at the end: 1 - sr / n in
292
+ * double lost the small margins (2^52 and 0.1: 0 for the complement, so -Infinity; integer tables such as
293
+ * [[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
294
+ * beyond the double range keeps the old formula
295
+ */
296
+ function contingencyStdres(x, n, sr, sc, E, diff) {
297
+ if (!Number.isFinite(n)) {
298
+ return diff.map((r, i) => r.map((d, j) => d / Math.sqrt(E[i][j] * (1 - sr[i] / n) * (1 - sc[j] / n))));
299
+ }
300
+ const srD = x.map((r) => ddSumOf(r));
301
+ const scD = x[0].map((_, j) => ddSumOf(x.map((r) => r[j])));
302
+ const nD = ddSumOfDD(srD);
303
+ const cr = othersSums(srD);
304
+ const cc = othersSums(scD);
305
+ const rowC = cr.map((c) => ddDiv(c, nD));
306
+ const colP = scD.map((c) => ddDiv(c, nD));
307
+ const colC = cc.map((c) => ddDiv(c, nD));
308
+ return x.map((r, i) => r.map((v, j) => {
309
+ const e = ddMul(srD[i], colP[j]);
310
+ const d = ddSub([v, 0], e);
311
+ const dd = d[0] + d[1];
312
+ const V = ddMul(ddMul(e, rowC[i]), colC[j]);
313
+ const vv = V[0] + V[1];
314
+ if (vv >= MIN_NORMAL || dd === 0)
315
+ return dd / Math.sqrt(vv);
316
+ // a variance below the normal range: divide by the square roots in turn
317
+ const ee = e[0] + e[1];
318
+ const rc = rowC[i][0] + rowC[i][1];
319
+ const ccj = colC[j][0] + colC[j][1];
320
+ return dd / Math.sqrt(ee) / Math.sqrt(rc) / Math.sqrt(ccj);
321
+ }));
322
+ }
323
+ const MIN_NORMAL = 2 ** -1022;
324
+ function ddSumOf(x) {
325
+ let s = [0, 0];
326
+ for (const v of x)
327
+ s = ddAdd(s, [v, 0]);
328
+ return s;
329
+ }
330
+ function ddSumOfDD(x) {
331
+ let s = [0, 0];
332
+ for (const v of x)
333
+ s = ddAdd(s, v);
334
+ return s;
335
+ }
336
+ /** For each i, the double-double sum of the entries other than x[i] (prefix and suffix sums) */
337
+ function othersSums(x) {
338
+ const m = x.length;
339
+ const suffix = new Array(m + 1);
340
+ suffix[m] = [0, 0];
341
+ for (let i = m - 1; i >= 0; i--)
342
+ suffix[i] = ddAdd(x[i], suffix[i + 1]);
343
+ const out = [];
344
+ let prefix = [0, 0];
345
+ for (let i = 0; i < m; i++) {
346
+ out.push(ddAdd(prefix, suffix[i + 1]));
347
+ prefix = ddAdd(prefix, x[i]);
348
+ }
349
+ return out;
350
+ }
@@ -30,7 +30,8 @@ export interface CorTestOptions extends CorOptions {
30
30
  /**
31
31
  * Compute an exact p-value (Kendall and Spearman). Default: as in R, exact when there are
32
32
  * no ties and n < 50 (Kendall) or n <= 1290 (Spearman). With ties the approximation is
33
- * always used.
33
+ * always used. Kendall's exact distribution takes about n^3 / 2 steps: for n above 1290 (about 5 s)
34
+ * `exact: true` without ties is a RangeError (R computes it however long it takes).
34
35
  */
35
36
  exact?: boolean;
36
37
  /** Confidence level of the interval (Pearson only; the interval needs at least 4 pairs). Default `0.95`. */