@numero-uno-jpn/rstats 1.5.0 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +34 -0
- package/README.ja.md +17 -10
- package/README.md +18 -10
- package/dist/chunks/chunk-56AMJQ27.js +2 -0
- package/dist/chunks/{chunk-TP4PRPVQ.js → chunk-76FLTZVF.js} +2 -2
- package/dist/chunks/chunk-AIEPW6DX.js +2 -0
- package/dist/chunks/chunk-B6KJ4RWG.js +2 -0
- package/dist/chunks/{chunk-73QCE2CI.js → chunk-B7XZMIQO.js} +2 -2
- package/dist/chunks/chunk-BJMPSDJ7.js +2 -0
- package/dist/chunks/chunk-CB7STL5Z.js +2 -0
- package/dist/chunks/{chunk-MYRCEQ2R.js → chunk-CUT3IHMY.js} +1 -1
- package/dist/chunks/{chunk-MJV5G7FG.js → chunk-CZUOG2U5.js} +2 -2
- package/dist/chunks/{chunk-LVB22NKV.js → chunk-FQRNZEH2.js} +2 -2
- package/dist/chunks/{chunk-2IYY74LX.js → chunk-HORF36FD.js} +2 -2
- package/dist/chunks/{chunk-GDMNF4P3.js → chunk-HSJ4OT3H.js} +1 -1
- package/dist/chunks/{chunk-E5M5RAVB.js → chunk-J7ZVV4DN.js} +2 -2
- package/dist/chunks/chunk-JXEXOD7K.js +2 -0
- package/dist/chunks/chunk-KSH43GX4.js +2 -0
- package/dist/chunks/chunk-LMRCFKVK.js +2 -0
- package/dist/chunks/{chunk-CX4XK7WC.js → chunk-MOJ2KIQE.js} +2 -2
- package/dist/chunks/chunk-PCTRVBEJ.js +3 -0
- package/dist/chunks/{chunk-F2MURX2Y.js → chunk-PLQQ4VFN.js} +2 -2
- package/dist/chunks/{chunk-L7PDJNJ3.js → chunk-QWDK3ZC2.js} +2 -2
- package/dist/chunks/{chunk-F7SQG6BV.js → chunk-R5BMFVIH.js} +2 -2
- package/dist/chunks/chunk-R7F7ELS7.js +3 -0
- package/dist/chunks/{chunk-2MYUAEYE.js → chunk-RIP2RKAW.js} +2 -2
- package/dist/chunks/chunk-RX6MZO2Y.js +2 -0
- package/dist/chunks/{chunk-VAWD57ZB.js → chunk-SDT3YHAG.js} +2 -2
- package/dist/chunks/{chunk-FCF6FBJP.js → chunk-THSV22QF.js} +2 -2
- package/dist/chunks/{chunk-AIXJAVDS.js → chunk-TY3IFCLI.js} +2 -2
- package/dist/chunks/{chunk-BJOZZ5J6.js → chunk-V2Y2W7LE.js} +2 -2
- package/dist/chunks/{chunk-UJM7AJII.js → chunk-VALULDEX.js} +1 -1
- package/dist/chunks/chunk-VQOU7U7R.js +2 -0
- package/dist/chunks/{chunk-DYCWYHYV.js → chunk-YKNRDPIB.js} +1 -1
- package/dist/chunks/chunk-YVJ4LDDE.js +2 -0
- package/dist/descriptive.js +2 -2
- package/dist/distributions.js +2 -2
- package/dist/entries/mixed.d.ts +2 -0
- package/dist/entries/mixed.js +2 -0
- package/dist/entries/regression.d.ts +3 -0
- package/dist/entries/regression.js +6 -0
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +5 -5
- package/dist/models/mixedConfint.d.ts +42 -0
- package/dist/models/mixedConfint.js +573 -0
- package/dist/models/mixedSimulate.d.ts +36 -0
- package/dist/models/mixedSimulate.js +232 -0
- package/dist/models/nls.d.ts +286 -0
- package/dist/models/nls.js +1007 -0
- package/dist/models/nlsFormula.d.ts +37 -0
- package/dist/models/nlsFormula.js +295 -0
- package/dist/models/polr.d.ts +341 -0
- package/dist/models/polr.js +1028 -0
- package/dist/models/rlm.d.ts +282 -0
- package/dist/models/rlm.js +766 -0
- package/dist/numerics.js +2 -2
- package/dist/regression.js +3 -0
- package/dist/rstats.js +1 -1
- package/dist/special.js +2 -2
- package/dist/tests.js +14 -14
- package/llms.txt +8 -2
- package/package.json +6 -1
- package/dist/chunks/chunk-3BEE6BHN.js +0 -2
- package/dist/chunks/chunk-FMLFYM7N.js +0 -2
- package/dist/chunks/chunk-JBJTXMRJ.js +0 -2
- package/dist/chunks/chunk-MXOGMN4P.js +0 -2
- package/dist/chunks/chunk-Q32WODL4.js +0 -2
- package/dist/chunks/chunk-RZBX6VYO.js +0 -3
- package/dist/chunks/chunk-WBEYJ5W5.js +0 -3
- package/dist/chunks/chunk-YK2EJU6T.js +0 -2
|
@@ -0,0 +1,766 @@
|
|
|
1
|
+
// Robust linear regression: M estimation and its Huber (1981) covariance.
|
|
2
|
+
// Derived independently from Huber (1981), Hampel et al. (1986), and the selected
|
|
3
|
+
// equations in oracle/rlm-behaviour.md; no MASS or R implementation was used.
|
|
4
|
+
import { chol, chol2inv } from "../linalg/chol.js";
|
|
5
|
+
import { pnorm } from "../distributions/normal.js";
|
|
6
|
+
import { qr, qrCoef } from "../linalg/qr.js";
|
|
7
|
+
import { reported } from "../internal/warnings.js";
|
|
8
|
+
import { parseFormula } from "./formula.js";
|
|
9
|
+
import { design } from "./modelMatrix.js";
|
|
10
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
11
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
12
|
+
const RLM_KEYS = /* @__PURE__ */ new Set([
|
|
13
|
+
"method", "psi", "scaleEst", "init", "weights", "wtMethod", "k", "a", "b", "c", "k2", "maxit", "acc",
|
|
14
|
+
]);
|
|
15
|
+
const PSI_HUBER_KEYS = ["deriv", "k"];
|
|
16
|
+
const PSI_HAMPEL_KEYS = ["deriv", "a", "b", "c"];
|
|
17
|
+
const PSI_BISQUARE_KEYS = ["deriv", "c"];
|
|
18
|
+
/** Huber's psi function. Equivalent to R's `MASS::psi.huber()`.
|
|
19
|
+
*
|
|
20
|
+
* @param u Standardised residuals.
|
|
21
|
+
* @param options Tuning constant and output selection.
|
|
22
|
+
* @returns The IRLS weight psi(u)/u, or psi'(u) when deriv is 1.
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* ```ts
|
|
26
|
+
* psiHuber([-2, 0, 1, 2]); // [0.6725, 1, 1, 0.6725]
|
|
27
|
+
* ```
|
|
28
|
+
*
|
|
29
|
+
* @category Regression
|
|
30
|
+
*/
|
|
31
|
+
export function psiHuber(u, options = {}) {
|
|
32
|
+
checkOptions(options, PSI_HUBER_KEYS, "psiHuber"); // generated: option-keys.mjs
|
|
33
|
+
const k = options.k ?? 1.345;
|
|
34
|
+
if (!(k > 0) || !Number.isFinite(k))
|
|
35
|
+
throw new RangeError("k must be positive and finite");
|
|
36
|
+
const one = (v) => options.deriv === 1
|
|
37
|
+
? Math.abs(v) <= k
|
|
38
|
+
: (v === 0 || Math.abs(v) <= k ? 1 : k / Math.abs(v));
|
|
39
|
+
return typeof u === "number" ? one(u) : Array.from(u, one);
|
|
40
|
+
}
|
|
41
|
+
/** Hampel's three-part psi function. Equivalent to R's `MASS::psi.hampel()`.
|
|
42
|
+
*
|
|
43
|
+
* @param u Standardised residuals.
|
|
44
|
+
* @param options Three tuning points and output selection.
|
|
45
|
+
* @returns The IRLS weight psi(u)/u, or psi'(u) when deriv is 1.
|
|
46
|
+
*
|
|
47
|
+
* @example
|
|
48
|
+
* ```ts
|
|
49
|
+
* psiHampel([-5, -2, 0, 5, 9]); // [0.3, 1, 1, 0.3, 0]
|
|
50
|
+
* ```
|
|
51
|
+
*
|
|
52
|
+
* @category Regression
|
|
53
|
+
*/
|
|
54
|
+
export function psiHampel(u, options = {}) {
|
|
55
|
+
checkOptions(options, PSI_HAMPEL_KEYS, "psiHampel"); // generated: option-keys.mjs
|
|
56
|
+
const a = options.a ?? 2, b = options.b ?? 4, c = options.c ?? 8;
|
|
57
|
+
if (!(a > 0 && a < b && b < c) || ![a, b, c].every(Number.isFinite)) {
|
|
58
|
+
throw new RangeError("psiHampel requires 0 < a < b < c");
|
|
59
|
+
}
|
|
60
|
+
const one = (v) => {
|
|
61
|
+
const z = Math.abs(v);
|
|
62
|
+
if (options.deriv === 1) {
|
|
63
|
+
if (z <= a)
|
|
64
|
+
return 1;
|
|
65
|
+
if (z <= b)
|
|
66
|
+
return 0;
|
|
67
|
+
if (z < c)
|
|
68
|
+
return -a / (c - b);
|
|
69
|
+
return 0;
|
|
70
|
+
}
|
|
71
|
+
if (z === 0 || z <= a)
|
|
72
|
+
return 1;
|
|
73
|
+
if (z <= b)
|
|
74
|
+
return a / z;
|
|
75
|
+
if (z < c)
|
|
76
|
+
return a * (c - z) / ((c - b) * z);
|
|
77
|
+
return 0;
|
|
78
|
+
};
|
|
79
|
+
return typeof u === "number" ? one(u) : Array.from(u, one);
|
|
80
|
+
}
|
|
81
|
+
/** Tukey's bisquare psi function. Equivalent to R's `MASS::psi.bisquare()`.
|
|
82
|
+
*
|
|
83
|
+
* @param u Standardised residuals.
|
|
84
|
+
* @param options Tuning constant and output selection.
|
|
85
|
+
* @returns The IRLS weight psi(u)/u, or psi'(u) when deriv is 1.
|
|
86
|
+
*
|
|
87
|
+
* @example
|
|
88
|
+
* ```ts
|
|
89
|
+
* psiBisquare([-5, 0, 2]); // [0, 1, 0.668733411888633]
|
|
90
|
+
* ```
|
|
91
|
+
*
|
|
92
|
+
* @category Regression
|
|
93
|
+
*/
|
|
94
|
+
export function psiBisquare(u, options = {}) {
|
|
95
|
+
checkOptions(options, PSI_BISQUARE_KEYS, "psiBisquare"); // generated: option-keys.mjs
|
|
96
|
+
const c = options.c ?? 4.685;
|
|
97
|
+
if (!(c > 0) || !Number.isFinite(c))
|
|
98
|
+
throw new RangeError("c must be positive and finite");
|
|
99
|
+
const one = (v) => {
|
|
100
|
+
const t = v / c, z = Math.abs(t);
|
|
101
|
+
if (!(z < 1))
|
|
102
|
+
return 0;
|
|
103
|
+
const q = 1 - t * t;
|
|
104
|
+
return options.deriv === 1 ? q * (1 - 5 * t * t) : q * q;
|
|
105
|
+
};
|
|
106
|
+
return typeof u === "number" ? one(u) : Array.from(u, one);
|
|
107
|
+
}
|
|
108
|
+
function median(values) {
|
|
109
|
+
if (values.length === 0)
|
|
110
|
+
return NaN;
|
|
111
|
+
const sorted = Array.from(values).sort((a, b) => a - b);
|
|
112
|
+
const m = Math.floor(sorted.length / 2);
|
|
113
|
+
return sorted.length % 2 ? sorted[m] : (sorted[m - 1] + sorted[m]) / 2;
|
|
114
|
+
}
|
|
115
|
+
function weightedMedian(values, weights) {
|
|
116
|
+
const pairs = values.map((value, i) => ({ value, weight: weights[i] })).filter((p) => p.weight > 0);
|
|
117
|
+
pairs.sort((a, b) => a.value - b.value);
|
|
118
|
+
const total = pairs.reduce((sum, p) => sum + p.weight, 0);
|
|
119
|
+
let cumulative = 0;
|
|
120
|
+
for (let i = 0; i < pairs.length; i++) {
|
|
121
|
+
const p = pairs[i];
|
|
122
|
+
cumulative += p.weight;
|
|
123
|
+
if (cumulative > total / 2)
|
|
124
|
+
return p.value;
|
|
125
|
+
if (cumulative === total / 2) {
|
|
126
|
+
const next = pairs[i + 1];
|
|
127
|
+
return next === undefined ? p.value : (p.value + next.value) / 2;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return pairs[pairs.length - 1]?.value ?? NaN;
|
|
131
|
+
}
|
|
132
|
+
function psiWeight(psi, u, options) {
|
|
133
|
+
if (psi === "huber")
|
|
134
|
+
return Number(psiHuber(u, { k: options.k }));
|
|
135
|
+
if (psi === "hampel")
|
|
136
|
+
return psiHampel(u, { a: options.a, b: options.b, c: options.c });
|
|
137
|
+
return psiBisquare(u, { c: options.c });
|
|
138
|
+
}
|
|
139
|
+
function psiScore(psi, u, model) {
|
|
140
|
+
return u * psiWeight(psi, u, model);
|
|
141
|
+
}
|
|
142
|
+
function psiDerivative(psi, u, model) {
|
|
143
|
+
if (psi === "huber")
|
|
144
|
+
return psiHuber(u, { k: model.k, deriv: 1 }) ? 1 : 0;
|
|
145
|
+
if (psi === "hampel")
|
|
146
|
+
return psiHampel(u, { a: model.a, b: model.b, c: model.c, deriv: 1 });
|
|
147
|
+
return psiBisquare(u, { c: model.c, deriv: 1 });
|
|
148
|
+
}
|
|
149
|
+
function effectiveResiduals(residuals, weights, method) {
|
|
150
|
+
if (method === "inv")
|
|
151
|
+
return { u: residuals.map((r, i) => Math.sqrt(weights[i]) * r), q: weights.map(() => 1), n: residuals.length };
|
|
152
|
+
return { u: residuals.slice(), q: weights.slice(), n: weights.reduce((sum, w) => sum + w, 0) };
|
|
153
|
+
}
|
|
154
|
+
function proposal2Constant(k) {
|
|
155
|
+
const upper = pnorm(k);
|
|
156
|
+
const density = Math.exp(-0.5 * k * k) / Math.sqrt(2 * Math.PI);
|
|
157
|
+
return 2 * upper - 1 - 2 * k * density + 2 * k * k * (1 - upper);
|
|
158
|
+
}
|
|
159
|
+
function proposalScale(residuals, weights, method, k2, p) {
|
|
160
|
+
const transformed = effectiveResiduals(residuals, weights, method);
|
|
161
|
+
const absolute = transformed.u.map(Math.abs);
|
|
162
|
+
const q = transformed.q;
|
|
163
|
+
const denominator = transformed.n - p;
|
|
164
|
+
if (!(denominator > 0))
|
|
165
|
+
return NaN;
|
|
166
|
+
const target = proposal2Constant(k2);
|
|
167
|
+
// The supplied stackloss-scale-huber check distinguishes the divisor: MASS fitTight
|
|
168
|
+
// satisfies sum(chi)/(n-p) - beta = -1.1e-15, while sum(chi)/n - beta = -0.135.
|
|
169
|
+
// The rStats.js fit satisfies the latter equation (2.2e-16) and has the wrong scale.
|
|
170
|
+
// Thus Proposal 2 uses the residual degrees of freedom, not the raw observation count.
|
|
171
|
+
// Weighted case/inverse extensions (N-p / n-p respectively) are mathematically natural
|
|
172
|
+
// but are not directly covered by a weighted Proposal 2 fixture.
|
|
173
|
+
const meanChi = (scale) => {
|
|
174
|
+
let sum = 0;
|
|
175
|
+
for (let i = 0; i < absolute.length; i++) {
|
|
176
|
+
const z = absolute[i] / scale;
|
|
177
|
+
sum += q[i] * Math.min(z * z, k2 * k2);
|
|
178
|
+
}
|
|
179
|
+
return sum / denominator;
|
|
180
|
+
};
|
|
181
|
+
let lo = 0, hi = Math.max(1, median(absolute));
|
|
182
|
+
if (!(hi > 0))
|
|
183
|
+
return 0;
|
|
184
|
+
while (meanChi(hi) > target && hi < Number.MAX_VALUE / 4)
|
|
185
|
+
hi *= 2;
|
|
186
|
+
for (let i = 0; i < 100; i++) {
|
|
187
|
+
const mid = lo + (hi - lo) / 2;
|
|
188
|
+
if (meanChi(mid) > target)
|
|
189
|
+
lo = mid;
|
|
190
|
+
else
|
|
191
|
+
hi = mid;
|
|
192
|
+
}
|
|
193
|
+
return (lo + hi) / 2;
|
|
194
|
+
}
|
|
195
|
+
function robustScale(residuals, weights, method, scaleEst, k2, p) {
|
|
196
|
+
if (scaleEst === "MAD") {
|
|
197
|
+
const transformed = effectiveResiduals(residuals, weights, method);
|
|
198
|
+
const values = transformed.u.map(Math.abs);
|
|
199
|
+
const m = method === "case" ? weightedMedian(values, transformed.q) : median(values);
|
|
200
|
+
// The recorded reference fits use the rounded normal-consistency constant 0.6745:
|
|
201
|
+
// their public scale agrees with median(|residual|) / 0.6745 to the fixture's full precision.
|
|
202
|
+
return m / 0.6745;
|
|
203
|
+
}
|
|
204
|
+
return proposalScale(residuals, weights, method, k2, p);
|
|
205
|
+
}
|
|
206
|
+
function weightedLeastSquares(x, y, weights) {
|
|
207
|
+
const rows = [];
|
|
208
|
+
const response = [];
|
|
209
|
+
for (let i = 0; i < x.length; i++) {
|
|
210
|
+
const w = weights[i];
|
|
211
|
+
if (!(w > 0))
|
|
212
|
+
continue;
|
|
213
|
+
const sw = Math.sqrt(w);
|
|
214
|
+
rows.push(x[i].map((v) => v * sw));
|
|
215
|
+
response.push(y[i] * sw);
|
|
216
|
+
}
|
|
217
|
+
if (rows.length < (x[0]?.length ?? 0))
|
|
218
|
+
throw new Error("'x' is singular: singular fits are not implemented in 'rlm'");
|
|
219
|
+
const decomposition = qr(rows, { tol: 1e-12 });
|
|
220
|
+
const p = x[0]?.length ?? 0;
|
|
221
|
+
if (decomposition.rank !== p)
|
|
222
|
+
throw new Error("'x' is singular: singular fits are not implemented in 'rlm'");
|
|
223
|
+
return qrCoef(decomposition, response);
|
|
224
|
+
}
|
|
225
|
+
function crossProduct(x, weights) {
|
|
226
|
+
const p = x[0]?.length ?? 0;
|
|
227
|
+
const out = Array.from({ length: p }, () => new Array(p).fill(0));
|
|
228
|
+
for (let i = 0; i < x.length; i++) {
|
|
229
|
+
const w = weights[i];
|
|
230
|
+
if (w === 0)
|
|
231
|
+
continue;
|
|
232
|
+
for (let j = 0; j < p; j++)
|
|
233
|
+
for (let k = 0; k <= j; k++) {
|
|
234
|
+
out[k][j] = out[k][j] + w * x[i][k] * x[i][j];
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
for (let j = 0; j < p; j++)
|
|
238
|
+
for (let k = 0; k < j; k++)
|
|
239
|
+
out[j][k] = out[k][j];
|
|
240
|
+
return out;
|
|
241
|
+
}
|
|
242
|
+
function covarianceScale(residuals, scale, weights, model, p) {
|
|
243
|
+
const { u, q, n } = effectiveResiduals(residuals, weights, model.wtMethod);
|
|
244
|
+
const d = u.map((v) => psiDerivative(model.psi, v / scale, model));
|
|
245
|
+
const meanD = q.reduce((sum, w, i) => sum + w * d[i], 0) / n;
|
|
246
|
+
let varianceD = 0;
|
|
247
|
+
for (let i = 0; i < d.length; i++)
|
|
248
|
+
varianceD += q[i] * (d[i] - meanD) ** 2;
|
|
249
|
+
varianceD /= n - 1;
|
|
250
|
+
const kappa = 1 + (p / n) * varianceD / (meanD * meanD);
|
|
251
|
+
let score2 = 0;
|
|
252
|
+
for (let i = 0; i < u.length; i++)
|
|
253
|
+
score2 += q[i] * psiScore(model.psi, u[i] / scale, model) ** 2;
|
|
254
|
+
const stddev = scale * kappa * Math.sqrt(score2 / (n - p)) / meanD;
|
|
255
|
+
const designWeights = weights;
|
|
256
|
+
const covUnscaled = chol2inv(chol(crossProduct(model.x, designWeights)));
|
|
257
|
+
return { stddev, covUnscaled };
|
|
258
|
+
}
|
|
259
|
+
const S_RHO_C = 1.548;
|
|
260
|
+
const MAX_SUBSET_CANDIDATES = 10_000;
|
|
261
|
+
const MAX_CANDIDATE_ROW_EVALUATIONS = 5_000_000;
|
|
262
|
+
function binomial(n, k) {
|
|
263
|
+
if (k < 0 || k > n)
|
|
264
|
+
return 0n;
|
|
265
|
+
const m = Math.min(k, n - k);
|
|
266
|
+
let value = 1n;
|
|
267
|
+
for (let i = 1; i <= m; i++)
|
|
268
|
+
value = value * BigInt(n - m + i) / BigInt(i);
|
|
269
|
+
return value;
|
|
270
|
+
}
|
|
271
|
+
function unrankSubset(n, p, initialRank) {
|
|
272
|
+
let rank = initialRank;
|
|
273
|
+
const subset = [];
|
|
274
|
+
let first = 0;
|
|
275
|
+
for (let position = 0; position < p; position++) {
|
|
276
|
+
const remaining = p - position - 1;
|
|
277
|
+
let selected = false;
|
|
278
|
+
for (let candidate = first; candidate <= n - remaining - 1; candidate++) {
|
|
279
|
+
const count = binomial(n - candidate - 1, remaining);
|
|
280
|
+
if (rank < count) {
|
|
281
|
+
subset.push(candidate);
|
|
282
|
+
first = candidate + 1;
|
|
283
|
+
selected = true;
|
|
284
|
+
break;
|
|
285
|
+
}
|
|
286
|
+
rank -= count;
|
|
287
|
+
}
|
|
288
|
+
if (!selected)
|
|
289
|
+
throw new RangeError("invalid deterministic subset rank");
|
|
290
|
+
}
|
|
291
|
+
return subset;
|
|
292
|
+
}
|
|
293
|
+
function deterministicSubsets(n, p) {
|
|
294
|
+
const total = binomial(n, p);
|
|
295
|
+
const budget = Math.max(1, Math.min(MAX_SUBSET_CANDIDATES, Math.floor(MAX_CANDIDATE_ROW_EVALUATIONS / (n * p))));
|
|
296
|
+
const count = total < BigInt(budget) ? Number(total) : budget;
|
|
297
|
+
const subsets = [];
|
|
298
|
+
for (let i = 0; i < count; i++) {
|
|
299
|
+
const rank = count === 1 ? 0n : BigInt(i) * (total - 1n) / BigInt(count - 1);
|
|
300
|
+
subsets.push(unrankSubset(n, p, rank));
|
|
301
|
+
}
|
|
302
|
+
return { subsets, total, exhaustive: BigInt(count) === total };
|
|
303
|
+
}
|
|
304
|
+
function residualVector(x, y, coefficients) {
|
|
305
|
+
return y.map((value, i) => value - x[i].reduce((sum, v, j) => sum + v * coefficients[j], 0));
|
|
306
|
+
}
|
|
307
|
+
function effectiveAbsoluteResiduals(residuals, weights, wtMethod) {
|
|
308
|
+
return residuals.map((value, i) => Math.abs(wtMethod === "inv" ? Math.sqrt(weights[i]) * value : value));
|
|
309
|
+
}
|
|
310
|
+
function majorityExactResiduals(x, y, coefficients) {
|
|
311
|
+
const fitted = x.map((row) => row.reduce((sum, value, j) => sum + value * coefficients[j], 0));
|
|
312
|
+
const magnitude = [...y, ...fitted].reduce((m, v) => Math.max(m, Math.abs(v)), Number.MIN_VALUE);
|
|
313
|
+
const tolerance = 64 * Number.EPSILON * magnitude;
|
|
314
|
+
return y.map((value, i) => Math.abs(value - fitted[i]) <= tolerance);
|
|
315
|
+
}
|
|
316
|
+
function ltsObjective(residuals, h, weights, wtMethod) {
|
|
317
|
+
const squares = effectiveAbsoluteResiduals(residuals, weights, wtMethod).map((value) => value * value);
|
|
318
|
+
squares.sort((a, b) => a - b);
|
|
319
|
+
let total = 0;
|
|
320
|
+
for (let i = 0; i < h; i++)
|
|
321
|
+
total += squares[i];
|
|
322
|
+
return total;
|
|
323
|
+
}
|
|
324
|
+
function ltsStart(x, y, observationWeights, wtMethod) {
|
|
325
|
+
if (wtMethod === "case" && observationWeights.some((value) => value !== 1)) {
|
|
326
|
+
throw new RangeError("deterministic LTS initialization does not support case weights");
|
|
327
|
+
}
|
|
328
|
+
const n = y.length, p = x[0]?.length ?? 0;
|
|
329
|
+
const h = Math.floor(n / 2) + Math.floor((p + 1) / 2);
|
|
330
|
+
if (h < p)
|
|
331
|
+
throw new RangeError("not enough observations for a high-breakdown LTS start");
|
|
332
|
+
const search = deterministicSubsets(n, p);
|
|
333
|
+
const candidates = [];
|
|
334
|
+
for (let rank = 0; rank < search.subsets.length; rank++) {
|
|
335
|
+
const indices = search.subsets[rank];
|
|
336
|
+
try {
|
|
337
|
+
const beta = weightedLeastSquares(indices.map((i) => x[i]), indices.map((i) => y[i]), indices.map((i) => observationWeights[i]));
|
|
338
|
+
const objective = ltsObjective(residualVector(x, y, beta), h, observationWeights, wtMethod);
|
|
339
|
+
if (Number.isFinite(objective))
|
|
340
|
+
candidates.push({ coefficients: beta, objective, rank });
|
|
341
|
+
}
|
|
342
|
+
catch {
|
|
343
|
+
// A singular elemental subset cannot identify the regression coefficients.
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
candidates.sort((a, b) => a.objective - b.objective || a.rank - b.rank);
|
|
347
|
+
let best;
|
|
348
|
+
for (const candidate of candidates.slice(0, 16)) {
|
|
349
|
+
let beta = candidate.coefficients;
|
|
350
|
+
let objective = candidate.objective;
|
|
351
|
+
for (let iteration = 0; iteration < 50; iteration++) {
|
|
352
|
+
const residuals = residualVector(x, y, beta);
|
|
353
|
+
const order = effectiveAbsoluteResiduals(residuals, observationWeights, wtMethod)
|
|
354
|
+
.map((value, index) => ({ value, index }))
|
|
355
|
+
.sort((a, b) => a.value - b.value || a.index - b.index);
|
|
356
|
+
const selected = order.slice(0, h).map((entry) => entry.index).sort((a, b) => a - b);
|
|
357
|
+
let next;
|
|
358
|
+
try {
|
|
359
|
+
next = weightedLeastSquares(selected.map((i) => x[i]), selected.map((i) => y[i]), selected.map((i) => observationWeights[i]));
|
|
360
|
+
}
|
|
361
|
+
catch {
|
|
362
|
+
break;
|
|
363
|
+
}
|
|
364
|
+
const nextObjective = ltsObjective(residualVector(x, y, next), h, observationWeights, wtMethod);
|
|
365
|
+
if (nextObjective > objective + 1e-12 * Math.max(1, objective))
|
|
366
|
+
break;
|
|
367
|
+
const same = next.every((value, j) => Math.abs(value - beta[j]) <= 1e-12 * Math.max(1, Math.abs(value)));
|
|
368
|
+
beta = next;
|
|
369
|
+
objective = nextObjective;
|
|
370
|
+
if (same)
|
|
371
|
+
break;
|
|
372
|
+
}
|
|
373
|
+
if (best === undefined || objective < best.objective)
|
|
374
|
+
best = { coefficients: beta, objective };
|
|
375
|
+
}
|
|
376
|
+
if (best === undefined)
|
|
377
|
+
throw new Error("deterministic LTS search found no full-rank subset");
|
|
378
|
+
return {
|
|
379
|
+
...best,
|
|
380
|
+
evaluated: search.subsets.length,
|
|
381
|
+
total: search.total,
|
|
382
|
+
...(search.exhaustive ? {} : {
|
|
383
|
+
warning: "deterministic LTS search examined " + search.subsets.length + " of " + search.total.toString() + " elemental subsets; a high-breakdown start is not certified",
|
|
384
|
+
}),
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
function sRhoValue(u) {
|
|
388
|
+
const t = u / S_RHO_C;
|
|
389
|
+
if (Math.abs(t) >= 1)
|
|
390
|
+
return 1;
|
|
391
|
+
const remainder = 1 - t * t;
|
|
392
|
+
return 1 - remainder * remainder * remainder;
|
|
393
|
+
}
|
|
394
|
+
function sRhoScale(residuals, weights, wtMethod, p) {
|
|
395
|
+
const absolute = effectiveAbsoluteResiduals(residuals, weights, wtMethod);
|
|
396
|
+
const n = absolute.length;
|
|
397
|
+
const denominator = n - p;
|
|
398
|
+
if (!(denominator > 0))
|
|
399
|
+
return NaN;
|
|
400
|
+
const maximumMean = absolute.filter((value) => value > 0).length / denominator;
|
|
401
|
+
if (maximumMean <= 0.5)
|
|
402
|
+
return 0;
|
|
403
|
+
const equation = (scale) => {
|
|
404
|
+
let sum = 0;
|
|
405
|
+
for (const value of absolute)
|
|
406
|
+
sum += sRhoValue(value / scale);
|
|
407
|
+
return sum / denominator - 0.5;
|
|
408
|
+
};
|
|
409
|
+
let lo = 0;
|
|
410
|
+
let hi = absolute.reduce((m, v) => Math.max(m, v), 0);
|
|
411
|
+
if (hi === 0)
|
|
412
|
+
return 0;
|
|
413
|
+
while (equation(hi) > 0 && hi < Number.MAX_VALUE / 4)
|
|
414
|
+
hi *= 2;
|
|
415
|
+
if (!Number.isFinite(hi))
|
|
416
|
+
return NaN;
|
|
417
|
+
for (let iteration = 0; iteration < 64; iteration++) {
|
|
418
|
+
const mid = lo + (hi - lo) / 2;
|
|
419
|
+
if (equation(mid) > 0)
|
|
420
|
+
lo = mid;
|
|
421
|
+
else
|
|
422
|
+
hi = mid;
|
|
423
|
+
}
|
|
424
|
+
return (lo + hi) / 2;
|
|
425
|
+
}
|
|
426
|
+
function sStart(x, y, observationWeights, wtMethod) {
|
|
427
|
+
if (wtMethod === "case" && observationWeights.some((value) => value !== 1)) {
|
|
428
|
+
throw new RangeError("MM estimation does not support case weights");
|
|
429
|
+
}
|
|
430
|
+
const n = y.length, p = x[0]?.length ?? 0;
|
|
431
|
+
if (n <= p)
|
|
432
|
+
throw new RangeError("not enough observations for a high-breakdown S start");
|
|
433
|
+
const search = deterministicSubsets(n, p);
|
|
434
|
+
const candidates = [];
|
|
435
|
+
for (let rank = 0; rank < search.subsets.length; rank++) {
|
|
436
|
+
const indices = search.subsets[rank];
|
|
437
|
+
try {
|
|
438
|
+
const beta = weightedLeastSquares(indices.map((i) => x[i]), indices.map((i) => y[i]), indices.map((i) => observationWeights[i]));
|
|
439
|
+
const scale = sRhoScale(residualVector(x, y, beta), observationWeights, wtMethod, p);
|
|
440
|
+
if (Number.isFinite(scale))
|
|
441
|
+
candidates.push({ coefficients: beta, objective: scale, rank });
|
|
442
|
+
}
|
|
443
|
+
catch {
|
|
444
|
+
// A singular elemental subset cannot identify the regression coefficients.
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
candidates.sort((a, b) => a.objective - b.objective || a.rank - b.rank);
|
|
448
|
+
let best;
|
|
449
|
+
for (const candidate of candidates.slice(0, 16)) {
|
|
450
|
+
let beta = candidate.coefficients;
|
|
451
|
+
let scale = candidate.objective;
|
|
452
|
+
for (let iteration = 0; iteration < 50; iteration++) {
|
|
453
|
+
if (!(scale > 0))
|
|
454
|
+
break;
|
|
455
|
+
const residuals = residualVector(x, y, beta);
|
|
456
|
+
const absolute = effectiveAbsoluteResiduals(residuals, observationWeights, wtMethod);
|
|
457
|
+
const refinementWeights = absolute.map((value, i) => {
|
|
458
|
+
const ratio = value / (scale * S_RHO_C);
|
|
459
|
+
return ratio < 1 ? (1 - ratio * ratio) ** 2 * observationWeights[i] : 0;
|
|
460
|
+
});
|
|
461
|
+
if (refinementWeights.filter((value) => value > 0).length < p)
|
|
462
|
+
break;
|
|
463
|
+
let next;
|
|
464
|
+
try {
|
|
465
|
+
next = weightedLeastSquares(x, y, refinementWeights);
|
|
466
|
+
}
|
|
467
|
+
catch {
|
|
468
|
+
break;
|
|
469
|
+
}
|
|
470
|
+
const nextScale = sRhoScale(residualVector(x, y, next), observationWeights, wtMethod, p);
|
|
471
|
+
const scaleTolerance = 1e-12 * Math.max(Math.abs(scale), Math.abs(nextScale), Number.MIN_VALUE);
|
|
472
|
+
if (!(nextScale >= 0) || nextScale > scale + scaleTolerance)
|
|
473
|
+
break;
|
|
474
|
+
const same = next.every((value, j) => Math.abs(value - beta[j])
|
|
475
|
+
<= 1e-12 * Math.max(Math.abs(value), Math.abs(beta[j]), Number.MIN_VALUE));
|
|
476
|
+
beta = next;
|
|
477
|
+
scale = nextScale;
|
|
478
|
+
if (same)
|
|
479
|
+
break;
|
|
480
|
+
}
|
|
481
|
+
if (best === undefined || scale < best.objective)
|
|
482
|
+
best = { coefficients: beta, objective: scale };
|
|
483
|
+
}
|
|
484
|
+
if (best === undefined)
|
|
485
|
+
throw new Error("deterministic S search found no full-rank subset");
|
|
486
|
+
return {
|
|
487
|
+
...best,
|
|
488
|
+
evaluated: search.subsets.length,
|
|
489
|
+
total: search.total,
|
|
490
|
+
...(search.exhaustive ? {} : {
|
|
491
|
+
warning: "deterministic S search examined " + search.subsets.length + " of " + search.total.toString() + " elemental subsets; a high-breakdown start is not certified",
|
|
492
|
+
}),
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
/** Robust M regression. Equivalent to R's `MASS::rlm()`.
|
|
496
|
+
*
|
|
497
|
+
* @param formula A formula such as `"y ~ x1 + x2"`.
|
|
498
|
+
* @param data Columns of equal-length observations.
|
|
499
|
+
* @param options Psi, scale, initial values, observation weights and iteration controls.
|
|
500
|
+
* @returns Coefficients, fitted values, residuals, robust weights, scale and covariance diagnostics.
|
|
501
|
+
*
|
|
502
|
+
* @example
|
|
503
|
+
* ```ts
|
|
504
|
+
* rlm("y ~ x", { y: [1, 2, 2.9, 4.2, 5], x: [1, 2, 3, 4, 5] }).coefficients;
|
|
505
|
+
* ```
|
|
506
|
+
*
|
|
507
|
+
* @category Regression
|
|
508
|
+
*/
|
|
509
|
+
export function rlm(formula, data, options = {}) {
|
|
510
|
+
checkOptions(options, RLM_KEYS, "rlm"); // generated: option-keys.mjs
|
|
511
|
+
const method = options.method ?? "M";
|
|
512
|
+
if (method !== "M" && method !== "MM")
|
|
513
|
+
throw new RangeError("method must be 'M' or 'MM'");
|
|
514
|
+
const psi = options.psi ?? (method === "MM" ? "bisquare" : "huber");
|
|
515
|
+
if (psi !== "huber" && psi !== "hampel" && psi !== "bisquare")
|
|
516
|
+
throw new RangeError("unknown psi function");
|
|
517
|
+
if (method === "MM" && psi === "huber")
|
|
518
|
+
throw new RangeError("MM estimation requires a redescending psi function");
|
|
519
|
+
const scaleEst = options.scaleEst ?? "MAD";
|
|
520
|
+
if (scaleEst !== "MAD" && scaleEst !== "Huber" && scaleEst !== "proposal 2")
|
|
521
|
+
throw new RangeError("unknown scale estimator");
|
|
522
|
+
const wtMethod = options.wtMethod ?? "inv";
|
|
523
|
+
if (wtMethod !== "inv" && wtMethod !== "case")
|
|
524
|
+
throw new RangeError("wtMethod must be 'inv' or 'case'");
|
|
525
|
+
if (method === "MM" && wtMethod === "case" && options.weights !== undefined) {
|
|
526
|
+
throw new RangeError("MM estimation does not support case weights");
|
|
527
|
+
}
|
|
528
|
+
if (method === "MM" && options.init !== undefined) {
|
|
529
|
+
throw new RangeError("MM estimation always uses its deterministic S-estimator start");
|
|
530
|
+
}
|
|
531
|
+
const k = options.k ?? 1.345, a = options.a ?? 2, b = options.b ?? 4;
|
|
532
|
+
const c = options.c ?? (psi === "bisquare" ? 4.685 : 8), k2 = options.k2 ?? 1.345;
|
|
533
|
+
const maxit = options.maxit ?? 1000, acc = options.acc ?? 1e-10;
|
|
534
|
+
if (!(k > 0 && k2 > 0) || ![k, k2].every(Number.isFinite))
|
|
535
|
+
throw new RangeError("k and k2 must be positive and finite");
|
|
536
|
+
if (!(a > 0 && a < b && b < c) || ![a, b, c].every(Number.isFinite)) {
|
|
537
|
+
if (psi === "hampel")
|
|
538
|
+
throw new RangeError("Hampel psi requires 0 < a < b < c");
|
|
539
|
+
}
|
|
540
|
+
if (psi === "bisquare" && (!(c > 0) || !Number.isFinite(c)))
|
|
541
|
+
throw new RangeError("bisquare c must be positive and finite");
|
|
542
|
+
if (!Number.isInteger(maxit) || maxit < 1)
|
|
543
|
+
throw new RangeError("maxit must be a positive integer");
|
|
544
|
+
if (!(acc > 0) || !Number.isFinite(acc))
|
|
545
|
+
throw new RangeError("acc must be positive and finite");
|
|
546
|
+
const parsed = parseFormula(formula);
|
|
547
|
+
if (parsed.response === undefined)
|
|
548
|
+
throw new TypeError("formula must have a response");
|
|
549
|
+
const designOptions = {};
|
|
550
|
+
if (options.weights !== undefined)
|
|
551
|
+
designOptions.weights = options.weights;
|
|
552
|
+
const d = design(parsed, data, designOptions);
|
|
553
|
+
if (d.y === undefined)
|
|
554
|
+
throw new TypeError("response must be numeric");
|
|
555
|
+
const x = d.x;
|
|
556
|
+
const y = d.y;
|
|
557
|
+
const observationWeights = d.frame.weights ?? new Array(y.length).fill(1);
|
|
558
|
+
if (observationWeights.some((w) => !Number.isFinite(w) || w < 0))
|
|
559
|
+
throw new RangeError("weights must be finite and non-negative");
|
|
560
|
+
if (!x.every((row) => row.every(Number.isFinite)) || !y.every(Number.isFinite))
|
|
561
|
+
throw new RangeError("NA/NaN/Inf in model matrix or response");
|
|
562
|
+
const p = x[0]?.length ?? 0;
|
|
563
|
+
if (p === 0)
|
|
564
|
+
throw new Error("model has no coefficients");
|
|
565
|
+
// Reject an aliased design before any robust-start search can discard singular subsets.
|
|
566
|
+
const leastSquaresCoefficients = weightedLeastSquares(x, y, observationWeights);
|
|
567
|
+
const model = {
|
|
568
|
+
formula, x, y, columnNames: d.colNames, observationWeights, wtMethod, psi, scaleEst,
|
|
569
|
+
k, a, b, c, k2, rows: d.frame.rows,
|
|
570
|
+
};
|
|
571
|
+
const searchWarnings = [];
|
|
572
|
+
let coefficients;
|
|
573
|
+
let fixedScale;
|
|
574
|
+
let initialization;
|
|
575
|
+
if (method === "MM") {
|
|
576
|
+
const start = sStart(x, y, observationWeights, wtMethod);
|
|
577
|
+
coefficients = start.coefficients;
|
|
578
|
+
fixedScale = start.objective;
|
|
579
|
+
initialization = {
|
|
580
|
+
method: "S",
|
|
581
|
+
coefficients: Object.fromEntries(model.columnNames.map((name, index) => [name, start.coefficients[index]])),
|
|
582
|
+
objective: start.objective, candidatesEvaluated: start.evaluated,
|
|
583
|
+
candidateCount: start.total.toString(), exhaustive: start.warning === undefined,
|
|
584
|
+
};
|
|
585
|
+
if (start.warning !== undefined)
|
|
586
|
+
searchWarnings.push(start.warning);
|
|
587
|
+
}
|
|
588
|
+
else if (options.init === "lts") {
|
|
589
|
+
const start = ltsStart(x, y, observationWeights, wtMethod);
|
|
590
|
+
coefficients = start.coefficients;
|
|
591
|
+
initialization = {
|
|
592
|
+
method: "LTS",
|
|
593
|
+
coefficients: Object.fromEntries(model.columnNames.map((name, index) => [name, start.coefficients[index]])),
|
|
594
|
+
objective: start.objective, candidatesEvaluated: start.evaluated,
|
|
595
|
+
candidateCount: start.total.toString(), exhaustive: start.warning === undefined,
|
|
596
|
+
};
|
|
597
|
+
if (start.warning !== undefined)
|
|
598
|
+
searchWarnings.push(start.warning);
|
|
599
|
+
}
|
|
600
|
+
else if (options.init === undefined || options.init === "ls") {
|
|
601
|
+
coefficients = leastSquaresCoefficients;
|
|
602
|
+
}
|
|
603
|
+
else if (typeof options.init === "string") {
|
|
604
|
+
throw new RangeError("init must be 'ls', 'lts' or a numeric coefficient vector");
|
|
605
|
+
}
|
|
606
|
+
else {
|
|
607
|
+
coefficients = Array.from(options.init);
|
|
608
|
+
if (coefficients.length !== p || !coefficients.every(Number.isFinite))
|
|
609
|
+
throw new RangeError("init must have " + p + " finite coefficients");
|
|
610
|
+
}
|
|
611
|
+
const convergence = [];
|
|
612
|
+
const initialInliers = majorityExactResiduals(x, y, coefficients);
|
|
613
|
+
let converged = initialInliers.filter((inlier, i) => inlier && observationWeights[i] > 0).length > y.length / 2;
|
|
614
|
+
let scale = converged ? 0 : (fixedScale ?? NaN);
|
|
615
|
+
let robustWeights = new Array(y.length).fill(1);
|
|
616
|
+
let workingWeights = observationWeights.slice();
|
|
617
|
+
let iterations = 0;
|
|
618
|
+
const effectiveObsWeights = (residuals, s) => {
|
|
619
|
+
const u = residuals.map((r, i) => (wtMethod === "inv" ? Math.sqrt(observationWeights[i]) * r : r) / s);
|
|
620
|
+
return u.map((v, i) => psiWeight(psi, v, model) * observationWeights[i]);
|
|
621
|
+
};
|
|
622
|
+
for (let iteration = 1; !converged && iteration <= maxit; iteration++) {
|
|
623
|
+
iterations = iteration;
|
|
624
|
+
const residuals = residualVector(x, y, coefficients);
|
|
625
|
+
scale = fixedScale ?? robustScale(residuals, observationWeights, wtMethod, scaleEst, k2, p);
|
|
626
|
+
if (!(scale > 0) || !Number.isFinite(scale)) {
|
|
627
|
+
const exact = scale === 0 && residuals.every((r, i) => observationWeights[i] === 0 || r === 0);
|
|
628
|
+
if (exact) {
|
|
629
|
+
converged = true;
|
|
630
|
+
break;
|
|
631
|
+
}
|
|
632
|
+
throw new Error("robust scale is not positive and finite");
|
|
633
|
+
}
|
|
634
|
+
robustWeights = residuals.map((r, i) => {
|
|
635
|
+
const u = (wtMethod === "inv" ? Math.sqrt(observationWeights[i]) * r : r) / scale;
|
|
636
|
+
return psiWeight(psi, u, model);
|
|
637
|
+
});
|
|
638
|
+
workingWeights = effectiveObsWeights(residuals, scale);
|
|
639
|
+
const irls = weightedLeastSquares(x, y, workingWeights);
|
|
640
|
+
// Redescending scores can make full IRLS updates oscillate between distinct roots.
|
|
641
|
+
// A fixed half-step is deterministic and keeps the iteration inside the basin of the
|
|
642
|
+
// robust start; monotone scores (Huber) retain the full update.
|
|
643
|
+
const damping = psi === "huber" ? 1 : 0.5;
|
|
644
|
+
const next = coefficients.map((value, j) => value + damping * (irls[j] - value));
|
|
645
|
+
const nextResiduals = residualVector(x, y, next);
|
|
646
|
+
const nextInliers = majorityExactResiduals(x, y, next);
|
|
647
|
+
if (nextInliers.filter((inlier, i) => inlier && observationWeights[i] > 0).length > y.length / 2) {
|
|
648
|
+
coefficients = next;
|
|
649
|
+
scale = 0;
|
|
650
|
+
converged = true;
|
|
651
|
+
break;
|
|
652
|
+
}
|
|
653
|
+
const nextScale = fixedScale ?? robustScale(nextResiduals, observationWeights, wtMethod, scaleEst, k2, p);
|
|
654
|
+
if (!(nextScale > 0) || !Number.isFinite(nextScale)) {
|
|
655
|
+
const exact = nextScale === 0 && nextResiduals.every((r, i) => observationWeights[i] === 0 || r === 0);
|
|
656
|
+
if (exact) {
|
|
657
|
+
coefficients = next;
|
|
658
|
+
scale = 0;
|
|
659
|
+
converged = true;
|
|
660
|
+
break;
|
|
661
|
+
}
|
|
662
|
+
throw new Error("robust scale is not positive and finite");
|
|
663
|
+
}
|
|
664
|
+
let scoreNorm = 0;
|
|
665
|
+
for (let j = 0; j < p; j++) {
|
|
666
|
+
let score = 0, magnitude = 0;
|
|
667
|
+
for (let i = 0; i < y.length; i++) {
|
|
668
|
+
const rootWeight = wtMethod === "inv" ? Math.sqrt(observationWeights[i]) : observationWeights[i];
|
|
669
|
+
const u = (wtMethod === "inv" ? Math.sqrt(observationWeights[i]) * nextResiduals[i] : nextResiduals[i]) / nextScale;
|
|
670
|
+
const contribution = rootWeight * x[i][j] * psiScore(psi, u, model);
|
|
671
|
+
score += contribution;
|
|
672
|
+
magnitude += Math.abs(contribution);
|
|
673
|
+
}
|
|
674
|
+
scoreNorm = Math.max(scoreNorm, magnitude === 0 ? Math.abs(score) : Math.abs(score) / magnitude);
|
|
675
|
+
}
|
|
676
|
+
const scaleNorm = fixedScale === undefined
|
|
677
|
+
? Math.abs(nextScale - scale) / Math.max(Math.abs(nextScale), Math.abs(scale), Number.MIN_VALUE)
|
|
678
|
+
: 0;
|
|
679
|
+
const residual = Math.max(scoreNorm, scaleNorm);
|
|
680
|
+
convergence.push(residual);
|
|
681
|
+
coefficients = next;
|
|
682
|
+
scale = nextScale;
|
|
683
|
+
if (residual <= acc) {
|
|
684
|
+
converged = true;
|
|
685
|
+
break;
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
const fittedValues = x.map((row) => row.reduce((sum, v, j) => sum + v * coefficients[j], 0));
|
|
689
|
+
const residuals = y.map((v, i) => v - fittedValues[i]);
|
|
690
|
+
scale = fixedScale ?? robustScale(residuals, observationWeights, wtMethod, scaleEst, k2, p);
|
|
691
|
+
const inlierMask = majorityExactResiduals(x, y, coefficients);
|
|
692
|
+
const exactFit = scale === 0 && residuals.every((r, i) => observationWeights[i] === 0 || r === 0);
|
|
693
|
+
const majorityExactFit = scale === 0
|
|
694
|
+
&& inlierMask.filter((inlier, i) => inlier && observationWeights[i] > 0).length > y.length / 2;
|
|
695
|
+
if (scale === 0 && !exactFit && !majorityExactFit)
|
|
696
|
+
throw new Error("robust scale is zero but fewer than half the observations lie on the fitted line");
|
|
697
|
+
robustWeights = majorityExactFit
|
|
698
|
+
? inlierMask.map((inlier, i) => inlier && observationWeights[i] > 0 ? 1 : 0)
|
|
699
|
+
: exactFit ? observationWeights.map((w) => w > 0 ? 1 : 0) : residuals.map((r, i) => {
|
|
700
|
+
const u = (wtMethod === "inv" ? Math.sqrt(observationWeights[i]) * r : r) / scale;
|
|
701
|
+
return psiWeight(psi, u, model);
|
|
702
|
+
});
|
|
703
|
+
workingWeights = majorityExactFit
|
|
704
|
+
? robustWeights.map((weight, i) => weight * observationWeights[i])
|
|
705
|
+
: exactFit ? observationWeights.slice() : effectiveObsWeights(residuals, scale);
|
|
706
|
+
const undefinedCovariance = () => Array.from({ length: p }, () => new Array(p).fill(Number.NaN));
|
|
707
|
+
const covariance = majorityExactFit
|
|
708
|
+
? { stddev: Number.NaN, covUnscaled: undefinedCovariance() }
|
|
709
|
+
: exactFit
|
|
710
|
+
? { stddev: 0, covUnscaled: chol2inv(chol(crossProduct(x, observationWeights))) }
|
|
711
|
+
: covarianceScale(residuals, scale, observationWeights, model, p);
|
|
712
|
+
const warnings = [...d.warnings, ...searchWarnings];
|
|
713
|
+
if (majorityExactFit)
|
|
714
|
+
warnings.push("more than half of the observations lie exactly on the fitted line; scale and inference are undefined");
|
|
715
|
+
if (!converged)
|
|
716
|
+
warnings.push("'rlm' failed to converge in " + maxit + " steps");
|
|
717
|
+
const result = {
|
|
718
|
+
coefficients: Object.fromEntries(d.colNames.map((name, i) => [name, coefficients[i]])),
|
|
719
|
+
fittedValues, residuals, robustWeights, workingWeights,
|
|
720
|
+
scale, stddev: covariance.stddev,
|
|
721
|
+
covariance: covariance.covUnscaled.map((row) => row.map((v) => v * covariance.stddev ** 2)),
|
|
722
|
+
covarianceUnscaled: covariance.covUnscaled,
|
|
723
|
+
converged, iterations, convergence, warnings, model,
|
|
724
|
+
...(initialization === undefined ? {} : { initialization }),
|
|
725
|
+
};
|
|
726
|
+
return reported("rlm", result);
|
|
727
|
+
}
|
|
728
|
+
/** Coefficient table of a robust fit. Equivalent to R's `summary.rlm()`.
|
|
729
|
+
*
|
|
730
|
+
* @param fit A fit returned by {@link rlm}.
|
|
731
|
+
* @returns Coefficients, standard errors and t statistics.
|
|
732
|
+
*
|
|
733
|
+
* @example
|
|
734
|
+
* ```ts
|
|
735
|
+
* rlmSummary(rlm("y ~ x", { y: [1, 2, 2.9, 4.2, 5], x: [1, 2, 3, 4, 5] }));
|
|
736
|
+
* ```
|
|
737
|
+
*
|
|
738
|
+
* @category Regression
|
|
739
|
+
*/
|
|
740
|
+
export function rlmSummary(fit, options = {}) {
|
|
741
|
+
const rows = fit.model.columnNames;
|
|
742
|
+
const values = rows.map((_, i) => {
|
|
743
|
+
const se = Math.sqrt(fit.covariance[i][i]);
|
|
744
|
+
const value = fit.coefficients[rows[i]];
|
|
745
|
+
return [value, se, value / se];
|
|
746
|
+
});
|
|
747
|
+
return reported("rlmSummary", { rows, columns: ["Value", "Std. Error", "t value"], values, warnings: fit.warnings }, fit);
|
|
748
|
+
}
|
|
749
|
+
/** Covariance matrix of robust-regression coefficients. Equivalent to R's `vcov.rlm()`.
|
|
750
|
+
*
|
|
751
|
+
* @param fit A fit returned by {@link rlm}.
|
|
752
|
+
* @returns The covariance matrix in coefficient order.
|
|
753
|
+
*
|
|
754
|
+
* @example
|
|
755
|
+
* ```ts
|
|
756
|
+
* rlmVcov(rlm("y ~ x", { y: [1, 2, 2.9, 4.2, 5], x: [1, 2, 3, 4, 5] }));
|
|
757
|
+
* ```
|
|
758
|
+
*
|
|
759
|
+
* @category Regression
|
|
760
|
+
*/
|
|
761
|
+
export function rlmVcov(fit, options = {}) {
|
|
762
|
+
return reported("rlmVcov", {
|
|
763
|
+
rows: fit.model.columnNames, columns: fit.model.columnNames,
|
|
764
|
+
values: fit.covariance, warnings: fit.warnings,
|
|
765
|
+
}, fit);
|
|
766
|
+
}
|