@numero-uno-jpn/rstats 1.2.0 → 1.3.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 (78) hide show
  1. package/CHANGELOG.md +81 -0
  2. package/README.ja.md +27 -10
  3. package/README.md +26 -9
  4. package/dist/chunks/{chunk-ORE5ZRCY.js → chunk-2VZW4XPK.js} +2 -2
  5. package/dist/chunks/chunk-4OOTEXZU.js +2 -0
  6. package/dist/chunks/{chunk-F3EQLL4F.js → chunk-6TZVS6WC.js} +2 -2
  7. package/dist/chunks/{chunk-L23RSC2N.js → chunk-6X2ZMPF5.js} +2 -2
  8. package/dist/chunks/{chunk-IAWXF73N.js → chunk-AJZV2SVY.js} +2 -2
  9. package/dist/chunks/{chunk-5SGTWSCB.js → chunk-BNTBZ5W3.js} +2 -2
  10. package/dist/chunks/{chunk-EEU7D4RU.js → chunk-EBRTF7RM.js} +1 -1
  11. package/dist/chunks/{chunk-IMPRIQE5.js → chunk-FFNHG5SB.js} +1 -1
  12. package/dist/chunks/{chunk-73LNRWU3.js → chunk-GUM57VVM.js} +1 -1
  13. package/dist/chunks/{chunk-RRO4LMCB.js → chunk-HBRSUHSU.js} +2 -2
  14. package/dist/chunks/{chunk-VERBXW6E.js → chunk-I5NWGQOQ.js} +2 -2
  15. package/dist/chunks/chunk-IJV43Y7Q.js +2 -0
  16. package/dist/chunks/{chunk-6FZHTD5G.js → chunk-IOGQEMDE.js} +2 -2
  17. package/dist/chunks/{chunk-JWBSEL3V.js → chunk-JJRZ2TTF.js} +2 -2
  18. package/dist/chunks/{chunk-2NNBUYHJ.js → chunk-LA4H6ZSC.js} +2 -2
  19. package/dist/chunks/{chunk-A66M3ZEA.js → chunk-LMNU4NHZ.js} +2 -2
  20. package/dist/chunks/{chunk-HBHMEPGY.js → chunk-LNUNKFIH.js} +3 -3
  21. package/dist/chunks/chunk-MJXETGT2.js +2 -0
  22. package/dist/chunks/{chunk-7WG7X2UI.js → chunk-P7ZHH2SF.js} +2 -2
  23. package/dist/chunks/{chunk-TNETWBF5.js → chunk-PDHBRDTF.js} +2 -2
  24. package/dist/chunks/{chunk-4AOTAT3O.js → chunk-RCGW2DCK.js} +2 -2
  25. package/dist/chunks/{chunk-NSU6U3ET.js → chunk-TZTVDVP4.js} +2 -2
  26. package/dist/chunks/{chunk-T5DRIITM.js → chunk-UJYRU37Z.js} +2 -2
  27. package/dist/chunks/{chunk-BI7NYJWP.js → chunk-UMDXXT3M.js} +1 -1
  28. package/dist/chunks/{chunk-7INBXTVV.js → chunk-UOAFEB64.js} +2 -2
  29. package/dist/chunks/{chunk-BKV3FINA.js → chunk-Z74ZOTUN.js} +2 -2
  30. package/dist/descriptive.js +2 -2
  31. package/dist/distributions.js +2 -2
  32. package/dist/entries/tests.d.ts +9 -0
  33. package/dist/entries/tests.js +9 -0
  34. package/dist/htest/agreement.d.ts +2 -2
  35. package/dist/htest/blandAltman.d.ts +100 -0
  36. package/dist/htest/blandAltman.js +159 -0
  37. package/dist/htest/diagnosticTests.d.ts +91 -0
  38. package/dist/htest/diagnosticTests.js +116 -0
  39. package/dist/htest/iccPsych.d.ts +106 -0
  40. package/dist/htest/iccPsych.js +332 -0
  41. package/dist/htest/ksTest.d.ts +1 -1
  42. package/dist/htest/mcreg.d.ts +209 -0
  43. package/dist/htest/mcreg.js +735 -0
  44. package/dist/htest/roc.d.ts +287 -0
  45. package/dist/htest/roc.js +635 -0
  46. package/dist/htest/rocTest.d.ts +139 -0
  47. package/dist/htest/rocTest.js +444 -0
  48. package/dist/htest/tTOST.d.ts +202 -0
  49. package/dist/htest/tTOST.js +558 -0
  50. package/dist/htest/trendTests.d.ts +1 -1
  51. package/dist/htest/trendTests.js +1 -1
  52. package/dist/internal/summary.js +5 -0
  53. package/dist/linalg/qr.d.ts +3 -0
  54. package/dist/linalg/qr.js +3 -0
  55. package/dist/linalg.js +2 -2
  56. package/dist/mixed.js +2 -2
  57. package/dist/models/coeftest.d.ts +139 -0
  58. package/dist/models/coeftest.js +237 -0
  59. package/dist/models/coxph.d.ts +60 -9
  60. package/dist/models/coxph.js +367 -38
  61. package/dist/models/glm.d.ts +11 -1
  62. package/dist/models/glm.js +19 -2
  63. package/dist/models/inputRows.d.ts +10 -0
  64. package/dist/models/inputRows.js +23 -0
  65. package/dist/models/lm.d.ts +8 -0
  66. package/dist/models/lm.js +14 -2
  67. package/dist/models/sandwich.d.ts +177 -0
  68. package/dist/models/sandwich.js +923 -0
  69. package/dist/numerics.js +2 -2
  70. package/dist/random/rng.d.ts +8 -1
  71. package/dist/random/rng.js +14 -1
  72. package/dist/rstats.js +16 -16
  73. package/dist/special.js +2 -2
  74. package/dist/tests.js +13 -13
  75. package/llms.txt +17 -0
  76. package/package.json +1 -1
  77. package/dist/chunks/chunk-47IIPUFN.js +0 -2
  78. package/dist/chunks/chunk-CQB4BJBR.js +0 -2
