@numero-uno-jpn/rstats 0.8.0 → 0.9.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 (39) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.ja.md +36 -9
  3. package/README.md +38 -10
  4. package/THIRD_PARTY_NOTICES.md +5 -0
  5. package/dist/chunks/chunk-24U4DKRY.js +2 -0
  6. package/dist/chunks/{chunk-XU4BGFZ6.js → chunk-5K4PS7IV.js} +2 -2
  7. package/dist/chunks/{chunk-VIPSPG3Y.js → chunk-BGVMSDVJ.js} +2 -2
  8. package/dist/chunks/{chunk-3I6EKGB6.js → chunk-FC2TLHZC.js} +2 -2
  9. package/dist/chunks/{chunk-OHPHNE3O.js → chunk-H2AP6TCR.js} +1 -1
  10. package/dist/chunks/{chunk-LXMMKO26.js → chunk-IVOBWYLV.js} +2 -2
  11. package/dist/chunks/{chunk-JVYV4633.js → chunk-JLSTEMSN.js} +1 -1
  12. package/dist/chunks/chunk-LE7TBHNI.js +2 -0
  13. package/dist/chunks/{chunk-32PRRONF.js → chunk-LWUSYIQ4.js} +1 -1
  14. package/dist/chunks/{chunk-RZ7SBJEG.js → chunk-MF4VBCHQ.js} +2 -2
  15. package/dist/chunks/{chunk-U633VFH3.js → chunk-MSAUU6PY.js} +2 -2
  16. package/dist/chunks/{chunk-YGWPU67I.js → chunk-TOVTN5Y2.js} +1 -1
  17. package/dist/chunks/{chunk-I3LAZE6C.js → chunk-YC4JWUKG.js} +2 -2
  18. package/dist/chunks/{chunk-SPQC445Q.js → chunk-ZRO446BP.js} +2 -2
  19. package/dist/descriptive.js +2 -2
  20. package/dist/distributions.js +2 -2
  21. package/dist/entries/tests.d.ts +3 -0
  22. package/dist/entries/tests.js +3 -0
  23. package/dist/linalg.js +2 -2
  24. package/dist/models/glm.d.ts +226 -0
  25. package/dist/models/glm.js +546 -0
  26. package/dist/models/glmAnova.d.ts +31 -0
  27. package/dist/models/glmAnova.js +146 -0
  28. package/dist/models/glmConfint.d.ts +25 -0
  29. package/dist/models/glmConfint.js +139 -0
  30. package/dist/models/glmFamily.d.ts +66 -0
  31. package/dist/models/glmFamily.js +359 -0
  32. package/dist/numerics.js +2 -2
  33. package/dist/rstats.js +4 -3
  34. package/dist/special.js +2 -2
  35. package/dist/tests.js +4 -3
  36. package/package.json +1 -1
  37. package/dist/chunks/chunk-EJRCDJ76.js +0 -2
  38. package/dist/chunks/chunk-JERGQKZM.js +0 -2
  39. package/dist/chunks/chunk-MJQLKEO5.js +0 -2
