@numero-uno-jpn/rstats 1.7.0 → 1.8.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 +18 -0
- package/README.ja.md +3 -3
- package/README.md +3 -3
- package/dist/chunks/{chunk-76FLTZVF.js → chunk-2X6PE6JF.js} +2 -2
- package/dist/chunks/{chunk-YKNRDPIB.js → chunk-2ZQ2TSZS.js} +1 -1
- package/dist/chunks/{chunk-PCTRVBEJ.js → chunk-3DO726WZ.js} +2 -2
- package/dist/chunks/{chunk-THSV22QF.js → chunk-45HUI3M4.js} +2 -2
- package/dist/chunks/{chunk-QWDK3ZC2.js → chunk-52RWDNO6.js} +2 -2
- package/dist/chunks/{chunk-VQOU7U7R.js → chunk-53OM63EU.js} +2 -2
- package/dist/chunks/{chunk-MOJ2KIQE.js → chunk-73IRLCTF.js} +2 -2
- package/dist/chunks/{chunk-J7ZVV4DN.js → chunk-7ODUCEGX.js} +2 -2
- package/dist/chunks/chunk-ANZUXEMH.js +3 -0
- package/dist/chunks/chunk-BHQGMZTI.js +2 -0
- package/dist/chunks/{chunk-RIP2RKAW.js → chunk-D3LKPD4H.js} +2 -2
- package/dist/chunks/{chunk-FQRNZEH2.js → chunk-DG2RTNIR.js} +2 -2
- package/dist/chunks/{chunk-SDT3YHAG.js → chunk-GRTQ7FYQ.js} +2 -2
- package/dist/chunks/{chunk-R5BMFVIH.js → chunk-HXYH5ZMB.js} +2 -2
- package/dist/chunks/chunk-HYJ4MIZE.js +2 -0
- package/dist/chunks/{chunk-CUT3IHMY.js → chunk-IJST2ZGT.js} +1 -1
- package/dist/chunks/{chunk-B7XZMIQO.js → chunk-JIAFWEED.js} +2 -2
- package/dist/chunks/{chunk-TY3IFCLI.js → chunk-JXJDCQYE.js} +2 -2
- package/dist/chunks/{chunk-CZUOG2U5.js → chunk-LZB43TUL.js} +2 -2
- package/dist/chunks/{chunk-RX6MZO2Y.js → chunk-MLNWWGGE.js} +2 -2
- package/dist/chunks/{chunk-HSJ4OT3H.js → chunk-QQHF5T2A.js} +1 -1
- package/dist/chunks/{chunk-PLQQ4VFN.js → chunk-RWZ6ICYN.js} +2 -2
- package/dist/chunks/{chunk-JXEXOD7K.js → chunk-TQM6KGKT.js} +2 -2
- package/dist/chunks/{chunk-CB7STL5Z.js → chunk-TUL6UFLQ.js} +2 -2
- package/dist/chunks/{chunk-HORF36FD.js → chunk-TYMC2D5I.js} +2 -2
- package/dist/chunks/{chunk-BJMPSDJ7.js → chunk-V7ECXPWY.js} +2 -2
- package/dist/chunks/{chunk-AIEPW6DX.js → chunk-VB6PVRSN.js} +2 -2
- package/dist/chunks/{chunk-YVJ4LDDE.js → chunk-Y4KNH43T.js} +2 -2
- package/dist/chunks/{chunk-VALULDEX.js → chunk-YD4U3QZ3.js} +1 -1
- package/dist/chunks/{chunk-V2Y2W7LE.js → chunk-YT62DNDS.js} +2 -2
- package/dist/descriptive.js +2 -2
- package/dist/distributions.js +2 -2
- package/dist/entries/regression.d.ts +4 -0
- package/dist/entries/regression.js +6 -0
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +2 -2
- package/dist/models/gee.d.ts +280 -0
- package/dist/models/gee.js +704 -0
- package/dist/models/glmnet.d.ts +259 -0
- package/dist/models/glmnet.js +1112 -0
- package/dist/models/modelMatrix.d.ts +2 -0
- package/dist/models/rq.d.ts +203 -0
- package/dist/models/rq.js +1089 -0
- package/dist/numerics.js +2 -2
- package/dist/regression.js +3 -3
- package/dist/rstats.js +1 -1
- package/dist/special.js +2 -2
- package/dist/tests.js +15 -15
- package/llms.txt +3 -0
- package/package.json +1 -1
- package/dist/chunks/chunk-56AMJQ27.js +0 -2
- package/dist/chunks/chunk-B6KJ4RWG.js +0 -2
- package/dist/chunks/chunk-KSH43GX4.js +0 -2
- package/dist/chunks/chunk-LMRCFKVK.js +0 -2
- package/dist/chunks/chunk-R7F7ELS7.js +0 -3
|
@@ -0,0 +1,1089 @@
|
|
|
1
|
+
// Quantile regression. The linear-programming formulation follows Koenker and Bassett (1978)
|
|
2
|
+
// and the primal-dual interior-point method of Portnoy and Koenker (1997).
|
|
3
|
+
// This implementation is independently derived from those published equations and public numerical output.
|
|
4
|
+
import { reported } from "../internal/warnings.js";
|
|
5
|
+
import { qr, qrCoef } from "../linalg/qr.js";
|
|
6
|
+
import { parseFormula } from "./formula.js";
|
|
7
|
+
import { design } from "./modelMatrix.js";
|
|
8
|
+
import { pt, qt } from "../distributions/t.js";
|
|
9
|
+
import { qnorm } from "../distributions/normal.js";
|
|
10
|
+
import { pf } from "../distributions/f.js";
|
|
11
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
12
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
13
|
+
const RQ_KEYS = ["tau", "method", "weights", "contrasts", "levels", "maxit", "eps"];
|
|
14
|
+
const RQ_SUMMARY_KEYS = ["se", "covariance", "level", "iid"];
|
|
15
|
+
const RQ_PREDICT_INTERVAL_KEYS = ["interval", "type", "level"];
|
|
16
|
+
function solveLinear(a, b) {
|
|
17
|
+
const n = b.length;
|
|
18
|
+
const m = a.map((row, i) => [...row, b[i]]);
|
|
19
|
+
for (let k = 0; k < n; k++) {
|
|
20
|
+
let pivot = k;
|
|
21
|
+
for (let i = k + 1; i < n; i++)
|
|
22
|
+
if (Math.abs(m[i][k]) > Math.abs(m[pivot][k]))
|
|
23
|
+
pivot = i;
|
|
24
|
+
let rowScale = 1;
|
|
25
|
+
for (let j = 0; j < n; j++)
|
|
26
|
+
rowScale = Math.max(rowScale, Math.abs(m[pivot][j]));
|
|
27
|
+
if (!(Math.abs(m[pivot][k]) > Number.EPSILON * rowScale)) {
|
|
28
|
+
throw new RangeError("singular design matrix");
|
|
29
|
+
}
|
|
30
|
+
[m[k], m[pivot]] = [m[pivot], m[k]];
|
|
31
|
+
const d = m[k][k];
|
|
32
|
+
for (let j = k; j <= n; j++)
|
|
33
|
+
m[k][j] /= d;
|
|
34
|
+
for (let i = 0; i < n; i++) {
|
|
35
|
+
if (i === k)
|
|
36
|
+
continue;
|
|
37
|
+
const f = m[i][k];
|
|
38
|
+
if (f === 0)
|
|
39
|
+
continue;
|
|
40
|
+
for (let j = k; j <= n; j++)
|
|
41
|
+
m[i][j] -= f * m[k][j];
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return m.map((row) => row[n]);
|
|
45
|
+
}
|
|
46
|
+
function dot(a, b) {
|
|
47
|
+
let s = 0;
|
|
48
|
+
for (let i = 0; i < a.length; i++)
|
|
49
|
+
s += a[i] * b[i];
|
|
50
|
+
return s;
|
|
51
|
+
}
|
|
52
|
+
function cholesky(a) {
|
|
53
|
+
const n = a.length;
|
|
54
|
+
const l = Array.from({ length: n }, () => new Array(n).fill(0));
|
|
55
|
+
for (let i = 0; i < n; i++) {
|
|
56
|
+
for (let j = 0; j <= i; j++) {
|
|
57
|
+
let value = a[i][j];
|
|
58
|
+
for (let k = 0; k < j; k++)
|
|
59
|
+
value -= l[i][k] * l[j][k];
|
|
60
|
+
if (i === j) {
|
|
61
|
+
if (!(value > 0) || !Number.isFinite(value))
|
|
62
|
+
throw new RangeError("normal equations are not positive definite");
|
|
63
|
+
l[i][j] = Math.sqrt(value);
|
|
64
|
+
}
|
|
65
|
+
else {
|
|
66
|
+
l[i][j] = value / l[j][j];
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return l;
|
|
71
|
+
}
|
|
72
|
+
function solveCholesky(l, rhs) {
|
|
73
|
+
const n = rhs.length;
|
|
74
|
+
const x = Array.from(rhs);
|
|
75
|
+
for (let i = 0; i < n; i++) {
|
|
76
|
+
for (let j = 0; j < i; j++)
|
|
77
|
+
x[i] -= l[i][j] * x[j];
|
|
78
|
+
x[i] /= l[i][i];
|
|
79
|
+
}
|
|
80
|
+
for (let i = n - 1; i >= 0; i--) {
|
|
81
|
+
for (let j = i + 1; j < n; j++)
|
|
82
|
+
x[i] -= l[j][i] * x[j];
|
|
83
|
+
x[i] /= l[i][i];
|
|
84
|
+
}
|
|
85
|
+
return x;
|
|
86
|
+
}
|
|
87
|
+
function dualDirection(x, b, lower, upper, rp, rd, rcLower, rcUpper) {
|
|
88
|
+
const n = b.length;
|
|
89
|
+
const p = x[0].length;
|
|
90
|
+
const inverseW = new Array(n);
|
|
91
|
+
const rhs = new Array(n);
|
|
92
|
+
for (let i = 0; i < n; i++) {
|
|
93
|
+
const bi = b[i];
|
|
94
|
+
const oneMinus = 1 - bi;
|
|
95
|
+
if (!(bi > 0 && oneMinus > 0 && lower[i] > 0 && upper[i] > 0)) {
|
|
96
|
+
throw new RangeError("invalid interior point in quantile regression");
|
|
97
|
+
}
|
|
98
|
+
const w = lower[i] / bi + upper[i] / oneMinus;
|
|
99
|
+
inverseW[i] = 1 / w;
|
|
100
|
+
rhs[i] = -rd[i] - rcLower[i] / bi + rcUpper[i] / oneMinus;
|
|
101
|
+
}
|
|
102
|
+
const gram = Array.from({ length: p }, () => new Array(p).fill(0));
|
|
103
|
+
const projected = new Array(p).fill(0);
|
|
104
|
+
for (let i = 0; i < n; i++) {
|
|
105
|
+
const wi = inverseW[i];
|
|
106
|
+
for (let j = 0; j < p; j++) {
|
|
107
|
+
const xj = x[i][j];
|
|
108
|
+
projected[j] += xj * wi * rhs[i];
|
|
109
|
+
for (let k = 0; k <= j; k++)
|
|
110
|
+
gram[j][k] += xj * wi * x[i][k];
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
for (let j = 0; j < p; j++) {
|
|
114
|
+
for (let k = 0; k < j; k++)
|
|
115
|
+
gram[k][j] = gram[j][k];
|
|
116
|
+
projected[j] += rp[j];
|
|
117
|
+
}
|
|
118
|
+
const dbeta = solveCholesky(cholesky(gram), projected);
|
|
119
|
+
const db = new Array(n);
|
|
120
|
+
const dl = new Array(n);
|
|
121
|
+
const du = new Array(n);
|
|
122
|
+
for (let i = 0; i < n; i++) {
|
|
123
|
+
let value = rhs[i];
|
|
124
|
+
for (let j = 0; j < p; j++)
|
|
125
|
+
value -= x[i][j] * dbeta[j];
|
|
126
|
+
db[i] = inverseW[i] * value;
|
|
127
|
+
dl[i] = (-rcLower[i] - lower[i] * db[i]) / b[i];
|
|
128
|
+
du[i] = (-rcUpper[i] + upper[i] * db[i]) / (1 - b[i]);
|
|
129
|
+
}
|
|
130
|
+
return { db, dl, du, dbeta };
|
|
131
|
+
}
|
|
132
|
+
function maxBoxStep(b, db) {
|
|
133
|
+
let step = 1;
|
|
134
|
+
for (let i = 0; i < b.length; i++) {
|
|
135
|
+
if (db[i] > 0)
|
|
136
|
+
step = Math.min(step, (1 - b[i]) / db[i]);
|
|
137
|
+
else if (db[i] < 0)
|
|
138
|
+
step = Math.min(step, -b[i] / db[i]);
|
|
139
|
+
}
|
|
140
|
+
return step;
|
|
141
|
+
}
|
|
142
|
+
function maxPositiveStep(v, dv) {
|
|
143
|
+
let step = 1;
|
|
144
|
+
for (let i = 0; i < v.length; i++)
|
|
145
|
+
if (dv[i] < 0)
|
|
146
|
+
step = Math.min(step, -v[i] / dv[i]);
|
|
147
|
+
return step;
|
|
148
|
+
}
|
|
149
|
+
/** Mehrotra predictor-corrector for the box-constrained dual regression-quantile LP. */
|
|
150
|
+
function fitFn(x, y, tau, maxit, eps) {
|
|
151
|
+
const n = y.length;
|
|
152
|
+
const p = x[0].length;
|
|
153
|
+
const b = new Array(n).fill(1 - tau);
|
|
154
|
+
const lower = new Array(n).fill(1);
|
|
155
|
+
const upper = new Array(n).fill(1);
|
|
156
|
+
const beta = new Array(p).fill(0);
|
|
157
|
+
const h = new Array(p).fill(0);
|
|
158
|
+
for (let i = 0; i < n; i++)
|
|
159
|
+
for (let j = 0; j < p; j++)
|
|
160
|
+
h[j] += (1 - tau) * x[i][j];
|
|
161
|
+
let iterations = 0;
|
|
162
|
+
for (let it = 0; it < maxit; it++) {
|
|
163
|
+
iterations = it + 1;
|
|
164
|
+
const rp = new Array(p).fill(0);
|
|
165
|
+
const rd = new Array(n);
|
|
166
|
+
let rpScale = 1;
|
|
167
|
+
let rdScale = 1;
|
|
168
|
+
let gap = 0;
|
|
169
|
+
let primalObjective = 0;
|
|
170
|
+
let dualObjective = 0;
|
|
171
|
+
for (let i = 0; i < n; i++) {
|
|
172
|
+
dualObjective += y[i] * b[i];
|
|
173
|
+
gap += b[i] * lower[i] + (1 - b[i]) * upper[i];
|
|
174
|
+
for (let j = 0; j < p; j++)
|
|
175
|
+
rp[j] += x[i][j] * b[i];
|
|
176
|
+
let fitted = 0;
|
|
177
|
+
for (let j = 0; j < p; j++)
|
|
178
|
+
fitted += x[i][j] * beta[j];
|
|
179
|
+
rd[i] = fitted - lower[i] + upper[i] - y[i];
|
|
180
|
+
}
|
|
181
|
+
for (let j = 0; j < p; j++) {
|
|
182
|
+
rp[j] -= h[j];
|
|
183
|
+
rpScale = Math.max(rpScale, Math.abs(h[j]));
|
|
184
|
+
}
|
|
185
|
+
for (let i = 0; i < n; i++)
|
|
186
|
+
rdScale = Math.max(rdScale, Math.abs(y[i]));
|
|
187
|
+
for (let i = 0; i < n; i++) {
|
|
188
|
+
const residual = y[i];
|
|
189
|
+
let fitted = 0;
|
|
190
|
+
for (let j = 0; j < p; j++)
|
|
191
|
+
fitted += x[i][j] * beta[j];
|
|
192
|
+
const r = residual - fitted;
|
|
193
|
+
primalObjective += r * (tau - (r < 0 ? 1 : 0));
|
|
194
|
+
}
|
|
195
|
+
const equalityNorm = rp.reduce((m, v) => Math.max(m, Math.abs(v)), 0) / rpScale;
|
|
196
|
+
const stationarityNorm = rd.reduce((m, v) => Math.max(m, Math.abs(v)), 0) / rdScale;
|
|
197
|
+
const gapNorm = gap / Math.max(1, Math.abs(primalObjective), Math.abs(dualObjective));
|
|
198
|
+
if (Math.max(equalityNorm, stationarityNorm, gapNorm) <= eps)
|
|
199
|
+
return { beta, dual: b, iterations };
|
|
200
|
+
const rcLowerAffine = b.map((v, i) => v * lower[i]);
|
|
201
|
+
const rcUpperAffine = b.map((v, i) => (1 - v) * upper[i]);
|
|
202
|
+
const affine = dualDirection(x, b, lower, upper, rp, rd, rcLowerAffine, rcUpperAffine);
|
|
203
|
+
const alphaPAff = Math.min(1, maxBoxStep(b, affine.db));
|
|
204
|
+
const alphaDAff = Math.min(1, maxPositiveStep(lower, affine.dl), maxPositiveStep(upper, affine.du));
|
|
205
|
+
let gapAffine = 0;
|
|
206
|
+
for (let i = 0; i < n; i++) {
|
|
207
|
+
const ba = b[i] + alphaPAff * affine.db[i];
|
|
208
|
+
const la = lower[i] + alphaDAff * affine.dl[i];
|
|
209
|
+
const ua = upper[i] + alphaDAff * affine.du[i];
|
|
210
|
+
gapAffine += ba * la + (1 - ba) * ua;
|
|
211
|
+
}
|
|
212
|
+
const mu = gap / (2 * n);
|
|
213
|
+
const muAffine = gapAffine / (2 * n);
|
|
214
|
+
const sigma = mu > 0 ? Math.max(0, Math.min(1, (muAffine / mu) ** 3)) : 0;
|
|
215
|
+
const rcLower = b.map((v, i) => v * lower[i] + affine.db[i] * affine.dl[i] - sigma * mu);
|
|
216
|
+
const rcUpper = b.map((v, i) => (1 - v) * upper[i] - affine.db[i] * affine.du[i] - sigma * mu);
|
|
217
|
+
const step = dualDirection(x, b, lower, upper, rp, rd, rcLower, rcUpper);
|
|
218
|
+
const alphaP = Math.min(1, 0.99995 * maxBoxStep(b, step.db));
|
|
219
|
+
const alphaD = Math.min(1, 0.99995 * maxPositiveStep(lower, step.dl), 0.99995 * maxPositiveStep(upper, step.du));
|
|
220
|
+
for (let i = 0; i < n; i++) {
|
|
221
|
+
b[i] += alphaP * step.db[i];
|
|
222
|
+
lower[i] += alphaD * step.dl[i];
|
|
223
|
+
upper[i] += alphaD * step.du[i];
|
|
224
|
+
}
|
|
225
|
+
for (let j = 0; j < p; j++)
|
|
226
|
+
beta[j] += alphaD * step.dbeta[j];
|
|
227
|
+
}
|
|
228
|
+
throw new Error("quantile regression interior-point method did not converge within maxit");
|
|
229
|
+
}
|
|
230
|
+
function directionalEdge(x, y, weights, tau, beta, basis, leaving, sign) {
|
|
231
|
+
const p = basis.length;
|
|
232
|
+
const matrix = basis.map((i) => Array.from(x[i]));
|
|
233
|
+
const unit = new Array(p).fill(0);
|
|
234
|
+
unit[leaving] = sign;
|
|
235
|
+
const direction = solveLinear(matrix, unit);
|
|
236
|
+
const slopeTerms = [];
|
|
237
|
+
let slope = 0;
|
|
238
|
+
for (let i = 0; i < x.length; i++) {
|
|
239
|
+
let fitted = 0;
|
|
240
|
+
let movement = 0;
|
|
241
|
+
for (let j = 0; j < p; j++) {
|
|
242
|
+
fitted += x[i][j] * beta[j];
|
|
243
|
+
movement -= x[i][j] * direction[j];
|
|
244
|
+
}
|
|
245
|
+
const residual = y[i] - fitted;
|
|
246
|
+
const scale = Math.max(1, Math.abs(y[i]), Math.abs(fitted));
|
|
247
|
+
if (Math.abs(residual) <= 32 * Number.EPSILON * scale) {
|
|
248
|
+
if (movement > 0)
|
|
249
|
+
slope += weights[i] * tau * movement;
|
|
250
|
+
else if (movement < 0)
|
|
251
|
+
slope += weights[i] * (tau - 1) * movement;
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
slope += weights[i] * movement * (tau - (residual < 0 ? 1 : 0));
|
|
255
|
+
if (movement !== 0) {
|
|
256
|
+
const time = -residual / movement;
|
|
257
|
+
if (time > 32 * Number.EPSILON * Math.max(1, Math.abs(time))) {
|
|
258
|
+
slopeTerms.push({ time, weight: weights[i] * Math.abs(movement), index: i });
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
if (!(slope < 0) || slopeTerms.length === 0)
|
|
263
|
+
return undefined;
|
|
264
|
+
slopeTerms.sort((a, b) => a.time - b.time || a.index - b.index);
|
|
265
|
+
let accumulated = 0;
|
|
266
|
+
const target = -slope;
|
|
267
|
+
let step = slopeTerms[slopeTerms.length - 1].time;
|
|
268
|
+
for (const term of slopeTerms) {
|
|
269
|
+
accumulated += term.weight;
|
|
270
|
+
if (accumulated >= target) {
|
|
271
|
+
step = term.time;
|
|
272
|
+
break;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
const tolerance = 128 * Number.EPSILON * Math.max(1, Math.abs(step));
|
|
276
|
+
const tied = slopeTerms.filter((term) => Math.abs(term.time - step) <= tolerance);
|
|
277
|
+
for (const term of tied) {
|
|
278
|
+
const candidate = basis.filter((_, j) => j !== leaving).concat(term.index);
|
|
279
|
+
if (new Set(candidate).size !== p)
|
|
280
|
+
continue;
|
|
281
|
+
if (qr(candidate.map((i) => x[i])).rank === p) {
|
|
282
|
+
return { slope, step, entering: term.index, direction, leaving };
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
return undefined;
|
|
286
|
+
}
|
|
287
|
+
/** Vertex-to-vertex edge descent for the weighted check-loss objective. */
|
|
288
|
+
function fitBr(x, y, weights, tau, maxit) {
|
|
289
|
+
const n = y.length;
|
|
290
|
+
const p = x[0].length;
|
|
291
|
+
const leastSquares = qrCoef(qr(x), y);
|
|
292
|
+
const residuals = y.map((v, i) => v - dot(x[i], leastSquares));
|
|
293
|
+
const order = Array.from({ length: n }, (_, i) => i).sort((a, b) => Math.abs(residuals[a]) - Math.abs(residuals[b]) || a - b);
|
|
294
|
+
const basis = [];
|
|
295
|
+
for (const i of order) {
|
|
296
|
+
const trial = basis.concat(i);
|
|
297
|
+
if (qr(trial.map((row) => x[row])).rank === trial.length)
|
|
298
|
+
basis.push(i);
|
|
299
|
+
if (basis.length === p)
|
|
300
|
+
break;
|
|
301
|
+
}
|
|
302
|
+
if (basis.length !== p)
|
|
303
|
+
throw new RangeError("could not construct a full-rank initial quantile-regression basis");
|
|
304
|
+
let beta = solveLinear(basis.map((i) => Array.from(x[i])), basis.map((i) => y[i]));
|
|
305
|
+
const seen = new Set();
|
|
306
|
+
for (let iteration = 0; iteration < maxit; iteration++) {
|
|
307
|
+
const key = basis.slice().sort((a, b) => a - b).join(",");
|
|
308
|
+
if (seen.has(key))
|
|
309
|
+
throw new Error("quantile regression vertex walk cycled");
|
|
310
|
+
seen.add(key);
|
|
311
|
+
let best;
|
|
312
|
+
for (let j = 0; j < p; j++) {
|
|
313
|
+
for (const sign of [1, -1]) {
|
|
314
|
+
const edge = directionalEdge(x, y, weights, tau, beta, basis, j, sign);
|
|
315
|
+
if (edge === undefined)
|
|
316
|
+
continue;
|
|
317
|
+
// Bland's deterministic entering/leaving order prevents cycling across
|
|
318
|
+
// zero-length pivots at degenerate vertices.
|
|
319
|
+
if (best === undefined || edge.entering < best.entering ||
|
|
320
|
+
(edge.entering === best.entering && basis[edge.leaving] < basis[best.leaving])) {
|
|
321
|
+
best = edge;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
if (best === undefined) {
|
|
326
|
+
const fitted = x.map((row) => dot(row, beta));
|
|
327
|
+
const residual = y.map((value, i) => value - fitted[i]);
|
|
328
|
+
const zeroRows = residual.map((value, i) => ({
|
|
329
|
+
index: i,
|
|
330
|
+
zero: Math.abs(value) <= 64 * Number.EPSILON * Math.max(1, Math.abs(y[i]), Math.abs(fitted[i])),
|
|
331
|
+
})).filter((item) => item.zero && !basis.includes(item.index)).map((item) => item.index);
|
|
332
|
+
if (zeroRows.length === 0 || residual.every((value, i) => Math.abs(value) <= 64 * Number.EPSILON * Math.max(1, Math.abs(y[i]), Math.abs(fitted[i])))) {
|
|
333
|
+
return { beta, iterations: iteration + 1 };
|
|
334
|
+
}
|
|
335
|
+
// Degenerate pivot: exchange an additional exact-fit observation into the
|
|
336
|
+
// basis without moving beta. This exposes descent edges hidden by tied zeros.
|
|
337
|
+
let swap;
|
|
338
|
+
const leavingOrder = Array.from({ length: p }, (_, j) => j)
|
|
339
|
+
.sort((a, b) => basis[a] - basis[b]);
|
|
340
|
+
// Bland's rule also applies to zero-length exchanges: smallest entering
|
|
341
|
+
// observation first, then smallest leaving basic observation.
|
|
342
|
+
for (const entering of zeroRows) {
|
|
343
|
+
for (const leaving of leavingOrder) {
|
|
344
|
+
const candidateBasis = basis.filter((_, j) => j !== leaving).concat(entering);
|
|
345
|
+
if (new Set(candidateBasis).size !== p)
|
|
346
|
+
continue;
|
|
347
|
+
const candidateKey = candidateBasis.slice().sort((a, b) => a - b).join(",");
|
|
348
|
+
if (seen.has(candidateKey) || qr(candidateBasis.map((i) => x[i])).rank !== p)
|
|
349
|
+
continue;
|
|
350
|
+
const candidateBeta = solveLinear(candidateBasis.map((i) => Array.from(x[i])), candidateBasis.map((i) => y[i]));
|
|
351
|
+
let hasDescent = false;
|
|
352
|
+
for (let j = 0; j < p && !hasDescent; j++)
|
|
353
|
+
for (const sign of [1, -1]) {
|
|
354
|
+
const edge = directionalEdge(x, y, weights, tau, candidateBeta, candidateBasis, j, sign);
|
|
355
|
+
if (edge !== undefined) {
|
|
356
|
+
hasDescent = true;
|
|
357
|
+
break;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
if (hasDescent) {
|
|
361
|
+
swap = { basis: candidateBasis, beta: candidateBeta };
|
|
362
|
+
break;
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
if (swap !== undefined)
|
|
366
|
+
break;
|
|
367
|
+
}
|
|
368
|
+
if (swap === undefined)
|
|
369
|
+
return { beta, iterations: iteration + 1 };
|
|
370
|
+
basis.length = 0;
|
|
371
|
+
for (const index of swap.basis)
|
|
372
|
+
basis.push(index);
|
|
373
|
+
beta = swap.beta;
|
|
374
|
+
continue;
|
|
375
|
+
}
|
|
376
|
+
const nextBasis = basis.filter((_, j) => j !== best.leaving).concat(best.entering);
|
|
377
|
+
const nextBeta = solveLinear(nextBasis.map((i) => Array.from(x[i])), nextBasis.map((i) => y[i]));
|
|
378
|
+
const currentLoss = x.reduce((sum, row, i) => {
|
|
379
|
+
const r = y[i] - dot(row, beta);
|
|
380
|
+
return sum + weights[i] * r * (tau - (r < 0 ? 1 : 0));
|
|
381
|
+
}, 0);
|
|
382
|
+
const nextLoss = x.reduce((sum, row, i) => {
|
|
383
|
+
const r = y[i] - dot(row, nextBeta);
|
|
384
|
+
return sum + weights[i] * r * (tau - (r < 0 ? 1 : 0));
|
|
385
|
+
}, 0);
|
|
386
|
+
const objectiveTolerance = 1e-12 * Math.max(1, Math.abs(currentLoss), Math.abs(nextLoss));
|
|
387
|
+
const objectiveDecreased = nextLoss < currentLoss - objectiveTolerance;
|
|
388
|
+
// A pivot with no numerically resolvable decrease is still necessary at a
|
|
389
|
+
// degenerate vertex. Bland ordering and the visited-basis guard provide
|
|
390
|
+
// deterministic anti-cycling; the objective comparison is diagnostic only.
|
|
391
|
+
void objectiveDecreased;
|
|
392
|
+
basis.length = 0;
|
|
393
|
+
for (const index of nextBasis)
|
|
394
|
+
basis.push(index);
|
|
395
|
+
beta = nextBeta;
|
|
396
|
+
}
|
|
397
|
+
throw new Error("quantile regression vertex walk did not converge within maxit");
|
|
398
|
+
}
|
|
399
|
+
function fitOne(x, y, weights, tau, method, maxit, eps) {
|
|
400
|
+
const n = y.length;
|
|
401
|
+
const p = x[0].length;
|
|
402
|
+
if (n === 0 || p === 0)
|
|
403
|
+
throw new RangeError("the design matrix must have at least one column and one row");
|
|
404
|
+
if (n < p)
|
|
405
|
+
throw new RangeError("singular design matrix");
|
|
406
|
+
if (qr(x).rank < p)
|
|
407
|
+
throw new RangeError("singular design matrix");
|
|
408
|
+
const weightScale = weights.reduce((m, v) => Math.max(m, v), 0);
|
|
409
|
+
const yScale = y.reduce((m, v) => Math.max(m, Math.abs(v)), 0) || 1;
|
|
410
|
+
const columnScale = new Array(p).fill(0);
|
|
411
|
+
for (const row of x)
|
|
412
|
+
for (let j = 0; j < p; j++)
|
|
413
|
+
columnScale[j] = Math.max(columnScale[j], Math.abs(row[j]));
|
|
414
|
+
if (columnScale.some((v) => !(v > 0) || !Number.isFinite(v)))
|
|
415
|
+
throw new RangeError("singular design matrix");
|
|
416
|
+
const normalizedX = x.map((row, i) => row.map((v, j) => (weights[i] / weightScale) * (v / columnScale[j])));
|
|
417
|
+
const normalizedY = y.map((v, i) => (weights[i] / weightScale) * (v / yScale));
|
|
418
|
+
let normalizedBeta;
|
|
419
|
+
let iterations;
|
|
420
|
+
if (p === 1 && x.every((row) => row[0] === x[0][0])) {
|
|
421
|
+
const scale = x[0][0];
|
|
422
|
+
const quantile = scale > 0 ? tau : 1 - tau;
|
|
423
|
+
const ordered = y.map((value, i) => ({ value: value / scale, weight: weights[i] }))
|
|
424
|
+
.sort((a, b) => a.value - b.value);
|
|
425
|
+
const total = ordered.reduce((sum, item) => sum + item.weight, 0);
|
|
426
|
+
let cumulative = 0;
|
|
427
|
+
let estimate = ordered[0].value;
|
|
428
|
+
for (const item of ordered) {
|
|
429
|
+
cumulative += item.weight;
|
|
430
|
+
estimate = item.value;
|
|
431
|
+
if (cumulative >= quantile * total)
|
|
432
|
+
break;
|
|
433
|
+
}
|
|
434
|
+
normalizedBeta = [estimate * columnScale[0] / yScale];
|
|
435
|
+
iterations = ordered.length;
|
|
436
|
+
}
|
|
437
|
+
else if (method === "br") {
|
|
438
|
+
const fit = fitBr(normalizedX, normalizedY, new Array(n).fill(1), tau, maxit);
|
|
439
|
+
normalizedBeta = fit.beta;
|
|
440
|
+
iterations = fit.iterations;
|
|
441
|
+
}
|
|
442
|
+
else {
|
|
443
|
+
const fit = fitFn(normalizedX, normalizedY, tau, maxit, eps);
|
|
444
|
+
normalizedBeta = fit.beta;
|
|
445
|
+
iterations = fit.iterations;
|
|
446
|
+
// Move the central-path estimate to a nearby vertex when its dual certificate
|
|
447
|
+
// verifies the same optimum. This is a bounded greedy basis selection, not enumeration.
|
|
448
|
+
const residual = normalizedY.map((v, i) => v - dot(normalizedX[i], normalizedBeta));
|
|
449
|
+
const ordered = Array.from({ length: n }, (_, i) => i).sort((a, b) => Math.abs(residual[a]) - Math.abs(residual[b]) || a - b);
|
|
450
|
+
const basis = [];
|
|
451
|
+
for (const i of ordered) {
|
|
452
|
+
const trial = basis.concat(i);
|
|
453
|
+
if (qr(trial.map((row) => normalizedX[row])).rank === trial.length)
|
|
454
|
+
basis.push(i);
|
|
455
|
+
if (basis.length === p)
|
|
456
|
+
break;
|
|
457
|
+
}
|
|
458
|
+
if (basis.length === p) {
|
|
459
|
+
try {
|
|
460
|
+
const candidate = solveLinear(basis.map((i) => Array.from(normalizedX[i])), basis.map((i) => normalizedY[i]));
|
|
461
|
+
const oldLoss = normalizedX.reduce((sum, row, i) => {
|
|
462
|
+
const r = normalizedY[i] - dot(row, normalizedBeta);
|
|
463
|
+
return sum + r * (tau - (r < 0 ? 1 : 0));
|
|
464
|
+
}, 0);
|
|
465
|
+
const candidateResidual = normalizedY.map((v, i) => v - dot(normalizedX[i], candidate));
|
|
466
|
+
const newLoss = candidateResidual.reduce((sum, r) => sum + r * (tau - (r < 0 ? 1 : 0)), 0);
|
|
467
|
+
let dualObjective = 0;
|
|
468
|
+
let signCompatible = true;
|
|
469
|
+
const residualScale = candidateResidual.reduce((m, v) => Math.max(m, Math.abs(v)), 1);
|
|
470
|
+
for (let i = 0; i < n; i++) {
|
|
471
|
+
const ai = fit.dual[i];
|
|
472
|
+
dualObjective += normalizedY[i] * ai;
|
|
473
|
+
if (candidateResidual[i] > 1e-8 * residualScale && ai < 1 - 1e-7)
|
|
474
|
+
signCompatible = false;
|
|
475
|
+
if (candidateResidual[i] < -1e-8 * residualScale && ai > 1e-7)
|
|
476
|
+
signCompatible = false;
|
|
477
|
+
}
|
|
478
|
+
const equalityResidual = new Array(p).fill(0);
|
|
479
|
+
for (let i = 0; i < n; i++)
|
|
480
|
+
for (let j = 0; j < p; j++) {
|
|
481
|
+
equalityResidual[j] += normalizedX[i][j] * (fit.dual[i] - (1 - tau));
|
|
482
|
+
}
|
|
483
|
+
const dualEquality = equalityResidual.reduce((m, v) => Math.max(m, Math.abs(v)), 0);
|
|
484
|
+
dualObjective -= (1 - tau) * normalizedY.reduce((sum, value) => sum + value, 0);
|
|
485
|
+
const certificate = signCompatible &&
|
|
486
|
+
dualEquality <= 1e-8 * Math.max(1, normalizedX[0].reduce((maximum, _, j) => Math.max(maximum, Math.abs(normalizedX.reduce((sum, row) => sum + row[j], 0))), 0)) &&
|
|
487
|
+
Math.abs(newLoss - dualObjective) <= 1e-8 * Math.max(1, Math.abs(newLoss), Math.abs(dualObjective));
|
|
488
|
+
if (certificate && newLoss <= oldLoss + 1e-12 * Math.max(1, Math.abs(oldLoss)))
|
|
489
|
+
normalizedBeta = candidate;
|
|
490
|
+
}
|
|
491
|
+
catch {
|
|
492
|
+
// Retain the converged central-path estimate if the nearby basis is numerically singular.
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
const beta = normalizedBeta.map((v, j) => v * yScale / columnScale[j]);
|
|
497
|
+
const fitted = x.map((row) => dot(row, beta));
|
|
498
|
+
const residuals = y.map((v, i) => v - fitted[i]);
|
|
499
|
+
let rho = 0;
|
|
500
|
+
for (let i = 0; i < n; i++)
|
|
501
|
+
rho += weights[i] * residuals[i] * (tau - (residuals[i] < 0 ? 1 : 0));
|
|
502
|
+
return { beta, fitted, residuals, rho, converged: true, iterations };
|
|
503
|
+
}
|
|
504
|
+
/**
|
|
505
|
+
* Fit a linear conditional quantile model. Equivalent to `quantreg::rq()` in R.
|
|
506
|
+
* Uses the formula/model-matrix interface of other regression models.
|
|
507
|
+
*
|
|
508
|
+
* @param formula A formula such as `y ~ x`.
|
|
509
|
+
* @param data A data frame of columns.
|
|
510
|
+
* @param options Quantile, algorithm, and prior weights.
|
|
511
|
+
* @example
|
|
512
|
+
* ```ts
|
|
513
|
+
* rq("y ~ x", { x: [1, 2, 3, 4], y: [2, 1, 4, 3] }, { tau: 0.5 });
|
|
514
|
+
* ```
|
|
515
|
+
* @category Regression
|
|
516
|
+
*/
|
|
517
|
+
export function rq(formula, data, options = {}) {
|
|
518
|
+
checkOptions(options, RQ_KEYS, "rq"); // generated: option-keys.mjs
|
|
519
|
+
const tauValues = typeof options.tau === "number" ? [options.tau] : options.tau === undefined ? [0.5] : Array.from(options.tau);
|
|
520
|
+
if (tauValues.length === 0 || tauValues.some((v) => !(v > 0 && v < 1) || !Number.isFinite(v))) {
|
|
521
|
+
throw new RangeError("tau must contain values strictly between 0 and 1");
|
|
522
|
+
}
|
|
523
|
+
const method = options.method ?? "br";
|
|
524
|
+
if (method !== "br" && method !== "fn")
|
|
525
|
+
throw new RangeError("method must be 'br' or 'fn'");
|
|
526
|
+
const maxit = options.maxit ?? 100;
|
|
527
|
+
const eps = options.eps ?? 1e-12;
|
|
528
|
+
if (!Number.isInteger(maxit) || maxit < 1)
|
|
529
|
+
throw new RangeError("maxit must be a positive integer");
|
|
530
|
+
if (!(eps > 0) || !Number.isFinite(eps))
|
|
531
|
+
throw new RangeError("eps must be positive and finite");
|
|
532
|
+
const d = design(parseFormula(formula), data, {
|
|
533
|
+
...(options.weights === undefined ? {} : { weights: options.weights }),
|
|
534
|
+
...(options.contrasts === undefined ? {} : { contrasts: options.contrasts }),
|
|
535
|
+
...(options.levels === undefined ? {} : { levels: options.levels }),
|
|
536
|
+
});
|
|
537
|
+
if (d.y === undefined)
|
|
538
|
+
throw new TypeError("the formula must have a numeric response");
|
|
539
|
+
const weights = d.frame.weights ?? new Array(d.y.length).fill(1);
|
|
540
|
+
if (weights.some((v) => !Number.isFinite(v) || v < 0))
|
|
541
|
+
throw new RangeError("weights must be non-negative and finite");
|
|
542
|
+
const kept = d.y.map((v, i) => i).filter((i) => weights[i] > 0);
|
|
543
|
+
if (kept.length < d.x[0].length)
|
|
544
|
+
throw new RangeError("singular design matrix");
|
|
545
|
+
const x = kept.map((i) => d.x[i]);
|
|
546
|
+
const y = kept.map((i) => d.y[i]);
|
|
547
|
+
const w = kept.map((i) => weights[i]);
|
|
548
|
+
if (x.some((row) => row.some((v) => !Number.isFinite(v))) || y.some((v) => !Number.isFinite(v))) {
|
|
549
|
+
throw new RangeError("x and y must contain only finite values");
|
|
550
|
+
}
|
|
551
|
+
const fits = tauValues.map((tau) => fitOne(x, y, w, tau, method, maxit, eps));
|
|
552
|
+
const coefficients = {};
|
|
553
|
+
d.colNames.forEach((name, j) => {
|
|
554
|
+
coefficients[name] = tauValues.length === 1 ? fits[0].beta[j] : fits.map((fit) => fit.beta[j]);
|
|
555
|
+
});
|
|
556
|
+
const model = { formula, x, y, weights: w, rows: kept.map((i) => d.frame.rows[i]), columnNames: d.colNames, tau: tauValues, method };
|
|
557
|
+
const warnings = [...d.warnings];
|
|
558
|
+
if (fits.some((fit) => !fit.converged))
|
|
559
|
+
warnings.push("quantile regression did not converge within the iteration limit");
|
|
560
|
+
const fittedValues = tauValues.length === 1 ? fits[0].fitted : fits.map((fit) => fit.fitted);
|
|
561
|
+
const residuals = tauValues.length === 1 ? fits[0].residuals : fits.map((fit) => fit.residuals);
|
|
562
|
+
const rho = tauValues.length === 1 ? fits[0].rho : fits.map((fit) => fit.rho);
|
|
563
|
+
return reported("rq", {
|
|
564
|
+
coefficients, fittedValues, residuals, rho, converged: fits.every((fit) => fit.converged),
|
|
565
|
+
iterations: fits.reduce((m, fit) => Math.max(m, fit.iterations), 0), warnings, model,
|
|
566
|
+
});
|
|
567
|
+
}
|
|
568
|
+
/**
|
|
569
|
+
* Predict conditional quantiles for new observations. Equivalent to `quantreg::predict.rq()` in R.
|
|
570
|
+
*
|
|
571
|
+
* @category Regression
|
|
572
|
+
*/
|
|
573
|
+
export function rqPredict(fit, newdata) {
|
|
574
|
+
const rhs = fit.model.formula.slice(fit.model.formula.indexOf("~") + 1);
|
|
575
|
+
const parsed = parseFormula("~ " + rhs);
|
|
576
|
+
const d = design(parsed, newdata, { anyResponse: true, dropUnusedLevels: true });
|
|
577
|
+
const matrix = d.x;
|
|
578
|
+
const coefs = fit.model.tau.map((_, k) => fit.model.columnNames.map((name) => {
|
|
579
|
+
const v = fit.coefficients[name];
|
|
580
|
+
return Array.isArray(v) ? v[k] : v;
|
|
581
|
+
}));
|
|
582
|
+
const values = coefs.map((beta) => matrix.map((row) => dot(row, beta)));
|
|
583
|
+
return values.length === 1 ? values[0] : values;
|
|
584
|
+
}
|
|
585
|
+
function rqInverse(a) {
|
|
586
|
+
const n = a.length;
|
|
587
|
+
if (n === 0 || a.some((row) => row.length !== n))
|
|
588
|
+
throw new RangeError("singular covariance matrix");
|
|
589
|
+
const scale = a.map((row, i) => Math.sqrt(Math.abs(row[i])));
|
|
590
|
+
if (scale.some((value) => !(value > 0) || !Number.isFinite(value)))
|
|
591
|
+
throw new RangeError("singular covariance matrix");
|
|
592
|
+
const m = a.map((row, i) => [...row.map((value, j) => value / scale[i] / scale[j]),
|
|
593
|
+
...Array.from({ length: n }, (_, j) => +(i === j))]);
|
|
594
|
+
for (let k = 0; k < n; k++) {
|
|
595
|
+
let pivot = k;
|
|
596
|
+
for (let i = k + 1; i < n; i++)
|
|
597
|
+
if (Math.abs(m[i][k]) > Math.abs(m[pivot][k]))
|
|
598
|
+
pivot = i;
|
|
599
|
+
let rowMax = 0;
|
|
600
|
+
for (let j = 0; j < n; j++)
|
|
601
|
+
rowMax = Math.max(rowMax, Math.abs(m[pivot][j]));
|
|
602
|
+
if (!(rowMax > 0) || !(Math.abs(m[pivot][k]) > Number.EPSILON * rowMax))
|
|
603
|
+
throw new RangeError("singular covariance matrix");
|
|
604
|
+
[m[k], m[pivot]] = [m[pivot], m[k]];
|
|
605
|
+
const d = m[k][k];
|
|
606
|
+
for (let j = 0; j < 2 * n; j++)
|
|
607
|
+
m[k][j] /= d;
|
|
608
|
+
for (let i = 0; i < n; i++)
|
|
609
|
+
if (i !== k) {
|
|
610
|
+
const v = m[i][k];
|
|
611
|
+
for (let j = 0; j < 2 * n; j++)
|
|
612
|
+
m[i][j] -= v * m[k][j];
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
return m.map((row, i) => row.slice(n).map((value, j) => value / scale[i] / scale[j]));
|
|
616
|
+
}
|
|
617
|
+
function rqMul(a, b) {
|
|
618
|
+
return a.map((row) => b[0].map((_, j) => row.reduce((sum, v, k) => sum + v * b[k][j], 0)));
|
|
619
|
+
}
|
|
620
|
+
const NID_DENSITY_EPS = 2 ** -26;
|
|
621
|
+
function rqBandwidth(n, tau, level) {
|
|
622
|
+
const z = qnorm(tau);
|
|
623
|
+
const critical = qnorm((1 + level) / 2);
|
|
624
|
+
const phi = Math.exp(-0.5 * z * z) / Math.sqrt(2 * Math.PI);
|
|
625
|
+
return Math.cbrt((1.5 * phi * phi * critical * critical) / (n * (2 * z * z + 1)));
|
|
626
|
+
}
|
|
627
|
+
function rqBread(model, tau, level, warnings) {
|
|
628
|
+
const h = rqBandwidth(model.y.length, tau, level);
|
|
629
|
+
let responseScale = 0;
|
|
630
|
+
for (const value of model.y)
|
|
631
|
+
responseScale = Math.max(responseScale, Math.abs(value));
|
|
632
|
+
const yScale = responseScale > 0 ? responseScale : 1;
|
|
633
|
+
const normalizedY = model.y.map((value) => value / yScale);
|
|
634
|
+
const minus = fitOne(model.x, normalizedY, model.weights, tau - h, model.method, 500, 1e-12).beta;
|
|
635
|
+
const plus = fitOne(model.x, normalizedY, model.weights, tau + h, model.method, 500, 1e-12).beta;
|
|
636
|
+
const p = model.columnNames.length;
|
|
637
|
+
const bread = Array.from({ length: p }, () => new Array(p).fill(0));
|
|
638
|
+
const extremeScale = responseScale > 1e8 || (responseScale > 0 && responseScale < 1e-8);
|
|
639
|
+
const densityTolerance = NID_DENSITY_EPS * (extremeScale ? 1 : 1 / yScale);
|
|
640
|
+
const delta = plus.map((value, j) => value - minus[j]);
|
|
641
|
+
let nonPositive = 0;
|
|
642
|
+
for (let i = 0; i < model.y.length; i++) {
|
|
643
|
+
const row = model.x[i];
|
|
644
|
+
const difference = dot(row, delta);
|
|
645
|
+
const density = difference > densityTolerance ? (2 * h / yScale) / (difference - densityTolerance) : 0;
|
|
646
|
+
if (density === 0)
|
|
647
|
+
nonPositive++;
|
|
648
|
+
for (let j = 0; j < p; j++)
|
|
649
|
+
for (let k = 0; k <= j; k++)
|
|
650
|
+
bread[j][k] += model.weights[i] * density * row[j] * row[k];
|
|
651
|
+
}
|
|
652
|
+
if (nonPositive > 0)
|
|
653
|
+
warnings?.push(`${nonPositive} non-positive fis`);
|
|
654
|
+
for (let j = 0; j < p; j++)
|
|
655
|
+
for (let k = 0; k < j; k++)
|
|
656
|
+
bread[k][j] = bread[j][k];
|
|
657
|
+
return bread;
|
|
658
|
+
}
|
|
659
|
+
function rqMeat(model) {
|
|
660
|
+
const p = model.columnNames.length;
|
|
661
|
+
const meat = Array.from({ length: p }, () => new Array(p).fill(0));
|
|
662
|
+
for (let i = 0; i < model.y.length; i++) {
|
|
663
|
+
const row = model.x[i];
|
|
664
|
+
for (let j = 0; j < p; j++)
|
|
665
|
+
for (let k = 0; k <= j; k++)
|
|
666
|
+
meat[j][k] += model.weights[i] ** 2 * row[j] * row[k];
|
|
667
|
+
}
|
|
668
|
+
for (let j = 0; j < p; j++)
|
|
669
|
+
for (let k = 0; k < j; k++)
|
|
670
|
+
meat[k][j] = meat[j][k];
|
|
671
|
+
return meat;
|
|
672
|
+
}
|
|
673
|
+
function rqNidCovariance(model, tau, level, warnings) {
|
|
674
|
+
const inv = rqInverse(rqBread(model, tau, level, warnings));
|
|
675
|
+
const middle = rqMul(rqMul(inv, rqMeat(model)), inv);
|
|
676
|
+
const scale = tau * (1 - tau);
|
|
677
|
+
return middle.map((row) => row.map((v) => v * scale));
|
|
678
|
+
}
|
|
679
|
+
// Confidence intervals by inversion of the regression rank-score test (Gutenbrunner, Jurečková, Koenker and Portnoy
|
|
680
|
+
// 1993; Koenker 1994). For H0: beta_j = b the restricted problem regresses y - x_j b on the other columns; its dual
|
|
681
|
+
// solution a (the regression rank scores at tau) gives
|
|
682
|
+
// T(b) = sum_i xt_i (a_i - (1 - tau)) / sqrt(tau (1 - tau) sum_i xt_i^2),
|
|
683
|
+
// xt being x_j less its least-squares projection on the other columns. As b moves away from the estimate, the
|
|
684
|
+
// restricted problem is followed by parametric linear programming: an event is a b at which a non-basic residual
|
|
685
|
+
// reaches 0; the residual changes sign, and the basis changes only when that would take the basic dual values out
|
|
686
|
+
// of [0, 1]. T is recorded after each event, and an endpoint is the linear interpolation, between the two events
|
|
687
|
+
// where T first crosses +-qt(1 - alpha / 2, n - p), of the point where it equals the critical value. Matching
|
|
688
|
+
// R's intervals needs exactly this path: the events and the interpolation between them (not the jumps of T) were
|
|
689
|
+
// identified from R's public output (experiments/regression18-rank-path.*).
|
|
690
|
+
const RANK_TOL = 1e-10;
|
|
691
|
+
function rqRankDual(xr, basis, positive, tau) {
|
|
692
|
+
const q = xr[0]?.length ?? 0;
|
|
693
|
+
const rhs = new Array(q).fill(0);
|
|
694
|
+
const inBasis = new Set(basis);
|
|
695
|
+
for (let i = 0; i < xr.length; i++) {
|
|
696
|
+
const row = xr[i];
|
|
697
|
+
const coefficient = (1 - tau) - (!inBasis.has(i) && positive[i] ? 1 : 0);
|
|
698
|
+
for (let k = 0; k < q; k++)
|
|
699
|
+
rhs[k] += coefficient * row[k];
|
|
700
|
+
}
|
|
701
|
+
if (q === 0)
|
|
702
|
+
return [];
|
|
703
|
+
const transposed = Array.from({ length: q }, (_, k) => basis.map((i) => xr[i][k]));
|
|
704
|
+
let a;
|
|
705
|
+
try {
|
|
706
|
+
a = solveLinear(transposed, rhs);
|
|
707
|
+
}
|
|
708
|
+
catch {
|
|
709
|
+
return undefined;
|
|
710
|
+
}
|
|
711
|
+
return a.every((v) => v > -RANK_TOL && v < 1 + RANK_TOL) ? a : undefined;
|
|
712
|
+
}
|
|
713
|
+
function rqRankEndpoint(x, y, j, tau, start, startBasis, direction, critical) {
|
|
714
|
+
const n = y.length;
|
|
715
|
+
const xj = x.map((row) => row[j]);
|
|
716
|
+
const xr = x.map((row) => row.filter((_, k) => k !== j));
|
|
717
|
+
const q = xr[0].length;
|
|
718
|
+
// xt: x_j less its least-squares projection on the other columns
|
|
719
|
+
let xt = xj;
|
|
720
|
+
if (q > 0) {
|
|
721
|
+
const gram = Array.from({ length: q }, (_, a) => Array.from({ length: q }, (_, b) => xr.reduce((s, row) => s + row[a] * row[b], 0)));
|
|
722
|
+
const coef = solveLinear(gram, Array.from({ length: q }, (_, a) => xr.reduce((s, row, i) => s + row[a] * xj[i], 0)));
|
|
723
|
+
xt = xj.map((v, i) => v - dot(xr[i], coef));
|
|
724
|
+
}
|
|
725
|
+
const scale = Math.sqrt(tau * (1 - tau) * xt.reduce((s, v) => s + v * v, 0));
|
|
726
|
+
// residual of row i as c_i - b d_i under a basis
|
|
727
|
+
const lines = (basis) => {
|
|
728
|
+
if (q === 0)
|
|
729
|
+
return { c: [...y], d: [...xj] };
|
|
730
|
+
const xb = basis.map((i) => xr[i]);
|
|
731
|
+
const u = solveLinear(xb.map((r) => [...r]), basis.map((i) => y[i]));
|
|
732
|
+
const v = solveLinear(xb.map((r) => [...r]), basis.map((i) => xj[i]));
|
|
733
|
+
return { c: y.map((yi, i) => yi - dot(xr[i], u)), d: xj.map((xi, i) => xi - dot(xr[i], v)) };
|
|
734
|
+
};
|
|
735
|
+
const statistic = (basis, positive, a) => {
|
|
736
|
+
const inBasis = new Map(basis.map((i, k) => [i, k]));
|
|
737
|
+
let s = 0;
|
|
738
|
+
for (let i = 0; i < n; i++) {
|
|
739
|
+
const k = inBasis.get(i);
|
|
740
|
+
const ai = k === undefined ? (positive[i] ? 1 : 0) : a[k];
|
|
741
|
+
s += xt[i] * (ai - (1 - tau));
|
|
742
|
+
}
|
|
743
|
+
return s / scale;
|
|
744
|
+
};
|
|
745
|
+
// the restricted basis at the estimate: the full basis less one row. Several can be dual feasible there (a
|
|
746
|
+
// degenerate vertex); the one that stays optimal as b moves is the vertex that is best for the objective
|
|
747
|
+
// (y - x_j b)' a just beyond the estimate, that is the largest x_j' a when b decreases and the smallest when it
|
|
748
|
+
// increases
|
|
749
|
+
let basis = [];
|
|
750
|
+
let positive = [];
|
|
751
|
+
let a = [];
|
|
752
|
+
let found = false;
|
|
753
|
+
let best = -Infinity;
|
|
754
|
+
for (const leave of startBasis) {
|
|
755
|
+
const candidate = startBasis.filter((i) => i !== leave).slice(0, q);
|
|
756
|
+
if (candidate.length !== q)
|
|
757
|
+
continue;
|
|
758
|
+
let ln;
|
|
759
|
+
try {
|
|
760
|
+
ln = lines(candidate);
|
|
761
|
+
}
|
|
762
|
+
catch {
|
|
763
|
+
continue;
|
|
764
|
+
}
|
|
765
|
+
const sign = y.map((_, i) => {
|
|
766
|
+
const r = ln.c[i] - start * ln.d[i];
|
|
767
|
+
return Math.abs(r) > RANK_TOL * (1 + Math.abs(y[i])) ? r > 0 : -direction * ln.d[i] > 0;
|
|
768
|
+
});
|
|
769
|
+
const dual = rqRankDual(xr, candidate, sign, tau);
|
|
770
|
+
if (!dual)
|
|
771
|
+
continue;
|
|
772
|
+
const position = new Map(candidate.map((i, k) => [i, k]));
|
|
773
|
+
let value = 0;
|
|
774
|
+
for (let i = 0; i < n; i++) {
|
|
775
|
+
const k = position.get(i);
|
|
776
|
+
value += xj[i] * (k === undefined ? (sign[i] ? 1 : 0) : dual[k]);
|
|
777
|
+
}
|
|
778
|
+
// ties (the same dual vector from several bases) go to the basis whose leaving row has a positive residual
|
|
779
|
+
const score = -direction * value + (sign[leave] ? RANK_TOL / 2 : 0);
|
|
780
|
+
if (!found || score > best) {
|
|
781
|
+
basis = candidate;
|
|
782
|
+
positive = sign;
|
|
783
|
+
a = dual;
|
|
784
|
+
best = score;
|
|
785
|
+
found = true;
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
if (!found)
|
|
789
|
+
throw new RangeError("rank inversion: no feasible restricted basis at the estimate");
|
|
790
|
+
let b = start;
|
|
791
|
+
let t = statistic(basis, positive, a);
|
|
792
|
+
const target = direction < 0 ? critical : -critical;
|
|
793
|
+
for (let iteration = 0; iteration < 50 * n; iteration++) {
|
|
794
|
+
const { c, d } = lines(basis);
|
|
795
|
+
const inBasis = new Set(basis);
|
|
796
|
+
// the next b in this direction at which a non-basic residual c_i - b d_i reaches 0
|
|
797
|
+
let step = Infinity;
|
|
798
|
+
let k = -1;
|
|
799
|
+
for (let i = 0; i < n; i++) {
|
|
800
|
+
if (inBasis.has(i) || d[i] === 0)
|
|
801
|
+
continue;
|
|
802
|
+
const root = c[i] / d[i];
|
|
803
|
+
const s = (root - b) * direction;
|
|
804
|
+
if (s > RANK_TOL * (1 + Math.abs(b)) && s < step) {
|
|
805
|
+
step = s;
|
|
806
|
+
k = i;
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
if (k < 0)
|
|
810
|
+
return direction * Infinity;
|
|
811
|
+
const next = b + direction * step;
|
|
812
|
+
// every non-basic residual that reaches 0 at this b (ties are common) changes sign before T is recorded; each
|
|
813
|
+
// change keeps the basis when the dual stays feasible and is a pivot otherwise
|
|
814
|
+
let nextBasis = basis;
|
|
815
|
+
let nextPositive = positive;
|
|
816
|
+
let dual = a;
|
|
817
|
+
for (let guard = 0; guard <= n; guard++) {
|
|
818
|
+
const ln = lines(nextBasis);
|
|
819
|
+
const current = new Set(nextBasis);
|
|
820
|
+
// of the rows whose residual is 0 here, the one whose computed root c_i / d_i comes first in this direction.
|
|
821
|
+
// With ties (several roots equal in exact arithmetic, as with integer data) the dual can be degenerate and R's
|
|
822
|
+
// path can pass another optimal vertex, so its endpoints there need not be the ones here (a known difference)
|
|
823
|
+
let flip = -1;
|
|
824
|
+
let first = Infinity;
|
|
825
|
+
for (let i = 0; i < n; i++) {
|
|
826
|
+
if (current.has(i))
|
|
827
|
+
continue;
|
|
828
|
+
const r = ln.c[i] - next * ln.d[i];
|
|
829
|
+
if (Math.abs(r) > RANK_TOL * (1 + Math.abs(y[i]) + Math.abs(next * xj[i])))
|
|
830
|
+
continue;
|
|
831
|
+
const beyond = -direction * ln.d[i] > 0;
|
|
832
|
+
if (ln.d[i] === 0 || beyond === nextPositive[i])
|
|
833
|
+
continue;
|
|
834
|
+
const ahead = ((ln.c[i] / ln.d[i]) - b) * direction;
|
|
835
|
+
if (ahead < first) {
|
|
836
|
+
first = ahead;
|
|
837
|
+
flip = i;
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
if (flip < 0)
|
|
841
|
+
break;
|
|
842
|
+
const flipped = nextPositive.map((v, i) => (i === flip ? !v : v));
|
|
843
|
+
const kept = rqRankDual(xr, nextBasis, flipped, tau);
|
|
844
|
+
if (kept) {
|
|
845
|
+
nextPositive = flipped;
|
|
846
|
+
dual = kept;
|
|
847
|
+
continue;
|
|
848
|
+
}
|
|
849
|
+
// pivot: the row enters, and the leaving row is the one that keeps the dual feasible
|
|
850
|
+
let pivoted = false;
|
|
851
|
+
for (const leave of nextBasis) {
|
|
852
|
+
const candidate = nextBasis.map((i) => (i === leave ? flip : i));
|
|
853
|
+
let lc;
|
|
854
|
+
try {
|
|
855
|
+
lc = lines(candidate);
|
|
856
|
+
}
|
|
857
|
+
catch {
|
|
858
|
+
continue;
|
|
859
|
+
}
|
|
860
|
+
const sign = flipped.map((v, i) => (i === leave ? -direction * lc.d[i] > 0 : v));
|
|
861
|
+
const trial = rqRankDual(xr, candidate, sign, tau);
|
|
862
|
+
if (trial) {
|
|
863
|
+
nextBasis = candidate;
|
|
864
|
+
nextPositive = sign;
|
|
865
|
+
dual = trial;
|
|
866
|
+
pivoted = true;
|
|
867
|
+
break;
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
if (!pivoted)
|
|
871
|
+
throw new RangeError("rank inversion: no feasible pivot");
|
|
872
|
+
}
|
|
873
|
+
if (!dual)
|
|
874
|
+
throw new RangeError("rank inversion: no feasible pivot");
|
|
875
|
+
const nextT = statistic(nextBasis, nextPositive, dual);
|
|
876
|
+
if (direction < 0 ? nextT >= target : nextT <= target) {
|
|
877
|
+
return b + ((next - b) * (target - t)) / (nextT - t);
|
|
878
|
+
}
|
|
879
|
+
b = next;
|
|
880
|
+
t = nextT;
|
|
881
|
+
basis = nextBasis;
|
|
882
|
+
positive = nextPositive;
|
|
883
|
+
a = dual;
|
|
884
|
+
}
|
|
885
|
+
throw new RangeError("rank inversion did not converge");
|
|
886
|
+
}
|
|
887
|
+
function rqRankIntervals(model, beta, tau, level) {
|
|
888
|
+
const w = model.weights;
|
|
889
|
+
const x = model.x.map((row, i) => row.map((v) => v * w[i]));
|
|
890
|
+
const y = model.y.map((v, i) => v * w[i]);
|
|
891
|
+
const p = beta.length;
|
|
892
|
+
const residuals = y.map((v, i) => v - dot(x[i], beta));
|
|
893
|
+
const order = residuals.map((r, i) => [Math.abs(r), i]).sort((u, v) => u[0] - v[0]).map(([, i]) => i);
|
|
894
|
+
const startBasis = order.slice(0, p);
|
|
895
|
+
const critical = qt((1 + level) / 2, y.length - p);
|
|
896
|
+
return beta.map((bj, j) => [
|
|
897
|
+
rqRankEndpoint(x, y, j, tau, bj, startBasis, -1, critical),
|
|
898
|
+
rqRankEndpoint(x, y, j, tau, bj, startBasis, 1, critical),
|
|
899
|
+
]);
|
|
900
|
+
}
|
|
901
|
+
/** Coefficient summary with Hall–Sheather bandwidth and the nid sandwich covariance. Equivalent to R's `summary.rq()`.
|
|
902
|
+
*
|
|
903
|
+
* @category Regression
|
|
904
|
+
*/
|
|
905
|
+
export function rqSummary(fit, options = {}) {
|
|
906
|
+
checkOptions(options, RQ_SUMMARY_KEYS, "rqSummary"); // generated: option-keys.mjs
|
|
907
|
+
const extendedOptions = options;
|
|
908
|
+
if (options.se === "rank" && extendedOptions.iid === false)
|
|
909
|
+
throw new RangeError('se = "rank", iid = false is not supported yet; omit iid or use se = "nid"');
|
|
910
|
+
for (const key of Object.keys(options))
|
|
911
|
+
if (!["se", "covariance", "level"].includes(key))
|
|
912
|
+
throw new TypeError("unused argument (" + key + ")");
|
|
913
|
+
const model = fit.model;
|
|
914
|
+
const requestedSe = options.se;
|
|
915
|
+
if (requestedSe !== undefined && requestedSe !== "nid" && requestedSe !== "rank")
|
|
916
|
+
throw new RangeError(`se = "${requestedSe}" is not supported yet; use "rank" or "nid"`);
|
|
917
|
+
const se = requestedSe ?? (model.y.length <= 1000 ? "rank" : "nid");
|
|
918
|
+
// R's default for the rank intervals is alpha = 0.1; the nid bandwidth uses 0.95
|
|
919
|
+
const level = options.level ?? (se === "rank" ? 0.9 : 0.95);
|
|
920
|
+
if (!(level > 0 && level < 1))
|
|
921
|
+
throw new RangeError("level must be between 0 and 1");
|
|
922
|
+
const warnings = [...fit.warnings];
|
|
923
|
+
if (se === "rank") {
|
|
924
|
+
const coefficients = [];
|
|
925
|
+
for (let k = 0; k < model.tau.length; k++) {
|
|
926
|
+
const beta = model.columnNames.map((term) => {
|
|
927
|
+
const raw = fit.coefficients[term];
|
|
928
|
+
return Array.isArray(raw) ? raw[k] : raw;
|
|
929
|
+
});
|
|
930
|
+
const intervals = rqRankIntervals(model, beta, model.tau[k], level);
|
|
931
|
+
model.columnNames.forEach((term, j) => {
|
|
932
|
+
const [lower, upper] = intervals[j];
|
|
933
|
+
coefficients.push({ tau: model.tau[k], term, estimate: beta[j], stdError: NaN, statistic: NaN, pValue: NaN, lower, upper });
|
|
934
|
+
});
|
|
935
|
+
}
|
|
936
|
+
return { coefficients, se, warnings };
|
|
937
|
+
}
|
|
938
|
+
const covariances = model.tau.map((tau) => rqNidCovariance(model, tau, level, warnings));
|
|
939
|
+
const coefficients = [];
|
|
940
|
+
for (let k = 0; k < model.tau.length; k++)
|
|
941
|
+
for (let j = 0; j < model.columnNames.length; j++) {
|
|
942
|
+
const term = model.columnNames[j];
|
|
943
|
+
const raw = fit.coefficients[term];
|
|
944
|
+
const estimate = Array.isArray(raw) ? raw[k] : raw;
|
|
945
|
+
const stdError = Math.sqrt(covariances[k][j][j]);
|
|
946
|
+
const statistic = estimate / stdError;
|
|
947
|
+
const pValue = 2 * pt(-Math.abs(statistic), model.y.length - model.columnNames.length);
|
|
948
|
+
coefficients.push({ tau: model.tau[k], term, estimate, stdError, statistic, pValue });
|
|
949
|
+
}
|
|
950
|
+
return { coefficients, ...(options.covariance ? { covariance: covariances } : {}), se, warnings };
|
|
951
|
+
}
|
|
952
|
+
/** Confidence intervals for conditional quantile predictions using nid or direct quantile refits. Equivalent to R's `predict.rq()`.
|
|
953
|
+
*
|
|
954
|
+
* @category Regression
|
|
955
|
+
*/
|
|
956
|
+
export function rqPredictInterval(fit, newdata, options = {}) {
|
|
957
|
+
checkOptions(options, RQ_PREDICT_INTERVAL_KEYS, "rqPredictInterval"); // generated: option-keys.mjs
|
|
958
|
+
for (const key of Object.keys(options))
|
|
959
|
+
if (!["interval", "type", "level"].includes(key))
|
|
960
|
+
throw new TypeError("unused argument (" + key + ")");
|
|
961
|
+
const interval = options.interval ?? "none";
|
|
962
|
+
const type = options.type ?? "none";
|
|
963
|
+
const level = options.level ?? 0.95;
|
|
964
|
+
if (!(level > 0 && level < 1))
|
|
965
|
+
throw new RangeError("level must be between 0 and 1");
|
|
966
|
+
const predicted = rqPredict(fit, newdata);
|
|
967
|
+
if (interval === "none")
|
|
968
|
+
return { fit: predicted, level, type };
|
|
969
|
+
if (interval !== "confidence")
|
|
970
|
+
throw new RangeError("interval must be 'none' or 'confidence'");
|
|
971
|
+
if (type === "percentile")
|
|
972
|
+
throw new RangeError("percentile prediction intervals require bootstrap inference");
|
|
973
|
+
const model = fit.model;
|
|
974
|
+
if (model.tau.length !== 1)
|
|
975
|
+
throw new RangeError("confidence intervals currently require a single tau");
|
|
976
|
+
const rhs = model.formula.slice(model.formula.indexOf("~") + 1);
|
|
977
|
+
const matrix = design(parseFormula("~ " + rhs), newdata, { anyResponse: true, dropUnusedLevels: true }).x;
|
|
978
|
+
const tau = model.tau[0];
|
|
979
|
+
let lower;
|
|
980
|
+
let upper;
|
|
981
|
+
if (type === "direct") {
|
|
982
|
+
const h = rqBandwidth(model.y.length, tau, level);
|
|
983
|
+
if (!(tau - h > 0 && tau + h < 1))
|
|
984
|
+
throw new RangeError("direct interval bandwidth leaves the unit interval");
|
|
985
|
+
const lo = fitOne(model.x, model.y, model.weights, tau - h, model.method, 500, 1e-12).beta;
|
|
986
|
+
const hi = fitOne(model.x, model.y, model.weights, tau + h, model.method, 500, 1e-12).beta;
|
|
987
|
+
lower = matrix.map((row) => dot(row, lo));
|
|
988
|
+
upper = matrix.map((row) => dot(row, hi));
|
|
989
|
+
}
|
|
990
|
+
else if (type === "none") {
|
|
991
|
+
const cov = rqNidCovariance(model, tau, level);
|
|
992
|
+
const beta = model.columnNames.map((name) => fit.coefficients[name]);
|
|
993
|
+
const critical = qt((1 + level) / 2, model.y.length - model.columnNames.length);
|
|
994
|
+
lower = [];
|
|
995
|
+
upper = [];
|
|
996
|
+
for (const row of matrix) {
|
|
997
|
+
const cv = cov.map((r) => dot(r, row));
|
|
998
|
+
const variance = dot(row, cv);
|
|
999
|
+
const center = dot(row, beta);
|
|
1000
|
+
const half = critical * Math.sqrt(Math.max(0, variance));
|
|
1001
|
+
lower.push(center - half);
|
|
1002
|
+
upper.push(center + half);
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
else
|
|
1006
|
+
throw new RangeError("type must be 'none', 'direct' or 'percentile'");
|
|
1007
|
+
return { fit: predicted, lower, upper, level, type };
|
|
1008
|
+
}
|
|
1009
|
+
export function rqAnova(fit, reducedOrJoint) {
|
|
1010
|
+
if (typeof reducedOrJoint === "object" && reducedOrJoint !== null) {
|
|
1011
|
+
const model = fit.model;
|
|
1012
|
+
const smallModel = reducedOrJoint.model;
|
|
1013
|
+
if (model.tau.length !== 1 || smallModel.tau.length !== 1 || model.tau[0] !== smallModel.tau[0]) {
|
|
1014
|
+
throw new RangeError("nested Wald comparison requires two fits at the same single tau");
|
|
1015
|
+
}
|
|
1016
|
+
if (model.y.length !== smallModel.y.length || model.weights.some((w, i) => w !== smallModel.weights[i])) {
|
|
1017
|
+
throw new RangeError("nested Wald comparison requires the same observations and weights");
|
|
1018
|
+
}
|
|
1019
|
+
const omitted = model.columnNames.map((name, i) => ({ name, i })).filter(({ name }) => !smallModel.columnNames.includes(name));
|
|
1020
|
+
if (omitted.length === 0 || smallModel.columnNames.some((name) => !model.columnNames.includes(name))) {
|
|
1021
|
+
throw new RangeError("the second model must be a strict nested submodel of the first");
|
|
1022
|
+
}
|
|
1023
|
+
const covariance = rqNidCovariance(model, model.tau[0], 0.95);
|
|
1024
|
+
const indices = omitted.map((v) => v.i);
|
|
1025
|
+
const small = indices.map((i) => indices.map((j) => covariance[i][j]));
|
|
1026
|
+
const inv = rqInverse(small);
|
|
1027
|
+
const difference = omitted.map(({ name }) => fit.coefficients[name]);
|
|
1028
|
+
const weighted = inv.map((row) => row.reduce((sum, value, i) => sum + value * difference[i], 0));
|
|
1029
|
+
const statistic = difference.reduce((sum, value, i) => sum + value * weighted[i], 0);
|
|
1030
|
+
const df = omitted.length;
|
|
1031
|
+
const dfResidual = model.y.length - model.columnNames.length;
|
|
1032
|
+
const fStatistic = statistic / df;
|
|
1033
|
+
return { statistic: fStatistic, df, dfResidual, pValue: pf(fStatistic, df, dfResidual, { lowerTail: false }), method: "Wald" };
|
|
1034
|
+
}
|
|
1035
|
+
const model = fit.model;
|
|
1036
|
+
const tested = Array.from({ length: model.columnNames.length - 1 }, (_, j) => j + 1);
|
|
1037
|
+
if (reducedOrJoint === false)
|
|
1038
|
+
return tested.map((j) => rqMultiTauWald(fit, [j]));
|
|
1039
|
+
return rqMultiTauWald(fit, tested);
|
|
1040
|
+
}
|
|
1041
|
+
function rqMultiTauWald(fit, tested) {
|
|
1042
|
+
const model = fit.model;
|
|
1043
|
+
const p = model.columnNames.length;
|
|
1044
|
+
const m = model.tau.length;
|
|
1045
|
+
if (m < 2)
|
|
1046
|
+
throw new RangeError("Wald anova requires a multiple-tau fit");
|
|
1047
|
+
if (tested.length === 0)
|
|
1048
|
+
throw new RangeError("Wald anova has no slope restrictions");
|
|
1049
|
+
const restrictions = [];
|
|
1050
|
+
const difference = [];
|
|
1051
|
+
for (const j of tested) {
|
|
1052
|
+
const raw = fit.coefficients[model.columnNames[j]];
|
|
1053
|
+
if (!Array.isArray(raw))
|
|
1054
|
+
throw new RangeError("multiple-tau coefficients are required");
|
|
1055
|
+
for (let k = 1; k < m; k++) {
|
|
1056
|
+
const row = new Array(p * m).fill(0);
|
|
1057
|
+
row[k * p + j] = 1;
|
|
1058
|
+
row[j] = -1;
|
|
1059
|
+
restrictions.push(row);
|
|
1060
|
+
difference.push(raw[k] - raw[0]);
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
const q = restrictions.length;
|
|
1064
|
+
const bread = model.tau.map((tau) => rqInverse(rqBread(model, tau, 0.95)));
|
|
1065
|
+
const meat = rqMeat(model);
|
|
1066
|
+
const covariance = Array.from({ length: p * m }, () => new Array(p * m).fill(0));
|
|
1067
|
+
for (let a = 0; a < m; a++)
|
|
1068
|
+
for (let b = 0; b < m; b++) {
|
|
1069
|
+
const block = rqMul(rqMul(bread[a], meat), bread[b]);
|
|
1070
|
+
const scale = Math.min(model.tau[a], model.tau[b]) - model.tau[a] * model.tau[b];
|
|
1071
|
+
for (let j = 0; j < p; j++)
|
|
1072
|
+
for (let k = 0; k < p; k++)
|
|
1073
|
+
covariance[a * p + j][b * p + k] = block[j][k] * scale;
|
|
1074
|
+
}
|
|
1075
|
+
const small = restrictions.map((r) => restrictions.map((c) => {
|
|
1076
|
+
let value = 0;
|
|
1077
|
+
for (let i = 0; i < r.length; i++)
|
|
1078
|
+
for (let j = 0; j < c.length; j++)
|
|
1079
|
+
value += r[i] * covariance[i][j] * c[j];
|
|
1080
|
+
return value;
|
|
1081
|
+
}));
|
|
1082
|
+
const inv = rqInverse(small);
|
|
1083
|
+
const weighted = inv.map((row) => row.reduce((sum, value, i) => sum + value * difference[i], 0));
|
|
1084
|
+
const statistic = difference.reduce((sum, value, i) => sum + value * weighted[i], 0);
|
|
1085
|
+
// R: n m - (the number of restrictions); 148 for n = 50, three taus and one slope, 176 for n = 60 and two slopes
|
|
1086
|
+
const dfResidual = model.y.length * m - q;
|
|
1087
|
+
const fStatistic = statistic / q;
|
|
1088
|
+
return { statistic: fStatistic, df: q, dfResidual, pValue: pf(fStatistic, q, dfResidual, { lowerTail: false }), method: "Wald" };
|
|
1089
|
+
}
|