@numero-uno-jpn/rstats 0.15.3 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (322) hide show
  1. package/CHANGELOG.md +294 -0
  2. package/README.ja.md +68 -35
  3. package/README.md +65 -30
  4. package/dist/chunks/chunk-2C33MXSW.js +3 -0
  5. package/dist/chunks/chunk-34S5SQY6.js +2 -0
  6. package/dist/chunks/chunk-4WE3OO62.js +2 -0
  7. package/dist/chunks/chunk-5AYHCITP.js +2 -0
  8. package/dist/chunks/chunk-6JJQL6HL.js +2 -0
  9. package/dist/chunks/chunk-C7V2FH6L.js +3 -0
  10. package/dist/chunks/chunk-CZI7KUO3.js +2 -0
  11. package/dist/chunks/chunk-DXI5N2ET.js +2 -0
  12. package/dist/chunks/chunk-FY3FVOBM.js +2 -0
  13. package/dist/chunks/chunk-H3WVPZDL.js +2 -0
  14. package/dist/chunks/chunk-LHUIJQHY.js +2 -0
  15. package/dist/chunks/chunk-LV3W2F7N.js +2 -0
  16. package/dist/chunks/chunk-M4ITG7YR.js +2 -0
  17. package/dist/chunks/chunk-NSYZTS26.js +2 -0
  18. package/dist/chunks/chunk-ONY5CISH.js +2 -0
  19. package/dist/chunks/chunk-RFE7MVP7.js +2 -0
  20. package/dist/chunks/chunk-SE7V2KLO.js +2 -0
  21. package/dist/chunks/chunk-THIGHOKK.js +2 -0
  22. package/dist/chunks/chunk-TNMJPQPV.js +2 -0
  23. package/dist/chunks/chunk-WM7VFXTV.js +2 -0
  24. package/dist/chunks/chunk-WMDYDTVQ.js +2 -0
  25. package/dist/chunks/chunk-XLSFJTTK.js +2 -0
  26. package/dist/chunks/chunk-Z37NELOS.js +2 -0
  27. package/dist/chunks/chunk-ZFQWB222.js +2 -0
  28. package/dist/data/grouping.js +26 -7
  29. package/dist/descriptive/basic.js +110 -8
  30. package/dist/descriptive/cov.js +23 -4
  31. package/dist/descriptive/dataFrames.d.ts +4 -2
  32. package/dist/descriptive/dataFrames.js +69 -23
  33. package/dist/descriptive/factanal.d.ts +2 -0
  34. package/dist/descriptive/factanal.js +26 -9
  35. package/dist/descriptive/hist.d.ts +8 -5
  36. package/dist/descriptive/hist.js +77 -31
  37. package/dist/descriptive/missing.js +3 -1
  38. package/dist/descriptive/moments.js +86 -19
  39. package/dist/descriptive/omega.d.ts +1 -1
  40. package/dist/descriptive/omega.js +74 -10
  41. package/dist/descriptive/pivot.d.ts +25 -10
  42. package/dist/descriptive/pivot.js +182 -42
  43. package/dist/descriptive/quantile.js +10 -1
  44. package/dist/descriptive/rank.js +8 -1
  45. package/dist/descriptive/table.d.ts +23 -3
  46. package/dist/descriptive/table.js +36 -21
  47. package/dist/descriptive.js +2 -2
  48. package/dist/distributions/arcsine.js +27 -2
  49. package/dist/distributions/beta.js +33 -4
  50. package/dist/distributions/binomial.js +46 -14
  51. package/dist/distributions/bvnorm.js +11 -2
  52. package/dist/distributions/cauchy.js +21 -4
  53. package/dist/distributions/chisq.js +16 -3
  54. package/dist/distributions/exponential.js +14 -0
  55. package/dist/distributions/f.js +41 -17
  56. package/dist/distributions/gamma.js +35 -3
  57. package/dist/distributions/geometric.js +58 -13
  58. package/dist/distributions/hypergeometric.d.ts +5 -1
  59. package/dist/distributions/hypergeometric.js +101 -6
  60. package/dist/distributions/invgamma.js +10 -1
  61. package/dist/distributions/kumaraswamy.js +9 -0
  62. package/dist/distributions/laplace.js +36 -6
  63. package/dist/distributions/logistic.js +13 -1
  64. package/dist/distributions/lognormal.js +16 -2
  65. package/dist/distributions/multinomial.js +58 -11
  66. package/dist/distributions/nbeta.js +62 -11
  67. package/dist/distributions/nchisq.js +30 -6
  68. package/dist/distributions/negbinomial.js +102 -17
  69. package/dist/distributions/normal.js +17 -4
  70. package/dist/distributions/nt.js +392 -17
  71. package/dist/distributions/pareto.js +12 -1
  72. package/dist/distributions/poisson.js +37 -3
  73. package/dist/distributions/signrank.js +16 -4
  74. package/dist/distributions/summary.d.ts +2 -1
  75. package/dist/distributions/summary.js +481 -61
  76. package/dist/distributions/t.js +9 -0
  77. package/dist/distributions/triangular.js +19 -5
  78. package/dist/distributions/tukey.js +11 -2
  79. package/dist/distributions/uniform.js +8 -0
  80. package/dist/distributions/weibull.js +18 -0
  81. package/dist/distributions/wilcox.d.ts +9 -3
  82. package/dist/distributions/wilcox.js +164 -26
  83. package/dist/distributions.js +2 -2
  84. package/dist/entries/descriptive.d.ts +3 -1
  85. package/dist/entries/descriptive.js +1 -1
  86. package/dist/entries/distributions.d.ts +1 -0
  87. package/dist/entries/distributions.js +2 -0
  88. package/dist/entries/linalg.d.ts +3 -1
  89. package/dist/entries/mixed.d.ts +3 -0
  90. package/dist/entries/mixed.js +2 -0
  91. package/dist/entries/numerics.d.ts +2 -1
  92. package/dist/entries/tests.d.ts +8 -5
  93. package/dist/entries/tests.js +3 -1
  94. package/dist/htest/agreement.d.ts +16 -2
  95. package/dist/htest/agreement.js +122 -21
  96. package/dist/htest/ansariTest.d.ts +8 -2
  97. package/dist/htest/ansariTest.js +116 -18
  98. package/dist/htest/aov.d.ts +29 -23
  99. package/dist/htest/aov.js +90 -47
  100. package/dist/htest/binomTest.d.ts +5 -0
  101. package/dist/htest/binomTest.js +47 -17
  102. package/dist/htest/brunnerMunzelTest.d.ts +4 -3
  103. package/dist/htest/brunnerMunzelTest.js +12 -5
  104. package/dist/htest/chisqTest.d.ts +5 -2
  105. package/dist/htest/chisqTest.js +151 -46
  106. package/dist/htest/cor.d.ts +9 -2
  107. package/dist/htest/cor.js +57 -26
  108. package/dist/htest/core/ansari.d.ts +9 -0
  109. package/dist/htest/core/ansari.js +21 -1
  110. package/dist/htest/core/kolmogorov.d.ts +25 -0
  111. package/dist/htest/core/kolmogorov.js +123 -0
  112. package/dist/htest/core/mantelhaen.js +6 -4
  113. package/dist/htest/core/shapiro.d.ts +1 -1
  114. package/dist/htest/core/shapiro.js +5 -1
  115. package/dist/htest/core/simulate.d.ts +6 -0
  116. package/dist/htest/core/simulate.js +20 -0
  117. package/dist/htest/dunnett.js +14 -5
  118. package/dist/htest/effectSize.d.ts +5 -0
  119. package/dist/htest/effectSize.js +117 -35
  120. package/dist/htest/fisherTest.d.ts +4 -3
  121. package/dist/htest/fisherTest.js +88 -24
  122. package/dist/htest/groups.d.ts +7 -0
  123. package/dist/htest/groups.js +21 -4
  124. package/dist/htest/ksTest.d.ts +7 -1
  125. package/dist/htest/ksTest.js +36 -6
  126. package/dist/htest/leveneTest.d.ts +2 -0
  127. package/dist/htest/leveneTest.js +28 -6
  128. package/dist/htest/mantelhaenTest.js +132 -25
  129. package/dist/htest/mcnemarTest.js +40 -11
  130. package/dist/htest/multipleComparisons.d.ts +24 -26
  131. package/dist/htest/multipleComparisons.js +70 -64
  132. package/dist/htest/normalityTests.js +54 -14
  133. package/dist/htest/onewayTest.js +106 -5
  134. package/dist/htest/pAdjust.d.ts +3 -2
  135. package/dist/htest/pAdjust.js +42 -6
  136. package/dist/htest/pairwise.d.ts +3 -1
  137. package/dist/htest/pairwise.js +46 -21
  138. package/dist/htest/poissonTest.d.ts +1 -1
  139. package/dist/htest/poissonTest.js +117 -59
  140. package/dist/htest/polycor.js +47 -17
  141. package/dist/htest/power.d.ts +15 -1
  142. package/dist/htest/power.js +128 -10
  143. package/dist/htest/propTest.d.ts +3 -0
  144. package/dist/htest/propTest.js +44 -6
  145. package/dist/htest/pwr.d.ts +38 -1
  146. package/dist/htest/pwr.js +159 -39
  147. package/dist/htest/rankTests.js +36 -6
  148. package/dist/htest/tTest.d.ts +2 -0
  149. package/dist/htest/tTest.js +53 -21
  150. package/dist/htest/testFormula.js +11 -11
  151. package/dist/htest/trendTests.d.ts +28 -4
  152. package/dist/htest/trendTests.js +124 -35
  153. package/dist/htest/types.d.ts +7 -0
  154. package/dist/htest/types.js +7 -0
  155. package/dist/htest/varTest.js +52 -14
  156. package/dist/htest/wilcoxTest.js +164 -29
  157. package/dist/integrate/quadpack.js +27 -5
  158. package/dist/internal/checkOptions.d.ts +11 -0
  159. package/dist/internal/checkOptions.js +31 -0
  160. package/dist/internal/covmat.d.ts +5 -0
  161. package/dist/internal/covmat.js +20 -0
  162. package/dist/internal/ddexp.d.ts +15 -1
  163. package/dist/internal/ddexp.js +59 -6
  164. package/dist/internal/discrete.d.ts +14 -0
  165. package/dist/internal/discrete.js +78 -5
  166. package/dist/internal/extremes.d.ts +9 -0
  167. package/dist/internal/extremes.js +24 -0
  168. package/dist/internal/fround.js +13 -4
  169. package/dist/internal/integer.d.ts +9 -0
  170. package/dist/internal/integer.js +12 -0
  171. package/dist/internal/invert.js +15 -2
  172. package/dist/internal/optionalArgs.d.ts +12 -0
  173. package/dist/internal/optionalArgs.js +46 -0
  174. package/dist/internal/scaledInverse.d.ts +10 -0
  175. package/dist/internal/scaledInverse.js +22 -0
  176. package/dist/internal/seq.js +15 -2
  177. package/dist/internal/summary.d.ts +90 -0
  178. package/dist/internal/summary.js +458 -39
  179. package/dist/internal/uniroot.d.ts +7 -0
  180. package/dist/internal/uniroot.js +28 -3
  181. package/dist/internal/warnings.d.ts +66 -0
  182. package/dist/internal/warnings.js +122 -0
  183. package/dist/linalg/basic.d.ts +3 -1
  184. package/dist/linalg/basic.js +58 -7
  185. package/dist/linalg/chol.js +10 -1
  186. package/dist/linalg/dot.d.ts +29 -0
  187. package/dist/linalg/dot.js +132 -0
  188. package/dist/linalg/eigen.d.ts +6 -1
  189. package/dist/linalg/eigen.js +75 -14
  190. package/dist/linalg/expm.d.ts +3 -2
  191. package/dist/linalg/expm.js +113 -15
  192. package/dist/linalg/kappa.js +64 -10
  193. package/dist/linalg/lu.d.ts +2 -1
  194. package/dist/linalg/lu.js +40 -5
  195. package/dist/linalg/matrix.d.ts +14 -0
  196. package/dist/linalg/matrix.js +24 -0
  197. package/dist/linalg/norm.js +4 -0
  198. package/dist/linalg/ops.d.ts +27 -2
  199. package/dist/linalg/ops.js +74 -26
  200. package/dist/linalg/qr.d.ts +2 -1
  201. package/dist/linalg/qr.js +105 -23
  202. package/dist/linalg/schur.js +11 -3
  203. package/dist/linalg/solve.d.ts +6 -1
  204. package/dist/linalg/solve.js +156 -26
  205. package/dist/linalg/svd.d.ts +9 -2
  206. package/dist/linalg/svd.js +33 -11
  207. package/dist/linalg.js +2 -2
  208. package/dist/mixed.js +4 -4
  209. package/dist/models/anovaSequential.d.ts +32 -2
  210. package/dist/models/anovaSequential.js +170 -28
  211. package/dist/models/aovEz.js +154 -39
  212. package/dist/models/aovStrata.js +68 -24
  213. package/dist/models/carAnova.d.ts +1 -1
  214. package/dist/models/carAnova.js +78 -33
  215. package/dist/models/coxph.d.ts +6 -0
  216. package/dist/models/coxph.js +166 -69
  217. package/dist/models/estimable.d.ts +15 -0
  218. package/dist/models/estimable.js +68 -0
  219. package/dist/models/formula.d.ts +1 -1
  220. package/dist/models/formula.js +26 -8
  221. package/dist/models/glm.d.ts +57 -7
  222. package/dist/models/glm.js +427 -74
  223. package/dist/models/glmAnova.js +90 -14
  224. package/dist/models/glmConfint.d.ts +1 -1
  225. package/dist/models/glmConfint.js +121 -29
  226. package/dist/models/glmFamily.d.ts +11 -6
  227. package/dist/models/glmFamily.js +247 -62
  228. package/dist/models/lm.d.ts +12 -1
  229. package/dist/models/lm.js +246 -37
  230. package/dist/models/lmer.d.ts +31 -7
  231. package/dist/models/lmer.js +129 -42
  232. package/dist/models/lmerAnova.d.ts +3 -3
  233. package/dist/models/lmerAnova.js +47 -9
  234. package/dist/models/lmerHypotheses.d.ts +6 -2
  235. package/dist/models/lmerHypotheses.js +14 -2
  236. package/dist/models/lmerTest.d.ts +13 -6
  237. package/dist/models/lmerTest.js +82 -29
  238. package/dist/models/mauchly.d.ts +6 -1
  239. package/dist/models/mauchly.js +41 -15
  240. package/dist/models/mixedStructure.js +6 -0
  241. package/dist/models/modelFrame.js +10 -4
  242. package/dist/models/modelMatrix.d.ts +3 -1
  243. package/dist/models/modelMatrix.js +47 -17
  244. package/dist/models/scaledTables.d.ts +8 -0
  245. package/dist/models/scaledTables.js +6 -0
  246. package/dist/models/survival.d.ts +12 -1
  247. package/dist/models/survival.js +75 -28
  248. package/dist/models/tiedTimes.d.ts +2 -0
  249. package/dist/models/tiedTimes.js +34 -0
  250. package/dist/numerics/deriv.d.ts +1 -1
  251. package/dist/numerics/deriv.js +72 -8
  252. package/dist/numerics/integrate.d.ts +9 -1
  253. package/dist/numerics/integrate.js +111 -16
  254. package/dist/numerics/interp.d.ts +40 -9
  255. package/dist/numerics/interp.js +375 -55
  256. package/dist/numerics/ode.js +59 -1
  257. package/dist/numerics.js +2 -2
  258. package/dist/optim/localmin.js +4 -0
  259. package/dist/optim/optim.d.ts +3 -1
  260. package/dist/optim/optim.js +97 -10
  261. package/dist/random/beta.js +58 -4
  262. package/dist/random/binomial.d.ts +14 -3
  263. package/dist/random/binomial.js +59 -24
  264. package/dist/random/continuous.js +50 -5
  265. package/dist/random/extra.js +55 -9
  266. package/dist/random/gamma.d.ts +4 -1
  267. package/dist/random/gamma.js +47 -8
  268. package/dist/random/hyper.js +9 -6
  269. package/dist/random/mt.js +17 -2
  270. package/dist/random/poisson.js +31 -3
  271. package/dist/random/r2dtable.d.ts +8 -1
  272. package/dist/random/r2dtable.js +24 -3
  273. package/dist/random/rank.d.ts +2 -0
  274. package/dist/random/rank.js +44 -4
  275. package/dist/random/rng.js +4 -0
  276. package/dist/random/sample.d.ts +12 -2
  277. package/dist/random/sample.js +63 -20
  278. package/dist/random/streams.js +4 -2
  279. package/dist/rstats.js +17 -14
  280. package/dist/special/besselIK.d.ts +12 -0
  281. package/dist/special/besselIK.js +175 -23
  282. package/dist/special/besselJY.d.ts +11 -1
  283. package/dist/special/besselJY.js +127 -19
  284. package/dist/special/besselSeries.d.ts +27 -0
  285. package/dist/special/besselSeries.js +45 -2
  286. package/dist/special/beta.js +4 -1
  287. package/dist/special/choose.js +24 -8
  288. package/dist/special/dd.js +122 -18
  289. package/dist/special/extra.js +14 -2
  290. package/dist/special/gamma.js +11 -2
  291. package/dist/special/incbet.js +30 -4
  292. package/dist/special/incbetTemme.d.ts +7 -0
  293. package/dist/special/incbetTemme.js +45 -12
  294. package/dist/special/loader.d.ts +1 -1
  295. package/dist/special/loader.js +117 -20
  296. package/dist/special/log1pmx.js +4 -0
  297. package/dist/special/psigamma.js +7 -0
  298. package/dist/special.js +2 -2
  299. package/dist/tests.js +15 -11
  300. package/llms.txt +15 -6
  301. package/package.json +19 -10
  302. package/dist/chunks/chunk-3THFTB36.js +0 -2
  303. package/dist/chunks/chunk-3TSWYE5L.js +0 -2
  304. package/dist/chunks/chunk-3WPU6LGK.js +0 -2
  305. package/dist/chunks/chunk-5ITR67MB.js +0 -2
  306. package/dist/chunks/chunk-5NRFU6F6.js +0 -2
  307. package/dist/chunks/chunk-E2LCSVQV.js +0 -2
  308. package/dist/chunks/chunk-FCNVTIPJ.js +0 -2
  309. package/dist/chunks/chunk-FKAKALOZ.js +0 -2
  310. package/dist/chunks/chunk-HD73UKPT.js +0 -2
  311. package/dist/chunks/chunk-IUULP3LE.js +0 -2
  312. package/dist/chunks/chunk-JQG3YQOC.js +0 -2
  313. package/dist/chunks/chunk-KT66SB7R.js +0 -2
  314. package/dist/chunks/chunk-MAUAOQG3.js +0 -2
  315. package/dist/chunks/chunk-MDYE7QP2.js +0 -2
  316. package/dist/chunks/chunk-NM3Z2UBQ.js +0 -2
  317. package/dist/chunks/chunk-PMJI5QO6.js +0 -3
  318. package/dist/chunks/chunk-UF7KOTHF.js +0 -3
  319. package/dist/chunks/chunk-UOE57JGT.js +0 -2
  320. package/dist/chunks/chunk-USPEBXSR.js +0 -2
  321. package/dist/chunks/chunk-VLUL2HFW.js +0 -3
  322. package/dist/chunks/chunk-ZIX7NYQF.js +0 -2
