@numero-uno-jpn/rstats 0.15.3 → 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.
- package/CHANGELOG.md +166 -0
- package/README.ja.md +40 -33
- package/README.md +36 -28
- package/dist/chunks/chunk-2D2IQWUQ.js +2 -0
- package/dist/chunks/chunk-5UQCRBAG.js +2 -0
- package/dist/chunks/chunk-6CSTWA5E.js +2 -0
- package/dist/chunks/chunk-72Y3HZID.js +2 -0
- package/dist/chunks/chunk-BG2KLEHM.js +2 -0
- package/dist/chunks/chunk-CMEKBNHQ.js +2 -0
- package/dist/chunks/chunk-FLJNSXSW.js +2 -0
- package/dist/chunks/chunk-GM53LWSR.js +2 -0
- package/dist/chunks/chunk-JBCA56ZS.js +3 -0
- package/dist/chunks/chunk-K3RJAD2T.js +2 -0
- package/dist/chunks/chunk-KAZRWIB5.js +2 -0
- package/dist/chunks/chunk-KBVVIMXX.js +3 -0
- package/dist/chunks/chunk-N3SIFCZX.js +2 -0
- package/dist/chunks/chunk-QNNL7AZ3.js +2 -0
- package/dist/chunks/chunk-SC6CV4Z3.js +2 -0
- package/dist/chunks/chunk-SYWOBOTR.js +2 -0
- package/dist/chunks/chunk-URIO5LY5.js +2 -0
- package/dist/chunks/chunk-VTUGG2SV.js +2 -0
- package/dist/chunks/chunk-W26LRYOJ.js +2 -0
- package/dist/chunks/chunk-XHETEYVC.js +2 -0
- package/dist/chunks/{chunk-VLUL2HFW.js → chunk-YRZWONZB.js} +1 -1
- package/dist/chunks/chunk-ZGABZMWX.js +2 -0
- package/dist/data/grouping.js +20 -5
- package/dist/descriptive/basic.js +90 -8
- package/dist/descriptive/cov.js +12 -4
- package/dist/descriptive/dataFrames.d.ts +4 -2
- package/dist/descriptive/dataFrames.js +56 -18
- package/dist/descriptive/factanal.js +16 -7
- package/dist/descriptive/hist.d.ts +8 -5
- package/dist/descriptive/hist.js +71 -31
- package/dist/descriptive/missing.js +3 -1
- package/dist/descriptive/moments.js +72 -19
- package/dist/descriptive/omega.d.ts +1 -1
- package/dist/descriptive/omega.js +68 -9
- package/dist/descriptive/pivot.d.ts +21 -9
- package/dist/descriptive/pivot.js +161 -35
- package/dist/descriptive/quantile.js +2 -1
- package/dist/descriptive/rank.js +4 -1
- package/dist/descriptive/table.d.ts +3 -2
- package/dist/descriptive/table.js +24 -9
- package/dist/descriptive.js +2 -2
- package/dist/distributions/arcsine.js +19 -2
- package/dist/distributions/beta.js +24 -4
- package/dist/distributions/binomial.js +37 -14
- package/dist/distributions/bvnorm.js +11 -2
- package/dist/distributions/cauchy.js +12 -4
- package/dist/distributions/chisq.js +7 -3
- package/dist/distributions/exponential.js +5 -0
- package/dist/distributions/f.js +32 -17
- package/dist/distributions/gamma.js +27 -3
- package/dist/distributions/geometric.js +49 -13
- package/dist/distributions/hypergeometric.d.ts +5 -1
- package/dist/distributions/hypergeometric.js +93 -6
- package/dist/distributions/invgamma.js +2 -1
- package/dist/distributions/laplace.js +27 -6
- package/dist/distributions/logistic.js +4 -1
- package/dist/distributions/lognormal.js +8 -2
- package/dist/distributions/multinomial.js +54 -11
- package/dist/distributions/nbeta.js +62 -11
- package/dist/distributions/nchisq.js +30 -6
- package/dist/distributions/negbinomial.js +94 -17
- package/dist/distributions/normal.js +9 -4
- package/dist/distributions/nt.js +392 -17
- package/dist/distributions/pareto.js +4 -1
- package/dist/distributions/poisson.js +28 -3
- package/dist/distributions/signrank.js +7 -4
- package/dist/distributions/summary.js +450 -60
- package/dist/distributions/triangular.js +10 -5
- package/dist/distributions/tukey.js +5 -2
- package/dist/distributions/weibull.js +10 -0
- package/dist/distributions/wilcox.d.ts +9 -3
- package/dist/distributions/wilcox.js +155 -26
- package/dist/distributions.js +2 -2
- package/dist/htest/agreement.d.ts +3 -2
- package/dist/htest/agreement.js +76 -14
- package/dist/htest/ansariTest.d.ts +6 -1
- package/dist/htest/ansariTest.js +75 -8
- package/dist/htest/aov.d.ts +1 -1
- package/dist/htest/aov.js +48 -34
- package/dist/htest/binomTest.d.ts +5 -0
- package/dist/htest/binomTest.js +41 -17
- package/dist/htest/brunnerMunzelTest.d.ts +4 -3
- package/dist/htest/brunnerMunzelTest.js +7 -5
- package/dist/htest/chisqTest.d.ts +2 -1
- package/dist/htest/chisqTest.js +130 -43
- package/dist/htest/cor.d.ts +2 -1
- package/dist/htest/cor.js +17 -19
- package/dist/htest/core/ansari.d.ts +9 -0
- package/dist/htest/core/ansari.js +21 -1
- package/dist/htest/core/kolmogorov.d.ts +25 -0
- package/dist/htest/core/kolmogorov.js +123 -0
- package/dist/htest/core/mantelhaen.js +6 -4
- package/dist/htest/core/shapiro.d.ts +1 -1
- package/dist/htest/core/shapiro.js +5 -1
- package/dist/htest/dunnett.js +14 -5
- package/dist/htest/effectSize.d.ts +2 -0
- package/dist/htest/effectSize.js +91 -29
- package/dist/htest/fisherTest.d.ts +2 -2
- package/dist/htest/fisherTest.js +36 -18
- package/dist/htest/groups.d.ts +7 -0
- package/dist/htest/groups.js +21 -4
- package/dist/htest/ksTest.d.ts +3 -1
- package/dist/htest/ksTest.js +23 -2
- package/dist/htest/leveneTest.js +19 -3
- package/dist/htest/mantelhaenTest.js +125 -25
- package/dist/htest/mcnemarTest.js +32 -11
- package/dist/htest/multipleComparisons.d.ts +8 -1
- package/dist/htest/multipleComparisons.js +44 -21
- package/dist/htest/normalityTests.js +44 -10
- package/dist/htest/onewayTest.js +96 -5
- package/dist/htest/pAdjust.d.ts +3 -2
- package/dist/htest/pAdjust.js +38 -6
- package/dist/htest/pairwise.d.ts +1 -1
- package/dist/htest/pairwise.js +17 -15
- package/dist/htest/poissonTest.d.ts +1 -1
- package/dist/htest/poissonTest.js +111 -59
- package/dist/htest/polycor.js +27 -7
- package/dist/htest/power.d.ts +11 -1
- package/dist/htest/power.js +112 -8
- package/dist/htest/propTest.js +21 -4
- package/dist/htest/pwr.js +121 -24
- package/dist/htest/rankTests.js +29 -5
- package/dist/htest/tTest.js +44 -21
- package/dist/htest/trendTests.d.ts +7 -3
- package/dist/htest/trendTests.js +114 -20
- package/dist/htest/types.d.ts +5 -0
- package/dist/htest/types.js +7 -0
- package/dist/htest/varTest.js +45 -14
- package/dist/htest/wilcoxTest.js +114 -21
- package/dist/integrate/quadpack.js +27 -5
- package/dist/internal/covmat.d.ts +5 -0
- package/dist/internal/covmat.js +20 -0
- package/dist/internal/ddexp.d.ts +15 -1
- package/dist/internal/ddexp.js +59 -6
- package/dist/internal/discrete.d.ts +14 -0
- package/dist/internal/discrete.js +78 -5
- package/dist/internal/extremes.d.ts +9 -0
- package/dist/internal/extremes.js +24 -0
- package/dist/internal/fround.js +13 -4
- package/dist/internal/integer.d.ts +9 -0
- package/dist/internal/integer.js +12 -0
- package/dist/internal/invert.js +15 -2
- package/dist/internal/scaledInverse.d.ts +10 -0
- package/dist/internal/scaledInverse.js +22 -0
- package/dist/internal/seq.js +15 -2
- package/dist/internal/summary.d.ts +90 -0
- package/dist/internal/summary.js +458 -39
- package/dist/internal/uniroot.d.ts +7 -0
- package/dist/internal/uniroot.js +28 -3
- package/dist/linalg/basic.d.ts +3 -1
- package/dist/linalg/basic.js +51 -7
- package/dist/linalg/chol.js +4 -1
- package/dist/linalg/dot.d.ts +29 -0
- package/dist/linalg/dot.js +132 -0
- package/dist/linalg/eigen.d.ts +6 -1
- package/dist/linalg/eigen.js +71 -14
- package/dist/linalg/expm.d.ts +3 -2
- package/dist/linalg/expm.js +109 -15
- package/dist/linalg/kappa.js +58 -10
- package/dist/linalg/lu.d.ts +2 -1
- package/dist/linalg/lu.js +35 -5
- package/dist/linalg/matrix.d.ts +14 -0
- package/dist/linalg/matrix.js +24 -0
- package/dist/linalg/ops.js +60 -13
- package/dist/linalg/qr.d.ts +2 -1
- package/dist/linalg/qr.js +91 -23
- package/dist/linalg/schur.js +11 -3
- package/dist/linalg/solve.d.ts +6 -1
- package/dist/linalg/solve.js +147 -26
- package/dist/linalg/svd.d.ts +9 -2
- package/dist/linalg/svd.js +29 -11
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +4 -4
- package/dist/models/anovaSequential.d.ts +16 -1
- package/dist/models/anovaSequential.js +124 -25
- package/dist/models/aovEz.js +140 -30
- package/dist/models/aovStrata.js +55 -22
- package/dist/models/carAnova.d.ts +1 -1
- package/dist/models/carAnova.js +83 -32
- package/dist/models/coxph.js +148 -66
- package/dist/models/estimable.d.ts +15 -0
- package/dist/models/estimable.js +68 -0
- package/dist/models/formula.d.ts +1 -1
- package/dist/models/formula.js +26 -8
- package/dist/models/glm.d.ts +35 -5
- package/dist/models/glm.js +398 -55
- package/dist/models/glmAnova.js +84 -13
- package/dist/models/glmConfint.d.ts +1 -1
- package/dist/models/glmConfint.js +115 -27
- package/dist/models/glmFamily.d.ts +10 -0
- package/dist/models/glmFamily.js +244 -40
- package/dist/models/lm.d.ts +12 -1
- package/dist/models/lm.js +235 -36
- package/dist/models/lmer.d.ts +20 -1
- package/dist/models/lmer.js +109 -27
- package/dist/models/lmerAnova.js +37 -4
- package/dist/models/lmerHypotheses.d.ts +6 -2
- package/dist/models/lmerHypotheses.js +14 -2
- package/dist/models/lmerTest.d.ts +9 -2
- package/dist/models/lmerTest.js +64 -19
- package/dist/models/mauchly.d.ts +4 -1
- package/dist/models/mauchly.js +34 -13
- package/dist/models/mixedStructure.js +6 -0
- package/dist/models/modelFrame.js +8 -2
- package/dist/models/modelMatrix.d.ts +3 -1
- package/dist/models/modelMatrix.js +40 -15
- package/dist/models/scaledTables.d.ts +8 -0
- package/dist/models/scaledTables.js +6 -0
- package/dist/models/survival.d.ts +6 -1
- package/dist/models/survival.js +67 -27
- package/dist/models/tiedTimes.d.ts +2 -0
- package/dist/models/tiedTimes.js +34 -0
- package/dist/numerics/deriv.d.ts +1 -1
- package/dist/numerics/deriv.js +64 -8
- package/dist/numerics/integrate.d.ts +9 -1
- package/dist/numerics/integrate.js +103 -16
- package/dist/numerics/interp.d.ts +8 -2
- package/dist/numerics/interp.js +352 -50
- package/dist/numerics/ode.js +55 -1
- package/dist/numerics.js +2 -2
- package/dist/optim/localmin.js +4 -0
- package/dist/optim/optim.d.ts +3 -1
- package/dist/optim/optim.js +80 -8
- package/dist/random/beta.js +53 -4
- package/dist/random/binomial.d.ts +14 -3
- package/dist/random/binomial.js +59 -24
- package/dist/random/continuous.js +33 -5
- package/dist/random/extra.js +42 -9
- package/dist/random/gamma.d.ts +4 -1
- package/dist/random/gamma.js +36 -8
- package/dist/random/hyper.js +9 -6
- package/dist/random/mt.js +17 -2
- package/dist/random/poisson.js +26 -3
- package/dist/random/r2dtable.d.ts +8 -1
- package/dist/random/r2dtable.js +24 -3
- package/dist/random/rank.d.ts +2 -0
- package/dist/random/rank.js +44 -4
- package/dist/random/sample.d.ts +12 -2
- package/dist/random/sample.js +57 -20
- package/dist/random/streams.js +4 -2
- package/dist/rstats.js +14 -14
- package/dist/special/besselIK.d.ts +12 -0
- package/dist/special/besselIK.js +168 -23
- package/dist/special/besselJY.d.ts +11 -1
- package/dist/special/besselJY.js +127 -19
- package/dist/special/besselSeries.d.ts +27 -0
- package/dist/special/besselSeries.js +45 -2
- package/dist/special/beta.js +4 -1
- package/dist/special/choose.js +17 -8
- package/dist/special/dd.js +122 -18
- package/dist/special/extra.js +14 -2
- package/dist/special/gamma.js +11 -2
- package/dist/special/incbet.js +30 -4
- package/dist/special/incbetTemme.d.ts +7 -0
- package/dist/special/incbetTemme.js +45 -12
- package/dist/special/loader.d.ts +1 -1
- package/dist/special/loader.js +117 -20
- package/dist/special/log1pmx.js +4 -0
- package/dist/special.js +2 -2
- package/dist/tests.js +11 -11
- package/llms.txt +12 -6
- package/package.json +1 -1
- package/dist/chunks/chunk-3THFTB36.js +0 -2
- package/dist/chunks/chunk-3TSWYE5L.js +0 -2
- package/dist/chunks/chunk-3WPU6LGK.js +0 -2
- package/dist/chunks/chunk-5ITR67MB.js +0 -2
- package/dist/chunks/chunk-5NRFU6F6.js +0 -2
- package/dist/chunks/chunk-E2LCSVQV.js +0 -2
- package/dist/chunks/chunk-FCNVTIPJ.js +0 -2
- package/dist/chunks/chunk-FKAKALOZ.js +0 -2
- package/dist/chunks/chunk-HD73UKPT.js +0 -2
- package/dist/chunks/chunk-IUULP3LE.js +0 -2
- package/dist/chunks/chunk-JQG3YQOC.js +0 -2
- package/dist/chunks/chunk-KT66SB7R.js +0 -2
- package/dist/chunks/chunk-MAUAOQG3.js +0 -2
- package/dist/chunks/chunk-MDYE7QP2.js +0 -2
- package/dist/chunks/chunk-NM3Z2UBQ.js +0 -2
- package/dist/chunks/chunk-PMJI5QO6.js +0 -3
- package/dist/chunks/chunk-UF7KOTHF.js +0 -3
- package/dist/chunks/chunk-UOE57JGT.js +0 -2
- package/dist/chunks/chunk-USPEBXSR.js +0 -2
- package/dist/chunks/chunk-ZIX7NYQF.js +0 -2
package/dist/models/glm.js
CHANGED
|
@@ -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 {
|
|
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
|
-
|
|
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) =>
|
|
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
|
|
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
|
-
|
|
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 =
|
|
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]
|
|
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 =
|
|
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
|
|
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
|
|
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
|
-
|
|
342
|
-
|
|
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
|
-
/**
|
|
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
|
-
|
|
398
|
-
|
|
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(
|
|
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
|
|
420
|
-
const
|
|
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 =
|
|
424
|
-
const statistic =
|
|
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
|
-
|
|
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
|
-
|
|
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:
|
|
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) => (
|
|
749
|
+
return y.map((v, i) => pearsonResidual(fam, v, mu[i], w[i]));
|
|
467
750
|
case "deviance":
|
|
468
|
-
|
|
469
|
-
|
|
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(
|
|
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
|
-
|
|
527
|
-
const
|
|
528
|
-
const
|
|
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(
|
|
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
|
-
|
|
548
|
-
const
|
|
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
|
|
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(
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
600
|
-
|
|
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
|
}
|