@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
@@ -8,9 +8,26 @@
8
8
  // that aliased columns are found as R finds them; their coefficients are NaN (R's NA).
9
9
  import { pt1 } from "../distributions/t.js";
10
10
  import { pnorm } from "../distributions/normal.js";
11
- import { chol2inv } from "../linalg/chol.js";
11
+ import { chol2invColumns } from "../internal/scaledInverse.js";
12
12
  import { qr, qrCoef, qrQy } from "../linalg/qr.js";
13
- import { familyAic, makeFamily, prepareResponse, Warnings, withWarnings, } from "./glmFamily.js";
13
+ import { familyAic, makeFamily, prepareResponse, } from "./glmFamily.js";
14
+ import { maxOf } from "../internal/extremes.js";
15
+ import { reported, Warnings, withWarnings } from "../internal/warnings.js";
16
+ import { optionalArgs } from "../internal/optionalArgs.js";
17
+ import { ldexp, ldexpWide, scaleToUnit } from "../internal/summary.js";
18
+ import { NON_ESTIMABLE_WARNING, nonEstimableRows } from "./estimable.js";
19
+ import { checkDot, checkedDot } from "../linalg/dot.js";
20
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
21
+ import { checkOptions, nestedOptions } from "../internal/checkOptions.js";
22
+ import { optionsIn } from "../internal/optionalArgs.js";
23
+ const GLM_KEYS = ["family", "link", "weights", "offset", "start", "epsilon", "maxit", "intercept"];
24
+ const GLM_FAMILY_KEYS = ["family", "link", "variance"];
25
+ const GLM_FAMILY_LINK_KEYS = ["power"];
26
+ const GLM_SUMMARY_KEYS = ["dispersion"];
27
+ const GLM_RESIDUALS_KEYS = ["type"];
28
+ const GLM_RSTANDARD_KEYS = ["dispersion"];
29
+ const GLM_COOKS_DISTANCE_KEYS = ["dispersion"];
30
+ const GLM_PREDICT_KEYS = ["newdata", "newoffset", "type", "dispersion"];
14
31
  const EPS = 2 ** -52;