@@ -17,10 +17,17 @@ 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";
25
+ import { reported } from "../internal/warnings.js";
26
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
27
+ import { checkOptions } from "../internal/checkOptions.js";
28
+ import { isOptionsObject } from "../internal/optionalArgs.js";
29
+ const POLYCHOR_KEYS = ["ML", "stdErr"];
30
+ const POLYSERIAL_KEYS = ["ML", "stdErr"];
24
31
  const BOUND = 0.9999;
25
32
  /** Normal quantiles of the cumulative proportions of the counts, without the last (which would be +Inf) */
26
33
  function thresholds(counts) {
@@ -40,7 +47,10 @@ const isVector = (v) => Array.isArray(v) || ArrayBuffer.isView(v);
40
47
  /** Φ(hi) − Φ(lo) for lo ≤ hi, from the upper tails when both are positive (no cancellation near 1) */
41
48
  const normalInterval = (lo, hi) => lo > 0 ? pnorm(lo, { lowerTail: false }) - pnorm(hi, { lowerTail: false }) : pnorm(hi) - pnorm(lo);
42
49
  /** v standardised to mean 0 and sample standard deviation 1 */
43
- function standardise(v) {
50
+ function standardise(data) {
51
+ // divided by a power of 2 first (exact; the standardised values do not depend on it): the sum of squares of values
52
+ // around 1e200 overflowed, and polyserial gave rho = 2e-9 instead of 0.589
53
+ const v = scaleToUnit([data]).groups[0];
44
54
  const m = mean(v);
45
55
  const centred = v.map((x) => x - m);
46
56
  const sd = Math.sqrt(variance(centred));
@@ -249,7 +259,7 @@ function newtonIterations(evaluate, start, startBounded) {
249
259
  next[0] = Math.sign(next[0]) * BOUND;
250
260
  const nextAt = evaluate(next);
251
261
  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]))));
