@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
@@ -7,19 +7,31 @@
7
7
  // model's fit, regressed by weighted least squares on the larger model's matrix.
8
8
  import { pf1 } from "../distributions/f.js";
9
9
  import { pgamma1 } from "../distributions/gamma.js";
10
- import { glmDispersion, refit } from "./glm.js";
11
- import { makeFamily, Warnings } from "./glmFamily.js";
10
+ import { ldexp, ldexpWide } from "../internal/summary.js";
11
+ import { nestedColumns } from "./estimable.js";
12
+ import { glmDispersion, refit, scaledDispersion, scaledView } from "./glm.js";
13
+ import { makeFamily } from "./glmFamily.js";
14
+ import { reported, Warnings } from "../internal/warnings.js";
12
15
  import { scoreStatistic } from "./glmConfint.js";
16
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
17
+ import { checkOptions } from "../internal/checkOptions.js";
18
+ const GLM_ANOVA_KEYS = ["test", "dispersion"];
13
19
  /** Upper tail of chi-squared with df degrees of freedom */
14
20
  const pchisqUpper = (q, df) => pgamma1(q, df / 2, 2, false, false);
15
- /** The working residuals and weights of the fit of the model with the given columns */
21
+ /**
22
+ * The working residuals and weights of the fit of the model with the given columns. Without the fit's start: R's
23
+ * anova.glm passes object$start, which glm does not keep (NULL), and the fit's start has the length of all its columns
24
+ * (#178)
25
+ */
16
26
  function rowOf(model, cols, warnings) {
17
- const { fit, w } = refit(model, cols, warnings);
27
+ const { fit, w } = refit(model, cols, warnings, { start: undefined });
18
28
  const nOk = w.filter((v) => v > 0).length;
19
29
  return { dfRes: nOk - fit.rank, dev: fit.deviance, fit, x: model.x.map((r) => cols.map((j) => r[j])), intercept: model.intercept };
20
30
  }
21
31
  /** Score statistic of the smaller model's fit against the larger model's matrix */
22
- const rao = (small, large) => scoreStatistic(large.x, small.fit.workingResiduals, small.fit.workingWeights, large.intercept);
32
+ // (the intercept of the smaller model, as R's anova.glmlist: with the larger one's, the residuals of a model without
33
+ // intercept were centred, removing what the added intercept explains; review 64)
34
+ const rao = (small, large) => scoreStatistic(large.x, small.fit.workingResiduals, small.fit.workingWeights, small.intercept);
23
35
  /**
24
36
  * Analysis of deviance, for one `glm` fit (the sequential table, each column of `x` added in order) or for several
25
37
  * fits of the same data (`anova(fit1, fit2, ...)`). Equivalent to R's `anova()`.
@@ -40,19 +52,55 @@ const rao = (small, large) => scoreStatistic(large.x, small.fit.workingResiduals
40
52
  * @category Generalized linear models
41
53
  */
