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