@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
@@ -6,10 +6,12 @@
6
6
  // c = sum (1 - w_i / sum w)^2 / (n_i - 1) / (k^2 - 1), on (k - 1, 1 / (3 c)) degrees of freedom.
7
7
  // shapiro.test: W and its p-value from src/htest/core/shapiro.ts (Royston's AS R94).
8
8
  import { pf1 } from "../distributions/f.js";
9
- import { mean, variance } from "../internal/summary.js";
9
+ import { groupMoments, ldexpWide } from "../internal/summary.js";
10
10
  import { swilkOneMinusW, swilkPValueFromOneMinusW } from "./core/shapiro.js";
11
11
  import { toGroups } from "./groups.js";
12
+ import { checkPooledVariance } from "./multipleComparisons.js";
12
13
  import { onewayData } from "./testFormula.js";
14
+ const MIN_NORMAL = 2 ** -1022;
13
15
  export function onewayTest(x, g, options = {}) {
14
16
  if (typeof x === "string") {
15
17
  const d = onewayData(x, g);
@@ -20,7 +22,11 @@ export function onewayTest(x, g, options = {}) {
20
22
  options = g;
21
23
  else
22
24
  labels = g;
23
- const groups = toGroups(x, labels);
25
+ // moments of the data scaled by a power of 2 (exact), so that the variances stay in range; the statistic has no
26
+ // units
27
+ const raw = toGroups(x, labels);
28
+ const gm = groupMoments(raw);
29
+ const groups = gm.groups;
24
30
  const varEqual = options.varEqual ?? false;
25
31
  const k = groups.length;
26
32
  if (k < 2)
@@ -28,13 +34,14 @@ export function onewayTest(x, g, options = {}) {
28
34
  const ni = groups.map((s) => s.length);
29
35
  if (ni.some((n) => n < 2))
30
36
  throw new RangeError("not enough observations");
31
- const mi = groups.map(mean);
32
- const vi = groups.map(variance);
37
+ const mi = gm.mean;
38
+ const vi = gm.variance;
33
39
  const N = ni.reduce((a, b) => a + b, 0);
34
40
  let statistic;
35
41
  let df2;
42
+ let own;
36
43
  if (varEqual) {
37
- const m = mean(groups.flat());
44
+ const m = gm.grandMean;
38
45
  let between = 0;
39
46
  let within = 0;
40
47
  for (let i = 0; i < k; i++) {
@@ -42,8 +49,63 @@ export function onewayTest(x, g, options = {}) {
42
49
  within += (ni[i] - 1) * vi[i];
43
50
  }
44
51
  df2 = N - k;
52
+ // every group constant: an error, as tukeyTest (R's F Inf and p 0, or NaN for equal means)
53
+ checkPooledVariance(df2, gm.ssWithin);
45
54
  statistic = between / (k - 1) / (within / df2);
46
55
  }
56
+ else if (vi.some((v) => !(v >= MIN_NORMAL)) && (own = ownScaleMoments(raw)) !== undefined) {
57
+ // A variance underflows (or is subnormal) on the common scale although no group is constant (#393; as #270 for
58
+ // bartlettTest): each group on its own scale 2^-k_i, the weights and the terms as a mantissa and a power of 2,
59
+ // and F in the pairwise form sum_{i<j} w_i w_j (m_i - m_j)^2 / sum w, with 1 - w_i / sum w = (the sum of the
60
+ // other weights) / sum w
61
+ const w = own.map((o, i) => splitPow2(ni[i] / o.variance, -2 * o.k));
62
+ const top = Math.max(...w.map((x) => x.e));
63
+ const parts = w.map((x) => ldexpWide(x.m, x.e - top));
64
+ const sw = parts.reduce((s, v) => s + v, 0);
65
+ let c = 0;
66
+ for (let i = 0; i < k; i++) {
67
+ const others = parts.reduce((s, v, j) => (j === i ? s : s + v), 0);
68
+ c += (others / sw) ** 2 / (ni[i] - 1);
69
+ }
70
+ c /= k * k - 1;
71
+ const terms = [];
72
+ for (let i = 0; i < k; i++) {
73
+ for (let j = i + 1; j < k; j++) {
74
+ // m_i - m_j in units of 2^max(k_i, k_j)
75
+ const [p, q] = own[i].k >= own[j].k ? [own[i], own[j]] : [own[j], own[i]];
76
+ const d = p.mean - ldexpWide(q.mean, q.k - p.k);
77
+ if (d === 0)
78
+ continue;
79
+ const dd = splitPow2(d, p.k);
80
+ terms.push({ m: (w[i].m * w[j].m * dd.m * dd.m) / sw, e: w[i].e + w[j].e + 2 * dd.e - top });
81
+ }
82
+ }
83
+ const peak = Math.max(...terms.map((t) => t.e));
84
+ const sum = terms.reduce((s, t) => s + ldexpWide(t.m, t.e - peak), 0);
85
+ statistic = (terms.length === 0 ? 0 : ldexpWide(sum, peak)) / ((k - 1) * (1 + 2 * (k - 2) * c));
86
+ df2 = 1 / (3 * c);
87
+ }
88
+ else if (vi.some((v) => v === 0)) {
89
+ // a constant group z (#313): as its variance tends to 0, w_z -> Infinity, the weighted mean -> m_z, and
90
+ // F -> sum_{i != z} w_i (m_i - m_z)^2 / ((k - 1)(1 + 2 (k - 2) c)), c = sum_{i != z} 1 / (n_i - 1) / (k^2 - 1)
91
+ // (for k = 2 the square of Welch's t). With two or more constant groups the limit depends on how the variances
92
+ // tend to 0 (df2, and F for equal means), so the test is not defined
93
+ const zero = vi.flatMap((v, i) => (v === 0 ? [i] : []));
94
+ if (zero.length > 1)
95
+ throw new RangeError("Welch's test is not defined with two or more constant groups");
96
+ const z = zero[0];
97
+ let c = 0;
98
+ let num = 0;
99
+ for (let i = 0; i < k; i++) {
100
+ if (i === z)
101
+ continue;
102
+ c += 1 / (ni[i] - 1);
103
+ num += (ni[i] / vi[i]) * (mi[i] - mi[z]) ** 2;
104
+ }
105
+ c /= k * k - 1;
106
+ statistic = num / ((k - 1) * (1 + 2 * (k - 2) * c));
107
+ df2 = 1 / (3 * c);
108
+ }
47
109
  else {
48
110
  const wi = ni.map((n, i) => n / vi[i]);
49
111
  const sw = wi.reduce((a, b) => a + b, 0);
@@ -103,3 +165,32 @@ export function shapiroTest(x) {
103
165
  pValue: swilkPValueFromOneMinusW(w1, n),
104
166
  };
105
167
  }
168
+ /**
169
+ * Each group's mean and variance on its own scale 2^-k (#393); undefined when a group is constant (its weight is
170
+ * infinite: #313)
171
+ */
172
+ function ownScaleMoments(groups) {
173
+ const out = [];
174
+ for (const g of groups) {
175
+ const m = groupMoments([g]);
176
+ const variance = m.variance[0];
177
+ if (!(variance > 0))
178
+ return undefined;
179
+ out.push({ mean: m.mean[0], variance, k: m.k });
180
+ }
181
+ return out;
182
+ }
183
+ /** v 2^e (v finite and nonzero) as m 2^e' with abs(m) in [1, 2) */
184
+ function splitPow2(v, e) {
185
+ let f = Math.floor(Math.log2(Math.abs(v)));
186
+ let m = ldexpWide(v, -f);
187
+ if (Math.abs(m) >= 2) {
188
+ m /= 2;
189
+ f++;
190
+ }
191
+ else if (Math.abs(m) < 1) {
192
+ m *= 2;
193
+ f--;
194
+ }
195
+ return { m, e: e + f };
196
+ }
@@ -14,7 +14,7 @@ export interface PAdjustOptions {
14
14
  method?: PAdjustMethod | (string & {});
15
15
  /**
16
16
  * Number of comparisons. Default: the number of non-`NaN` p-values. Must not be smaller
17
- * than that; must be an integer for `"hommel"`.
17
+ * than that; must be an integer and at most 65536 for `"hommel"`.
18
18
  */
19
19
  n?: number;
20
20
  }
@@ -23,7 +23,8 @@ export interface PAdjustOptions {
23
23
  *
24
24
  * `NaN` values are excluded from the adjustment and returned as `NaN` in place. If `n` is
25
25
  * 1 or less, the p-values are returned unchanged. Differences from R: with `"hommel"` a
26
- * non-integer `n` is an error, and an empty `p` always gives an empty result.
26
+ * non-integer `n` or an `n` above 65536 (O(n^2) work, about 6 s at the limit) is an error, and an empty `p` always
27
+ * gives an empty result.
27
28
  *
28
29
  * @param p p-values.
29
30
  * @param options See {@link PAdjustOptions}, or just the method name as a string.
@@ -12,7 +12,7 @@
12
12
  // - p outside [0, 1] is computed as is, like R (capped at 1 above, not bounded below)
13
13
  // Differences from R: with Hommel, a non-integer n is an error (R silently returns something). For a length-0 p
14
14
  // with Hommel and n > 0, R returns a length-1 value; here a length-0 result is returned
15
- import { sum } from "../internal/summary.js";
15
+ import { wideSum, wideSumAdd, wideSumValue } from "../internal/summary.js";
16
16
  const METHODS = ["holm", "hochberg", "hommel", "bonferroni", "BH", "BY", "fdr", "none"];
17
17
  function matchMethod(m) {
18
18
  if (METHODS.includes(m))
@@ -27,7 +27,8 @@ function matchMethod(m) {
27
27
  *
28
28
  * `NaN` values are excluded from the adjustment and returned as `NaN` in place. If `n` is
29
29
  * 1 or less, the p-values are returned unchanged. Differences from R: with `"hommel"` a
30
- * non-integer `n` is an error, and an empty `p` always gives an empty result.
30
+ * non-integer `n` or an `n` above 65536 (O(n^2) work, about 6 s at the limit) is an error, and an empty `p` always
31
+ * gives an empty result.
31
32
  *
32
33
  * @param p p-values.
33
34
  * @param options See {@link PAdjustOptions}, or just the method name as a string.
@@ -55,7 +56,11 @@ export function pAdjust(p, options = {}) {
55
56
  const n = opts.n ?? lp;
56
57
  if (!(n >= lp))
57
58
  throw new RangeError("n must be at least the number of non-NaN p-values");
58
- if (n <= 1)
59
+ // (an infinite number of comparisons: BY's harmonic sum never ended, and holm gave 1 for every p-value; R stops)
60
+ if (n === Infinity)
61
+ throw new RangeError("n must be finite");
62
+ // no p-values to adjust (empty or all NaN): returned before hommel builds n - lp padding values (#306)
63
+ if (n <= 1 || lp === 0)
59
64
  return all;
60
65
  const pv = idx.map((i) => all[i]);
61
66
  const adj = adjust(pv, method, n);
@@ -104,20 +109,44 @@ function adjust(p, method, n) {
104
109
  // Cumulative minimum of (n / i) p_(i) in decreasing order. BY additionally multiplies by sum_{k=1}^{n} 1/k
105
110
  // (evaluated as q * n / i * p, which rounds the same way as R)
106
111
  // (R's sum accumulates in extended precision, so the sum is taken in double-double)
107
- const q = method === "BY" ? sum(Array.from({ length: Math.floor(n) }, (_, k) => 1 / (k + 1))) : 1;
112
+ // sum_{k=1}^{n} 1/k accumulated term by term (no array of n terms; the same double-double sum as sum())
113
+ let q = 1;
114
+ if (method === "BY") {
115
+ const acc = wideSum();
116
+ const m = Math.floor(n);
117
+ if (m <= 1e6) {
118
+ for (let k = 1; k <= m; k++)
119
+ wideSumAdd(acc, 1 / k, m);
120
+ q = wideSumValue(acc);
121
+ }
122
+ else {
123
+ // the asymptotic expansion of the harmonic number (error below 1/(252 m^6)): the sum took m steps
124
+ const m2 = m * m;
125
+ q = Math.log(m) + 0.5772156649015329 + 1 / (2 * m) - 1 / (12 * m2) + 1 / (120 * m2 * m2);
126
+ }
127
+ }
128
+ // q n overflows for n above about 2.5e305 (BY): then the same products in units of 2^10 (q < 2^10), which
129
+ // round the same way (the values are far above the subnormal range: n p >= 1e305 Number.MIN_VALUE)
130
+ const qn = q * n;
131
+ const unit = Number.isFinite(qn) ? 1 : 1024;
132
+ const qnu = Number.isFinite(qn) ? qn : q * (n / 1024);
108
133
  const o = order(p, true);
109
134
  let m = Infinity;
110
135
  o.forEach((j, k) => {
111
136
  const i = lp - k;
112
- m = Math.min(m, ((q * n) / i) * p[j]);
137
+ m = Math.min(m, (qnu / i) * p[j] * unit);
113
138
  out[j] = Math.min(1, m);
114
139
  });
115
140
  return out;
116
141
  }
117
142
  case "hommel":
118
- return hommel(p, n);
143
+ // as R, Hochberg's method for n = 2 (the same values for p in [0, 1]; p outside it are taken as they are, where
144
+ // the Hommel loop gave [-2, 0.3] for [-2, 0.3], R [-4, 0.3]; #471)
145
+ return n === 2 ? adjust(p, "hochberg", n) : hommel(p, n);
119
146
  }
120
147
  }
148
+ /** Largest n of the Hommel method (#391) */
149
+ const MAX_HOMMEL_N = 2 ** 16;
121
150
  /**
122
151
  * Hommel adjusted p-values (the hommel procedure of statsmodels multipletests).
123
152
  * The n - lp unobserved p are added as 1. O(n^2)
@@ -125,6 +154,9 @@ function adjust(p, method, n) {
125
154
  function hommel(p, n) {
126
155
  if (!Number.isInteger(n))
127
156
  throw new RangeError("n must be an integer for the hommel method");
157
+ // O(n^2) steps: n = 65536 takes about 6 s, 1e5 about 12 s (#391); checked before the padding is built
158
+ if (n > MAX_HOMMEL_N)
159
+ throw new RangeError(`n must be at most ${MAX_HOMMEL_N} for the hommel method (O(n^2) work)`);
128
160
  const lp = p.length;
129
161
  const full = [...p, ...new Array(n - lp).fill(1)];
130
162
  const o = order(full, false);
@@ -1,4 +1,4 @@
1
- import type { GroupLabel } from "./groups.js";
1
+ import { type GroupLabel } from "./groups.js";
2
2
  import { type PAdjustMethod } from "./pAdjust.js";
3
3
  import { type Alternative, type Sample } from "./types.js";
4
4
  import { type WilcoxTestOptions } from "./wilcoxTest.js";
@@ -6,21 +6,23 @@
6
6
  // the standard deviation pooled over all groups, s^2 = sum (n_i - 1) s_i^2 / sum (n_i - 1), with its degrees of
7
7
  // freedom; the other comparisons are the two-sample tests themselves.
8
8
  import { pt1 } from "../distributions/t.js";
9
- import { levelText, numberLevels } from "../internal/levels.js";
10
- import { mean, variance } from "../internal/summary.js";
9
+ import { levelText } from "../internal/levels.js";
10
+ import { groupMoments } from "../internal/summary.js";
11
+ import { compareLabels, factorLabels } from "./groups.js";
12
+ import { checkPooledVariance } from "./multipleComparisons.js";
11
13
  import { pAdjust } from "./pAdjust.js";
12
14
  import { propTest } from "./propTest.js";
13
15
  import { tTest } from "./tTest.js";
14
16
  import { matchAlternative } from "./types.js";
15
17
  import { wilcoxTest } from "./wilcoxTest.js";
16
- /** Group a sample by labels: levels sorted (numbers numerically, strings in code-unit order), values in input order */
18
+ /** Group a sample by labels: levels sorted (numbers numerically, strings by code point), values in input order */
17
19
  function byLevel(x, g, dropNaN) {
18
20
  const xs = Array.from(x);
19
21
  if (xs.length !== g.length)
20
22
  throw new RangeError("'x' and 'g' must have the same length");
21
23
  const map = new Map();
22
- // numeric labels with the same 15-digit text are one level, as in R's factor()
23
- const gs = numberLevels(g);
24
+ // numeric labels with the same 15-digit text are one level, and mixed labels are text, as in R's factor()
25
+ const gs = factorLabels(g);
24
26
  for (let i = 0; i < xs.length; i++) {
25
27
  const l = gs[i];
26
28
  if (typeof l === "number" && Number.isNaN(l))
@@ -32,7 +34,7 @@ function byLevel(x, g, dropNaN) {
32
34
  map.set(l, (arr = []));
33
35
  arr.push(xs[i]);
34
36
  }
35
- const levels = Array.from(map.keys()).sort((a, b) => typeof a === "number" && typeof b === "number" ? a - b : String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0);
37
+ const levels = Array.from(map.keys()).sort(compareLabels);
36
38
  return { levels, groups: levels.map((l) => map.get(l)) };
37
39
  }
38
40
  /** Lower-triangular table of compare(i, j) for i > j, adjusted together */
@@ -90,16 +92,16 @@ export function pairwiseTTest(x, g, options = {}) {
90
92
  if (poolSd) {
91
93
  method = "t tests with pooled SD";
92
94
  const n = groups.map((s) => s.length);
93
- const means = groups.map((s) => (s.length > 0 ? mean(s) : NaN));
94
- let ss = 0;
95
+ // moments of the data scaled by a power of 2 (exact), so that the variances stay in range; t has no units
96
+ const gm = groupMoments(groups);
97
+ const means = gm.mean;
95
98
  let df = 0;
96
- groups.forEach((s) => {
97
- if (s.length > 1) {
98
- ss += variance(s) * (s.length - 1);
99
- df += s.length - 1;
100
- }
101
- });
102
- const sd = Math.sqrt(ss / df);
99
+ for (const m of n)
100
+ if (m > 1)
101
+ df += m - 1;
102
+ // every group constant: an error, as tukeyTest (R's p-values 0, or NaN for equal means)
103
+ checkPooledVariance(df, gm.ssWithin);
104
+ const sd = Math.sqrt(gm.ssWithin / df);
103
105
  compare = (i, j) => {
104
106
  const t = (means[i] - means[j]) / (sd * Math.sqrt(1 / n[i] + 1 / n[j]));
105
107
  if (alternative === "less")
@@ -5,7 +5,7 @@ import { type Alternative, type HTest } from "./types.js";
5
5
  * @category Hypothesis tests
6
6
  */
7
7
  export interface PoissonTestOptions {
8
- /** Time base(s): one per count, nonnegative. Default `1` (or `[1, 1]`). */
8
+ /** Time base(s): one per count, positive and finite (R accepts 0 and returns NaN or Inf; an error here). Default `1` (or `[1, 1]`). */
9
9
  T?: number | readonly number[];
10
10
  /** Hypothesized rate, or rate ratio for two samples (nonnegative). Default `1`. */
11
11
  r?: number;
@@ -8,12 +8,11 @@
8
8
  // p / (1 - p) T2 / T1.
9
9
  import { dpois1, ppois1 } from "../distributions/poisson.js";
10
10
  import { qgamma1 } from "../distributions/gamma.js";
11
- import { binomTest } from "./binomTest.js";
12
- import { checkConfLevelOpen, matchAlternative } from "./types.js";
11
+ import { firstTrue, lastTrue } from "../internal/discrete.js";
12
+ import { ldexp } from "../internal/summary.js";
13
+ import { binomTestCounts } from "./binomTest.js";
14
+ import { checkConfLevel, checkConfLevelOpen, isCount, matchAlternative } from "./types.js";
13
15
  const REL_ERR = 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
16
  /**
18
17
  * Two-sided p-value of the count x under Poisson(m): the total probability of the counts whose probability is at most
19
18
  * (1 + 1e-7) times that of x. The density is unimodal (increasing up to floor(m), decreasing after), so the observed
@@ -29,48 +28,73 @@ function twoSidedP(x, m) {
29
28
  const qualifies = (i) => dpois1(i, m, false) <= cut;
30
29
  const mode = Math.floor(m);
31
30
  if (x < m) {
32
- // smallest j >= start with dpois(j) <= cut; densities decrease from the mode onwards (with m an integer, m - 1
33
- // and m are equally likely, so starting at x + 1 picks up m when x = m - 1)
34
- const start = Math.max(x + 1, mode);
35
- let j = start;
36
- if (!qualifies(start)) {
37
- let fails = start; // largest count known not to qualify
38
- let step = 1;
39
- j = start + 1;
40
- while (!qualifies(j)) {
41
- fails = j;
42
- step *= 2;
43
- j = start + step;
44
- }
45
- while (j - fails > 1) {
46
- const mid = fails + Math.floor((j - fails) / 2);
47
- if (qualifies(mid))
48
- j = mid;
49
- else
50
- fails = mid;
51
- }
52
- }
53
- return Math.min(1, ppois1(x, m, true, false) + ppois1(j - 1, m, false, false));
54
- }
55
- // x > m: largest j <= end with dpois(j) <= cut; densities increase from 0 up to the mode (j = -1 when none does)
56
- const end = Math.min(x - 1, mode);
57
- let j;
58
- if (!qualifies(0))
59
- j = -1;
60
- else if (qualifies(end))
61
- j = end;
62
- else {
63
- j = 0;
64
- let fails = end; // smallest count known not to qualify
65
- while (fails - j > 1) {
66
- const mid = j + Math.floor((fails - j) / 2);
67
- if (qualifies(mid))
68
- j = mid;
69
- else
70
- fails = mid;
71
- }
31
+ // smallest j >= max(x + 1, mode) with dpois(j) <= cut; densities decrease from the mode onwards (with m an
32
+ // integer, m - 1 and m are equally likely, so starting at x + 1 picks up m when x = m - 1)
33
+ const j = firstTrue(qualifies, Math.max(x + 1, mode), Infinity);
34
+ return Math.min(1, ppois1(x, m, true, false) + atLeast(j, m));
72
35
  }
73
- return Math.min(1, ppois1(j, m, true, false) + ppois1(x - 1, m, false, false));
36
+ // x > m: largest j <= min(x - 1, mode) with dpois(j) <= cut; densities increase from 0 up to the mode (j = -1
37
+ // when none does)
38
+ const j = lastTrue(qualifies, 0, Math.min(x - 1, mode));
39
+ return Math.min(1, ppois1(j, m, true, false) + atLeast(x, m));
40
+ }
41
+ const MIN_NORMAL = 2 ** -1022;
42
+ /**
43
+ * P[X >= x] under Poisson(m). Where x - 1 is not exact (x beyond 2^53), P[X > x] + dpois(x): ppois(x - 1, upper)
44
+ * rounded x - 1 and dropped or added a point mass (x = 2^53 + 2, m = x gave 0.5000000056047, true 0.5000000014012;
45
+ * issue #323)
46
+ */
47
+ function atLeast(x, m) {
48
+ return x - (x - 1) === 1 ? ppois1(x - 1, m, false, false) : ppois1(x, m, false, false) + dpois1(x, m, false);
49
+ }
50
+ /** [f, e] with v = f 2^e, f in [1, 2) up to the rounding of log2 (v > 0 finite, subnormal v included; exact) */
51
+ function frexp(v) {
52
+ const s = v < 2 ** -1000 ? 600 : 0;
53
+ const e = Math.floor(Math.log2(v * 2 ** s));
54
+ return [v * 2 ** s * 2 ** -e, e - s];
55
+ }
56
+ /**
57
+ * n r T1 / (T1 + r T2), with the ratio T2 / T1 where the products overflow, fall below the normal range or underflow
58
+ * to 0. Where that
59
+ * overflows too (n r, or r T2 / T1; #223: n = 1e308, r = 2, T = (1, 1e308) gave Inf / Inf), from the mantissas of n, r,
60
+ * T1 and T2 with their powers of 2 applied last
61
+ */
62
+ function expectedCount1(n, r, T1, T2) {
63
+ const den = T1 + r * T2;
64
+ const v = (n * r * T1) / den;
65
+ // (a 0 from positive n and r is n r T1 underflowing, not the value: n = T2 = MAX_VALUE, r = T1 = MIN_VALUE gave 0
66
+ // for MIN_VALUE; issue #481)
67
+ if (Number.isFinite(v) && Number.isFinite(den) && den >= MIN_NORMAL && (v !== 0 || n === 0 || r === 0))
68
+ return v;
69
+ const nr = n * r;
70
+ const den1 = 1 + r * (T2 / T1);
71
+ // (n or r of 0: 0, as R's n r T1 / (T1 + r T2); 0 r (T2 / T1) here was 0 Inf = NaN)
72
+ if (n === 0 || r === 0)
73
+ return 0;
74
+ if (Number.isFinite(nr) && Number.isFinite(den1))
75
+ return nr / den1;
76
+ const [fn, en] = frexp(n);
77
+ const [fr, er] = frexp(r);
78
+ const [f1, e1] = frexp(T1);
79
+ const [f2, e2] = frexp(T2);
80
+ // T1 / (T1 + r T2) = f1 / (f1 + f 2^-d) = 2^d f1 / (2^d f1 + f), with f = fr f2 in [1, 4) and d = e1 - er - e2; the
81
+ // power of 2 goes on the term it makes smaller (2^-d for d >= 0, 2^d otherwise), so g is in (0, 2) and fn fr g < 8
82
+ const f = fr * f2;
83
+ const d = e1 - er - e2;
84
+ const g = d >= 0 ? f1 / (f1 + ldexp(f, -d)) : f1 / (ldexp(f1, d) + f);
85
+ return ldexp(fn * fr * g, en + er + Math.min(d, 0));
86
+ }
87
+ /** (x1 / T1) / (x2 / T2), as (x1 / x2) (T2 / T1) where the rates overflow or fall below the normal range */
88
+ function rateRatio(x1, x2, T1, T2) {
89
+ const r1 = x1 / T1;
90
+ const r2 = x2 / T2;
91
+ const v = r1 / r2;
92
+ if (x2 === 0 || (Number.isFinite(r1) && Number.isFinite(r2) && r2 >= MIN_NORMAL && (r1 === 0 || r1 >= MIN_NORMAL)))
93
+ return v;
94
+ // (x1 of 0: 0; 0 (T2 / T1) was 0 Inf = NaN for T = (5e-324, 1e308); issue #325)
95
+ if (x1 === 0)
96
+ return 0;
97
+ return (x1 / x2) * (T2 / T1);
74
98
  }
75
99
  /**
76
100
  * Exact test of a Poisson rate, or comparison of two Poisson rates. Equivalent to R's `poisson.test()`.
@@ -98,36 +122,63 @@ export function poissonTest(x, options = {}) {
98
122
  const T = typeof Traw === "number" ? new Array(k).fill(Traw) : Array.from(Traw);
99
123
  if (T.length !== k)
100
124
  throw new RangeError("'x' and 'T' have incompatible length");
101
- // as in R, a time base or rate of 0 is accepted (the counts then have mean 0 under the null hypothesis)
102
- if (!T.every((t) => Number.isFinite(t) && t >= 0))
103
- throw new RangeError("'T' must be nonnegative");
125
+ // a time base of 0 defines no rate (R accepts it and returns NaN or Infinity for the estimate and the interval); a
126
+ // rate r of 0 is accepted, as in R (the counts then have mean 0 under the null hypothesis)
127
+ if (!T.every((t) => Number.isFinite(t) && t > 0))
128
+ throw new RangeError("'T' must be positive");
104
129
  const r = options.r ?? 1;
105
130
  if (!(Number.isFinite(r) && r >= 0))
106
131
  throw new RangeError("'r' must be a single positive number");
107
132
  const alternative = matchAlternative(options.alternative);
108
133
  const confLevel = options.confLevel ?? 0.95;
109
- checkConfLevelOpen(confLevel);
134
+ // as in R, the one-sample interval takes the closed range (at 1 it is [0, Inf)); the two-sample one goes through
135
+ // binomTest, which needs 0 < confLevel < 1
136
+ if (k === 2)
137
+ checkConfLevelOpen(confLevel);
138
+ else
139
+ checkConfLevel(confLevel);
110
140
  if (k === 2) {
111
141
  const [x1, x2] = counts;
112
142
  const [T1, T2] = T;
113
143
  const n = x1 + x2;
114
- // NaN (rejected by binomTest, as in R) when both r T1 and T2 are 0. The [successes, failures] form also takes
115
- // a total of 0 (p-value 1, interval [0, 1]), where binomTest(0, 0) is an error as in R
116
- const p0 = (r * T1) / (r * T1 + T2);
117
- const b = binomTest([x1, x2], { p: p0, alternative, confLevel });
118
- const toRatio = (p) => (p / (1 - p)) * (T2 / T1);
144
+ // (two counts whose sum overflows: R stops; binomTest would have n = Infinity)
145
+ if (n === Infinity)
146
+ throw new RangeError("'x' must be finite, nonnegative, and integer");
147
+ // Two counts of 0 give p-value 1 and the interval [0, 1] as in R, where binomTest([0, 0]) and binomTest(0, 0) are
148
+ // errors. Where r T1 + T2 overflows or is not a normal number, the ratio of the time bases instead
149
+ // (T = c(1e308, 1e308) gave p0 = 0 and a p-value of 0; R too)
150
+ const a = r * T1;
151
+ const den = a + T2;
152
+ const p0 = Number.isFinite(den) && den >= MIN_NORMAL && (a === 0 || a >= MIN_NORMAL) ? a / den : 1 / (1 + T2 / T1 / r);
153
+ const b = binomTestCounts(Math.round(x1), Math.round(x1) + Math.round(x2), { p: p0, alternative, confLevel });
154
+ // (a limit p of 0 is the ratio 0, also where T2 / T1 overflows: 0 Inf was NaN; issue #325)
155
+ // Where T2 / T1 overflows, the odds p / (1 - p) and T2 / T1 from their mantissas with the powers of 2 applied last
156
+ // (a subnormal limit p for a count of about MAX_VALUE: T = (1e-12, MAX_VALUE) gave [Inf, Inf] for [2.5e10, 5.6e12];
157
+ // issue #482)
158
+ const t21 = T2 / T1;
159
+ const toRatio = (p) => {
160
+ if (p === 0)
161
+ return 0;
162
+ const odds = p / (1 - p);
163
+ if (Number.isFinite(t21) || odds === Infinity)
164
+ return odds * t21;
165
+ const [fo, eo] = frexp(odds);
166
+ const [f1, e1] = frexp(T1);
167
+ const [f2, e2] = frexp(T2);
168
+ return ldexp((fo * f2) / f1, eo + e2 - e1);
169
+ };
119
170
  return {
120
171
  method: "Comparison of Poisson rates",
121
172
  alternative,
122
173
  statistic: x1,
123
174
  statisticName: "count1",
124
175
  // R reports sum(x) r T1 / (T1 + r T2) here (r on the other time base than in the binomial probability)
125
- parameter: (n * r * T1) / (T1 + r * T2),
176
+ parameter: expectedCount1(n, r, T1, T2),
126
177
  parameterName: "expected count1",
127
178
  pValue: b.pValue,
128
179
  confInt: [toRatio(b.confInt[0]), toRatio(b.confInt[1])],
129
180
  confLevel,
130
- estimate: x1 / T1 / (x2 / T2),
181
+ estimate: rateRatio(x1, x2, T1, T2),
131
182
  estimateNames: "rate ratio",
132
183
  nullValue: r,
133
184
  nullValueName: "rate ratio",
@@ -140,11 +191,12 @@ export function poissonTest(x, options = {}) {
140
191
  if (alternative === "less")
141
192
  pValue = ppois1(xv, m, true, false);
142
193
  else if (alternative === "greater")
143
- pValue = ppois1(xv - 1, m, false, false);
194
+ pValue = atLeast(xv, m);
144
195
  else
145
196
  pValue = twoSidedP(xv, m);
146
197
  const lower = (alpha) => (xv === 0 ? 0 : qgamma1(alpha, xv, 1, true, false));
147
- const upper = (alpha) => qgamma1(1 - alpha, xv + 1, 1, true, false);
198
+ // (for alpha below 1e-8 the upper probability itself, as in binomTest: 1 - alpha rounds to 1 below 1.1e-16)
199
+ const upper = (alpha) => alpha < 1e-8 ? qgamma1(alpha, xv + 1, 1, false, false) : qgamma1(1 - alpha, xv + 1, 1, true, false);
148
200
  let ci;
149
201
  if (alternative === "less")
150
202
  ci = [0, upper(1 - confLevel)];
@@ -17,10 +17,11 @@ import { pbvnorm } from "../distributions/bvnorm.js";
17
17
  import { dnorm, pnorm, qnorm } from "../distributions/normal.js";
18
18
  import { pearsonDD } from "./cor.js";
19
19
  import { numberLevels } from "../internal/levels.js";
20
- import { mean, sum, variance } from "../internal/summary.js";
20
+ import { ldexp, mean, scaleToUnit, sum, variance } from "../internal/summary.js";
21
21
  import { optimize } from "../numerics/integrate.js";
22
22
  import { solve } from "../linalg/solve.js";
23
23
  import { formatR } from "./core/simulate.js";
24
+ import { maxOf } from "../internal/extremes.js";
24
25
  const BOUND = 0.9999;
25
26
  /** Normal quantiles of the cumulative proportions of the counts, without the last (which would be +Inf) */
26
27
  function thresholds(counts) {
@@ -40,7 +41,10 @@ const isVector = (v) => Array.isArray(v) || ArrayBuffer.isView(v);
40
41
  /** Φ(hi) − Φ(lo) for lo ≤ hi, from the upper tails when both are positive (no cancellation near 1) */
41
42
  const normalInterval = (lo, hi) => lo > 0 ? pnorm(lo, { lowerTail: false }) - pnorm(hi, { lowerTail: false }) : pnorm(hi) - pnorm(lo);
42
43
  /** v standardised to mean 0 and sample standard deviation 1 */
43
- function standardise(v) {
44
+ function standardise(data) {
45
+ // divided by a power of 2 first (exact; the standardised values do not depend on it): the sum of squares of values
46
+ // around 1e200 overflowed, and polyserial gave rho = 2e-9 instead of 0.589
47
+ const v = scaleToUnit([data]).groups[0];
44
48
  const m = mean(v);
45
49
  const centred = v.map((x) => x - m);
46
50
  const sd = Math.sqrt(variance(centred));
@@ -249,7 +253,7 @@ function newtonIterations(evaluate, start, startBounded) {
249
253
  next[0] = Math.sign(next[0]) * BOUND;
250
254
  const nextAt = evaluate(next);
251
255
  if (noLowerThan(nextAt.value, at.value)) {
252
- const moved = Math.max(...next.map((v, k) => Math.abs(v - theta[k]) / Math.max(1, Math.abs(theta[k]))));
256
+ const moved = maxOf(next.map((v, k) => Math.abs(v - theta[k]) / Math.max(1, Math.abs(theta[k]))));
253
257
  theta = next;
254
258
  at = nextAt;
255
259
  accepted = moved > 1e-12;
@@ -302,6 +306,8 @@ export function polychor(x, yOrOptions, maybeOptions) {
302
306
  if (t.some((r) => r.length !== k))
303
307
  throw new TypeError("the table must have rows of equal length");
304
308
  tab = t.map((r) => Array.from(r));
309
+ if (tab.some((r) => r.some((v) => !(v >= 0 && v < Infinity))))
310
+ throw new RangeError("the counts of the table must be nonnegative and finite");
305
311
  options = yOrOptions ?? {};
306
312
  }
307
313
  else {
@@ -321,6 +327,12 @@ export function polychor(x, yOrOptions, maybeOptions) {
321
327
  }
322
328
  const { ML = false, stdErr = false } = options;
323
329
  const warnings = [];
330
+ // Where the total is 2^1000 or more (the log-likelihood, up to the total times 745, could overflow, and the total
331
+ // itself may), the counts are divided by a power of 2, 2^k: the thresholds and rho do not depend on the units of
332
+ // the counts, and the variances, the chi-square and n are multiplied back below
333
+ let k = 0;
334
+ if (!(sum(tab.map((row) => sum(row))) < 2 ** 1000))
335
+ ({ groups: tab, k } = scaleToUnit(tab));
324
336
  const rowSums = tab.map((r) => sum(r));
325
337
  const zeroRows = rowSums.filter((s) => s === 0).length;
326
338
  if (zeroRows > 0) {
@@ -378,23 +390,31 @@ export function polychor(x, yOrOptions, maybeOptions) {
378
390
  const n = sum(tab.map((row) => sum(row)));
379
391
  // chisq = 2 (−ℓ + Σ n_ij log((n_ij + 1e-6)/n)) = 2 Σ [n log(1 + 1e-6/n) + n (ε − log(1 + ε))] + 2 n Σ_{empty} P
380
392
  const terms = [];
393
+ // with scaled counts, the terms n log(1 + 1e-6 / n) (absolute, about 1e-6 each) from the original counts
394
+ const fixed = [];
381
395
  for (let i = 0; i < r; i++) {
382
396
  for (let j = 0; j < c; j++) {
383
397
  const count = tab[i][j];
384
398
  const prob = pbvnorm([fittedRow[i], fittedCol[j]], [fittedRow[i + 1], fittedCol[j + 1]], rho);
385
399
  if (count === 0)
386
400
  terms.push(n * prob);
387
- else
401
+ else if (k === 0)
388
402
  terms.push(count * Math.log1p(1e-6 / count), count * excessOverLog1p((n * prob) / count - 1));
403
+ else {
404
+ const original = ldexp(count, k);
405
+ fixed.push(original * Math.log1p(1e-6 / original));
406
+ terms.push(count * excessOverLog1p((n * prob) / count - 1));
407
+ }
389
408
  }
390
409
  }
410
+ const variances = inverseNegHessian(at.hessian, bounded);
391
411
  return {
392
412
  rho,
393
413
  warnings,
394
- var: inverseNegHessian(at.hessian, bounded),
395
- chisq: 2 * sum(terms),
414
+ var: k === 0 ? variances : variances.map((row) => row.map((v) => ldexp(v, -k))),
415
+ chisq: k === 0 ? 2 * sum(terms) : ldexp(2 * sum(terms), k) + 2 * sum(fixed),
396
416
  df: r * c - r - c,
397
- n,
417
+ n: ldexp(n, k),
398
418
  rowCuts: fittedRow.slice(1, r),
399
419
  colCuts: fittedCol.slice(1, c),
400
420
  };