@@ -0,0 +1,546 @@
1
+ // Generalized linear models with a matrix interface: R's glm (the fit of glm.fit), summary.glm, the four kinds of
2
+ // residuals, hatvalues, rstandard, cooks.distance and predict (with standard errors).
3
+ //
4
+ // Written for rStats.js (no ported code) from oracle/glm-behaviour.md (a description of R's behaviour), R's help
5
+ // pages (?glm, ?glm.control, ?summary.glm, ?predict.glm, ?influence.measures) and McCullagh and Nelder (1989),
6
+ // Generalized Linear Models, 2nd ed., section 2.5 (iteratively reweighted least squares). The least squares steps use
7
+ // the QR decomposition of src/linalg/qr.ts with R's limited pivoting and the tolerance min(1e-7, epsilon / 1000), so
8
+ // that aliased columns are found as R finds them; their coefficients are NaN (R's NA).
9
+ import { pt1 } from "../distributions/t.js";
10
+ import { pnorm } from "../distributions/normal.js";
11
+ import { chol2inv } from "../linalg/chol.js";
12
+ import { qr, qrCoef, qrQy } from "../linalg/qr.js";
13
+ import { familyAic, makeFamily, prepareResponse, Warnings, withWarnings, } from "./glmFamily.js";
14
+ const EPS = 2 ** -52;
15
+ function deparseNames(names) {
16
+ const q = names.map((s) => `"${s}"`);
17
+ return q.length === 1 ? q[0] : `c(${q.join(", ")})`;
18
+ }
19
+ function linearPredictor(x, b, offset) {
20
+ return x.map((r, i) => {
21
+ let s = 0;
22
+ for (let j = 0; j < r.length; j++)
23
+ s += r[j] * b[j];
24
+ return s + offset[i];
25
+ });
26
+ }
27
+ function totalDeviance(fam, y, mu, w) {
28
+ let d = 0;
29
+ for (let i = 0; i < y.length; i++)
30
+ d += fam.devContribution(y[i], mu[i], w[i]);
31
+ return d;
32
+ }
33
+ /** Iteratively reweighted least squares (glm-behaviour.md, "Fitting") */
34
+ export function irls(inp, warnings) {
35
+ const { x, p, y, w, offset, fam, epsilon, maxit } = inp;
36
+ const n = y.length;
37
+ return withWarnings(warnings, () => {
38
+ const allOk = (eta, mu) => eta.every((e) => fam.etaOk(e)) && mu.every((m) => fam.muOk(m));
39
+ if (p === 0) {
40
+ // a model without columns: the linear predictor is the offset
41
+ const eta = offset.slice();
42
+ if (!eta.every((e) => fam.etaOk(e)))
43
+ throw new Error("invalid linear predictor values in empty model");
44
+ const mu = eta.map((e) => fam.linkinv(e));
45
+ if (!mu.every((m) => fam.muOk(m)))
46
+ throw new Error("invalid fitted means in empty model");
47
+ const me = eta.map((e) => fam.muEta(e));
48
+ const ww = mu.map((m, i) => Math.sqrt((w[i] * me[i] ** 2) / fam.variance(m)) ** 2);
49
+ return {
50
+ coefficients: [],
51
+ eta,
52
+ mu,
53
+ deviance: totalDeviance(fam, y, mu, w),
54
+ iter: 0,
55
+ converged: true,
56
+ boundary: true,
57
+ rank: 0,
58
+ qr: undefined,
59
+ used: w.map((v) => v > 0),
60
+ workingWeights: ww,
61
+ workingResiduals: y.map((v, i) => (v - mu[i]) / me[i]),
62
+ };
63
+ }
64
+ let eta;
65
+ let previous;
66
+ if (inp.start !== undefined) {
67
+ if (inp.start.length !== p) {
68
+ throw new RangeError(`length of 'start' should equal ${p} and correspond to initial coefs for ${deparseNames(inp.columnNames)}`);
69
+ }
70
+ previous = inp.start.slice();
71
+ eta = linearPredictor(x, previous, offset);
72
+ }
73
+ else if (inp.etastart !== undefined)
74
+ eta = inp.etastart.slice();
75
+ else
76
+ eta = inp.mustart.map((m) => fam.link(m));
77
+ let mu = eta.map((e) => fam.linkinv(e));
78
+ if (!allOk(eta, mu))
79
+ throw new Error("cannot find valid starting values: please specify some");
80
+ let devPrevious = totalDeviance(fam, y, mu, w);
81
+ let dev = devPrevious;
82
+ let converged = false;
83
+ let boundary = false;
84
+ let iter = 0;
85
+ let coef = new Array(p).fill(0);
86
+ let q;
87
+ let used = w.map(() => false);
88
+ let sqrtW = [];
89
+ const tol = Math.min(1e-7, epsilon / 1000);
90
+ for (iter = 1; iter <= maxit; iter++) {
91
+ const me = eta.map((e) => fam.muEta(e));
92
+ for (let i = 0; i < n; i++) {
93
+ if (!(w[i] > 0))
94
+ continue;
95
+ const v = fam.variance(mu[i]);
96
+ if (Number.isNaN(v))
97
+ throw new Error("NAs in V(mu)");
98
+ if (v === 0)
99
+ throw new Error("0s in V(mu)");
100
+ if (Number.isNaN(me[i]))
101
+ throw new Error("NAs in d(mu)/d(eta)");
102
+ }
103
+ used = w.map((v, i) => v > 0 && me[i] !== 0);
104
+ const rows = [];
105
+ for (let i = 0; i < n; i++)
106
+ if (used[i])
107
+ rows.push(i);
108
+ if (rows.length === 0) {
109
+ warnings.add(`no observations informative at iteration ${iter}`);
110
+ converged = false;
111
+ break;
112
+ }
113
+ sqrtW = new Array(n).fill(0);
114
+ const zw = [];
115
+ const xw = [];
116
+ for (const i of rows) {
117
+ const s = Math.sqrt((w[i] * me[i] ** 2) / fam.variance(mu[i]));
118
+ sqrtW[i] = s;
119
+ zw.push(((eta[i] - offset[i]) + (y[i] - mu[i]) / me[i]) * s);
120
+ xw.push(x[i].map((v) => v * s));
121
+ }
122
+ q = qr(xw, { tol });
123
+ const b = qrCoef(q, zw);
124
+ if (b.some((v, j) => q.pivot.indexOf(j) < q.rank && !Number.isFinite(v))) {
125
+ warnings.add(`non-finite coefficients at iteration ${iter}`);
126
+ converged = false;
127
+ break;
128
+ }
129
+ coef = b.map((v) => (Number.isNaN(v) ? 0 : v));
130
+ boundary = false;
131
+ eta = linearPredictor(x, coef, offset);
132
+ mu = eta.map((e) => fam.linkinv(e));
133
+ dev = totalDeviance(fam, y, mu, w);
134
+ if (!Number.isFinite(dev)) {
135
+ if (previous === undefined)
136
+ throw new Error("no valid set of coefficients has been found: please supply starting values");
137
+ warnings.add("step size truncated due to divergence");
138
+ let halvings = 0;
139
+ while (!Number.isFinite(dev)) {
140
+ if (halvings >= maxit)
141
+ throw new Error("inner loop 1; cannot correct step size");
142
+ halvings++;
143
+ coef = coef.map((v, j) => (v + previous[j]) / 2);
144
+ eta = linearPredictor(x, coef, offset);
145
+ mu = eta.map((e) => fam.linkinv(e));
146
+ dev = totalDeviance(fam, y, mu, w);
147
+ }
148
+ boundary = true;
149
+ }
150
+ if (!allOk(eta, mu)) {
151
+ if (previous === undefined)
152
+ throw new Error("no valid set of coefficients has been found: please supply starting values");
153
+ warnings.add("step size truncated: out of bounds");
154
+ let halvings = 0;
155
+ while (!allOk(eta, mu)) {
156
+ if (halvings >= maxit)
157
+ throw new Error("inner loop 2; cannot correct step size");
158
+ halvings++;
159
+ coef = coef.map((v, j) => (v + previous[j]) / 2);
160
+ eta = linearPredictor(x, coef, offset);
161
+ mu = eta.map((e) => fam.linkinv(e));
162
+ }
163
+ boundary = true;
164
+ dev = totalDeviance(fam, y, mu, w);
165
+ }
166
+ if (inp.untilCoefficients) {
167
+ const scale = Math.max(...coef.map(Math.abs));
168
+ if (previous !== undefined && coef.every((v, j) => Math.abs(v - previous[j]) <= 8 * EPS * scale)) {
169
+ converged = true;
170
+ break;
171
+ }
172
+ }
173
+ else if (Math.abs(dev - devPrevious) / (Math.abs(dev) + 0.1) < epsilon) {
174
+ converged = true;
175
+ break;
176
+ }
177
+ devPrevious = dev;
178
+ previous = coef.slice();
179
+ }
180
+ if (iter > maxit)
181
+ iter = maxit;
182
+ let rank = p;
183
+ const coefficients = coef.slice();
184
+ if (q !== undefined) {
185
+ rank = q.rank;
186
+ for (let k = q.rank; k < p; k++)
187
+ coefficients[q.pivot[k]] = NaN;
188
+ }
189
+ const me = eta.map((e) => fam.muEta(e));
190
+ return {
191
+ coefficients,
192
+ eta,
193
+ mu,
194
+ deviance: dev,
195
+ iter,
196
+ converged,
197
+ boundary,
198
+ rank,
199
+ qr: q,
200
+ used,
201
+ workingWeights: sqrtW.map((s) => s * s),
202
+ workingResiduals: y.map((v, i) => (v - mu[i]) / me[i]),
203
+ };
204
+ });
205
+ }
206
+ function toRows(x) {
207
+ return x.length > 0 && typeof x[0] !== "number" ? x.map((r) => Array.from(r)) : Array.from(x, (v) => [v]);
208
+ }
209
+ /** After the fit: the warnings about convergence and fitted values at the boundary */
210
+ function finalWarnings(fit, fam, warnings, empty) {
211
+ if (empty)
212
+ return;
213
+ if (!fit.converged)
214
+ warnings.add("glm.fit: algorithm did not converge");
215
+ if (fit.boundary)
216
+ warnings.add("glm.fit: algorithm stopped at boundary value");
217
+ if (fam.family === "binomial" && fit.mu.some((m) => m > 1 - 10 * EPS || m < 10 * EPS)) {
218
+ warnings.add("glm.fit: fitted probabilities numerically 0 or 1 occurred");
219
+ }
220
+ if (fam.family === "poisson" && fit.mu.some((m) => m < 10 * EPS))
221
+ warnings.add("glm.fit: fitted rates numerically 0 occurred");
222
+ }
223
+ /** Fits a model from its stored data, with the columns `cols` of the model matrix (all by default) */
224
+ export function refit(model, cols, warnings, control = {}) {
225
+ const fam = makeFamily(model.familySpec);
226
+ const start = "start" in control ? control.start : model.start;
227
+ const prep = prepareResponse(fam, model.yGiven, model.priorGiven, start !== undefined || control.etastart !== undefined, warnings);
228
+ const offset = control.extraOffset === undefined ? model.offset : model.offset.map((o, i) => o + control.extraOffset[i]);
229
+ const x = model.x.map((r) => cols.map((j) => r[j]));
230
+ const fit = irls({
231
+ x,
232
+ p: cols.length,
233
+ y: prep.y,
234
+ w: prep.weights,
235
+ offset,
236
+ fam,
237
+ epsilon: control.epsilon ?? model.epsilon,
238
+ maxit: control.maxit ?? model.maxit,
239
+ columnNames: cols.map((j) => model.columnNames[j]),
240
+ start,
241
+ etastart: control.etastart,
242
+ mustart: prep.mustart,
243
+ untilCoefficients: control.untilCoefficients,
244
+ }, warnings);
245
+ finalWarnings(fit, fam, warnings, cols.length === 0);
246
+ return { fit, fam, y: prep.y, w: prep.weights, size: prep.size, offset };
247
+ }
248
+ /**
249
+ * Fit a generalized linear model by iteratively reweighted least squares. Equivalent to R's
250
+ * `glm(y ~ x, family = ...)` (or `y ~ x - 1` without intercept); the predictors are given as a matrix instead of a
251
+ * formula. Rows with a missing value (NaN) in `x`, `y`, the weights or the offset are dropped. Every family and link
252
+ * of R's `stats` is available; R's warnings are returned in `warnings`. See {@link glmSummary}, {@link glmResiduals},
253
+ * {@link glmPredict}, {@link glmConfint} and {@link glmAnova} for the methods.
254
+ *
255
+ * @param x Predictors: a matrix (array of rows, one column per predictor; rows of length 0 for a model with the
256
+ * intercept only) or a vector (one predictor).
257
+ * @param y Response: a vector, or for the binomial families rows of (successes, failures).
258
+ *
259
+ * @example
260
+ * ```ts
261
+ * const fit = glm([1, 2, 3, 4, 5, 6], [0, 0, 1, 0, 1, 1], { family: "binomial" });
262
+ * fit.coefficients; // [intercept, slope]
263
+ * glmSummary(fit).pValue;
264
+ * ```
265
+ */
266
+ export function glm(x, y, options = {}) {
267
+ const intercept = options.intercept ?? true;
268
+ const xr = toRows(x);
269
+ const yIsMatrix = y.length > 0 && typeof y[0] !== "number";
270
+ const yr = yIsMatrix ? y.map((r) => Array.from(r)) : Array.from(y);
271
+ const nAll = yr.length;
272
+ if (xr.length !== nAll)
273
+ throw new RangeError("variable lengths differ (found for 'x1')");
274
+ const wGiven = options.weights === undefined ? undefined : Array.from(options.weights);
275
+ if (wGiven !== undefined && wGiven.length !== nAll)
276
+ throw new RangeError("variable lengths differ (found for '(weights)')");
277
+ const oGiven = options.offset === undefined ? undefined : Array.from(options.offset);
278
+ if (oGiven !== undefined && oGiven.length !== nAll)
279
+ throw new RangeError("variable lengths differ (found for '(offset)')");
280
+ const keep = xr.map((r, i) => {
281
+ const yi = yr[i];
282
+ const yNa = Array.isArray(yi) ? yi.some((v) => Number.isNaN(v)) : Number.isNaN(yi);
283
+ return !yNa && r.every((v) => !Number.isNaN(v)) && !(wGiven !== undefined && Number.isNaN(wGiven[i])) && !(oGiven !== undefined && Number.isNaN(oGiven[i]));
284
+ });
285
+ const X = xr.filter((_, i) => keep[i]).map((r) => (intercept ? [1, ...r] : r));
286
+ const yGiven = yr.filter((_, i) => keep[i]);
287
+ const n = yGiven.length;
288
+ if (n === 0)
289
+ throw new RangeError("0 (non-NA) cases");
290
+ const priorGiven = wGiven === undefined ? new Array(n).fill(1) : wGiven.filter((_, i) => keep[i]);
291
+ if (priorGiven.some((v) => v < 0))
292
+ throw new RangeError("negative weights not allowed");
293
+ const offset = oGiven === undefined ? new Array(n).fill(0) : oGiven.filter((_, i) => keep[i]);
294
+ const nx = xr.length > 0 ? xr[0].length : 0;
295
+ const columnNames = [...(intercept ? ["(Intercept)"] : []), ...Array.from({ length: nx }, (_, j) => `x${j + 1}`)];
296
+ const p = columnNames.length;
297
+ if (X.some((r) => r.length !== p))
298
+ throw new TypeError("all rows of x must have the same length");
299
+ const familySpec = typeof options.family === "object" ? { ...options.family } : { family: options.family ?? "gaussian" };
300
+ if (options.link !== undefined)
301
+ familySpec.link = options.link;
302
+ const model = {
303
+ x: X,
304
+ columnNames,
305
+ yGiven,
306
+ priorGiven,
307
+ offset,
308
+ hasOffset: oGiven !== undefined,
309
+ intercept,
310
+ familySpec,
311
+ epsilon: options.epsilon ?? 1e-8,
312
+ maxit: options.maxit ?? 25,
313
+ start: options.start === undefined ? undefined : Array.from(options.start),
314
+ };
315
+ if (!(model.epsilon > 0))
316
+ throw new RangeError("value of 'epsilon' must be > 0");
317
+ if (!(model.maxit > 0))
318
+ throw new RangeError("maximum number of iterations must be > 0");
319
+ const warnings = new Warnings();
320
+ const all = Array.from({ length: p }, (_, j) => j);
321
+ const { fit, fam, y: yy, w, size } = refit(model, all, warnings);
322
+ // null deviance: the constant weighted mean (with an intercept) or the inverse link of the offset
323
+ let nullDeviance;
324
+ if (intercept && model.hasOffset) {
325
+ const nullWarnings = new Warnings();
326
+ const nf = irls({ x: X.map(() => [1]), p: 1, y: yy, w, offset, fam, epsilon: model.epsilon, maxit: model.maxit, columnNames: ["(Intercept)"], mustart: fit.mu }, nullWarnings);
327
+ finalWarnings(nf, fam, nullWarnings, false);
328
+ nullWarnings.list.forEach((m) => warnings.add(m));
329
+ nullDeviance = nf.deviance;
330
+ if (!nf.converged)
331
+ warnings.add("fitting to calculate the null deviance did not converge -- increase 'maxit'?");
332
+ }
333
+ else if (intercept) {
334
+ let sw = 0;
335
+ let swy = 0;
336
+ for (let i = 0; i < n; i++) {
337
+ sw += w[i];
338
+ swy += w[i] * yy[i];
339
+ }
340
+ const m = swy / sw;
341
+ nullDeviance = totalDeviance(fam, yy, yy.map(() => m), w);
342
+ }
343
+ else
344
+ nullDeviance = totalDeviance(fam, yy, withWarnings(warnings, () => offset.map((o) => fam.linkinv(o))), w);
345
+ const nOk = n - w.filter((v) => v === 0).length;
346
+ const aic = familyAic(fam, yy, fit.mu, w, size, fit.deviance, warnings) + 2 * fit.rank;
347
+ return {
348
+ coefficients: fit.coefficients,
349
+ fittedValues: fit.mu,
350
+ linearPredictors: fit.eta,
351
+ deviance: fit.deviance,
352
+ nullDeviance,
353
+ aic,
354
+ rank: fit.rank,
355
+ dfResidual: nOk - fit.rank,
356
+ dfNull: nOk - (intercept ? 1 : 0),
357
+ iter: fit.iter,
358
+ converged: fit.converged,
359
+ boundary: fit.boundary,
360
+ y: yy,
361
+ priorWeights: w,
362
+ weights: fit.workingWeights,
363
+ residuals: fit.workingResiduals,
364
+ family: fam.family,
365
+ link: fam.name,
366
+ warnings: warnings.list,
367
+ qr: fit.qr,
368
+ model,
369
+ };
370
+ }
371
+ /** The family object of a fit */
372
+ export function familyOf(fit) {
373
+ return makeFamily(fit.model.familySpec);
374
+ }
375
+ /** Pearson dispersion of summary.glm (1 for binomial and poisson) */
376
+ export function glmDispersion(fit, warnings) {
377
+ if (familyOf(fit).fixedDispersion)
378
+ return 1;
379
+ if (fit.dfResidual <= 0)
380
+ return NaN;
381
+ let s = 0;
382
+ for (let i = 0; i < fit.weights.length; i++)
383
+ if (fit.weights[i] > 0)
384
+ s += fit.weights[i] * fit.residuals[i] ** 2;
385
+ if (fit.weights.some((v) => v === 0))
386
+ warnings?.add("observations with zero weight not used for calculating dispersion");
387
+ return s / fit.dfResidual;
388
+ }
389
+ /** (R'R)^-1 of the leading rank x rank block of the last QR, in pivot order */
390
+ function unscaledCovariance(fit) {
391
+ if (fit.qr === undefined || fit.rank === 0)
392
+ return [];
393
+ const Rr = fit.qr.qr.slice(0, fit.rank).map((row) => row.slice(0, fit.rank));
394
+ return chol2inv(Rr);
395
+ }
396
+ /**
397
+ * Summary of a generalized linear model: the dispersion, the coefficient table and the covariance of the estimates.
398
+ * Equivalent to R's `summary()` for a `glm` fit.
399
+ */
400
+ export function glmSummary(fit, options = {}) {
401
+ const warnings = new Warnings();
402
+ const fam = familyOf(fit);
403
+ const estimated = options.dispersion === undefined && !fam.fixedDispersion;
404
+ const dispersion = options.dispersion ?? glmDispersion(fit, warnings);
405
+ const covUnscaled = unscaledCovariance(fit);
406
+ const piv = fit.qr === undefined ? [] : fit.qr.pivot.slice(0, fit.rank);
407
+ const estimate = piv.map((j) => fit.coefficients[j]);
408
+ const stdError = covUnscaled.map((r, k) => Math.sqrt(r[k] * dispersion));
409
+ const statistic = estimate.map((e, k) => e / stdError[k]);
410
+ const zTest = !estimated;
411
+ const pValue = statistic.map((t) => zTest ? 2 * pnorm(-Math.abs(t)) : fit.dfResidual > 0 ? 2 * pt1(-Math.abs(t), fit.dfResidual, true, false) : NaN);
412
+ if (estimated && fit.dfResidual === 0) {
413
+ stdError.fill(NaN);
414
+ statistic.fill(NaN);
415
+ }
416
+ return {
417
+ dispersion,
418
+ estimate,
419
+ stdError,
420
+ statistic,
421
+ pValue,
422
+ statisticName: fam.fixedDispersion ? "z value" : "t value",
423
+ covUnscaled,
424
+ covScaled: covUnscaled.map((r) => r.map((v) => v * dispersion)),
425
+ dfResidual: fit.dfResidual,
426
+ warnings: warnings.list,
427
+ };
428
+ }
429
+ /**
430
+ * Residuals of a generalized linear model, one per row. Equivalent to R's `residuals(fit, type)` for a `glm` fit
431
+ * (default `"deviance"`).
432
+ */
433
+ export function glmResiduals(fit, type = "deviance") {
434
+ const fam = familyOf(fit);
435
+ const { y, fittedValues: mu, priorWeights: w } = fit;
436
+ switch (type) {
437
+ case "response":
438
+ return y.map((v, i) => v - mu[i]);
439
+ case "working":
440
+ return fit.residuals.slice();
441
+ case "pearson":
442
+ return y.map((v, i) => ((v - mu[i]) * Math.sqrt(w[i])) / Math.sqrt(fam.variance(mu[i])));
443
+ case "deviance":
444
+ if (fit.dfResidual <= 0)
445
+ return y.map(() => 0);
446
+ return y.map((v, i) => Math.sign(v - mu[i]) * Math.sqrt(Math.max(fam.devContribution(v, mu[i], w[i]), 0)));
447
+ default:
448
+ throw new RangeError(`unknown type of residuals "${String(type)}"`);
449
+ }
450
+ }
451
+ /**
452
+ * Diagonal of the hat matrix of the last weighted least squares step, for the rows of non-zero prior weight.
453
+ * Equivalent to R's `hatvalues()` for a `glm` fit.
454
+ */
455
+ export function glmHatvalues(fit) {
456
+ const out = [];
457
+ const q = fit.qr;
458
+ let h = [];
459
+ if (q !== undefined && fit.rank > 0) {
460
+ const m = q.qr.length;
461
+ const e = Array.from({ length: m }, (_, i) => Array.from({ length: fit.rank }, (_, j) => (i === j ? 1 : 0)));
462
+ const Q = qrQy(q, e);
463
+ h = Q.map((r) => r.reduce((s, v) => s + v * v, 0));
464
+ }
465
+ // rows of the last least squares step, in order
466
+ let k = 0;
467
+ const usedRows = fit.weights.map((v) => v > 0);
468
+ fit.priorWeights.forEach((w, i) => {
469
+ const hi = usedRows[i] ? (h[k++] ?? 0) : 0;
470
+ if (w > 0)
471
+ out.push(hi > 1 - 10 * EPS ? 1 : hi);
472
+ });
473
+ return out;
474
+ }
475
+ function median(v) {
476
+ const s = v.slice().sort((a, b) => a - b);
477
+ const m = s.length >> 1;
478
+ return s.length % 2 === 1 ? s[m] : (s[m - 1] + s[m]) / 2;
479
+ }
480
+ /**
481
+ * Standardized deviance residuals, for the rows of non-zero prior weight. Equivalent to R's `rstandard()` for a
482
+ * `glm` fit.
483
+ */
484
+ export function glmRstandard(fit, options = {}) {
485
+ const h = glmHatvalues(fit);
486
+ const disp = options.dispersion ?? glmDispersion(fit);
487
+ const r = glmResiduals(fit, "deviance").filter((_, i) => fit.priorWeights[i] > 0);
488
+ const small = 100 * EPS * median(r.map(Math.abs));
489
+ return r.map((v, i) => {
490
+ const s = (Math.abs(v) < small ? 0 : v) / Math.sqrt(disp * (1 - h[i]));
491
+ return Number.isFinite(s) ? s : NaN;
492
+ });
493
+ }
494
+ /** Cook's distances, for the rows of non-zero prior weight. Equivalent to R's `cooks.distance()` for a `glm` fit. */
495
+ export function glmCooksDistance(fit, options = {}) {
496
+ const h = glmHatvalues(fit);
497
+ const disp = options.dispersion ?? glmDispersion(fit);
498
+ const r = glmResiduals(fit, "pearson").filter((_, i) => fit.priorWeights[i] > 0);
499
+ return r.map((v, i) => {
500
+ const c = (v / (1 - h[i])) ** 2 * (h[i] / (disp * fit.rank));
501
+ return Number.isFinite(c) ? c : NaN;
502
+ });
503
+ }
504
+ /**
505
+ * Predictions of a generalized linear model with their standard errors. Equivalent to R's
506
+ * `predict(fit, newdata, type, se.fit = TRUE)` for a `glm` fit. Aliased columns are left out, as R does.
507
+ */
508
+ export function glmPredict(fit, options = {}) {
509
+ const fam = familyOf(fit);
510
+ let X;
511
+ let eta;
512
+ if (options.newdata === undefined) {
513
+ X = fit.model.x;
514
+ eta = fit.linearPredictors.slice();
515
+ }
516
+ else {
517
+ X = toRows(options.newdata).map((r) => (fit.model.intercept ? [1, ...r] : r));
518
+ const off = options.newoffset === undefined ? X.map(() => 0) : Array.from(options.newoffset);
519
+ if (off.length !== X.length)
520
+ throw new RangeError("newoffset must have one value per row of newdata");
521
+ eta = X.map((r, i) => r.reduce((s, v, j) => (Number.isNaN(fit.coefficients[j]) ? s : s + v * fit.coefficients[j]), 0) + off[i]);
522
+ }
523
+ const disp = options.dispersion ?? glmDispersion(fit);
524
+ const rank = fit.rank;
525
+ const piv = fit.qr === undefined ? [] : fit.qr.pivot.slice(0, rank);
526
+ const R = fit.qr?.qr;
527
+ // || R^-T x_piv ||, by forward substitution with R^T
528
+ const se = X.map((r) => {
529
+ const z = new Array(rank).fill(0);
530
+ let ss = 0;
531
+ for (let i = 0; i < rank; i++) {
532
+ let s = r[piv[i]];
533
+ for (let k = 0; k < i; k++)
534
+ s -= R[k][i] * z[k];
535
+ z[i] = s / R[i][i];
536
+ ss += z[i] * z[i];
537
+ }
538
+ return Math.sqrt(ss) * Math.sqrt(disp);
539
+ });
540
+ if ((options.type ?? "link") === "link")
541
+ return { fit: eta, seFit: se };
542
+ return withWarnings(new Warnings(), () => ({
543
+ fit: eta.map((e) => fam.linkinv(e)),
544
+ seFit: se.map((s, i) => s * Math.abs(fam.muEta(eta[i]))),
545
+ }));
546
+ }
@@ -0,0 +1,31 @@
1
+ import { type GlmResult } from "./glm.js";
2
+ /** Tests of {@link glmAnova}. */
3
+ export type GlmAnovaTest = "Chisq" | "LRT" | "Rao" | "F" | "Cp";
4
+ /** Options for {@link glmAnova}. */
5
+ export interface GlmAnovaOptions {
6
+ /**
7
+ * The test: `"Chisq"` (or its synonym `"LRT"`), `"Rao"`, `"F"`, `"Cp"`, or `false` for none. Default, as R since
8
+ * 4.4.0: `"Chisq"` when the dispersion is known (binomial, poisson or `dispersion` given), else `"F"`.
9
+ */
10
+ test?: GlmAnovaTest | false;
11
+ /** Dispersion for the tests instead of the estimate of the largest model. */
12
+ dispersion?: number;
13
+ }
14
+ /** Result of {@link glmAnova}: R's anova table. */
15
+ export interface GlmAnovaResult {
16
+ /** Column names, such as `"Df"`, `"Deviance"`, `"Resid. Df"`, `"Resid. Dev"`, `"Pr(>Chi)"`. */
17
+ colNames: string[];
18
+ /** Row names: `"NULL"`, `"x1"`, ... for one fit; `"1"`, `"2"`, ... for a comparison. */
19
+ rowNames: string[];
20
+ /** One array per row; NaN where R leaves the cell empty (NA). */
21
+ table: number[][];
22
+ /** R's warnings (from the refits and the F test of binomial or poisson families). */
23
+ warnings: string[];
24
+ }
25
+ /**
26
+ * Analysis of deviance. Equivalent to R's `anova()` for one `glm` fit (the sequential table, each column of `x`
27
+ * added in order) or for several fits of the same data (`anova(fit1, fit2, ...)`).
28
+ *
29
+ * @param fits One fit, or an array of fits to compare.
30
+ */
31
+ export declare function glmAnova(fits: GlmResult | readonly GlmResult[], options?: GlmAnovaOptions): GlmAnovaResult;