15
32
  function deparseNames(names) {
16
33
  const q = names.map((s) => `"${s}"`);
@@ -26,14 +43,74 @@ function linearPredictor(x, b, offset) {
26
43
  }
27
44
  function totalDeviance(fam, y, mu, w) {
28
45
  let d = 0;
46
+ // an observation of weight 0 adds nothing (its contribution 0 * Inf was NaN for a poisson y of 1e308, as in R)
29
47
  for (let i = 0; i < y.length; i++)
30
- d += fam.devContribution(y[i], mu[i], w[i]);
48
+ if (w[i] !== 0)
49
+ d += fam.devContribution(y[i], mu[i], w[i]);
31
50
  return d;
32
51
  }
52
+ const MIN_NORMAL = 2 ** -1022;
53
+ /** Whether v is 0 or a finite number of the normal range */
54
+ const inRange = (v) => v === 0 || (Math.abs(v) >= MIN_NORMAL && Math.abs(v) < Infinity);
55
+ /**
56
+ * The square root of the working weight, sqrt(w muEta^2 / V(mu)). Where a part of that form (muEta^2, V, w muEta^2) or
57
+ * the result is outside the normal range although the weight is not (a poisson mean beyond 1.34e154 squared muEta to
58
+ * Infinity, an inverse.gaussian V of mu^3 overflowed or underflowed, a muEta of 1e-160 squared to 0: #165-#168), as
59
+ * sqrt(w) |c| mu^((2a - p)/2) from muEta = c mu^a and V = mu^p. Otherwise, and for the links and variances not of
60
+ * that form (the binomial ones), the same bits as R's form. (Not sqrt(w) |muEta| / sqrt(V) for those: a binomial
61
+ * mean at its clamp 1 - 2^-53 has V far above mu (1 - mu) while muEta keeps falling, so that form gave rows at an
62
+ * infinite linear predictor a weight, and the working response Infinity, where R's form gives them the weight 0)
63
+ */
64
+ function sqrtWeight(fam, w, me, mu) {
65
+ const v = fam.variance(mu);
66
+ const me2 = me ** 2;
67
+ const s = Math.sqrt((w * me2) / v);
68
+ if (s > 0 && s < Infinity && inRange(me2) && me2 !== 0 && inRange(v) && v !== 0 && inRange(w * me2))
69
+ return s;
70
+ if (fam.muPower !== undefined && fam.varPower !== undefined && mu > 0) {
71
+ const { c, a } = fam.muPower;
72
+ return Math.sqrt(w) * Math.abs(c) * mu ** ((2 * a - fam.varPower) / 2);
73
+ }
74
+ return s;
75
+ }
76
+ /**
77
+ * The working residual (y - mu) / muEta; where muEta is not finite or below the normal range (the inverse link's
78
+ * -1/eta^2 overflowed for a Gamma mean of 1e308, #159), as ((y - mu)/c)/mu^(a/2)/mu^(a/2) from muEta = c mu^a
79
+ */
80
+ function workingResidual(fam, y, mu, me) {
81
+ const r = (y - mu) / me;
82
+ if (Math.abs(me) >= MIN_NORMAL && Math.abs(me) < Infinity)
83
+ return r;
84
+ if (fam.muPower !== undefined && mu > 0) {
85
+ const { c, a } = fam.muPower;
86
+ const h = mu ** (a / 2);
87
+ return (y - mu) / c / h / h;
88
+ }
89
+ return r;
90
+ }
91
+ /**
92
+ * The Pearson residual (y - mu) sqrt(w) / sqrt(V(mu)); where V is outside the normal range or the result is not finite,
93
+ * as ((y - mu)/h) sqrt(w)/h with h = mu^(p/4) from V = mu^p
94
+ */
95
+ function pearsonResidual(fam, y, mu, w) {
96
+ const v = fam.variance(mu);
97
+ const r = ((y - mu) * Math.sqrt(w)) / Math.sqrt(v);
98
+ if ((Number.isFinite(r) && inRange(v) && v !== 0) || fam.varPower === undefined || !(mu > 0))
99
+ return r;
100
+ const h = mu ** (fam.varPower / 4);
101
+ return (((y - mu) / h) * Math.sqrt(w)) / h;
102
+ }
33
103
  /** Iteratively reweighted least squares (glm-behaviour.md, "Fitting") */
104
+ /** The change of the linear predictor in the last iteration above which a converged fit is reported separated */
105
+ const SEPARATION_STEP = 0.1;
34
106
  export function irls(inp, warnings) {
35
107
  const { x, p, y, w, offset, fam, epsilon, maxit } = inp;
36
108
  const n = y.length;
109
+ // As R, whose least-squares step (C_Cdqrls) stops on a non-finite value among the rows of positive weight
110
+ if (y.some((v, i) => w[i] > 0 && !Number.isFinite(v)))
111
+ throw new RangeError("NA/NaN/Inf in 'y'");
112
+ if (x.some((r, i) => w[i] > 0 && r.some((v) => !Number.isFinite(v))))
113
+ throw new RangeError("NA/NaN/Inf in 'x'");
37
114
  return withWarnings(warnings, () => {
38
115
  const allOk = (eta, mu) => eta.every((e) => fam.etaOk(e)) && mu.every((m) => fam.muOk(m));
39
116
  if (p === 0) {
@@ -45,7 +122,7 @@ export function irls(inp, warnings) {
45
122
  if (!mu.every((m) => fam.muOk(m)))
46
123
  throw new Error("invalid fitted means in empty model");
47
124
  const me = eta.map((e) => fam.muEta(e));
48
- const ww = mu.map((m, i) => Math.sqrt((w[i] * me[i] ** 2) / fam.variance(m)) ** 2);
125
+ const ww = mu.map((m, i) => sqrtWeight(fam, w[i], me[i], m) ** 2);
49
126
  return {
50
127
  coefficients: [],
51
128
  eta,
@@ -60,7 +137,7 @@ export function irls(inp, warnings) {
60
137
  qr: undefined,
61
138
  used: w.map((v) => v > 0),
62
139
  workingWeights: ww,
63
- workingResiduals: y.map((v, i) => (v - mu[i]) / me[i]),
140
+ workingResiduals: y.map((v, i) => workingResidual(fam, v, mu[i], me[i])),
64
141
  };
65
142
  }
66
143
  let eta;
@@ -88,6 +165,7 @@ export function irls(inp, warnings) {
88
165
  let q;
89
166
  let used = w.map(() => false);
90
167
  let sqrtW = [];
168
+ const recent = [];
91
169
  const tol = Math.min(1e-7, epsilon / 1000);
92
170
  for (iter = 1; iter <= maxit; iter++) {
93
171
  const me = eta.map((e) => fam.muEta(e));
@@ -97,7 +175,8 @@ export function irls(inp, warnings) {
97
175
  const v = fam.variance(mu[i]);
98
176
  if (Number.isNaN(v))
99
177
  throw new Error("NAs in V(mu)");
100
- if (v === 0)
178
+ // (not where V = mu^p underflowed for a positive mean: an inverse.gaussian mean of 1e-200, #166)
179
+ if (v === 0 && !(fam.varPower !== undefined && mu[i] > 0))
101
180
  throw new Error("0s in V(mu)");
102
181
  if (Number.isNaN(me[i]))
103
182
  throw new Error("NAs in d(mu)/d(eta)");
@@ -116,9 +195,9 @@ export function irls(inp, warnings) {
116
195
  const zw = [];
117
196
  const xw = [];
118
197
  for (const i of rows) {
119
- const s = Math.sqrt((w[i] * me[i] ** 2) / fam.variance(mu[i]));
198
+ const s = sqrtWeight(fam, w[i], me[i], mu[i]);
120
199
  sqrtW[i] = s;
121
- zw.push(((eta[i] - offset[i]) + (y[i] - mu[i]) / me[i]) * s);
200
+ zw.push(((eta[i] - offset[i]) + workingResidual(fam, y[i], mu[i], me[i])) * s);
122
201
  xw.push(x[i].map((v) => v * s));
123
202
  }
124
203
  q = qr(xw, { tol });
@@ -130,6 +209,7 @@ export function irls(inp, warnings) {
130
209
  }
131
210
  coef = b.map((v) => (Number.isNaN(v) ? 0 : v));
132
211
  boundary = false;
212
+ const etaBefore = eta;
133
213
  eta = linearPredictor(x, coef, offset);
134
214
  mu = eta.map((e) => fam.linkinv(e));
135
215
  dev = totalDeviance(fam, y, mu, w);
@@ -165,15 +245,57 @@ export function irls(inp, warnings) {
165
245
  boundary = true;
166
246
  dev = totalDeviance(fam, y, mu, w);
167
247
  }
248
+ // A step that increases the deviance is halved until it does not, as glm2's glm.fit2 (R's glm.fit accepts it:
249
+ // binomial with weights 1000 went from 7564 to 89255 and stopped at 144175 with coefficients of 1e15,
250
+ // "converged", where the maximum is 4956)
251
+ // (an increase of 1e-10 at least: with a tiny epsilon, as the profiles of glmConfint iterate, rounding of the
252
+ // deviance near the maximum is no increase to correct)
253
+ const rise = Math.max(epsilon, 1e-10);
254
+ if (previous !== undefined && iter > 1 && (dev - devPrevious) / (0.1 + Math.abs(dev)) >= rise) {
255
+ warnings.add("step size truncated due to increasing deviance");
256
+ let halvings = 0;
257
+ while ((dev - devPrevious) / (0.1 + Math.abs(dev)) >= rise && halvings < maxit) {
258
+ halvings++;
259
+ coef = coef.map((v, j) => (v + previous[j]) / 2);
260
+ eta = linearPredictor(x, coef, offset);
261
+ mu = eta.map((e) => fam.linkinv(e));
262
+ dev = totalDeviance(fam, y, mu, w);
263
+ }
264
+ if ((dev - devPrevious) / (0.1 + Math.abs(dev)) >= rise) {
265
+ warnings.add("inner loop 3; cannot correct step size");
266
+ converged = false;
267
+ break;
268
+ }
269
+ }
168
270
  if (inp.untilCoefficients) {
169
- const scale = Math.max(...coef.map(Math.abs));
271
+ const scale = maxOf(coef.map(Math.abs));
170
272
  if (previous !== undefined && coef.every((v, j) => Math.abs(v - previous[j]) <= 8 * EPS * scale)) {
171
273
  converged = true;
172
274
  break;
173
275
  }
276
+ // back to one of the last 16 iterates: a cycle in the last bits (of 2 to 5 iterates seen; rounding of the
277
+ // working response, far larger than 8 eps times a coefficient near 0), as close to the maximum as the doubles
278
+ // go (the profiles of glmConfint went to maxit, unconverged, and gave a NaN limit; review 66)
279
+ if (recent.some((r) => r.every((v, j) => v === coef[j]))) {
280
+ converged = true;
281
+ break;
282
+ }
283
+ recent.push(coef.slice());
284
+ if (recent.length > 16)
285
+ recent.shift();
174
286
  }
175
287
  else if (Math.abs(dev - devPrevious) / (Math.abs(dev) + 0.1) < epsilon) {
176
288
  converged = true;
289
+ // The deviance settles while the linear predictor still moves by about 1 per iteration when the data are
290
+ // separated (R reports such fits converged, with finite coefficients that only depend on maxit and epsilon).
291
+ // At a maximum the last step is far smaller; eta has no units, so the test does not depend on those of x
292
+ let moved = 0;
293
+ for (let i = 0; i < n; i++)
294
+ if (used[i])
295
+ moved = Math.max(moved, Math.abs(eta[i] - etaBefore[i]));
296
+ if (moved > SEPARATION_STEP) {
297
+ warnings.add("glm.fit: the linear predictor was still changing at convergence: the data may be separated (no finite maximum likelihood estimates)");
298
+ }
177
299
  break;
178
300
  }
179
301
  devPrevious = dev;
@@ -201,7 +323,7 @@ export function irls(inp, warnings) {
201
323
  qr: q,
202
324
  used,
203
325
  workingWeights: sqrtW.map((s) => s * s),
204
- workingResiduals: y.map((v, i) => (v - mu[i]) / me[i]),
326
+ workingResiduals: y.map((v, i) => workingResidual(fam, v, mu[i], me[i])),
205
327
  };
206
328
  });
207
329
  }
@@ -227,6 +349,10 @@ export function refit(model, cols, warnings, control = {}) {
227
349
  const fam = makeFamily(model.familySpec);
228
350
  const start = "start" in control ? control.start : model.start;
229
351
  const prep = prepareResponse(fam, model.yGiven, model.priorGiven, start !== undefined || control.etastart !== undefined, warnings);
352
+ // no observation carries information (R stops with an internal error); the fit came out with rank p and negative
353
+ // residual degrees of freedom
354
+ if (!prep.weights.some((w) => w > 0))
355
+ throw new RangeError("all weights are zero");
230
356
  const offset = control.extraOffset === undefined ? model.offset : model.offset.map((o, i) => o + control.extraOffset[i]);
231
357
  const x = model.x.map((r) => cols.map((j) => r[j]));
232
358
  const fit = irls({
@@ -268,8 +394,15 @@ export function refit(model, cols, warnings, control = {}) {
268
394
  * @category Generalized linear models
269
395
  */
270
396
  export function glm(x, y, options = {}) {
397
+ checkOptions(options, GLM_KEYS, "glm"); // generated: option-keys.mjs
398
+ checkOptions(nestedOptions(options, "family"), GLM_FAMILY_KEYS, "glm", "family"); // generated: option-keys.mjs
399
+ checkOptions(nestedOptions(options, "family.link"), GLM_FAMILY_LINK_KEYS, "glm", "family.link"); // generated: option-keys.mjs
400
+ checkOptions(nestedOptions(options, "link"), GLM_FAMILY_LINK_KEYS, "glm", "link"); // generated: option-keys.mjs
271
401
  const intercept = options.intercept ?? true;
272
402
  const xr = toRows(x);
403
+ // the shape of all the rows given, before the rows with a missing value are dropped (#463)
404
+ if (xr.some((r) => r.length !== xr[0].length))
405
+ throw new TypeError("all rows of x must have the same length");
273
406
  const yIsMatrix = y.length > 0 && typeof y[0] !== "number";
274
407
  const yr = yIsMatrix ? y.map((r) => Array.from(r)) : Array.from(y);
275
408
  const nAll = yr.length;
@@ -294,12 +427,16 @@ export function glm(x, y, options = {}) {
294
427
  const priorGiven = wGiven === undefined ? new Array(n).fill(1) : wGiven.filter((_, i) => keep[i]);
295
428
  if (priorGiven.some((v) => v < 0))
296
429
  throw new RangeError("negative weights not allowed");
430
+ // (R: "NA/NaN/Inf in 'x'" from the weighted least squares step; here the error of the QR on a matrix with Inf)
431
+ if (priorGiven.some((v) => !Number.isFinite(v)))
432
+ throw new RangeError("non-finite weights not allowed");
297
433
  const offset = oGiven === undefined ? new Array(n).fill(0) : oGiven.filter((_, i) => keep[i]);
434
+ // as R ("NA/NaN/Inf in 'y'" there, from the working response); an infinite offset gave coefficients of 0
435
+ if (offset.some((v) => !Number.isFinite(v)))
436
+ throw new RangeError("the offset must be finite");
298
437
  const nx = xr.length > 0 ? xr[0].length : 0;
299
438
  const columnNames = [...(intercept ? ["(Intercept)"] : []), ...Array.from({ length: nx }, (_, j) => `x${j + 1}`)];
300
439
  const p = columnNames.length;
301
- if (X.some((r) => r.length !== p))
302
- throw new TypeError("all rows of x must have the same length");
303
440
  const familySpec = typeof options.family === "object" ? { ...options.family } : { family: options.family ?? "gaussian" };
304
441
  if (options.link !== undefined)
305
442
  familySpec.link = options.link;
@@ -313,13 +450,33 @@ export function glm(x, y, options = {}) {
313
450
  intercept,
314
451
  familySpec,
315
452
  epsilon: options.epsilon ?? 1e-8,
316
- maxit: options.maxit ?? 25,
453
+ // R loops over 1:maxit, so a fractional maxit runs (and reports) its integer part
454
+ maxit: Math.floor(options.maxit ?? 25),
317
455
  start: options.start === undefined ? undefined : Array.from(options.start),
318
456
  };
319
- if (!(model.epsilon > 0))
320
- throw new RangeError("value of 'epsilon' must be > 0");
321
- if (!(model.maxit > 0))
457
+ if (!(model.epsilon > 0 && model.epsilon < Infinity))
458
+ throw new RangeError("value of 'epsilon' must be > 0 and finite");
459
+ if (!(model.maxit > 0 && model.maxit < Infinity))
322
460
  throw new RangeError("maximum number of iterations must be > 0");
461
+ // gaussian (and quasi with constant variance) on the identity link: fitted to the response scaled by a power of 2
462
+ // (exact; src/internal/summary.ts), so that the deviance stays in range; see scaledView
463
+ const k = !yIsMatrix && scalesWithResponse(familySpec) ? scaleToUnit([yGiven]).k : 0;
464
+ if (k === 0)
465
+ return reported("glm", fitModel(model));
466
+ const down = (v) => ldexp(v, -k);
467
+ const scaled = fitModel({
468
+ ...model,
469
+ yGiven: yGiven.map(down),
470
+ offset: offset.map(down),
471
+ start: model.start?.map(down),
472
+ });
473
+ return reported("glm", unscaledResult(scaled, k, { ...model, yScale: k }));
474
+ }
475
+ /** The fit of a model (the part of glm after its checks) */
476
+ function fitModel(model) {
477
+ const { x: X, offset, intercept } = model;
478
+ const n = X.length;
479
+ const p = model.columnNames.length;
323
480
  const warnings = new Warnings();
324
481
  const all = Array.from({ length: p }, (_, j) => j);
325
482
  const { fit, fam, y: yy, w, size } = refit(model, all, warnings);
@@ -335,20 +492,40 @@ export function glm(x, y, options = {}) {
335
492
  warnings.add("fitting to calculate the null deviance did not converge -- increase 'maxit'?");
336
493
  }
337
494
  else if (intercept) {
495
+ // the weights divided by a power of 2 (the mean unchanged; their sum overflowed for weights of 1e308), and rows of
496
+ // weight 0 left out (0 times an infinite response was NaN); R gave NaN for both
497
+ const kw = Math.floor(Math.log2(maxOf(w)));
338
498
  let sw = 0;
339
499
  let swy = 0;
340
500
  for (let i = 0; i < n; i++) {
341
- sw += w[i];
342
- swy += w[i] * yy[i];
501
+ if (!(w[i] > 0))
502
+ continue;
503
+ const wi = ldexp(w[i], -kw);
504
+ sw += wi;
505
+ swy += wi * yy[i];
506
+ }
507
+ let m = swy / sw;
508
+ if (!Number.isFinite(m)) {
509
+ // the weighted sum of the response overflowed (a poisson response of 1e308, #168): with the response divided by a
510
+ // power of 2 as well
511
+ let ymax = 0;
512
+ for (let i = 0; i < n; i++)
513
+ if (w[i] > 0)
514
+ ymax = Math.max(ymax, Math.abs(yy[i]));
515
+ const ky = Math.floor(Math.log2(ymax));
516
+ let swy2 = 0;
517
+ for (let i = 0; i < n; i++)
518
+ if (w[i] > 0)
519
+ swy2 += ldexp(w[i], -kw) * ldexp(yy[i], -ky);
520
+ m = ldexp(swy2 / sw, ky);
343
521
  }
344
- const m = swy / sw;
345
522
  nullDeviance = withWarnings(warnings, () => totalDeviance(fam, yy, yy.map(() => m), w));
346
523
  }
347
524
  else
348
525
  nullDeviance = withWarnings(warnings, () => totalDeviance(fam, yy, offset.map((o) => fam.linkinv(o)), w));
349
526
  const nOk = n - w.filter((v) => v === 0).length;
350
527
  const aic = familyAic(fam, yy, fit.mu, w, size, fit.deviance, warnings) + 2 * fit.rank;
351
- return {
528
+ return withUsedRows(fit.used, {
352
529
  coefficients: fit.coefficients,
353
530
  fittedValues: fit.mu,
354
531
  linearPredictors: fit.eta,
@@ -370,7 +547,57 @@ export function glm(x, y, options = {}) {
370
547
  warnings: warnings.list,
371
548
  qr: fit.qr,
372
549
  model,
550
+ });
551
+ }
552
+ /** Whether the family's fit scales with the response: gaussian, or quasi with constant variance, on the identity link */
553
+ function scalesWithResponse(spec) {
554
+ const link = spec.link ?? "identity";
555
+ if (link !== "identity")
556
+ return false;
557
+ return spec.family === "gaussian" || (spec.family === "quasi" && (spec.variance ?? "constant") === "constant");
558
+ }
559
+ /**
560
+ * The fit of the response in its own units from the fit of the response scaled by 2^-k: coefficients, means, linear
561
+ * predictors, the response and the working residuals times 2^k, deviances times 2^2k, and the gaussian AIC
562
+ * (n log(deviance / n) + ...) plus 2 n k log 2. The scaled fit stays with it (not enumerable), for scaledView
563
+ */
564
+ function unscaledResult(scaled, k, model) {
565
+ const up = (v) => ldexp(v, k);
566
+ const out = {
567
+ ...scaled,
568
+ coefficients: scaled.coefficients.map(up),
569
+ fittedValues: scaled.fittedValues.map(up),
570
+ linearPredictors: scaled.linearPredictors.map(up),
571
+ deviance: ldexp(scaled.deviance, 2 * k),
572
+ nullDeviance: ldexp(scaled.nullDeviance, 2 * k),
573
+ // (n log of the deviance scaled by 2^-2k, n the rows of positive weight as in familyAic)
574
+ aic: scaled.aic + 2 * scaled.priorWeights.filter((v) => v > 0).length * k * Math.LN2,
575
+ y: scaled.y.map(up),
576
+ residuals: scaled.residuals.map(up),
577
+ model,
373
578
  };
579
+ Object.defineProperty(out, "scaled", { value: scaled, enumerable: false });
580
+ return withUsedRows(USED_ROWS.get(scaled), out);
581
+ }
582
+ /**
583
+ * The rows of the last least squares step of a fit (irls's used): its working weights, squares of the square roots
584
+ * that went into the QR, may underflow to 0 for a row in it, so they do not tell (the hat values of the rows after it
585
+ * were shifted by one)
586
+ */
587
+ const USED_ROWS = new WeakMap();
588
+ function withUsedRows(used, fit) {
589
+ if (used !== undefined)
590
+ USED_ROWS.set(fit, used);
591
+ return fit;
592
+ }
593
+ /**
594
+ * The fit to compute with and its scale k: for a fit of a response scaled by 2^-k (see glm), that scaled fit, whose
595
+ * quantities with units are 2^-k (or 2^-2k) times the fit's; otherwise the fit itself with k = 0. The functions on a
596
+ * fit compute on it (statistics without units unchanged) and scale back only what has units
597
+ */
598
+ export function scaledView(fit) {
599
+ const scaled = fit.scaled;
600
+ return scaled === undefined ? { fit, k: 0 } : { fit: scaled, k: fit.model.yScale ?? 0 };
374
601
  }
375
602
  /** The family object of a fit */
376
603
  export function familyOf(fit) {
@@ -378,6 +605,12 @@ export function familyOf(fit) {
378
605
  }
379
606
  /** Pearson dispersion of summary.glm (1 for binomial and poisson) */
380
607
  export function glmDispersion(fit, warnings) {
608
+ const v = scaledView(fit);
609
+ const d = dispersionOf(v.fit, warnings);
610
+ return familyOf(fit).fixedDispersion ? d : ldexp(d, 2 * v.k);
611
+ }
612
+ /** The dispersion of a fit in its own units (of the scaled fit for a scaled view) */
613
+ function dispersionOf(fit, warnings) {
381
614
  if (familyOf(fit).fixedDispersion)
382
615
  return 1;
383
616
  if (fit.dfResidual <= 0)
@@ -388,14 +621,61 @@ export function glmDispersion(fit, warnings) {
388
621
  s += fit.weights[i] * fit.residuals[i] ** 2;
389
622
  if (fit.weights.some((v) => v === 0))
390
623
  warnings?.add("observations with zero weight not used for calculating dispersion");
624
+ if (s === Infinity)
625
+ return scaledPearsonMean(fit);
391
626
  return s / fit.dfResidual;
392
627
  }
393
- /** (R'R)^-1 of the leading rank x rank block of the last QR, in pivot order */
628
+ /**
629
+ * sum W r^2 / dfResidual where the plain sum overflows: each term as (sqrt(W) r)^2 with the residuals and then the
630
+ * products divided by powers of 2 (2^-kr, 2^-kb), so that the sum stays in range, and the exponents added back after
631
+ * the division (#176). Terms below 2^-1074 of the largest are lost, which cannot matter next to a sum beyond the
632
+ * double range
633
+ */
634
+ function scaledPearsonMean(fit) {
635
+ const rows = [];
636
+ for (let i = 0; i < fit.weights.length; i++)
637
+ if (fit.weights[i] > 0)
638
+ rows.push(i);
639
+ if (!rows.every((i) => Number.isFinite(fit.weights[i]) && Number.isFinite(fit.residuals[i])))
640
+ return Infinity;
641
+ const r = scaleToUnit([rows.map((i) => fit.residuals[i])]);
642
+ const b = scaleToUnit([rows.map((i, j) => Math.sqrt(fit.weights[i]) * Math.abs(r.groups[0][j]))]);
643
+ let s = 0;
644
+ for (const v of b.groups[0])
645
+ s += v * v;
646
+ return ldexp(s / fit.dfResidual, 2 * (r.k + b.k));
647
+ }
648
+ /**
649
+ * (R'R)^-1 of the leading rank x rank block of the last QR, in pivot order, as inv_jk 2^(-e_j - e_k) (columns far from
650
+ * 1 divided by powers of 2 first: chol2invColumns)
651
+ */
394
652
  function unscaledCovariance(fit) {
395
653
  if (fit.qr === undefined || fit.rank === 0)
396
- return [];
397
- const Rr = fit.qr.qr.slice(0, fit.rank).map((row) => row.slice(0, fit.rank));
398
- return chol2inv(Rr);
654
+ return { inv: [], e: [] };
655
+ return chol2invColumns(fit.qr.qr.slice(0, fit.rank).map((row) => row.slice(0, fit.rank)));
656
+ }
657
+ /**
658
+ * A dispersion given by the user: a non-negative finite number (a negative one gave NaN standard errors, as R's with a
659
+ * warning; 0 gives standard errors of 0, as R)
660
+ */
661
+ export function checkDispersion(d) {
662
+ if (!(d >= 0 && d < Infinity))
663
+ throw new RangeError("'dispersion' must be a non-negative finite number");
664
+ return d;
665
+ }
666
+ /**
667
+ * A dispersion d given by the user, in the units of a fit computed on the response scaled by 2^-k (scaledView), as
668
+ * m 4^s: d 2^-2k with s = 0 where that is 0 or in the normal range (the old value, the same bits); where it underflows
669
+ * or overflows although d does not (k = 1023 for a response of 1e308, where d = 1 gave 0 and standard errors 0,
670
+ * #349), m is d brought to [1, 4) by an even power of 2, 4^h, and s = h - k, for the callers to apply 2^s and 4^s
671
+ * where the result is in range
672
+ */
673
+ export function scaledDispersion(d, k) {
674
+ const v = ldexp(checkDispersion(d), -2 * k);
675
+ if (v === 0 ? d === 0 : v >= 2 ** -1022 && v < Infinity)
676
+ return { m: v, s: 0 };
677
+ const h = Math.floor(Math.floor(Math.log2(d)) / 2);
678
+ return { m: ldexp(d, -2 * h), s: h - k };
399
679
  }
400
680
  /**
401
681
  * Summary of a generalized linear model: the dispersion, the coefficient table and the covariance of the estimates,
@@ -412,49 +692,59 @@ function unscaledCovariance(fit) {
412
692
  *
413
693
  * @category Generalized linear models
414
694
  */
415
- export function glmSummary(fit, options = {}) {
695
+ export function glmSummary(given, options = {}) {
696
+ checkOptions(options, GLM_SUMMARY_KEYS, "glmSummary"); // generated: option-keys.mjs
697
+ // computed on the scaled fit (scaledView); estimates, standard errors and the dispersion scaled back
698
+ const { fit, k } = scaledView(given);
416
699
  const warnings = new Warnings();
417
700
  const fam = familyOf(fit);
418
701
  const estimated = options.dispersion === undefined && !fam.fixedDispersion;
419
- const dispersion = options.dispersion ?? glmDispersion(fit, warnings);
420
- const covUnscaled = unscaledCovariance(fit);
702
+ const user = options.dispersion === undefined ? undefined : scaledDispersion(options.dispersion, k);
703
+ const dispersion = user === undefined ? dispersionOf(fit, warnings) : user.m;
704
+ // (a given dispersion is m 4^s; s != 0 only where its scaled value is out of range, #349)
705
+ const s = user?.s ?? 0;
706
+ const { inv, e } = unscaledCovariance(fit);
707
+ // (Infinity or 0 where the covariance itself is out of range; the standard errors scale back from the scaled columns)
708
+ const covUnscaled = inv.map((r, j) => r.map((v, k) => ldexp(v, -e[j] - e[k])));
421
709
  const piv = fit.qr === undefined ? [] : fit.qr.pivot.slice(0, fit.rank);
422
710
  const estimate = piv.map((j) => fit.coefficients[j]);
423
- const stdError = covUnscaled.map((r, k) => Math.sqrt(r[k] * dispersion));
424
- const statistic = estimate.map((e, k) => e / stdError[k]);
711
+ const stdError = inv.map((r, k) => ldexp(Math.sqrt(r[k] * dispersion), -e[k]));
712
+ const statistic = s === 0
713
+ ? estimate.map((e, k) => e / stdError[k])
714
+ : estimate.map((b, j) => ldexpWide(b / Math.sqrt(inv[j][j] * dispersion), e[j] - s));
425
715
  const zTest = !estimated;
426
716
  const pValue = statistic.map((t) => zTest ? 2 * pnorm(-Math.abs(t)) : fit.dfResidual > 0 ? 2 * pt1(-Math.abs(t), fit.dfResidual, true, false) : NaN);
427
717
  if (estimated && fit.dfResidual === 0) {
428
718
  stdError.fill(NaN);
429
719
  statistic.fill(NaN);
430
720
  }
431
- return {
432
- dispersion,
433
- estimate,
434
- stdError,
721
+ const up = (v) => ldexp(v, k);
722
+ const up2 = (v) => ldexp(v, 2 * k);
723
+ return reported("glmSummary", {
724
+ dispersion: s === 0 ? up2(dispersion) : options.dispersion,
725
+ estimate: estimate.map(up),
726
+ // (with s != 0 in the original units at once: sqrt(inv m) 2^(s + k - e))
727
+ stdError: s === 0 ? stdError.map(up) : inv.map((r, j) => ldexpWide(Math.sqrt(r[j] * dispersion), s + k - e[j])),
435
728
  statistic,
436
729
  pValue,
437
- statisticName: fam.fixedDispersion ? "z value" : "t value",
730
+ // (z whenever the dispersion is not estimated, as R: a given dispersion was named "t value")
731
+ statisticName: zTest ? "z value" : "t value",
438
732
  covUnscaled,
439
- covScaled: covUnscaled.map((r) => r.map((v) => v * dispersion)),
733
+ covScaled: s === 0
734
+ ? covUnscaled.map((r) => r.map((v) => up2(v * dispersion)))
735
+ : inv.map((r, j) => r.map((v, l) => ldexpWide(v * dispersion, 2 * (s + k) - e[j] - e[l]))),
440
736
  dfResidual: fit.dfResidual,
441
737
  warnings: warnings.list,
442
- };
738
+ }, given);
443
739
  }
444
- /**
445
- * Residuals of a generalized linear model, one per row, for a `glm` fit (default `"deviance"`). Equivalent to R's
446
- * `residuals(fit, type)`.
447
- *
448
- * @example
449
- * ```ts
450
- * const fit = glm([1, 2, 3, 4, 5, 6], [0, 0, 1, 0, 1, 1], { family: "binomial" });
451
- * glmResiduals(fit); // [-0.30644, -0.54776, 1.4436, -1.4436, 0.54776, 0.30644]
452
- * glmResiduals(fit, "pearson"); // [-0.21925, -0.40231, 1.3546, -1.3546, 0.40231, 0.21925]
453
- * ```
454
- *
455
- * @category Generalized linear models
456
- */
457
- export function glmResiduals(fit, type = "deviance") {
740
+ export function glmResiduals(fit, ...args) {
741
+ checkOptions(optionsIn(args), GLM_RESIDUALS_KEYS, "glmResiduals"); // generated: option-keys.mjs
742
+ const type = optionalArgs(["type"], args).type ?? "deviance";
743
+ // of the scaled fit (scaledView), scaled back: for the families that are scaled, every kind has the response's units
744
+ const v = scaledView(fit);
745
+ return residualsOf(v.fit, type).map((r) => ldexp(r, v.k));
746
+ }
747
+ function residualsOf(fit, type) {
458
748
  const fam = familyOf(fit);
459
749
  const { y, fittedValues: mu, priorWeights: w } = fit;
460
750
  switch (type) {
@@ -463,11 +753,11 @@ export function glmResiduals(fit, type = "deviance") {
463
753
  case "working":
464
754
  return fit.residuals.slice();
465
755
  case "pearson":
466
- return y.map((v, i) => ((v - mu[i]) * Math.sqrt(w[i])) / Math.sqrt(fam.variance(mu[i])));
756
+ return y.map((v, i) => pearsonResidual(fam, v, mu[i], w[i]));
467
757
  case "deviance":
468
- if (fit.dfResidual <= 0)
469
- return y.map(() => 0);
470
- return y.map((v, i) => Math.sign(v - mu[i]) * Math.sqrt(Math.max(fam.devContribution(v, mu[i], w[i]), 0)));
758
+ // from each row's contribution also without residual degrees of freedom (R's residuals.glm gives 0 there, even
759
+ // for a fit that has not converged: deviance 0.34 with residuals 0); their squares sum to the deviance
760
+ return y.map((v, i) => w[i] === 0 ? 0 : Math.sign(v - mu[i]) * Math.sqrt(Math.max(fam.devContribution(v, mu[i], w[i]), 0)));
471
761
  default:
472
762
  throw new RangeError(`unknown type of residuals "${String(type)}"`);
473
763
  }
@@ -496,7 +786,7 @@ export function glmHatvalues(fit) {
496
786
  }
497
787
  // rows of the last least squares step, in order
498
788
  let k = 0;
499
- const usedRows = fit.weights.map((v) => v > 0);
789
+ const usedRows = USED_ROWS.get(fit) ?? fit.weights.map((v) => v > 0);
500
790
  fit.priorWeights.forEach((w, i) => {
501
791
  const hi = usedRows[i] ? (h[k++] ?? 0) : 0;
502
792
  if (w > 0)
@@ -521,13 +811,18 @@ function median(v) {
521
811
  *
522
812
  * @category Generalized linear models
523
813
  */
524
- export function glmRstandard(fit, options = {}) {
814
+ export function glmRstandard(given, options = {}) {
815
+ checkOptions(options, GLM_RSTANDARD_KEYS, "glmRstandard"); // generated: option-keys.mjs
816
+ // on the scaled fit (scaledView): the standardized residuals have no units
817
+ const { fit, k } = scaledView(given);
525
818
  const h = glmHatvalues(fit);
526
- const disp = options.dispersion ?? glmDispersion(fit);
527
- const r = glmResiduals(fit, "deviance").filter((_, i) => fit.priorWeights[i] > 0);
528
- const small = 100 * EPS * median(r.map(Math.abs));
819
+ // (a given dispersion is m 4^s, s != 0 only where its scaled value is out of range, #349)
820
+ const { m: disp, s: shift } = options.dispersion === undefined ? { m: dispersionOf(fit), s: 0 } : scaledDispersion(options.dispersion, k);
821
+ const r = residualsOf(fit, "deviance").filter((_, i) => fit.priorWeights[i] > 0);
822
+ // residuals below 100 eps times their median are taken as 0 only with columns, as R's lm.influence (rank 0 keeps them)
823
+ const small = fit.rank > 0 ? 100 * EPS * median(r.map(Math.abs)) : 0;
529
824
  return r.map((v, i) => {
530
- const s = (Math.abs(v) < small ? 0 : v) / Math.sqrt(disp * (1 - h[i]));
825
+ const s = ldexpWide((Math.abs(v) < small ? 0 : v) / Math.sqrt(disp * (1 - h[i])), -shift);
531
826
  return Number.isFinite(s) ? s : NaN;
532
827
  });
533
828
  }
@@ -542,15 +837,39 @@ export function glmRstandard(fit, options = {}) {
542
837
  *
543
838
  * @category Generalized linear models
544
839
  */
545
- export function glmCooksDistance(fit, options = {}) {
840
+ export function glmCooksDistance(given, options = {}) {
841
+ checkOptions(options, GLM_COOKS_DISTANCE_KEYS, "glmCooksDistance"); // generated: option-keys.mjs
842
+ // on the scaled fit (scaledView): Cook's distances have no units
843
+ const { fit, k } = scaledView(given);
546
844
  const h = glmHatvalues(fit);
547
- const disp = options.dispersion ?? glmDispersion(fit);
548
- const r = glmResiduals(fit, "pearson").filter((_, i) => fit.priorWeights[i] > 0);
845
+ // (a given dispersion is m 4^s, s != 0 only where its scaled value is out of range, #349)
846
+ const { m: disp, s: shift } = options.dispersion === undefined ? { m: dispersionOf(fit), s: 0 } : scaledDispersion(options.dispersion, k);
847
+ const r = residualsOf(fit, "pearson").filter((_, i) => fit.priorWeights[i] > 0);
549
848
  return r.map((v, i) => {
550
- const c = (v / (1 - h[i])) ** 2 * (h[i] / (disp * fit.rank));
849
+ const q = h[i] / (disp * fit.rank);
850
+ let c = (v / (1 - h[i])) ** 2 * q;
851
+ // Where the square overflows, or h/(dispersion p) falls below the normal range (a large dispersion), with the residual
852
+ // and the dispersion in units of powers of 2 (cookScaled). Otherwise the same bits as before
853
+ if (!Number.isFinite(c) || q < 2 ** -1022)
854
+ c = cookScaled(v, h[i], disp, fit.rank);
855
+ if (shift !== 0)
856
+ c = ldexpWide(c, -2 * shift);
551
857
  return Number.isFinite(c) ? c : NaN;
552
858
  });
553
859
  }
860
+ /**
861
+ * Cook's distance (r/(1 - h))^2 h/(d p) with r = 2^er r' and d = 2^ed d' (r', d' in [1, 2)), scaled back once at the end:
862
+ * the square of r/(1 - h) overflowed although the distance is finite (a binomial fit with prior weights 4e306 and
863
+ * dispersion 100: r/(1 - h) = 2.7e154 for a distance of 3.6e306, which was NaN)
864
+ */
865
+ function cookScaled(r, h, d, p) {
866
+ if (!Number.isFinite(r) || !(d > 0 && Number.isFinite(d)))
867
+ return NaN;
868
+ const er = r === 0 ? 0 : Math.floor(Math.log2(Math.abs(r)));
869
+ const ed = Math.floor(Math.log2(d));
870
+ const u = ldexp(r, -er) / (1 - h);
871
+ return ldexp(u * u * (h / (ldexp(d, -ed) * p)), 2 * er - ed);
872
+ }
554
873
  /**
555
874
  * Predictions of a generalized linear model with their standard errors, for a `glm` fit. Equivalent to R's
556
875
  * `predict(fit, newdata, type, se.fit = TRUE)`. Aliased columns are left out, as R does.
@@ -564,7 +883,12 @@ export function glmCooksDistance(fit, options = {}) {
564
883
  *
565
884
  * @category Generalized linear models
566
885
  */
567
- export function glmPredict(fit, options = {}) {
886
+ export function glmPredict(given, options = {}) {
887
+ checkOptions(options, GLM_PREDICT_KEYS, "glmPredict"); // generated: option-keys.mjs
888
+ // on the scaled fit (scaledView), with the new offset and the dispersion scaled alike; predictions and standard
889
+ // errors scaled back (the families that are scaled use the identity link)
890
+ const { fit, k } = scaledView(given);
891
+ const up = (v) => ldexp(v, k);
568
892
  const fam = familyOf(fit);
569
893
  let X;
570
894
  let eta;
@@ -574,12 +898,24 @@ export function glmPredict(fit, options = {}) {
574
898
  }
575
899
  else {
576
900
  X = toRows(options.newdata).map((r) => (fit.model.intercept ? [1, ...r] : r));
577
- const off = options.newoffset === undefined ? X.map(() => 0) : Array.from(options.newoffset);
901
+ if (X.some((r) => r.length !== fit.coefficients.length))
902
+ throw new RangeError("newdata must have one column per predictor of the fit");
903
+ const off = options.newoffset === undefined ? X.map(() => 0) : Array.from(options.newoffset, (v) => ldexp(v, -k));
578
904
  if (off.length !== X.length)
579
905
  throw new RangeError("newoffset must have one value per row of newdata");
580
- eta = X.map((r, i) => r.reduce((s, v, j) => (Number.isNaN(fit.coefficients[j]) ? s : s + v * fit.coefficients[j]), 0) + off[i]);
906
+ const used = fit.coefficients.flatMap((b, j) => (Number.isNaN(b) ? [] : [j]));
907
+ eta = X.map((r, i) => {
908
+ const s = r.reduce((s, v, j) => (Number.isNaN(fit.coefficients[j]) ? s : s + v * fit.coefficients[j]), 0);
909
+ // products of finite values may overflow while x'b is in range (2 * 1e308 - 2 * 1e308): the exact inner
910
+ // product, as predict for lm (#174); also where products underflow while the sum is tiny (#395)
911
+ const xb = checkDot(s, 0) ? checkedDot(used.map((j) => r[j]), used.map((j) => fit.coefficients[j]), s) : s;
912
+ return xb + off[i];
913
+ });
581
914
  }
582
- const disp = options.dispersion ?? glmDispersion(fit);
915
+ // (a given dispersion is m 4^s, s != 0 only where its scaled value is out of range: the standard errors are then
916
+ // brought back by 2^(k + s), #349)
917
+ const { m: disp, s: shift } = options.dispersion === undefined ? { m: dispersionOf(fit), s: 0 } : scaledDispersion(options.dispersion, k);
918
+ const upSe = (v) => ldexp(v, k + shift);
583
919
  const rank = fit.rank;
584
920
  const piv = fit.qr === undefined ? [] : fit.qr.pivot.slice(0, rank);
585
921
  const R = fit.qr?.qr;
@@ -594,12 +930,29 @@ export function glmPredict(fit, options = {}) {
594
930
  z[i] = s / R[i][i];
595
931
  ss += z[i] * z[i];
596
932
  }
933
+ // the squares overflowed (newdata 1e155: Infinity, R too) or underflowed: the norm of z divided by its largest
934
+ if (!(ss >= 2 ** -1022 && ss < Infinity)) {
935
+ const top = z.reduce((m, v) => Math.max(m, Math.abs(v)), 0);
936
+ if (top > 0 && Number.isFinite(top)) {
937
+ const norm = Math.sqrt(z.reduce((t, v) => t + (v / top) ** 2, 0));
938
+ const value = top * norm * Math.sqrt(disp);
939
+ // the norm of z beyond the doubles, brought back by a small dispersion (#175)
940
+ return Number.isFinite(value) ? value : top * (norm * Math.sqrt(disp));
941
+ }
942
+ }
597
943
  return Math.sqrt(ss) * Math.sqrt(disp);
598
944
  });
599
- if ((options.type ?? "link") === "link")
600
- return { fit: eta, seFit: se };
601
- return withWarnings(new Warnings(), () => ({
602
- fit: eta.map((e) => fam.linkinv(e)),
603
- seFit: se.map((s, i) => s * Math.abs(fam.muEta(eta[i]))),
604
- }));
945
+ const type = options.type ?? "link";
946
+ if (type !== "link" && type !== "response")
947
+ throw new RangeError(`invalid 'type': ${String(type)}`);
948
+ // as predict.lm, which R's predict.glm calls (only for new data: the fitted rows are estimable)
949
+ const nonEstimable = options.newdata === undefined ? [] : nonEstimableRows(fit.qr, rank, X);
950
+ const extra = nonEstimable.length > 0 ? { nonEstimable, warnings: [NON_ESTIMABLE_WARNING] } : {};
951
+ if (type === "link")
952
+ return reported("glmPredict", { fit: eta.map(up), seFit: se.map(upSe), ...extra }, given);
953
+ return reported("glmPredict", withWarnings(new Warnings(), () => ({
954
+ fit: eta.map((e) => up(fam.linkinv(e))),
955
+ seFit: se.map((s, i) => upSe(s * Math.abs(fam.muEta(eta[i])))),
956
+ ...extra,
957
+ })), given);
605
958
  }