@@ -0,0 +1,923 @@
1
+ // Heteroskedasticity-consistent and clustered covariance matrices of the coefficients of lm and glm fits: the
2
+ // sandwich package's vcovHC and vcovCL.
3
+ //
4
+ // Written for rStats.js (no ported code) from oracle/robust-behaviour.md (a description of the behaviour of sandwich
5
+ // 3.1-3) and the published methods: White (1980), "A heteroskedasticity-consistent covariance matrix estimator and a
6
+ // direct test for heteroskedasticity", Econometrica 48, 817-838 (HC0 and the sandwich); MacKinnon and White (1985),
7
+ // "Some heteroskedasticity-consistent covariance matrix estimators with improved finite sample properties", J.
8
+ // Econometrics 29, 305-325 (HC1, HC2, HC3); Long and Ervin (2000), "Using heteroscedasticity consistent standard errors
9
+ // in the linear regression model", Am. Stat. 54, 217-224; Cribari-Neto (2004), "Asymptotic inference under
10
+ // heteroskedasticity of unknown form", CSDA 45, 215-233 (HC4); Cribari-Neto, Souza and Vasconcellos (2007), "Inference
11
+ // under heteroskedasticity and leveraged data", Comm. Stat. Theory Methods 36, 1877-1888 (HC5); Cribari-Neto and da
12
+ // Silva (2011), "A new heteroskedasticity-consistent covariance matrix estimator for the linear regression model",
13
+ // AStA 95, 129-146 (HC4m); Zeileis (2004), "Econometric computing with HC and HAC covariance matrix estimators", JSS
14
+ // 11(10) (the omega framework, type "const"); Zeileis (2006), "Object-oriented computation of sandwich estimators",
15
+ // JSS 16(9) (estimating functions and bread of lm and glm); Zeileis, Köll and Graham (2020), "Various versatile
16
+ // variances: an object-oriented implementation of clustered covariances in R", JSS 95(1) (vcovCL: the cluster
17
+ // adjustment G/(G - 1), HC1's (n - 1)/(n - k), multi-way clustering, multi0, the eigenvalue fix, clustered HC2/HC3);
18
+ // Cameron, Gelbach and Miller (2011), "Robust inference with multiway clustering", JBES 29, 238-249 (inclusion-exclusion
19
+ // over the clustering dimensions, the fix of negative eigenvalues); Bell and McCaffrey (2002), "Bias reduction in
20
+ // standard errors for linear regression with multi-stage samples", Survey Methodology 28, 169-181, and Pustejovsky and
21
+ // Tipton (2018), "Small-sample methods for cluster-robust variance estimation and hypothesis testing in fixed effects
22
+ // models", JBES 36, 672-683 (the symmetric adjustment of clustered HC2/HC3 for weighted fits).
23
+ //
24
+ // The pieces (Zeileis 2006): with the n rows of non-zero prior weight, the k non-aliased columns x_i of the unweighted
25
+ // model matrix, A = (X'WX)^-1 from the fit's QR factor (lm: W the prior weights; glm: the working weights), the
26
+ // estimating functions psi_i = res_i x_i with res_i = w_i e_i (lm) or W_i z_i / phi_s (glm: z the working residuals,
27
+ // phi_s = sum (W z)^2 / sum W except for binomial and poisson, where it is 1), the meat M = (1/n) sum omega_i x_i x_i'
28
+ // (HC) or the cluster sums, and the sandwich V = n phi_s^2 A M A.
29
+ import { eigen } from "../linalg/eigen.js";
30
+ import { qrQty, qrQy } from "../linalg/qr.js";
31
+ import { chol2invColumns } from "../internal/scaledInverse.js";
32
+ import { ldexp, ldexpWide } from "../internal/summary.js";
33
+ import { levelText } from "../internal/levels.js";
34
+ import { reported } from "../internal/warnings.js";
35
+ import { matchChoice } from "../htest/power.js";
36
+ import { familyOf, glmDispersion, glmHatvalues, glmQrRows, scaledView } from "./glm.js";
37
+ import { qrWeightExponent } from "./lm.js";
38
+ import { inputRowCount } from "./inputRows.js";
39
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
40
+ import { checkOptions } from "../internal/checkOptions.js";
41
+ const VCOV_HC_KEYS = ["type", "omega", "sandwich"];
42
+ const VCOV_CL_KEYS = ["cluster", "type", "cadjust", "multi0", "fix", "sandwich"];
43
+ // Generated by `node scripts/option-keys.mjs --write` (end)
44
+ const EPS = 2 ** -52;
45
+ /** A covariance (or meat) times 2^2k, kept in units of powers of 2 (scaledVcovs) */
46
+ function rescaled(V, k) {
47
+ if (k === 0)
48
+ return V;
49
+ const rec = scaledVcovs.get(V) ?? { mant: V, exp: V.map(() => 0) };
50
+ return withScale(rec.mant, rec.exp.map((e) => e + k));
51
+ }
52
+ /** The exponent of a finite non-zero value: floor(log2 |v|) (within one of it, which is all the scaling needs) */
53
+ const exponentOf = (v) => Math.floor(Math.log2(Math.abs(v)));
54
+ function toPair(v) {
55
+ if (v === 0 || !Number.isFinite(v))
56
+ return [v, 0];
57
+ const x = exponentOf(v);
58
+ return [ldexp(v, -x), x];
59
+ }
60
+ const mulPair = (a, b) => [a[0] * b[0], a[1] + b[1]];
61
+ /** The values of pairs times 2^-s, s the exponent of the largest (even if asked) */
62
+ function commonScale(p, even = false) {
63
+ let top = -Infinity;
64
+ for (const [m, x] of p)
65
+ if (m !== 0 && Number.isFinite(m))
66
+ top = Math.max(top, x + exponentOf(m));
67
+ let s = top === -Infinity ? 0 : top;
68
+ if (even)
69
+ s = 2 * Math.floor(s / 2);
70
+ return { v: p.map(([m, x]) => ldexpWide(m, x - s)), s };
71
+ }
72
+ /** v 2^k for an integer k of any size */
73
+ const scaledEntry = (v, k) => (Math.abs(k) <= 2046 ? ldexp(v, k) : ldexpWide(v, k));
74
+ export const scaledVcovs = new WeakMap();
75
+ /** The matrix of a scaled covariance, recorded in scaledVcovs */
76
+ function withScale(mant, exp) {
77
+ const V = mant.map((r, a) => r.map((v, b) => scaledEntry(v, exp[a] + exp[b])));
78
+ scaledVcovs.set(V, { mant, exp });
79
+ return V;
80
+ }
81
+ /**
82
+ * The standard error of row j of a covariance matrix kept in scaledVcovs: sqrt(mant_jj) 2^exp_j, or undefined if the
83
+ * matrix has no record or was changed since
84
+ */
85
+ export function scaledStandardError(V, j, entry) {
86
+ const rec = scaledVcovs.get(V);
87
+ const m = rec?.mant[j]?.[j];
88
+ if (rec === undefined || m === undefined || !Object.is(scaledEntry(m, 2 * rec.exp[j]), entry))
89
+ return undefined;
90
+ return scaledEntry(Math.sqrt(m), rec.exp[j]);
91
+ }
92
+ export function isGlm(fit) {
93
+ return typeof fit === "object" && fit !== null && "family" in fit && "model" in fit;
94
+ }
95
+ export function checkFit(fit) {
96
+ const ok = typeof fit === "object" &&
97
+ fit !== null &&
98
+ Array.isArray(fit.coefficients) &&
99
+ "qr" in fit &&
100
+ (isGlm(fit) || ("sigma" in fit && "x" in fit && "rows" in fit));
101
+ if (!ok)
102
+ throw new TypeError("'fit' must be the result of lm or glm");
103
+ }
104
+ /** The order of the first `rank` pivots by column: [column, position in the pivots] */
105
+ function pivotOrder(q, rank) {
106
+ return q.pivot
107
+ .slice(0, rank)
108
+ .map((col, k) => [col, k])
109
+ .sort((a, b) => a[0] - b[0]);
110
+ }
111
+ /**
112
+ * (R'R)^-1 of the leading rank x rank block of a QR factor, in the order of the columns (not the pivots), as inv_ab
113
+ * 2^(-e_a - e_b - shift) (chol2invColumns)
114
+ */
115
+ function unscaledParts(q, rank) {
116
+ const { inv, e } = chol2invColumns(q.qr.slice(0, rank).map((r) => r.slice(0, rank)));
117
+ const order = pivotOrder(q, rank);
118
+ return { inv: order.map(([, a]) => order.map(([, b]) => inv[a][b])), e: order.map(([, a]) => e[a]), cols: order.map(([c]) => c) };
119
+ }
120
+ /** (R'R)^-1 of the leading rank x rank block of a QR factor, in the order of the columns (not the pivots) */
121
+ function unscaledFromQR(q, rank, shift) {
122
+ const { inv, e, cols } = unscaledParts(q, rank);
123
+ return { A: inv.map((r, a) => r.map((v, b) => ldexp(v, -e[a] - e[b] - shift))), cols };
124
+ }
125
+ /** B and e of ScaledParts (in the order of the columns): every column of R divided by the power of 2 of its largest entry */
126
+ function scaledBread(q, rank) {
127
+ const R = q.qr.slice(0, rank).map((r) => r.slice(0, rank));
128
+ const e = R.map((_, j) => {
129
+ let top = 0;
130
+ for (let i = 0; i <= j; i++)
131
+ top = Math.max(top, Math.abs(R[i][j]));
132
+ return top > 0 && Number.isFinite(top) ? exponentOf(top) : 0;
133
+ });
134
+ // (the columns are then in [1, 2), which chol2invColumns leaves as they are)
135
+ const { inv } = chol2invColumns(R.map((r) => r.map((v, j) => ldexp(v, -e[j]))));
136
+ const order = pivotOrder(q, rank);
137
+ return { B: order.map(([, a]) => order.map(([, b]) => inv[a][b])), e: order.map(([, a]) => e[a]) };
138
+ }
139
+ /** The first `rank` columns of Q (m x rank) */
140
+ function qrLeading(q, rank) {
141
+ const m = q.qr.length;
142
+ return qrQy(q, Array.from({ length: m }, (_, i) => Array.from({ length: rank }, (_, j) => (i === j ? 1 : 0))));
143
+ }
144
+ /** Squared row norms of the first `rank` columns of Q (the hat values of the rows of the decomposition) */
145
+ function qrHat(q, rank) {
146
+ const m = q.qr.length;
147
+ if (rank === 0)
148
+ return new Array(m).fill(0);
149
+ const Q = qrLeading(q, rank);
150
+ // above 1 - 10 eps set to 1, as R's lm.influence
151
+ return Q.map((r) => {
152
+ const h = r.reduce((s, v) => s + v * v, 0);
153
+ return h > 1 - 10 * EPS ? 1 : h;
154
+ });
155
+ }
156
+ /**
157
+ * 1 - h_i: where h_i > 1/2 (at most 2k rows), the squared norm of row i of the trailing columns of the full Q, which
158
+ * has no cancellation (1 - h lost the digits of h, an error of eps / (1 - h) in HC2 to HC5); 1 - h elsewhere (the same
159
+ * bits as before) and 0 for a hat value of 1. qrRow gives a row's row in the decomposition (-1: none)
160
+ */
161
+ function oneMinusHat(q, rank, h, qrRow) {
162
+ return h.map((v, i) => {
163
+ if (v >= 1)
164
+ return 0;
165
+ const r = qrRow(i);
166
+ if (v <= 0.5 || q === undefined || r < 0)
167
+ return 1 - v;
168
+ const m = q.qr.length;
169
+ const unit = new Array(m).fill(0);
170
+ unit[r] = 1;
171
+ const c = qrQty(q, unit);
172
+ let s = 0;
173
+ for (let j = rank; j < m; j++)
174
+ s += c[j] * c[j];
175
+ return s;
176
+ });
177
+ }
178
+ export function coefficientNames(fit) {
179
+ if (isGlm(fit))
180
+ return fit.model.columnNames;
181
+ const named = fit.coefNames;
182
+ if (named !== undefined)
183
+ return named;
184
+ const p = fit.coefficients.length;
185
+ return fit.intercept ? ["(Intercept)", ...Array.from({ length: p - 1 }, (_, j) => `x${j + 1}`)] : Array.from({ length: p }, (_, j) => `x${j + 1}`);
186
+ }
187
+ /**
188
+ * The model-based covariance of the coefficients that are not aliased (R's vcov(fit) without the NA rows): sigma^2 A
189
+ * for an lm, the dispersion of summary.glm times A for a glm, with A = (X'WX)^-1 from the fit's QR factor. Formed as
190
+ * inv_ab d~ 2^(x - e_a - e_b - shift) with the dispersion d = d~ 2^x (x even), so that the standard errors are
191
+ * representable where sigma^2 or the covariance is not (the same bits as A d wherever that is in range)
192
+ */
193
+ export function modelCovariance(fit) {
194
+ const names = coefficientNames(fit);
195
+ if (fit.qr === undefined || fit.rank === 0)
196
+ return { vcov: [], names: [] };
197
+ const { inv, e, cols } = unscaledParts(fit.qr, fit.rank);
198
+ const shift = isGlm(fit) ? 0 : qrWeightExponent(fit.qr);
199
+ let d;
200
+ let x;
201
+ if (isGlm(fit)) {
202
+ // the dispersion of the scaled fit (scaledView) times 2^2k
203
+ const v = scaledView(fit);
204
+ const ds = familyOf(fit).fixedDispersion ? 1 : glmDispersion(v.fit);
205
+ const t = ds === 0 || !Number.isFinite(ds) ? 0 : 2 * Math.floor(exponentOf(ds) / 2);
206
+ d = ldexp(ds, -t);
207
+ x = t + 2 * v.k;
208
+ }
209
+ else {
210
+ const [m, t] = toPair(fit.sigma);
211
+ d = m * m;
212
+ x = 2 * t;
213
+ }
214
+ const mant = inv.map((r) => r.map((v) => v * d));
215
+ // (shift is even: twice an integer, see lm)
216
+ return { vcov: withScale(mant, e.map((ea) => (x - shift) / 2 - ea)), names: cols.map((j) => names[j]) };
217
+ }
218
+ /** The pieces of the sandwich of a fit (see the header) */
219
+ function partsOf(given, onView = false) {
220
+ const allNames = coefficientNames(given);
221
+ if (isGlm(given)) {
222
+ // on the scaled fit if asked (scaledView: a gaussian fit on the identity link computed on the response divided by
223
+ // 2^k), whose sandwich is 2^-2k times the fit's, bit for bit where both are in range
224
+ const top = onView ? scaledView(given) : { fit: given, k: 0 };
225
+ const fit = top.fit;
226
+ const fam = familyOf(fit);
227
+ const prior = fit.priorWeights;
228
+ const nonZero = prior.map((w) => w > 0);
229
+ const idx = prior.flatMap((w, i) => (w > 0 ? [i] : []));
230
+ const { A, cols } = fit.qr === undefined || fit.rank === 0 ? { A: [], cols: [] } : unscaledFromQR(fit.qr, fit.rank, 0);
231
+ const X = idx.map((i) => cols.map((j) => fit.model.x[i][j]));
232
+ const W = idx.map((i) => fit.weights[i]);
233
+ const wz = idx.map((i) => fit.weights[i] * fit.residuals[i]);
234
+ // phi_s (Zeileis 2006): it cancels in the sandwich and scales the meat and the residual factors given to omega
235
+ const fixed = fam.family === "binomial" || fam.family === "poisson";
236
+ const phiS = fixed ? 1 : wz.reduce((s, v) => s + v * v, 0) / W.reduce((s, v) => s + v, 0);
237
+ const usedRows = fit.model.rows;
238
+ const h = glmHatvalues(fit);
239
+ const qrRows = glmQrRows(fit);
240
+ const scaled = () => {
241
+ // on the scaled fit (scaledView: gaussian on the identity link), whose working residuals are 2^-k times the fit's
242
+ const view = scaledView(fit);
243
+ const z = idx.map((i) => view.fit.residuals[i]);
244
+ const sw = W.map(Math.sqrt);
245
+ const { B, e } = fit.qr === undefined || fit.rank === 0 ? { B: [], e: [] } : scaledBread(fit.qr, fit.rank);
246
+ const T = X.map((x, i) => x.map((v, a) => ldexp(sw[i] * v, -e[a])));
247
+ // sqrt(W) z (0 for a row of working weight 0, whose working residual may not be finite)
248
+ const { v: u, s } = commonScale(sw.map((w, i) => (w === 0 ? [0, 0] : mulPair(toPair(w), toPair(z[i])))));
249
+ const omegaPart = () => {
250
+ // phi_s = sum (W z)^2 / sum W in the fit's units
251
+ let phi = [1, 0];
252
+ if (!fixed) {
253
+ const num = commonScale(W.map((w, i) => (w === 0 ? [0, 0] : mulPair(toPair(w), toPair(z[i])))));
254
+ const den = commonScale(W.map(toPair));
255
+ phi = [num.v.reduce((t, v) => t + v * v, 0) / den.v.reduce((t, v) => t + v, 0), 2 * num.s - den.s + 2 * view.k];
256
+ }
257
+ return { T: X.map((x) => x.map((v, a) => scaledEntry(v, -e[a]))), factor: [phi[0] * phi[0], 2 * phi[1]] };
258
+ };
259
+ return { T, B, e, u, s: s + view.k, omegaPart };
260
+ };
261
+ // the residual factors W z / phi_s: the plain quotient where phi_s and W z are in range; otherwise (phi_s overflows
262
+ // or underflows for a gaussian response beyond 2^±256, given an omega) from W z 2^-s and phi_s = phi 2^x of the
263
+ // scaled fit's working residuals, as W z 2^-s / phi 2^(s - x + k): in the fit's units, as the omega function takes them
264
+ let res;
265
+ if (representable(phiS) && wz.every(Number.isFinite))
266
+ res = wz.map((v) => v / phiS);
267
+ else {
268
+ const view = scaledView(fit);
269
+ const num = commonScale(W.map((w, i) => (w === 0 ? [0, 0] : mulPair(toPair(w), toPair(view.fit.residuals[idx[i]])))));
270
+ if (fixed)
271
+ res = num.v.map((v) => scaledEntry(v, num.s + view.k));
272
+ else {
273
+ const den = commonScale(W.map(toPair));
274
+ // phi = (sum (W z 2^-s)^2 / sum W 2^-t) 2^(2s - t + 2k), s here including k
275
+ const phi = num.v.reduce((t, v) => t + v * v, 0) / den.v.reduce((t, v) => t + v, 0);
276
+ res = num.v.map((v) => scaledEntry(v / phi, den.s - num.s - view.k));
277
+ }
278
+ }
279
+ return {
280
+ glm: true,
281
+ names: cols.map((j) => allNames[j]),
282
+ X,
283
+ W,
284
+ res,
285
+ phiS,
286
+ A,
287
+ h,
288
+ omh: oneMinusHat(fit.qr, fit.rank, h, (i) => qrRows[i]),
289
+ qr: fit.qr,
290
+ rank: fit.rank,
291
+ qrRow: (i) => qrRows[i],
292
+ inputRows: idx.map((i) => usedRows[i]),
293
+ nInput: inputRowCount(given, usedRows),
294
+ nonZero,
295
+ dispersion: () => glmDispersion(fit),
296
+ scaled,
297
+ k: top.k,
298
+ };
299
+ }
300
+ const fit = given;
301
+ const wAll = fit.weights;
302
+ const nonZero = fit.residuals.map((_, i) => wAll === undefined || wAll[i] !== 0);
303
+ const idx = nonZero.flatMap((z, i) => (z ? [i] : []));
304
+ const qw = qrWeightExponent(fit.qr);
305
+ const { A, cols } = fit.rank === 0 ? { A: [], cols: [] } : unscaledFromQR(fit.qr, fit.rank, qw);
306
+ const X = idx.map((i) => cols.map((j) => fit.x[i][j]));
307
+ const W = idx.map((i) => wAll?.[i] ?? 1);
308
+ const res = idx.map((i, k) => W[k] * fit.residuals[i]);
309
+ const h = qrHat(fit.qr, fit.rank);
310
+ const scaled = () => {
311
+ // the square roots of the weights as in the QR (divided by 2^qw/2 for #199, see lm)
312
+ const sw = W.map((w) => (qw === 0 ? Math.sqrt(w) : ldexp(Math.sqrt(w), -qw / 2)));
313
+ const { B, e } = fit.rank === 0 ? { B: [], e: [] } : scaledBread(fit.qr, fit.rank);
314
+ const T = X.map((x, i) => x.map((v, a) => ldexp(sw[i] * v, -e[a])));
315
+ const { v: u, s } = commonScale(sw.map((w, i) => mulPair(toPair(w), toPair(fit.residuals[idx[i]]))));
316
+ const omegaPart = () => ({ T: X.map((x) => x.map((v, a) => scaledEntry(v, -e[a]))), factor: [1, -2 * qw] });
317
+ return { T, B, e, u, s, omegaPart };
318
+ };
319
+ return {
320
+ glm: false,
321
+ names: cols.map((j) => allNames[j]),
322
+ X,
323
+ W,
324
+ res,
325
+ phiS: 1,
326
+ A,
327
+ h,
328
+ omh: oneMinusHat(fit.qr, fit.rank, h, (i) => i),
329
+ qr: fit.qr,
330
+ rank: fit.rank,
331
+ qrRow: (i) => i,
332
+ inputRows: idx.map((i) => fit.rows[i]),
333
+ nInput: inputRowCount(fit, fit.rows),
334
+ nonZero,
335
+ dispersion: () => fit.sigma * fit.sigma,
336
+ scaled,
337
+ k: 0,
338
+ };
339
+ }
340
+ /** Whether the diagonal entry v of the meat or the sandwich lost nothing to the double range */
341
+ const SAFE = 2 ** -969;
342
+ const representable = (v) => Math.abs(v) >= SAFE && Math.abs(v) < Infinity;
343
+ /**
344
+ * Whether the sandwich in plain doubles can be trusted: phi_s, the bread's and the meat's diagonals and the result's
345
+ * diagonal at least 2^-969 (so that terms below the normal range cannot matter) and finite, every entry finite. A
346
+ * meat of zeros is right where every omega is 0 (a perfect fit). Otherwise the sandwich is formed in units of powers of
347
+ * 2 (ScaledParts): weights beyond 2^±510, responses beyond 2^±256 in a gaussian glm, and x and y in the same huge or
348
+ * tiny units made it Infinity, 0 or NaN
349
+ */
350
+ function plainOk(P, M, V, zero) {
351
+ // (and the factor n phi_s^2 of the sandwich: subnormal for phi_s below 2^-511, a gaussian glm's response near 2^-260
352
+ // with an omega given, which lost 1e-13)
353
+ if (!(P.phiS >= SAFE && P.phiS < Infinity) || !representable(P.X.length * P.phiS * P.phiS))
354
+ return false;
355
+ for (let a = 0; a < V.length; a++) {
356
+ if (!representable(P.A[a][a]))
357
+ return false;
358
+ if (!zero && (!representable(M[a][a]) || !representable(V[a][a])))
359
+ return false;
360
+ if (!V[a].every(Number.isFinite))
361
+ return false;
362
+ }
363
+ return true;
364
+ }
365
+ /** a b a' for symmetric k x k matrices a (bread core) and b (meat), times f */
366
+ function sandwichOf(A, M, f) {
367
+ const k = A.length;
368
+ const AM = A.map((r) => Array.from({ length: k }, (_, j) => r.reduce((s, v, l) => s + v * M[l][j], 0)));
369
+ const V = AM.map((r) => Array.from({ length: k }, (_, j) => f * r.reduce((s, v, l) => s + v * A[l][j], 0)));
370
+ // symmetric by construction; the two triangles may differ in the last bit
371
+ for (let i = 0; i < k; i++)
372
+ for (let j = 0; j < i; j++)
373
+ V[i][j] = V[j][i];
374
+ return V;
375
+ }
376
+ /** (1/n) sum_i omega_i x_i x_i' */
377
+ function weightedCrossprod(X, omega, n) {
378
+ const k = X[0]?.length ?? 0;
379
+ const M = Array.from({ length: k }, () => new Array(k).fill(0));
380
+ X.forEach((x, i) => {
381
+ const o = omega[i];
382
+ for (let a = 0; a < k; a++)
383
+ for (let b = a; b < k; b++)
384
+ M[a][b] += o * x[a] * x[b];
385
+ });
386
+ for (let a = 0; a < k; a++)
387
+ for (let b = a; b < k; b++)
388
+ M[a][b] = M[b][a] = M[a][b] / n;
389
+ return M;
390
+ }
391
+ /** The observations listed in sandwich's warnings: 1-based input rows, at most 10 and then "..." */
392
+ function observationList(rows) {
393
+ const shown = rows.slice(0, 10).map((r) => String(r + 1));
394
+ return rows.length > 10 ? `${shown.join(", ")}, ...` : shown.join(", ");
395
+ }
396
+ const HC_TYPES = ["HC3", "const", "HC", "HC0", "HC1", "HC2", "HC4", "HC4m", "HC5"];
397
+ /**
398
+ * Heteroskedasticity-consistent covariance matrix of the coefficients of an `lm` or `glm` fit. Equivalent to R's
399
+ * `sandwich::vcovHC()`.
400
+ *
401
+ * The sandwich A (X' diag(omega) X) A (Zeileis 2006), A = (X'WX)^-1, with omega_i = res_i^2 (HC0, White 1980), times n
402
+ * / (n - k) (HC1), divided by 1 - h_i (HC2) or (1 - h_i)^2 (HC3, MacKinnon and White 1985), by (1 - h_i)^delta_i
403
+ * (HC4, Cribari-Neto 2004; HC4m, Cribari-Neto and da Silva 2011) or by its square root (HC5, Cribari-Neto et al.
404
+ * 2007), with HC4m's gamma = (1, 1.5) and HC5's k = 0.7 fixed as in sandwich; res_i is w_i e_i for an lm and W_i z_i /
405
+ * phi_s for a glm (working weights and residuals). `"const"` is the model-based covariance of the fit (R's `vcov(fit)`:
406
+ * sigma^2 A, or the dispersion times A for a glm); sandwich's `"const"` equals it only for an unweighted lm.
407
+ *
408
+ * Rows of prior weight 0 are left out (R counts them in n and returns different values); a hat value of 1 gives R's
409
+ * warning, and with HC2 to HC5, whose value is then undefined (R's NaN), an error, as is HC1 with as many
410
+ * observations as coefficients. Aliased coefficients are left out of the matrix. Data far from 1 (weights, responses)
411
+ * are handled in units of powers of 2: entries that are not representable are Infinity or 0, and {@link coeftest}
412
+ * still gives their standard errors, from a record kept with the matrix object returned (a copy of the matrix loses it:
413
+ * pass the result or its original matrix). See docs/differences-from-r.md.
414
+ *
415
+ * @param fit The result of {@link lm} or {@link glm}.
416
+ *
417
+ * @example
418
+ * ```ts
419
+ * const fit = lm([1, 2, 3, 4, 5, 6], [1.1, 2.3, 2.8, 4.5, 4.9, 6.4]);
420
+ * vcovHC(fit).vcov; // [[0.043766, -0.01134], [-0.01134, 0.0045125]] (HC3)
421
+ * vcovHC(fit, { type: "HC0" }).names; // ["(Intercept)", "x1"]
422
+ * ```
423
+ *
424
+ * @category Linear models and ANOVA
425
+ */
426
+ export function vcovHC(fit, options = {}) {
427
+ checkOptions(options, VCOV_HC_KEYS, "vcovHC"); // generated: option-keys.mjs
428
+ checkFit(fit);
429
+ const given = matchChoice(options.type, HC_TYPES);
430
+ const type = given === "HC" ? "HC0" : given;
431
+ const sandwich = options.sandwich ?? true;
432
+ if (typeof sandwich !== "boolean")
433
+ throw new TypeError("'sandwich' must be true or false");
434
+ // (a gaussian glm on its scaled fit, unless omega is given: omega and its function are in the units of the fit)
435
+ const P = partsOf(fit, options.omega === undefined);
436
+ const n = P.X.length;
437
+ const k = P.names.length;
438
+ const warnings = [];
439
+ const { res, h, omh } = P;
440
+ let omega;
441
+ // the weights of the meat from the squared residual factors (the type's), for the plain and the scaled sandwich
442
+ let omegaOf;
443
+ if (options.omega !== undefined) {
444
+ let o;
445
+ if (typeof options.omega === "function")
446
+ o = options.omega(res.slice(), h.slice(), n - k);
447
+ else {
448
+ o = options.omega;
449
+ // one per row used: those of weight 0 left out
450
+ if (o.length !== n && o.length === P.nonZero.length)
451
+ o = o.filter((_, i) => P.nonZero[i]);
452
+ }
453
+ if (!Array.isArray(o) && !ArrayBuffer.isView(o))
454
+ throw new TypeError("'omega' must give an array of numbers");
455
+ if (o.length !== n)
456
+ throw new RangeError(`'omega' must have one value per observation (${n})`);
457
+ omega = Array.from(o, Number);
458
+ if (omega.some((v) => !Number.isFinite(v)))
459
+ throw new RangeError("'omega' must be finite");
460
+ }
461
+ else if (type === "const") {
462
+ // the model-based covariance (choice 5 of robust-behaviour.md): omega_i = dispersion W_i / phi_s^2, so that the
463
+ // sandwich is dispersion A (sandwich's own "const" uses the unweighted X'X and sum res^2 / (n - k))
464
+ const d = P.dispersion();
465
+ omega = P.W.map((w) => (d * w) / (P.phiS * P.phiS));
466
+ }
467
+ else {
468
+ // warnings for hat values (close to) 1, naming the 1-based input rows (sandwich's text)
469
+ const close = h.flatMap((v, i) => (v > 1 - Math.sqrt(EPS) ? [P.inputRows[i]] : []));
470
+ if (close.length > 0) {
471
+ warnings.push(type === "HC0" || type === "HC1"
472
+ ? `${type} covariances become (close to) singular if hat values are (close to) 1 as for observation(s) ${observationList(close)}`
473
+ : `${type} covariances are numerically unstable for hat values close to 1 (and undefined if exactly 1) as for observation(s) ${observationList(close)}`);
474
+ }
475
+ // a hat value of 1 leaves HC2 to HC5 undefined (R returns a matrix of NaN): an error
476
+ if (type !== "HC0" && type !== "HC1") {
477
+ const bad = h.flatMap((v, i) => (v >= 1 ? [P.inputRows[i]] : []));
478
+ if (bad.length > 0)
479
+ throw new RangeError(`${type} covariances are undefined for hat values of 1 as for observation(s) ${observationList(bad)}`);
480
+ }
481
+ // n / (n - k) is infinite for as many observations as coefficients (R: a matrix of NaN): an error
482
+ if (type === "HC1" && n <= k)
483
+ throw new RangeError("HC1 covariances need more observations than coefficients");
484
+ const p = Math.round(h.reduce((s, v) => s + v, 0));
485
+ const hmax = h.reduce((m, v) => Math.max(m, v), 0);
486
+ omegaOf = (r2) => {
487
+ switch (type) {
488
+ case "HC0":
489
+ return r2;
490
+ case "HC1":
491
+ return r2.map((v) => (v * n) / (n - k));
492
+ case "HC2":
493
+ return r2.map((v, i) => v / omh[i]);
494
+ case "HC3":
495
+ return r2.map((v, i) => v / omh[i] ** 2);
496
+ case "HC4":
497
+ return r2.map((v, i) => v / omh[i] ** Math.min(4, (n * h[i]) / p));
498
+ case "HC4m":
499
+ return r2.map((v, i) => v / omh[i] ** (Math.min(1, (n * h[i]) / p) + Math.min(1.5, (n * h[i]) / p)));
500
+ default:
501
+ return r2.map((v, i) => v / Math.sqrt(omh[i] ** Math.min((n * h[i]) / p, Math.max(4, (n * 0.7 * hmax) / p))));
502
+ }
503
+ };
504
+ omega = omegaOf(res.map((r) => r * r));
505
+ }
506
+ let vcov;
507
+ // (const: the model-based covariance itself, not A (X'WX) A, which loses digits for an ill-conditioned X)
508
+ if (sandwich && type === "const" && options.omega === undefined)
509
+ vcov = modelCovariance(fit).vcov;
510
+ else if (!sandwich) {
511
+ const M = weightedCrossprod(P.X, omega, n);
512
+ if (meatOk(M, (omegaOf === undefined ? omega : res).every((v) => v === 0)))
513
+ vcov = M;
514
+ else {
515
+ // in units of powers of 2 (scaledMeat): the type's omega from the scaled residual factors, a given omega by its
516
+ // own power of 2 on X D^-1
517
+ const S = P.scaled();
518
+ if (omegaOf !== undefined) {
519
+ const { mant, exp } = scaledMeat(S, weightedCrossprod(S.T, omegaOf(S.u.map((v) => v * v)), n));
520
+ vcov = withScale(mant, exp);
521
+ }
522
+ else {
523
+ const g = commonScale(omega.map(toPair), true);
524
+ vcov = withScale(weightedCrossprod(S.omegaPart().T, g.v, n), S.e.map((e) => g.s / 2 + e));
525
+ }
526
+ }
527
+ vcov = rescaled(vcov, -P.k);
528
+ }
529
+ else {
530
+ const M = weightedCrossprod(P.X, omega, n);
531
+ vcov = sandwichOf(P.A, M, n * P.phiS * P.phiS);
532
+ if (!plainOk(P, M, vcov, (omegaOf === undefined ? omega : res).every((v) => v === 0))) {
533
+ // in units of powers of 2 (ScaledParts)
534
+ const S = P.scaled();
535
+ if (omegaOf !== undefined) {
536
+ const Vs = sandwichOf(S.B, weightedCrossprod(S.T, omegaOf(S.u.map((v) => v * v)), n), n);
537
+ vcov = withScale(Vs, S.e.map((e) => S.s - e));
538
+ }
539
+ else {
540
+ const { T, factor } = S.omegaPart();
541
+ const g = commonScale(omega.map((o) => mulPair(toPair(o), factor)), true);
542
+ vcov = withScale(sandwichOf(S.B, weightedCrossprod(T, g.v, n), n), S.e.map((e) => g.s / 2 - e));
543
+ }
544
+ }
545
+ vcov = rescaled(vcov, P.k);
546
+ }
547
+ return reported("vcovHC", { vcov, names: P.names, warnings }, fit);
548
+ }
549
+ const CL_TYPES = ["HC", "HC0", "HC1", "HC2", "HC3"];
550
+ /** The text of a cluster label (R compares the labels as text: 1 and "1" are one cluster) */
551
+ function labelKey(v) {
552
+ if (v === null || v === undefined || (typeof v === "number" && Number.isNaN(v))) {
553
+ throw new RangeError("cannot handle NAs in 'cluster': either refit the model without the NA observations in 'cluster' or impute the NAs");
554
+ }
555
+ if (typeof v === "boolean")
556
+ return v ? "TRUE" : "FALSE";
557
+ if (typeof v === "number")
558
+ return levelText(v);
559
+ if (typeof v === "string")
560
+ return v;
561
+ throw new TypeError("cluster labels must be numbers, strings or booleans");
562
+ }
563
+ /** Group indices (0..G-1, in order of first appearance) of keys */
564
+ function groupsOf(keys) {
565
+ const map = new Map();
566
+ const g = keys.map((s) => {
567
+ let v = map.get(s);
568
+ if (v === undefined) {
569
+ v = map.size;
570
+ map.set(s, v);
571
+ }
572
+ return v;
573
+ });
574
+ return { g, G: map.size };
575
+ }
576
+ /** All non-empty subsets of 0..d-1, by size and then lexicographically (R's combn order) */
577
+ function subsets(d) {
578
+ const out = [];
579
+ const rec = (size, start, cur) => {
580
+ if (cur.length === size) {
581
+ out.push(cur.slice());
582
+ return;
583
+ }
584
+ for (let i = start; i < d; i++) {
585
+ cur.push(i);
586
+ rec(size, i + 1, cur);
587
+ cur.pop();
588
+ }
589
+ };
590
+ for (let s = 1; s <= d; s++)
591
+ rec(s, 0, []);
592
+ return out;
593
+ }
594
+ /** The smallest eigenvalue of a block I - H_gg that is not singular (sandwich's eps^(1/1.3)) */
595
+ const SINGULAR = EPS ** (1 / 1.3);
596
+ /** M^p of a symmetric positive definite matrix by its eigen decomposition (p = -1/2 or -1); undefined if singular */
597
+ function symmetricPower(m, p) {
598
+ const { values, vectors } = eigen(m, { symmetric: true });
599
+ // eigenvalues below eps^(1/1.3) count as 0, as sandwich: the block is singular (cluster fixed effects)
600
+ if (values.some((l) => !(l >= SINGULAR)))
601
+ return undefined;
602
+ const V = vectors;
603
+ const f = values.map((l) => l ** p);
604
+ return m.map((_, i) => m.map((_, j) => V[i].reduce((s, v, l) => s + v * f[l] * V[j][l], 0)));
605
+ }
606
+ function plainRows(P) {
607
+ return {
608
+ A: P.A,
609
+ xs: (i) => P.X[i].map((v) => v * Math.sqrt(P.W[i])),
610
+ rs: (i) => {
611
+ const sw = Math.sqrt(P.W[i]);
612
+ return sw === 0 ? 0 : P.res[i] / sw;
613
+ },
614
+ single: (i, f, d) => P.X[i].map((x) => f * P.res[i] * d * x),
615
+ psi: (i) => P.X[i].map((v) => v * P.res[i]),
616
+ };
617
+ }
618
+ function scaledRows(S) {
619
+ return {
620
+ A: S.B,
621
+ xs: (i) => S.T[i],
622
+ rs: (i) => S.u[i],
623
+ single: (i, f, d) => S.T[i].map((x) => f * S.u[i] * d * x),
624
+ psi: (i) => S.T[i].map((v) => v * S.u[i]),
625
+ };
626
+ }
627
+ /**
628
+ * The estimating functions of a clustering term adjusted for HC2 (power -1/2) or HC3 (-1), in sums per cluster: for
629
+ * each cluster g, U_g = (W_g^½ X_g)' (I - Hs_g)^p (W_g^-½ res_g) with Hs_g = W_g^½ X_g A X_g' W_g^½ (the symmetric
630
+ * form of Bell and McCaffrey 2002 and Pustejovsky and Tipton 2018; for HC3 the leave-one-cluster-out jackknife). A
631
+ * cluster of one row uses its hat value, U = res x / (1 - h)^-p; where every cluster has one row (G = n) a hat value
632
+ * of 1 is an error, otherwise the 1 x 1 block I - H_gg = 1 - h is singular below the threshold of larger blocks, as
633
+ * sandwich's eigenvalues. Times sqrt((G - 1)/G)
634
+ */
635
+ function adjustedSums(P, C, g, G, power) {
636
+ const k = P.names.length;
637
+ const members = Array.from({ length: G }, () => []);
638
+ g.forEach((c, i) => members[c].push(i));
639
+ const f = Math.sqrt((G - 1) / G);
640
+ const allSingle = G === g.length;
641
+ let leading;
642
+ return members.map((rows, c) => {
643
+ if (rows.length === 1) {
644
+ const i = rows[0];
645
+ if (allSingle ? P.h[i] >= 1 : !(P.omh[i] >= SINGULAR))
646
+ throw singularBlock(c);
647
+ return C.single(i, f, P.omh[i] ** power);
648
+ }
649
+ const Xs = rows.map(C.xs);
650
+ const rs = rows.map(C.rs);
651
+ if (P.qr !== undefined && P.rank > 0) {
652
+ leading ??= qrLeading(P.qr, P.rank);
653
+ const v = complementPower(P, leading, rows, rs, power);
654
+ if (v === null)
655
+ throw singularBlock(c);
656
+ if (v !== undefined)
657
+ return Array.from({ length: k }, (_, j) => f * Xs.reduce((s, x, a) => s + x[j] * v[a], 0));
658
+ }
659
+ const XA = Xs.map((x) => Array.from({ length: k }, (_, j) => x.reduce((s, v, l) => s + v * C.A[l][j], 0)));
660
+ const IH = Xs.map((_, a) => Xs.map((xb, b) => (a === b ? 1 : 0) - XA[a].reduce((s, v, l) => s + v * xb[l], 0)));
661
+ for (let a = 0; a < IH.length; a++)
662
+ for (let b = 0; b < a; b++)
663
+ IH[a][b] = IH[b][a] = (IH[a][b] + IH[b][a]) / 2;
664
+ const Mg = symmetricPower(IH, power);
665
+ if (Mg === undefined)
666
+ throw singularBlock(c);
667
+ const v = Mg.map((r) => r.reduce((s, m, b) => s + m * rs[b], 0));
668
+ return Array.from({ length: k }, (_, j) => f * Xs.reduce((s, x, a) => s + x[j] * v[a], 0));
669
+ });
670
+ }
671
+ /**
672
+ * (I - H_gg)^p r for a block of rows whose H_gg has an eigenvalue above 1/2, where I - H_gg by subtraction loses the
673
+ * digits of that eigenvalue (an error of eps / (1 - lambda), as 1 - h for one row; Bell and McCaffrey's adjustment
674
+ * then had relative errors of 3e-5 at 1 - lambda = 2.5e-11). With Q1_g the block's rows of the first `rank` columns of
675
+ * Q (H_gg = Q1_g Q1_g') and Q1_g' Q1_g = V diag(s) V', the vectors w_j = Q1_g v_j (|w_j|^2 = s_j) span the range of
676
+ * H_gg and I - H_gg = I - sum_j w_j w_j' (I - H_gg is the identity on the rest). For s_j <= 1/2 the eigenvalue 1 - s_j
677
+ * is formed directly; for the others, u_j = w_j / sqrt(s_j) put in the block's rows of a vector of length m has Q'u
678
+ * with |Q1'u|^2 = s_j and |Q2'u|^2 = 1 - s_j, Q2 the trailing columns of the full Q: the matrix Z'Z, Z = Q2' [u_j],
679
+ * is u_j' (I - H_gg) u_l without cancellation (the trailing columns as in oneMinusHat). So (I - H_gg)^p = I + sum_(s_j
680
+ * <= 1/2) ((1 - s_j)^p - 1) / s_j w_j w_j' + U ((Z'Z)^p - I) U'. undefined where no eigenvalue exceeds 1/2 (the
681
+ * subtraction is exact enough there, and its bits are kept); null where the block is singular (an eigenvalue of Z'Z
682
+ * below the threshold of symmetricPower)
683
+ */
684
+ function complementPower(P, leading, rows, r, power) {
685
+ const qr = P.qr;
686
+ const rank = P.rank;
687
+ const zero = new Array(rank).fill(0);
688
+ const Qg = rows.map((i) => {
689
+ const q = P.qrRow(i);
690
+ return q < 0 ? zero : leading[q];
691
+ });
692
+ const gram = Array.from({ length: rank }, (_, a) => Array.from({ length: rank }, (_, b) => Qg.reduce((s, q) => s + q[a] * q[b], 0)));
693
+ const { values, vectors } = eigen(gram, { symmetric: true });
694
+ if (!values.some((s) => s > 0.5))
695
+ return undefined;
696
+ const V = vectors;
697
+ const out = r.slice();
698
+ const big = [];
699
+ values.forEach((s, j) => {
700
+ const w = Qg.map((q) => q.reduce((t, v, l) => t + v * V[l][j], 0));
701
+ if (s > 0.5)
702
+ big.push(w.map((v) => v / Math.sqrt(s)));
703
+ else if (s > 0) {
704
+ // ((1 - s)^p - 1) / s without cancellation for small s
705
+ const c = Math.expm1(power * Math.log1p(-s)) / s;
706
+ const t = c * w.reduce((a, v, i) => a + v * r[i], 0);
707
+ w.forEach((v, i) => (out[i] += t * v));
708
+ }
709
+ });
710
+ const m = qr.qr.length;
711
+ const Z = big.map((u) => {
712
+ const e = new Array(m).fill(0);
713
+ rows.forEach((i, a) => {
714
+ const q = P.qrRow(i);
715
+ if (q >= 0)
716
+ e[q] = u[a];
717
+ });
718
+ return qrQty(qr, e).slice(rank);
719
+ });
720
+ const ZZ = Z.map((za) => Z.map((zb) => za.reduce((s, v, l) => s + v * zb[l], 0)));
721
+ const Mp = symmetricPower(ZZ, power);
722
+ if (Mp === undefined)
723
+ return null;
724
+ // U ((Z'Z)^p - I) U' r
725
+ const ur = big.map((u) => u.reduce((s, v, i) => s + v * r[i], 0));
726
+ const t = Mp.map((row, a) => row.reduce((s, v, b) => s + v * ur[b], 0) - ur[a]);
727
+ big.forEach((u, a) => u.forEach((v, i) => (out[i] += t[a] * v)));
728
+ return out;
729
+ }
730
+ function singularBlock(c) {
731
+ return new RangeError(`clustered HC2/HC3 covariances are undefined: the block I - H_gg of cluster ${c + 1} (in order of appearance) is singular, as with cluster fixed effects`);
732
+ }
733
+ /** sum_g U_g U_g' */
734
+ function outerSum(U, k) {
735
+ const S = Array.from({ length: k }, () => new Array(k).fill(0));
736
+ for (const u of U)
737
+ for (let a = 0; a < k; a++)
738
+ for (let b = 0; b < k; b++)
739
+ S[a][b] += u[a] * u[b];
740
+ return S;
741
+ }
742
+ /** Q diag(max(lambda, 0)) Q' of a symmetric matrix with some negative eigenvalue; the matrix itself otherwise */
743
+ function fixNegative(V) {
744
+ if (V.length === 0)
745
+ return V;
746
+ const { values, vectors } = eigen(V, { symmetric: true });
747
+ if (values.every((l) => l >= 0))
748
+ return V;
749
+ const Q = vectors;
750
+ const l = values.map((v) => Math.max(v, 0));
751
+ return V.map((_, i) => V.map((_, j) => Q[i].reduce((s, q, m) => s + q * l[m] * Q[j][m], 0)));
752
+ }
753
+ /**
754
+ * fixNegative of a matrix kept as mant_ab 2^(exp_a + exp_b) (see ScaledVcov). Whether an eigenvalue is negative is
755
+ * decided on the equilibrated matrix D^-1 V D^-1, D = sqrt(|diag V|), whose entries mant_ab / sqrt(|mant_aa mant_bb|)
756
+ * are near 1 whatever the units (the signs of the eigenvalues are those of V: Sylvester's law of inertia), with a
757
+ * margin of rounding (16 k eps of its largest eigenvalue): then the matrix and its exponents are kept as they are. A
758
+ * negative eigenvalue is set to 0 in one common unit (that of the largest exponent), as the truncation is defined in the
759
+ * units of V and does not commute with a diagonal scaling: coefficients whose scale is about 2^537 or more below the
760
+ * largest then get variance 0 (see docs/differences-from-r.md). Before, the common unit was used in every case, so
761
+ * that such coefficients got variance 0 also for a positive definite matrix
762
+ */
763
+ function fixScaled(mant, exp) {
764
+ const k = mant.length;
765
+ if (k === 0)
766
+ return { mant, exp };
767
+ const d = mant.map((r, a) => (r[a] !== 0 ? Math.sqrt(Math.abs(r[a])) : 1));
768
+ const C = mant.map((r, a) => r.map((v, b) => v / d[a] / d[b]));
769
+ const { values } = eigen(C, { symmetric: true });
770
+ const top = values.reduce((m, l) => Math.max(m, Math.abs(l)), 0);
771
+ if (values.every((l) => l >= -16 * k * EPS * top))
772
+ return { mant, exp };
773
+ const t = Math.max(...exp);
774
+ return { mant: fixNegative(mant.map((r, a) => r.map((v, b) => scaledEntry(v, exp[a] + exp[b] - 2 * t)))), exp: exp.map(() => t) };
775
+ }
776
+ /**
777
+ * Whether the meat in plain doubles can be trusted (with `sandwich: false`): every entry finite and the diagonal
778
+ * representable (2^-969 up to the largest double), or all residual factors 0. Otherwise (huge or tiny residual factors:
779
+ * entries Infinity - Infinity = NaN, or 0) it is formed in units of powers of 2 (scaledMeat)
780
+ */
781
+ function meatOk(M, zero) {
782
+ return zero || M.every((r, a) => representable(r[a]) && r.every(Number.isFinite));
783
+ }
784
+ /**
785
+ * The meat from its form in the units of ScaledParts: sum psi_i psi_i' / n (or the cluster sums) with psi_i =
786
+ * (T_i u_i) D 2^s / c, where c = phi_s (glm) or 2^-qw (lm) is the square root of the factor of S.omegaPart; so M_ab =
787
+ * Ms_ab / c~^2 2^(exp_a + exp_b), exp_a = s + e_a - x for c^2 = c~^2 2^2x
788
+ */
789
+ function scaledMeat(S, Ms) {
790
+ const [fm, fx] = S.omegaPart().factor;
791
+ return { mant: Ms.map((r) => r.map((v) => v / fm)), exp: S.e.map((e) => S.s + e - fx / 2) };
792
+ }
793
+ /**
794
+ * Clustered covariance matrix of the coefficients of an `lm` or `glm` fit. Equivalent to R's
795
+ * `sandwich::vcovCL()`.
796
+ *
797
+ * The meat sums the estimating functions within each cluster (Zeileis, Köll and Graham 2020), times G / (G - 1) with
798
+ * `cadjust`; HC1 multiplies by (n - 1) / (n - k). Several clustering dimensions are combined by inclusion and exclusion
799
+ * over all their intersections, each term with its own G (Cameron, Gelbach and Miller 2011); `multi0` uses clusters of
800
+ * one observation for the full intersection. HC2 and HC3 adjust each cluster's residuals by (I - H_gg)^-1/2 or
801
+ * (I - H_gg)^-1 in the symmetric form of Bell and McCaffrey (2002) (for HC3 the leave-one-cluster-out jackknife),
802
+ * which is sandwich's for an unweighted lm; sandwich transposes the adjustment for a weighted lm or a glm. A singular
803
+ * block (cluster fixed effects) is an error. `fix` sets negative eigenvalues to 0.
804
+ *
805
+ * The default type is HC1 for an lm and HC0 for a glm, as sandwich. Without `cluster` each observation is its own
806
+ * cluster. G is the number of distinct labels among the rows used (labels are compared as text, numbers with 15
807
+ * significant digits as R's `as.character`: 1 and 1 + 2^-52, or 0.1 + 0.2 and 0.3, are one label); intersections of
808
+ * dimensions are tuples of labels; at least two clusters are needed. Rows of prior weight 0 are left out. HC1 needs
809
+ * more observations than coefficients. Data far from 1 as {@link vcovHC} (the same record of the units, lost by a copy
810
+ * of the matrix); with `fix`, a negative eigenvalue is set to 0 in the units of the largest coefficient's variance, so
811
+ * that coefficients whose scale is about 2^537 or more below it then get variance 0. See docs/differences-from-r.md.
812
+ *
813
+ * @param fit The result of {@link lm} or {@link glm}.
814
+ *
815
+ * @example
816
+ * ```ts
817
+ * const fit = lm([1, 2, 3, 4, 5, 6, 7, 8], [1.2, 1.9, 3.2, 3.8, 5.3, 5.9, 7.1, 8.2]);
818
+ * vcovCL(fit, { cluster: ["a", "a", "b", "b", "c", "c", "d", "d"] }).vcov;
819
+ * // [[0.002257, -0.00053463], [-0.00053463, 0.00016363]] (HC1)
820
+ * ```
821
+ *
822
+ * @category Linear models and ANOVA
823
+ */
824
+ export function vcovCL(fit, options = {}) {
825
+ checkOptions(options, VCOV_CL_KEYS, "vcovCL"); // generated: option-keys.mjs
826
+ checkFit(fit);
827
+ const P = partsOf(fit, true);
828
+ const n = P.X.length;
829
+ const k = P.names.length;
830
+ const given = options.type === undefined ? (P.glm ? "HC0" : "HC1") : matchChoice(options.type, CL_TYPES);
831
+ const type = given === "HC" ? "HC0" : given;
832
+ const cadjust = options.cadjust ?? true;
833
+ const multi0 = options.multi0 ?? false;
834
+ const fix = options.fix ?? false;
835
+ const sandwich = options.sandwich ?? true;
836
+ for (const [name, v] of [["cadjust", cadjust], ["multi0", multi0], ["fix", fix], ["sandwich", sandwich]]) {
837
+ if (typeof v !== "boolean")
838
+ throw new TypeError(`'${name}' must be true or false`);
839
+ }
840
+ // the labels of the n rows, per dimension
841
+ let dims;
842
+ const cl = options.cluster;
843
+ if (cl === undefined)
844
+ dims = [P.inputRows.map(String)];
845
+ else {
846
+ const isList = (c) => Array.isArray(c) || ArrayBuffer.isView(c);
847
+ if (!isList(cl))
848
+ throw new TypeError("'cluster' must be an array of labels or an array of such arrays");
849
+ const multi = cl.length > 0 && Array.from(cl).every(isList);
850
+ const given = (multi ? Array.from(cl) : [cl]);
851
+ if (given.length === 0)
852
+ throw new RangeError("'cluster' has no dimension");
853
+ dims = given.map((c) => {
854
+ if (c.length !== P.nInput)
855
+ throw new RangeError("number of observations in 'cluster' and 'estfun()' do not match");
856
+ return P.inputRows.map((r) => labelKey(c[r]));
857
+ });
858
+ }
859
+ // (n - 1) / (n - k) is infinite for as many observations as coefficients (R: a matrix of NaN): an error
860
+ if (type === "HC1" && n <= k)
861
+ throw new RangeError("HC1 covariances need more observations than coefficients");
862
+ const d = dims.length;
863
+ const terms = subsets(d).map((S, t) => {
864
+ const last = multi0 && d > 1 && t === 2 ** d - 2;
865
+ const keys = last ? P.inputRows.map(String) : P.inputRows.map((_, i) => (S.length === 1 ? dims[S[0]][i] : JSON.stringify(S.map((j) => dims[j][i]))));
866
+ const { g, G } = groupsOf(keys);
867
+ if (G < 2)
868
+ throw new RangeError("at least two clusters are needed");
869
+ const c = last ? (type === "HC1" ? (n - k) / (n - 1) : 1) : cadjust ? G / (G - 1) : 1;
870
+ return { g, G, c, sign: S.length % 2 === 1 ? 1 : -1 };
871
+ });
872
+ /** The meat from the rows C (plain or scaled) */
873
+ const meatOf = (C) => {
874
+ let M = Array.from({ length: k }, () => new Array(k).fill(0));
875
+ for (const { g, G, c, sign } of terms) {
876
+ let U;
877
+ if (type === "HC2" || type === "HC3")
878
+ U = adjustedSums(P, C, g, G, type === "HC2" ? -0.5 : -1);
879
+ else if (G === n)
880
+ U = P.X.map((_, i) => C.psi(i));
881
+ else {
882
+ U = Array.from({ length: G }, () => new Array(k).fill(0));
883
+ P.X.forEach((_, i) => {
884
+ const u = U[g[i]];
885
+ const p = C.psi(i);
886
+ for (let j = 0; j < k; j++)
887
+ u[j] += p[j];
888
+ });
889
+ }
890
+ const Sg = outerSum(U, k);
891
+ M = M.map((r, a) => r.map((v, b) => v + (sign * c * Sg[a][b]) / n));
892
+ }
893
+ if (type === "HC1")
894
+ M = M.map((r) => r.map((v) => (v * (n - 1)) / (n - k)));
895
+ return M;
896
+ };
897
+ const zero = P.res.every((v) => v === 0);
898
+ // the plain sandwich where its pieces are in range (the adjusted sums of HC2 and HC3 would fail on NaN otherwise)
899
+ const inRange = P.phiS >= SAFE && P.phiS < Infinity && P.A.every((r, a) => representable(r[a])) && P.res.every(Number.isFinite);
900
+ let vcov;
901
+ if (inRange) {
902
+ const M = meatOf(plainRows(P));
903
+ if (!sandwich) {
904
+ if (meatOk(M, zero))
905
+ vcov = fix ? fixNegative(M) : M;
906
+ }
907
+ else {
908
+ const V = sandwichOf(P.A, M, n * P.phiS * P.phiS);
909
+ if (plainOk(P, M, V, zero))
910
+ vcov = fix ? fixNegative(V) : V;
911
+ }
912
+ }
913
+ if (vcov === undefined) {
914
+ // in units of powers of 2 (ScaledParts); fix on the equilibrated matrix (fixScaled)
915
+ const S = P.scaled();
916
+ const Ms = meatOf(scaledRows(S));
917
+ const { mant, exp } = sandwich ? { mant: sandwichOf(S.B, Ms, n), exp: S.e.map((e) => S.s - e) } : scaledMeat(S, Ms);
918
+ const fixed = fix ? fixScaled(mant, exp) : { mant, exp };
919
+ vcov = withScale(fixed.mant, fixed.exp);
920
+ }
921
+ vcov = rescaled(vcov, sandwich ? P.k : -P.k);
922
+ return reported("vcovCL", { vcov, names: P.names, warnings: [] }, fit);
923
+ }