@numero-uno-jpn/rstats 1.6.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 +15 -0
- package/README.ja.md +11 -9
- package/README.md +12 -9
- package/dist/chunks/chunk-56AMJQ27.js +2 -0
- package/dist/chunks/{chunk-O5CMNUJL.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-2TVHT4PF.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-ZL7EAPO5.js → chunk-CUT3IHMY.js} +1 -1
- package/dist/chunks/{chunk-FLITCXLY.js → chunk-CZUOG2U5.js} +2 -2
- package/dist/chunks/chunk-FQRNZEH2.js +2 -0
- package/dist/chunks/{chunk-BMEO5X5F.js → chunk-HORF36FD.js} +2 -2
- package/dist/chunks/{chunk-OZLDZOOA.js → chunk-HSJ4OT3H.js} +1 -1
- package/dist/chunks/chunk-J7ZVV4DN.js +2 -0
- package/dist/chunks/{chunk-RSTU6CX7.js → chunk-JXEXOD7K.js} +2 -2
- package/dist/chunks/chunk-KSH43GX4.js +2 -0
- package/dist/chunks/chunk-LMRCFKVK.js +2 -0
- package/dist/chunks/{chunk-2I7Z7L5J.js → chunk-MOJ2KIQE.js} +2 -2
- package/dist/chunks/{chunk-F7G74UNI.js → chunk-PCTRVBEJ.js} +2 -2
- package/dist/chunks/chunk-PLQQ4VFN.js +2 -0
- package/dist/chunks/{chunk-ABSUQPOG.js → chunk-QWDK3ZC2.js} +2 -2
- package/dist/chunks/chunk-R5BMFVIH.js +2 -0
- package/dist/chunks/chunk-R7F7ELS7.js +3 -0
- package/dist/chunks/{chunk-3PCHPKBD.js → chunk-RIP2RKAW.js} +2 -2
- package/dist/chunks/chunk-RX6MZO2Y.js +2 -0
- package/dist/chunks/{chunk-Z2XN4NN7.js → chunk-SDT3YHAG.js} +2 -2
- package/dist/chunks/{chunk-WAMHZ47G.js → chunk-THSV22QF.js} +2 -2
- package/dist/chunks/{chunk-7ZNFRZO4.js → chunk-TY3IFCLI.js} +2 -2
- package/dist/chunks/{chunk-SFZF44G6.js → chunk-V2Y2W7LE.js} +2 -2
- package/dist/chunks/{chunk-AHFMBHZW.js → chunk-VALULDEX.js} +1 -1
- package/dist/chunks/chunk-VQOU7U7R.js +2 -0
- package/dist/chunks/{chunk-KAAUNR3G.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/regression.d.ts +3 -0
- package/dist/entries/regression.js +6 -0
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +2 -2
- 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 +5 -1
- package/package.json +6 -1
- package/dist/chunks/chunk-55XSRONZ.js +0 -3
- package/dist/chunks/chunk-5AITXV3T.js +0 -2
- package/dist/chunks/chunk-BJTGQ52J.js +0 -2
- package/dist/chunks/chunk-KND2BFD5.js +0 -2
- package/dist/chunks/chunk-N2PNW4HR.js +0 -2
- package/dist/chunks/chunk-NVIJXWS6.js +0 -2
- package/dist/chunks/chunk-TPBVVP32.js +0 -2
- package/dist/chunks/chunk-XNWSQVXS.js +0 -2
|
@@ -0,0 +1,1028 @@
|
|
|
1
|
+
// Ordinal regression with cumulative links.
|
|
2
|
+
// Written for rStats.js (no ported code) from McCullagh (1980), Agresti (2002),
|
|
3
|
+
// oracle/polr-behaviour.md, and the public model-matrix and optimisation APIs.
|
|
4
|
+
import { pnorm, qnorm } from "../distributions/normal.js";
|
|
5
|
+
import { qlogis } from "../distributions/logistic.js";
|
|
6
|
+
import { qcauchy } from "../distributions/cauchy.js";
|
|
7
|
+
import { pchisq } from "../distributions/chisq.js";
|
|
8
|
+
import { chol, chol2inv } from "../linalg/chol.js";
|
|
9
|
+
import { optim } from "../optim/optim.js";
|
|
10
|
+
import { reported } from "../internal/warnings.js";
|
|
11
|
+
import { parseFormula } from "./formula.js";
|
|
12
|
+
import { design } from "./modelMatrix.js";
|
|
13
|
+
import { dataRowCount } from "./inputRows.js";
|
|
14
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
15
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
16
|
+
const POLR_KEYS = ["method", "weights", "offset", "start", "contrasts", "levels", "maxit", "reltol"];
|
|
17
|
+
const POLR_PREDICT_KEYS = ["newdata", "rowNames", "type"];
|
|
18
|
+
const POLR_CONFINT_KEYS = ["method", "level", "parm"];
|
|
19
|
+
const softplus = (x) => x > 0 ? x + Math.log1p(Math.exp(-x)) : Math.log1p(Math.exp(x));
|
|
20
|
+
function log1mexp(x) {
|
|
21
|
+
if (x > 0)
|
|
22
|
+
return NaN;
|
|
23
|
+
if (x === 0)
|
|
24
|
+
return -Infinity;
|
|
25
|
+
return x < -Math.LN2 ? Math.log1p(-Math.exp(x)) : Math.log(-Math.expm1(x));
|
|
26
|
+
}
|
|
27
|
+
function logCdf(z, method, upper = false) {
|
|
28
|
+
if (method === "logistic")
|
|
29
|
+
return upper ? -softplus(z) : -softplus(-z);
|
|
30
|
+
if (method === "probit")
|
|
31
|
+
return pnorm(z, { lowerTail: !upper, logP: true });
|
|
32
|
+
if (method === "cauchit") {
|
|
33
|
+
// F(t) = 1/2 + atan(t)/pi. Evaluate the smaller tail directly.
|
|
34
|
+
const t = upper ? -z : z;
|
|
35
|
+
if (t === 0)
|
|
36
|
+
return -Math.LN2;
|
|
37
|
+
if (t > 0) {
|
|
38
|
+
const reciprocal = 1 / t;
|
|
39
|
+
const smallTail = reciprocal === 0 ? 0 : Math.atan(reciprocal) / Math.PI;
|
|
40
|
+
return Math.log1p(-smallTail);
|
|
41
|
+
}
|
|
42
|
+
const reciprocal = -1 / t;
|
|
43
|
+
if (reciprocal === 0)
|
|
44
|
+
return -Infinity;
|
|
45
|
+
return Math.log(Math.atan(reciprocal)) - Math.log(Math.PI);
|
|
46
|
+
}
|
|
47
|
+
if (method === "cloglog")
|
|
48
|
+
return upper ? -Math.exp(z) : log1mexp(-Math.exp(z));
|
|
49
|
+
return upper ? log1mexp(-Math.exp(-z)) : -Math.exp(-z);
|
|
50
|
+
}
|
|
51
|
+
function logDifference(a, b) {
|
|
52
|
+
if (b === -Infinity)
|
|
53
|
+
return a;
|
|
54
|
+
if (!(a > b))
|
|
55
|
+
return -Infinity;
|
|
56
|
+
return a + log1mexp(b - a);
|
|
57
|
+
}
|
|
58
|
+
function categoryLogProbability(z, cutpoints, category, method) {
|
|
59
|
+
const upper = cutpoints.map((c) => logCdf(c - z, method));
|
|
60
|
+
if (category === 0)
|
|
61
|
+
return upper[0];
|
|
62
|
+
if (category === cutpoints.length)
|
|
63
|
+
return logCdf(cutpoints[cutpoints.length - 1] - z, method, true);
|
|
64
|
+
return logDifference(upper[category], upper[category - 1]);
|
|
65
|
+
}
|
|
66
|
+
function inverseCdf(p, method) {
|
|
67
|
+
if (method === "logistic")
|
|
68
|
+
return qlogis(p);
|
|
69
|
+
if (method === "probit")
|
|
70
|
+
return qnorm(p);
|
|
71
|
+
if (method === "cauchit")
|
|
72
|
+
return qcauchy(p);
|
|
73
|
+
if (method === "cloglog")
|
|
74
|
+
return Math.log(-Math.log1p(-p));
|
|
75
|
+
return -Math.log(-Math.log(p));
|
|
76
|
+
}
|
|
77
|
+
function cutpointsFrom(theta, p, k) {
|
|
78
|
+
const out = new Array(k - 1);
|
|
79
|
+
out[0] = theta[p];
|
|
80
|
+
for (let j = 1; j < k - 1; j++)
|
|
81
|
+
out[j] = out[j - 1] + Math.exp(theta[p + j]);
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
function rawStart(values, p, k) {
|
|
85
|
+
if (values.length !== p + k - 1)
|
|
86
|
+
throw new RangeError(`length of 'start' must be ${p + k - 1}`);
|
|
87
|
+
const out = values.slice(0, p);
|
|
88
|
+
out.push(values[p]);
|
|
89
|
+
for (let j = 1; j < k - 1; j++) {
|
|
90
|
+
const gap = values[p + j] - values[p + j - 1];
|
|
91
|
+
if (!(gap > 0))
|
|
92
|
+
throw new RangeError("'start' cut-points must be strictly increasing");
|
|
93
|
+
out.push(Math.log(gap));
|
|
94
|
+
}
|
|
95
|
+
return out;
|
|
96
|
+
}
|
|
97
|
+
function initialValues(y, weights, levels, method) {
|
|
98
|
+
const counts = new Array(levels).fill(0);
|
|
99
|
+
for (let i = 0; i < y.length; i++) {
|
|
100
|
+
const j = y[i];
|
|
101
|
+
counts[j] = (counts[j] ?? 0) + weights[i];
|
|
102
|
+
}
|
|
103
|
+
const total = counts.reduce((a, b) => a + b, 0);
|
|
104
|
+
const cuts = [];
|
|
105
|
+
let cumulative = 0;
|
|
106
|
+
for (let j = 0; j < levels - 1; j++) {
|
|
107
|
+
cumulative += counts[j];
|
|
108
|
+
cuts.push(inverseCdf(cumulative / total, method));
|
|
109
|
+
}
|
|
110
|
+
const transformed = [cuts[0]];
|
|
111
|
+
for (let j = 1; j < cuts.length; j++)
|
|
112
|
+
transformed.push(Math.log(cuts[j] - cuts[j - 1]));
|
|
113
|
+
return transformed;
|
|
114
|
+
}
|
|
115
|
+
function linkDensity(t, method) {
|
|
116
|
+
if (!Number.isFinite(t))
|
|
117
|
+
return 0;
|
|
118
|
+
if (method === "logistic") {
|
|
119
|
+
const logF = -softplus(-t);
|
|
120
|
+
const logS = -softplus(t);
|
|
121
|
+
return Math.exp(logF + logS);
|
|
122
|
+
}
|
|
123
|
+
if (method === "probit")
|
|
124
|
+
return Math.exp(-0.5 * t * t - 0.5 * Math.log(2 * Math.PI));
|
|
125
|
+
if (method === "cauchit")
|
|
126
|
+
return 1 / (Math.PI * (1 + t * t));
|
|
127
|
+
if (method === "cloglog") {
|
|
128
|
+
const et = Math.exp(t);
|
|
129
|
+
return et === 0 || !Number.isFinite(et) ? 0 : Math.exp(t - et);
|
|
130
|
+
}
|
|
131
|
+
const emt = Math.exp(-t);
|
|
132
|
+
return emt === 0 || !Number.isFinite(emt) ? 0 : Math.exp(-t - emt);
|
|
133
|
+
}
|
|
134
|
+
function linkDensityDerivative(t, method) {
|
|
135
|
+
const f = linkDensity(t, method);
|
|
136
|
+
if (f === 0)
|
|
137
|
+
return 0;
|
|
138
|
+
if (method === "logistic")
|
|
139
|
+
return f * (1 - 2 / (1 + Math.exp(-t)));
|
|
140
|
+
if (method === "probit")
|
|
141
|
+
return -t * f;
|
|
142
|
+
if (method === "cauchit")
|
|
143
|
+
return -2 * t * f / (1 + t * t);
|
|
144
|
+
if (method === "cloglog")
|
|
145
|
+
return f * (1 - Math.exp(t));
|
|
146
|
+
return f * (Math.exp(-t) - 1);
|
|
147
|
+
}
|
|
148
|
+
/** Negative log likelihood and its exact first and second derivatives in the unconstrained coordinates. */
|
|
149
|
+
function polrDerivatives(x, y, weights, offset, levels, method, theta) {
|
|
150
|
+
const p = x[0]?.length ?? 0;
|
|
151
|
+
const n = p + levels - 1;
|
|
152
|
+
const beta = theta.slice(0, p);
|
|
153
|
+
const cuts = cutpointsFrom(theta, p, levels);
|
|
154
|
+
const gradientNatural = new Array(n).fill(0);
|
|
155
|
+
const hessianNatural = Array.from({ length: n }, () => new Array(n).fill(0));
|
|
156
|
+
let value = 0;
|
|
157
|
+
for (let i = 0; i < y.length; i++) {
|
|
158
|
+
const w = weights[i];
|
|
159
|
+
if (w === 0)
|
|
160
|
+
continue;
|
|
161
|
+
let eta = offset[i];
|
|
162
|
+
for (let r = 0; r < p; r++)
|
|
163
|
+
eta += x[i][r] * beta[r];
|
|
164
|
+
const category = y[i];
|
|
165
|
+
const lowerT = category === 0 ? -Infinity : cuts[category - 1] - eta;
|
|
166
|
+
const upperT = category === levels - 1 ? Infinity : cuts[category] - eta;
|
|
167
|
+
const logP = categoryLogProbability(eta, cuts, category, method);
|
|
168
|
+
const probability = Math.exp(logP);
|
|
169
|
+
if (!(probability > 0) || !Number.isFinite(probability)) {
|
|
170
|
+
return { value: Number.MAX_VALUE, gradient: new Array(n).fill(0), hessian: hessianNatural };
|
|
171
|
+
}
|
|
172
|
+
const fl = linkDensity(lowerT, method);
|
|
173
|
+
const fu = linkDensity(upperT, method);
|
|
174
|
+
const fpl = linkDensityDerivative(lowerT, method);
|
|
175
|
+
const fpu = linkDensityDerivative(upperT, method);
|
|
176
|
+
// For P = F(u) - F(l), with u/l = cut-point - eta:
|
|
177
|
+
// P_eta = f(l) - f(u), P_eta,eta = f'(u) - f'(l).
|
|
178
|
+
const pEta = fl - fu;
|
|
179
|
+
const pEtaEta = fpu - fpl;
|
|
180
|
+
const pGradient = new Array(n).fill(0);
|
|
181
|
+
const upperIndex = category < levels - 1 ? p + category : -1;
|
|
182
|
+
const lowerIndex = category > 0 ? p + category - 1 : -1;
|
|
183
|
+
const active = Array.from({ length: p }, (_, j) => j);
|
|
184
|
+
if (upperIndex >= 0)
|
|
185
|
+
active.push(upperIndex);
|
|
186
|
+
if (lowerIndex >= 0)
|
|
187
|
+
active.push(lowerIndex);
|
|
188
|
+
for (let r = 0; r < p; r++)
|
|
189
|
+
pGradient[r] = pEta * x[i][r];
|
|
190
|
+
if (upperIndex >= 0)
|
|
191
|
+
pGradient[upperIndex] = fu;
|
|
192
|
+
if (lowerIndex >= 0)
|
|
193
|
+
pGradient[lowerIndex] = -fl;
|
|
194
|
+
value -= w * logP;
|
|
195
|
+
for (const a of active) {
|
|
196
|
+
gradientNatural[a] = gradientNatural[a] - w * pGradient[a] / probability;
|
|
197
|
+
for (const b of active) {
|
|
198
|
+
let second = 0;
|
|
199
|
+
if (a < p && b < p)
|
|
200
|
+
second = pEtaEta * x[i][a] * x[i][b];
|
|
201
|
+
else if (a < p && b === upperIndex)
|
|
202
|
+
second = -fpu * x[i][a];
|
|
203
|
+
else if (b < p && a === upperIndex)
|
|
204
|
+
second = -fpu * x[i][b];
|
|
205
|
+
else if (a < p && b === lowerIndex)
|
|
206
|
+
second = fpl * x[i][a];
|
|
207
|
+
else if (b < p && a === lowerIndex)
|
|
208
|
+
second = fpl * x[i][b];
|
|
209
|
+
else if (a === upperIndex && b === upperIndex)
|
|
210
|
+
second = fpu;
|
|
211
|
+
else if (a === lowerIndex && b === lowerIndex)
|
|
212
|
+
second = -fpl;
|
|
213
|
+
hessianNatural[a][b] = hessianNatural[a][b] - w * (second / probability
|
|
214
|
+
- pGradient[a] * pGradient[b] / (probability * probability));
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
// Transform natural cut-point derivatives to the first cut-point and log-gaps.
|
|
219
|
+
// The cut-point Jacobian is lower triangular, so use suffix sums instead of
|
|
220
|
+
// multiplying four dense parameter-sized matrices on every likelihood evaluation.
|
|
221
|
+
const cutCount = levels - 1;
|
|
222
|
+
const gradient = new Array(n).fill(0);
|
|
223
|
+
const hessian = Array.from({ length: n }, () => new Array(n).fill(0));
|
|
224
|
+
const cutGradientSuffix = new Array(cutCount).fill(0);
|
|
225
|
+
for (let m = cutCount - 1; m >= 0; m--) {
|
|
226
|
+
cutGradientSuffix[m] = gradientNatural[p + m] + (m + 1 < cutCount ? cutGradientSuffix[m + 1] : 0);
|
|
227
|
+
}
|
|
228
|
+
const cutHessianSuffix = Array.from({ length: cutCount }, () => new Array(cutCount).fill(0));
|
|
229
|
+
for (let a = cutCount - 1; a >= 0; a--) {
|
|
230
|
+
for (let b = cutCount - 1; b >= 0; b--) {
|
|
231
|
+
cutHessianSuffix[a][b] = hessianNatural[p + a][p + b]
|
|
232
|
+
+ (a + 1 < cutCount ? cutHessianSuffix[a + 1][b] : 0)
|
|
233
|
+
+ (b + 1 < cutCount ? cutHessianSuffix[a][b + 1] : 0)
|
|
234
|
+
- (a + 1 < cutCount && b + 1 < cutCount ? cutHessianSuffix[a + 1][b + 1] : 0);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
for (let a = 0; a < p; a++) {
|
|
238
|
+
gradient[a] = gradientNatural[a];
|
|
239
|
+
for (let b = 0; b < p; b++)
|
|
240
|
+
hessian[a][b] = hessianNatural[a][b];
|
|
241
|
+
hessian[a][p] = 0;
|
|
242
|
+
for (let j = 0; j < cutCount; j++)
|
|
243
|
+
hessian[a][p] = hessian[a][p] + hessianNatural[a][p + j];
|
|
244
|
+
hessian[p][a] = hessian[a][p];
|
|
245
|
+
for (let m = 1; m < cutCount; m++) {
|
|
246
|
+
const gap = Math.exp(theta[p + m]);
|
|
247
|
+
let suffix = 0;
|
|
248
|
+
for (let j = m; j < cutCount; j++)
|
|
249
|
+
suffix += hessianNatural[a][p + j];
|
|
250
|
+
hessian[a][p + m] = gap * suffix;
|
|
251
|
+
hessian[p + m][a] = hessian[a][p + m];
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
gradient[p] = cutGradientSuffix[0];
|
|
255
|
+
hessian[p][p] = cutHessianSuffix[0][0];
|
|
256
|
+
for (let m = 1; m < cutCount; m++) {
|
|
257
|
+
const gap = Math.exp(theta[p + m]);
|
|
258
|
+
gradient[p + m] = gap * cutGradientSuffix[m];
|
|
259
|
+
hessian[p][p + m] = gap * cutHessianSuffix[m][0];
|
|
260
|
+
hessian[p + m][p] = hessian[p][p + m];
|
|
261
|
+
for (let q = 1; q < cutCount; q++) {
|
|
262
|
+
const otherGap = Math.exp(theta[p + q]);
|
|
263
|
+
hessian[p + m][p + q] = gap * otherGap * cutHessianSuffix[m][q]
|
|
264
|
+
+ (m === q ? gap * cutGradientSuffix[m] : 0);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
return { value, gradient, hessian };
|
|
268
|
+
}
|
|
269
|
+
/** Internal derivative hook used by finite-difference verification in the model tests. */
|
|
270
|
+
export function __polrDerivativesForTest(x, y, weights, offset, levels, method, theta) {
|
|
271
|
+
return polrDerivatives(x, y, weights, offset, levels, method, theta);
|
|
272
|
+
}
|
|
273
|
+
function maxAbs(values) {
|
|
274
|
+
let result = 0;
|
|
275
|
+
for (const value of values)
|
|
276
|
+
result = Math.max(result, Math.abs(value));
|
|
277
|
+
return result;
|
|
278
|
+
}
|
|
279
|
+
function newtonPolish(start, evaluate, scoreTolerance) {
|
|
280
|
+
let theta = Array.from(start);
|
|
281
|
+
let current = evaluate(theta);
|
|
282
|
+
for (let iteration = 0; iteration < 30 && maxAbs(current.gradient) > scoreTolerance; iteration++) {
|
|
283
|
+
let inverse;
|
|
284
|
+
try {
|
|
285
|
+
inverse = chol2inv(chol(current.hessian));
|
|
286
|
+
}
|
|
287
|
+
catch {
|
|
288
|
+
break;
|
|
289
|
+
}
|
|
290
|
+
const direction = inverse.map((row) => -row.reduce((sum, v, j) => sum + v * current.gradient[j], 0));
|
|
291
|
+
const slope = direction.reduce((sum, v, j) => sum + v * current.gradient[j], 0);
|
|
292
|
+
if (!(slope < 0) || !Number.isFinite(slope))
|
|
293
|
+
break;
|
|
294
|
+
const currentScore = maxAbs(current.gradient);
|
|
295
|
+
let step = 1;
|
|
296
|
+
let accepted = false;
|
|
297
|
+
for (let backtrack = 0; backtrack < 50; backtrack++, step *= 0.5) {
|
|
298
|
+
const candidate = theta.map((v, j) => v + step * direction[j]);
|
|
299
|
+
const trial = evaluate(candidate);
|
|
300
|
+
if (!Number.isFinite(trial.value))
|
|
301
|
+
continue;
|
|
302
|
+
const armijo = trial.value <= current.value + 1e-4 * step * slope;
|
|
303
|
+
// Close to the optimum, the predicted decrease can be below one ulp of the
|
|
304
|
+
// total negative log likelihood. In that regime, accept a genuine score
|
|
305
|
+
// reduction if the objective has not increased beyond its rounding error.
|
|
306
|
+
const roundingAllowance = 16 * Number.EPSILON * Math.max(1, Math.abs(current.value), Math.abs(trial.value));
|
|
307
|
+
const scoreImproved = maxAbs(trial.gradient) <= 0.5 * currentScore
|
|
308
|
+
&& trial.value <= current.value + roundingAllowance;
|
|
309
|
+
if (armijo || scoreImproved) {
|
|
310
|
+
theta = candidate;
|
|
311
|
+
current = trial;
|
|
312
|
+
accepted = true;
|
|
313
|
+
break;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
if (!accepted)
|
|
317
|
+
break;
|
|
318
|
+
}
|
|
319
|
+
return { ...current, theta };
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* Indices of the columns of x that are not in the span of a constant column and the earlier kept columns:
|
|
323
|
+
* modified Gram-Schmidt, twice for stability, with R's QR tolerance 1e-7 relative to the column's norm.
|
|
324
|
+
*/
|
|
325
|
+
// A loop, not Math.hypot(...v): spreading a column overflows the call stack for long data.
|
|
326
|
+
function euclidean(v) {
|
|
327
|
+
let scale = 0;
|
|
328
|
+
for (const value of v)
|
|
329
|
+
scale = Math.max(scale, Math.abs(value));
|
|
330
|
+
if (!(scale > 0) || !Number.isFinite(scale))
|
|
331
|
+
return scale;
|
|
332
|
+
let sum = 0;
|
|
333
|
+
for (const value of v)
|
|
334
|
+
sum += (value / scale) ** 2;
|
|
335
|
+
return scale * Math.sqrt(sum);
|
|
336
|
+
}
|
|
337
|
+
function estimableColumns(x) {
|
|
338
|
+
const n = x.length, p = x[0]?.length ?? 0;
|
|
339
|
+
const basis = n > 0 ? [new Array(n).fill(1 / Math.sqrt(n))] : [];
|
|
340
|
+
const kept = [];
|
|
341
|
+
for (let j = 0; j < p; j++) {
|
|
342
|
+
const v = x.map((row) => row[j]);
|
|
343
|
+
const norm0 = euclidean(v);
|
|
344
|
+
for (let pass = 0; pass < 2; pass++) {
|
|
345
|
+
for (const b of basis) {
|
|
346
|
+
let dot = 0;
|
|
347
|
+
for (let i = 0; i < n; i++)
|
|
348
|
+
dot += b[i] * v[i];
|
|
349
|
+
for (let i = 0; i < n; i++)
|
|
350
|
+
v[i] = v[i] - dot * b[i];
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
const norm = euclidean(v);
|
|
354
|
+
if (!(norm0 > 0) || !(norm > 1e-7 * norm0))
|
|
355
|
+
continue;
|
|
356
|
+
basis.push(v.map((value) => value / norm));
|
|
357
|
+
kept.push(j);
|
|
358
|
+
}
|
|
359
|
+
return kept;
|
|
360
|
+
}
|
|
361
|
+
function rowPredictors(x, beta, offset) {
|
|
362
|
+
return x.map((row, i) => {
|
|
363
|
+
let value = offset[i];
|
|
364
|
+
for (let j = 0; j < beta.length; j++)
|
|
365
|
+
value += row[j] * beta[j];
|
|
366
|
+
return value;
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
function probabilities(eta, cuts, method) {
|
|
370
|
+
return eta.map((z) => {
|
|
371
|
+
const logs = Array.from({ length: cuts.length + 1 }, (_, j) => categoryLogProbability(z, cuts, j, method));
|
|
372
|
+
const values = logs.map((v) => Math.exp(v));
|
|
373
|
+
const total = values.reduce((a, b) => a + b, 0);
|
|
374
|
+
return values.map((v) => v / total);
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
function covarianceFromHessian(hessian, p, k, theta) {
|
|
378
|
+
const upper = chol(hessian);
|
|
379
|
+
const rawCov = chol2inv(upper);
|
|
380
|
+
const n = p + k - 1;
|
|
381
|
+
const jacobian = Array.from({ length: n }, () => new Array(n).fill(0));
|
|
382
|
+
for (let i = 0; i < p; i++)
|
|
383
|
+
jacobian[i][i] = 1;
|
|
384
|
+
for (let j = 0; j < k - 1; j++) {
|
|
385
|
+
jacobian[p + j][p] = 1;
|
|
386
|
+
for (let m = 1; m <= j; m++)
|
|
387
|
+
jacobian[p + j][p + m] = Math.exp(theta[p + m]);
|
|
388
|
+
}
|
|
389
|
+
return Array.from({ length: n }, (_, i) => Array.from({ length: n }, (_, j) => {
|
|
390
|
+
let sum = 0;
|
|
391
|
+
for (let a = 0; a < n; a++)
|
|
392
|
+
for (let b = 0; b < n; b++)
|
|
393
|
+
sum += jacobian[i][a] * rawCov[a][b] * jacobian[j][b];
|
|
394
|
+
return sum;
|
|
395
|
+
}));
|
|
396
|
+
}
|
|
397
|
+
function offsetFormula(formula) {
|
|
398
|
+
const match = /\s*\+\s*offset\(\s*([A-Za-z.][\w.]*)\s*\)/.exec(formula);
|
|
399
|
+
if (match === null)
|
|
400
|
+
return { formula };
|
|
401
|
+
return { formula: formula.replace(match[0], ""), column: match[1] };
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* Fit a cumulative-link ordinal regression. Equivalent to R's `MASS::polr()`.
|
|
405
|
+
*
|
|
406
|
+
* @param formula A formula such as `"rating ~ treatment + age"`.
|
|
407
|
+
* @param data The data frame: an object of columns.
|
|
408
|
+
* @param options The link, weights, offset, starts, contrasts and optimisation controls.
|
|
409
|
+
* @returns The fitted slopes, cut-points, fitted probabilities and likelihood statistics.
|
|
410
|
+
*
|
|
411
|
+
* @example
|
|
412
|
+
* ```ts
|
|
413
|
+
* const fit = polr("rating ~ dose", { rating: ["low", "medium", "high", "low", "medium", "high"], dose: [0, 1, 2, 0, 1, 2] });
|
|
414
|
+
* fit.zeta;
|
|
415
|
+
* ```
|
|
416
|
+
*
|
|
417
|
+
* @category Regression
|
|
418
|
+
*/
|
|
419
|
+
export function polr(formula, data, options = {}) {
|
|
420
|
+
checkOptions(options, POLR_KEYS, "polr"); // generated: option-keys.mjs
|
|
421
|
+
const method = options.method ?? "logistic";
|
|
422
|
+
if (!["logistic", "probit", "cloglog", "loglog", "cauchit"].includes(method)) {
|
|
423
|
+
throw new RangeError(`unknown method '${String(method)}'`);
|
|
424
|
+
}
|
|
425
|
+
const extracted = offsetFormula(formula);
|
|
426
|
+
if (extracted.column !== undefined && options.offset !== undefined)
|
|
427
|
+
throw new RangeError("specify the offset in the formula or options, not both");
|
|
428
|
+
const parsed = parseFormula(extracted.formula);
|
|
429
|
+
if (parsed.response === undefined)
|
|
430
|
+
throw new TypeError("the formula must have a response");
|
|
431
|
+
const designOptions = {};
|
|
432
|
+
if (options.weights !== undefined)
|
|
433
|
+
designOptions.weights = options.weights;
|
|
434
|
+
if (options.levels !== undefined)
|
|
435
|
+
designOptions.levels = options.levels;
|
|
436
|
+
if (options.contrasts !== undefined)
|
|
437
|
+
designOptions.contrasts = options.contrasts;
|
|
438
|
+
designOptions.anyResponse = true;
|
|
439
|
+
const d = design(parsed, data, designOptions);
|
|
440
|
+
const response = d.frame.variables[0];
|
|
441
|
+
if (response === undefined || response.kind !== "factor")
|
|
442
|
+
throw new TypeError("response must be a factor");
|
|
443
|
+
const responseLevels = response.levels;
|
|
444
|
+
if (responseLevels.length < 3)
|
|
445
|
+
throw new Error("response must have 3 or more levels");
|
|
446
|
+
const weights = d.frame.weights ?? new Array(d.frame.rows.length).fill(1);
|
|
447
|
+
for (let j = 0; j < responseLevels.length; j++) {
|
|
448
|
+
if (!weights.some((w, i) => w > 0 && response.codes[i] === j)) {
|
|
449
|
+
throw new Error(`response level '${responseLevels[j]}' has no positive-weight observations`);
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
if (weights.some((w) => !Number.isFinite(w) || w < 0))
|
|
453
|
+
throw new RangeError("weights must be finite and non-negative");
|
|
454
|
+
const designX = d.x.map((row) => row.slice(d.terms.intercept ? 1 : 0));
|
|
455
|
+
if (designX.some((row) => row.some((value) => !Number.isFinite(value)))) {
|
|
456
|
+
throw new RangeError("NA/NaN/Inf in model matrix or response");
|
|
457
|
+
}
|
|
458
|
+
// The cut-points play the part of an intercept, so a column in the span of the constant and the earlier columns
|
|
459
|
+
// has no estimable coefficient. R drops such columns with a warning; so does rStats.js (decided 2026-11-20).
|
|
460
|
+
const kept = estimableColumns(designX);
|
|
461
|
+
const designNames = d.colNames.slice(d.terms.intercept ? 1 : 0);
|
|
462
|
+
const dropped = designNames.filter((_, j) => !kept.includes(j));
|
|
463
|
+
const rankWarnings = dropped.length > 0
|
|
464
|
+
? [`design appears to be rank-deficient, so dropping some coefs: ${dropped.join(", ")}`] : [];
|
|
465
|
+
if (rankWarnings.length > 0 && options.start !== undefined) {
|
|
466
|
+
throw new RangeError("start cannot be given for a rank-deficient design; remove the aliased columns");
|
|
467
|
+
}
|
|
468
|
+
const x = designX.map((row) => kept.map((j) => row[j]));
|
|
469
|
+
const columnNames = kept.map((j) => d.colNames[j + (d.terms.intercept ? 1 : 0)]);
|
|
470
|
+
const p = columnNames.length;
|
|
471
|
+
const columnScales = Array.from({ length: p }, (_, j) => {
|
|
472
|
+
const scale = x.reduce((m, row) => Math.max(m, Math.abs(row[j])), 0);
|
|
473
|
+
return scale > 0 && Number.isFinite(scale) ? scale : 1;
|
|
474
|
+
});
|
|
475
|
+
const scaledX = x.map(row => row.map((value, j) => value / columnScales[j]));
|
|
476
|
+
const offsetSource = options.offset ?? (extracted.column === undefined ? undefined : data[extracted.column]);
|
|
477
|
+
const offset = offsetSource === undefined
|
|
478
|
+
? new Array(d.frame.rows.length).fill(0)
|
|
479
|
+
: d.frame.rows.map((row) => Number(offsetSource[row]));
|
|
480
|
+
if (offset.some((v) => !Number.isFinite(v)))
|
|
481
|
+
throw new RangeError("offset must contain finite values");
|
|
482
|
+
const y = response.codes;
|
|
483
|
+
const k = responseLevels.length;
|
|
484
|
+
const rawTheta0 = options.start === undefined
|
|
485
|
+
? [...new Array(p).fill(0), ...initialValues(y, weights, k, method)]
|
|
486
|
+
: rawStart(Array.from(options.start), p, k);
|
|
487
|
+
const theta0 = rawTheta0.map((value, i) => i < p ? value * columnScales[i] : value);
|
|
488
|
+
const objective = (theta) => {
|
|
489
|
+
const beta = theta.slice(0, p);
|
|
490
|
+
const cuts = cutpointsFrom(theta, p, k);
|
|
491
|
+
const eta = rowPredictors(scaledX, beta, offset);
|
|
492
|
+
let logLikelihood = 0;
|
|
493
|
+
for (let i = 0; i < y.length; i++) {
|
|
494
|
+
if (weights[i] === 0)
|
|
495
|
+
continue;
|
|
496
|
+
const lp = categoryLogProbability(eta[i], cuts, y[i], method);
|
|
497
|
+
if (!Number.isFinite(lp))
|
|
498
|
+
return Number.MAX_VALUE;
|
|
499
|
+
logLikelihood -= weights[i] * lp;
|
|
500
|
+
}
|
|
501
|
+
return logLikelihood;
|
|
502
|
+
};
|
|
503
|
+
const evaluate = (theta) => polrDerivatives(scaledX, y, weights, offset, k, method, theta);
|
|
504
|
+
const fit = optim(theta0, objective, {
|
|
505
|
+
method: "BFGS",
|
|
506
|
+
gr: (theta) => evaluate(theta).gradient,
|
|
507
|
+
control: { maxit: options.maxit ?? 2000, reltol: options.reltol ?? 1e-15 },
|
|
508
|
+
});
|
|
509
|
+
// BFGS supplies a robust starting point; the exact score and observed Hessian finish the fit.
|
|
510
|
+
// Its iteration-limit code is not decisive if the Newton refinement reaches the score tolerance.
|
|
511
|
+
// The score is a sum of weighted row contributions, so its absolute scale
|
|
512
|
+
// grows linearly with total prior weight. Use a per-unit-weight tolerance: proportional to the total weight with
|
|
513
|
+
// no absolute floor, so that weights scaled by any constant give the same fit (found 2026-11-20: with a floor
|
|
514
|
+
// of 1, weights of 1e-6 stopped the fit early and moved the coefficients by 3e-5).
|
|
515
|
+
const scoreTolerance = 1e-9 * weights.reduce((sum, weight) => sum + weight, 0);
|
|
516
|
+
const polished = newtonPolish(fit.par, evaluate, scoreTolerance);
|
|
517
|
+
if (maxAbs(polished.gradient) > scoreTolerance) {
|
|
518
|
+
throw new Error(`ordinal regression score did not converge (max |score| = ${maxAbs(polished.gradient)})`);
|
|
519
|
+
}
|
|
520
|
+
const thetaScaled = polished.theta;
|
|
521
|
+
const theta = thetaScaled.map((value, i) => i < p ? value / columnScales[i] : value);
|
|
522
|
+
const beta = theta.slice(0, p);
|
|
523
|
+
const cuts = cutpointsFrom(theta, p, k);
|
|
524
|
+
const hessian = polished.hessian;
|
|
525
|
+
const scaledCovariance = covarianceFromHessian(hessian, p, k, thetaScaled);
|
|
526
|
+
const cov = scaledCovariance.map((row, i) => row.map((value, j) => value / (i < p ? columnScales[i] : 1) / (j < p ? columnScales[j] : 1)));
|
|
527
|
+
const eta = rowPredictors(x, beta, offset);
|
|
528
|
+
const fitted = probabilities(eta, cuts, method);
|
|
529
|
+
const names = [...columnNames, ...cuts.map((_, j) => `${responseLevels[j]}|${responseLevels[j + 1]}`)];
|
|
530
|
+
const coefficients = Object.fromEntries(columnNames.map((name, i) => [name, beta[i]]));
|
|
531
|
+
const zeta = Object.fromEntries(names.slice(p).map((name, i) => [name, cuts[i]]));
|
|
532
|
+
const logLik = -polished.value;
|
|
533
|
+
const edf = p + k - 1;
|
|
534
|
+
const nobs = weights.reduce((a, b) => a + b, 0);
|
|
535
|
+
const warnings = [...d.warnings, ...rankWarnings, ...fit.warnings];
|
|
536
|
+
const factorLevels = {};
|
|
537
|
+
for (let i = 1; i < d.terms.variables.length; i++) {
|
|
538
|
+
const variable = d.frame.variables[i];
|
|
539
|
+
if (variable?.kind === "factor")
|
|
540
|
+
factorLevels[d.terms.variables[i]] = variable.levels;
|
|
541
|
+
}
|
|
542
|
+
const model = {
|
|
543
|
+
formula, rhs: parsed.rhs, predictorVariables: d.terms.variables.slice(1), factorLevels,
|
|
544
|
+
contrasts: options.contrasts ?? {},
|
|
545
|
+
...(extracted.column === undefined ? {} : { offsetColumn: extracted.column }),
|
|
546
|
+
externalOffset: options.offset !== undefined,
|
|
547
|
+
response: parsed.response, x, columnNames, y, responseLevels, weights, offset,
|
|
548
|
+
rows: d.frame.rows, method, logLikelihood: logLik, theta, rawHessian: hessian,
|
|
549
|
+
};
|
|
550
|
+
const result = {
|
|
551
|
+
coefficients, zeta, fittedValues: fitted, linearPredictors: eta, deviance: -2 * logLik,
|
|
552
|
+
logLik, aic: -2 * logLik + 2 * edf, bic: -2 * logLik + Math.log(nobs) * edf,
|
|
553
|
+
edf, nobs, converged: true, convergence: 0, warnings, model,
|
|
554
|
+
};
|
|
555
|
+
// Keep the covariance on the public result without exposing optimisation coordinates.
|
|
556
|
+
COVARIANCE.set(result, cov);
|
|
557
|
+
return reported("polr", result);
|
|
558
|
+
}
|
|
559
|
+
const COVARIANCE = new WeakMap();
|
|
560
|
+
/**
|
|
561
|
+
* Predict ordinal categories or their probabilities for new observations. Equivalent to R's `predict.polr()`.
|
|
562
|
+
*
|
|
563
|
+
* @param fit A fit returned by {@link polr}.
|
|
564
|
+
* @param options New predictor columns, optional row labels, and the prediction type.
|
|
565
|
+
* @returns Predicted category labels, or a matrix with one probability column per response level.
|
|
566
|
+
*
|
|
567
|
+
* @example
|
|
568
|
+
* ```ts
|
|
569
|
+
* const fit = polr("rating ~ dose", { rating: ["low", "medium", "high", "low", "medium", "high"], dose: [0, 1, 2, 0, 1, 2] });
|
|
570
|
+
* polrPredict(fit, { newdata: { dose: [0, 1, 2] } });
|
|
571
|
+
* ```
|
|
572
|
+
*
|
|
573
|
+
* @category Regression
|
|
574
|
+
*/
|
|
575
|
+
export function polrPredict(fit, options = {}) {
|
|
576
|
+
checkOptions(options, POLR_PREDICT_KEYS, "polrPredict"); // generated: option-keys.mjs
|
|
577
|
+
const type = options.type ?? "class";
|
|
578
|
+
if (type !== "class" && type !== "probs")
|
|
579
|
+
throw new RangeError(`unknown prediction type '${String(type)}'`);
|
|
580
|
+
const model = fit.model;
|
|
581
|
+
let x;
|
|
582
|
+
let offsets;
|
|
583
|
+
let rowIndices;
|
|
584
|
+
let rowNames;
|
|
585
|
+
let warnings = fit.warnings;
|
|
586
|
+
if (options.newdata === undefined) {
|
|
587
|
+
x = model.x;
|
|
588
|
+
offsets = model.offset;
|
|
589
|
+
rowIndices = Array.from({ length: x.length }, (_, i) => i);
|
|
590
|
+
rowNames = options.rowNames === undefined
|
|
591
|
+
? model.rows.map((row) => String(row + 1))
|
|
592
|
+
: Array.from(options.rowNames);
|
|
593
|
+
}
|
|
594
|
+
else {
|
|
595
|
+
if (model.externalOffset)
|
|
596
|
+
throw new TypeError("newdata prediction requires the offset in the formula");
|
|
597
|
+
const data = options.newdata;
|
|
598
|
+
const n = dataRowCount(data, model.predictorVariables);
|
|
599
|
+
if (n === undefined)
|
|
600
|
+
throw new TypeError("cannot determine the number of rows in newdata");
|
|
601
|
+
rowNames = options.rowNames === undefined
|
|
602
|
+
? Array.from({ length: n }, (_, i) => String(i + 1))
|
|
603
|
+
: Array.from(options.rowNames);
|
|
604
|
+
if (rowNames.length !== n)
|
|
605
|
+
throw new RangeError("rowNames must have the same length as newdata");
|
|
606
|
+
for (const [name, levels] of Object.entries(model.factorLevels)) {
|
|
607
|
+
const column = data[name];
|
|
608
|
+
if (column === undefined)
|
|
609
|
+
throw new RangeError(`object '${name}' not found`);
|
|
610
|
+
for (const raw of column) {
|
|
611
|
+
if (raw === null || (typeof raw === "number" && Number.isNaN(raw)))
|
|
612
|
+
continue;
|
|
613
|
+
const value = typeof raw === "boolean" ? (raw ? "TRUE" : "FALSE") : String(raw);
|
|
614
|
+
if (!levels.includes(value))
|
|
615
|
+
throw new RangeError(`factor ${name} has new level ${value}`);
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
const designOptions = {
|
|
619
|
+
levels: model.factorLevels,
|
|
620
|
+
contrasts: model.contrasts,
|
|
621
|
+
};
|
|
622
|
+
if (model.offsetColumn !== undefined)
|
|
623
|
+
designOptions.extraVariables = [model.offsetColumn];
|
|
624
|
+
const d = design({ response: undefined, rhs: model.rhs }, data, designOptions);
|
|
625
|
+
const first = d.terms.intercept ? 1 : 0;
|
|
626
|
+
const names = d.colNames.slice(first);
|
|
627
|
+
// The fit may have dropped aliased columns, so take the fitted columns by name.
|
|
628
|
+
const columns = model.columnNames.map((name) => names.indexOf(name));
|
|
629
|
+
if (columns.some((j) => j < 0))
|
|
630
|
+
throw new RangeError("newdata does not produce the fitted model matrix columns");
|
|
631
|
+
x = d.x.map((row) => columns.map((j) => row[first + j]));
|
|
632
|
+
rowIndices = d.frame.rows;
|
|
633
|
+
offsets = model.offsetColumn === undefined
|
|
634
|
+
? new Array(rowIndices.length).fill(0)
|
|
635
|
+
: rowIndices.map((i) => Number(data[model.offsetColumn][i]));
|
|
636
|
+
if (offsets.some((value) => !Number.isFinite(value)))
|
|
637
|
+
throw new RangeError("offset must contain finite values");
|
|
638
|
+
warnings = [...fit.warnings, ...d.warnings];
|
|
639
|
+
}
|
|
640
|
+
if (options.newdata === undefined && rowNames.length !== x.length) {
|
|
641
|
+
throw new RangeError("rowNames must have the same length as the fitted observations");
|
|
642
|
+
}
|
|
643
|
+
const beta = Object.values(fit.coefficients);
|
|
644
|
+
const cuts = Object.values(fit.zeta);
|
|
645
|
+
const eta = rowPredictors(x, beta, offsets);
|
|
646
|
+
const predicted = probabilities(eta, cuts, model.method);
|
|
647
|
+
const n = rowNames.length;
|
|
648
|
+
const full = Array.from({ length: n }, () => new Array(model.responseLevels.length).fill(null));
|
|
649
|
+
rowIndices.forEach((original, i) => { full[original] = predicted[i]; });
|
|
650
|
+
if (type === "class") {
|
|
651
|
+
const classes = full.map((values) => {
|
|
652
|
+
if (values[0] === null)
|
|
653
|
+
return null;
|
|
654
|
+
let best = 0;
|
|
655
|
+
for (let j = 1; j < values.length; j++)
|
|
656
|
+
if (values[j] > values[best])
|
|
657
|
+
best = j;
|
|
658
|
+
return model.responseLevels[best];
|
|
659
|
+
});
|
|
660
|
+
return reported("polrPredict", { value: classes, warnings }, fit).value;
|
|
661
|
+
}
|
|
662
|
+
const result = {
|
|
663
|
+
rows: rowNames,
|
|
664
|
+
columns: model.responseLevels,
|
|
665
|
+
values: full,
|
|
666
|
+
warnings,
|
|
667
|
+
};
|
|
668
|
+
return reported("polrPredict", result, fit);
|
|
669
|
+
}
|
|
670
|
+
/**
|
|
671
|
+
* Summary table of the slope and cut-point estimates. Equivalent to R's `summary.polr()`.
|
|
672
|
+
*
|
|
673
|
+
* @param fit A fit returned by {@link polr}.
|
|
674
|
+
* @returns Estimates, standard errors and Wald t statistics.
|
|
675
|
+
*
|
|
676
|
+
* @category Regression
|
|
677
|
+
*/
|
|
678
|
+
export function polrSummary(fit) {
|
|
679
|
+
const names = [...Object.keys(fit.coefficients), ...Object.keys(fit.zeta)];
|
|
680
|
+
const estimates = [...Object.values(fit.coefficients), ...Object.values(fit.zeta)];
|
|
681
|
+
const covariance = COVARIANCE.get(fit);
|
|
682
|
+
if (covariance === undefined)
|
|
683
|
+
throw new TypeError("fit was not created by polr");
|
|
684
|
+
const values = estimates.map((estimate, i) => {
|
|
685
|
+
const se = Math.sqrt(covariance[i][i]);
|
|
686
|
+
return [estimate, se, estimate / se];
|
|
687
|
+
});
|
|
688
|
+
return reported("polrSummary", { rows: names, columns: ["Value", "Std. Error", "t value"], values, warnings: fit.warnings }, fit);
|
|
689
|
+
}
|
|
690
|
+
/**
|
|
691
|
+
* Covariance matrix of the slopes and cut-points. Equivalent to R's `vcov.polr()`.
|
|
692
|
+
*
|
|
693
|
+
* @param fit A fit returned by {@link polr}.
|
|
694
|
+
* @returns The covariance matrix in slope-then-cut-point order.
|
|
695
|
+
*
|
|
696
|
+
* @category Regression
|
|
697
|
+
*/
|
|
698
|
+
export function polrVcov(fit) {
|
|
699
|
+
const covariance = COVARIANCE.get(fit);
|
|
700
|
+
if (covariance === undefined)
|
|
701
|
+
throw new TypeError("fit was not created by polr");
|
|
702
|
+
const names = [...Object.keys(fit.coefficients), ...Object.keys(fit.zeta)];
|
|
703
|
+
return reported("polrVcov", { rows: names, columns: names, values: covariance, warnings: fit.warnings }, fit);
|
|
704
|
+
}
|
|
705
|
+
/** Indices of requested slopes, preserving the caller's order. */
|
|
706
|
+
function confintParameterIndices(names, parm) {
|
|
707
|
+
const requested = parm === undefined ? Array.from({ length: names.length }, (_, i) => i + 1)
|
|
708
|
+
: Array.isArray(parm) ? Array.from(parm) : [parm];
|
|
709
|
+
return requested.map((value) => {
|
|
710
|
+
if (typeof value === "number") {
|
|
711
|
+
if (!Number.isInteger(value) || value < 1 || value > names.length) {
|
|
712
|
+
throw new RangeError(`'parm' must identify a slope from 1 to ${names.length}`);
|
|
713
|
+
}
|
|
714
|
+
return value - 1;
|
|
715
|
+
}
|
|
716
|
+
const index = names.indexOf(value);
|
|
717
|
+
if (index < 0)
|
|
718
|
+
throw new RangeError(`unknown slope parameter '${value}'`);
|
|
719
|
+
return index;
|
|
720
|
+
});
|
|
721
|
+
}
|
|
722
|
+
function profileConstrainedFit(fit, fixedIndex, fixedValue, startTheta) {
|
|
723
|
+
const model = fit.model;
|
|
724
|
+
const theta = Array.from(startTheta);
|
|
725
|
+
theta[fixedIndex] = fixedValue;
|
|
726
|
+
const freeIndices = theta.map((_, i) => i).filter((i) => i !== fixedIndex);
|
|
727
|
+
const evaluate = (point) => {
|
|
728
|
+
const full = Array.from(theta);
|
|
729
|
+
for (let i = 0; i < freeIndices.length; i++)
|
|
730
|
+
full[freeIndices[i]] = point[i];
|
|
731
|
+
const d = polrDerivatives(model.x, model.y, model.weights, model.offset, model.responseLevels.length, model.method, full);
|
|
732
|
+
return {
|
|
733
|
+
value: d.value,
|
|
734
|
+
gradient: freeIndices.map((i) => d.gradient[i]),
|
|
735
|
+
hessian: freeIndices.map((i) => freeIndices.map((j) => d.hessian[i][j])),
|
|
736
|
+
};
|
|
737
|
+
};
|
|
738
|
+
let point = freeIndices.map((i) => theta[i]);
|
|
739
|
+
let current = evaluate(point);
|
|
740
|
+
const scoreTolerance = 2e-11 * Math.max(1, model.weights.reduce((sum, w) => sum + w, 0));
|
|
741
|
+
let usedBfgs = false;
|
|
742
|
+
const bfgsFallback = () => {
|
|
743
|
+
try {
|
|
744
|
+
const result = optim(point, (candidate) => evaluate(candidate).value, {
|
|
745
|
+
method: "BFGS",
|
|
746
|
+
gr: (candidate) => evaluate(candidate).gradient,
|
|
747
|
+
control: { maxit: 1000, reltol: 1e-14 },
|
|
748
|
+
});
|
|
749
|
+
if (!result.par.every(Number.isFinite))
|
|
750
|
+
return false;
|
|
751
|
+
point = result.par;
|
|
752
|
+
current = evaluate(point);
|
|
753
|
+
usedBfgs = true;
|
|
754
|
+
return Number.isFinite(current.value);
|
|
755
|
+
}
|
|
756
|
+
catch {
|
|
757
|
+
return false;
|
|
758
|
+
}
|
|
759
|
+
};
|
|
760
|
+
for (let iteration = 0; iteration < 40 && maxAbs(current.gradient) > scoreTolerance; iteration++) {
|
|
761
|
+
let inverse;
|
|
762
|
+
try {
|
|
763
|
+
inverse = chol2inv(chol(current.hessian));
|
|
764
|
+
}
|
|
765
|
+
catch {
|
|
766
|
+
if (!usedBfgs && bfgsFallback())
|
|
767
|
+
continue;
|
|
768
|
+
break;
|
|
769
|
+
}
|
|
770
|
+
const direction = inverse.map((row) => -row.reduce((sum, value, j) => sum + value * current.gradient[j], 0));
|
|
771
|
+
const slope = direction.reduce((sum, value, j) => sum + value * current.gradient[j], 0);
|
|
772
|
+
if (!(slope < 0) || !Number.isFinite(slope)) {
|
|
773
|
+
if (!usedBfgs && bfgsFallback())
|
|
774
|
+
continue;
|
|
775
|
+
break;
|
|
776
|
+
}
|
|
777
|
+
let step = 1;
|
|
778
|
+
let accepted = false;
|
|
779
|
+
for (let backtrack = 0; backtrack < 40; backtrack++, step *= 0.5) {
|
|
780
|
+
const candidate = point.map((value, j) => value + step * direction[j]);
|
|
781
|
+
const trial = evaluate(candidate);
|
|
782
|
+
const allowance = 16 * Number.EPSILON * Math.max(1, Math.abs(current.value), Math.abs(trial.value));
|
|
783
|
+
if (Number.isFinite(trial.value)
|
|
784
|
+
&& (trial.value <= current.value + 1e-4 * step * slope
|
|
785
|
+
|| (maxAbs(trial.gradient) < maxAbs(current.gradient) && trial.value <= current.value + allowance))) {
|
|
786
|
+
point = candidate;
|
|
787
|
+
current = trial;
|
|
788
|
+
accepted = true;
|
|
789
|
+
break;
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
if (!accepted) {
|
|
793
|
+
if (!usedBfgs && bfgsFallback())
|
|
794
|
+
continue;
|
|
795
|
+
break;
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
const full = Array.from(theta);
|
|
799
|
+
for (let i = 0; i < freeIndices.length; i++)
|
|
800
|
+
full[freeIndices[i]] = point[i];
|
|
801
|
+
const final = polrDerivatives(model.x, model.y, model.weights, model.offset, model.responseLevels.length, model.method, full);
|
|
802
|
+
const converged = maxAbs(freeIndices.map((i) => final.gradient[i])) <= scoreTolerance;
|
|
803
|
+
return { value: converged ? final.value : NaN, fixedScore: final.gradient[fixedIndex], theta: full };
|
|
804
|
+
}
|
|
805
|
+
function profileEndpoint(fit, parameterIndex, target, standardError) {
|
|
806
|
+
const estimate = Object.values(fit.coefficients)[parameterIndex];
|
|
807
|
+
const centre = -fit.logLik;
|
|
808
|
+
let warmTheta = Array.from(fit.model.theta);
|
|
809
|
+
const evaluate = (value) => {
|
|
810
|
+
const point = profileConstrainedFit(fit, parameterIndex, value, warmTheta);
|
|
811
|
+
if (!Number.isFinite(point.value) || !Number.isFinite(point.fixedScore))
|
|
812
|
+
return null;
|
|
813
|
+
warmTheta = point.theta;
|
|
814
|
+
const r = Math.sign(value - estimate) * Math.sqrt(Math.max(0, 2 * (point.value - centre)));
|
|
815
|
+
return { x: value, g: r - target, r, score: point.fixedScore };
|
|
816
|
+
};
|
|
817
|
+
// The estimate itself has r=0, so start from the corresponding Wald endpoint,
|
|
818
|
+
// not from a Newton step at the singular point.
|
|
819
|
+
const centreValue = { x: estimate, g: -target, r: 0, score: 0 };
|
|
820
|
+
let inside = centreValue;
|
|
821
|
+
let distance = Math.max(Math.abs(target) * standardError, standardError, 1e-6);
|
|
822
|
+
let outside = evaluate(estimate + Math.sign(target) * distance);
|
|
823
|
+
for (let iteration = 0; iteration < 60 && (outside === null || inside.g * outside.g > 0); iteration++) {
|
|
824
|
+
distance *= 2;
|
|
825
|
+
outside = evaluate(estimate + Math.sign(target) * distance);
|
|
826
|
+
}
|
|
827
|
+
if (outside === null || inside.g * outside.g > 0)
|
|
828
|
+
return NaN;
|
|
829
|
+
let low = inside;
|
|
830
|
+
let high = outside;
|
|
831
|
+
if (low.x > high.x)
|
|
832
|
+
[low, high] = [high, low];
|
|
833
|
+
let current = outside;
|
|
834
|
+
for (let iteration = 0; iteration < 80; iteration++) {
|
|
835
|
+
if (Math.abs(current.g) <= 2e-10)
|
|
836
|
+
return current.x;
|
|
837
|
+
// The stored gradient is for negative log likelihood, hence dr/db = score/r.
|
|
838
|
+
// Newton is used only away from r=0 and only while it remains inside the bracket.
|
|
839
|
+
const derivative = current.r === 0 ? NaN : current.score / current.r;
|
|
840
|
+
let candidate = current.x - current.g / derivative;
|
|
841
|
+
const width = high.x - low.x;
|
|
842
|
+
const guard = 0.05 * width;
|
|
843
|
+
if (!Number.isFinite(candidate) || candidate <= low.x + guard || candidate >= high.x - guard) {
|
|
844
|
+
// A secant step is cheaper than a profile refit and is safe only inside the bracket.
|
|
845
|
+
candidate = low.x - low.g * (high.x - low.x) / (high.g - low.g);
|
|
846
|
+
}
|
|
847
|
+
if (!Number.isFinite(candidate) || candidate <= low.x + guard || candidate >= high.x - guard) {
|
|
848
|
+
candidate = low.x + width / 2;
|
|
849
|
+
}
|
|
850
|
+
if (candidate === low.x || candidate === high.x || candidate === current.x)
|
|
851
|
+
return NaN;
|
|
852
|
+
const next = evaluate(candidate);
|
|
853
|
+
if (next === null)
|
|
854
|
+
return NaN;
|
|
855
|
+
if (low.g * next.g <= 0)
|
|
856
|
+
high = next;
|
|
857
|
+
else
|
|
858
|
+
low = next;
|
|
859
|
+
if (low.x > high.x)
|
|
860
|
+
[low, high] = [high, low];
|
|
861
|
+
current = next;
|
|
862
|
+
}
|
|
863
|
+
return NaN;
|
|
864
|
+
}
|
|
865
|
+
/**
|
|
866
|
+
* Equivalent to R's `confint.polr()`.
|
|
867
|
+
*
|
|
868
|
+
* @param fit A fit returned by {@link polr}.
|
|
869
|
+
* @param options The interval method, confidence level and selected slope parameters.
|
|
870
|
+
* @returns A table of lower and upper confidence limits; cut-points are not included.
|
|
871
|
+
*
|
|
872
|
+
* @example
|
|
873
|
+
* ```ts
|
|
874
|
+
* const fit = polr("rating ~ dose", { rating: ["low", "medium", "high", "low", "medium", "high"], dose: [0, 1, 2, 0, 1, 2] });
|
|
875
|
+
* polrConfint(fit, { method: "wald", level: 0.95 });
|
|
876
|
+
* ```
|
|
877
|
+
*
|
|
878
|
+
* @category Regression
|
|
879
|
+
*/
|
|
880
|
+
export function polrConfint(fit, options = {}) {
|
|
881
|
+
checkOptions(options, POLR_CONFINT_KEYS, "polrConfint"); // generated: option-keys.mjs
|
|
882
|
+
const method = options.method ?? "profile";
|
|
883
|
+
if (method !== "profile" && method !== "wald")
|
|
884
|
+
throw new RangeError(`unknown confidence-interval method '${String(method)}'`);
|
|
885
|
+
const level = options.level ?? 0.95;
|
|
886
|
+
if (!(level > 0 && level < 1) || !Number.isFinite(level)) {
|
|
887
|
+
throw new RangeError("'level' must be between 0 and 1");
|
|
888
|
+
}
|
|
889
|
+
const names = Object.keys(fit.coefficients);
|
|
890
|
+
const indices = confintParameterIndices(names, options.parm);
|
|
891
|
+
const alpha = (1 - level) / 2;
|
|
892
|
+
const lowerPercent = String(Number((100 * alpha).toPrecision(12)));
|
|
893
|
+
const upperPercent = String(Number((100 * (1 - alpha)).toPrecision(12)));
|
|
894
|
+
const columns = [`${lowerPercent} %`, `${upperPercent} %`];
|
|
895
|
+
const covariance = COVARIANCE.get(fit);
|
|
896
|
+
if (covariance === undefined)
|
|
897
|
+
throw new TypeError("fit was not created by polr");
|
|
898
|
+
const z = qnorm(1 - alpha);
|
|
899
|
+
const warnings = [];
|
|
900
|
+
const values = indices.map((index) => {
|
|
901
|
+
const estimate = Object.values(fit.coefficients)[index];
|
|
902
|
+
const se = Math.sqrt(covariance[index][index]);
|
|
903
|
+
if (method === "wald")
|
|
904
|
+
return [estimate - z * se, estimate + z * se];
|
|
905
|
+
const lower = profileEndpoint(fit, index, -z, se);
|
|
906
|
+
const upper = profileEndpoint(fit, index, z, se);
|
|
907
|
+
if (!Number.isFinite(lower) || !Number.isFinite(upper)) {
|
|
908
|
+
warnings.push(`profile confidence limit could not be found for '${names[index]}'`);
|
|
909
|
+
}
|
|
910
|
+
return [lower, upper];
|
|
911
|
+
});
|
|
912
|
+
return reported("polrConfint", {
|
|
913
|
+
rows: indices.map((index) => names[index]),
|
|
914
|
+
columns,
|
|
915
|
+
values,
|
|
916
|
+
warnings: [...new Set(warnings)],
|
|
917
|
+
}, fit);
|
|
918
|
+
}
|
|
919
|
+
/**
|
|
920
|
+
* Equivalent to R's `anova.polr()`.
|
|
921
|
+
*
|
|
922
|
+
* @param fits Two or more nested fits, ordered from the smallest to the largest model.
|
|
923
|
+
* @returns The sequential likelihood-ratio chi-squared comparison table.
|
|
924
|
+
*
|
|
925
|
+
* @example
|
|
926
|
+
* ```ts
|
|
927
|
+
* const data = {
|
|
928
|
+
* rating: [
|
|
929
|
+
* "low", "low", "low", "medium", "medium", "high",
|
|
930
|
+
* "low", "low", "medium", "medium", "medium", "high",
|
|
931
|
+
* "low", "medium", "medium", "medium", "high", "high",
|
|
932
|
+
* "low", "low", "medium", "medium", "medium", "high",
|
|
933
|
+
* "low", "medium", "medium", "medium", "high", "high",
|
|
934
|
+
* "low", "medium", "medium", "high", "high", "high",
|
|
935
|
+
* ],
|
|
936
|
+
* dose: [
|
|
937
|
+
* 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1,
|
|
938
|
+
* 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0,
|
|
939
|
+
* 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2,
|
|
940
|
+
* ],
|
|
941
|
+
* treatment: [
|
|
942
|
+
* "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A",
|
|
943
|
+
* "A", "A", "A", "A", "A", "A", "B", "B", "B", "B", "B", "B",
|
|
944
|
+
* "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B",
|
|
945
|
+
* ],
|
|
946
|
+
* };
|
|
947
|
+
* const small = polr("rating ~ dose", data);
|
|
948
|
+
* const large = polr("rating ~ dose + treatment", data);
|
|
949
|
+
* polrAnova(small, large);
|
|
950
|
+
* ```
|
|
951
|
+
*
|
|
952
|
+
* @category Regression
|
|
953
|
+
*/
|
|
954
|
+
export function polrAnova(...fits) {
|
|
955
|
+
checkOptions({}, [], "polrAnova");
|
|
956
|
+
if (fits.length === 1)
|
|
957
|
+
throw new Error('anova is not implemented for a single "polr" object');
|
|
958
|
+
if (fits.length < 2)
|
|
959
|
+
throw new Error("polrAnova requires at least two fits");
|
|
960
|
+
const first = fits[0];
|
|
961
|
+
const reference = first.model;
|
|
962
|
+
const warnings = [...new Set(fits.flatMap((fit) => fit.warnings))];
|
|
963
|
+
for (let index = 1; index < fits.length; index++) {
|
|
964
|
+
const previous = fits[index - 1];
|
|
965
|
+
const current = fits[index];
|
|
966
|
+
const a = previous.model;
|
|
967
|
+
const b = current.model;
|
|
968
|
+
if (a.response !== b.response || a.rows.length !== b.rows.length
|
|
969
|
+
|| a.rows.some((row, i) => row !== b.rows[i])
|
|
970
|
+
|| a.responseLevels.length !== b.responseLevels.length
|
|
971
|
+
|| a.responseLevels.some((level, i) => level !== b.responseLevels[i])
|
|
972
|
+
|| a.y.length !== b.y.length || a.y.some((value, i) => value !== b.y[i])) {
|
|
973
|
+
throw new Error("models were not all fitted to the same size of dataset");
|
|
974
|
+
}
|
|
975
|
+
if (a.method !== b.method)
|
|
976
|
+
throw new Error("models must use the same link");
|
|
977
|
+
if (a.weights.length !== b.weights.length || a.weights.some((value, i) => value !== b.weights[i])
|
|
978
|
+
|| a.offset.length !== b.offset.length || a.offset.some((value, i) => value !== b.offset[i])) {
|
|
979
|
+
throw new Error("models must use identical weights and offsets");
|
|
980
|
+
}
|
|
981
|
+
const previousColumns = new Map(a.columnNames.map((name, i) => [name, i]));
|
|
982
|
+
const currentColumns = new Map(b.columnNames.map((name, i) => [name, i]));
|
|
983
|
+
for (const [name, previousIndex] of previousColumns) {
|
|
984
|
+
const currentIndex = currentColumns.get(name);
|
|
985
|
+
if (currentIndex === undefined) {
|
|
986
|
+
throw new Error("models are not nested");
|
|
987
|
+
}
|
|
988
|
+
for (let row = 0; row < a.x.length; row++) {
|
|
989
|
+
if (a.x[row][previousIndex] !== b.x[row][currentIndex]) {
|
|
990
|
+
throw new Error("models are not nested");
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
const modelLabels = fits.map((fit) => {
|
|
996
|
+
const separator = fit.model.formula.indexOf("~");
|
|
997
|
+
return separator < 0 ? fit.model.formula : fit.model.formula.slice(separator + 1).trim().replace(/\\s+/g, " ");
|
|
998
|
+
});
|
|
999
|
+
const residualDf = fits.map((fit) => fit.nobs - fit.edf);
|
|
1000
|
+
const residualDeviance = fits.map((fit) => fit.deviance);
|
|
1001
|
+
const tests = fits.map((_, i) => i === 0 ? "" : `${i} vs ${i + 1}`);
|
|
1002
|
+
const degrees = ["NA"];
|
|
1003
|
+
const statistics = ["NA"];
|
|
1004
|
+
const probabilities = ["NA"];
|
|
1005
|
+
for (let i = 1; i < fits.length; i++) {
|
|
1006
|
+
const df = fits[i].edf - fits[i - 1].edf;
|
|
1007
|
+
if (df < 0)
|
|
1008
|
+
throw new Error("models are not nested");
|
|
1009
|
+
const statistic = df === 0 ? 0 : Math.max(0, fits[i - 1].deviance - fits[i].deviance);
|
|
1010
|
+
degrees.push(df);
|
|
1011
|
+
statistics.push(statistic);
|
|
1012
|
+
probabilities.push(df === 0 ? 1 : pchisq(statistic, df, { lowerTail: false }));
|
|
1013
|
+
}
|
|
1014
|
+
return reported("polrAnova", {
|
|
1015
|
+
table: {
|
|
1016
|
+
Model: modelLabels,
|
|
1017
|
+
"Resid. df": residualDf,
|
|
1018
|
+
"Resid. Dev": residualDeviance,
|
|
1019
|
+
Test: tests,
|
|
1020
|
+
" Df": degrees,
|
|
1021
|
+
"LR stat.": statistics,
|
|
1022
|
+
"Pr(Chi)": probabilities,
|
|
1023
|
+
},
|
|
1024
|
+
rows: fits.map((_, i) => String(i + 1)),
|
|
1025
|
+
heading: ["Likelihood ratio tests of ordinal regression models\n", `Response: ${reference.response}`],
|
|
1026
|
+
warnings,
|
|
1027
|
+
}, ...fits);
|
|
1028
|
+
}
|