@numero-uno-jpn/rstats 1.14.0 → 1.15.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 (73) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.ja.md +6 -6
  3. package/README.md +6 -6
  4. package/dist/causal.js +2 -2
  5. package/dist/chunks/{chunk-A5DZG7FH.js → chunk-3K47QLCY.js} +2 -2
  6. package/dist/chunks/{chunk-AQHG7BEZ.js → chunk-4EH3O466.js} +2 -2
  7. package/dist/chunks/{chunk-NA7EDZ4Q.js → chunk-5BCXHJPF.js} +2 -2
  8. package/dist/chunks/{chunk-7FGVMDJE.js → chunk-5JKKIVYL.js} +2 -2
  9. package/dist/chunks/{chunk-4O6XLQBN.js → chunk-5Q5YVM7S.js} +2 -2
  10. package/dist/chunks/{chunk-6VY3XNAF.js → chunk-6SZLUVSL.js} +2 -2
  11. package/dist/chunks/{chunk-CKUBQW2A.js → chunk-AGA7JCRF.js} +2 -2
  12. package/dist/chunks/{chunk-7VMGP2U7.js → chunk-AILN2NGE.js} +2 -2
  13. package/dist/chunks/{chunk-SEKOIW43.js → chunk-APOF7BLH.js} +2 -2
  14. package/dist/chunks/chunk-CIBAGTO2.js +4 -0
  15. package/dist/chunks/{chunk-EDRBKZ3C.js → chunk-FD375XBW.js} +2 -2
  16. package/dist/chunks/{chunk-XXH5OIUO.js → chunk-FV4ZQPRI.js} +2 -2
  17. package/dist/chunks/{chunk-D25AVVVI.js → chunk-GBNGGBU3.js} +2 -2
  18. package/dist/chunks/{chunk-TGXUU5NB.js → chunk-HF4TT233.js} +1 -1
  19. package/dist/chunks/{chunk-MJHFGGPU.js → chunk-HSVVCFEN.js} +2 -2
  20. package/dist/chunks/{chunk-FPJ2CWLK.js → chunk-IMSXMJ43.js} +2 -2
  21. package/dist/chunks/{chunk-DZQWGBTW.js → chunk-JAXYZJV7.js} +2 -2
  22. package/dist/chunks/{chunk-B6NPCYFO.js → chunk-JGZSGGMD.js} +2 -2
  23. package/dist/chunks/{chunk-EWNJT27V.js → chunk-KQGH6SEW.js} +2 -2
  24. package/dist/chunks/chunk-L7HJGM52.js +2 -0
  25. package/dist/chunks/{chunk-YLUF4WTL.js → chunk-M3HFLMXL.js} +2 -2
  26. package/dist/chunks/{chunk-ZWSHIUBZ.js → chunk-MKCPS5QQ.js} +2 -2
  27. package/dist/chunks/{chunk-ZJJJDLRL.js → chunk-NULJXDAR.js} +2 -2
  28. package/dist/chunks/{chunk-3DA7CMFN.js → chunk-OBTCIG5D.js} +2 -2
  29. package/dist/chunks/{chunk-MXOBCQQP.js → chunk-OO22LZ7Q.js} +2 -2
  30. package/dist/chunks/chunk-P4TKSL4W.js +2 -0
  31. package/dist/chunks/{chunk-QLKZ2OFQ.js → chunk-PZRABNMZ.js} +2 -2
  32. package/dist/chunks/{chunk-2426YL2X.js → chunk-R74QJUYU.js} +2 -2
  33. package/dist/chunks/{chunk-IXFWR3LH.js → chunk-RHNGF7R7.js} +2 -2
  34. package/dist/chunks/{chunk-VWCCPBBG.js → chunk-RV4JZHTE.js} +2 -2
  35. package/dist/chunks/{chunk-3746VXPM.js → chunk-SMA62635.js} +2 -2
  36. package/dist/chunks/{chunk-3XUHCWLU.js → chunk-SNQABDAT.js} +1 -1
  37. package/dist/chunks/{chunk-SDIIGAY5.js → chunk-U5UOVXKD.js} +2 -2
  38. package/dist/chunks/{chunk-PHDTVTKV.js → chunk-UFJFVNC6.js} +1 -1
  39. package/dist/chunks/{chunk-Y7VD43TO.js → chunk-VHBIWPB4.js} +2 -2
  40. package/dist/chunks/{chunk-BCXYAILN.js → chunk-VHMFOILD.js} +2 -2
  41. package/dist/chunks/{chunk-H5GBKP57.js → chunk-VO3E4Q6H.js} +1 -1
  42. package/dist/chunks/{chunk-6HUTVWPO.js → chunk-WL3JGBLZ.js} +2 -2
  43. package/dist/chunks/{chunk-62Y36UKH.js → chunk-XVRRYHLM.js} +2 -2
  44. package/dist/chunks/{chunk-I2OTBVRK.js → chunk-YYLBBEWZ.js} +2 -2
  45. package/dist/chunks/{chunk-JCGCJT7T.js → chunk-ZDUVFNFH.js} +1 -1
  46. package/dist/chunks/{chunk-MCEZRRQO.js → chunk-ZUTVNRML.js} +2 -2
  47. package/dist/descriptive.js +2 -2
  48. package/dist/distributions.js +2 -2
  49. package/dist/entries/tests.d.ts +2 -1
  50. package/dist/entries/tests.js +1 -0
  51. package/dist/linalg.js +2 -2
  52. package/dist/mixed.js +4 -5
  53. package/dist/models/fitOptions.d.ts +4 -0
  54. package/dist/models/fitOptions.js +14 -0
  55. package/dist/models/glm.d.ts +67 -5
  56. package/dist/models/glm.js +105 -27
  57. package/dist/models/glmerStructure.d.ts +5 -0
  58. package/dist/models/glmerStructure.js +2 -2
  59. package/dist/models/lm.js +3 -1
  60. package/dist/models/step.d.ts +250 -0
  61. package/dist/models/step.js +592 -0
  62. package/dist/multivariate.js +2 -2
  63. package/dist/numerics.js +2 -2
  64. package/dist/regression.js +2 -2
  65. package/dist/rstats.js +17 -17
  66. package/dist/special.js +2 -2
  67. package/dist/tests.js +14 -14
  68. package/dist/timeseries.js +2 -2
  69. package/package.json +1 -1
  70. package/dist/chunks/chunk-7BBIQY4W.js +0 -2
  71. package/dist/chunks/chunk-AONDWNMF.js +0 -2
  72. package/dist/chunks/chunk-F6KKW5YN.js +0 -2
  73. package/dist/chunks/chunk-KITNZUYC.js +0 -3