262
+ const moved = maxOf(next.map((v, k) => Math.abs(v - theta[k]) / Math.max(1, Math.abs(theta[k]))));
253
263
  theta = next;
254
264
  at = nextAt;
255
265
  accepted = moved > 1e-12;
@@ -292,6 +302,9 @@ function inverseNegHessian(hessian, bounded) {
292
302
  }
293
303
  const inadmissibleWarning = (rho) => `inadmissible correlation set to ${rho > 0 ? "0.9999" : "-0.9999"}`;
294
304
  export function polychor(x, yOrOptions, maybeOptions) {
305
+ if (isOptionsObject(yOrOptions))
306
+ checkOptions(yOrOptions, POLYCHOR_KEYS, "polychor"); // generated: option-keys.mjs
307
+ checkOptions(maybeOptions, POLYCHOR_KEYS, "polychor"); // generated: option-keys.mjs
295
308
  let tab;
296
309
  let options;
297
310
  if (!isVector(yOrOptions)) {
@@ -302,6 +315,8 @@ export function polychor(x, yOrOptions, maybeOptions) {
302
315
  if (t.some((r) => r.length !== k))
303
316
  throw new TypeError("the table must have rows of equal length");
304
317
  tab = t.map((r) => Array.from(r));
318
+ if (tab.some((r) => r.some((v) => !(v >= 0 && v < Infinity))))
319
+ throw new RangeError("the counts of the table must be nonnegative and finite");
305
320
  options = yOrOptions ?? {};
306
321
  }
307
322
  else {
@@ -321,6 +336,12 @@ export function polychor(x, yOrOptions, maybeOptions) {
321
336
  }
322
337
  const { ML = false, stdErr = false } = options;
323
338
  const warnings = [];
339
+ // Where the total is 2^1000 or more (the log-likelihood, up to the total times 745, could overflow, and the total
340
+ // itself may), the counts are divided by a power of 2, 2^k: the thresholds and rho do not depend on the units of
341
+ // the counts, and the variances, the chi-square and n are multiplied back below
342
+ let k = 0;
343
+ if (!(sum(tab.map((row) => sum(row))) < 2 ** 1000))
344
+ ({ groups: tab, k } = scaleToUnit(tab));
324
345
  const rowSums = tab.map((r) => sum(r));
325
346
  const zeroRows = rowSums.filter((s) => s === 0).length;
326
347
  if (zeroRows > 0) {
@@ -340,7 +361,7 @@ export function polychor(x, yOrOptions, maybeOptions) {
340
361
  if (c < 2)
341
362
  warnings.push("the table has fewer than 2 columns");
342
363
  if (r < 2 || c < 2)
343
- return { rho: NaN, warnings };
364
+ return reported("polychor", { rho: NaN, warnings });
344
365
  const rowCuts = [-Infinity, ...thresholds(tab.map((row) => sum(row))), Infinity];
345
366
  const colCuts = [-Infinity, ...thresholds(tab[0].map((_, j) => sum(tab.map((row) => row[j])))), Infinity];
346
367
  const negLogLik = (rho0) => {
@@ -359,7 +380,7 @@ export function polychor(x, yOrOptions, maybeOptions) {
359
380
  };
360
381
  const twoStep = optimize(negLogLik, -BOUND, BOUND).optimum;
361
382
  if (!ML && !stdErr)
362
- return { rho: twoStep, warnings };
383
+ return reported("polychor", { rho: twoStep, warnings });
363
384
  // maximum likelihood: θ = (ρ, the inner row thresholds, the inner column thresholds) with ML, ρ alone otherwise
364
385
  const extend = (cuts) => [-Infinity, ...cuts, Infinity];
365
386
  const innerRow = rowCuts.slice(1, r);
@@ -372,32 +393,40 @@ export function polychor(x, yOrOptions, maybeOptions) {
372
393
  if (bounded)
373
394
  warnings.push(inadmissibleWarning(rho));
374
395
  if (!stdErr)
375
- return { rho, warnings };
396
+ return reported("polychor", { rho, warnings });
376
397
  const fittedRow = ML ? extend(theta.slice(1, r)) : rowCuts;
377
398
  const fittedCol = ML ? extend(theta.slice(r)) : colCuts;
378
399
  const n = sum(tab.map((row) => sum(row)));
379
400
  // 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
401
  const terms = [];
402
+ // with scaled counts, the terms n log(1 + 1e-6 / n) (absolute, about 1e-6 each) from the original counts
403
+ const fixed = [];
381
404
  for (let i = 0; i < r; i++) {
382
405
  for (let j = 0; j < c; j++) {
383
406
  const count = tab[i][j];
384
407
  const prob = pbvnorm([fittedRow[i], fittedCol[j]], [fittedRow[i + 1], fittedCol[j + 1]], rho);
385
408
  if (count === 0)
386
409
  terms.push(n * prob);
387
- else
410
+ else if (k === 0)
388
411
  terms.push(count * Math.log1p(1e-6 / count), count * excessOverLog1p((n * prob) / count - 1));
412
+ else {
413
+ const original = ldexp(count, k);
414
+ fixed.push(original * Math.log1p(1e-6 / original));
415
+ terms.push(count * excessOverLog1p((n * prob) / count - 1));
416
+ }
389
417
  }
390
418
  }
391
- return {
419
+ const variances = inverseNegHessian(at.hessian, bounded);
420
+ return reported("polychor", {
392
421
  rho,
393
422
  warnings,
394
- var: inverseNegHessian(at.hessian, bounded),
395
- chisq: 2 * sum(terms),
423
+ var: k === 0 ? variances : variances.map((row) => row.map((v) => ldexp(v, -k))),
424
+ chisq: k === 0 ? 2 * sum(terms) : ldexp(2 * sum(terms), k) + 2 * sum(fixed),
396
425
  df: r * c - r - c,
397
- n,
426
+ n: ldexp(n, k),
398
427
  rowCuts: fittedRow.slice(1, r),
399
428
  colCuts: fittedCol.slice(1, c),
400
- };
429
+ });
401
430
  }
402
431
  /** polycor's chi-square for the polyserial model: the standardised codes and z binned, against the bivariate normal */
403
432
  function polyserialChisq(codes, z, cuts, rho) {
@@ -421,6 +450,7 @@ function polyserialChisq(codes, z, cuts, rho) {
421
450
  return 2 * sum(terms);
422
451
  }
423
452
  export function polyserial(x, y, options = {}) {
453
+ checkOptions(options, POLYSERIAL_KEYS, "polyserial"); // generated: option-keys.mjs
424
454
  if (x.length !== y.length)
425
455
  throw new RangeError("'x' and 'y' must have the same length");
426
456
  const { ML = false, stdErr = false } = options;
@@ -430,7 +460,7 @@ export function polyserial(x, y, options = {}) {
430
460
  const n = xv.length;
431
461
  const levels = sortedDistinct(yv);
432
462
  if (levels.length < 2)
433
- return { rho: NaN, warnings: ["y has fewer than 2 levels"] };
463
+ return reported("polyserial", { rho: NaN, warnings: ["y has fewer than 2 levels"] });
434
464
  const code = new Map(levels.map((v, i) => [v, i + 1]));
435
465
  const yc = yv.map((v) => code.get(v));
436
466
  const counts = levels.map(() => 0);
@@ -445,7 +475,7 @@ export function polyserial(x, y, options = {}) {
445
475
  rho = bounded;
446
476
  }
447
477
  if (!ML && !stdErr)
448
- return { rho, warnings };
478
+ return reported("polyserial", { rho, warnings });
449
479
  // maximum likelihood: θ = (ρ, the thresholds) with ML, ρ alone otherwise
450
480
  const z = standardise(xv);
451
481
  const category = yc.map((v) => v - 1);
@@ -454,10 +484,10 @@ export function polyserial(x, y, options = {}) {
454
484
  if (bounded)
455
485
  warnings.push(inadmissibleWarning(theta[0]));
456
486
  if (!stdErr)
457
- return { rho: theta[0], warnings };
487
+ return reported("polyserial", { rho: theta[0], warnings });
458
488
  const fittedCuts = ML ? theta.slice(1) : cuts;
459
489
  const s = levels.length;
460
- return {
490
+ return reported("polyserial", {
461
491
  rho: theta[0],
462
492
  warnings,
463
493
  var: inverseNegHessian(at.hessian, bounded),
@@ -466,5 +496,5 @@ export function polyserial(x, y, options = {}) {
466
496
  df: 4 * s - s - 1,
467
497
  n,
468
498
  cuts: fittedCuts,
469
- };
499
+ });
470
500
  }
@@ -3,7 +3,6 @@ import { type UnirootOptions } from "../numerics/integrate.js";
3
3
  export declare function matchChoice<T extends string>(value: string | undefined, choices: readonly T[]): T;
4
4
  /** Whether a quantity is to be solved for: null, or omitted when R gives it no default */
5
5
  export declare const isUnknown: (v: unknown) => v is null | undefined;
6
- /** The error when not exactly one of the quantities is unknown */
7
6
  export declare function checkExactlyOne(values: readonly unknown[], message: string): void;
8
7
  /** The root of f(x) = 0 by uniroot, as the power functions call it */
9
8
  export declare function solveFor(f: (x: number) => number, lower: number, upper: number, options?: UnirootOptions): number;
@@ -56,6 +55,8 @@ export interface PowerTTestResult {
56
55
  note?: string;
57
56
  /** Description of the calculation. */
58
57
  method: string;
58
+ /** R's warnings, each once, in R's order (an empty array when there are none). */
59
+ warnings: string[];
59
60
  }
60
61
  /**
61
62
  * Power of a one- or two-sample t test, or the sample size, difference, standard deviation or significance level
@@ -171,7 +172,20 @@ export interface PowerAnovaTestResult {
171
172
  note: string;
172
173
  /** Description of the calculation. */
173
174
  method: string;
175
+ /** R's warnings, each once, in R's order (an empty array when there are none). */
176
+ warnings: string[];
174
177
  }
178
+ /** Whether an F test's power is taken from the normal approximation (df1 finite, both above 1e16) */
179
+ export declare const hugeDf: (df1: number, df2: number) => boolean;
180
+ /**
181
+ * The power P[F > qf(sig)] of an F test with noncentrality ncp where both degrees of freedom exceed 1e16 (df2 may be
182
+ * Infinity). There the critical value 1 + O(df^-1/2) keeps only a few significant digits beyond 1 in doubles (and
183
+ * rounds to 1 for the largest), so that pf(qf(...)) loses the test; F = (χ²(df1, λ)/df1) / (χ²_df2/df2) is normal
184
+ * instead, with mean 1 + μ, μ = λ/df1, and variance 2 (1 + 2μ)/df1 + 2 (1 + μ)²/df2 (2/df1 + 2/df2 under the null),
185
+ * to within O(df1^-1/2) in the power (about 1e-8 at 1e16, 1e-10 at 1e20).
186
+ * The standard deviation is formed as a hypot so that (1 + μ)² does not overflow.
187
+ */
188
+ export declare function fPowerHugeDf(df1: number, df2: number, ncp: number, sig: number): number;
175
189
  /**
176
190
  * Power of the F test of a balanced one-way analysis of variance, or one of the other quantities for a given power.
177
191
  * Equivalent to R's `power.anova.test()`.
@@ -7,7 +7,17 @@
7
7
  import { pf, qf } from "../distributions/f.js";
8
8
  import { pnorm, qnorm } from "../distributions/normal.js";
9
9
  import { pt, qt } from "../distributions/t.js";
10
+ import { ldexp } from "../internal/summary.js";
10
11
  import { uniroot } from "../numerics/integrate.js";
12
+ import { reported } from "../internal/warnings.js";
13
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
14
+ import { checkOptions } from "../internal/checkOptions.js";
15
+ const POWER_TTEST_KEYS = /* @__PURE__ */ new Set([
16
+ "n", "delta", "sd", "sigLevel", "power", "type", "alternative", "strict", "tol",
17
+ ]);
18
+ const POWER_PROP_TEST_KEYS = ["n", "p1", "p2", "sigLevel", "power", "alternative", "strict", "tol"];
19
+ const POWER_ANOVA_TEST_KEYS = ["groups", "n", "betweenVar", "withinVar", "sigLevel", "power"];
20
+ // Generated by `node scripts/option-keys.mjs --write` (end)
11
21
  const TOL = Number.EPSILON ** 0.25;
12
22
  /** R's match.arg: the value in full, also from an unambiguous abbreviation */
13
23
  export function matchChoice(value, choices) {
@@ -25,6 +35,13 @@ export function matchChoice(value, choices) {
25
35
  /** Whether a quantity is to be solved for: null, or omitted when R gives it no default */
26
36
  export const isUnknown = (v) => v === null || v === undefined;
27
37
  /** The error when not exactly one of the quantities is unknown */
38
+ /** Throws unless a known (non-null) value satisfies ok */
39
+ function checkKnown(v, ok, message) {
40
+ if (!isUnknown(v) && !ok(v))
41
+ throw new RangeError(message);
42
+ }
43
+ const isProb = (v) => v >= 0 && v <= 1;
44
+ const isPositiveFinite = (v) => v > 0 && v < Infinity;
28
45
  export function checkExactlyOne(values, message) {
29
46
  if (values.filter(isUnknown).length !== 1)
30
47
  throw new RangeError(message);
@@ -54,11 +71,17 @@ const SIG_MESSAGE = "'sig.level' must be numeric in [0, 1]";
54
71
  * @category Effect sizes and power
55
72
  */
56
73
  export function powerTTest(options = {}) {
74
+ checkOptions(options, POWER_TTEST_KEYS, "powerTTest"); // generated: option-keys.mjs
57
75
  let { n, delta, power } = options;
58
76
  let sd = options.sd === undefined ? 1 : options.sd;
59
77
  let sigLevel = options.sigLevel === undefined ? 0.05 : options.sigLevel;
60
78
  checkExactlyOne([n, delta, sd, power, sigLevel], "exactly one of 'n', 'delta', 'sd', 'power', and 'sig.level' must be NULL");
61
79
  checkSigLevel(sigLevel, SIG_MESSAGE);
80
+ checkKnown(power, isProb, "'power' must be a probability");
81
+ checkKnown(sd, isPositiveFinite, "'sd' must be a positive finite number");
82
+ checkKnown(n, (v) => v >= 2, "number of observations in each group must be at least 2");
83
+ checkKnown(delta, (v) => !Number.isNaN(v), "'delta' must not be NaN");
84
+ checkKnown(options.tol, isPositiveFinite, "'tol' must be a positive finite number");
62
85
  const type = matchChoice(options.type, ["two.sample", "one.sample", "paired"]);
63
86
  const alternative = matchChoice(options.alternative, ["two.sided", "one.sided"]);
64
87
  const strict = options.strict ?? false;
@@ -70,7 +93,12 @@ export function powerTTest(options = {}) {
70
93
  const powerOf = (n, delta, sd, sig) => {
71
94
  const nu = Math.max(1e-7, n - 1) * ts;
72
95
  const q = qt(sig / sides, nu, { lowerTail: false });
73
- const ncp = (Math.sqrt(n / ts) * delta) / sd;
96
+ let ncp = (Math.sqrt(n / ts) * delta) / sd;
97
+ // sqrt(n / ts) * delta can overflow before the division by a large sd (#197); with the ratio delta / sd first the
98
+ // noncentrality is Infinity only where it is beyond the doubles itself (sqrt(n / ts) >= 1). Only there: elsewhere
99
+ // R's order, with its bits
100
+ if (!Number.isFinite(ncp))
101
+ ncp = Math.sqrt(n / ts) * (delta / sd);
74
102
  const p = ptNcp(q, nu, ncp, false);
75
103
  return strict && sides === 2 ? p + ptNcp(-q, nu, ncp, true) : p;
76
104
  };
@@ -78,10 +106,19 @@ export function powerTTest(options = {}) {
78
106
  power = powerOf(n, delta, sd, sigLevel);
79
107
  else {
80
108
  const target = power;
81
- if (isUnknown(n))
109
+ if (isUnknown(n)) {
110
+ // with delta = 0 the power does not depend on n (R and before #311: the search failed with "no sign change")
111
+ if (delta === 0)
112
+ throw new RangeError("'n' cannot be determined when 'delta' is 0: the power does not depend on it");
82
113
  n = solveFor((x) => powerOf(x, delta, sd, sigLevel) - target, 2, 1e7, { tol, extendInt: "upX" });
114
+ }
83
115
  else if (isUnknown(sd)) {
84
- sd = solveFor((x) => powerOf(n, delta, x, sigLevel) - target, delta * 1e-7, delta * 1e7, { tol, extendInt: "downX" });
116
+ // with delta = 0 the power does not depend on sd (R: "lower < upper is not fulfilled"); with a negative delta (one
117
+ // sided) the power rises towards sigLevel as sd grows, so the search runs over |delta| the other way
118
+ if (delta === 0)
119
+ throw new RangeError("'sd' cannot be determined when 'delta' is 0: the power does not depend on it");
120
+ const ad = Math.abs(delta);
121
+ sd = solveFor((x) => powerOf(n, delta, x, sigLevel) - target, ad * 1e-7, ad * 1e7, { tol, extendInt: delta > 0 ? "downX" : "upX" });
85
122
  }
86
123
  else if (isUnknown(delta)) {
87
124
  delta = solveFor((x) => powerOf(n, x, sd, sigLevel) - target, sd * 1e-7, sd * 1e7, { tol, extendInt: "upX" });
@@ -105,6 +142,7 @@ export function powerTTest(options = {}) {
105
142
  alternative,
106
143
  ...(note === undefined ? {} : { note }),
107
144
  method,
145
+ warnings: [],
108
146
  };
109
147
  }
110
148
  /**
@@ -119,10 +157,17 @@ export function powerTTest(options = {}) {
119
157
  * @category Effect sizes and power
120
158
  */
121
159
  export function powerPropTest(options = {}) {
160
+ checkOptions(options, POWER_PROP_TEST_KEYS, "powerPropTest"); // generated: option-keys.mjs
122
161
  let { n, p1, p2, power } = options;
123
162
  let sigLevel = options.sigLevel === undefined ? 0.05 : options.sigLevel;
124
163
  checkExactlyOne([n, p1, p2, power, sigLevel], "exactly one of 'n', 'p1', 'p2', 'power', and 'sig.level' must be NULL");
125
164
  checkSigLevel(sigLevel, SIG_MESSAGE);
165
+ checkKnown(power, isProb, "'power' must be a probability");
166
+ checkKnown(p1, isProb, "'p1' must be a probability");
167
+ checkKnown(p2, isProb, "'p2' must be a probability");
168
+ // (R gives a power for n = 0 and NaN for a negative n)
169
+ checkKnown(n, (v) => v > 0, "number of observations in each group must be positive");
170
+ checkKnown(options.tol, isPositiveFinite, "'tol' must be a positive finite number");
126
171
  const alternative = matchChoice(options.alternative, ["two.sided", "one.sided"]);
127
172
  const strict = options.strict ?? false;
128
173
  const tol = options.tol ?? TOL;
@@ -146,14 +191,24 @@ export function powerPropTest(options = {}) {
146
191
  power = powerOf(n, p1, p2, sigLevel);
147
192
  else {
148
193
  const target = power;
149
- if (isUnknown(n))
194
+ if (isUnknown(n)) {
195
+ // with p1 = p2 the power does not depend on n (R and before #311: the search failed with "no sign change")
196
+ if (p1 === p2)
197
+ throw new RangeError("'n' cannot be determined when 'p1' equals 'p2': the power does not depend on it");
150
198
  n = solveFor((x) => powerOf(x, p1, p2, sigLevel) - target, 1, 1e7, { tol, extendInt: "upX" });
199
+ }
151
200
  else if (isUnknown(p1)) {
201
+ // p1 is searched in [0, p2]: with p2 = 0 that is a point (R and before #312: "lower < upper is not fulfilled")
202
+ if (p2 === 0)
203
+ throw new RangeError("'p1' cannot be determined when 'p2' is 0: no p1 in [0, p2] differs from p2");
152
204
  p1 = solveFor((x) => powerOf(n, x, p2, sigLevel) - target, 0, p2, { tol, extendInt: "yes" });
153
205
  if (p1 < 0)
154
206
  warnings.push("No p1 in [0, p2] can be found to achieve the desired power");
155
207
  }
156
208
  else if (isUnknown(p2)) {
209
+ // p2 is searched in [p1, 1]: with p1 = 1 that is a point (as for p1 above)
210
+ if (p1 === 1)
211
+ throw new RangeError("'p2' cannot be determined when 'p1' is 1: no p2 in [p1, 1] differs from p1");
157
212
  p2 = solveFor((x) => powerOf(n, p1, x, sigLevel) - target, p1, 1, { tol, extendInt: "yes" });
158
213
  if (p2 > 1)
159
214
  warnings.push("No p2 in [p1, 1] can be found to achieve the desired power");
@@ -164,7 +219,7 @@ export function powerPropTest(options = {}) {
164
219
  warnings.push("No significance level [0, 1] can be found to achieve the desired power");
165
220
  }
166
221
  }
167
- return {
222
+ return reported("powerPropTest", {
168
223
  n: n,
169
224
  p1: p1,
170
225
  p2: p2,
@@ -174,7 +229,42 @@ export function powerPropTest(options = {}) {
174
229
  note: "n is number in *each* group",
175
230
  method: "Two-sample comparison of proportions power calculation",
176
231
  warnings,
177
- };
232
+ });
233
+ }
234
+ /**
235
+ * Above this, both degrees of freedom of an F test are huge enough for {@link fPowerHugeDf} (pwrF2Test, pwrAnovaTest,
236
+ * powerAnovaTest). (1e16: the exact path pf(qf(...)) already loses about 1e-8 of the power there, from the critical
237
+ * value's few significant digits beyond 1, and up to 1e-5 just below 1e20; the approximation's error O(df^-1/2) is
238
+ * below that.)
239
+ */
240
+ const HUGE_DF = 1e16;
241
+ /** Whether an F test's power is taken from the normal approximation (df1 finite, both above 1e16) */
242
+ export const hugeDf = (df1, df2) => df1 > HUGE_DF && df1 < Infinity && df2 > HUGE_DF;
243
+ /**
244
+ * The power P[F > qf(sig)] of an F test with noncentrality ncp where both degrees of freedom exceed 1e16 (df2 may be
245
+ * Infinity). There the critical value 1 + O(df^-1/2) keeps only a few significant digits beyond 1 in doubles (and
246
+ * rounds to 1 for the largest), so that pf(qf(...)) loses the test; F = (χ²(df1, λ)/df1) / (χ²_df2/df2) is normal
247
+ * instead, with mean 1 + μ, μ = λ/df1, and variance 2 (1 + 2μ)/df1 + 2 (1 + μ)²/df2 (2/df1 + 2/df2 under the null),
248
+ * to within O(df1^-1/2) in the power (about 1e-8 at 1e16, 1e-10 at 1e20).
249
+ * The standard deviation is formed as a hypot so that (1 + μ)² does not overflow.
250
+ */
251
+ export function fPowerHugeDf(df1, df2, ncp, sig) {
252
+ const z = qnorm(sig, { lowerTail: false });
253
+ const mu = ncp / df1;
254
+ const sd0 = Math.sqrt(2 / df1 + 2 / df2);
255
+ const sd1 = Math.hypot(Math.sqrt((2 * (1 + 2 * mu)) / df1), Math.sqrt(2 / df2) * (1 + mu));
256
+ return pnorm((z * sd0 - mu) / sd1, { lowerTail: false });
257
+ }
258
+ /**
259
+ * a b c / d for finite a, b, d > 0 and c >= 0, each factor scaled to [1, 2) by a power of 2 and the exponents added
260
+ * back at the end, so that no partial product overflows or underflows unless the result does
261
+ */
262
+ function scaledProductOver(a, b, c, d) {
263
+ if (c === 0)
264
+ return 0;
265
+ const k = (v) => Math.floor(Math.log2(v));
266
+ const [ka, kb, kc, kd] = [k(a), k(b), k(c), k(d)];
267
+ return ldexp((ldexp(a, -ka) * ldexp(b, -kb) * ldexp(c, -kc)) / ldexp(d, -kd), ka + kb + kc - kd);
178
268
  }
179
269
  /**
180
270
  * Power of the F test of a balanced one-way analysis of variance, or one of the other quantities for a given power.
@@ -188,18 +278,37 @@ export function powerPropTest(options = {}) {
188
278
  * @category Effect sizes and power
189
279
  */
190
280
  export function powerAnovaTest(options = {}) {
281
+ checkOptions(options, POWER_ANOVA_TEST_KEYS, "powerAnovaTest"); // generated: option-keys.mjs
191
282
  let { groups, n, betweenVar, withinVar, power } = options;
192
283
  let sigLevel = options.sigLevel === undefined ? 0.05 : options.sigLevel;
193
284
  checkExactlyOne([groups, n, betweenVar, withinVar, power, sigLevel], "exactly one of 'groups', 'n', 'between.var', 'within.var', 'power', and 'sig.level' must be NULL");
194
- if (!isUnknown(groups) && groups < 2)
285
+ if (!isUnknown(groups) && !(groups >= 2))
195
286
  throw new RangeError("number of groups must be at least 2");
196
- if (!isUnknown(n) && n < 2)
287
+ if (!isUnknown(n) && !(n >= 2))
197
288
  throw new RangeError("number of observations in each group must be at least 2");
198
289
  checkSigLevel(sigLevel, SIG_MESSAGE);
290
+ checkKnown(power, isProb, "'power' must be a probability");
291
+ checkKnown(betweenVar, (v) => v >= 0 && v < Infinity, "'betweenVar' must be a nonnegative finite number");
292
+ checkKnown(withinVar, isPositiveFinite, "'withinVar' must be a positive finite number");
199
293
  const powerOf = (groups, n, between, within, sig) => {
200
- const lambda = ((groups - 1) * n * between) / within;
294
+ // (the ratio first where the product with between overflows but the noncentrality is in range; where
295
+ // (groups - 1) n itself overflows, from the four factors scaled by powers of 2: groups 3, n 1e308, between 1,
296
+ // within 1e308 gave the limit 1 for lambda = 2, and between 0 NaN for 0)
297
+ let lambda = ((groups - 1) * n * between) / within;
298
+ if (!(lambda < Infinity))
299
+ lambda = (groups - 1) * n * (between / within);
300
+ if (!(lambda < Infinity) && Number.isFinite(groups) && Number.isFinite(n)) {
301
+ lambda = scaledProductOver(groups - 1, n, between, within);
302
+ }
201
303
  const df1 = groups - 1;
202
304
  const df2 = (n - 1) * groups;
305
+ // (a noncentrality beyond the doubles: the limit 1)
306
+ if (lambda === Infinity)
307
+ return 1;
308
+ // (both degrees of freedom above 1e16: the normal approximation, as in pwrAnovaTest; the critical value is 1 to a
309
+ // few digits, and groups 1e200, n 1e200, between 1e8, within 1e308 gave 0.760 for 0.174. R gives NaN there)
310
+ if (hugeDf(df1, df2))
311
+ return fPowerHugeDf(df1, df2, lambda, sig);
203
312
  return pf(qf(sig, df1, df2, { lowerTail: false }), df1, df2, { ncp: lambda, lowerTail: false });
204
313
  };
205
314
  if (isUnknown(power))
@@ -208,9 +317,17 @@ export function powerAnovaTest(options = {}) {
208
317
  const target = power;
209
318
  if (isUnknown(groups))
210
319
  groups = solveFor((x) => powerOf(x, n, betweenVar, withinVar, sigLevel) - target, 2, 100);
211
- else if (isUnknown(n))
320
+ else if (isUnknown(n)) {
321
+ // (with betweenVar = 0 the power does not depend on n; R and before #311: "f() values at end points not of
322
+ // opposite sign")
323
+ if (betweenVar === 0)
324
+ throw new RangeError("'n' cannot be determined when 'betweenVar' is 0: the power does not depend on it");
212
325
  n = solveFor((x) => powerOf(groups, x, betweenVar, withinVar, sigLevel) - target, 2, 1e5);
326
+ }
213
327
  else if (isUnknown(withinVar)) {
328
+ // (with betweenVar = 0 the power does not depend on withinVar; R: "lower < upper is not fulfilled")
329
+ if (betweenVar === 0)
330
+ throw new RangeError("'withinVar' cannot be determined when 'betweenVar' is 0: the power does not depend on it");
214
331
  withinVar = solveFor((x) => powerOf(groups, n, betweenVar, x, sigLevel) - target, betweenVar * 1e-7, betweenVar * 1e7);
215
332
  }
216
333
  else if (isUnknown(betweenVar)) {
@@ -229,5 +346,6 @@ export function powerAnovaTest(options = {}) {
229
346
  power,
230
347
  note: "n is number in each group",
231
348
  method: "Balanced one-way analysis of variance power calculation",
349
+ warnings: [],
232
350
  };
233
351
  }
@@ -33,6 +33,9 @@ export interface PropTestResult extends Omit<HTest, "nullValue" | "nullValueName
33
33
  /**
34
34
  * Test of equal or given proportions. Equivalent to R's `prop.test()`.
35
35
  *
36
+ * As R, `warnings` has "Chi-squared approximation may be incorrect" where an expected count of the table of successes
37
+ * and failures (n p or n (1 - p), p the given or the pooled proportion) is below 5.
38
+ *
36
39
  * @param x Numbers of successes, or a table of rows `[successes, failures]`.
37
40
  * @param n Numbers of trials (omitted, and the options passed in its place, when `x` is a table).
38
41
  * @param options See {@link PropTestOptions}.
@@ -8,13 +8,26 @@
8
8
  // statistic is then exactly 0). One-sided alternatives use the signed square root of the statistic as a normal
9
9
  // deviate. Intervals: the Wilson score interval (Wilson, JASA 22, 1927) with continuity correction for one proportion
10
10
  // (Newcombe, Statistics in Medicine 17, 1998, method 4), and the Wald interval with continuity correction for the
11
- // difference of two.
11
+ // difference of two. R's warning "Chi-squared approximation may be incorrect" where an expected count n p or n (1 - p)
12
+ // is below 5 (p the given or the pooled proportion).
12
13
  import { pgamma1 } from "../distributions/gamma.js";
13
14
  import { pnorm, qnorm } from "../distributions/normal.js";
15
+ import { ldexp, squareOver } from "../internal/summary.js";
14
16
  import { checkConfLevelOpen, matchAlternative } from "./types.js";
17
+ import { reported } from "../internal/warnings.js";
18
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
19
+ import { checkOptions } from "../internal/checkOptions.js";
20
+ import { isOptionsObject } from "../internal/optionalArgs.js";
21
+ const PROP_TEST_KEYS = ["p", "alternative", "confLevel", "correct"];
22
+ // Generated by `node scripts/option-keys.mjs --write` (end)
23
+ /** R's warning where an expected count of the table is below 5 */
24
+ const APPROXIMATION = "Chi-squared approximation may be incorrect";
15
25
  /**
16
26
  * Test of equal or given proportions. Equivalent to R's `prop.test()`.
17
27
  *
28
+ * As R, `warnings` has "Chi-squared approximation may be incorrect" where an expected count of the table of successes
29
+ * and failures (n p or n (1 - p), p the given or the pooled proportion) is below 5.
30
+ *
18
31
  * @param x Numbers of successes, or a table of rows `[successes, failures]`.
19
32
  * @param n Numbers of trials (omitted, and the options passed in its place, when `x` is a table).
20
33
  * @param options See {@link PropTestOptions}.
@@ -28,6 +41,9 @@ import { checkConfLevelOpen, matchAlternative } from "./types.js";
28
41
  * @category Hypothesis tests
29
42
  */
30
43
  export function propTest(x, n, options = {}) {
44
+ if (isOptionsObject(n))
45
+ checkOptions(n, PROP_TEST_KEYS, "propTest"); // generated: option-keys.mjs
46
+ checkOptions(options, PROP_TEST_KEYS, "propTest"); // generated: option-keys.mjs
31
47
  // ---- inputs: successes and trials per group ----
32
48
  let xs;
33
49
  let ns;
@@ -61,6 +77,8 @@ export function propTest(x, n, options = {}) {
61
77
  ns = kept.map((i) => ns[i]);
62
78
  if (ns.some((v) => !(v > 0)))
63
79
  throw new RangeError("elements of 'n' must be positive");
80
+ if (ns.some((v) => v === Infinity))
81
+ throw new RangeError("elements of 'n' must be finite");
64
82
  if (xs.some((v) => !(v >= 0)))
65
83
  throw new RangeError("elements of 'x' must be nonnegative");
66
84
  if (xs.some((v, i) => v > ns[i]))
@@ -99,15 +117,20 @@ export function propTest(x, n, options = {}) {
99
117
  [yates, capped] = [gap, true];
100
118
  }
101
119
  // ---- Pearson's chi-squared on the k x 2 table of successes and failures ----
102
- const pooled = xs.reduce((a, b) => a + b, 0) / ns.reduce((a, b) => a + b, 0);
120
+ const pooled = pooledProportion(xs, ns);
121
+ // R's expected counts n p and n (1 - p) of the table, checked whatever the correction
122
+ const small = ns.some((v, i) => {
123
+ const pi = p?.[i] ?? pooled;
124
+ return v * pi < 5 || v * (1 - pi) < 5;
125
+ });
103
126
  let statistic = 0;
104
127
  if (!capped) {
105
128
  for (let i = 0; i < k; i++) {
106
129
  const pi = p?.[i] ?? pooled;
107
130
  const e1 = ns[i] * pi;
108
131
  const e2 = ns[i] * (1 - pi);
109
- statistic += (Math.abs(xs[i] - e1) - yates) ** 2 / e1;
110
- statistic += (Math.abs(ns[i] - xs[i] - e2) - yates) ** 2 / e2;
132
+ statistic += squareOver(Math.abs(xs[i] - e1) - yates, e1);
133
+ statistic += squareOver(Math.abs(ns[i] - xs[i] - e2) - yates, e2);
111
134
  }
112
135
  }
113
136
  const df = p !== undefined ? k : k - 1;
@@ -121,7 +144,9 @@ export function propTest(x, n, options = {}) {
121
144
  // ---- confidence interval ----
122
145
  let confInt;
123
146
  if (k === 1 || (k === 2 && !pGiven)) {
124
- const z = qnorm(alternative === "two.sided" ? (1 + confLevel) / 2 : confLevel);
147
+ // (for alpha below 1e-8 the upper probability itself: 1 - alpha loses its digits and rounds to 1 below 1.1e-16; review 58)
148
+ const a2 = (1 - confLevel) / 2;
149
+ const z = alternative === "two.sided" && a2 < 1e-8 ? qnorm(a2, { lowerTail: false }) : qnorm(alternative === "two.sided" ? (1 + confLevel) / 2 : confLevel);
125
150
  if (k === 1) {
126
151
  const nn = ns[0];
127
152
  const z2 = z * z;
@@ -153,6 +178,7 @@ export function propTest(x, n, options = {}) {
153
178
  pValue,
154
179
  estimate: k === 1 ? phat[0] : phat,
155
180
  estimateNames: names,
181
+ warnings: small ? [APPROXIMATION] : [],
156
182
  };
157
183
  if (p !== undefined) {
158
184
  result.nullValue = k === 1 ? p[0] : p;
@@ -162,5 +188,17 @@ export function propTest(x, n, options = {}) {
162
188
  result.confInt = confInt;
163
189
  result.confLevel = confLevel;
164
190
  }
165
- return result;
191
+ return reported("propTest", result);
192
+ }
193
+ /**
194
+ * sum(x) / sum(n). Where the total of the trials overflows (each n is finite), both totals in units of 2^s with
195
+ * 2^s >= the number of groups, so that neither can overflow; the common power of 2 cancels in the ratio. Elsewhere the
196
+ * plain ratio, unchanged
197
+ */
198
+ function pooledProportion(xs, ns) {
199
+ const total = ns.reduce((a, b) => a + b, 0);
200
+ if (total < Infinity)
201
+ return xs.reduce((a, b) => a + b, 0) / total;
202
+ const s = Math.ceil(Math.log2(ns.length));
203
+ return xs.reduce((a, b) => a + ldexp(b, -s), 0) / ns.reduce((a, b) => a + ldexp(b, -s), 0);
166
204
  }