@numero-uno-jpn/rstats 0.15.2 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (297) hide show
  1. package/CHANGELOG.md +280 -0
  2. package/README.ja.md +40 -33
  3. package/README.md +36 -28
  4. package/dist/chunks/chunk-2D2IQWUQ.js +2 -0
  5. package/dist/chunks/chunk-5UQCRBAG.js +2 -0
  6. package/dist/chunks/chunk-6CSTWA5E.js +2 -0
  7. package/dist/chunks/chunk-72Y3HZID.js +2 -0
  8. package/dist/chunks/chunk-BG2KLEHM.js +2 -0
  9. package/dist/chunks/chunk-CMEKBNHQ.js +2 -0
  10. package/dist/chunks/chunk-FLJNSXSW.js +2 -0
  11. package/dist/chunks/chunk-GM53LWSR.js +2 -0
  12. package/dist/chunks/chunk-JBCA56ZS.js +3 -0
  13. package/dist/chunks/chunk-K3RJAD2T.js +2 -0
  14. package/dist/chunks/chunk-KAZRWIB5.js +2 -0
  15. package/dist/chunks/chunk-KBVVIMXX.js +3 -0
  16. package/dist/chunks/chunk-N3SIFCZX.js +2 -0
  17. package/dist/chunks/chunk-QNNL7AZ3.js +2 -0
  18. package/dist/chunks/chunk-SC6CV4Z3.js +2 -0
  19. package/dist/chunks/chunk-SYWOBOTR.js +2 -0
  20. package/dist/chunks/chunk-URIO5LY5.js +2 -0
  21. package/dist/chunks/chunk-VTUGG2SV.js +2 -0
  22. package/dist/chunks/chunk-W26LRYOJ.js +2 -0
  23. package/dist/chunks/chunk-XHETEYVC.js +2 -0
  24. package/dist/chunks/{chunk-PWVQVJTP.js → chunk-YRZWONZB.js} +1 -1
  25. package/dist/chunks/chunk-ZGABZMWX.js +2 -0
  26. package/dist/data/grouping.js +20 -5
  27. package/dist/descriptive/basic.js +90 -8
  28. package/dist/descriptive/cov.js +12 -4
  29. package/dist/descriptive/dataFrames.d.ts +4 -2
  30. package/dist/descriptive/dataFrames.js +56 -18
  31. package/dist/descriptive/factanal.js +16 -7
  32. package/dist/descriptive/hist.d.ts +8 -5
  33. package/dist/descriptive/hist.js +71 -31
  34. package/dist/descriptive/missing.js +3 -1
  35. package/dist/descriptive/moments.js +72 -19
  36. package/dist/descriptive/omega.d.ts +1 -1
  37. package/dist/descriptive/omega.js +68 -9
  38. package/dist/descriptive/pivot.d.ts +21 -9
  39. package/dist/descriptive/pivot.js +161 -35
  40. package/dist/descriptive/quantile.js +2 -1
  41. package/dist/descriptive/rank.js +4 -1
  42. package/dist/descriptive/table.d.ts +3 -2
  43. package/dist/descriptive/table.js +24 -9
  44. package/dist/descriptive.js +2 -2
  45. package/dist/distributions/arcsine.js +19 -2
  46. package/dist/distributions/beta.js +35 -5
  47. package/dist/distributions/binomial.js +37 -14
  48. package/dist/distributions/bvnorm.js +11 -2
  49. package/dist/distributions/cauchy.js +87 -8
  50. package/dist/distributions/chisq.js +7 -3
  51. package/dist/distributions/exponential.js +11 -1
  52. package/dist/distributions/f.js +73 -22
  53. package/dist/distributions/gamma.js +61 -6
  54. package/dist/distributions/geometric.js +53 -14
  55. package/dist/distributions/hypergeometric.d.ts +5 -1
  56. package/dist/distributions/hypergeometric.js +93 -6
  57. package/dist/distributions/invgamma.js +6 -1
  58. package/dist/distributions/kumaraswamy.js +22 -4
  59. package/dist/distributions/laplace.js +31 -7
  60. package/dist/distributions/logistic.js +11 -2
  61. package/dist/distributions/lognormal.js +20 -3
  62. package/dist/distributions/multinomial.js +54 -11
  63. package/dist/distributions/nbeta.js +128 -35
  64. package/dist/distributions/nchisq.js +85 -14
  65. package/dist/distributions/negbinomial.js +100 -18
  66. package/dist/distributions/normal.js +35 -5
  67. package/dist/distributions/nt.d.ts +28 -3
  68. package/dist/distributions/nt.js +536 -35
  69. package/dist/distributions/pareto.js +9 -1
  70. package/dist/distributions/poisson.js +28 -3
  71. package/dist/distributions/signrank.js +7 -4
  72. package/dist/distributions/summary.js +450 -60
  73. package/dist/distributions/t.js +55 -3
  74. package/dist/distributions/triangular.js +45 -13
  75. package/dist/distributions/tukey.js +21 -2
  76. package/dist/distributions/uniform.js +2 -0
  77. package/dist/distributions/weibull.js +33 -3
  78. package/dist/distributions/wilcox.d.ts +9 -3
  79. package/dist/distributions/wilcox.js +155 -26
  80. package/dist/distributions.js +2 -2
  81. package/dist/htest/agreement.d.ts +3 -2
  82. package/dist/htest/agreement.js +76 -14
  83. package/dist/htest/ansariTest.d.ts +6 -1
  84. package/dist/htest/ansariTest.js +75 -8
  85. package/dist/htest/aov.d.ts +1 -1
  86. package/dist/htest/aov.js +48 -34
  87. package/dist/htest/binomTest.d.ts +5 -0
  88. package/dist/htest/binomTest.js +41 -17
  89. package/dist/htest/brunnerMunzelTest.d.ts +4 -3
  90. package/dist/htest/brunnerMunzelTest.js +7 -5
  91. package/dist/htest/chisqTest.d.ts +2 -1
  92. package/dist/htest/chisqTest.js +130 -43
  93. package/dist/htest/cor.d.ts +2 -1
  94. package/dist/htest/cor.js +17 -19
  95. package/dist/htest/core/ansari.d.ts +9 -0
  96. package/dist/htest/core/ansari.js +21 -1
  97. package/dist/htest/core/kolmogorov.d.ts +25 -0
  98. package/dist/htest/core/kolmogorov.js +123 -0
  99. package/dist/htest/core/mantelhaen.js +6 -4
  100. package/dist/htest/core/shapiro.d.ts +1 -1
  101. package/dist/htest/core/shapiro.js +5 -1
  102. package/dist/htest/dunnett.js +14 -5
  103. package/dist/htest/effectSize.d.ts +2 -0
  104. package/dist/htest/effectSize.js +91 -29
  105. package/dist/htest/fisherTest.d.ts +2 -2
  106. package/dist/htest/fisherTest.js +36 -18
  107. package/dist/htest/groups.d.ts +7 -0
  108. package/dist/htest/groups.js +21 -4
  109. package/dist/htest/ksTest.d.ts +3 -1
  110. package/dist/htest/ksTest.js +23 -2
  111. package/dist/htest/leveneTest.js +19 -3
  112. package/dist/htest/mantelhaenTest.js +125 -25
  113. package/dist/htest/mcnemarTest.js +32 -11
  114. package/dist/htest/multipleComparisons.d.ts +8 -1
  115. package/dist/htest/multipleComparisons.js +44 -21
  116. package/dist/htest/normalityTests.js +44 -10
  117. package/dist/htest/onewayTest.js +96 -5
  118. package/dist/htest/pAdjust.d.ts +3 -2
  119. package/dist/htest/pAdjust.js +38 -6
  120. package/dist/htest/pairwise.d.ts +1 -1
  121. package/dist/htest/pairwise.js +17 -15
  122. package/dist/htest/poissonTest.d.ts +1 -1
  123. package/dist/htest/poissonTest.js +111 -59
  124. package/dist/htest/polycor.js +27 -7
  125. package/dist/htest/power.d.ts +11 -1
  126. package/dist/htest/power.js +112 -8
  127. package/dist/htest/propTest.js +21 -4
  128. package/dist/htest/pwr.js +121 -24
  129. package/dist/htest/rankTests.js +29 -5
  130. package/dist/htest/tTest.js +44 -21
  131. package/dist/htest/trendTests.d.ts +7 -3
  132. package/dist/htest/trendTests.js +114 -20
  133. package/dist/htest/types.d.ts +5 -0
  134. package/dist/htest/types.js +7 -0
  135. package/dist/htest/varTest.js +45 -14
  136. package/dist/htest/wilcoxTest.js +114 -21
  137. package/dist/integrate/quadpack.js +27 -5
  138. package/dist/internal/covmat.d.ts +5 -0
  139. package/dist/internal/covmat.js +20 -0
  140. package/dist/internal/ddexp.d.ts +23 -1
  141. package/dist/internal/ddexp.js +86 -6
  142. package/dist/internal/discrete.d.ts +14 -0
  143. package/dist/internal/discrete.js +78 -5
  144. package/dist/internal/extremes.d.ts +9 -0
  145. package/dist/internal/extremes.js +24 -0
  146. package/dist/internal/fround.js +13 -4
  147. package/dist/internal/integer.d.ts +9 -0
  148. package/dist/internal/integer.js +12 -0
  149. package/dist/internal/invert.d.ts +5 -0
  150. package/dist/internal/invert.js +25 -7
  151. package/dist/internal/noncentral.d.ts +7 -0
  152. package/dist/internal/noncentral.js +9 -0
  153. package/dist/internal/poissonMixture.js +29 -6
  154. package/dist/internal/scaledInverse.d.ts +10 -0
  155. package/dist/internal/scaledInverse.js +22 -0
  156. package/dist/internal/seq.js +15 -2
  157. package/dist/internal/summary.d.ts +90 -0
  158. package/dist/internal/summary.js +458 -39
  159. package/dist/internal/uniroot.d.ts +7 -0
  160. package/dist/internal/uniroot.js +28 -3
  161. package/dist/linalg/basic.d.ts +3 -1
  162. package/dist/linalg/basic.js +51 -7
  163. package/dist/linalg/chol.js +4 -1
  164. package/dist/linalg/dot.d.ts +29 -0
  165. package/dist/linalg/dot.js +132 -0
  166. package/dist/linalg/eigen.d.ts +6 -1
  167. package/dist/linalg/eigen.js +71 -14
  168. package/dist/linalg/expm.d.ts +3 -2
  169. package/dist/linalg/expm.js +109 -15
  170. package/dist/linalg/kappa.js +58 -10
  171. package/dist/linalg/lu.d.ts +2 -1
  172. package/dist/linalg/lu.js +35 -5
  173. package/dist/linalg/matrix.d.ts +14 -0
  174. package/dist/linalg/matrix.js +24 -0
  175. package/dist/linalg/ops.js +60 -13
  176. package/dist/linalg/qr.d.ts +2 -1
  177. package/dist/linalg/qr.js +91 -23
  178. package/dist/linalg/schur.js +11 -3
  179. package/dist/linalg/solve.d.ts +6 -1
  180. package/dist/linalg/solve.js +147 -26
  181. package/dist/linalg/svd.d.ts +9 -2
  182. package/dist/linalg/svd.js +29 -11
  183. package/dist/linalg.js +2 -2
  184. package/dist/mixed.js +4 -4
  185. package/dist/models/anovaSequential.d.ts +16 -1
  186. package/dist/models/anovaSequential.js +124 -25
  187. package/dist/models/aovEz.js +140 -30
  188. package/dist/models/aovStrata.js +55 -22
  189. package/dist/models/carAnova.d.ts +1 -1
  190. package/dist/models/carAnova.js +83 -32
  191. package/dist/models/coxph.js +148 -66
  192. package/dist/models/estimable.d.ts +15 -0
  193. package/dist/models/estimable.js +68 -0
  194. package/dist/models/formula.d.ts +1 -1
  195. package/dist/models/formula.js +26 -8
  196. package/dist/models/glm.d.ts +35 -5
  197. package/dist/models/glm.js +398 -55
  198. package/dist/models/glmAnova.js +84 -13
  199. package/dist/models/glmConfint.d.ts +1 -1
  200. package/dist/models/glmConfint.js +115 -27
  201. package/dist/models/glmFamily.d.ts +10 -0
  202. package/dist/models/glmFamily.js +244 -40
  203. package/dist/models/lm.d.ts +12 -1
  204. package/dist/models/lm.js +235 -36
  205. package/dist/models/lmer.d.ts +20 -1
  206. package/dist/models/lmer.js +109 -27
  207. package/dist/models/lmerAnova.js +37 -4
  208. package/dist/models/lmerHypotheses.d.ts +6 -2
  209. package/dist/models/lmerHypotheses.js +14 -2
  210. package/dist/models/lmerTest.d.ts +9 -2
  211. package/dist/models/lmerTest.js +64 -19
  212. package/dist/models/mauchly.d.ts +4 -1
  213. package/dist/models/mauchly.js +34 -13
  214. package/dist/models/mixedStructure.js +6 -0
  215. package/dist/models/modelFrame.js +8 -2
  216. package/dist/models/modelMatrix.d.ts +3 -1
  217. package/dist/models/modelMatrix.js +40 -15
  218. package/dist/models/scaledTables.d.ts +8 -0
  219. package/dist/models/scaledTables.js +6 -0
  220. package/dist/models/survival.d.ts +6 -1
  221. package/dist/models/survival.js +67 -27
  222. package/dist/models/tiedTimes.d.ts +2 -0
  223. package/dist/models/tiedTimes.js +34 -0
  224. package/dist/numerics/deriv.d.ts +1 -1
  225. package/dist/numerics/deriv.js +64 -8
  226. package/dist/numerics/integrate.d.ts +9 -1
  227. package/dist/numerics/integrate.js +103 -16
  228. package/dist/numerics/interp.d.ts +8 -2
  229. package/dist/numerics/interp.js +352 -50
  230. package/dist/numerics/ode.js +55 -1
  231. package/dist/numerics.js +2 -2
  232. package/dist/optim/localmin.js +4 -0
  233. package/dist/optim/optim.d.ts +3 -1
  234. package/dist/optim/optim.js +80 -8
  235. package/dist/random/beta.js +53 -4
  236. package/dist/random/binomial.d.ts +14 -3
  237. package/dist/random/binomial.js +59 -24
  238. package/dist/random/continuous.js +33 -5
  239. package/dist/random/extra.js +42 -9
  240. package/dist/random/gamma.d.ts +4 -1
  241. package/dist/random/gamma.js +36 -8
  242. package/dist/random/hyper.js +9 -6
  243. package/dist/random/mt.js +17 -2
  244. package/dist/random/poisson.js +26 -3
  245. package/dist/random/r2dtable.d.ts +8 -1
  246. package/dist/random/r2dtable.js +24 -3
  247. package/dist/random/rank.d.ts +2 -0
  248. package/dist/random/rank.js +44 -4
  249. package/dist/random/sample.d.ts +12 -2
  250. package/dist/random/sample.js +57 -20
  251. package/dist/random/streams.js +4 -2
  252. package/dist/rstats.js +14 -14
  253. package/dist/special/besselIK.d.ts +12 -0
  254. package/dist/special/besselIK.js +168 -23
  255. package/dist/special/besselJY.d.ts +11 -1
  256. package/dist/special/besselJY.js +127 -19
  257. package/dist/special/besselSeries.d.ts +27 -0
  258. package/dist/special/besselSeries.js +45 -2
  259. package/dist/special/beta.js +11 -1
  260. package/dist/special/choose.js +17 -8
  261. package/dist/special/dd.js +122 -18
  262. package/dist/special/extra.js +14 -2
  263. package/dist/special/gamma.js +15 -2
  264. package/dist/special/igam.js +33 -6
  265. package/dist/special/incbet.js +100 -10
  266. package/dist/special/incbetLargeA.js +7 -2
  267. package/dist/special/incbetPrefactor.d.ts +5 -0
  268. package/dist/special/incbetPrefactor.js +14 -3
  269. package/dist/special/incbetTemme.d.ts +7 -0
  270. package/dist/special/incbetTemme.js +45 -12
  271. package/dist/special/loader.d.ts +1 -1
  272. package/dist/special/loader.js +179 -33
  273. package/dist/special/log1pmx.js +4 -0
  274. package/dist/special.js +2 -2
  275. package/dist/tests.js +11 -11
  276. package/llms.txt +12 -6
  277. package/package.json +1 -1
  278. package/dist/chunks/chunk-2CUKVVRO.js +0 -2
  279. package/dist/chunks/chunk-3WQCKGKP.js +0 -2
  280. package/dist/chunks/chunk-4Z2XDWKV.js +0 -2
  281. package/dist/chunks/chunk-AJBLCNZ7.js +0 -3
  282. package/dist/chunks/chunk-D4F7GQAY.js +0 -2
  283. package/dist/chunks/chunk-EBQMGCQZ.js +0 -2
  284. package/dist/chunks/chunk-HBMHR5SS.js +0 -2
  285. package/dist/chunks/chunk-IBPWRQIF.js +0 -2
  286. package/dist/chunks/chunk-JLAH3X77.js +0 -2
  287. package/dist/chunks/chunk-LG74QY5U.js +0 -2
  288. package/dist/chunks/chunk-PEYGUK32.js +0 -2
  289. package/dist/chunks/chunk-Q4PGYESP.js +0 -2
  290. package/dist/chunks/chunk-RCAL4VHM.js +0 -3
  291. package/dist/chunks/chunk-SREPSVTT.js +0 -2
  292. package/dist/chunks/chunk-UFT662QZ.js +0 -2
  293. package/dist/chunks/chunk-VWJ74UHC.js +0 -2
  294. package/dist/chunks/chunk-XNPU54NH.js +0 -2
  295. package/dist/chunks/chunk-XPLDEK6D.js +0 -2
  296. package/dist/chunks/chunk-YGT4P7EU.js +0 -2
  297. package/dist/chunks/chunk-YVREYVI2.js +0 -2