@@ -0,0 +1,592 @@
1
+ // Stepwise model selection by AIC: R's step (stats) and stepAIC (MASS) for formula fits of lm and glm, with the
2
+ // tables of drop1 and add1 and the criterion of extractAIC.
3
+ //
4
+ // Written for rStats.js (no ported code) from oracle/step-behaviour.md, which sets out the behaviour found by calling
5
+ // R's public functions (experiments/step115*.R, Issue #565). Every model is refitted from a formula built from term
6
+ // labels (the response's text, the labels joined by +, "- 1" or "0" without intercept), as R refits by update(). Terms
7
+ // are compared by their sets of variables (x1:f is f:x1). Where R behaves oddly the code does the same and says why.
8
+ import { pchisq } from "../distributions/chisq.js";
9
+ import { pf } from "../distributions/f.js";
10
+ import { unreported, Warnings, reported } from "../internal/warnings.js";
11
+ import { fitLm, lm } from "./lm.js";
12
+ import { glm, glmDispersion, refit } from "./glm.js";
13
+ import { parseFormula, termsOf } from "./formula.js";
14
+ import { modelFrame } from "./modelFrame.js";
15
+ import { fitOptions } from "./fitOptions.js";
16
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
17
+ import { checkOptions, nestedOptions } from "../internal/checkOptions.js";
18
+ const STEP_KEYS = ["scope", "direction", "k", "scale", "steps"];
19
+ const STEP_SCOPE_KEYS = ["lower", "upper"];
20
+ const STEP_AIC_KEYS = ["scope", "direction", "k", "scale", "steps"];
21
+ const STEP_AIC_SCOPE_KEYS = ["lower", "upper"];
22
+ const DROP1_KEYS = ["scope", "test", "k", "scale"];
23
+ const ADD1_KEYS = ["scope", "test", "k", "scale"];
24
+ const EXTRACT_AIC_KEYS = ["k", "scale"];
25
+ const isGlmFit = (fit) => "linearPredictors" in fit;
26
+ function contextOf(fit, data, caller) {
27
+ if (typeof fit !== "object" || fit === null || typeof fit.formula !== "string" || !Array.isArray(fit.termLabels)) {
28
+ throw new TypeError(`${caller} needs a fit of lm or glm with a formula`);
29
+ }
30
+ if (typeof data !== "object" || data === null)
31
+ throw new TypeError("data must be an object of columns");
32
+ const g = isGlmFit(fit);
33
+ const options = fitOptions(fit);
34
+ if (options === undefined) {
35
+ // a copy of a result: its options are not known; usable only when it had none that matter
36
+ const weighted = g ? fit.model.priorGiven.some((w) => w !== 1) || fit.model.hasOffset : fit.weights !== undefined;
37
+ if (weighted || g)
38
+ throw new TypeError(`${caller} needs the fit as returned by lm or glm (its options are not known)`);
39
+ }
40
+ const tilde = fit.formula.indexOf("~");
41
+ const lhs = fit.formula.slice(0, tilde).trim();
42
+ const intercept = g ? fit.model.intercept : fit.coefNames[0] === "(Intercept)";
43
+ const nAll = Object.values(data)[0]?.length ?? 0;
44
+ return { data, glm: g, lhs, intercept, options: options ?? {}, nAll };
45
+ }
46
+ /** The formula of a model with these terms */
47
+ function formulaOf(ctx, labels) {
48
+ if (labels.length === 0)
49
+ return `${ctx.lhs} ~ ${ctx.intercept ? "1" : "0"}`;
50
+ return `${ctx.lhs} ~ ${labels.join(" + ")}${ctx.intercept ? "" : " - 1"}`;
51
+ }
52
+ /** The data (and the options' arrays) restricted to some rows */
53
+ function restrict(ctx, rows) {
54
+ const pick = (col) => {
55
+ if (col instanceof Float64Array)
56
+ return Float64Array.from(rows, (i) => col[i]);
57
+ if (Array.isArray(col) && col.length === ctx.nAll)
58
+ return rows.map((i) => col[i]);
59
+ return col;
60
+ };
61
+ const data = Object.fromEntries(Object.entries(ctx.data).map(([k, c]) => [k, pick(c)]));
62
+ const options = { ...ctx.options };
63
+ for (const key of ["weights", "offset"])
64
+ if (typeof options[key] === "object" && options[key] !== null)
65
+ options[key] = pick(options[key]);
66
+ return { data, options };
67
+ }
68
+ /** A refit with these terms, on all rows or on some */
69
+ function refitTerms(ctx, labels, rows) {
70
+ const { data, options } = rows === undefined ? { data: ctx.data, options: { ...ctx.options } } : restrict(ctx, rows);
71
+ const formula = formulaOf(ctx, labels);
72
+ const fit = unreported(() => (ctx.glm ? glm(formula, data, options) : lm(formula, data, options)));
73
+ if (rows !== undefined) {
74
+ // the rows in the indices of the whole data
75
+ const used = ctx.glm ? fit.model.rows : fit.rows;
76
+ const mapped = used.map((i) => rows[i]);
77
+ if (ctx.glm)
78
+ fit.model.rows = mapped;
79
+ else
80
+ fit.rows = mapped;
81
+ }
82
+ return fit;
83
+ }
84
+ const rowsOf = (fit) => (isGlmFit(fit) ? fit.model.rows : fit.rows);
85
+ /** The number of residuals (rows used, weight-0 rows included) */
86
+ const nResiduals = (fit) => rowsOf(fit).length;
87
+ /** The rows of positive weight (R's nobs) */
88
+ const nObs = (fit) => (isGlmFit(fit) ? fit.priorWeights.filter((w) => w > 0).length : fit.nObs);
89
+ const devianceOf = (fit) => (isGlmFit(fit) ? fit.deviance : fit.rss);
90
+ const rankOf = (fit) => fit.rank;
91
+ /**
92
+ * log RSS of an lm fit: log(rss) while the sum is in range; otherwise (a response of 1e±300 overflows or underflows
93
+ * the squares) from the residuals and weights in the log domain, so that the criterion stays finite where R's is
94
+ * Inf (no move) or −Inf (an error). R gives the same values wherever its own are finite
95
+ */
96
+ function logRss(fit) {
97
+ const rss = fit.rss;
98
+ if (rss > 1e-290 && rss < Infinity)
99
+ return Math.log(rss);
100
+ const w = fit.weights;
101
+ const a = [];
102
+ fit.residuals.forEach((r, i) => {
103
+ const wi = w?.[i] ?? 1;
104
+ if (wi > 0 && r !== 0)
105
+ a.push(Math.log(Math.abs(r)) + 0.5 * Math.log(wi));
106
+ });
107
+ if (a.length === 0)
108
+ return -Infinity;
109
+ const m = Math.max(...a);
110
+ return 2 * m + Math.log(a.reduce((t, v) => t + Math.exp(2 * (v - m)), 0));
111
+ }
112
+ /** log RSS of a fit of the matrix form (yScale: fitted to the response scaled by 2^-k) */
113
+ function logRssCore(core) {
114
+ if (core.rss > 1e-290 && core.rss < Infinity)
115
+ return Math.log(core.rss);
116
+ if (core.yScale !== undefined && core.rssScaled !== undefined && core.rssScaled > 0)
117
+ return Math.log(core.rssScaled) + 2 * core.yScale * Math.LN2;
118
+ return Math.log(core.rss);
119
+ }
120
+ /** R's extractAIC: [edf, criterion] */
121
+ function criterionOf(fit, k, scale) {
122
+ const n = nResiduals(fit);
123
+ // edf = n − df.residual: with weight-0 rows (counted in n but not in the residual df) it exceeds the rank by their
124
+ // number, as R's extractAIC (the selection is unchanged: every model of a search carries the same excess)
125
+ const edf = n - fit.dfResidual;
126
+ if (isGlmFit(fit))
127
+ return [edf, fit.aic + (k - 2) * edf];
128
+ if (scale > 0)
129
+ return [edf, fit.rss / scale - n + k * edf];
130
+ return [edf, n * (logRss(fit) - Math.log(n)) + k * edf];
131
+ }
132
+ function termsOfFit(fit) {
133
+ return fit.termLabels.map((label, j) => {
134
+ const vars = fit.variables.filter((_, v) => (fit.factors[v]?.[j] ?? 0) !== 0);
135
+ return { label, vars, key: [...vars].sort().join("\u0000") };
136
+ });
137
+ }
138
+ function termsOfScope(scope, data, what) {
139
+ if (typeof scope !== "string")
140
+ throw new TypeError(`the ${what} scope must be a formula such as "~ x1 + x2"`);
141
+ const text = scope.includes("~") ? scope : `~ ${scope}`;
142
+ const parsed = parseFormula(text);
143
+ const hasDot = (n) => typeof n === "object" && n !== null && (n.type === "dot" || Object.values(n).some((c) => typeof c === "object" && hasDot(c)));
144
+ if (hasDot(parsed.rhs))
145
+ throw new RangeError(`'.' is not supported in the ${what} scope: list its terms`);
146
+ const t = termsOf({ response: undefined, rhs: parsed.rhs }, Object.keys(data));
147
+ return t.termLabels.map((label, j) => {
148
+ const vars = t.variables.filter((_, v) => (t.factors[v]?.[j] ?? 0) !== 0);
149
+ return { label, vars, key: [...vars].sort().join("\u0000") };
150
+ });
151
+ }
152
+ const contains = (big, small) => small.vars.length < big.vars.length && small.vars.every((v) => big.vars.includes(v));
153
+ /** The terms of the model that may be dropped: not in the lower scope, not contained in another term of the model */
154
+ function dropScope(model, lower) {
155
+ return model.filter((t) => !lower.some((l) => l.key === t.key) && !model.some((u) => contains(u, t)));
156
+ }
157
+ /** The terms of the upper scope that may be added: not in the model, every term of the upper scope inside it in the model */
158
+ function addScope(model, upper) {
159
+ const inModel = (t) => model.some((m) => m.key === t.key);
160
+ return upper.filter((t) => !inModel(t) && upper.every((u) => !contains(t, u) || inModel(u)));
161
+ }
162
+ /** lm: R's warning when the current model fits essentially perfectly (RSS below 1e-10 of the weighted Σ y²) */
163
+ function perfectFitCheck(fit, warnings) {
164
+ if (isGlmFit(fit))
165
+ return;
166
+ const w = fit.weights;
167
+ let ssy = 0;
168
+ fit.y.forEach((y, i) => (ssy += (w?.[i] ?? 1) * y * y));
169
+ if (fit.rss < 1e-10 * ssy)
170
+ warnings.add("attempting model selection on an essentially perfect fit is nonsense");
171
+ }
172
+ /** The warnings of a refit, without lm's warning of summary() (R's step does not call summary) */
173
+ function addWarnings(warnings, fit) {
174
+ for (const m of fit.warnings)
175
+ if (isGlmFit(fit) || m !== "essentially perfect fit: summary may be unreliable")
176
+ warnings.add(m);
177
+ }
178
+ /** The rows of positive prior weight of a glm */
179
+ const positiveRows = (fit) => fit.priorWeights.filter((w) => w > 0).length;
180
+ /** glm: the families whose dispersion is fixed at 1 */
181
+ const fixedDispersion = (fit) => fit.family === "binomial" || fit.family === "poisson";
182
+ /**
183
+ * The change of −2 log-likelihood from the current model `none` to a model of deviance `dev`, as R's drop1 / add1 for
184
+ * glm: gaussian n log(dev / dev₀) (the dispersion profiled out); binomial and poisson the change of deviance; the other
185
+ * families the change of deviance over the current model's (Pearson) dispersion, an approximation that R uses for the
186
+ * AIC column as well (so that for Gamma the table's AIC is not that of the refitted model, nor is the selection)
187
+ */
188
+ function scaledDeviance(none, dev) {
189
+ if (none.family === "gaussian")
190
+ return positiveRows(none) * Math.log(dev / none.deviance);
191
+ if (fixedDispersion(none))
192
+ return dev - none.deviance;
193
+ return (dev - none.deviance) / glmDispersion(none);
194
+ }
195
+ /** The row of the current model */
196
+ function noneRow(fit, k, scale) {
197
+ const n = nResiduals(fit);
198
+ // the table's edf is the rank (R's drop1 / add1), not extractAIC's n − df.residual
199
+ const edf = rankOf(fit);
200
+ const logDev = isGlmFit(fit) ? NaN : logRss(fit);
201
+ const aic = isGlmFit(fit) ? fit.aic + (k - 2) * edf : scale > 0 ? fit.rss / scale - n + k * edf : n * (logDev - Math.log(n)) + k * edf;
202
+ return { label: "<none>", df: NaN, sumOfSq: NaN, deviance: devianceOf(fit), aic, rank: edf, dfResidual: fit.dfResidual, logDev, fit };
203
+ }
204
+ /** A row from a model's deviance and rank, against the current model's row */
205
+ function candidateRow(none, label, dev, rank, dfResidual, adding, k, scale, logDev = Math.log(dev), fit) {
206
+ const base = none.fit;
207
+ const df = adding ? rank - none.rank : none.rank - rank;
208
+ let aic;
209
+ if (isGlmFit(base))
210
+ aic = none.aic + scaledDeviance(base, dev) + k * (rank - none.rank);
211
+ else {
212
+ const n = nResiduals(base);
213
+ aic = scale > 0 ? dev / scale - n + k * rank : n * (logDev - Math.log(n)) + k * rank;
214
+ }
215
+ return { label, df, sumOfSq: adding ? none.deviance - dev : dev - none.deviance, deviance: dev, aic, rank, dfResidual, logDev, fit };
216
+ }
217
+ /**
218
+ * drop1's rows: the current model and each term dropped, as R's drop1 fits them: the columns of the term taken out of
219
+ * the current model matrix (on its rows), not a refit of a formula (dropping x1 from y ~ x1 * f keeps the columns of
220
+ * x1:f as they are coded, so it removes a degree of freedom)
221
+ */
222
+ /** glm: R computes the dispersion for the tables of the families without a fixed one (with its warnings) */
223
+ function dispersionWarnings(fit, warnings) {
224
+ if (isGlmFit(fit) && !fixedDispersion(fit))
225
+ glmDispersion(fit, warnings);
226
+ }
227
+ function dropRows(fit, drops, k, scale, warnings) {
228
+ perfectFitCheck(fit, warnings);
229
+ dispersionWarnings(fit, warnings);
230
+ const none = noneRow(fit, k, scale);
231
+ const terms = termsOfFit(fit);
232
+ const out = [none];
233
+ for (const t of drops) {
234
+ const j = terms.findIndex((u) => u.key === t.key) + 1;
235
+ const cols = fit.assign.flatMap((a, c) => (a === j ? [] : [c]));
236
+ if (isGlmFit(fit)) {
237
+ const w = new Warnings();
238
+ const r = refit(fit.model, cols, w);
239
+ for (const m of w.list)
240
+ warnings.add(m);
241
+ out.push(candidateRow(none, t.label, r.fit.deviance, r.fit.rank, positiveRows(fit) - r.fit.rank, false, k, scale));
242
+ }
243
+ else {
244
+ const core = fitLm(fit.x.map((row) => cols.map((c) => row[c])), fit.y, fit.weights, fit.coefNames[0] === "(Intercept)" && cols[0] === 0, true);
245
+ out.push(candidateRow(none, t.label, core.rss, core.result.rank, core.result.dfResidual, false, k, scale, logRssCore(core)));
246
+ }
247
+ }
248
+ return out;
249
+ }
250
+ /**
251
+ * add1's rows: on the rows complete in the model's and all the candidates' variables (with R's warning when that is
252
+ * fewer than the model's rows; the current model is then refitted on them too, so the table and the path differ)
253
+ */
254
+ function addRows(ctx, fit, adds, k, scale, warnings) {
255
+ let rows = rowsOf(fit);
256
+ let base = fit;
257
+ const extra = [...new Set(adds.flatMap((t) => t.vars))].filter((v) => !fit.variables.includes(v));
258
+ if (extra.length > 0) {
259
+ const levels = ctx.options.levels;
260
+ const sub = restrict(ctx, rows).data;
261
+ const complete = modelFrame(sub, extra, levels === undefined ? {} : { levels }).rows.map((i) => rows[i]);
262
+ if (complete.length < rows.length) {
263
+ warnings.add(`using the ${complete.length}/${rows.length} rows from a combined fit`);
264
+ rows = complete;
265
+ base = refitTerms(ctx, fit.termLabels, rows);
266
+ }
267
+ }
268
+ perfectFitCheck(base, warnings);
269
+ dispersionWarnings(base, warnings);
270
+ const none = noneRow(base, k, scale);
271
+ // glm on fewer rows: R keeps the current fit's own AIC for <none> and adds to it the scaled changes of deviance on
272
+ // the rows of the combined fit (so the table mixes the two sets of rows); lm recomputes <none> on those rows
273
+ if (isGlmFit(base) && base !== fit)
274
+ none.aic = noneRow(fit, k, scale).aic;
275
+ const out = [none];
276
+ for (const t of adds) {
277
+ const m = refitTerms(ctx, [...fit.termLabels, t.label], rows);
278
+ addWarnings(warnings, m);
279
+ out.push(candidateRow(none, t.label, devianceOf(m), rankOf(m), m.dfResidual, true, k, scale, isGlmFit(m) ? NaN : logRss(m), m));
280
+ }
281
+ return out;
282
+ }
283
+ /** The tests of drop1 / add1 (the larger model of each comparison: the current one for drops, the candidate for adds) */
284
+ function testColumns(rows, test, adding) {
285
+ const none = rows[0];
286
+ const base = none.fit;
287
+ const statistic = [NaN];
288
+ const pValue = [NaN];
289
+ for (const r of rows.slice(1)) {
290
+ const big = adding ? r : none;
291
+ const change = Math.abs(r.deviance - none.deviance);
292
+ let s;
293
+ let p;
294
+ if (test === "F") {
295
+ // the change per degree of freedom against the residual deviance per degree of freedom of the larger model
296
+ s = change / r.df / (big.deviance / big.dfResidual);
297
+ p = pf(s, r.df, big.dfResidual, { lowerTail: false });
298
+ }
299
+ else {
300
+ s = isGlmFit(base) ? Math.abs(scaledDeviance(base, r.deviance)) : change / (big.deviance / big.dfResidual);
301
+ p = pchisq(s, r.df, { lowerTail: false });
302
+ }
303
+ statistic.push(r.df === 0 ? NaN : s);
304
+ pValue.push(r.df === 0 ? NaN : p);
305
+ }
306
+ const statisticName = test === "F" ? "F value" : isGlmFit(base) && fixedDispersion(base) ? "LRT" : "scaled dev.";
307
+ return { statistic, pValue, statisticName };
308
+ }
309
+ function tableOf(rows, glmFit, scale, warnings) {
310
+ const out = {
311
+ term: rows.map((r) => r.label),
312
+ df: rows.map((r) => r.df),
313
+ deviance: rows.map((r) => r.deviance),
314
+ aic: rows.map((r) => r.aic),
315
+ criterion: scale > 0 && !glmFit ? "Cp" : "AIC",
316
+ warnings: warnings.list,
317
+ };
318
+ if (!glmFit)
319
+ out.sumOfSq = rows.map((r) => r.sumOfSq);
320
+ return out;
321
+ }
322
+ function checkNumber(v, name, positive = false) {
323
+ if (typeof v !== "number" || Number.isNaN(v))
324
+ throw new TypeError(`${name} must be a number`);
325
+ if (positive ? !(v >= 0) : !Number.isFinite(v))
326
+ throw new RangeError(`${name} must be ${positive ? "non-negative" : "finite"}`);
327
+ return v;
328
+ }
329
+ // ---------------------------------------------------------------------------------------------------------------------
330
+ // Public functions
331
+ /**
332
+ * The criterion of a fit for model selection: `[edf, criterion]`. Equivalent to R's `extractAIC()`. lm: n log(RSS / n) + k edf, or with `scale > 0`
333
+ * Mallows' Cp = RSS / scale − n + k edf; glm: AIC + (k − 2) edf. n counts the rows used (weight-0 rows included) and
334
+ * edf = n − the residual degrees of freedom, so that with weight-0 rows edf exceeds the rank by their number, as in R.
335
+ *
336
+ * @param fit A fit of {@link lm} or {@link glm} with a formula.
337
+ *
338
+ * @example
339
+ * ```ts
340
+ * const data = { y: [1.2, 2.3, 2.9, 4.1, 5.2, 5.8], x: [1, 2, 3, 4, 5, 6] };
341
+ * extractAIC(lm("y ~ x", data)); // [2, -19.211]
342
+ * ```
343
+ *
344
+ * @category Model selection
345
+ */
346
+ export function extractAIC(fit, options = {}) {
347
+ checkOptions(options, EXTRACT_AIC_KEYS, "extractAIC"); // generated: option-keys.mjs
348
+ const k = checkNumber(options.k ?? 2, "k");
349
+ const scale = checkNumber(options.scale ?? 0, "scale", true);
350
+ return criterionOf(fit, k, scale);
351
+ }
352
+ /**
353
+ * The models with one term dropped, for lm and glm. Equivalent to R's `drop1()`. With the change of the residual sum of squares or
354
+ * the deviance, the criterion of {@link extractAIC} (edf the rank) and optionally a test. As in R, each model is the
355
+ * fit's model matrix without the columns of the term, on the rows of `fit` (not a refit of a formula). By default
356
+ * only the terms not contained in another term of the model are dropped (marginality).
357
+ *
358
+ * @param fit A fit of {@link lm} or {@link glm} with a formula.
359
+ * @param data The data frame the fit was made from.
360
+ *
361
+ * @example
362
+ * ```ts
363
+ * const data = { y: [1.2, 2.3, 2.9, 4.1, 5.2, 5.8, 7.1, 7.9], x: [1, 2, 3, 4, 5, 6, 7, 8], z: [5, 3, 8, 1, 9, 2, 7, 4] };
364
+ * drop1(lm("y ~ x + z", data), data, { test: "F" }).term; // ["<none>", "x", "z"]
365
+ * ```
366
+ *
367
+ * @category Model selection
368
+ */
369
+ export function drop1(fit, data, options = {}) {
370
+ checkOptions(options, DROP1_KEYS, "drop1"); // generated: option-keys.mjs
371
+ const ctx = contextOf(fit, data, "drop1");
372
+ const k = checkNumber(options.k ?? 2, "k");
373
+ const scale = ctx.glm ? 0 : checkNumber(options.scale ?? 0, "scale", true);
374
+ const model = termsOfFit(fit);
375
+ const drops = options.scope === undefined ? dropScope(model, []) : termsOfScope(options.scope, data, "drop1").map((t) => {
376
+ const m = model.find((u) => u.key === t.key);
377
+ if (m === undefined)
378
+ throw new RangeError(`scope is not a subset of term labels`);
379
+ return m;
380
+ });
381
+ const warnings = new Warnings();
382
+ addWarnings(warnings, fit);
383
+ const rows = dropRows(fit, drops, k, scale, warnings);
384
+ const table = tableOf(rows, ctx.glm, scale, warnings);
385
+ if (options.test !== undefined && options.test !== "none")
386
+ Object.assign(table, { test: options.test === "F" ? "F" : "Chisq" }, testColumns(rows, options.test === "F" ? "F" : "Chisq", false));
387
+ table.warnings = warnings.list.filter((m) => !fit.warnings.includes(m));
388
+ return reported("drop1", table, fit);
389
+ }
390
+ /**
391
+ * The models with one term added, for lm and glm. Equivalent to R's `add1()`. With the change of the residual sum of squares or the
392
+ * deviance, the criterion of {@link extractAIC} (edf the rank) and optionally a test. The terms are those of `scope`
393
+ * that can be added respecting marginality. Every model is refitted on the rows complete in the variables of the
394
+ * model and of all the terms; when these are fewer than the fit's rows the current model is refitted on them too,
395
+ * with R's warning "using the m/n rows from a combined fit".
396
+ *
397
+ * @param fit A fit of {@link lm} or {@link glm} with a formula.
398
+ * @param data The data frame the fit was made from.
399
+ *
400
+ * @example
401
+ * ```ts
402
+ * const data = { y: [1.2, 2.3, 2.9, 4.1, 5.2, 5.8, 7.1, 7.9], x: [1, 2, 3, 4, 5, 6, 7, 8], z: [5, 3, 8, 1, 9, 2, 7, 4] };
403
+ * add1(lm("y ~ 1", data), data, { scope: "~ x + z" }).term; // ["<none>", "x", "z"]
404
+ * ```
405
+ *
406
+ * @category Model selection
407
+ */
408
+ export function add1(fit, data, options = {}) {
409
+ checkOptions(options, ADD1_KEYS, "add1"); // generated: option-keys.mjs
410
+ const ctx = contextOf(fit, data, "add1");
411
+ if (options.scope === undefined)
412
+ throw new TypeError("no terms in scope for adding to object");
413
+ const k = checkNumber(options.k ?? 2, "k");
414
+ const scale = ctx.glm ? 0 : checkNumber(options.scale ?? 0, "scale", true);
415
+ const adds = addScope(termsOfFit(fit), termsOfScope(options.scope, data, "add1"));
416
+ const warnings = new Warnings();
417
+ addWarnings(warnings, fit);
418
+ const rows = addRows(ctx, fit, adds, k, scale, warnings);
419
+ const table = tableOf(rows, ctx.glm, scale, warnings);
420
+ if (options.test !== undefined && options.test !== "none")
421
+ Object.assign(table, { test: options.test === "F" ? "F" : "Chisq" }, testColumns(rows, options.test === "F" ? "F" : "Chisq", true));
422
+ table.warnings = warnings.list.filter((m) => !fit.warnings.includes(m));
423
+ return reported("add1", table, fit);
424
+ }
425
+ function search(fit, data, options, caller) {
426
+ const ctx = contextOf(fit, data, caller);
427
+ const direction = options.direction ?? "both";
428
+ if (!["both", "backward", "forward"].includes(direction))
429
+ throw new RangeError(`'direction' should be one of "both", "backward", "forward"`);
430
+ const k = checkNumber(options.k ?? 2, "k");
431
+ const scale = ctx.glm ? 0 : checkNumber(options.scale ?? 0, "scale", true);
432
+ const steps = checkNumber(options.steps ?? 1000, "steps", true);
433
+ const model0 = termsOfFit(fit);
434
+ // the scope: lower and upper terms (the default upper is the start model; a one-sided formula is the upper)
435
+ // (without a scope "both" may add back a term it dropped: the upper scope is the start model)
436
+ let lower = [];
437
+ let upper = model0;
438
+ const scope = options.scope;
439
+ if (scope === undefined) {
440
+ // the start model's terms
441
+ }
442
+ else if (typeof scope === "string")
443
+ upper = termsOfScope(scope, data, "upper");
444
+ else if (typeof scope === "object" && scope !== null) {
445
+ if (scope.lower !== undefined)
446
+ lower = termsOfScope(scope.lower, data, "lower");
447
+ if (scope.upper !== undefined)
448
+ upper = termsOfScope(scope.upper, data, "upper");
449
+ }
450
+ else
451
+ throw new TypeError("scope must be a formula or { lower, upper }");
452
+ for (const t of model0)
453
+ if (!upper.some((u) => u.key === t.key))
454
+ throw new RangeError(`upper scope has term ‘${t.label}’ not included in model`);
455
+ for (const t of lower)
456
+ if (!model0.some((u) => u.key === t.key))
457
+ throw new RangeError(`lower scope has term ‘${t.label}’ not included in model`);
458
+ const backward = direction !== "forward";
459
+ const forward = direction !== "backward";
460
+ const warnings = new Warnings();
461
+ addWarnings(warnings, fit);
462
+ let current = fit;
463
+ let [, aic] = criterionOf(current, k, scale);
464
+ if (Number.isNaN(aic))
465
+ throw new RangeError(`AIC is not defined for this model, so '${caller === "step" ? "step" : "stepAIC"}' cannot proceed`);
466
+ if (aic === -Infinity)
467
+ throw new RangeError(`AIC is -infinity for this model, so '${caller === "step" ? "step" : "stepAIC"}' cannot proceed`);
468
+ const n0 = nObs(current);
469
+ const anova = { step: [""], df: [NaN], deviance: [NaN], residDf: [nObs(current) - criterionOf(current, k, scale)[0]], residDeviance: [devianceOf(current)], aic: [aic] };
470
+ const visits = [{ formula: formulaOf(ctx, current.termLabels), termLabels: [...current.termLabels], aic }];
471
+ const move = (next, label, dropped) => {
472
+ // the refit of the chosen model on its own rows: R stops when that changes the number of rows used
473
+ if (nObs(next) !== n0)
474
+ throw new RangeError("number of rows in use has changed: remove missing values?");
475
+ const [edf, a] = criterionOf(next, k, scale);
476
+ const dfChange = next.dfResidual - current.dfResidual;
477
+ anova.step.push(label);
478
+ anova.df.push(caller === "step" ? dfChange : Math.abs(dfChange));
479
+ anova.deviance.push(dropped ? devianceOf(next) - devianceOf(current) : devianceOf(current) - devianceOf(next));
480
+ anova.residDf.push(nObs(next) - edf);
481
+ anova.residDeviance.push(devianceOf(next));
482
+ anova.aic.push(a);
483
+ current = next;
484
+ aic = a;
485
+ visits.push({ formula: formulaOf(ctx, current.termLabels), termLabels: [...current.termLabels], aic });
486
+ };
487
+ let moves = 0;
488
+ while (moves < steps) {
489
+ const terms = termsOfFit(current);
490
+ // a term whose columns are all aliased is removed first, without a table, the last such term first
491
+ const aliased = terms.filter((_, j) => {
492
+ const cols = (isGlmFit(current) ? current.coefNames : current.coefNames).map((_, c) => c).filter((c) => current.assign[c] === j + 1);
493
+ return cols.length > 0 && cols.every((c) => Number.isNaN(current.coefficients[c]));
494
+ });
495
+ if (aliased.length > 0) {
496
+ const t = aliased[aliased.length - 1];
497
+ const next = refitTerms(ctx, current.termLabels.filter((l) => l !== t.label));
498
+ addWarnings(warnings, next);
499
+ move(next, `- ${t.label}`, true);
500
+ moves++;
501
+ continue;
502
+ }
503
+ const drops = backward ? dropScope(terms, lower) : [];
504
+ const adds = forward ? addScope(terms, upper) : [];
505
+ let rows = [];
506
+ if (drops.length > 0)
507
+ rows = dropRows(current, drops, k, scale, warnings).map((r, i) => (i === 0 ? r : { ...r, label: `- ${r.label}` }));
508
+ if (adds.length > 0) {
509
+ const a = addRows(ctx, current, adds, k, scale, warnings).map((r, i) => (i === 0 ? r : { ...r, label: `+ ${r.label}` }));
510
+ // adds whose term would bring no column are not offered
511
+ rows = rows.length === 0 ? a.filter((r, i) => i === 0 || r.df > 0) : [...rows, ...a.slice(1).filter((r) => r.df > 0)];
512
+ }
513
+ if (rows.length === 0)
514
+ break;
515
+ // sorted by the criterion, the table order kept among equal values (<none> first, then drops, then adds)
516
+ const order = rows.map((_, i) => i).sort((i, j) => cmp(rows[i].aic, rows[j].aic) || i - j);
517
+ const sorted = order.map((i) => rows[i]);
518
+ const last = visits[visits.length - 1];
519
+ last.table = {
520
+ move: sorted.map((r) => r.label),
521
+ df: sorted.map((r) => r.df),
522
+ deviance: sorted.map((r) => r.deviance),
523
+ aic: sorted.map((r) => r.aic),
524
+ };
525
+ if (!ctx.glm)
526
+ last.table.sumOfSq = sorted.map((r) => r.sumOfSq);
527
+ if (order[0] === 0)
528
+ break;
529
+ const best = sorted[0];
530
+ const dropped = best.label.startsWith("- ");
531
+ const label = best.label.slice(2);
532
+ const next = dropped ? refitTerms(ctx, current.termLabels.filter((l) => l !== label)) : refitTerms(ctx, [...current.termLabels, label]);
533
+ addWarnings(warnings, next);
534
+ move(next, best.label, dropped);
535
+ moves++;
536
+ }
537
+ const result = { fit: current, anova, criterion: scale > 0 && !ctx.glm ? "Cp" : "AIC", visits, warnings: warnings.list.filter((m) => !fit.warnings.includes(m)) };
538
+ return reported(caller, result, fit);
539
+ }
540
+ /** Ascending, NaN last */
541
+ const cmp = (a, b) => (Number.isNaN(a) ? (Number.isNaN(b) ? 0 : 1) : Number.isNaN(b) ? -1 : a - b);
542
+ /**
543
+ * Stepwise selection of the terms of a linear or generalized linear model by AIC. Equivalent to R's `step()`. From the start model,
544
+ * each step examines the models with one term dropped (respecting marginality, keeping the lower scope) and, with an
545
+ * upper scope, one term added, and moves to the one with the smallest criterion of {@link extractAIC} when it is
546
+ * strictly below the current model's; it stops when no move improves it, or after `steps` moves. `k = Math.log(n)`
547
+ * gives BIC. Terms whose columns are all aliased are removed first. The result holds the selected fit, the path
548
+ * (R's `$anova`) and every table examined (R's printed trace).
549
+ *
550
+ * As in R, the models are refitted on their own rows: when a move changes the number of rows used (a variable with
551
+ * missing values dropped or added) the search stops with an error, and the table of adds is computed on the rows
552
+ * complete in all the candidates' variables (with a warning when those are fewer).
553
+ *
554
+ * @param fit The start model: a fit of {@link lm} or {@link glm} with a formula.
555
+ * @param data The data frame the fit was made from.
556
+ *
557
+ * @example
558
+ * ```ts
559
+ * const data = { y: [1.2, 2.3, 2.9, 4.1, 5.2, 5.8, 7.1, 7.9], x: [1, 2, 3, 4, 5, 6, 7, 8], z: [5, 3, 8, 1, 9, 2, 7, 4] };
560
+ * const s = step(lm("y ~ x + z", data), data);
561
+ * s.fit.formula; // "y ~ x"
562
+ * s.anova.step; // ["", "- z"]
563
+ * ```
564
+ *
565
+ * @category Model selection
566
+ */
567
+ export function step(fit, data, options = {}) {
568
+ checkOptions(options, STEP_KEYS, "step"); // generated: option-keys.mjs
569
+ checkOptions(nestedOptions(options, "scope"), STEP_SCOPE_KEYS, "step", "scope"); // generated: option-keys.mjs
570
+ return search(fit, data, options, "step");
571
+ }
572
+ /**
573
+ * Stepwise selection by AIC. Equivalent to `MASS::stepAIC()` in R. The same search as {@link step}; the only difference R shows is the
574
+ * path's `df`, which stepAIC gives as the size of the term moved (positive) where step gives the change of the
575
+ * residual degrees of freedom.
576
+ *
577
+ * @param fit The start model: a fit of {@link lm} or {@link glm} with a formula.
578
+ * @param data The data frame the fit was made from.
579
+ *
580
+ * @example
581
+ * ```ts
582
+ * const data = { y: [1.2, 2.3, 2.9, 4.1, 5.2, 5.8, 7.1, 7.9], x: [1, 2, 3, 4, 5, 6, 7, 8], z: [5, 3, 8, 1, 9, 2, 7, 4] };
583
+ * stepAIC(lm("y ~ 1", data), data, { scope: "~ x + z" }).anova.df; // [NaN, 1]
584
+ * ```
585
+ *
586
+ * @category Model selection
587
+ */
588
+ export function stepAIC(fit, data, options = {}) {
589
+ checkOptions(options, STEP_AIC_KEYS, "stepAIC"); // generated: option-keys.mjs
590
+ checkOptions(nestedOptions(options, "scope"), STEP_AIC_SCOPE_KEYS, "stepAIC", "scope"); // generated: option-keys.mjs
591
+ return search(fit, data, options, "stepAIC");
592
+ }