@numero-uno-jpn/rstats 1.16.0 → 1.18.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 +34 -0
- package/README.ja.md +6 -6
- package/README.md +6 -6
- package/dist/causal/mediationProcedures.js +18 -1
- package/dist/causal/moderation.js +11 -2
- package/dist/causal.js +2 -2
- package/dist/chunks/{chunk-J74CELYL.js → chunk-2JB7F646.js} +2 -2
- package/dist/chunks/{chunk-K23MXTLC.js → chunk-3JFRDXN7.js} +2 -2
- package/dist/chunks/chunk-53WQDB3C.js +2 -0
- package/dist/chunks/{chunk-DP6TE35N.js → chunk-5CTWYFMB.js} +2 -2
- package/dist/chunks/chunk-6I23C2YJ.js +2 -0
- package/dist/chunks/{chunk-57BGTHS7.js → chunk-CTZUYKVL.js} +2 -2
- package/dist/chunks/{chunk-UMXY4R4G.js → chunk-EC77KAAM.js} +2 -2
- package/dist/chunks/{chunk-37YHUVXL.js → chunk-FLFNMSHI.js} +2 -2
- package/dist/chunks/{chunk-FCE6N6PI.js → chunk-GEHMND3C.js} +2 -2
- package/dist/chunks/{chunk-W5D6CIZM.js → chunk-GIK34P23.js} +2 -2
- package/dist/chunks/chunk-H6Z7JVSD.js +2 -0
- package/dist/chunks/{chunk-HOH5KGSU.js → chunk-HG4LJBNV.js} +2 -2
- package/dist/chunks/chunk-HGAEVPVS.js +2 -0
- package/dist/chunks/{chunk-ISOLPXQV.js → chunk-HMLYEFQN.js} +2 -2
- package/dist/chunks/chunk-HRRCC2BD.js +2 -0
- package/dist/chunks/chunk-IBHMM2SL.js +2 -0
- package/dist/chunks/chunk-ICDW3I2F.js +2 -0
- package/dist/chunks/{chunk-6DP2U23T.js → chunk-IKMW63BE.js} +2 -2
- package/dist/chunks/{chunk-KSN6A4OK.js → chunk-IOJVFYHW.js} +2 -2
- package/dist/chunks/chunk-IW4S634O.js +2 -0
- package/dist/chunks/{chunk-ZZ6KYMBW.js → chunk-JF4PXFJE.js} +2 -2
- package/dist/chunks/{chunk-NQWFURFV.js → chunk-JPWYGTUN.js} +2 -2
- package/dist/chunks/{chunk-XMA2NWYX.js → chunk-KJMLQHCY.js} +1 -1
- package/dist/chunks/chunk-KVJBCT3D.js +2 -0
- package/dist/chunks/chunk-LCIX76FR.js +2 -0
- package/dist/chunks/chunk-LY5XGFPU.js +2 -0
- package/dist/chunks/{chunk-JYE3T7FS.js → chunk-MKZH65DK.js} +2 -2
- package/dist/chunks/{chunk-B5QE2FDM.js → chunk-MVPHISOV.js} +1 -1
- package/dist/chunks/chunk-MXZ64QME.js +2 -0
- package/dist/chunks/{chunk-XAMWBGTP.js → chunk-N7BUE54L.js} +2 -2
- package/dist/chunks/{chunk-244M5C2B.js → chunk-NDZVVNBB.js} +2 -2
- package/dist/chunks/{chunk-AC22FPFB.js → chunk-NOTJ45G3.js} +2 -2
- package/dist/chunks/{chunk-MNPZUMPL.js → chunk-QUD3374N.js} +2 -2
- package/dist/chunks/{chunk-AIII5VRA.js → chunk-RXYZQ3UX.js} +2 -2
- package/dist/chunks/{chunk-LHMG6Q5C.js → chunk-SCFFHEDZ.js} +2 -2
- package/dist/chunks/{chunk-BHNDCNWM.js → chunk-V6FMGGUV.js} +2 -2
- package/dist/chunks/{chunk-FHHI3PYN.js → chunk-VATAUY7N.js} +2 -2
- package/dist/chunks/chunk-W5M3R4NH.js +2 -0
- package/dist/chunks/{chunk-H6WBOIFZ.js → chunk-WYVUCQO3.js} +1 -1
- package/dist/chunks/{chunk-7MFMRNMT.js → chunk-XQCHC3SH.js} +1 -1
- package/dist/chunks/{chunk-IPMC3VOC.js → chunk-XUMVTGMM.js} +2 -2
- package/dist/chunks/{chunk-6MHLWTBF.js → chunk-YXMHWS5R.js} +2 -2
- package/dist/chunks/{chunk-K5IP4ZJ5.js → chunk-Z33Q545U.js} +2 -2
- package/dist/descriptive/qcc.d.ts +320 -0
- package/dist/descriptive/qcc.js +524 -0
- package/dist/descriptive/qccTools.d.ts +301 -0
- package/dist/descriptive/qccTools.js +390 -0
- package/dist/descriptive.js +2 -2
- package/dist/distributions.js +2 -2
- package/dist/entries/descriptive.d.ts +2 -0
- package/dist/entries/descriptive.js +2 -0
- package/dist/entries/regression.d.ts +4 -0
- package/dist/entries/regression.js +8 -0
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +2 -2
- package/dist/models/betareg.d.ts +278 -0
- package/dist/models/betareg.js +600 -0
- package/dist/models/bradleyterry.d.ts +188 -0
- package/dist/models/bradleyterry.js +533 -0
- package/dist/models/loglin.d.ts +186 -0
- package/dist/models/loglin.js +349 -0
- package/dist/models/survreg.d.ts +48 -0
- package/dist/models/survreg.js +29 -6
- package/dist/models/tobit.d.ts +132 -0
- package/dist/models/tobit.js +183 -0
- package/dist/multivariate.js +2 -2
- package/dist/numerics.js +2 -2
- package/dist/regression.js +3 -3
- package/dist/rstats.js +17 -17
- package/dist/special.js +2 -2
- package/dist/tests.js +15 -15
- package/dist/timeseries.js +2 -2
- package/package.json +1 -1
- package/dist/chunks/chunk-3L333CTJ.js +0 -2
- package/dist/chunks/chunk-3RO5FWJ5.js +0 -2
- package/dist/chunks/chunk-3VKN6K3P.js +0 -2
- package/dist/chunks/chunk-7IU5OE5I.js +0 -2
- package/dist/chunks/chunk-GKDA5W53.js +0 -2
- package/dist/chunks/chunk-IVJTWTGV.js +0 -2
- package/dist/chunks/chunk-NCVEJDRI.js +0 -2
- package/dist/chunks/chunk-P3Q6IJMR.js +0 -2
- package/dist/chunks/chunk-PIWXBWMD.js +0 -2
- package/dist/chunks/chunk-QBY63DGM.js +0 -2
- package/dist/chunks/chunk-RV4SUKXV.js +0 -2
- package/dist/chunks/chunk-SALMA4XX.js +0 -2
- package/dist/chunks/chunk-ZTZX2UYP.js +0 -2
|
@@ -0,0 +1,600 @@
|
|
|
1
|
+
// Beta regression: betareg's betareg (maximum likelihood, bias-corrected and bias-reduced) with summary, confint,
|
|
2
|
+
// predict and residuals. Behaviour: oracle/tobit-betareg-loglin-behaviour.md (clean room: from betareg's
|
|
3
|
+
// documentation, the papers it cites and the output of R; no source of R or of a package was read). Written for
|
|
4
|
+
// rStats.js.
|
|
5
|
+
import { pnorm, qnorm } from "../distributions/normal.js";
|
|
6
|
+
import { dbeta1, pbeta1, qbeta1 } from "../distributions/beta.js";
|
|
7
|
+
import { digamma, trigamma, psigamma } from "../special/psigamma.js";
|
|
8
|
+
import { parseFormula } from "./formula.js";
|
|
9
|
+
import { design } from "./modelMatrix.js";
|
|
10
|
+
import { dataRowCount } from "./inputRows.js";
|
|
11
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
12
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
13
|
+
const BETAREG_KEYS = ["link", "linkPhi", "type", "weights", "contrasts", "maxit"];
|
|
14
|
+
const BETAREG_CONFINT_KEYS = ["level"];
|
|
15
|
+
const BETAREG_PREDICT_KEYS = ["newdata", "type", "at", "elementwise"];
|
|
16
|
+
const BETAREG_RESIDUALS_KEYS = ["type"];
|
|
17
|
+
/** The standard errors of a fit, from the scaled covariance (exact where the variances leave the doubles) */
|
|
18
|
+
const standardErrors = new WeakMap();
|
|
19
|
+
const EPS = 2 ** -52;
|
|
20
|
+
/** A probability kept within (0, 1): the least double and the largest double below 1 at the ends */
|
|
21
|
+
const inUnit = (p) => Math.min(Math.max(p, Number.MIN_VALUE), 1 - 2 ** -53);
|
|
22
|
+
function meanLink(name) {
|
|
23
|
+
switch (name) {
|
|
24
|
+
case "logit": return {
|
|
25
|
+
fun: (m) => Math.log(m / (1 - m)),
|
|
26
|
+
inv: (e) => inUnit(e >= 0 ? 1 / (1 + Math.exp(-e)) : Math.exp(e) / (1 + Math.exp(e))),
|
|
27
|
+
d1: (e) => { const z = Math.exp(-Math.abs(e)); return z / ((1 + z) * (1 + z)); },
|
|
28
|
+
d2: (e) => { const z = Math.exp(-Math.abs(e)), m = 1 / (1 + z), d = z / ((1 + z) * (1 + z)); return d * (e >= 0 ? 1 - 2 * m : 2 * m - 1); },
|
|
29
|
+
};
|
|
30
|
+
case "probit": return {
|
|
31
|
+
fun: (m) => qnorm(m), inv: (e) => inUnit(pnorm(e)),
|
|
32
|
+
d1: (e) => Math.exp(-0.5 * e * e) / Math.sqrt(2 * Math.PI), d2: (e) => -e * Math.exp(-0.5 * e * e) / Math.sqrt(2 * Math.PI),
|
|
33
|
+
};
|
|
34
|
+
// cloglog and loglog: R's bias correction uses the second derivative of the inverse link floored at 2.2e-16 where
|
|
35
|
+
// it is negative (read off R's bias in intercept-only models, experiments/regression117-betareg-d2b.R; logit's
|
|
36
|
+
// negative values are used as they are). Kept as R: it changes BC and BR estimates by about 1e-4
|
|
37
|
+
case "cloglog": return {
|
|
38
|
+
fun: (m) => Math.log(-Math.log1p(-m)), inv: (e) => inUnit(-Math.expm1(-Math.exp(e))),
|
|
39
|
+
d1: (e) => Math.exp(e - Math.exp(e)), d2: (e) => Math.max(Math.exp(e - Math.exp(e)) * (1 - Math.exp(e)), EPS),
|
|
40
|
+
};
|
|
41
|
+
case "cauchit": return {
|
|
42
|
+
fun: (m) => Math.tan(Math.PI * (m - 0.5)), inv: (e) => inUnit(0.5 + Math.atan(e) / Math.PI),
|
|
43
|
+
d1: (e) => 1 / (Math.PI * (1 + e * e)), d2: (e) => -2 * e / (Math.PI * (1 + e * e) * (1 + e * e)),
|
|
44
|
+
};
|
|
45
|
+
// no clamp: a mean above 1 makes the log-likelihood NaN, as in R
|
|
46
|
+
case "log": return { fun: Math.log, inv: Math.exp, d1: Math.exp, d2: Math.exp };
|
|
47
|
+
case "loglog": return {
|
|
48
|
+
fun: (m) => -Math.log(-Math.log(m)), inv: (e) => inUnit(Math.exp(-Math.exp(-e))),
|
|
49
|
+
d1: (e) => Math.exp(-e - Math.exp(-e)), d2: (e) => Math.max(Math.exp(-e - Math.exp(-e)) * (Math.exp(-e) - 1), EPS),
|
|
50
|
+
};
|
|
51
|
+
default:
|
|
52
|
+
throw new RangeError("'arg' should be one of “logit”, “probit”, “cloglog”, “cauchit”, “log”, “loglog”");
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
function phiLink(name) {
|
|
56
|
+
switch (name) {
|
|
57
|
+
case "identity": return { fun: (m) => m, inv: (e) => e, d1: () => 1, d2: () => 0 };
|
|
58
|
+
case "log": return { fun: Math.log, inv: Math.exp, d1: Math.exp, d2: Math.exp };
|
|
59
|
+
case "sqrt": return { fun: Math.sqrt, inv: (e) => e * e, d1: (e) => 2 * e, d2: () => 2 };
|
|
60
|
+
default:
|
|
61
|
+
throw new RangeError("'arg' should be one of “identity”, “log”, “sqrt”");
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
function evaluate(th, m, l1, l2) {
|
|
65
|
+
const { x, z, y, weights } = m, p = x[0].length, q = z[0].length, k = p + q;
|
|
66
|
+
const score = new Array(k).fill(0), info = Array.from({ length: k }, () => new Array(k).fill(0));
|
|
67
|
+
const mu = [], phi = [], e1s = [], e2s = [];
|
|
68
|
+
let ll = 0;
|
|
69
|
+
for (let i = 0; i < y.length; i++) {
|
|
70
|
+
const xi = x[i], zi = z[i], w = weights[i];
|
|
71
|
+
let e1 = 0, e2 = 0;
|
|
72
|
+
for (let j = 0; j < p; j++)
|
|
73
|
+
e1 += xi[j] * th[j];
|
|
74
|
+
for (let j = 0; j < q; j++)
|
|
75
|
+
e2 += zi[j] * th[p + j];
|
|
76
|
+
const m1 = l1.inv(e1), f = l2.inv(e2);
|
|
77
|
+
mu.push(m1);
|
|
78
|
+
phi.push(f);
|
|
79
|
+
e1s.push(e1);
|
|
80
|
+
e2s.push(e2);
|
|
81
|
+
if (w === 0)
|
|
82
|
+
continue;
|
|
83
|
+
const a = m1 * f, b = (1 - m1) * f, yi = y[i];
|
|
84
|
+
ll += w * dbeta1(yi, a, b, true);
|
|
85
|
+
const d1 = l1.d1(e1), d2 = l2.d1(e2);
|
|
86
|
+
const ys = Math.log(yi) - Math.log1p(-yi), ms = digamma(a) - digamma(b);
|
|
87
|
+
const s1 = w * f * (ys - ms) * d1, s2 = w * (m1 * (ys - ms) + Math.log1p(-yi) - digamma(b) + digamma(f)) * d2;
|
|
88
|
+
const t1 = trigamma(a), t2 = trigamma(b);
|
|
89
|
+
const W = w * f * f * (t1 + t2) * d1 * d1, C = w * f * (t1 * m1 - t2 * (1 - m1)) * d1 * d2;
|
|
90
|
+
const D = w * (t1 * m1 * m1 + t2 * (1 - m1) * (1 - m1) - trigamma(f)) * d2 * d2;
|
|
91
|
+
for (let j = 0; j < p; j++)
|
|
92
|
+
score[j] += s1 * xi[j];
|
|
93
|
+
for (let j = 0; j < q; j++)
|
|
94
|
+
score[p + j] += s2 * zi[j];
|
|
95
|
+
for (let r = 0; r < k; r++) {
|
|
96
|
+
const ur = r < p ? xi[r] : zi[r - p];
|
|
97
|
+
for (let c = 0; c <= r; c++) {
|
|
98
|
+
const uc = c < p ? xi[c] : zi[c - p];
|
|
99
|
+
const v = r < p ? W : c < p ? C : D;
|
|
100
|
+
info[r][c] += v * ur * uc;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
for (let r = 0; r < k; r++)
|
|
105
|
+
for (let c = r + 1; c < k; c++)
|
|
106
|
+
info[r][c] = info[c][r];
|
|
107
|
+
return { ll, score, info, mu, phi, e1: e1s, e2: e2s };
|
|
108
|
+
}
|
|
109
|
+
/** Inverse of a symmetric positive definite matrix (Cholesky); null if it is not. */
|
|
110
|
+
function spdInverse(A) {
|
|
111
|
+
const n = A.length, L = A.map(() => new Array(n).fill(0));
|
|
112
|
+
for (let i = 0; i < n; i++)
|
|
113
|
+
for (let j = 0; j <= i; j++) {
|
|
114
|
+
let s = A[i][j];
|
|
115
|
+
for (let k = 0; k < j; k++)
|
|
116
|
+
s -= L[i][k] * L[j][k];
|
|
117
|
+
if (i === j) {
|
|
118
|
+
if (!(s > 0))
|
|
119
|
+
return null;
|
|
120
|
+
L[i][i] = Math.sqrt(s);
|
|
121
|
+
}
|
|
122
|
+
else
|
|
123
|
+
L[i][j] = s / L[j][j];
|
|
124
|
+
}
|
|
125
|
+
const inv = A.map(() => new Array(n).fill(0));
|
|
126
|
+
for (let c = 0; c < n; c++) {
|
|
127
|
+
const zc = new Array(n).fill(0);
|
|
128
|
+
for (let i = 0; i < n; i++) {
|
|
129
|
+
let s = i === c ? 1 : 0;
|
|
130
|
+
for (let k = 0; k < i; k++)
|
|
131
|
+
s -= L[i][k] * zc[k];
|
|
132
|
+
zc[i] = s / L[i][i];
|
|
133
|
+
}
|
|
134
|
+
for (let i = n - 1; i >= 0; i--) {
|
|
135
|
+
let s = zc[i];
|
|
136
|
+
for (let k = i + 1; k < n; k++)
|
|
137
|
+
s -= L[k][i] * inv[k][c];
|
|
138
|
+
inv[i][c] = s / L[i][i];
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
return inv;
|
|
142
|
+
}
|
|
143
|
+
const matVec = (A, v) => A.map((row) => row.reduce((s, a, j) => s + a * v[j], 0));
|
|
144
|
+
/** The Kosmidis-Firth adjustment A(theta) = 1/2 tr(F^-1 (P_t + Q_t)) (see the behaviour file for the closed forms). */
|
|
145
|
+
function adjustment(th, m, l1, l2, Finv) {
|
|
146
|
+
const { x, z, y, weights } = m, p = x[0].length, q = z[0].length, k = p + q;
|
|
147
|
+
const A = new Array(k).fill(0);
|
|
148
|
+
for (let i = 0; i < y.length; i++) {
|
|
149
|
+
const w = weights[i];
|
|
150
|
+
if (w === 0)
|
|
151
|
+
continue;
|
|
152
|
+
const xi = x[i], zi = z[i];
|
|
153
|
+
let e1 = 0, e2 = 0;
|
|
154
|
+
for (let j = 0; j < p; j++)
|
|
155
|
+
e1 += xi[j] * th[j];
|
|
156
|
+
for (let j = 0; j < q; j++)
|
|
157
|
+
e2 += zi[j] * th[p + j];
|
|
158
|
+
const mu = l1.inv(e1), f = l2.inv(e2), a = mu * f, b = (1 - mu) * f;
|
|
159
|
+
const d1 = l1.d1(e1), d2 = l2.d1(e2), d1p = l1.d2(e1), d2p = l2.d2(e2);
|
|
160
|
+
// the scores in (eta1, eta2) are C (L - E L), L = (log y, log(1 - y))
|
|
161
|
+
const C = [[f * d1, -f * d1], [mu * d2, (1 - mu) * d2]];
|
|
162
|
+
const tf = trigamma(f), S = [[trigamma(a) - tf, -tf], [-tf, trigamma(b) - tf]];
|
|
163
|
+
const pf = psigamma(f, 2), kap = (r, s, t) => {
|
|
164
|
+
const ones = r + s + t;
|
|
165
|
+
return ones === 0 ? psigamma(a, 2) - pf : ones === 3 ? psigamma(b, 2) - pf : -pf;
|
|
166
|
+
};
|
|
167
|
+
// dC_a / deta_b
|
|
168
|
+
const dC = [[[f * d1p, -f * d1p], [d2 * d1, -d2 * d1]], [[d1 * d2, -d1 * d2], [mu * d2p, (1 - mu) * d2p]]];
|
|
169
|
+
const SC = [0, 1].map((c) => [0, 1].map((r) => S[r][0] * C[c][0] + S[r][1] * C[c][1])); // Sigma C_c'
|
|
170
|
+
// G = J F^-1 J' (2 x 2)
|
|
171
|
+
const J0 = [...xi, ...new Array(q).fill(0)], J1 = [...new Array(p).fill(0), ...zi];
|
|
172
|
+
const FJ0 = matVec(Finv, J0), FJ1 = matVec(Finv, J1);
|
|
173
|
+
const G = [[dot(J0, FJ0), dot(J0, FJ1)], [dot(J1, FJ0), dot(J1, FJ1)]];
|
|
174
|
+
for (let c = 0; c < 2; c++) {
|
|
175
|
+
let tr = 0;
|
|
176
|
+
for (let r = 0; r < 2; r++)
|
|
177
|
+
for (let s = 0; s < 2; s++) {
|
|
178
|
+
let M = 0;
|
|
179
|
+
for (let u = 0; u < 2; u++)
|
|
180
|
+
for (let v = 0; v < 2; v++)
|
|
181
|
+
for (let t = 0; t < 2; t++)
|
|
182
|
+
M += C[r][u] * C[s][v] * C[c][t] * kap(u, v, t);
|
|
183
|
+
const Q = dC[r][s][0] * SC[c][0] + dC[r][s][1] * SC[c][1];
|
|
184
|
+
tr += (M + Q) * G[r][s];
|
|
185
|
+
}
|
|
186
|
+
const Jc = c === 0 ? J0 : J1;
|
|
187
|
+
for (let t = 0; t < k; t++)
|
|
188
|
+
A[t] += 0.5 * w * tr * Jc[t];
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
return A;
|
|
192
|
+
}
|
|
193
|
+
/** Columns other than an intercept (all 1) centred (when there is one) and divided by a power of 2; `map` takes the
|
|
194
|
+
* coefficients of the scaled columns to those of the original ones. */
|
|
195
|
+
function scaleColumns(m) {
|
|
196
|
+
const k = m[0]?.length ?? 0, n = m.length;
|
|
197
|
+
const icpt = Array.from({ length: k }, (_, j) => m.every((r) => r[j] === 1)).indexOf(true);
|
|
198
|
+
const centre = Array.from({ length: k }, (_, j) => (j === icpt || icpt < 0 ? 0 : m.reduce((s, r) => s + r[j], 0) / n));
|
|
199
|
+
const exps = Array.from({ length: k }, (_, j) => {
|
|
200
|
+
if (j === icpt)
|
|
201
|
+
return 0;
|
|
202
|
+
let top = 0;
|
|
203
|
+
for (const r of m)
|
|
204
|
+
top = Math.max(top, Math.abs(r[j] - centre[j]));
|
|
205
|
+
return top > 0 && Number.isFinite(top) ? Math.floor(Math.log2(top)) : 0;
|
|
206
|
+
});
|
|
207
|
+
const scaled = m.map((r) => r.map((v, j) => (j === icpt ? v : (v - centre[j]) * 2 ** -exps[j])));
|
|
208
|
+
// the 2^-e factor as two halves, so that e near +-1074 does not under- or overflow
|
|
209
|
+
const pw = (e) => 2 ** Math.trunc(-e / 2) * 2 ** (-e - Math.trunc(-e / 2));
|
|
210
|
+
const map = Array.from({ length: k }, (_, a) => Array.from({ length: k }, (_, b) => {
|
|
211
|
+
if (a === b)
|
|
212
|
+
return a === icpt ? 1 : pw(exps[a]);
|
|
213
|
+
if (a === icpt && b !== icpt)
|
|
214
|
+
return -centre[b] * pw(exps[b]);
|
|
215
|
+
return 0;
|
|
216
|
+
}));
|
|
217
|
+
return { scaled, map };
|
|
218
|
+
}
|
|
219
|
+
function blockDiagonal(a, b) {
|
|
220
|
+
const p = a.length, q = b.length;
|
|
221
|
+
return Array.from({ length: p + q }, (_, i) => Array.from({ length: p + q }, (_, j) => i < p && j < p ? a[i][j] : i >= p && j >= p ? b[i - p][j - p] : 0));
|
|
222
|
+
}
|
|
223
|
+
const dot = (a, b) => a.reduce((s, v, j) => s + v * b[j], 0);
|
|
224
|
+
/** Splits "y ~ x | z" at its top-level bar. */
|
|
225
|
+
function splitBar(formula) {
|
|
226
|
+
let depth = 0;
|
|
227
|
+
for (let i = 0; i < formula.length; i++) {
|
|
228
|
+
const ch = formula[i];
|
|
229
|
+
if (ch === "(")
|
|
230
|
+
depth++;
|
|
231
|
+
else if (ch === ")")
|
|
232
|
+
depth--;
|
|
233
|
+
else if (ch === "|" && depth === 0)
|
|
234
|
+
return [formula.slice(0, i), formula.slice(i + 1)];
|
|
235
|
+
}
|
|
236
|
+
return [formula, undefined];
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Beta regression for rates and proportions in (0, 1): the mean linked to a linear predictor, the precision phi
|
|
240
|
+
* constant (`y ~ x`) or linked to its own regressors (`y ~ x | z`), fitted by maximum likelihood, or bias-corrected or
|
|
241
|
+
* bias-reduced (Kosmidis and Firth 2010). Equivalent to R's `betareg::betareg()`.
|
|
242
|
+
*
|
|
243
|
+
* The response must lie strictly between 0 and 1 (R fits an extended-support distribution to 0 and 1; rStats.js does
|
|
244
|
+
* not). rStats.js maximises the likelihood to convergence by Fisher scoring; R stops its optimiser slightly earlier,
|
|
245
|
+
* so estimates agree with R's to about 1e-7 relative.
|
|
246
|
+
* @example
|
|
247
|
+
* ```ts
|
|
248
|
+
* const fit = betareg("y ~ x", { y: [0.21, 0.35, 0.3, 0.52, 0.48, 0.66, 0.6, 0.81], x: [1, 2, 3, 4, 5, 6, 7, 8] });
|
|
249
|
+
* fit.coefficients; // { mean: [-1.5409, 0.33424], precision: [62.03] }
|
|
250
|
+
* ```
|
|
251
|
+
* @category Regression
|
|
252
|
+
*/
|
|
253
|
+
export function betareg(formula, data, options = {}) {
|
|
254
|
+
checkOptions(options, BETAREG_KEYS, "betareg"); // generated: option-keys.mjs
|
|
255
|
+
const type = options.type ?? "ML";
|
|
256
|
+
if (type !== "ML" && type !== "BC" && type !== "BR")
|
|
257
|
+
throw new RangeError("'arg' should be one of “ML”, “BC”, “BR”");
|
|
258
|
+
const linkName = options.link ?? "logit", l1 = meanLink(linkName);
|
|
259
|
+
const [meanPart, precPart] = splitBar(formula);
|
|
260
|
+
const linkPhiName = options.linkPhi ?? (precPart === undefined ? "identity" : "log"), l2 = phiLink(linkPhiName);
|
|
261
|
+
const maxit = options.maxit ?? 5000;
|
|
262
|
+
if (!Number.isInteger(maxit) || maxit < 1)
|
|
263
|
+
throw new RangeError("'maxit' must be a positive integer");
|
|
264
|
+
const parsed = parseFormula(meanPart);
|
|
265
|
+
if (parsed.response === undefined)
|
|
266
|
+
throw new TypeError("the formula must have a response");
|
|
267
|
+
const parsedZ = precPart === undefined ? undefined : parseFormula(`~ ${precPart}`);
|
|
268
|
+
const contrasts = (options.contrasts ?? {});
|
|
269
|
+
// the rows: those complete in every variable of both parts
|
|
270
|
+
const zVars = parsedZ === undefined ? [] : design(parsedZ, data, { contrasts }).terms.variables;
|
|
271
|
+
const dOpts = { contrasts, extraVariables: zVars };
|
|
272
|
+
if (options.weights !== undefined)
|
|
273
|
+
dOpts.weights = options.weights;
|
|
274
|
+
const d = design(parsed, data, dOpts);
|
|
275
|
+
const y = d.y;
|
|
276
|
+
if (y === undefined)
|
|
277
|
+
throw new TypeError("the response must be numeric");
|
|
278
|
+
if (y.some((v) => !(v >= 0 && v <= 1)))
|
|
279
|
+
throw new RangeError("invalid dependent variable, all observations must be in [0, 1]");
|
|
280
|
+
if (y.some((v) => v === 0 || v === 1)) {
|
|
281
|
+
throw new RangeError("the responses must lie strictly between 0 and 1: rStats.js fits the beta distribution only (R's betareg switches to the extended-support beta distribution \"xbetax\" for 0 and 1)");
|
|
282
|
+
}
|
|
283
|
+
const rows = d.frame.rows;
|
|
284
|
+
let z, zNames;
|
|
285
|
+
const factorLevels = {};
|
|
286
|
+
d.terms.variables.forEach((v, i) => { const fv = d.frame.variables[i]; if (i > 0 && fv?.kind === "factor")
|
|
287
|
+
factorLevels[v] = fv.levels; });
|
|
288
|
+
if (parsedZ === undefined) {
|
|
289
|
+
z = y.map(() => [1]);
|
|
290
|
+
zNames = ["(Intercept)"];
|
|
291
|
+
}
|
|
292
|
+
else {
|
|
293
|
+
const sub = {};
|
|
294
|
+
for (const v of zVars) {
|
|
295
|
+
const col = data[v];
|
|
296
|
+
if (col !== undefined)
|
|
297
|
+
sub[v] = rows.map((r) => col[r]);
|
|
298
|
+
}
|
|
299
|
+
const dz = design(parsedZ, sub, { contrasts });
|
|
300
|
+
if (dz.frame.rows.length !== rows.length)
|
|
301
|
+
throw new RangeError("the precision model drops rows that the mean model keeps");
|
|
302
|
+
z = dz.x;
|
|
303
|
+
zNames = dz.colNames;
|
|
304
|
+
dz.terms.variables.forEach((v, i) => { const fv = dz.frame.variables[i]; if (fv?.kind === "factor")
|
|
305
|
+
factorLevels[v] = fv.levels; });
|
|
306
|
+
}
|
|
307
|
+
const weights = d.frame.weights ?? y.map(() => 1);
|
|
308
|
+
if (weights.some((v) => !(v >= 0) || !Number.isFinite(v)))
|
|
309
|
+
throw new RangeError("weights must be finite and non-negative");
|
|
310
|
+
const x = d.x, p = x[0]?.length ?? 0, q = z[0].length, k = p + q;
|
|
311
|
+
if (p === 0)
|
|
312
|
+
throw new RangeError("the mean model has no coefficients");
|
|
313
|
+
// the fit is done on columns centred (with an intercept) and divided by a power of 2, so that it does not depend on
|
|
314
|
+
// the scale of a covariate (1e+-300) or on a large common value (1e15 + small differences); the coefficients, their
|
|
315
|
+
// covariance and the bias follow exactly (R fails from 1e150 and from a common value of 1e8: log 28)
|
|
316
|
+
if (weights.filter((w) => w > 0).length < k)
|
|
317
|
+
throw new RangeError("fewer observations than coefficients");
|
|
318
|
+
const sx = scaleColumns(x), sz = scaleColumns(z);
|
|
319
|
+
const model = {
|
|
320
|
+
meanRhs: parsed.rhs, precisionRhs: parsedZ?.rhs, factorLevels, contrasts,
|
|
321
|
+
variables: [...new Set([...d.terms.variables.slice(1), ...zVars])], x, z, y, weights, rows, xScaled: sx.scaled,
|
|
322
|
+
};
|
|
323
|
+
const fitModel = { ...model, x: sx.scaled, z: sz.scaled };
|
|
324
|
+
const back = blockDiagonal(sx.map, sz.map);
|
|
325
|
+
// R's starting values: weighted least squares of g(y) on X; phi from the delta method (Ferrari and Cribari-Neto 2004)
|
|
326
|
+
const gy = y.map((v) => l1.fun(v));
|
|
327
|
+
const XtX = Array.from({ length: p }, (_, a) => Array.from({ length: p }, (_, b) => sx.scaled.reduce((s, r, i) => s + weights[i] * r[a] * r[b], 0)));
|
|
328
|
+
const XtXi = spdInverse(XtX);
|
|
329
|
+
if (XtXi === null)
|
|
330
|
+
throw new RangeError("the mean model's matrix is rank-deficient");
|
|
331
|
+
const beta0 = matVec(XtXi, Array.from({ length: p }, (_, a) => sx.scaled.reduce((s, r, i) => s + weights[i] * r[a] * gy[i], 0)));
|
|
332
|
+
const eta0 = sx.scaled.map((r) => dot(r, beta0));
|
|
333
|
+
const sw = weights.reduce((s, v) => s + v, 0);
|
|
334
|
+
const sse = eta0.reduce((s, e, i) => s + weights[i] * (gy[i] - e) ** 2, 0) / (sw - p);
|
|
335
|
+
let phiSum = 0;
|
|
336
|
+
eta0.forEach((e, i) => { const m = l1.inv(e), s2 = sse * l1.d1(e) ** 2; phiSum += weights[i] * (m * (1 - m) / s2 - 1); });
|
|
337
|
+
// R's phi0 can be negative (weights summing to less than p, responses near 0 or 1, where R still fits): then the
|
|
338
|
+
// method of moments on y
|
|
339
|
+
let phi0 = phiSum / sw;
|
|
340
|
+
if (!(phi0 > 0) || !Number.isFinite(phi0)) {
|
|
341
|
+
const my = y.reduce((s, v, i) => s + weights[i] * v, 0) / sw, vy = y.reduce((s, v, i) => s + weights[i] * (v - my) ** 2, 0) / sw;
|
|
342
|
+
phi0 = vy > 0 && my * (1 - my) / vy - 1 > 0 ? my * (1 - my) / vy - 1 : 1;
|
|
343
|
+
}
|
|
344
|
+
let th = [...beta0, l2.fun(phi0), ...new Array(q - 1).fill(0)];
|
|
345
|
+
let cur = evaluate(th, fitModel, l1, l2);
|
|
346
|
+
if (!Number.isFinite(cur.ll))
|
|
347
|
+
throw new RangeError("initial value in 'vmmin' is not finite");
|
|
348
|
+
// Fisher scoring with step halving
|
|
349
|
+
let iterations = 0, converged = false;
|
|
350
|
+
const fisher = (target, accept) => {
|
|
351
|
+
for (let it = 0; it < maxit; it++) {
|
|
352
|
+
const Fi = spdInverse(cur.info);
|
|
353
|
+
if (Fi === null)
|
|
354
|
+
break;
|
|
355
|
+
const step = matVec(Fi, target(cur, th));
|
|
356
|
+
let t = 1, next, cand = th;
|
|
357
|
+
for (let h = 0; h < 60; h++) {
|
|
358
|
+
cand = th.map((v, j) => v + t * step[j]);
|
|
359
|
+
const e = evaluate(cand, fitModel, l1, l2);
|
|
360
|
+
if (Number.isFinite(e.ll) && e.phi.every((f) => f > 0) && accept(e, cur)) {
|
|
361
|
+
next = e;
|
|
362
|
+
break;
|
|
363
|
+
}
|
|
364
|
+
t /= 2;
|
|
365
|
+
}
|
|
366
|
+
iterations++;
|
|
367
|
+
if (next === undefined)
|
|
368
|
+
break;
|
|
369
|
+
const small = step.every((s, j) => Math.abs(t * s) <= 1e-12 * Math.max(1, Math.abs(th[j])));
|
|
370
|
+
th = cand;
|
|
371
|
+
cur = next;
|
|
372
|
+
if (small) {
|
|
373
|
+
converged = true;
|
|
374
|
+
break;
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
};
|
|
378
|
+
fisher((e) => e.score, (next, prev) => next.ll >= prev.ll - 1e-12 * Math.abs(prev.ll));
|
|
379
|
+
const warnings = [...d.warnings];
|
|
380
|
+
let bias;
|
|
381
|
+
if (type !== "ML") {
|
|
382
|
+
const Fi = spdInverse(cur.info);
|
|
383
|
+
if (Fi === null)
|
|
384
|
+
throw new RangeError("the expected information is singular");
|
|
385
|
+
if (type === "BC") {
|
|
386
|
+
const A = adjustment(th, fitModel, l1, l2, Fi);
|
|
387
|
+
const b = matVec(Fi, A).map((v) => -v);
|
|
388
|
+
th = th.map((v, j) => v - b[j]);
|
|
389
|
+
bias = matVec(back, b);
|
|
390
|
+
cur = evaluate(th, fitModel, l1, l2);
|
|
391
|
+
}
|
|
392
|
+
else {
|
|
393
|
+
converged = false;
|
|
394
|
+
fisher((e, t) => { const Fn = spdInverse(e.info); const A = adjustment(t, fitModel, l1, l2, Fn); return e.score.map((s, j) => s + A[j]); }, () => true);
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
if (!converged && type !== "BC")
|
|
398
|
+
warnings.push("the Fisher scoring did not converge");
|
|
399
|
+
const vcovScaled = spdInverse(cur.info);
|
|
400
|
+
if (vcovScaled === null)
|
|
401
|
+
throw new RangeError("the expected information is singular");
|
|
402
|
+
const vcov = back.map((r) => back.map((c) => r.reduce((acc, v, a) => acc + v * c.reduce((t, u, b2) => t + vcovScaled[a][b2] * u, 0), 0)));
|
|
403
|
+
// the standard errors from the scaled covariance, each row of `back` divided by its largest entry: for a covariate near
|
|
404
|
+
// 1e+-300 the variance (1e-+600) is not a double, the standard error is
|
|
405
|
+
const ses = back.map((r) => {
|
|
406
|
+
const m = Math.max(...r.map(Math.abs));
|
|
407
|
+
if (m === 0)
|
|
408
|
+
return 0;
|
|
409
|
+
const u = r.map((v) => v / m);
|
|
410
|
+
return m * Math.sqrt(Math.max(0, u.reduce((acc, v, a) => acc + v * u.reduce((t, w, b2) => t + vcovScaled[a][b2] * w, 0), 0)));
|
|
411
|
+
});
|
|
412
|
+
th = matVec(back, th);
|
|
413
|
+
// pseudo R^2: squared weighted correlation of eta and g(y)
|
|
414
|
+
const mE = cur.e1.reduce((s, v, i) => s + weights[i] * v, 0) / sw, mY = gy.reduce((s, v, i) => s + weights[i] * v, 0) / sw;
|
|
415
|
+
let sxy = 0, sxx = 0, syy = 0;
|
|
416
|
+
cur.e1.forEach((e, i) => { const w = weights[i]; sxy += w * (e - mE) * (gy[i] - mY); sxx += w * (e - mE) ** 2; syy += w * (gy[i] - mY) ** 2; });
|
|
417
|
+
const nobs = weights.filter((w) => w > 0).length;
|
|
418
|
+
const precisionNames = parsedZ === undefined && linkPhiName === "identity" ? ["(phi)"] : zNames.map((nm) => `(phi)_${nm}`);
|
|
419
|
+
const result = {
|
|
420
|
+
coefficients: { mean: th.slice(0, p), precision: th.slice(p) }, meanNames: d.colNames.slice(), precisionNames,
|
|
421
|
+
names: [...d.colNames, ...precisionNames], vcov, loglik: cur.ll, pseudoRSquared: (sxy * sxy) / (sxx * syy),
|
|
422
|
+
fitted: cur.mu, linearPredictor: cur.e1, precision: cur.phi, link: linkName, linkPhi: linkPhiName, type,
|
|
423
|
+
n: y.length, nobs, dfNull: nobs - 2, dfResidual: nobs - k, iterations, converged, model, warnings,
|
|
424
|
+
};
|
|
425
|
+
if (bias !== undefined)
|
|
426
|
+
result.bias = bias;
|
|
427
|
+
standardErrors.set(result, ses);
|
|
428
|
+
return result;
|
|
429
|
+
}
|
|
430
|
+
/**
|
|
431
|
+
* Summary of a {@link betareg} fit: Wald tests of the mean and precision coefficients. Equivalent to
|
|
432
|
+
* `betareg::summary.betareg()` in R.
|
|
433
|
+
* @example
|
|
434
|
+
* ```ts
|
|
435
|
+
* const fit = betareg("y ~ x", { y: [0.21, 0.35, 0.3, 0.52, 0.48, 0.66, 0.6, 0.81], x: [1, 2, 3, 4, 5, 6, 7, 8] });
|
|
436
|
+
* betaregSummary(fit).mean.p; // [2.355e-12, 2.267e-14]
|
|
437
|
+
* ```
|
|
438
|
+
* @category Regression
|
|
439
|
+
*/
|
|
440
|
+
export function betaregSummary(fit) {
|
|
441
|
+
const all = [...fit.coefficients.mean, ...fit.coefficients.precision];
|
|
442
|
+
const se = standardErrors.get(fit) ?? fit.vcov.map((r, j) => Math.sqrt(r[j]));
|
|
443
|
+
const table = (from, to, names) => {
|
|
444
|
+
const estimate = all.slice(from, to), s = se.slice(from, to), z = estimate.map((v, j) => v / s[j]);
|
|
445
|
+
return { names: names.slice(), estimate, se: s, z, p: z.map((v) => 2 * pnorm(-Math.abs(v))) };
|
|
446
|
+
};
|
|
447
|
+
const p = fit.coefficients.mean.length;
|
|
448
|
+
const r = betaregResiduals(fit, { type: "quantile" }).slice().sort((a, b) => a - b);
|
|
449
|
+
const quantile = (pr) => { const h = (r.length - 1) * pr, lo = Math.floor(h); return r[lo] + (h - lo) * ((r[lo + 1] ?? r[lo]) - r[lo]); };
|
|
450
|
+
return {
|
|
451
|
+
mean: table(0, p, fit.meanNames), precision: table(p, all.length, fit.precisionNames), loglik: fit.loglik,
|
|
452
|
+
df: all.length, aic: -2 * fit.loglik + 2 * all.length, pseudoRSquared: fit.pseudoRSquared, type: fit.type,
|
|
453
|
+
link: fit.link, linkPhi: fit.linkPhi, residuals: [0, 0.25, 0.5, 0.75, 1].map(quantile),
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
/**
|
|
457
|
+
* Wald confidence intervals of all coefficients of a {@link betareg} fit. Equivalent to R's
|
|
458
|
+
* `confint()`.
|
|
459
|
+
* @example
|
|
460
|
+
* ```ts
|
|
461
|
+
* const fit = betareg("y ~ x", { y: [0.21, 0.35, 0.3, 0.52, 0.48, 0.66, 0.6, 0.81], x: [1, 2, 3, 4, 5, 6, 7, 8] });
|
|
462
|
+
* betaregConfint(fit, { level: 0.9 });
|
|
463
|
+
* // { names: ["(Intercept)", "x", "(phi)"], lower: [-1.9023, 0.26223, 11.375], upper: [-1.1794, 0.40625, 112.68] }
|
|
464
|
+
* ```
|
|
465
|
+
* @category Regression
|
|
466
|
+
*/
|
|
467
|
+
export function betaregConfint(fit, options = {}) {
|
|
468
|
+
checkOptions(options, BETAREG_CONFINT_KEYS, "betaregConfint"); // generated: option-keys.mjs
|
|
469
|
+
const level = options.level ?? 0.95;
|
|
470
|
+
if (!(level > 0 && level < 1))
|
|
471
|
+
throw new RangeError("'level' must be between 0 and 1");
|
|
472
|
+
const zq = qnorm((1 + level) / 2);
|
|
473
|
+
const all = [...fit.coefficients.mean, ...fit.coefficients.precision];
|
|
474
|
+
const se = standardErrors.get(fit) ?? fit.vcov.map((r, j) => Math.sqrt(r[j]));
|
|
475
|
+
return { names: fit.names.slice(), lower: all.map((v, j) => v - zq * se[j]), upper: all.map((v, j) => v + zq * se[j]) };
|
|
476
|
+
}
|
|
477
|
+
/**
|
|
478
|
+
* Predictions of a {@link betareg} fit: means, linear predictors, precisions, variances, or the density,
|
|
479
|
+
* distribution function or quantiles of the fitted beta distributions. Equivalent to
|
|
480
|
+
* `betareg::predict.betareg()` in R.
|
|
481
|
+
* @example
|
|
482
|
+
* ```ts
|
|
483
|
+
* const fit = betareg("y ~ x", { y: [0.21, 0.35, 0.3, 0.52, 0.48, 0.66, 0.6, 0.81], x: [1, 2, 3, 4, 5, 6, 7, 8] });
|
|
484
|
+
* betaregPredict(fit, { newdata: { x: [2.5, 9] } }); // [0.33064, 0.81265]
|
|
485
|
+
* betaregPredict(fit, { type: "quantile", at: [0.1, 0.9] }); // one row per observation: [[0.16414, 0.30026], ...]
|
|
486
|
+
* ```
|
|
487
|
+
* @category Regression
|
|
488
|
+
*/
|
|
489
|
+
export function betaregPredict(fit, options = {}) {
|
|
490
|
+
checkOptions(options, BETAREG_PREDICT_KEYS, "betaregPredict"); // generated: option-keys.mjs
|
|
491
|
+
const type = options.type ?? "response";
|
|
492
|
+
const types = ["response", "link", "precision", "variance", "parameters", "density", "probability", "quantile"];
|
|
493
|
+
if (!types.includes(type))
|
|
494
|
+
throw new RangeError(`'arg' should be one of ${types.map((t) => `“${t}”`).join(", ")}`);
|
|
495
|
+
const l1 = meanLink(fit.link), l2 = phiLink(fit.linkPhi);
|
|
496
|
+
let e1, e2;
|
|
497
|
+
if (options.newdata === undefined) {
|
|
498
|
+
e1 = fit.linearPredictor.slice();
|
|
499
|
+
e2 = fit.precision.map((f) => l2.fun(f));
|
|
500
|
+
}
|
|
501
|
+
else {
|
|
502
|
+
const data = options.newdata, m = fit.model;
|
|
503
|
+
const nRows = dataRowCount(data, m.variables);
|
|
504
|
+
if (nRows === undefined)
|
|
505
|
+
throw new TypeError("cannot determine the number of rows in newdata");
|
|
506
|
+
const build = (rhs, names, constant) => {
|
|
507
|
+
if (constant || rhs === undefined)
|
|
508
|
+
return Array.from({ length: nRows }, () => [1]);
|
|
509
|
+
const dd = design({ response: undefined, rhs }, data, { levels: m.factorLevels, contrasts: m.contrasts });
|
|
510
|
+
if (dd.frame.rows.length !== nRows)
|
|
511
|
+
throw new RangeError("newdata has missing values");
|
|
512
|
+
const cols = names.map((nm) => dd.colNames.indexOf(nm));
|
|
513
|
+
if (cols.some((j) => j < 0))
|
|
514
|
+
throw new RangeError("newdata does not produce the fitted model matrix columns");
|
|
515
|
+
return dd.x.map((r) => cols.map((j) => r[j]));
|
|
516
|
+
};
|
|
517
|
+
const X = build(m.meanRhs, fit.meanNames, false);
|
|
518
|
+
const Z = build(m.precisionRhs, fit.precisionNames.map((nm) => (nm === "(phi)" ? "(Intercept)" : nm.slice(6))), m.precisionRhs === undefined);
|
|
519
|
+
e1 = X.map((r) => dot(r, fit.coefficients.mean));
|
|
520
|
+
e2 = Z.map((r) => dot(r, fit.coefficients.precision));
|
|
521
|
+
}
|
|
522
|
+
const mu = e1.map((e) => l1.inv(e)), phi = e2.map((e) => l2.inv(e));
|
|
523
|
+
switch (type) {
|
|
524
|
+
case "response": return mu;
|
|
525
|
+
case "link": return e1;
|
|
526
|
+
case "precision": return phi;
|
|
527
|
+
case "variance": return mu.map((m, i) => (m * (1 - m)) / (1 + phi[i]));
|
|
528
|
+
case "parameters": return mu.map((m, i) => [m, phi[i]]);
|
|
529
|
+
default: {
|
|
530
|
+
const at = typeof options.at === "number" ? [options.at] : Array.from(options.at ?? [0.5]);
|
|
531
|
+
const f = (v, i) => {
|
|
532
|
+
const a = mu[i] * phi[i], b = (1 - mu[i]) * phi[i];
|
|
533
|
+
return type === "density" ? dbeta1(v, a, b, false) : type === "probability" ? pbeta1(v, a, b, true, false) : qbeta1(v, a, b, true, false);
|
|
534
|
+
};
|
|
535
|
+
const elementwise = options.elementwise ?? (at.length === mu.length);
|
|
536
|
+
if (elementwise) {
|
|
537
|
+
if (at.length !== mu.length && at.length !== 1)
|
|
538
|
+
throw new RangeError("'at' must have one value per row for elementwise evaluation");
|
|
539
|
+
return mu.map((_, i) => f(at.length === 1 ? at[0] : at[i], i));
|
|
540
|
+
}
|
|
541
|
+
return mu.map((_, i) => at.map((v) => f(v, i)));
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
/**
|
|
546
|
+
* Residuals of a {@link betareg} fit (Espinheira, Ferrari and Cribari-Neto 2008; quantile residuals of Dunn and Smyth
|
|
547
|
+
* 1996). Every type but `"response"` is multiplied by the square root of the case weight, as R. Equivalent to
|
|
548
|
+
* `betareg::residuals.betareg()` in R.
|
|
549
|
+
* @example
|
|
550
|
+
* ```ts
|
|
551
|
+
* const fit = betareg("y ~ x", { y: [0.21, 0.35, 0.3, 0.52, 0.48, 0.66, 0.6, 0.81], x: [1, 2, 3, 4, 5, 6, 7, 8] });
|
|
552
|
+
* betaregResiduals(fit, { type: "sweighted2" }).slice(0, 3); // [-0.38464, 1.1271, -1.2608]
|
|
553
|
+
* ```
|
|
554
|
+
* @category Regression
|
|
555
|
+
*/
|
|
556
|
+
export function betaregResiduals(fit, options = {}) {
|
|
557
|
+
checkOptions(options, BETAREG_RESIDUALS_KEYS, "betaregResiduals"); // generated: option-keys.mjs
|
|
558
|
+
const type = options.type ?? "quantile";
|
|
559
|
+
const types = ["quantile", "deviance", "pearson", "response", "weighted", "sweighted", "sweighted2"];
|
|
560
|
+
if (!types.includes(type))
|
|
561
|
+
throw new RangeError(`'arg' should be one of ${types.map((t) => `“${t}”`).join(", ")}`);
|
|
562
|
+
const { y, weights } = fit.model, mu = fit.fitted, phi = fit.precision;
|
|
563
|
+
if (type === "response")
|
|
564
|
+
return y.map((v, i) => v - mu[i]);
|
|
565
|
+
const h = type === "sweighted2" ? betaregHatvalues(fit) : undefined;
|
|
566
|
+
return y.map((v, i) => {
|
|
567
|
+
const m = mu[i], f = phi[i], a = m * f, b = (1 - m) * f, sw = Math.sqrt(weights[i]);
|
|
568
|
+
let r;
|
|
569
|
+
switch (type) {
|
|
570
|
+
case "quantile":
|
|
571
|
+
r = qnorm(pbeta1(v, a, b, true, false));
|
|
572
|
+
break;
|
|
573
|
+
case "pearson":
|
|
574
|
+
r = (v - m) / Math.sqrt((m * (1 - m)) / (1 + f));
|
|
575
|
+
break;
|
|
576
|
+
// |l(y | mean y) - l(y | mean mu)|: mean y is not the maximum, the difference can be negative (R takes abs)
|
|
577
|
+
case "deviance":
|
|
578
|
+
r = Math.sign(v - m) * Math.sqrt(2 * Math.abs(dbeta1(v, v * f, (1 - v) * f, true) - dbeta1(v, a, b, true)));
|
|
579
|
+
break;
|
|
580
|
+
default: {
|
|
581
|
+
const ys = Math.log(v) - Math.log1p(-v), ms = digamma(a) - digamma(b), vv = trigamma(a) + trigamma(b);
|
|
582
|
+
r = type === "weighted" ? (ys - ms) / Math.sqrt(f * vv) : type === "sweighted" ? (ys - ms) / Math.sqrt(vv) : (ys - ms) / Math.sqrt(vv * (1 - h[i]));
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
return sw * r;
|
|
586
|
+
});
|
|
587
|
+
}
|
|
588
|
+
/** Diagonal of the hat matrix W^1/2 X (X'WX)^-1 X' W^1/2, W = w phi (psi'(a) + psi'(b)) (dmu/deta)^2 */
|
|
589
|
+
function betaregHatvalues(fit) {
|
|
590
|
+
const { xScaled: x, weights } = fit.model, l1 = meanLink(fit.link), p = x[0].length;
|
|
591
|
+
const W = fit.fitted.map((m, i) => {
|
|
592
|
+
const f = fit.precision[i];
|
|
593
|
+
return weights[i] * f * (trigamma(m * f) + trigamma((1 - m) * f)) * l1.d1(fit.linearPredictor[i]) ** 2;
|
|
594
|
+
});
|
|
595
|
+
const XtWX = Array.from({ length: p }, (_, a) => Array.from({ length: p }, (_, b) => x.reduce((s, r, i) => s + W[i] * r[a] * r[b], 0)));
|
|
596
|
+
const inv = spdInverse(XtWX);
|
|
597
|
+
if (inv === null)
|
|
598
|
+
return x.map(() => NaN);
|
|
599
|
+
return x.map((r, i) => W[i] * dot(r, matVec(inv, r)));
|
|
600
|
+
}
|