@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
@@ -8,9 +8,13 @@
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
13
  import { familyAic, makeFamily, prepareResponse, Warnings, withWarnings, } from "./glmFamily.js";
14
+ import { maxOf } from "../internal/extremes.js";
15
+ import { ldexp, ldexpWide, scaleToUnit } from "../internal/summary.js";
16
+ import { NON_ESTIMABLE_WARNING, nonEstimableRows } from "./estimable.js";
17
+ import { checkDot, checkedDot } from "../linalg/dot.js";
14
18
  const EPS = 2 ** -52;
15
19
  function deparseNames(names) {
16
20
  const q = names.map((s) => `"${s}"`);
@@ -26,14 +30,74 @@ function linearPredictor(x, b, offset) {
26
30
  }
27
31
  function totalDeviance(fam, y, mu, w) {
28
32
  let d = 0;
33
+ // an observation of weight 0 adds nothing (its contribution 0 * Inf was NaN for a poisson y of 1e308, as in R)
29
34
  for (let i = 0; i < y.length; i++)
30
- d += fam.devContribution(y[i], mu[i], w[i]);
35
+ if (w[i] !== 0)
36
+ d += fam.devContribution(y[i], mu[i], w[i]);
31
37
  return d;
32
38
  }
39
+ const MIN_NORMAL = 2 ** -1022;
40
+ /** Whether v is 0 or a finite number of the normal range */
41
+ const inRange = (v) => v === 0 || (Math.abs(v) >= MIN_NORMAL && Math.abs(v) < Infinity);
42
+ /**
43
+ * 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
44
+ * the result is outside the normal range although the weight is not (a poisson mean beyond 1.34e154 squared muEta to
45
+ * Infinity, an inverse.gaussian V of mu^3 overflowed or underflowed, a muEta of 1e-160 squared to 0: #165-#168), as
46
+ * 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
47
+ * that form (the binomial ones), the same bits as R's form. (Not sqrt(w) |muEta| / sqrt(V) for those: a binomial
48
+ * 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
49
+ * infinite linear predictor a weight, and the working response Infinity, where R's form gives them the weight 0)
50
+ */
51
+ function sqrtWeight(fam, w, me, mu) {
52
+ const v = fam.variance(mu);
53
+ const me2 = me ** 2;
54
+ const s = Math.sqrt((w * me2) / v);
55
+ if (s > 0 && s < Infinity && inRange(me2) && me2 !== 0 && inRange(v) && v !== 0 && inRange(w * me2))
56
+ return s;
57
+ if (fam.muPower !== undefined && fam.varPower !== undefined && mu > 0) {
58
+ const { c, a } = fam.muPower;
59
+ return Math.sqrt(w) * Math.abs(c) * mu ** ((2 * a - fam.varPower) / 2);
60
+ }
61
+ return s;
62
+ }
63
+ /**
64
+ * The working residual (y - mu) / muEta; where muEta is not finite or below the normal range (the inverse link's
65
+ * -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
66
+ */
67
+ function workingResidual(fam, y, mu, me) {
68
+ const r = (y - mu) / me;
69
+ if (Math.abs(me) >= MIN_NORMAL && Math.abs(me) < Infinity)
70
+ return r;
71
+ if (fam.muPower !== undefined && mu > 0) {
72
+ const { c, a } = fam.muPower;
73
+ const h = mu ** (a / 2);
74
+ return (y - mu) / c / h / h;
75
+ }
76
+ return r;
77
+ }
78
+ /**
79
+ * The Pearson residual (y - mu) sqrt(w) / sqrt(V(mu)); where V is outside the normal range or the result is not finite,
80
+ * as ((y - mu)/h) sqrt(w)/h with h = mu^(p/4) from V = mu^p
81
+ */
82
+ function pearsonResidual(fam, y, mu, w) {
83
+ const v = fam.variance(mu);
84
+ const r = ((y - mu) * Math.sqrt(w)) / Math.sqrt(v);
85
+ if ((Number.isFinite(r) && inRange(v) && v !== 0) || fam.varPower === undefined || !(mu > 0))
86
+ return r;
87
+ const h = mu ** (fam.varPower / 4);
88
+ return (((y - mu) / h) * Math.sqrt(w)) / h;
89
+ }
33
90
  /** Iteratively reweighted least squares (glm-behaviour.md, "Fitting") */
91
+ /** The change of the linear predictor in the last iteration above which a converged fit is reported separated */
92
+ const SEPARATION_STEP = 0.1;
34
93
  export function irls(inp, warnings) {
35
94
  const { x, p, y, w, offset, fam, epsilon, maxit } = inp;
36
95
  const n = y.length;
96
+ // As R, whose least-squares step (C_Cdqrls) stops on a non-finite value among the rows of positive weight
97
+ if (y.some((v, i) => w[i] > 0 && !Number.isFinite(v)))
98
+ throw new RangeError("NA/NaN/Inf in 'y'");
99
+ if (x.some((r, i) => w[i] > 0 && r.some((v) => !Number.isFinite(v))))
100
+ throw new RangeError("NA/NaN/Inf in 'x'");
37
101
  return withWarnings(warnings, () => {
38
102
  const allOk = (eta, mu) => eta.every((e) => fam.etaOk(e)) && mu.every((m) => fam.muOk(m));
39
103
  if (p === 0) {
@@ -45,7 +109,7 @@ export function irls(inp, warnings) {
45
109
  if (!mu.every((m) => fam.muOk(m)))
46
110
  throw new Error("invalid fitted means in empty model");
47
111
  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);
112
+ const ww = mu.map((m, i) => sqrtWeight(fam, w[i], me[i], m) ** 2);
49
113
  return {
50
114
  coefficients: [],
51
115
  eta,
@@ -60,7 +124,7 @@ export function irls(inp, warnings) {
60
124
  qr: undefined,
61
125
  used: w.map((v) => v > 0),
62
126
  workingWeights: ww,
63
- workingResiduals: y.map((v, i) => (v - mu[i]) / me[i]),
127
+ workingResiduals: y.map((v, i) => workingResidual(fam, v, mu[i], me[i])),
64
128
  };
65
129
  }
66
130
  let eta;
@@ -88,6 +152,7 @@ export function irls(inp, warnings) {
88
152
  let q;
89
153
  let used = w.map(() => false);
90
154
  let sqrtW = [];
155
+ const recent = [];
91
156
  const tol = Math.min(1e-7, epsilon / 1000);
92
157
  for (iter = 1; iter <= maxit; iter++) {
93
158
  const me = eta.map((e) => fam.muEta(e));
@@ -97,7 +162,8 @@ export function irls(inp, warnings) {
97
162
  const v = fam.variance(mu[i]);
98
163
  if (Number.isNaN(v))
99
164
  throw new Error("NAs in V(mu)");
100
- if (v === 0)
165
+ // (not where V = mu^p underflowed for a positive mean: an inverse.gaussian mean of 1e-200, #166)
166
+ if (v === 0 && !(fam.varPower !== undefined && mu[i] > 0))
101
167
  throw new Error("0s in V(mu)");
102
168
  if (Number.isNaN(me[i]))
103
169
  throw new Error("NAs in d(mu)/d(eta)");
@@ -116,9 +182,9 @@ export function irls(inp, warnings) {
116
182
  const zw = [];
117
183
  const xw = [];
118
184
  for (const i of rows) {
119
- const s = Math.sqrt((w[i] * me[i] ** 2) / fam.variance(mu[i]));
185
+ const s = sqrtWeight(fam, w[i], me[i], mu[i]);
120
186
  sqrtW[i] = s;
121
- zw.push(((eta[i] - offset[i]) + (y[i] - mu[i]) / me[i]) * s);
187
+ zw.push(((eta[i] - offset[i]) + workingResidual(fam, y[i], mu[i], me[i])) * s);
122
188
  xw.push(x[i].map((v) => v * s));
123
189
  }
124
190
  q = qr(xw, { tol });
@@ -130,6 +196,7 @@ export function irls(inp, warnings) {
130
196
  }
131
197
  coef = b.map((v) => (Number.isNaN(v) ? 0 : v));
132
198
  boundary = false;
199
+ const etaBefore = eta;
133
200
  eta = linearPredictor(x, coef, offset);
134
201
  mu = eta.map((e) => fam.linkinv(e));
135
202
  dev = totalDeviance(fam, y, mu, w);
@@ -165,15 +232,57 @@ export function irls(inp, warnings) {
165
232
  boundary = true;
166
233
  dev = totalDeviance(fam, y, mu, w);
167
234
  }
235
+ // A step that increases the deviance is halved until it does not, as glm2's glm.fit2 (R's glm.fit accepts it:
236
+ // binomial with weights 1000 went from 7564 to 89255 and stopped at 144175 with coefficients of 1e15,
237
+ // "converged", where the maximum is 4956)
238
+ // (an increase of 1e-10 at least: with a tiny epsilon, as the profiles of glmConfint iterate, rounding of the
239
+ // deviance near the maximum is no increase to correct)
240
+ const rise = Math.max(epsilon, 1e-10);
241
+ if (previous !== undefined && iter > 1 && (dev - devPrevious) / (0.1 + Math.abs(dev)) >= rise) {
242
+ warnings.add("step size truncated due to increasing deviance");
243
+ let halvings = 0;
244
+ while ((dev - devPrevious) / (0.1 + Math.abs(dev)) >= rise && halvings < maxit) {
245
+ halvings++;
246
+ coef = coef.map((v, j) => (v + previous[j]) / 2);
247
+ eta = linearPredictor(x, coef, offset);
248
+ mu = eta.map((e) => fam.linkinv(e));
249
+ dev = totalDeviance(fam, y, mu, w);
250
+ }
251
+ if ((dev - devPrevious) / (0.1 + Math.abs(dev)) >= rise) {
252
+ warnings.add("inner loop 3; cannot correct step size");
253
+ converged = false;
254
+ break;
255
+ }
256
+ }
168
257
  if (inp.untilCoefficients) {
169
- const scale = Math.max(...coef.map(Math.abs));
258
+ const scale = maxOf(coef.map(Math.abs));
170
259
  if (previous !== undefined && coef.every((v, j) => Math.abs(v - previous[j]) <= 8 * EPS * scale)) {
171
260
  converged = true;
172
261
  break;
173
262
  }
263
+ // back to one of the last 16 iterates: a cycle in the last bits (of 2 to 5 iterates seen; rounding of the
264
+ // working response, far larger than 8 eps times a coefficient near 0), as close to the maximum as the doubles
265
+ // go (the profiles of glmConfint went to maxit, unconverged, and gave a NaN limit; review 66)
266
+ if (recent.some((r) => r.every((v, j) => v === coef[j]))) {
267
+ converged = true;
268
+ break;
269
+ }
270
+ recent.push(coef.slice());
271
+ if (recent.length > 16)
272
+ recent.shift();
174
273
  }
175
274
  else if (Math.abs(dev - devPrevious) / (Math.abs(dev) + 0.1) < epsilon) {
176
275
  converged = true;
276
+ // The deviance settles while the linear predictor still moves by about 1 per iteration when the data are
277
+ // separated (R reports such fits converged, with finite coefficients that only depend on maxit and epsilon).
278
+ // At a maximum the last step is far smaller; eta has no units, so the test does not depend on those of x
279
+ let moved = 0;
280
+ for (let i = 0; i < n; i++)
281
+ if (used[i])
282
+ moved = Math.max(moved, Math.abs(eta[i] - etaBefore[i]));
283
+ if (moved > SEPARATION_STEP) {
284
+ warnings.add("glm.fit: the linear predictor was still changing at convergence: the data may be separated (no finite maximum likelihood estimates)");
285
+ }
177
286
  break;
178
287
  }
179
288
  devPrevious = dev;
@@ -201,7 +310,7 @@ export function irls(inp, warnings) {
201
310
  qr: q,
202
311
  used,
203
312
  workingWeights: sqrtW.map((s) => s * s),
204
- workingResiduals: y.map((v, i) => (v - mu[i]) / me[i]),
313
+ workingResiduals: y.map((v, i) => workingResidual(fam, v, mu[i], me[i])),
205
314
  };
206
315
  });
207
316
  }
@@ -227,6 +336,10 @@ export function refit(model, cols, warnings, control = {}) {
227
336
  const fam = makeFamily(model.familySpec);
228
337
  const start = "start" in control ? control.start : model.start;
229
338
  const prep = prepareResponse(fam, model.yGiven, model.priorGiven, start !== undefined || control.etastart !== undefined, warnings);
339
+ // no observation carries information (R stops with an internal error); the fit came out with rank p and negative
340
+ // residual degrees of freedom
341
+ if (!prep.weights.some((w) => w > 0))
342
+ throw new RangeError("all weights are zero");
230
343
  const offset = control.extraOffset === undefined ? model.offset : model.offset.map((o, i) => o + control.extraOffset[i]);
231
344
  const x = model.x.map((r) => cols.map((j) => r[j]));
232
345
  const fit = irls({
@@ -270,6 +383,9 @@ export function refit(model, cols, warnings, control = {}) {
270
383
  export function glm(x, y, options = {}) {
271
384
  const intercept = options.intercept ?? true;
272
385
  const xr = toRows(x);
386
+ // the shape of all the rows given, before the rows with a missing value are dropped (#463)
387
+ if (xr.some((r) => r.length !== xr[0].length))
388
+ throw new TypeError("all rows of x must have the same length");
273
389
  const yIsMatrix = y.length > 0 && typeof y[0] !== "number";
274
390
  const yr = yIsMatrix ? y.map((r) => Array.from(r)) : Array.from(y);
275
391
  const nAll = yr.length;
@@ -294,12 +410,16 @@ export function glm(x, y, options = {}) {
294
410
  const priorGiven = wGiven === undefined ? new Array(n).fill(1) : wGiven.filter((_, i) => keep[i]);
295
411
  if (priorGiven.some((v) => v < 0))
296
412
  throw new RangeError("negative weights not allowed");
413
+ // (R: "NA/NaN/Inf in 'x'" from the weighted least squares step; here the error of the QR on a matrix with Inf)
414
+ if (priorGiven.some((v) => !Number.isFinite(v)))
415
+ throw new RangeError("non-finite weights not allowed");
297
416
  const offset = oGiven === undefined ? new Array(n).fill(0) : oGiven.filter((_, i) => keep[i]);
417
+ // as R ("NA/NaN/Inf in 'y'" there, from the working response); an infinite offset gave coefficients of 0
418
+ if (offset.some((v) => !Number.isFinite(v)))
419
+ throw new RangeError("the offset must be finite");
298
420
  const nx = xr.length > 0 ? xr[0].length : 0;
299
421
  const columnNames = [...(intercept ? ["(Intercept)"] : []), ...Array.from({ length: nx }, (_, j) => `x${j + 1}`)];
300
422
  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
423
  const familySpec = typeof options.family === "object" ? { ...options.family } : { family: options.family ?? "gaussian" };
304
424
  if (options.link !== undefined)
305
425
  familySpec.link = options.link;
@@ -313,13 +433,33 @@ export function glm(x, y, options = {}) {
313
433
  intercept,
314
434
  familySpec,
315
435
  epsilon: options.epsilon ?? 1e-8,
316
- maxit: options.maxit ?? 25,
436
+ // R loops over 1:maxit, so a fractional maxit runs (and reports) its integer part
437
+ maxit: Math.floor(options.maxit ?? 25),
317
438
  start: options.start === undefined ? undefined : Array.from(options.start),
318
439
  };
319
- if (!(model.epsilon > 0))
320
- throw new RangeError("value of 'epsilon' must be > 0");
321
- if (!(model.maxit > 0))
440
+ if (!(model.epsilon > 0 && model.epsilon < Infinity))
441
+ throw new RangeError("value of 'epsilon' must be > 0 and finite");
442
+ if (!(model.maxit > 0 && model.maxit < Infinity))
322
443
  throw new RangeError("maximum number of iterations must be > 0");
444
+ // gaussian (and quasi with constant variance) on the identity link: fitted to the response scaled by a power of 2
445
+ // (exact; src/internal/summary.ts), so that the deviance stays in range; see scaledView
446
+ const k = !yIsMatrix && scalesWithResponse(familySpec) ? scaleToUnit([yGiven]).k : 0;
447
+ if (k === 0)
448
+ return fitModel(model);
449
+ const down = (v) => ldexp(v, -k);
450
+ const scaled = fitModel({
451
+ ...model,
452
+ yGiven: yGiven.map(down),
453
+ offset: offset.map(down),
454
+ start: model.start?.map(down),
455
+ });
456
+ return unscaledResult(scaled, k, { ...model, yScale: k });
457
+ }
458
+ /** The fit of a model (the part of glm after its checks) */
459
+ function fitModel(model) {
460
+ const { x: X, offset, intercept } = model;
461
+ const n = X.length;
462
+ const p = model.columnNames.length;
323
463
  const warnings = new Warnings();
324
464
  const all = Array.from({ length: p }, (_, j) => j);
325
465
  const { fit, fam, y: yy, w, size } = refit(model, all, warnings);
@@ -335,20 +475,40 @@ export function glm(x, y, options = {}) {
335
475
  warnings.add("fitting to calculate the null deviance did not converge -- increase 'maxit'?");
336
476
  }
337
477
  else if (intercept) {
478
+ // the weights divided by a power of 2 (the mean unchanged; their sum overflowed for weights of 1e308), and rows of
479
+ // weight 0 left out (0 times an infinite response was NaN); R gave NaN for both
480
+ const kw = Math.floor(Math.log2(maxOf(w)));
338
481
  let sw = 0;
339
482
  let swy = 0;
340
483
  for (let i = 0; i < n; i++) {
341
- sw += w[i];
342
- swy += w[i] * yy[i];
484
+ if (!(w[i] > 0))
485
+ continue;
486
+ const wi = ldexp(w[i], -kw);
487
+ sw += wi;
488
+ swy += wi * yy[i];
489
+ }
490
+ let m = swy / sw;
491
+ if (!Number.isFinite(m)) {
492
+ // the weighted sum of the response overflowed (a poisson response of 1e308, #168): with the response divided by a
493
+ // power of 2 as well
494
+ let ymax = 0;
495
+ for (let i = 0; i < n; i++)
496
+ if (w[i] > 0)
497
+ ymax = Math.max(ymax, Math.abs(yy[i]));
498
+ const ky = Math.floor(Math.log2(ymax));
499
+ let swy2 = 0;
500
+ for (let i = 0; i < n; i++)
501
+ if (w[i] > 0)
502
+ swy2 += ldexp(w[i], -kw) * ldexp(yy[i], -ky);
503
+ m = ldexp(swy2 / sw, ky);
343
504
  }
344
- const m = swy / sw;
345
505
  nullDeviance = withWarnings(warnings, () => totalDeviance(fam, yy, yy.map(() => m), w));
346
506
  }
347
507
  else
348
508
  nullDeviance = withWarnings(warnings, () => totalDeviance(fam, yy, offset.map((o) => fam.linkinv(o)), w));
349
509
  const nOk = n - w.filter((v) => v === 0).length;
350
510
  const aic = familyAic(fam, yy, fit.mu, w, size, fit.deviance, warnings) + 2 * fit.rank;
351
- return {
511
+ return withUsedRows(fit.used, {
352
512
  coefficients: fit.coefficients,
353
513
  fittedValues: fit.mu,
354
514
  linearPredictors: fit.eta,
@@ -370,7 +530,57 @@ export function glm(x, y, options = {}) {
370
530
  warnings: warnings.list,
371
531
  qr: fit.qr,
372
532
  model,
533
+ });
534
+ }
535
+ /** Whether the family's fit scales with the response: gaussian, or quasi with constant variance, on the identity link */
536
+ function scalesWithResponse(spec) {
537
+ const link = spec.link ?? "identity";
538
+ if (link !== "identity")
539
+ return false;
540
+ return spec.family === "gaussian" || (spec.family === "quasi" && (spec.variance ?? "constant") === "constant");
541
+ }
542
+ /**
543
+ * The fit of the response in its own units from the fit of the response scaled by 2^-k: coefficients, means, linear
544
+ * predictors, the response and the working residuals times 2^k, deviances times 2^2k, and the gaussian AIC
545
+ * (n log(deviance / n) + ...) plus 2 n k log 2. The scaled fit stays with it (not enumerable), for scaledView
546
+ */
547
+ function unscaledResult(scaled, k, model) {
548
+ const up = (v) => ldexp(v, k);
549
+ const out = {
550
+ ...scaled,
551
+ coefficients: scaled.coefficients.map(up),
552
+ fittedValues: scaled.fittedValues.map(up),
553
+ linearPredictors: scaled.linearPredictors.map(up),
554
+ deviance: ldexp(scaled.deviance, 2 * k),
555
+ nullDeviance: ldexp(scaled.nullDeviance, 2 * k),
556
+ // (n log of the deviance scaled by 2^-2k, n the rows of positive weight as in familyAic)
557
+ aic: scaled.aic + 2 * scaled.priorWeights.filter((v) => v > 0).length * k * Math.LN2,
558
+ y: scaled.y.map(up),
559
+ residuals: scaled.residuals.map(up),
560
+ model,
373
561
  };
562
+ Object.defineProperty(out, "scaled", { value: scaled, enumerable: false });
563
+ return withUsedRows(USED_ROWS.get(scaled), out);
564
+ }
565
+ /**
566
+ * The rows of the last least squares step of a fit (irls's used): its working weights, squares of the square roots
567
+ * 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
568
+ * were shifted by one)
569
+ */
570
+ const USED_ROWS = new WeakMap();
571
+ function withUsedRows(used, fit) {
572
+ if (used !== undefined)
573
+ USED_ROWS.set(fit, used);
574
+ return fit;
575
+ }
576
+ /**
577
+ * 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
578
+ * quantities with units are 2^-k (or 2^-2k) times the fit's; otherwise the fit itself with k = 0. The functions on a
579
+ * fit compute on it (statistics without units unchanged) and scale back only what has units
580
+ */
581
+ export function scaledView(fit) {
582
+ const scaled = fit.scaled;
583
+ return scaled === undefined ? { fit, k: 0 } : { fit: scaled, k: fit.model.yScale ?? 0 };
374
584
  }
375
585
  /** The family object of a fit */
376
586
  export function familyOf(fit) {
@@ -378,6 +588,12 @@ export function familyOf(fit) {
378
588
  }
379
589
  /** Pearson dispersion of summary.glm (1 for binomial and poisson) */
380
590
  export function glmDispersion(fit, warnings) {
591
+ const v = scaledView(fit);
592
+ const d = dispersionOf(v.fit, warnings);
593
+ return familyOf(fit).fixedDispersion ? d : ldexp(d, 2 * v.k);
594
+ }
595
+ /** The dispersion of a fit in its own units (of the scaled fit for a scaled view) */
596
+ function dispersionOf(fit, warnings) {
381
597
  if (familyOf(fit).fixedDispersion)
382
598
  return 1;
383
599
  if (fit.dfResidual <= 0)
@@ -388,14 +604,61 @@ export function glmDispersion(fit, warnings) {
388
604
  s += fit.weights[i] * fit.residuals[i] ** 2;
389
605
  if (fit.weights.some((v) => v === 0))
390
606
  warnings?.add("observations with zero weight not used for calculating dispersion");
607
+ if (s === Infinity)
608
+ return scaledPearsonMean(fit);
391
609
  return s / fit.dfResidual;
392
610
  }
393
- /** (R'R)^-1 of the leading rank x rank block of the last QR, in pivot order */
611
+ /**
612
+ * sum W r^2 / dfResidual where the plain sum overflows: each term as (sqrt(W) r)^2 with the residuals and then the
613
+ * products divided by powers of 2 (2^-kr, 2^-kb), so that the sum stays in range, and the exponents added back after
614
+ * the division (#176). Terms below 2^-1074 of the largest are lost, which cannot matter next to a sum beyond the
615
+ * double range
616
+ */
617
+ function scaledPearsonMean(fit) {
618
+ const rows = [];
619
+ for (let i = 0; i < fit.weights.length; i++)
620
+ if (fit.weights[i] > 0)
621
+ rows.push(i);
622
+ if (!rows.every((i) => Number.isFinite(fit.weights[i]) && Number.isFinite(fit.residuals[i])))
623
+ return Infinity;
624
+ const r = scaleToUnit([rows.map((i) => fit.residuals[i])]);
625
+ const b = scaleToUnit([rows.map((i, j) => Math.sqrt(fit.weights[i]) * Math.abs(r.groups[0][j]))]);
626
+ let s = 0;
627
+ for (const v of b.groups[0])
628
+ s += v * v;
629
+ return ldexp(s / fit.dfResidual, 2 * (r.k + b.k));
630
+ }
631
+ /**
632
+ * (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
633
+ * 1 divided by powers of 2 first: chol2invColumns)
634
+ */
394
635
  function unscaledCovariance(fit) {
395
636
  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);
637
+ return { inv: [], e: [] };
638
+ return chol2invColumns(fit.qr.qr.slice(0, fit.rank).map((row) => row.slice(0, fit.rank)));
639
+ }
640
+ /**
641
+ * A dispersion given by the user: a non-negative finite number (a negative one gave NaN standard errors, as R's with a
642
+ * warning; 0 gives standard errors of 0, as R)
643
+ */
644
+ export function checkDispersion(d) {
645
+ if (!(d >= 0 && d < Infinity))
646
+ throw new RangeError("'dispersion' must be a non-negative finite number");
647
+ return d;
648
+ }
649
+ /**
650
+ * A dispersion d given by the user, in the units of a fit computed on the response scaled by 2^-k (scaledView), as
651
+ * 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
652
+ * or overflows although d does not (k = 1023 for a response of 1e308, where d = 1 gave 0 and standard errors 0,
653
+ * #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
654
+ * where the result is in range
655
+ */
656
+ export function scaledDispersion(d, k) {
657
+ const v = ldexp(checkDispersion(d), -2 * k);
658
+ if (v === 0 ? d === 0 : v >= 2 ** -1022 && v < Infinity)
659
+ return { m: v, s: 0 };
660
+ const h = Math.floor(Math.floor(Math.log2(d)) / 2);
661
+ return { m: ldexp(d, -2 * h), s: h - k };
399
662
  }
400
663
  /**
401
664
  * Summary of a generalized linear model: the dispersion, the coefficient table and the covariance of the estimates,
@@ -412,31 +675,46 @@ function unscaledCovariance(fit) {
412
675
  *
413
676
  * @category Generalized linear models
414
677
  */
415
- export function glmSummary(fit, options = {}) {
678
+ export function glmSummary(given, options = {}) {
679
+ // computed on the scaled fit (scaledView); estimates, standard errors and the dispersion scaled back
680
+ const { fit, k } = scaledView(given);
416
681
  const warnings = new Warnings();
417
682
  const fam = familyOf(fit);
418
683
  const estimated = options.dispersion === undefined && !fam.fixedDispersion;
419
- const dispersion = options.dispersion ?? glmDispersion(fit, warnings);
420
- const covUnscaled = unscaledCovariance(fit);
684
+ const user = options.dispersion === undefined ? undefined : scaledDispersion(options.dispersion, k);
685
+ const dispersion = user === undefined ? dispersionOf(fit, warnings) : user.m;
686
+ // (a given dispersion is m 4^s; s != 0 only where its scaled value is out of range, #349)
687
+ const s = user?.s ?? 0;
688
+ const { inv, e } = unscaledCovariance(fit);
689
+ // (Infinity or 0 where the covariance itself is out of range; the standard errors scale back from the scaled columns)
690
+ const covUnscaled = inv.map((r, j) => r.map((v, k) => ldexp(v, -e[j] - e[k])));
421
691
  const piv = fit.qr === undefined ? [] : fit.qr.pivot.slice(0, fit.rank);
422
692
  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]);
693
+ const stdError = inv.map((r, k) => ldexp(Math.sqrt(r[k] * dispersion), -e[k]));
694
+ const statistic = s === 0
695
+ ? estimate.map((e, k) => e / stdError[k])
696
+ : estimate.map((b, j) => ldexpWide(b / Math.sqrt(inv[j][j] * dispersion), e[j] - s));
425
697
  const zTest = !estimated;
426
698
  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
699
  if (estimated && fit.dfResidual === 0) {
428
700
  stdError.fill(NaN);
429
701
  statistic.fill(NaN);
430
702
  }
703
+ const up = (v) => ldexp(v, k);
704
+ const up2 = (v) => ldexp(v, 2 * k);
431
705
  return {
432
- dispersion,
433
- estimate,
434
- stdError,
706
+ dispersion: s === 0 ? up2(dispersion) : options.dispersion,
707
+ estimate: estimate.map(up),
708
+ // (with s != 0 in the original units at once: sqrt(inv m) 2^(s + k - e))
709
+ stdError: s === 0 ? stdError.map(up) : inv.map((r, j) => ldexpWide(Math.sqrt(r[j] * dispersion), s + k - e[j])),
435
710
  statistic,
436
711
  pValue,
437
- statisticName: fam.fixedDispersion ? "z value" : "t value",
712
+ // (z whenever the dispersion is not estimated, as R: a given dispersion was named "t value")
713
+ statisticName: zTest ? "z value" : "t value",
438
714
  covUnscaled,
439
- covScaled: covUnscaled.map((r) => r.map((v) => v * dispersion)),
715
+ covScaled: s === 0
716
+ ? covUnscaled.map((r) => r.map((v) => up2(v * dispersion)))
717
+ : inv.map((r, j) => r.map((v, l) => ldexpWide(v * dispersion, 2 * (s + k) - e[j] - e[l]))),
440
718
  dfResidual: fit.dfResidual,
441
719
  warnings: warnings.list,
442
720
  };
@@ -455,6 +733,11 @@ export function glmSummary(fit, options = {}) {
455
733
  * @category Generalized linear models
456
734
  */
457
735
  export function glmResiduals(fit, type = "deviance") {
736
+ // of the scaled fit (scaledView), scaled back: for the families that are scaled, every kind has the response's units
737
+ const v = scaledView(fit);
738
+ return residualsOf(v.fit, type).map((r) => ldexp(r, v.k));
739
+ }
740
+ function residualsOf(fit, type) {
458
741
  const fam = familyOf(fit);
459
742
  const { y, fittedValues: mu, priorWeights: w } = fit;
460
743
  switch (type) {
@@ -463,11 +746,11 @@ export function glmResiduals(fit, type = "deviance") {
463
746
  case "working":
464
747
  return fit.residuals.slice();
465
748
  case "pearson":
466
- return y.map((v, i) => ((v - mu[i]) * Math.sqrt(w[i])) / Math.sqrt(fam.variance(mu[i])));
749
+ return y.map((v, i) => pearsonResidual(fam, v, mu[i], w[i]));
467
750
  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)));
751
+ // from each row's contribution also without residual degrees of freedom (R's residuals.glm gives 0 there, even
752
+ // for a fit that has not converged: deviance 0.34 with residuals 0); their squares sum to the deviance
753
+ 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
754
  default:
472
755
  throw new RangeError(`unknown type of residuals "${String(type)}"`);
473
756
  }
@@ -496,7 +779,7 @@ export function glmHatvalues(fit) {
496
779
  }
497
780
  // rows of the last least squares step, in order
498
781
  let k = 0;
499
- const usedRows = fit.weights.map((v) => v > 0);
782
+ const usedRows = USED_ROWS.get(fit) ?? fit.weights.map((v) => v > 0);
500
783
  fit.priorWeights.forEach((w, i) => {
501
784
  const hi = usedRows[i] ? (h[k++] ?? 0) : 0;
502
785
  if (w > 0)
@@ -521,13 +804,17 @@ function median(v) {
521
804
  *
522
805
  * @category Generalized linear models
523
806
  */
524
- export function glmRstandard(fit, options = {}) {
807
+ export function glmRstandard(given, options = {}) {
808
+ // on the scaled fit (scaledView): the standardized residuals have no units
809
+ const { fit, k } = scaledView(given);
525
810
  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));
811
+ // (a given dispersion is m 4^s, s != 0 only where its scaled value is out of range, #349)
812
+ const { m: disp, s: shift } = options.dispersion === undefined ? { m: dispersionOf(fit), s: 0 } : scaledDispersion(options.dispersion, k);
813
+ const r = residualsOf(fit, "deviance").filter((_, i) => fit.priorWeights[i] > 0);
814
+ // residuals below 100 eps times their median are taken as 0 only with columns, as R's lm.influence (rank 0 keeps them)
815
+ const small = fit.rank > 0 ? 100 * EPS * median(r.map(Math.abs)) : 0;
529
816
  return r.map((v, i) => {
530
- const s = (Math.abs(v) < small ? 0 : v) / Math.sqrt(disp * (1 - h[i]));
817
+ const s = ldexpWide((Math.abs(v) < small ? 0 : v) / Math.sqrt(disp * (1 - h[i])), -shift);
531
818
  return Number.isFinite(s) ? s : NaN;
532
819
  });
533
820
  }
@@ -542,15 +829,38 @@ export function glmRstandard(fit, options = {}) {
542
829
  *
543
830
  * @category Generalized linear models
544
831
  */
545
- export function glmCooksDistance(fit, options = {}) {
832
+ export function glmCooksDistance(given, options = {}) {
833
+ // on the scaled fit (scaledView): Cook's distances have no units
834
+ const { fit, k } = scaledView(given);
546
835
  const h = glmHatvalues(fit);
547
- const disp = options.dispersion ?? glmDispersion(fit);
548
- const r = glmResiduals(fit, "pearson").filter((_, i) => fit.priorWeights[i] > 0);
836
+ // (a given dispersion is m 4^s, s != 0 only where its scaled value is out of range, #349)
837
+ const { m: disp, s: shift } = options.dispersion === undefined ? { m: dispersionOf(fit), s: 0 } : scaledDispersion(options.dispersion, k);
838
+ const r = residualsOf(fit, "pearson").filter((_, i) => fit.priorWeights[i] > 0);
549
839
  return r.map((v, i) => {
550
- const c = (v / (1 - h[i])) ** 2 * (h[i] / (disp * fit.rank));
840
+ const q = h[i] / (disp * fit.rank);
841
+ let c = (v / (1 - h[i])) ** 2 * q;
842
+ // Where the square overflows, or h/(dispersion p) falls below the normal range (a large dispersion), with the residual
843
+ // and the dispersion in units of powers of 2 (cookScaled). Otherwise the same bits as before
844
+ if (!Number.isFinite(c) || q < 2 ** -1022)
845
+ c = cookScaled(v, h[i], disp, fit.rank);
846
+ if (shift !== 0)
847
+ c = ldexpWide(c, -2 * shift);
551
848
  return Number.isFinite(c) ? c : NaN;
552
849
  });
553
850
  }
851
+ /**
852
+ * 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:
853
+ * the square of r/(1 - h) overflowed although the distance is finite (a binomial fit with prior weights 4e306 and
854
+ * dispersion 100: r/(1 - h) = 2.7e154 for a distance of 3.6e306, which was NaN)
855
+ */
856
+ function cookScaled(r, h, d, p) {
857
+ if (!Number.isFinite(r) || !(d > 0 && Number.isFinite(d)))
858
+ return NaN;
859
+ const er = r === 0 ? 0 : Math.floor(Math.log2(Math.abs(r)));
860
+ const ed = Math.floor(Math.log2(d));
861
+ const u = ldexp(r, -er) / (1 - h);
862
+ return ldexp(u * u * (h / (ldexp(d, -ed) * p)), 2 * er - ed);
863
+ }
554
864
  /**
555
865
  * Predictions of a generalized linear model with their standard errors, for a `glm` fit. Equivalent to R's
556
866
  * `predict(fit, newdata, type, se.fit = TRUE)`. Aliased columns are left out, as R does.
@@ -564,7 +874,11 @@ export function glmCooksDistance(fit, options = {}) {
564
874
  *
565
875
  * @category Generalized linear models
566
876
  */
567
- export function glmPredict(fit, options = {}) {
877
+ export function glmPredict(given, options = {}) {
878
+ // on the scaled fit (scaledView), with the new offset and the dispersion scaled alike; predictions and standard
879
+ // errors scaled back (the families that are scaled use the identity link)
880
+ const { fit, k } = scaledView(given);
881
+ const up = (v) => ldexp(v, k);
568
882
  const fam = familyOf(fit);
569
883
  let X;
570
884
  let eta;
@@ -574,12 +888,24 @@ export function glmPredict(fit, options = {}) {
574
888
  }
575
889
  else {
576
890
  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);
891
+ if (X.some((r) => r.length !== fit.coefficients.length))
892
+ throw new RangeError("newdata must have one column per predictor of the fit");
893
+ const off = options.newoffset === undefined ? X.map(() => 0) : Array.from(options.newoffset, (v) => ldexp(v, -k));
578
894
  if (off.length !== X.length)
579
895
  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]);
896
+ const used = fit.coefficients.flatMap((b, j) => (Number.isNaN(b) ? [] : [j]));
897
+ eta = X.map((r, i) => {
898
+ const s = r.reduce((s, v, j) => (Number.isNaN(fit.coefficients[j]) ? s : s + v * fit.coefficients[j]), 0);
899
+ // products of finite values may overflow while x'b is in range (2 * 1e308 - 2 * 1e308): the exact inner
900
+ // product, as predict for lm (#174); also where products underflow while the sum is tiny (#395)
901
+ const xb = checkDot(s, 0) ? checkedDot(used.map((j) => r[j]), used.map((j) => fit.coefficients[j]), s) : s;
902
+ return xb + off[i];
903
+ });
581
904
  }
582
- const disp = options.dispersion ?? glmDispersion(fit);
905
+ // (a given dispersion is m 4^s, s != 0 only where its scaled value is out of range: the standard errors are then
906
+ // brought back by 2^(k + s), #349)
907
+ const { m: disp, s: shift } = options.dispersion === undefined ? { m: dispersionOf(fit), s: 0 } : scaledDispersion(options.dispersion, k);
908
+ const upSe = (v) => ldexp(v, k + shift);
583
909
  const rank = fit.rank;
584
910
  const piv = fit.qr === undefined ? [] : fit.qr.pivot.slice(0, rank);
585
911
  const R = fit.qr?.qr;
@@ -594,12 +920,29 @@ export function glmPredict(fit, options = {}) {
594
920
  z[i] = s / R[i][i];
595
921
  ss += z[i] * z[i];
596
922
  }
923
+ // the squares overflowed (newdata 1e155: Infinity, R too) or underflowed: the norm of z divided by its largest
924
+ if (!(ss >= 2 ** -1022 && ss < Infinity)) {
925
+ const top = z.reduce((m, v) => Math.max(m, Math.abs(v)), 0);
926
+ if (top > 0 && Number.isFinite(top)) {
927
+ const norm = Math.sqrt(z.reduce((t, v) => t + (v / top) ** 2, 0));
928
+ const value = top * norm * Math.sqrt(disp);
929
+ // the norm of z beyond the doubles, brought back by a small dispersion (#175)
930
+ return Number.isFinite(value) ? value : top * (norm * Math.sqrt(disp));
931
+ }
932
+ }
597
933
  return Math.sqrt(ss) * Math.sqrt(disp);
598
934
  });
599
- if ((options.type ?? "link") === "link")
600
- return { fit: eta, seFit: se };
935
+ const type = options.type ?? "link";
936
+ if (type !== "link" && type !== "response")
937
+ throw new RangeError(`invalid 'type': ${String(type)}`);
938
+ // as predict.lm, which R's predict.glm calls (only for new data: the fitted rows are estimable)
939
+ const nonEstimable = options.newdata === undefined ? [] : nonEstimableRows(fit.qr, rank, X);
940
+ const extra = nonEstimable.length > 0 ? { nonEstimable, warnings: [NON_ESTIMABLE_WARNING] } : {};
941
+ if (type === "link")
942
+ return { fit: eta.map(up), seFit: se.map(upSe), ...extra };
601
943
  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]))),
944
+ fit: eta.map((e) => up(fam.linkinv(e))),
945
+ seFit: se.map((s, i) => upSe(s * Math.abs(fam.muEta(eta[i])))),
946
+ ...extra,
604
947
  }));
605
948
  }