@@ -19,10 +19,11 @@
19
19
  import { pf1 } from "../distributions/f.js";
20
20
  import { pgamma1 } from "../distributions/gamma.js";
21
21
  import { pnorm, qnorm } from "../distributions/normal.js";
22
- import { rank, tieCounts, variance } from "../internal/summary.js";
22
+ import { rank, scaleToUnit, tieCounts, variance } from "../internal/summary.js";
23
23
  import { completeRows, median, toGroups } from "./groups.js";
24
24
  import { blockData, kSampleData, twoGroupData } from "./testFormula.js";
25
25
  import { matchAlternative } from "./types.js";
26
+ import { maxOf, minOf } from "../internal/extremes.js";
26
27
  function chisqResult(method, name, statistic, df) {
27
28
  return {
28
29
  method,
@@ -102,18 +103,29 @@ export function friedmanTest(y, data) {
102
103
  * @category Hypothesis tests
103
104
  */
104
105
  export function cochranQTest(y) {
106
+ if (y.some((r) => r.some((v) => !Number.isNaN(v) && v !== 0 && v !== 1)))
107
+ throw new RangeError("the responses must be 0 or 1 (or NaN)");
105
108
  return { ...friedmanTest(y), method: "Cochran's Q test", statisticName: "Q" };
106
109
  }
107
110
  export function quadeTest(y, data) {
108
111
  if (typeof y === "string")
109
112
  return quadeTest(blockData(y, data));
110
113
  const rows = completeRows(y);
111
- // as in R, b counts all blocks, including those dropped for a missing value
112
- const b = y.length;
114
+ // b is the number of complete blocks, those the statistic is computed from. R's quade.test (4.5.2) counts the
115
+ // blocks dropped for a missing value as well (in B = sum S_j^2 / b, in (b - 1) B / (A - B) and in the degrees of
116
+ // freedom), so that its result for data with an incomplete block differs from that for the same data without the
117
+ // block (F 10 against 25 in docs/differences-from-r.md); here the two agree
118
+ const b = rows.length;
113
119
  const k = y[0]?.length ?? 0;
114
120
  if (rows.length < 2 || k < 2)
115
121
  throw new RangeError("'y' must have at least two complete rows and two columns");
116
- const q = rank(rows.map((r) => Math.max(...r) - Math.min(...r)));
122
+ let ranges = rows.map((r) => maxOf(r) - minOf(r));
123
+ // ranges of finite data that overflow (-1e308 to 1e308 and -9e307 to 9e307 both gave Infinity, tied; R too): the data
124
+ // divided by a common power of 2 first, which keeps their order
125
+ if (ranges.some((v) => v === Infinity) && rows.every((r) => r.every(Number.isFinite))) {
126
+ ranges = scaleToUnit(rows).groups.map((r) => maxOf(r) - minOf(r));
127
+ }
128
+ const q = rank(ranges);
117
129
  const colS = new Array(k).fill(0);
118
130
  let A = 0;
119
131
  rows.forEach((row, i) => {
@@ -164,10 +176,20 @@ export function flignerTest(x, g) {
164
176
  const k = groups.length;
165
177
  if (k < 2)
166
178
  throw new RangeError("all observations are in the same group");
167
- const centred = groups.flatMap((grp) => {
179
+ const deviations = (gs) => gs.flatMap((grp) => {
168
180
  const m = median(grp);
169
181
  return grp.map((v) => Math.abs(v - m));
170
182
  });
183
+ let centred = deviations(groups);
184
+ // a group whose median is infinite (half its values infinite, or both infinities) has deviations Inf - Inf: no
185
+ // order, so no ranks (#329). An infinite value about a finite median ranks last, as in R
186
+ if (centred.some(Number.isNaN))
187
+ throw new RangeError("a group has an infinite median: its deviations are undefined");
188
+ // deviations of finite data that overflow (1e308 from medians of -1e308 and -9e307 both gave Infinity, tied; R too):
189
+ // all groups divided by one common power of 2 first, which keeps the order of the deviations across groups
190
+ if (centred.some((v) => v === Infinity) && groups.every((grp) => grp.every(Number.isFinite))) {
191
+ centred = deviations(scaleToUnit(groups).groups);
192
+ }
171
193
  const n = centred.length;
172
194
  const r = rank(centred);
173
195
  const a = r.map((v) => qnorm((1 + v / (n + 1)) / 2));
@@ -202,6 +224,8 @@ export function moodTest(x, y, options = {}) {
202
224
  const N = m + n;
203
225
  if (N < 3)
204
226
  throw new RangeError("not enough observations");
227
+ if (m === 0 || n === 0)
228
+ throw new RangeError("not enough observations in each sample");
205
229
  const z = xs.concat(ys);
206
230
  // positions in sorted order; tied values share the mean of the scores of their positions
207
231
  const order = Array.from({ length: N }, (_, i) => i).sort((p, q) => z[p] - z[q]);
@@ -4,9 +4,10 @@
4
4
  // (equal_var = False is Welch) and ttest_rel (scipy/stats/_stats_py.py; SciPy commit a087e61,
5
5
  // BSD-3-Clause, see THIRD_PARTY_NOTICES.md). Defaults, confidence intervals and result names follow R's output.
6
6
  // - Welch is the default (scipy's default is equal variance)
7
- // - If the standard error is below 10 eps times the absolute mean, the data are treated as constant and an error is raised (as in R)
7
+ // - If the standard error is below 10 eps times the absolute mean, the data are treated as constant and an error is raised (as in R),
8
+ // and also if it is 0 (R lets through samples of zeros with NaN results; #314)
8
9
  import { pt1, qt1 } from "../distributions/t.js";
9
- import { completePairs, dropNaN, mean, variance } from "../internal/summary.js";
10
+ import { completePairs, dropNaN, ldexp, mean, pairedDifferences, satterthwaiteDfSe, scaleToUnit, variance } from "../internal/summary.js";
10
11
  import { twoSampleData } from "./testFormula.js";
11
12
  import { checkConfLevel, matchAlternative } from "./types.js";
12
13
  export function tTest(x, y, options = {}) {
@@ -28,18 +29,23 @@ export function tTest(x, y, options = {}) {
28
29
  checkConfLevel(confLevel);
29
30
  if (paired && ys === undefined)
30
31
  throw new TypeError("y is required when paired is true");
31
- let xs = Array.from(x);
32
- let yv = ys === undefined ? undefined : Array.from(ys);
32
+ // Work on the data scaled by 2^-k (exact; paired values before their differences are taken), so that neither the
33
+ // differences nor the variances and their squares leave the range. mu goes with them; the estimates, standard
34
+ // error and interval are scaled back at the end
35
+ let xs;
36
+ let yv;
37
+ let k;
33
38
  if (paired) {
34
- const [a, b] = completePairs(xs, yv);
35
- xs = a.map((v, i) => v - b[i]);
36
- yv = undefined;
39
+ const [a, b] = completePairs(Array.from(x), Array.from(ys));
40
+ ({ d: xs, k } = pairedDifferences(a, b));
37
41
  }
38
42
  else {
39
- xs = dropNaN(xs);
40
- if (yv !== undefined)
41
- yv = dropNaN(yv);
43
+ const scaled = scaleToUnit(ys === undefined ? [dropNaN(Array.from(x))] : [dropNaN(Array.from(x)), dropNaN(Array.from(ys))]);
44
+ k = scaled.k;
45
+ xs = scaled.groups[0];
46
+ yv = scaled.groups[1];
42
47
  }
48
+ const muS = ldexp(mu, -k);
43
49
  let tstat;
44
50
  let df;
45
51
  let stdErr;
@@ -57,9 +63,10 @@ export function tTest(x, y, options = {}) {
57
63
  if (yv === undefined) {
58
64
  df = nx - 1;
59
65
  stdErr = Math.sqrt(vx / nx);
60
- if (stdErr < 10 * Number.EPSILON * Math.abs(mx))
66
+ // A standard error of 0 is constant data also when the mean is 0 (R's test 0 < 0 lets [0, 0] through to NaN; #314)
67
+ if (stdErr === 0 || stdErr < 10 * Number.EPSILON * Math.abs(mx))
61
68
  throw new Error("data are essentially constant");
62
- tstat = (mx - mu) / stdErr;
69
+ tstat = (mx - muS) / stdErr;
63
70
  method = paired ? "Paired t-test" : "One Sample t-test";
64
71
  estimate = mx;
65
72
  estimateNames = paired ? "mean difference" : "mean of x";
@@ -91,31 +98,47 @@ export function tTest(x, y, options = {}) {
91
98
  else {
92
99
  const sx = vx / nx;
93
100
  const sy = vy / ny;
94
- stdErr = Math.sqrt(sx + sy);
95
- df = (stdErr * stdErr) ** 2 / ((sx * sx) / (nx - 1) + (sy * sy) / (ny - 1));
101
+ // as R, the standard error from the two standard errors (sqrt of the scaled variances is exact: the scale is
102
+ // 2^-2k)
103
+ stdErr = Math.sqrt(Math.sqrt(sx) ** 2 + Math.sqrt(sy) ** 2);
104
+ df = satterthwaiteDfSe([sx, sy], [nx - 1, ny - 1]);
96
105
  }
97
- if (stdErr < 10 * Number.EPSILON * Math.max(Math.abs(mx), Math.abs(my))) {
106
+ if (stdErr === 0 || stdErr < 10 * Number.EPSILON * Math.max(Math.abs(mx), Math.abs(my))) {
98
107
  throw new Error("data are essentially constant");
99
108
  }
100
- tstat = (mx - my - mu) / stdErr;
109
+ tstat = (mx - my - muS) / stdErr;
101
110
  }
111
+ // The ends are R's mu + (t ± q) stdErr (the same bits as R where its parts are). That cancels where mu or t stdErr is
112
+ // far larger than the interval itself (R's t.test(1:4, mu = 1e6) is 1.4e-10 off, mu = -1e300 gives [0, 0]; an
113
+ // infinite mu NaN): where either exceeds 16 times abs(estimate) + q stdErr, or the end is not finite, the end is the
114
+ // estimate -+ q stdErr instead (revision of review 3). (A standard error of 0 is an error above)
115
+ const centre = typeof estimate === "number" ? estimate : estimate[0] - estimate[1];
116
+ const end = (q, sign) => {
117
+ const r = muS + (tstat + sign * q) * stdErr;
118
+ if (Number.isFinite(r) && Math.max(Math.abs(muS), Math.abs(tstat * stdErr)) <= 16 * (Math.abs(centre) + q * stdErr))
119
+ return r;
120
+ return centre + sign * q * stdErr;
121
+ };
102
122
  let pValue;
103
123
  let confInt;
104
124
  if (alternative === "less") {
105
125
  pValue = pt1(tstat, df, true, false);
106
- confInt = [-Infinity, tstat + qt1(confLevel, df, true, false)];
126
+ confInt = [-Infinity, end(qt1(confLevel, df, true, false), 1)];
107
127
  }
108
128
  else if (alternative === "greater") {
109
129
  pValue = pt1(tstat, df, false, false);
110
- confInt = [tstat - qt1(confLevel, df, true, false), Infinity];
130
+ confInt = [end(qt1(confLevel, df, true, false), -1), Infinity];
111
131
  }
112
132
  else {
113
133
  pValue = 2 * pt1(-Math.abs(tstat), df, true, false);
114
134
  const alpha = 1 - confLevel;
115
- const c = qt1(1 - alpha / 2, df, true, false);
116
- confInt = [tstat - c, tstat + c];
135
+ // (for alpha below 1e-8 the upper probability itself: 1 - alpha loses its digits and rounds to 1 below 1.1e-16; review 58)
136
+ const c = alpha / 2 < 1e-8 ? qt1(alpha / 2, df, false, false) : qt1(1 - alpha / 2, df, true, false);
137
+ confInt = [end(c, -1), end(c, 1)];
117
138
  }
118
- confInt = [mu + confInt[0] * stdErr, mu + confInt[1] * stdErr];
139
+ confInt = [ldexp(confInt[0], k), ldexp(confInt[1], k)];
140
+ estimate = typeof estimate === "number" ? ldexp(estimate, k) : estimate.map((v) => ldexp(v, k));
141
+ stdErr = ldexp(stdErr, k);
119
142
  return {
120
143
  method,
121
144
  alternative,
@@ -14,7 +14,9 @@ export interface PropTrendTestResult extends Omit<HTest, "alternative"> {
14
14
  *
15
15
  * @param x Numbers of events.
16
16
  * @param n Numbers of trials.
17
- * @param score Scores of the groups. Default `1, 2, ..., k`.
17
+ * @param score Scores of the groups. Default `1, 2, ..., k`. A group with a NaN score is left out of the regression
18
+ * (as R's `lm` omits it), but its counts stay in the pooled proportion and the weights, as in R. Other scores must
19
+ * be finite, with at least two distinct values. With no events or only events (all proportions 0, or all 1) the test is not defined (an error, as in R).
18
20
  *
19
21
  * @example
20
22
  * ```ts
@@ -40,7 +42,9 @@ export interface JonckheereTestOptions {
40
42
  alternative?: JonckheereAlternative | (string & {});
41
43
  /**
42
44
  * The exact p-value (`"DescTools"` only). Default: exact when there are no ties and at most 100 observations. With
43
- * ties the normal approximation is used anyway, with a warning.
45
+ * ties the normal approximation is used anyway, with a warning. The exact distribution is the convolution of the
46
+ * Mann-Whitney distributions; where it would have more than 2^24 values or take more than 2^32 multiply-adds
47
+ * (three groups of 215, about 8 s), `exact: true` is a RangeError (R computes it however long it takes).
44
48
  */
45
49
  exact?: boolean;
46
50
  /** `"DescTools"` (default: `JonckheereTerpstraTest`) or `"clinfun"` (`jonckheere.test`). */
@@ -63,7 +67,7 @@ export interface JonckheereTestResult extends Omit<HTest, "alternative"> {
63
67
  * Jonckheere-Terpstra test of equal distributions against ordered alternatives. Equivalent to
64
68
  * `DescTools::JonckheereTerpstraTest()` in R. Computes `JonckheereTerpstraTest(x, g, alternative, exact)` (with `g`
65
69
  * an ordered factor) or, with `variant: "clinfun"`, clinfun's `jonckheere.test(x, g, alternative)` (whose
66
- * two-sided p-value is `2 min(p_increasing, p_decreasing, 0.5)`; DescTools caps it at 1 instead of 0.5). Pairs with a missing value are dropped.
70
+ * two-sided p-value is `2 min(p_increasing, p_decreasing, 0.5)`; DescTools caps it at 1 instead of 0.5). Pairs with a missing value are dropped (with `variant: "clinfun"`, also those with an infinite value, as clinfun does).
67
71
  *
68
72
  * @param x The values.
69
73
  * @param g Group labels, parallel to `x`, in the order of the alternative.
@@ -13,6 +13,7 @@ import { pgamma1 } from "../distributions/gamma.js";
13
13
  import { pnorm } from "../distributions/normal.js";
14
14
  import { dwilcox1 } from "../distributions/wilcox.js";
15
15
  import { levelText, numberLevels } from "../internal/levels.js";
16
+ import { ldexp, scaleToUnit, squareOver } from "../internal/summary.js";
16
17
  import { compareCodePoints } from "../models/modelFrame.js";
17
18
  import { matchChoice } from "./power.js";
18
19
  /**
@@ -20,7 +21,9 @@ import { matchChoice } from "./power.js";
20
21
  *
21
22
  * @param x Numbers of events.
22
23
  * @param n Numbers of trials.
23
- * @param score Scores of the groups. Default `1, 2, ..., k`.
24
+ * @param score Scores of the groups. Default `1, 2, ..., k`. A group with a NaN score is left out of the regression
25
+ * (as R's `lm` omits it), but its counts stay in the pooled proportion and the weights, as in R. Other scores must
26
+ * be finite, with at least two distinct values. With no events or only events (all proportions 0, or all 1) the test is not defined (an error, as in R).
24
27
  *
25
28
  * @example
26
29
  * ```ts
@@ -36,20 +39,53 @@ export function propTrendTest(x, n, score) {
36
39
  const s = score === undefined ? xs.map((_, i) => i + 1) : Array.from(score);
37
40
  if (ns.length !== k || s.length !== k)
38
41
  throw new RangeError("'x', 'n' and 'score' must have the same length");
39
- const p = xs.reduce((a, v) => a + v, 0) / ns.reduce((a, v) => a + v, 0);
42
+ if (ns.some((v) => !(v > 0 && v < Infinity)))
43
+ throw new RangeError("elements of 'n' must be positive and finite");
44
+ if (xs.some((v, i) => !(v >= 0 && v <= ns[i])))
45
+ throw new RangeError("elements of 'x' must be between 0 and 'n'");
46
+ // With no events or only events the pooled proportion is 0 or 1, the weights n / (p (1 - p)) are infinite and every
47
+ // proportion is the same: no trend to test (R's lm: "NA/NaN/Inf in 'x'"; this returned NaN, #319)
48
+ if (xs.every((v) => v === 0) || xs.every((v, i) => v === ns[i])) {
49
+ throw new RangeError("all proportions are 0 or all are 1: the test for trend is not defined");
50
+ }
51
+ const sumN = ns.reduce((a, v) => a + v, 0);
52
+ const p = xs.reduce((a, v) => a + v, 0) / sumN;
40
53
  const w = ns.map((v) => v / (p * (1 - p)));
41
54
  const f = xs.map((v, i) => v / ns[i]);
42
- const sw = w.reduce((a, v) => a + v, 0);
43
- const sBar = w.reduce((a, wi, i) => a + wi * s[i], 0) / sw;
44
- const fBar = w.reduce((a, wi, i) => a + wi * f[i], 0) / sw;
45
- let sxy = 0;
46
- let sxx = 0;
47
- w.forEach((wi, i) => {
48
- const ds = s[i] - sBar;
49
- sxy += wi * ds * (f[i] - fBar);
50
- sxx += wi * ds * ds;
51
- });
52
- const statistic = (sxy * sxy) / sxx;
55
+ // the weighted regression of f on the scores, over the groups with a score
56
+ const rows = s.flatMap((v, i) => (Number.isNaN(v) ? [] : [i]));
57
+ if (rows.length === 0)
58
+ throw new RangeError("no non-missing scores");
59
+ // An infinite score made the centred scores Inf - Inf and the statistic NaN (R's lm: "NA/NaN/Inf in 'x'"; #317)
60
+ if (rows.some((i) => !Number.isFinite(s[i])))
61
+ throw new RangeError("non-missing scores must be finite");
62
+ // One distinct score (all equal, or one group with a score) leaves no slope: sxx = sxy = 0 and the statistic 0 / 0
63
+ // (R's NA; NaN before, #318)
64
+ if (rows.every((i) => s[i] === s[rows[0]]))
65
+ throw new RangeError("at least 2 distinct non-missing scores are needed");
66
+ let sc = s;
67
+ let { sw, sxy, sxx } = trendRegression(w, f, sc, rows);
68
+ if (!(sxx >= 2 ** -1022 && sxx < Infinity && Math.abs(sxy) < Infinity)) {
69
+ // Scores far from 1 (0 and 1e200, or 0 and 2^-700): sxx overflowed or underflowed, and the statistic was 0 or
70
+ // Infinity. The statistic does not change when the scores are multiplied by a constant, so it is formed from the
71
+ // scores divided by a power of 2 that brings the largest into [1, 2) (#389). Otherwise the same bits as before
72
+ const scaled = scaleToUnit([rows.map((i) => s[i])]);
73
+ if (scaled.k !== 0) {
74
+ sc = s.slice();
75
+ rows.forEach((i, j) => (sc[i] = scaled.groups[0][j]));
76
+ ({ sw, sxy, sxx } = trendRegression(w, f, sc, rows));
77
+ }
78
+ }
79
+ let statistic = squareOver(sxy, sxx);
80
+ if (!(sumN < Infinity) || (p > 0 && p < 1 && !(sw < Infinity && Math.abs(sxy) < Infinity && sxx < Infinity))) {
81
+ // The totals or the weights overflow although the counts are finite: the pooled proportion from the counts
82
+ // scaled by 2^-k, and the regression with the weights n_i 2^-k (the common factor 1 / (p (1 - p)) cancels in the
83
+ // means), the statistic sxy^2 / sxx / (p (1 - p)) multiplied back by 2^k
84
+ const { groups: [xu, nu], k, } = scaleToUnit([xs, ns]);
85
+ const pu = xu.reduce((a, v) => a + v, 0) / nu.reduce((a, v) => a + v, 0);
86
+ const u = trendRegression(nu, f, sc, rows);
87
+ statistic = ldexp((u.sxy / pu) * (u.sxy / u.sxx / (1 - pu)), k);
88
+ }
53
89
  return {
54
90
  method: "Chi-squared Test for Trend in Proportions",
55
91
  statistic,
@@ -59,14 +95,35 @@ export function propTrendTest(x, n, score) {
59
95
  pValue: pgamma1(statistic, 0.5, 2, false, false),
60
96
  };
61
97
  }
98
+ /** Weighted sums of the regression of f on the scores s over the given rows: the total weight and the centred sums */
99
+ function trendRegression(w, f, s, rows) {
100
+ const sw = rows.reduce((a, i) => a + w[i], 0);
101
+ const sBar = rows.reduce((a, i) => a + w[i] * s[i], 0) / sw;
102
+ const fBar = rows.reduce((a, i) => a + w[i] * f[i], 0) / sw;
103
+ let sxy = 0;
104
+ let sxx = 0;
105
+ for (const i of rows) {
106
+ const ds = s[i] - sBar;
107
+ sxy += w[i] * ds * (f[i] - fBar);
108
+ sxx += w[i] * ds * ds;
109
+ }
110
+ return { sw, sxy, sxx };
111
+ }
112
+ /** Largest length (as #232's 2^24) and number of multiply-adds (three groups of 215: about 8 s) of the exact JT distribution (#321) */
113
+ const MAX_EXACT_LENGTH = 2 ** 24;
114
+ const MAX_EXACT_WORK = 2 ** 32;
62
115
  const NOT_EXACT = "Sample size > 100 or data with ties \n p-value based on normal approximation. Specify nperm for permutation p-value";
63
116
  const TIES = "Sample data with ties \n p-value based on normal approximation. Specify nperm for permutation p-value.";
64
- /** The groups in order: the labels sorted (numbers as numbers, strings by code point) or as `levels` */
65
- function orderedGroups(x, g, levels) {
117
+ /**
118
+ * The groups in order: the labels sorted (numbers as numbers, strings by code point) or as `levels`. Pairs with a NaN
119
+ * are dropped, and with `finiteOnly` also those with an infinite value or numeric label
120
+ */
121
+ function orderedGroups(x, g, levels, finiteOnly = false) {
66
122
  const xs = Array.from(x);
67
123
  if (xs.length !== g.length)
68
124
  throw new RangeError("'x' and 'g' must have the same length");
69
- const keep = xs.flatMap((v, i) => (Number.isNaN(v) || (typeof g[i] === "number" && Number.isNaN(g[i])) ? [] : [i]));
125
+ const bad = (v) => typeof v === "number" && (finiteOnly ? !Number.isFinite(v) : Number.isNaN(v));
126
+ const keep = xs.flatMap((v, i) => (bad(v) || bad(g[i]) ? [] : [i]));
70
127
  // numeric labels with the same 15-digit text are one level, as in R's factor() (only without given levels, which
71
128
  // are matched by their text)
72
129
  if (levels === undefined)
@@ -90,11 +147,28 @@ function orderedGroups(x, g, levels) {
90
147
  }
91
148
  return groups;
92
149
  }
150
+ /**
151
+ * The null variance of JT under ties (Hollander & Wolfe): the variance of the permutation distribution given the
152
+ * group sizes n_i and the sizes t_j of the groups of tied values. The packages (clinfun, DescTools) use the variance
153
+ * without ties there, which is too large (review 59)
154
+ */
155
+ function tiedVariance(groupSizes, all) {
156
+ const counts = new Map();
157
+ for (const v of all)
158
+ counts.set(v, (counts.get(v) ?? 0) + 1);
159
+ const t = [...counts.values()];
160
+ const N = all.length;
161
+ const s1 = (a, f) => a.reduce((acc, v) => acc + f(v), 0);
162
+ const first = (N * (N - 1) * (2 * N + 5) - s1(groupSizes, (v) => v * (v - 1) * (2 * v + 5)) - s1(t, (v) => v * (v - 1) * (2 * v + 5))) / 72;
163
+ const second = N < 3 ? 0 : (s1(groupSizes, (v) => v * (v - 1) * (v - 2)) * s1(t, (v) => v * (v - 1) * (v - 2))) / (36 * N * (N - 1) * (N - 2));
164
+ const third = (s1(groupSizes, (v) => v * (v - 1)) * s1(t, (v) => v * (v - 1))) / (8 * N * (N - 1));
165
+ return first + second + third;
166
+ }
93
167
  /**
94
168
  * Jonckheere-Terpstra test of equal distributions against ordered alternatives. Equivalent to
95
169
  * `DescTools::JonckheereTerpstraTest()` in R. Computes `JonckheereTerpstraTest(x, g, alternative, exact)` (with `g`
96
170
  * an ordered factor) or, with `variant: "clinfun"`, clinfun's `jonckheere.test(x, g, alternative)` (whose
97
- * two-sided p-value is `2 min(p_increasing, p_decreasing, 0.5)`; DescTools caps it at 1 instead of 0.5). Pairs with a missing value are dropped.
171
+ * two-sided p-value is `2 min(p_increasing, p_decreasing, 0.5)`; DescTools caps it at 1 instead of 0.5). Pairs with a missing value are dropped (with `variant: "clinfun"`, also those with an infinite value, as clinfun does).
98
172
  *
99
173
  * @param x The values.
100
174
  * @param g Group labels, parallel to `x`, in the order of the alternative.
@@ -113,7 +187,11 @@ export function jonckheereTest(x, g, options = {}) {
113
187
  throw new RangeError(`invalid variant "${String(variant)}"`);
114
188
  if (variant === "clinfun" && options.exact !== undefined)
115
189
  throw new TypeError("clinfun's jonckheere.test has no option 'exact'");
116
- const groups = orderedGroups(x, g, options.levels);
190
+ // clinfun keeps only the pairs where both values are finite
191
+ const groups = orderedGroups(x, g, options.levels, variant === "clinfun");
192
+ // with fewer than 2 nonempty groups there is no pair to compare (the packages' errors)
193
+ if (groups.filter((gi) => gi.length > 0).length < 2)
194
+ throw new RangeError(variant === "clinfun" ? "only one group has non-missing data" : "all observations are in the same group");
117
195
  const all = groups.flat();
118
196
  const nTotal = all.length;
119
197
  const ties = new Set(all).size < nTotal;
@@ -144,6 +222,18 @@ export function jonckheereTest(x, g, options = {}) {
144
222
  let lower;
145
223
  let upper;
146
224
  if (exact) {
225
+ // the length of the convolution and its multiply-adds, checked before anything is built (#321)
226
+ let len = 1;
227
+ let work = 0;
228
+ for (const [ni, mi] of sizes) {
229
+ if (ni === 0 || mi === 0)
230
+ continue;
231
+ work += len * (ni * mi + 1);
232
+ len += ni * mi;
233
+ }
234
+ if (len > MAX_EXACT_LENGTH || work > MAX_EXACT_WORK) {
235
+ throw new RangeError(`the exact distribution of JT has ${len} values and needs ${work} steps, too many: use exact: false`);
236
+ }
147
237
  // the convolution of the Mann-Whitney distributions
148
238
  let dist = [1];
149
239
  for (const [ni, mi] of sizes) {
@@ -165,12 +255,16 @@ export function jonckheereTest(x, g, options = {}) {
165
255
  }
166
256
  else {
167
257
  const mean = sizes.reduce((a, [ni, mi]) => a + ni * mi, 0) / 2;
168
- const variance = sizes.reduce((a, [ni, mi]) => a + (ni * mi * (ni + mi + 1)) / 12, 0);
258
+ const variance = ties ? tiedVariance(groups.map((gi) => gi.length), all) : sizes.reduce((a, [ni, mi]) => a + (ni * mi * (ni + mi + 1)) / 12, 0);
169
259
  const z = (jt - mean) / Math.sqrt(variance);
170
260
  lower = pnorm(z);
171
261
  upper = 1 - lower;
262
+ // 1 - pnorm loses the small upper tail (0 beyond z ~ 8.3); below 1e-8 take it directly,
263
+ // elsewhere the packages' expression (the same bits) (#280)
264
+ if (upper < 1e-8)
265
+ upper = pnorm(z, { lowerTail: false });
172
266
  }
173
267
  const cap = variant === "clinfun" ? 0.5 : 1;
174
- const pValue = alternative === "increasing" ? upper : alternative === "decreasing" ? lower : 2 * Math.min(upper, lower, cap);
268
+ const pValue = alternative === "increasing" ? upper : alternative === "decreasing" ? lower : Math.min(1, 2 * Math.min(upper, lower, cap)); // (DescTools can exceed 1)
175
269
  return { method: "Jonckheere-Terpstra test", alternative, statistic: jt, statisticName: "JT", pValue, warnings };
176
270
  }
@@ -59,5 +59,10 @@ export interface HTest {
59
59
  export declare function matchAlternative(a: string | undefined): Alternative;
60
60
  /** Validate the confidence level (R's t.test also accepts exactly 0 and 1; with 1 the interval is ±Inf) */
61
61
  export declare function checkConfLevel(level: number): void;
62
+ /**
63
+ * Whether v is a nonnegative count. The slack is absolute: a count is an integer whatever its size, so a relative
64
+ * slack would accept 1e8 + 0.25 and silently round it
65
+ */
66
+ export declare function isCount(v: number): boolean;
62
67
  /** Validate the confidence level strictly inside (0, 1), as most of R's tests require */
63
68
  export declare function checkConfLevelOpen(level: number): void;
@@ -18,6 +18,13 @@ export function checkConfLevel(level) {
18
18
  throw new RangeError("confLevel must be a number between 0 and 1");
19
19
  }
20
20
  }
21
+ /**
22
+ * Whether v is a nonnegative count. The slack is absolute: a count is an integer whatever its size, so a relative
23
+ * slack would accept 1e8 + 0.25 and silently round it
24
+ */
25
+ export function isCount(v) {
26
+ return Number.isFinite(v) && v >= 0 && Math.abs(v - Math.round(v)) <= 1e-7;
27
+ }
21
28
  /** Validate the confidence level strictly inside (0, 1), as most of R's tests require */
22
29
  export function checkConfLevelOpen(level) {
23
30
  if (!(Number.isFinite(level) && level > 0 && level < 1)) {
@@ -7,9 +7,10 @@
7
7
  // n_i = size - 1, N = sum n_i and s_p^2 the pooled variance; chi-squared with k - 1 degrees of freedom.
8
8
  import { pf1, qf1 } from "../distributions/f.js";
9
9
  import { pgamma1 } from "../distributions/gamma.js";
10
- import { variance } from "../internal/summary.js";
10
+ import { groupMoments, ldexpWide } from "../internal/summary.js";
11
11
  import { kSampleData, samplesByLevel, twoGroupData } from "./testFormula.js";
12
12
  import { checkConfLevelOpen, matchAlternative } from "./types.js";
13
+ const MIN_NORMAL = 2 ** -1022;
13
14
  export function varTest(x, y, options = {}) {
14
15
  if (typeof x === "string") {
15
16
  const d = twoGroupData(x, y);
@@ -30,7 +31,22 @@ export function varTest(x, y, options = {}) {
30
31
  throw new Error("not enough 'x' observations");
31
32
  if (dfy < 1)
32
33
  throw new Error("not enough 'y' observations");
33
- const estimate = variance(xs) / variance(ys);
34
+ // scaled by a power of 2 (exact) so that the variances stay in range; the statistic does not depend on the units
35
+ let [vx, vy] = groupMoments([xs, ys]).variance;
36
+ let exponent = 0;
37
+ if (!(vx >= MIN_NORMAL && vy >= MIN_NORMAL)) {
38
+ // a variance below the normal range on the common scale (#393; as #270): each sample on its own scale 2^-e,
39
+ // the ratio times 2^(2 (e_x - e_y)). varTest([1e308, 1e308], [0, 1e-100]) had both variances 0
40
+ const mx = groupMoments([xs]);
41
+ const my = groupMoments([ys]);
42
+ vx = mx.variance[0];
43
+ vy = my.variance[0];
44
+ exponent = 2 * (mx.k - my.k);
45
+ }
46
+ // both variances 0: the ratio is 0 / 0 (R returns NaN); one of them 0 gives the limit 0 or Infinity as before
47
+ if (vx === 0 && vy === 0)
48
+ throw new RangeError("both samples have zero variance");
49
+ const estimate = exponent === 0 ? vx / vy : ldexpWide(vx / vy, exponent);
34
50
  const statistic = estimate / ratio;
35
51
  const lower = pf1(statistic, dfx, dfy, true, false);
36
52
  const upper = pf1(statistic, dfx, dfy, false, false);
@@ -47,7 +63,9 @@ export function varTest(x, y, options = {}) {
47
63
  else {
48
64
  pValue = Math.min(1, 2 * Math.min(lower, upper));
49
65
  const beta = (1 - confLevel) / 2;
50
- confInt = [estimate / qf1(1 - beta, dfx, dfy, true, false), estimate / qf1(beta, dfx, dfy, true, false)];
66
+ // (for alpha below 1e-8 the upper probability itself: 1 - alpha loses its digits and rounds to 1 below 1.1e-16; review 58)
67
+ const fHigh = beta < 1e-8 ? qf1(beta, dfx, dfy, false, false) : qf1(1 - beta, dfx, dfy, true, false);
68
+ confInt = [estimate / fHigh, estimate / qf1(beta, dfx, dfy, true, false)];
51
69
  }
52
70
  return {
53
71
  method: "F test to compare two variances",
@@ -74,16 +92,13 @@ export function bartlettTest(x, data) {
74
92
  const k = groups.length;
75
93
  if (k < 2)
76
94
  throw new RangeError("'x' must be a list with at least 2 elements");
77
- const n = [];
78
- const v = [];
79
- for (const g of groups) {
80
- // as in R, infinite values are dropped along with NaN
81
- const s = Array.from(g).filter(Number.isFinite);
82
- if (s.length < 2)
83
- throw new RangeError("there must be at least 2 observations in each group");
84
- n.push(s.length - 1);
85
- v.push(variance(s));
86
- }
95
+ // as in R, infinite values are dropped along with NaN
96
+ const samples = groups.map((g) => Array.from(g).filter(Number.isFinite));
97
+ if (samples.some((s) => s.length < 2))
98
+ throw new RangeError("there must be at least 2 observations in each group");
99
+ const n = samples.map((s) => s.length - 1);
100
+ // scaled by a power of 2 (exact) so that the variances stay in range; the statistic does not depend on the units
101
+ const v = groupMoments(samples).variance;
87
102
  let N = 0;
88
103
  let pooled = 0;
89
104
  let sumLog = 0;
@@ -95,7 +110,23 @@ export function bartlettTest(x, data) {
95
110
  sumInv += 1 / n[i];
96
111
  }
97
112
  pooled /= N;
98
- const statistic = (N * Math.log(pooled) - sumLog) / (1 + (sumInv - 1 / N) / (3 * (k - 1)));
113
+ let logRatio = N * Math.log(pooled) - sumLog;
114
+ if (v.some((vi) => vi < MIN_NORMAL)) {
115
+ // A variance underflows (or is subnormal) on the common scale although the log ratio is finite: each group on
116
+ // its own scale 2^-e_i, log v_i = log w_i + 2 (e_i - E) log 2 relative to the largest exponent E (the E terms
117
+ // cancel, as sum n_i = N), and the log of the pooled variance by log-sum-exp
118
+ const own = samples.map((g) => {
119
+ const m = groupMoments([g]);
120
+ return { w: m.variance[0], e: m.k };
121
+ });
122
+ const top = Math.max(...own.map((o) => o.e));
123
+ const logs = own.map((o) => Math.log(o.w) + 2 * (o.e - top) * Math.LN2);
124
+ const terms = logs.map((l, i) => Math.log(n[i]) + l);
125
+ const peak = Math.max(...terms);
126
+ const logPooled = peak + Math.log(terms.reduce((a, t) => a + Math.exp(t - peak), 0)) - Math.log(N);
127
+ logRatio = N * logPooled - logs.reduce((a, l, i) => a + n[i] * l, 0);
128
+ }
129
+ const statistic = logRatio / (1 + (sumInv - 1 / N) / (3 * (k - 1)));
99
130
  const df = k - 1;
100
131
  return {
101
132
  method: "Bartlett test of homogeneity of variances",