42
54
  export function glmAnova(fits, options = {}) {
43
- const list = Array.isArray(fits) ? fits : [fits];
44
- if (list.length === 0)
55
+ checkOptions(options, GLM_ANOVA_KEYS, "glmAnova"); // generated: option-keys.mjs
56
+ const given = Array.isArray(fits) ? fits : [fits];
57
+ if (given.length === 0)
45
58
  throw new RangeError("no fits to compare");
59
+ // on the scaled fits (scaledView) when they share one scale: deviances, scores and Cp scaled back by 2^2k
60
+ const views = given.map(scaledView);
61
+ const k = views.every((v) => v.k === views[0].k) ? views[0].k : 0;
62
+ const list = k === 0 ? given : views.map((v) => v.fit);
63
+ // (a given dispersion is m 4^s; s != 0 only where its scaled value is out of range, #349: the statistics divided by
64
+ // it are then brought back by 4^-s, and Cp is formed in the original units below)
65
+ const user = options.dispersion === undefined ? undefined : scaledDispersion(options.dispersion, k);
66
+ const shift = user?.s ?? 0;
67
+ const table = glmAnovaScaled(list, Array.isArray(fits) && list.length > 1, { ...options, ...(user === undefined ? {} : { dispersion: user.m }) }, shift);
68
+ if (k === 0 && shift === 0)
69
+ return reported("glmAnova", table, ...given);
70
+ const squared = new Set(["Deviance", "Resid. Dev", "Rao", "Cp"]);
71
+ const cols = table.colNames.map((c) => squared.has(c));
72
+ const scaledBack = table.table.map((r) => r.map((v, j) => (cols[j] ? ldexp(v, 2 * k) : v)));
73
+ if (shift !== 0 && table.colNames.includes("Cp")) {
74
+ // R's residual deviance + 2 dispersion (n - residual df), from the deviance scaled back and the given dispersion
75
+ const cp = table.colNames.indexOf("Cp");
76
+ const dev = table.colNames.indexOf("Resid. Dev");
77
+ const dfRes = table.colNames.indexOf("Resid. Df");
78
+ const n = list[0].model.x.length;
79
+ for (const r of scaledBack)
80
+ r[cp] = r[dev] + 2 * (n - r[dfRes]) * options.dispersion;
81
+ }
82
+ return reported("glmAnova", { ...table, table: scaledBack }, ...given);
83
+ }
84
+ function glmAnovaScaled(list, compare, options, shift = 0) {
46
85
  const warnings = new Warnings();
47
- const compare = Array.isArray(fits) && list.length > 1;
48
86
  const first = list[0];
49
87
  const fam = makeFamily(first.model.familySpec);
88
+ // deviances of different families (or links) are not on one likelihood: no test compares them (R uses the first
89
+ // fit's family for all)
90
+ if (list.some((f) => { const g = makeFamily(f.model.familySpec); return g.family !== fam.family || g.name !== fam.name || g.varianceName !== fam.varianceName; })) {
91
+ throw new RangeError("models were not all fitted with the same family and link");
92
+ }
50
93
  const fixed = fam.fixedDispersion;
51
94
  const test = options.test === undefined ? (options.dispersion !== undefined || fixed ? "Chisq" : "F") : options.test;
95
+ if (test !== false && !["Rao", "LRT", "Chisq", "F", "Cp"].includes(test))
96
+ throw new RangeError(`invalid 'test': ${String(test)}`);
52
97
  const rows = [];
53
98
  let df;
54
99
  let devDiff;
55
100
  let score = [];
101
+ // rows (of a comparison) whose model with fewer parameters is not a special case of the other: no test (R tests any
102
+ // pair), as lmerAnova and anova of lm fits
103
+ const untested = new Set();
56
104
  let ref;
57
105
  if (!compare) {
58
106
  const fit = first;
@@ -84,9 +132,30 @@ export function glmAnova(fits, options = {}) {
84
132
  const n = list[0].model.x.length;
85
133
  if (list.some((f) => f.model.x.length !== n))
86
134
  throw new RangeError("models were not all fitted to the same size of dataset");
135
+ // deviances compare likelihoods of the same observations: the same response and prior weights (R's anova.glmlist
136
+ // drops fits whose formula has another response, with a warning, and compares only the number of rows otherwise)
137
+ const same = (a, b) => a.length === b.length && a.every((v, i) => JSON.stringify(v) === JSON.stringify(b[i]));
138
+ if (list.some((f) => !same(f.model.yGiven, list[0].model.yGiven)))
139
+ throw new RangeError("models were not all fitted to the same response");
140
+ if (list.some((f) => !same(f.model.priorGiven, list[0].model.priorGiven)))
141
+ throw new RangeError("models were not all fitted with the same prior weights");
87
142
  list.forEach((f, i) => rows.push({ name: String(i + 1), dfRes: f.dfResidual, dev: f.deviance }));
88
143
  df = rows.map((r, i) => (i === 0 ? NaN : rows[i - 1].dfRes - r.dfRes));
89
144
  devDiff = rows.map((r, i) => (i === 0 ? NaN : rows[i - 1].dev - r.dev));
145
+ list.forEach((f, i) => {
146
+ if (i === 0 || df[i] === 0)
147
+ return;
148
+ const [small, large] = df[i] > 0 ? [list[i - 1], f] : [f, list[i - 1]];
149
+ // nested as affine models: the columns of the smaller model and the difference of the offsets both in the column
150
+ // space of the larger one (two fits with other offsets are not nested even when their columns are)
151
+ // on the rows of positive weight only: rows of weight 0 are not in the likelihoods (one of them made the columns
152
+ // of nested models look otherwise; review 64)
153
+ const active = (rows) => rows.filter((_, r) => small.priorWeights[r] > 0 && large.priorWeights[r] > 0);
154
+ const d = small.model.offset.map((o, r) => o - large.model.offset[r]);
155
+ const smallX = d.some((v, r) => v !== 0 && small.priorWeights[r] > 0) ? small.model.x.map((row, r) => [...row, d[r]]) : small.model.x;
156
+ if (!nestedColumns(active(smallX), active(large.model.x)))
157
+ untested.add(i);
158
+ });
90
159
  if (test === "Rao") {
91
160
  const fr = list.map((f) => ({ dfRes: f.dfResidual, dev: f.deviance, fit: asIrls(f), x: f.model.x, intercept: f.model.intercept }));
92
161
  score = rows.map((_, i) => {
@@ -98,6 +167,11 @@ export function glmAnova(fits, options = {}) {
98
167
  }
99
168
  ref = list.reduce((a, b) => (b.dfResidual < a.dfResidual ? b : a));
100
169
  }
170
+ // (R tests fits that have not converged without a word in the table; review 66)
171
+ list.forEach((f, i) => {
172
+ if (!f.converged)
173
+ warnings.add(`model ${i + 1} has not converged: its deviance is not that of the maximum likelihood fit`);
174
+ });
101
175
  const summaryWarnings = new Warnings();
102
176
  const dispersion = options.dispersion ?? glmDispersion(ref, summaryWarnings);
103
177
  summaryWarnings.list.forEach((m) => warnings.add(m));
@@ -106,9 +180,9 @@ export function glmAnova(fits, options = {}) {
106
180
  const cells = rows.map((r, i) => (compare ? [r.dfRes, r.dev, df[i], devDiff[i]] : [df[i], devDiff[i], r.dfRes, r.dev]));
107
181
  const colNames = [...head];
108
182
  const chisqP = (stat) => rows.map((_, i) => {
109
- if (i === 0 || df[i] === 0)
183
+ if (i === 0 || df[i] === 0 || untested.has(i))
110
184
  return NaN;
111
- const v = (stat[i] / dispersion) * Math.sign(df[i]);
185
+ const v = ldexpWide((stat[i] / dispersion) * Math.sign(df[i]), -2 * shift);
112
186
  return v < 0 || Number.isNaN(v) ? NaN : pchisqUpper(v, Math.abs(df[i]));
113
187
  });
114
188
  let extra = [];
@@ -118,15 +192,15 @@ export function glmAnova(fits, options = {}) {
118
192
  }
119
193
  else if (test === "Rao") {
120
194
  colNames.push("Rao", "Pr(>Chi)");
121
- extra = [score, chisqP(score)];
195
+ extra = [score.map((v, i) => (untested.has(i) ? NaN : v)), chisqP(score)];
122
196
  }
123
197
  else if (test === "F") {
124
198
  if (fixed)
125
199
  warnings.add(`using F test with a '${fam.family}' family is inappropriate`);
126
200
  if (dfDispersion !== 0) {
127
201
  const F = rows.map((_, i) => {
128
- const v = devDiff[i] / df[i] / dispersion;
129
- return i === 0 || df[i] === 0 || v < 0 ? NaN : v;
202
+ const v = ldexpWide(devDiff[i] / df[i] / dispersion, -2 * shift);
203
+ return i === 0 || df[i] === 0 || untested.has(i) || v < 0 ? NaN : v;
130
204
  });
131
205
  colNames.push("F", "Pr(>F)");
132
206
  extra = [F, F.map((v, i) => (Number.isNaN(v) ? NaN : pf1(v, Math.abs(df[i]), dfDispersion, false, false)))];
@@ -135,7 +209,9 @@ export function glmAnova(fits, options = {}) {
135
209
  else if (test === "Cp") {
136
210
  const n = ref.model.x.length;
137
211
  colNames.push("Cp");
138
- extra = [rows.map((r) => r.dev + 2 * dispersion * (n - r.dfRes))];
212
+ // R's 2 * dispersion * (n - df) reordered: the products by 2 are exact, so the bits are the same where 2 * dispersion
213
+ // does not overflow, and a penalty of 0 parameters is 0 instead of Inf * 0 = NaN (#188)
214
+ extra = [rows.map((r) => r.dev + 2 * (n - r.dfRes) * dispersion)];
139
215
  }
140
216
  const table = cells.map((r, i) => [...r, ...extra.map((col) => col[i])]);
141
217
  return { colNames, rowNames: rows.map((r) => r.name), table, warnings: warnings.list };
@@ -31,7 +31,7 @@ export declare function scoreStatistic(x: number[][], r: number[], v: number[],
31
31
  *
32
32
  * @category Generalized linear models
33
33
  */
34
- export declare function glmConfint(fit: GlmResult, options?: GlmConfintOptions): {
34
+ export declare function glmConfint(given: GlmResult, options?: GlmConfintOptions): {
35
35
  /** Lower limits, one per coefficient (R's first column, `2.5 %` by default). */
36
36
  lower: number[];
37
37
  /** Upper limits, one per coefficient (R's second column, `97.5 %` by default). */
@@ -11,10 +11,14 @@
11
11
  // rounding, at most 100 iterations): the deviance is stationary at the estimate, so R's rule on its relative change
12
12
  // stops while the coefficients, the dispersion and the score statistic can still move by about sqrt(epsilon).
13
13
  import { qnorm } from "../distributions/normal.js";
14
+ import { ldexp } from "../internal/summary.js";
14
15
  import { uniroot } from "../internal/uniroot.js";
15
16
  import { qr, qrResid } from "../linalg/qr.js";
16
- import { glmSummary, refit } from "./glm.js";
17
- import { Warnings } from "./glmFamily.js";
17
+ import { glmSummary, refit, scaledView } from "./glm.js";
18
+ import { unreported, Warnings } from "../internal/warnings.js";
19
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
20
+ import { checkOptions } from "../internal/checkOptions.js";
21
+ const GLM_CONFINT_KEYS = ["parm", "level", "test"];
18
22
  /**
19
23
  * Settings of the fits iterated to convergence: until the coefficients stop changing (at most 100 iterations), and
20
24
  * the tolerance of the QR decomposition that of epsilon = 1e-300 (columns found aliased by the fit are left out)
@@ -35,6 +39,22 @@ export function scoreStatistic(x, r, v, intercept, tol = 1e-11) {
35
39
  sw += v[i];
36
40
  swr += v[i] * r[i];
37
41
  }
42
+ if (intercept && !(Number.isFinite(sw) && Number.isFinite(swr))) {
43
+ // only where the sums overflow (#173): the weights divided by a power of 2 (2^k at most the largest weight)
44
+ let m = 0;
45
+ for (const i of rows)
46
+ m = Math.max(m, v[i]);
47
+ if (Number.isFinite(m)) {
48
+ const k = m > 1 ? Math.floor(Math.log2(m)) : 0;
49
+ sw = 0;
50
+ swr = 0;
51
+ for (const i of rows) {
52
+ const vi = ldexp(v[i], -k);
53
+ sw += vi;
54
+ swr += vi * r[i];
55
+ }
56
+ }
57
+ }
38
58
  const centre = intercept ? swr / sw : 0;
39
59
  let total = 0;
40
60
  for (const i of rows)
@@ -48,6 +68,26 @@ export function scoreStatistic(x, r, v, intercept, tol = 1e-11) {
48
68
  let rss = 0;
49
69
  for (const e of res)
50
70
  rss += e * e;
71
+ if (!Number.isFinite(total)) {
72
+ // only where v (r - centre)^2 overflows (#172): the total from sqrt(v) (r - centre), as the rss, both scaled by a
73
+ // power of 2 when those squares overflow too
74
+ const t = rows.map((i, k) => s[k] * (r[i] - centre));
75
+ let m = 0;
76
+ for (const e of t)
77
+ m = Math.max(m, Math.abs(e));
78
+ for (const e of res)
79
+ m = Math.max(m, Math.abs(e));
80
+ if (Number.isFinite(m)) {
81
+ const k = m > 1 ? Math.floor(Math.log2(m)) : 0;
82
+ let ts = 0;
83
+ for (const e of t)
84
+ ts += ldexp(e, -k) ** 2;
85
+ let rs = 0;
86
+ for (const e of res)
87
+ rs += ldexp(e, -k) ** 2;
88
+ return ldexp(ldexp(ts - rs, k), k);
89
+ }
90
+ }
51
91
  return total - rss;
52
92
  }
53
93
  /**
@@ -64,9 +104,14 @@ export function scoreStatistic(x, r, v, intercept, tol = 1e-11) {
64
104
  *
65
105
  * @category Generalized linear models
66
106
  */
67
- export function glmConfint(fit, options = {}) {
107
+ export function glmConfint(given, options = {}) {
108
+ checkOptions(options, GLM_CONFINT_KEYS, "glmConfint"); // generated: option-keys.mjs
109
+ // on the scaled fit (scaledView); the limits scaled back
110
+ const { fit, k } = scaledView(given);
68
111
  const level = options.level ?? 0.95;
69
112
  const test = options.test ?? "LRT";
113
+ if (test !== "LRT" && test !== "Rao")
114
+ throw new RangeError(`invalid 'test': ${String(test)}`);
70
115
  if (!(level > 0 && level < 1))
71
116
  throw new RangeError("'level' must be in (0, 1)");
72
117
  const p = fit.coefficients.length;
@@ -84,6 +129,12 @@ export function glmConfint(fit, options = {}) {
84
129
  });
85
130
  const B = new Array(p).fill(NaN);
86
131
  cols.forEach((j, k) => (B[j] = full.fit.coefficients[k]));
132
+ // the profile is that of the maximum likelihood fit: without a converged fit there is none (NaN limits)
133
+ if (!full.fit.converged)
134
+ return { lower: parm.map(() => NaN), upper: parm.map(() => NaN) };
135
+ // set when a restricted fit of the profile does not converge: its deviance is not the profile's, so the limit
136
+ // being searched is NaN rather than a root of a wrong function
137
+ let unconverged = false;
87
138
  const convergedFit = {
88
139
  ...fit,
89
140
  coefficients: B,
@@ -92,7 +143,7 @@ export function glmConfint(fit, options = {}) {
92
143
  qr: full.fit.qr,
93
144
  rank: full.fit.rank,
94
145
  };
95
- const summary = glmSummary(convergedFit);
146
+ const summary = unreported(() => glmSummary(convergedFit));
96
147
  const dispersion = summary.dispersion;
97
148
  const se = new Array(p).fill(NaN);
98
149
  const piv = full.fit.qr === undefined ? [] : full.fit.qr.pivot.slice(0, full.fit.rank);
@@ -107,41 +158,82 @@ export function glmConfint(fit, options = {}) {
107
158
  etastart: eta0,
108
159
  extraOffset: model.x.map((r) => r[j] * b),
109
160
  }).fit;
161
+ if (!restricted.converged) {
162
+ unconverged = true;
163
+ return NaN;
164
+ }
110
165
  const stat = test === "LRT"
111
166
  ? restricted.deviance - full.fit.deviance
112
167
  : scoreStatistic(xFull, restricted.workingResiduals, restricted.workingWeights, false);
113
168
  return Math.sign(b - B[j]) * Math.sqrt(Math.max(stat / dispersion, 0));
114
169
  };
115
- const cut = [qnorm((1 - level) / 2), qnorm((1 + level) / 2)];
170
+ // (for alpha below 1e-8 the upper probability itself: 1 - alpha loses its digits and rounds to 1 below 1.1e-16; review 58)
171
+ const a2 = (1 - level) / 2;
172
+ // the cutoff qnorm((1 + level) / 2) for a small level from the series of sqrt(2) erfinv(level) (relative error below 2e-18
173
+ // where it is used: it is below 2^-9 only for level below about 1.6e-3), as 1 + level loses the digits of level
174
+ const cSmall = Math.sqrt(Math.PI / 2) * level * (1 + (Math.PI / 12) * level ** 2 + ((7 * Math.PI ** 2) / 480) * level ** 4);
175
+ // below this cutoff the deviance difference of the profile cannot resolve z (its relative error is about
176
+ // epsilon D / z^2), so the limits come from the inverse profile b(z) interpolated through z = 0, +-C0, +-2 C0 (#179)
177
+ const C0 = 2 ** -9;
178
+ const tiny = cSmall < C0;
179
+ const cut = tiny ? [-cSmall, cSmall] : [qnorm(a2), a2 < 1e-8 ? qnorm(a2, { lowerTail: false }) : qnorm((1 + level) / 2)];
116
180
  const lower = parm.map(() => NaN);
117
181
  const upper = parm.map(() => NaN);
182
+ // the limit of coefficient j where the profile reaches the cutoff c (side 0: below the estimate, c < 0)
183
+ const limitAt = (j, c, side) => {
184
+ const dir = side === 0 ? -1 : 1;
185
+ unconverged = false;
186
+ let far = NaN;
187
+ let zFar = NaN;
188
+ for (let e = 0; e <= 30; e++) {
189
+ const b = B[j] + dir * 2 ** e * se[j];
190
+ const z = zStat(j, b);
191
+ if (Math.abs(z) >= Math.abs(c)) {
192
+ far = b;
193
+ zFar = z;
194
+ break;
195
+ }
196
+ }
197
+ if (Number.isNaN(far) || unconverged)
198
+ return NaN;
199
+ const f = (b) => (b === B[j] ? -c : zStat(j, b) - c);
200
+ const [lo, hi] = side === 0 ? [far, B[j]] : [B[j], far];
201
+ const [fLo, fHi] = side === 0 ? [zFar - c, -c] : [-c, zFar - c];
202
+ let root;
203
+ try {
204
+ root = uniroot(f, lo, hi, { tol: 1e-14 * se[j], maxIter: 500, fLower: fLo, fUpper: fHi });
205
+ }
206
+ catch (err) {
207
+ if (!unconverged)
208
+ throw err;
209
+ root = NaN;
210
+ }
211
+ return unconverged ? NaN : root;
212
+ };
118
213
  parm.forEach((j, k) => {
119
214
  if (Number.isNaN(B[j]))
120
215
  return;
121
- for (const side of [0, 1]) {
122
- const dir = side === 0 ? -1 : 1;
123
- let far = NaN;
124
- let zFar = NaN;
125
- for (let e = 0; e <= 30; e++) {
126
- const b = B[j] + dir * 2 ** e * se[j];
127
- const z = zStat(j, b);
128
- if (Math.abs(z) >= Math.abs(cut[side])) {
129
- far = b;
130
- zFar = z;
131
- break;
132
- }
133
- }
134
- if (Number.isNaN(far))
135
- continue;
136
- const f = (b) => (b === B[j] ? -cut[side] : zStat(j, b) - cut[side]);
137
- const [lo, hi] = side === 0 ? [far, B[j]] : [B[j], far];
138
- const [fLo, fHi] = side === 0 ? [zFar - cut[side], -cut[side]] : [-cut[side], zFar - cut[side]];
139
- const root = uniroot(f, lo, hi, { tol: 1e-14 * se[j], maxIter: 500, fLower: fLo, fUpper: fHi });
140
- if (side === 0)
141
- lower[k] = root;
142
- else
143
- upper[k] = root;
216
+ if (!tiny) {
217
+ lower[k] = limitAt(j, cut[0], 0);
218
+ upper[k] = limitAt(j, cut[1], 1);
219
+ return;
144
220
  }
221
+ // the polynomial of degree 4 through (z, b(z) - b_j) at z = -2 C0, -C0, 0, C0, 2 C0 (Lagrange form)
222
+ const zs = [-2 * C0, -C0, 0, C0, 2 * C0];
223
+ const ds = [limitAt(j, -2 * C0, 0), limitAt(j, -C0, 0), B[j], limitAt(j, C0, 1), limitAt(j, 2 * C0, 1)].map((b) => b - B[j]);
224
+ const at = (z) => {
225
+ let v = 0;
226
+ for (let a = 0; a < 5; a++) {
227
+ let w = 1;
228
+ for (let b = 0; b < 5; b++)
229
+ if (b !== a)
230
+ w *= (z - zs[b]) / (zs[a] - zs[b]);
231
+ v += w * ds[a];
232
+ }
233
+ return B[j] + v;
234
+ };
235
+ lower[k] = at(cut[0]);
236
+ upper[k] = at(cut[1]);
145
237
  });
146
- return { lower, upper };
238
+ return { lower: lower.map((v) => ldexp(v, k)), upper: upper.map((v) => ldexp(v, k)) };
147
239
  }
@@ -1,3 +1,4 @@
1
+ import { type Warnings } from "../internal/warnings.js";
1
2
  /**
2
3
  * Names of the families of R's stats.
3
4
  *
@@ -49,6 +50,14 @@ export interface LinkFunctions {
49
50
  muEta(eta: number): number;
50
51
  /** Whether a linear predictor is in the domain of the inverse link */
51
52
  etaOk(eta: number): boolean;
53
+ /**
54
+ * d mu/d eta = c mu^a for mu > 0 (identity, log, inverse, sqrt, 1/mu^2 and the power links): the working weights
55
+ * and residuals in that form where the direct one overflows or underflows (see irls in glm.ts)
56
+ */
57
+ muPower?: {
58
+ c: number;
59
+ a: number;
60
+ };
52
61
  }
53
62
  /** A family resolved to its functions (the counterpart of R's family object). */
54
63
  export interface Family extends LinkFunctions {
@@ -61,13 +70,9 @@ export interface Family extends LinkFunctions {
61
70
  devContribution(y: number, mu: number, w: number): number;
62
71
  /** Whether the dispersion is fixed at 1 (binomial and poisson) */
63
72
  fixedDispersion: boolean;
73
+ /** The variance function is mu^varPower (gaussian 0, poisson 1, Gamma 2, inverse.gaussian 3 and their quasi) */
74
+ varPower?: number;
64
75
  }
65
- /** Collects warnings in order of first appearance, each once (as the fixtures list R's warnings) */
66
- export declare class Warnings {
67
- readonly list: string[];
68
- add(message: string): void;
69
- }
70
- export declare function withWarnings<T>(sink: Warnings, f: () => T): T;
71
76
  /** Resolves a family name or specification (and a link given separately) to its functions */
72
77
  export declare function makeFamily(family: GlmFamilyName | GlmFamilySpec, link?: GlmLink): Family;
73
78
  /** The response after the family has read it, with the prior weights, the starting means and the binomial sizes */