@numero-uno-jpn/rstats 1.17.0 → 1.18.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 +25 -0
- package/README.ja.md +6 -6
- package/README.md +6 -6
- package/dist/causal/mediationProcedures.js +18 -1
- package/dist/causal/moderation.js +11 -2
- package/dist/causal.js +2 -2
- package/dist/chunks/{chunk-NPWWGIFG.js → chunk-2JB7F646.js} +2 -2
- package/dist/chunks/{chunk-JG4TWDQ4.js → chunk-3JFRDXN7.js} +2 -2
- package/dist/chunks/chunk-53WQDB3C.js +2 -0
- package/dist/chunks/{chunk-QCPGV7XH.js → chunk-5CTWYFMB.js} +2 -2
- package/dist/chunks/chunk-6I23C2YJ.js +2 -0
- package/dist/chunks/{chunk-6MLDKHTY.js → chunk-CTZUYKVL.js} +2 -2
- package/dist/chunks/{chunk-GOYTZ5RB.js → chunk-EC77KAAM.js} +2 -2
- package/dist/chunks/{chunk-VZSQAGL2.js → chunk-FLFNMSHI.js} +2 -2
- package/dist/chunks/{chunk-XEJX5HBJ.js → chunk-GEHMND3C.js} +2 -2
- package/dist/chunks/{chunk-KY53MB3J.js → chunk-GIK34P23.js} +2 -2
- package/dist/chunks/chunk-H6Z7JVSD.js +2 -0
- package/dist/chunks/{chunk-YMI33F7W.js → chunk-HG4LJBNV.js} +2 -2
- package/dist/chunks/chunk-HGAEVPVS.js +2 -0
- package/dist/chunks/{chunk-EIUK6TKF.js → chunk-HMLYEFQN.js} +2 -2
- package/dist/chunks/chunk-HRRCC2BD.js +2 -0
- package/dist/chunks/chunk-IBHMM2SL.js +2 -0
- package/dist/chunks/chunk-ICDW3I2F.js +2 -0
- package/dist/chunks/chunk-IKMW63BE.js +2 -0
- package/dist/chunks/{chunk-O4D43LWM.js → chunk-IOJVFYHW.js} +2 -2
- package/dist/chunks/chunk-IW4S634O.js +2 -0
- package/dist/chunks/{chunk-GIIURG5X.js → chunk-JF4PXFJE.js} +2 -2
- package/dist/chunks/chunk-JPWYGTUN.js +2 -0
- package/dist/chunks/{chunk-I2KJMF4G.js → chunk-KJMLQHCY.js} +1 -1
- package/dist/chunks/chunk-KVJBCT3D.js +2 -0
- package/dist/chunks/chunk-LCIX76FR.js +2 -0
- package/dist/chunks/chunk-LY5XGFPU.js +2 -0
- package/dist/chunks/{chunk-NCDPZSI2.js → chunk-MKZH65DK.js} +2 -2
- package/dist/chunks/{chunk-GTSK4IN4.js → chunk-MVPHISOV.js} +1 -1
- package/dist/chunks/chunk-MXZ64QME.js +2 -0
- package/dist/chunks/{chunk-NCRL33PQ.js → chunk-N7BUE54L.js} +2 -2
- package/dist/chunks/{chunk-L77QFL3C.js → chunk-NDZVVNBB.js} +2 -2
- package/dist/chunks/{chunk-EB45CDFA.js → chunk-NOTJ45G3.js} +2 -2
- package/dist/chunks/{chunk-ZRKXHVTJ.js → chunk-QUD3374N.js} +2 -2
- package/dist/chunks/{chunk-XR7Y4ZV6.js → chunk-RXYZQ3UX.js} +2 -2
- package/dist/chunks/{chunk-V54MBEJM.js → chunk-SCFFHEDZ.js} +2 -2
- package/dist/chunks/{chunk-RNGDVSTS.js → chunk-V6FMGGUV.js} +2 -2
- package/dist/chunks/{chunk-TTOJDLIQ.js → chunk-VATAUY7N.js} +2 -2
- package/dist/chunks/chunk-W5M3R4NH.js +2 -0
- package/dist/chunks/{chunk-DD2GG4EC.js → chunk-WYVUCQO3.js} +1 -1
- package/dist/chunks/{chunk-JHABMYNH.js → chunk-XQCHC3SH.js} +1 -1
- package/dist/chunks/chunk-XUMVTGMM.js +2 -0
- package/dist/chunks/{chunk-72I7GDWL.js → chunk-YXMHWS5R.js} +2 -2
- package/dist/chunks/{chunk-LKKUUREA.js → chunk-Z33Q545U.js} +2 -2
- package/dist/descriptive/qcc.d.ts +320 -0
- package/dist/descriptive/qcc.js +524 -0
- package/dist/descriptive/qccTools.d.ts +301 -0
- package/dist/descriptive/qccTools.js +390 -0
- package/dist/descriptive.js +2 -2
- package/dist/distributions.js +2 -2
- package/dist/entries/descriptive.d.ts +2 -0
- package/dist/entries/descriptive.js +2 -0
- package/dist/entries/regression.d.ts +1 -0
- package/dist/entries/regression.js +2 -0
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +2 -2
- package/dist/models/betareg.js +14 -2
- package/dist/models/bradleyterry.d.ts +188 -0
- package/dist/models/bradleyterry.js +533 -0
- package/dist/models/survreg.d.ts +5 -0
- package/dist/models/survreg.js +23 -3
- package/dist/models/tobit.js +16 -5
- package/dist/multivariate.js +2 -2
- package/dist/numerics.js +2 -2
- package/dist/regression.js +3 -3
- package/dist/rstats.js +17 -17
- package/dist/special.js +2 -2
- package/dist/tests.js +2 -2
- package/dist/timeseries.js +2 -2
- package/package.json +1 -1
- package/dist/chunks/chunk-23QCIPET.js +0 -2
- package/dist/chunks/chunk-3UEYA6VG.js +0 -2
- package/dist/chunks/chunk-3Y4DNK4O.js +0 -2
- package/dist/chunks/chunk-4BGGWQWS.js +0 -2
- package/dist/chunks/chunk-5UFVACSV.js +0 -2
- package/dist/chunks/chunk-5W2OZAHQ.js +0 -2
- package/dist/chunks/chunk-BWDXJL7T.js +0 -2
- package/dist/chunks/chunk-GLABB425.js +0 -2
- package/dist/chunks/chunk-JV3POOET.js +0 -2
- package/dist/chunks/chunk-K3YSXDTU.js +0 -2
- package/dist/chunks/chunk-LY2UZGUL.js +0 -2
- package/dist/chunks/chunk-PSQ6MLJM.js +0 -2
- package/dist/chunks/chunk-RM5D7Q7W.js +0 -2
- package/dist/chunks/chunk-SA2E5GVO.js +0 -2
- package/dist/chunks/chunk-T5ZALLTJ.js +0 -2
- package/dist/chunks/chunk-XPYZOG5H.js +0 -2
|
@@ -0,0 +1,533 @@
|
|
|
1
|
+
// Bradley-Terry models for paired comparisons (BradleyTerry2's BTm, BTabilities and countsToBinomial) and quasi
|
|
2
|
+
// variances (qvcalc's qvcalc and worstErrors). Abilities of the players, or abilities modelled by player covariates
|
|
3
|
+
// with random player effects fitted by PQL (Breslow and Clayton): the fixed point where sigma maximizes the REML
|
|
4
|
+
// likelihood of the working linear mixed model. Behaviour: oracle/qcc-bt-behaviour.md (clean room: from the packages'
|
|
5
|
+
// documentation, the papers they cite and the output of R; no source of R or of a package was read). Written for
|
|
6
|
+
// rStats.js.
|
|
7
|
+
import { pnorm, dnorm } from "../distributions/normal.js";
|
|
8
|
+
import { glm, glmSummary } from "./glm.js";
|
|
9
|
+
import { unirootCore } from "../numerics/integrate.js";
|
|
10
|
+
import { eigen } from "../linalg/eigen.js";
|
|
11
|
+
import { reported, Warnings } from "../internal/warnings.js";
|
|
12
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
13
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
14
|
+
const BTM_KEYS = /* @__PURE__ */ new Set([
|
|
15
|
+
"outcome", "player1", "player2", "formula", "predictors", "levels", "contestCovariates", "refcat", "link",
|
|
16
|
+
]);
|
|
17
|
+
const LINKS = {
|
|
18
|
+
logit: {
|
|
19
|
+
inv: (e) => (e >= 0 ? 1 / (1 + Math.exp(-e)) : Math.exp(e) / (1 + Math.exp(e))),
|
|
20
|
+
dmu: (e) => { const a = Math.exp(-Math.abs(e)); return a / (1 + a) ** 2; },
|
|
21
|
+
},
|
|
22
|
+
probit: { inv: (e) => pnorm(e), dmu: (e) => dnorm(e) },
|
|
23
|
+
cauchit: { inv: (e) => 0.5 + Math.atan(e) / Math.PI, dmu: (e) => 1 / (Math.PI * (1 + e * e)) },
|
|
24
|
+
};
|
|
25
|
+
const zeros = (r, c) => Array.from({ length: r }, () => new Array(c).fill(0));
|
|
26
|
+
function cholesky(A) {
|
|
27
|
+
const n = A.length, L = zeros(n, n);
|
|
28
|
+
for (let j = 0; j < n; j++) {
|
|
29
|
+
let s = A[j][j];
|
|
30
|
+
for (let k = 0; k < j; k++)
|
|
31
|
+
s -= L[j][k] ** 2;
|
|
32
|
+
if (!(s > 0))
|
|
33
|
+
throw new RangeError("the information matrix is not positive definite (a player or covariate is not identifiable)");
|
|
34
|
+
L[j][j] = Math.sqrt(s);
|
|
35
|
+
for (let i = j + 1; i < n; i++) {
|
|
36
|
+
let t = A[i][j];
|
|
37
|
+
for (let k = 0; k < j; k++)
|
|
38
|
+
t -= L[i][k] * L[j][k];
|
|
39
|
+
L[i][j] = t / L[j][j];
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return L;
|
|
43
|
+
}
|
|
44
|
+
function cholSolve(L, b) {
|
|
45
|
+
const n = L.length, y = new Array(n);
|
|
46
|
+
for (let i = 0; i < n; i++) {
|
|
47
|
+
let s = b[i];
|
|
48
|
+
for (let k = 0; k < i; k++)
|
|
49
|
+
s -= L[i][k] * y[k];
|
|
50
|
+
y[i] = s / L[i][i];
|
|
51
|
+
}
|
|
52
|
+
for (let i = n - 1; i >= 0; i--) {
|
|
53
|
+
let s = y[i];
|
|
54
|
+
for (let k = i + 1; k < n; k++)
|
|
55
|
+
s -= L[k][i] * y[k];
|
|
56
|
+
y[i] = s / L[i][i];
|
|
57
|
+
}
|
|
58
|
+
return y;
|
|
59
|
+
}
|
|
60
|
+
const cols = (B) => (B.length === 0 ? [] : B[0].map((_, j) => B.map((r) => r[j])));
|
|
61
|
+
const solveM = (L, B) => cols(cols(B).map((c) => cholSolve(L, c)));
|
|
62
|
+
const mul = (A, B) => A.map((r) => (B[0] ?? []).map((_, j) => r.reduce((s, v, k) => s + v * B[k][j], 0)));
|
|
63
|
+
const tr = (A) => cols(A);
|
|
64
|
+
const sub = (A, B) => A.map((r, i) => r.map((v, j) => v - B[i][j]));
|
|
65
|
+
const mv = (A, v) => A.map((r) => r.reduce((s, a, k) => s + a * v[k], 0));
|
|
66
|
+
const dot = (a, b) => a.reduce((s, v, i) => s + v * b[i], 0);
|
|
67
|
+
const inverseSpd = (A) => solveM(cholesky(A), A.map((_, i) => A.map((__, j) => (i === j ? 1 : 0))));
|
|
68
|
+
function parseBtFormula(formula) {
|
|
69
|
+
const f = formula.trim().replace(/^~/, "").trim();
|
|
70
|
+
const t = { player: false, covariates: [], contest: [], random: false };
|
|
71
|
+
if (f === "")
|
|
72
|
+
return { ...t, player: true };
|
|
73
|
+
for (const raw of f.split("+").map((s) => s.trim())) {
|
|
74
|
+
if (raw === "..")
|
|
75
|
+
t.player = true;
|
|
76
|
+
else if (/^\(\s*1\s*\|\s*\.\.\s*\)$/.test(raw))
|
|
77
|
+
t.random = true;
|
|
78
|
+
else if (/^[A-Za-z._][A-Za-z0-9._]*\[\s*\.\.\s*\]$/.test(raw))
|
|
79
|
+
t.covariates.push(raw.replace(/\s/g, "").replace(/\[\.\.\]$/, ""));
|
|
80
|
+
else if (/^[A-Za-z._][A-Za-z0-9._]*$/.test(raw))
|
|
81
|
+
t.contest.push(raw);
|
|
82
|
+
else
|
|
83
|
+
throw new RangeError(`unsupported term "${raw}" in the formula of btm`);
|
|
84
|
+
}
|
|
85
|
+
return t;
|
|
86
|
+
}
|
|
87
|
+
const column = (d, name) => {
|
|
88
|
+
const c = d[name];
|
|
89
|
+
if (!Array.isArray(c))
|
|
90
|
+
throw new RangeError(`no column "${name}"`);
|
|
91
|
+
return c;
|
|
92
|
+
};
|
|
93
|
+
const numberOf = (v) => (v === null || v === undefined ? NaN : typeof v === "boolean" ? Number(v) : Number(v));
|
|
94
|
+
/**
|
|
95
|
+
* A Bradley-Terry model for paired comparisons: the probability that player1 beats player2 is
|
|
96
|
+
* `link^-1(lambda_1 - lambda_2)`. With `"~ .."` each player has an ability (the reference's is 0) and the model is the
|
|
97
|
+
* binomial glm without intercept on the +1 / -1 design of the two players; contest-level variables add their
|
|
98
|
+
* difference. With player covariates and random player effects (`"~ x[..] + (1 | ..)"`) the abilities are
|
|
99
|
+
* `x_j' beta + e_j`, `e ~ N(0, sigma^2)`, fitted by PQL to the fixed point where sigma maximizes the REML likelihood of
|
|
100
|
+
* the working linear mixed model (BTm stops at its tolerance, about 1e-7 from it); sigma at the boundary 0 gives the
|
|
101
|
+
* glm. A player with a missing covariate gets an ability of its own (as BTm).
|
|
102
|
+
*
|
|
103
|
+
* Equivalent to `BradleyTerry2::BTm()` in R.
|
|
104
|
+
*
|
|
105
|
+
* @param contests one row per contest, or per pair with the numbers of wins
|
|
106
|
+
* @category Regression
|
|
107
|
+
*/
|
|
108
|
+
export function btm(contests, options) {
|
|
109
|
+
checkOptions(options, BTM_KEYS, "btm"); // generated: option-keys.mjs
|
|
110
|
+
const warnings = new Warnings();
|
|
111
|
+
const terms = parseBtFormula(options.formula ?? "~ ..");
|
|
112
|
+
const linkName = options.link ?? "logit";
|
|
113
|
+
const link = LINKS[linkName];
|
|
114
|
+
if (link === undefined)
|
|
115
|
+
throw new RangeError(`unknown link "${linkName}"`);
|
|
116
|
+
const p1 = column(contests, options.player1).map(String), p2 = column(contests, options.player2).map(String);
|
|
117
|
+
const levels = options.levels ? [...options.levels] : [...new Set([...p1, ...p2])].sort();
|
|
118
|
+
const index = new Map(levels.map((l, i) => [l, i]));
|
|
119
|
+
const i1 = p1.map((p) => index.get(p)), i2 = p2.map((p) => index.get(p));
|
|
120
|
+
if (i1.some((i) => i === undefined) || i2.some((i) => i === undefined))
|
|
121
|
+
throw new RangeError("a player is not among the levels");
|
|
122
|
+
const K = p1.length, q = levels.length;
|
|
123
|
+
let win1, win2;
|
|
124
|
+
if (typeof options.outcome === "string") {
|
|
125
|
+
const y = column(contests, options.outcome).map(numberOf);
|
|
126
|
+
win1 = y;
|
|
127
|
+
win2 = y.map((v) => 1 - v);
|
|
128
|
+
}
|
|
129
|
+
else {
|
|
130
|
+
win1 = column(contests, options.outcome[0]).map(numberOf);
|
|
131
|
+
win2 = column(contests, options.outcome[1]).map(numberOf);
|
|
132
|
+
}
|
|
133
|
+
const refcat = options.refcat ?? levels[0];
|
|
134
|
+
if (!index.has(refcat))
|
|
135
|
+
throw new RangeError(`refcat "${refcat}" is not a player`);
|
|
136
|
+
if (terms.random && terms.covariates.length === 0) {
|
|
137
|
+
throw new RangeError("Predictor variables are not of the correct length --they probably need indexing in 'formula'.");
|
|
138
|
+
}
|
|
139
|
+
if (terms.player && (terms.covariates.length > 0 || terms.random)) {
|
|
140
|
+
throw new RangeError("btm: abilities by player and by player covariates together are not supported");
|
|
141
|
+
}
|
|
142
|
+
// player covariates; players with a missing value get a separate ability
|
|
143
|
+
const covs = terms.covariates.map((name) => {
|
|
144
|
+
if (options.predictors === undefined)
|
|
145
|
+
throw new RangeError(`btm: the covariate "${name}" needs 'predictors'`);
|
|
146
|
+
const c = column(options.predictors, name).map(numberOf);
|
|
147
|
+
if (c.length !== q)
|
|
148
|
+
throw new RangeError("Predictor variables are not of the correct length --they probably need indexing in 'formula'.");
|
|
149
|
+
return c;
|
|
150
|
+
});
|
|
151
|
+
const separateIdx = levels.map((_, j) => j).filter((j) => covs.some((c) => Number.isNaN(c[j])));
|
|
152
|
+
if (covs.length > 0 && !terms.random)
|
|
153
|
+
warnings.add("Ability modelled by predictors but no random effects");
|
|
154
|
+
// the fixed design (contests x coefficients) and how the abilities are formed (players x coefficients)
|
|
155
|
+
const names = [], Xcols = [], abilityRows = levels.map(() => []);
|
|
156
|
+
const addAbilityColumn = (name, perPlayer) => {
|
|
157
|
+
names.push(name);
|
|
158
|
+
Xcols.push(Array.from({ length: K }, (_, k) => perPlayer(i1[k]) - perPlayer(i2[k])));
|
|
159
|
+
levels.forEach((_, j) => abilityRows[j].push(perPlayer(j)));
|
|
160
|
+
};
|
|
161
|
+
if (terms.player) {
|
|
162
|
+
levels.forEach((l, j) => { if (l !== refcat)
|
|
163
|
+
addAbilityColumn(`..${l}`, (i) => (i === j ? 1 : 0)); });
|
|
164
|
+
}
|
|
165
|
+
for (const j of separateIdx)
|
|
166
|
+
addAbilityColumn(`..${levels[j]}`, (i) => (i === j ? 1 : 0));
|
|
167
|
+
terms.covariates.forEach((name, t) => {
|
|
168
|
+
const c = covs[t].map((v, j) => (separateIdx.includes(j) ? 0 : v));
|
|
169
|
+
addAbilityColumn(`${name}[..]`, (i) => c[i]);
|
|
170
|
+
});
|
|
171
|
+
for (const name of terms.contest) {
|
|
172
|
+
const pair = options.contestCovariates?.[name];
|
|
173
|
+
if (pair === undefined)
|
|
174
|
+
throw new RangeError(`btm: the contest variable "${name}" needs contestCovariates`);
|
|
175
|
+
const a = column(contests, pair[0]).map(numberOf), b = column(contests, pair[1]).map(numberOf);
|
|
176
|
+
names.push(name);
|
|
177
|
+
Xcols.push(a.map((v, k) => v - b[k]));
|
|
178
|
+
levels.forEach((_, j) => abilityRows[j].push(0));
|
|
179
|
+
}
|
|
180
|
+
Xcols.forEach((c, j) => {
|
|
181
|
+
if (terms.random && c.every((v) => v === 0))
|
|
182
|
+
throw new RangeError(`btm: "${names[j]}" does not vary between the players of any contest (not identifiable)`);
|
|
183
|
+
});
|
|
184
|
+
const X = Array.from({ length: K }, (_, k) => Xcols.map((c) => c[k]));
|
|
185
|
+
const n = win1.map((w, k) => w + win2[k]);
|
|
186
|
+
const y = win1.map((w, k) => w / n[k]);
|
|
187
|
+
const g = glmFit(X, win1, win2, linkName);
|
|
188
|
+
const base = {
|
|
189
|
+
coefNames: names, levels, refcat, link: linkName, abilityDesign: abilityRows,
|
|
190
|
+
separate: separateIdx.map((j) => levels[j]),
|
|
191
|
+
};
|
|
192
|
+
if (!terms.random) {
|
|
193
|
+
for (const w of g.warnings)
|
|
194
|
+
warnings.add(w);
|
|
195
|
+
return reported("btm", {
|
|
196
|
+
...base, coefficients: g.coef, stdError: g.se, statistic: g.coef.map((b, i) => b / g.se[i]),
|
|
197
|
+
pValue: g.coef.map((b, i) => 2 * pnorm(-Math.abs(b / g.se[i]))), vcov: g.vcov, deviance: g.deviance,
|
|
198
|
+
nullDeviance: g.nullDeviance, aic: g.aic, dfResidual: g.dfResidual, dfNull: g.dfNull, iter: g.iter,
|
|
199
|
+
converged: g.converged, fittedValues: g.fitted, linearPredictors: g.eta, sigma: null, varSigma: null,
|
|
200
|
+
random: null, warnings: warnings.list,
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
// random effects: Z (contests x players) without the columns of the separate players
|
|
204
|
+
const keep = levels.map((_, j) => j).filter((j) => !separateIdx.includes(j));
|
|
205
|
+
const col = new Map(keep.map((j, t) => [j, t]));
|
|
206
|
+
const Z = { q: keep.length, cols: [], vals: [] };
|
|
207
|
+
for (let k = 0; k < K; k++) {
|
|
208
|
+
const c = [], v = [];
|
|
209
|
+
if (col.has(i1[k])) {
|
|
210
|
+
c.push(col.get(i1[k]));
|
|
211
|
+
v.push(1);
|
|
212
|
+
}
|
|
213
|
+
if (col.has(i2[k])) {
|
|
214
|
+
c.push(col.get(i2[k]));
|
|
215
|
+
v.push(-1);
|
|
216
|
+
}
|
|
217
|
+
Z.cols.push(c);
|
|
218
|
+
Z.vals.push(v);
|
|
219
|
+
}
|
|
220
|
+
let pql;
|
|
221
|
+
try {
|
|
222
|
+
pql = fitPql(X, Z, y, n, link, g.coef);
|
|
223
|
+
}
|
|
224
|
+
catch (err) {
|
|
225
|
+
// the working weights vanish when the outcomes are separated (every contest won by one side): no finite estimates
|
|
226
|
+
if (err instanceof RangeError && /not positive definite/.test(err.message)) {
|
|
227
|
+
throw new RangeError("btm: PQL failed: the working weights vanish (separated outcomes, no finite estimates)");
|
|
228
|
+
}
|
|
229
|
+
throw err;
|
|
230
|
+
}
|
|
231
|
+
// at sigma = 0 the fit is the glm's, with its warnings (separation among them)
|
|
232
|
+
if (pql.sigma === 0)
|
|
233
|
+
for (const w of g.warnings)
|
|
234
|
+
warnings.add(w);
|
|
235
|
+
const randomAll = levels.map(() => 0);
|
|
236
|
+
keep.forEach((j, t) => { randomAll[j] = pql.e[t]; });
|
|
237
|
+
const se = pql.varFix.map((r, i) => Math.sqrt(r[i]));
|
|
238
|
+
return reported("btm", {
|
|
239
|
+
...base, coefficients: pql.beta, stdError: se, statistic: pql.beta.map((b, i) => b / se[i]),
|
|
240
|
+
pValue: pql.beta.map((b, i) => 2 * pnorm(-Math.abs(b / se[i]))), vcov: pql.varFix, deviance: NaN,
|
|
241
|
+
nullDeviance: NaN, aic: NaN, dfResidual: K - names.length, dfNull: K, iter: pql.iter, converged: pql.converged,
|
|
242
|
+
fittedValues: pql.eta.map(link.inv), linearPredictors: pql.eta, sigma: pql.sigma,
|
|
243
|
+
varSigma: pql.sigma === 0 ? null : pql.varSigma, random: randomAll, warnings: warnings.list,
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
/** The binomial glm without intercept */
|
|
247
|
+
function glmFit(X, win1, win2, link) {
|
|
248
|
+
const fit = glm(X, win1.map((w, k) => [w, win2[k]]), { family: "binomial", link: link, intercept: false });
|
|
249
|
+
const s = glmSummary(fit);
|
|
250
|
+
// aliased coefficients (players not connected to the reference) are NaN, as R's NA; the summary leaves them out
|
|
251
|
+
const ok = fit.coefficients.map((b) => !Number.isNaN(b));
|
|
252
|
+
const pos = ok.map((o, i) => (o ? ok.slice(0, i).filter(Boolean).length : -1));
|
|
253
|
+
const se = pos.map((k) => (k < 0 ? NaN : s.stdError[k]));
|
|
254
|
+
const vcov = pos.map((a) => pos.map((b) => (a < 0 || b < 0 ? NaN : s.covScaled[a][b])));
|
|
255
|
+
return {
|
|
256
|
+
coef: fit.coefficients, se, vcov, deviance: fit.deviance, nullDeviance: fit.nullDeviance,
|
|
257
|
+
aic: fit.aic, dfResidual: fit.dfResidual, dfNull: fit.dfNull, iter: fit.iter, converged: fit.converged,
|
|
258
|
+
fitted: fit.fittedValues, eta: fit.linearPredictors, warnings: fit.warnings,
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
const EPS = 2.220446049250313e-16;
|
|
262
|
+
/** The working weights and response; mu kept in [eps, 1 - eps] and dmu/deta at least eps (as R's binomial family) */
|
|
263
|
+
function working(X, Z, y, n, link, beta, e) {
|
|
264
|
+
const K = X.length;
|
|
265
|
+
const eta = new Array(K), w = new Array(K), z = new Array(K);
|
|
266
|
+
for (let k = 0; k < K; k++) {
|
|
267
|
+
let v = dot(X[k], beta);
|
|
268
|
+
const c = Z.cols[k], a = Z.vals[k];
|
|
269
|
+
for (let t = 0; t < c.length; t++)
|
|
270
|
+
v += a[t] * e[c[t]];
|
|
271
|
+
const mu = Math.min(1 - EPS, Math.max(EPS, link.inv(v))), d = Math.max(EPS, link.dmu(v));
|
|
272
|
+
eta[k] = v;
|
|
273
|
+
w[k] = n[k] * d * d / (mu * (1 - mu));
|
|
274
|
+
z[k] = v + (y[k] - mu) / d;
|
|
275
|
+
}
|
|
276
|
+
return { eta, w, z };
|
|
277
|
+
}
|
|
278
|
+
/** X'WX, Z'WX, Z'WZ, X'Wz and Z'Wz, using the sparsity of Z */
|
|
279
|
+
function crossProducts(X, Z, w, z) {
|
|
280
|
+
const K = X.length, p = X[0].length, q = Z.q;
|
|
281
|
+
const C = zeros(p, p), B = zeros(q, p), A = zeros(q, q), bx = new Array(p).fill(0), a = new Array(q).fill(0);
|
|
282
|
+
for (let k = 0; k < K; k++) {
|
|
283
|
+
const x = X[k], wk = w[k], c = Z.cols[k], v = Z.vals[k];
|
|
284
|
+
for (let i = 0; i < p; i++) {
|
|
285
|
+
const wx = wk * x[i];
|
|
286
|
+
bx[i] = bx[i] + wx * z[k];
|
|
287
|
+
for (let j = 0; j <= i; j++)
|
|
288
|
+
C[i][j] = C[i][j] + wx * x[j];
|
|
289
|
+
}
|
|
290
|
+
for (let t = 0; t < c.length; t++) {
|
|
291
|
+
const r = c[t], wv = wk * v[t];
|
|
292
|
+
a[r] = a[r] + wv * z[k];
|
|
293
|
+
for (let j = 0; j < p; j++)
|
|
294
|
+
B[r][j] = B[r][j] + wv * x[j];
|
|
295
|
+
for (let u = 0; u < c.length; u++)
|
|
296
|
+
A[r][c[u]] = A[r][c[u]] + wv * v[u];
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
for (let i = 0; i < p; i++)
|
|
300
|
+
for (let j = 0; j < i; j++)
|
|
301
|
+
C[j][i] = C[i][j];
|
|
302
|
+
return { A, B, C, a, bx };
|
|
303
|
+
}
|
|
304
|
+
/** Penalized IWLS given sigma (Henderson's equations), from a start */
|
|
305
|
+
function pirls(X, Z, y, n, link, sigma, start) {
|
|
306
|
+
const p = X[0].length, q = Z.q;
|
|
307
|
+
let beta = [...start.beta], e = sigma === 0 ? new Array(q).fill(0) : [...start.e];
|
|
308
|
+
for (let it = 0; it < 500; it++) {
|
|
309
|
+
const { w, z } = working(X, Z, y, n, link, beta, e);
|
|
310
|
+
const { A, B, C, a, bx } = crossProducts(X, Z, w, z);
|
|
311
|
+
let nb, ne;
|
|
312
|
+
if (sigma === 0) {
|
|
313
|
+
nb = cholSolve(cholesky(C), bx);
|
|
314
|
+
ne = e;
|
|
315
|
+
}
|
|
316
|
+
else {
|
|
317
|
+
const dim = p + q, H = zeros(dim, dim);
|
|
318
|
+
for (let i = 0; i < p; i++)
|
|
319
|
+
for (let j = 0; j < p; j++)
|
|
320
|
+
H[i][j] = C[i][j];
|
|
321
|
+
for (let r = 0; r < q; r++)
|
|
322
|
+
for (let j = 0; j < p; j++) {
|
|
323
|
+
H[p + r][j] = B[r][j];
|
|
324
|
+
H[j][p + r] = B[r][j];
|
|
325
|
+
}
|
|
326
|
+
for (let r = 0; r < q; r++)
|
|
327
|
+
for (let u = 0; u < q; u++)
|
|
328
|
+
H[p + r][p + u] = A[r][u] + (r === u ? 1 / sigma ** 2 : 0);
|
|
329
|
+
const sol = cholSolve(cholesky(H), [...bx, ...a]);
|
|
330
|
+
nb = sol.slice(0, p);
|
|
331
|
+
ne = sol.slice(p);
|
|
332
|
+
}
|
|
333
|
+
const change = Math.max(...nb.map((v, i) => Math.abs(v - beta[i]) / (1 + Math.abs(v))), ...ne.map((v, i) => Math.abs(v - e[i]) / (1 + Math.abs(v))));
|
|
334
|
+
beta = nb;
|
|
335
|
+
e = ne;
|
|
336
|
+
if (change < 1e-14)
|
|
337
|
+
break;
|
|
338
|
+
}
|
|
339
|
+
return { beta, e, ...working(X, Z, y, n, link, beta, e) };
|
|
340
|
+
}
|
|
341
|
+
/**
|
|
342
|
+
* The quantities of the working linear mixed model at sigma, by Woodbury in the dimension of the players: with
|
|
343
|
+
* M = Z'WZ + I / sigma^2, Z'V^-1 Z = (I - M^-1 / sigma^2) / sigma^2, Z'V^-1 X = M^-1 Z'WX / sigma^2,
|
|
344
|
+
* X'V^-1 X = X'WX - X'WZ M^-1 Z'WX (one inverse of M per evaluation).
|
|
345
|
+
*/
|
|
346
|
+
function workingModel(X, Z, s, sigma) {
|
|
347
|
+
const { A, B, C, a, bx } = crossProducts(X, Z, s.w, s.z);
|
|
348
|
+
const q = Z.q;
|
|
349
|
+
let ZVZ = A, ZVX = B, XVX = C, ZVz = a, XVz = bx;
|
|
350
|
+
if (sigma > 0) {
|
|
351
|
+
const s2 = sigma ** 2;
|
|
352
|
+
const Mi = inverseSpd(A.map((r, i) => r.map((v, j) => v + (i === j ? 1 / s2 : 0))));
|
|
353
|
+
const MiB = mul(Mi, B), Mia = mv(Mi, a);
|
|
354
|
+
ZVZ = Mi.map((r, i) => r.map((v, j) => ((i === j ? 1 : 0) - v / s2) / s2));
|
|
355
|
+
ZVX = MiB.map((r) => r.map((v) => v / s2));
|
|
356
|
+
XVX = sub(C, mul(tr(B), MiB));
|
|
357
|
+
ZVz = Mia.map((v) => v / s2);
|
|
358
|
+
XVz = bx.map((v, i) => v - B.reduce((acc, r, k) => acc + r[i] * Mia[k], 0));
|
|
359
|
+
}
|
|
360
|
+
const varFix = inverseSpd(XVX);
|
|
361
|
+
const g = mv(varFix, XVz);
|
|
362
|
+
const ZPz = ZVz.map((v, i) => v - dot(ZVX[i], g));
|
|
363
|
+
const T = mul(ZVX, varFix);
|
|
364
|
+
let trace = 0, frob = 0;
|
|
365
|
+
for (let i = 0; i < q; i++)
|
|
366
|
+
for (let j = 0; j < q; j++) {
|
|
367
|
+
const v = ZVZ[i][j] - dot(T[i], ZVX[j]);
|
|
368
|
+
if (i === j)
|
|
369
|
+
trace += v;
|
|
370
|
+
frob += v * v;
|
|
371
|
+
}
|
|
372
|
+
return { varFix, score: 0.5 * (dot(ZPz, ZPz) - trace), info: 0.5 * frob };
|
|
373
|
+
}
|
|
374
|
+
/**
|
|
375
|
+
* PQL: sigma solves the REML score equation of the working model at the PIRLS working response for that sigma (the
|
|
376
|
+
* fixed point of BTm's alternation of IWLS and Fisher scoring for sigma); 0 when the score at 0 is not positive.
|
|
377
|
+
*/
|
|
378
|
+
function fitPql(X, Z, y, n, link, beta0) {
|
|
379
|
+
let cur = pirls(X, Z, y, n, link, 0, { beta: beta0, e: new Array(Z.q).fill(0) });
|
|
380
|
+
let iter = 0;
|
|
381
|
+
const F = (sigma) => {
|
|
382
|
+
iter++;
|
|
383
|
+
cur = pirls(X, Z, y, n, link, sigma, cur);
|
|
384
|
+
return workingModel(X, Z, cur, sigma).score;
|
|
385
|
+
};
|
|
386
|
+
let sigma = 0;
|
|
387
|
+
if (F(0) > 0) {
|
|
388
|
+
let lo = 0, hi = 0.5;
|
|
389
|
+
while (F(hi) > 0 && hi < 1e6) {
|
|
390
|
+
lo = hi;
|
|
391
|
+
hi *= 2;
|
|
392
|
+
}
|
|
393
|
+
sigma = unirootCore(F, lo, hi, { tol: 1e-15, maxiter: 1000 }).root;
|
|
394
|
+
}
|
|
395
|
+
cur = pirls(X, Z, y, n, link, sigma, cur);
|
|
396
|
+
const wm = workingModel(X, Z, cur, sigma);
|
|
397
|
+
return { ...cur, sigma, varFix: wm.varFix, varSigma: sigma > 0 ? 1 / (4 * sigma ** 2 * wm.info) : NaN, iter, converged: true };
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* The abilities of the players of a Bradley-Terry model. They are the estimated abilities with the reference at 0,
|
|
401
|
+
* or, for abilities modelled by player covariates, `x_j' beta` (without the random effects) with
|
|
402
|
+
* standard errors from the covariance of beta; contest-level variables are taken as 0.
|
|
403
|
+
*
|
|
404
|
+
* Equivalent to `BradleyTerry2::BTabilities()` in R.
|
|
405
|
+
* @category Regression
|
|
406
|
+
*/
|
|
407
|
+
export function btAbilities(fit) {
|
|
408
|
+
const A = fit.abilityDesign;
|
|
409
|
+
// only the coefficients a player's ability uses: an aliased coefficient (a player without contests, NaN) makes
|
|
410
|
+
// that player's ability NaN, not everyone's
|
|
411
|
+
const used = (r, v) => r.reduce((acc, a, k) => (a === 0 ? acc : acc + a * v[k]), 0);
|
|
412
|
+
const ability = A.map((r) => used(r, fit.coefficients));
|
|
413
|
+
const vcov = A.map((r) => A.map((s) => used(r, fit.vcov.map((row) => used(s, row)))));
|
|
414
|
+
return { levels: [...fit.levels], ability, se: vcov.map((r, i) => Math.sqrt(Math.max(0, r[i]))), vcov, separate: [...fit.separate] };
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
417
|
+
* The wins of each pair of players from a table of wins. The rows of the table are the winners, the columns the
|
|
418
|
+
* losers. One row per pair i < j (in the order of the levels) that met at least once.
|
|
419
|
+
*
|
|
420
|
+
* Equivalent to `BradleyTerry2::countsToBinomial()` in R.
|
|
421
|
+
* @category Regression
|
|
422
|
+
*/
|
|
423
|
+
export function countsToBinomial(table, levels) {
|
|
424
|
+
const k = levels.length;
|
|
425
|
+
if (table.length !== k || table.some((r) => r.length !== k))
|
|
426
|
+
throw new RangeError("the table must be square with one row per level");
|
|
427
|
+
const out = { player1: [], player2: [], win1: [], win2: [] };
|
|
428
|
+
for (let i = 0; i < k; i++)
|
|
429
|
+
for (let j = i + 1; j < k; j++) {
|
|
430
|
+
const a = table[i][j], b = table[j][i];
|
|
431
|
+
if (a + b === 0)
|
|
432
|
+
continue;
|
|
433
|
+
out.player1.push(levels[i]);
|
|
434
|
+
out.player2.push(levels[j]);
|
|
435
|
+
out.win1.push(a);
|
|
436
|
+
out.win2.push(b);
|
|
437
|
+
}
|
|
438
|
+
return out;
|
|
439
|
+
}
|
|
440
|
+
/**
|
|
441
|
+
* Quasi variances (Firth 2003). They are the q_j minimizing `sum_{i<j} (log(q_i + q_j) - log var(b_i - b_j))^2`,
|
|
442
|
+
* so that `q_i + q_j` approximates the variance of every simple contrast. Accepts the abilities of a Bradley-Terry
|
|
443
|
+
* model or estimates with their covariance matrix.
|
|
444
|
+
*
|
|
445
|
+
* Equivalent to `qvcalc::qvcalc()` in R.
|
|
446
|
+
* @category Regression
|
|
447
|
+
*/
|
|
448
|
+
export function qvcalc(object) {
|
|
449
|
+
const est = "ability" in object ? object.ability : [...object.estimate];
|
|
450
|
+
const V = object.vcov.map((r) => [...r]);
|
|
451
|
+
const names = "levels" in object ? object.levels : object.names ? [...object.names] : est.map((_, i) => String(i + 1));
|
|
452
|
+
const k = est.length;
|
|
453
|
+
if (k < 3)
|
|
454
|
+
throw new RangeError("qvcalc needs at least 3 levels");
|
|
455
|
+
if (V.some((r) => r.some((v) => !Number.isFinite(v))))
|
|
456
|
+
throw new RangeError("qvcalc: the covariance matrix has missing values");
|
|
457
|
+
const pairs = [];
|
|
458
|
+
for (let i = 0; i < k; i++)
|
|
459
|
+
for (let j = i + 1; j < k; j++)
|
|
460
|
+
pairs.push([i, j]);
|
|
461
|
+
const v = pairs.map(([i, j]) => V[i][i] + V[j][j] - 2 * V[i][j]);
|
|
462
|
+
// Gauss-Newton with damping on log q (the least squares problem is smooth and small)
|
|
463
|
+
let lq = names.map((_, i) => Math.log(Math.max(V[i][i], 1e-12 * Math.max(...v)) || Math.max(...v) / 2));
|
|
464
|
+
const resid = (l) => pairs.map(([i, j], t) => Math.log(Math.exp(l[i]) + Math.exp(l[j])) - Math.log(v[t]));
|
|
465
|
+
let r = resid(lq), ss = dot(r, r), lambda = 1e-3;
|
|
466
|
+
for (let it = 0; it < 500; it++) {
|
|
467
|
+
const J = pairs.map(([i, j]) => {
|
|
468
|
+
const qi = Math.exp(lq[i]), qj = Math.exp(lq[j]), row = new Array(k).fill(0);
|
|
469
|
+
row[i] = qi / (qi + qj);
|
|
470
|
+
row[j] = qj / (qi + qj);
|
|
471
|
+
return row;
|
|
472
|
+
});
|
|
473
|
+
const JtJ = tr(J).map((c) => tr(J).map((d) => dot(c, d)));
|
|
474
|
+
const Jtr = tr(J).map((c) => dot(c, r));
|
|
475
|
+
let improved = false;
|
|
476
|
+
for (let tries = 0; tries < 60; tries++) {
|
|
477
|
+
const Aa = JtJ.map((row, i) => row.map((x, j) => x + (i === j ? lambda * (1 + JtJ[i][i]) : 0)));
|
|
478
|
+
const step = cholSolve(cholesky(Aa), Jtr);
|
|
479
|
+
const next = lq.map((x, i) => x - step[i]);
|
|
480
|
+
const rn = resid(next), sn = dot(rn, rn);
|
|
481
|
+
if (sn <= ss) {
|
|
482
|
+
const done = Math.max(...step.map(Math.abs)) < 1e-14;
|
|
483
|
+
lq = next;
|
|
484
|
+
r = rn;
|
|
485
|
+
ss = sn;
|
|
486
|
+
lambda = Math.max(lambda / 10, 1e-12);
|
|
487
|
+
improved = true;
|
|
488
|
+
if (done)
|
|
489
|
+
it = 1e9;
|
|
490
|
+
break;
|
|
491
|
+
}
|
|
492
|
+
lambda *= 10;
|
|
493
|
+
}
|
|
494
|
+
if (!improved)
|
|
495
|
+
break;
|
|
496
|
+
}
|
|
497
|
+
const quasiVar = lq.map(Math.exp);
|
|
498
|
+
const relerrs = pairs.map(([i, j], t) => Math.sqrt((quasiVar[i] + quasiVar[j]) / v[t]) - 1);
|
|
499
|
+
return {
|
|
500
|
+
names: [...names], estimate: [...est], se: names.map((_, i) => Math.sqrt(V[i][i])), quasiSE: quasiVar.map(Math.sqrt),
|
|
501
|
+
quasiVar, relerrs, relerrsNames: pairs.map(([i, j]) => `${names[i]},${names[j]}`), covmat: V,
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
/**
|
|
505
|
+
* The worst relative errors of the quasi standard errors over all contrasts. They are the square roots
|
|
506
|
+
* of the extreme eigenvalues of `(C'VC)^-1 C'QC` minus 1, over a basis C of the contrasts, Q = diag(quasiVar).
|
|
507
|
+
*
|
|
508
|
+
* Equivalent to `qvcalc::worstErrors()` in R.
|
|
509
|
+
* @category Regression
|
|
510
|
+
*/
|
|
511
|
+
export function worstErrors(qv) {
|
|
512
|
+
const k = qv.quasiVar.length;
|
|
513
|
+
const C = Array.from({ length: k }, (_, i) => Array.from({ length: k - 1 }, (__, j) => (i === j ? 1 : i === k - 1 ? -1 : 0)));
|
|
514
|
+
const CVC = mul(mul(tr(C), qv.covmat), C);
|
|
515
|
+
const CQC = mul(mul(tr(C), qv.quasiVar.map((qq, i) => qv.quasiVar.map((_, j) => (i === j ? qq : 0)))), C);
|
|
516
|
+
// L^-1 CQC L^-T (symmetric) has the eigenvalues of (C'VC)^-1 C'QC
|
|
517
|
+
const Li = lowerInverse(cholesky(CVC));
|
|
518
|
+
const S = mul(mul(Li, CQC), tr(Li));
|
|
519
|
+
const values = eigen(S.map((r, i) => r.map((v, j) => (v + S[j][i]) / 2)), { symmetric: true, onlyValues: true }).values;
|
|
520
|
+
return [Math.sqrt(Math.min(...values)) - 1, Math.sqrt(Math.max(...values)) - 1];
|
|
521
|
+
}
|
|
522
|
+
/** L^-1 of a lower triangular L, by forward substitution */
|
|
523
|
+
function lowerInverse(L) {
|
|
524
|
+
const n = L.length, R = zeros(n, n);
|
|
525
|
+
for (let c = 0; c < n; c++)
|
|
526
|
+
for (let i = 0; i < n; i++) {
|
|
527
|
+
let s = i === c ? 1 : 0;
|
|
528
|
+
for (let k = 0; k < i; k++)
|
|
529
|
+
s -= L[i][k] * R[k][c];
|
|
530
|
+
R[i][c] = s / L[i][i];
|
|
531
|
+
}
|
|
532
|
+
return R;
|
|
533
|
+
}
|
package/dist/models/survreg.d.ts
CHANGED
|
@@ -154,6 +154,11 @@ export interface SurvregResidualsOptions {
|
|
|
154
154
|
type?: "response" | "deviance" | "working" | "dfbeta" | "dfbetas" | "ldcase" | "ldresp" | "ldshape" | "matrix";
|
|
155
155
|
weighted?: boolean;
|
|
156
156
|
}
|
|
157
|
+
/** The covariance in the fit's scaled coordinates (coefficient j times 2^xExponent[j]), for statistics of covariates far from 1 in size */
|
|
158
|
+
export declare function survregScaledState(fit: SurvregResult): {
|
|
159
|
+
V: number[][];
|
|
160
|
+
xExponent: number[];
|
|
161
|
+
} | undefined;
|
|
157
162
|
/**
|
|
158
163
|
* Fit a parametric survival regression model. Equivalent to R's `survival::survreg()`.
|
|
159
164
|
*
|
package/dist/models/survreg.js
CHANGED
|
@@ -19,6 +19,8 @@ const SURVREG_CONTROL_KEYS = ["maxiter", "relTolerance", "tolerChol"];
|
|
|
19
19
|
const SURVREG_PREDICT_KEYS = ["type", "p", "newX", "newStrata", "newOffset", "seFit"];
|
|
20
20
|
const SURVREG_RESIDUALS_KEYS = ["type", "weighted"];
|
|
21
21
|
const survregNumericState = new WeakMap();
|
|
22
|
+
/** The covariance in the fit's scaled coordinates (coefficient j times 2^xExponent[j]), for statistics of covariates far from 1 in size */
|
|
23
|
+
export function survregScaledState(fit) { return survregNumericState.get(fit); }
|
|
22
24
|
const LOG2PI = Math.log(2 * Math.PI);
|
|
23
25
|
const safelyNumber = (x) => Number(x);
|
|
24
26
|
const log1mexp = (x) => x < -Math.LN2 ? Math.log1p(-Math.exp(x)) : Math.log(-Math.expm1(x));
|
|
@@ -655,11 +657,29 @@ export function survreg(time, event, x = [], options = {}) {
|
|
|
655
657
|
}
|
|
656
658
|
catch { }
|
|
657
659
|
}
|
|
658
|
-
|
|
660
|
+
let model = isNull ? nullFit : fitCore(X, yy, lo, hi, st, ww, oo, sid, k, d, nu, fixed, start, maxiter, tol, control.tolerChol ?? 1e-10);
|
|
661
|
+
// A covariate with a large common value (x + 1e8) is collinear with the intercept to the Cholesky tolerance, though
|
|
662
|
+
// R's survreg fits it (experiments/qccbt118-old-extreme.R): when a coefficient comes out aliased, fit again with the
|
|
663
|
+
// covariates centred and take the intercept and the covariance back exactly (b0 = b0c - sum c_j b_j, V = T Vc T').
|
|
664
|
+
// Ordinary fits are not refitted, so their iterations stay R's.
|
|
665
|
+
if (!isNull && intercept && p > 1 && model.z.slice(1, p).some(Number.isNaN)) {
|
|
666
|
+
const c = Array.from({ length: p }, (_, j) => j === 0 ? 0 : X.reduce((s, r) => s + r[j], 0) / X.length);
|
|
667
|
+
const Xc = X.map(r => r.map((v, j) => v - c[j])), startC = start.slice();
|
|
668
|
+
startC[0] = start[0] + c.reduce((s, cj, j) => s + cj * start[j], 0);
|
|
669
|
+
const refit = fitCore(Xc, yy, lo, hi, st, ww, oo, sid, k, d, nu, fixed, startC, maxiter, tol, control.tolerChol ?? 1e-10);
|
|
670
|
+
if (!refit.z.slice(0, p).some(Number.isNaN)) {
|
|
671
|
+
const q2 = refit.b.length, T = Array.from({ length: q2 }, (_, i) => Array.from({ length: q2 }, (_, j) => i === j ? 1 : i === 0 && j > 0 && j < p ? -c[j] : 0));
|
|
672
|
+
const b = matVec(T, refit.b), V = T.map(r => T.map(t => dot(r, matVec(refit.V, t))));
|
|
673
|
+
model = { ...refit, b, V, VScaled: V.map(r => r.slice()), xExponent: Array(p).fill(0), z: V.map((r, j) => r[j] > 0 ? b[j] / Math.sqrt(r[j]) : NaN) };
|
|
674
|
+
}
|
|
675
|
+
}
|
|
659
676
|
const jac = logTime ? rows.reduce((s, orig, j) => s + (st[j] === 1 ? ww[j] * Math.log(time[orig]) : 0), 0) * -1 : 0;
|
|
660
677
|
const varmat = model.V.map(r => r.slice());
|
|
661
678
|
const coefs = model.b.slice(0, p).map((v, j) => Number.isNaN(model.z[j]) ? NaN : v);
|
|
662
|
-
|
|
679
|
+
// standard errors from the scaled covariance: for a covariate near 1e+-300 its variance (1e-+600) is not a double, the
|
|
680
|
+
// standard error is
|
|
681
|
+
const seOf = (j) => { const v = model.VScaled[j]?.[j] ?? 0; return v === 0 ? 0 : ldexpWide(Math.sqrt(Math.max(0, v)), j < p ? -model.xExponent[j] : 0); };
|
|
682
|
+
const ses = coefs.map((_, j) => seOf(j));
|
|
663
683
|
const zstat = coefs.map((_, j) => model.z[j]);
|
|
664
684
|
const pv = zstat.map(v => 2 * pnorm(-Math.abs(v)));
|
|
665
685
|
const scales = fixed !== undefined ? [fixed] : Array.from({ length: k }, (_, s) => Math.exp(model.b[p + s]));
|
|
@@ -668,7 +688,7 @@ export function survreg(time, event, x = [], options = {}) {
|
|
|
668
688
|
const lp = X.map((r, i) => dot(r, model.b.slice(0, p)) + oo[i]);
|
|
669
689
|
const chi = 2 * ((model.ll + jac) - (nullFit.ll + jac)), chiDf = p + (fixed === undefined ? k : 0) - (1 + (fixed === undefined ? k : 0));
|
|
670
690
|
const tableNames = [...coefs.map((_, j) => j === 0 && intercept ? "(Intercept)" : `x${j + (intercept ? 0 : 1)}`), ...(fixed === undefined ? (k === 1 ? ["Log(scale)"] : lev) : [])];
|
|
671
|
-
const values = [...coefs, ...(fixed === undefined ? model.b.slice(p) : [])], seAll = values.map((_, j) => (
|
|
691
|
+
const values = [...coefs, ...(fixed === undefined ? model.b.slice(p) : [])], seAll = values.map((_, j) => seOf(j)), zAll = values.map((_, j) => model.z[j]), pAll = zAll.map(v => 2 * pnorm(-Math.abs(v)));
|
|
672
692
|
const result = { coefficients: coefs, coefNames: tableNames.slice(0, p), scale: scales, table: { value: values, se: seAll, z: zAll, p: pAll }, strataLevels: lev.map(s => strataIn.find(v => String(v) === s)), hasOffset: options.offset !== undefined, icoef: fixed === undefined || rows.length === 1 ? nullFit.b.slice() : [nullFit.b[0], Math.log(fixed)], var: varmat, loglik: [nullFit.ll + jac, model.ll + jac], iter: model.iter, df: p + (fixed === undefined ? k : 0), idf: 1 + (fixed === undefined ? k : 0), dfResidual: rows.length - (p + (fixed === undefined ? k : 0)), n: rows.length, linearPredictors: lp, means, score: model.score.slice(), tableRowNames: tableNames, value: values, se: seAll, z: zAll, p: pAll, chi, chiDf, chiP: pchisq(chi, chiDf, { lowerTail: false }), dist: d, distributionDf: nu, parms: nu, intercept, x: X, offset: oo, rows, weights: ww, strata: sid, y: yy, lower: lo, upper: hi, status: st, type, warnings: [...dataWarnings, ...(model.warn || nullFit.warn ? ["Ran out of iterations and did not converge"] : []), ...(d === "exponential" && options.scale !== undefined && options.scale > 0 ? ["Exponential has a fixed scale, user specified value ignored"] : [])] };
|
|
673
693
|
survregNumericState.set(result, { V: model.VScaled, xExponent: model.xExponent });
|
|
674
694
|
return reported("survreg", result);
|
package/dist/models/tobit.js
CHANGED
|
@@ -4,7 +4,10 @@
|
|
|
4
4
|
import { pchisq } from "../distributions/chisq.js";
|
|
5
5
|
import { parseFormula } from "./formula.js";
|
|
6
6
|
import { design } from "./modelMatrix.js";
|
|
7
|
-
import { survreg } from "./survreg.js";
|
|
7
|
+
import { survreg, survregScaledState } from "./survreg.js";
|
|
8
|
+
import { ldexpWide } from "../internal/summary.js";
|
|
9
|
+
/** The inner survreg fit's scaled covariance and coefficients, for the Wald test of tobitSummary */
|
|
10
|
+
const waldState = new WeakMap();
|
|
8
11
|
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
9
12
|
import { checkOptions, nestedOptions } from "../internal/checkOptions.js";
|
|
10
13
|
const TOBIT_KEYS = ["left", "right", "dist", "df", "parms", "weights", "contrasts", "control"];
|
|
@@ -83,14 +86,21 @@ export function tobit(formula, data, options = {}) {
|
|
|
83
86
|
const e = ["gaussian", "logistic", "t", "extreme"].includes(dist) && top > 0 ? Math.floor(Math.log2(top)) : 0;
|
|
84
87
|
const scaled = Math.abs(e) > 30;
|
|
85
88
|
const sc = scaled ? 2 ** e : 1;
|
|
86
|
-
const
|
|
89
|
+
const inner = scaled ? survreg(lo.map((v) => v / sc), undefined, x, { ...sOptions, time2: hi.map((v) => v / sc) }) : survreg(lo, undefined, x, sOptions);
|
|
90
|
+
const fit = scaled ? unscale(inner, sc, lo, hi) : inner;
|
|
87
91
|
const names = d.colNames.slice();
|
|
88
92
|
const rowNames = [...names, ...fit.tableRowNames.slice(names.length)];
|
|
89
|
-
|
|
93
|
+
const result = {
|
|
90
94
|
...fit, coefNames: names, tableRowNames: rowNames, formula, left, right,
|
|
91
95
|
counts: { total: y.length, left: nLeft, uncensored: y.length - nLeft - nRight, right: nRight },
|
|
92
96
|
warnings: [...d.warnings, ...fit.warnings],
|
|
93
97
|
};
|
|
98
|
+
// the Wald statistic does not change with the scale of the response or of a covariate: tobitSummary computes it in
|
|
99
|
+
// the inner fit's scaled coordinates (a covariate near 1e+-300 has a variance outside the doubles)
|
|
100
|
+
const state = survregScaledState(inner);
|
|
101
|
+
if (state)
|
|
102
|
+
waldState.set(result, { V: state.V, exponent: state.xExponent, b: inner.coefficients.slice() });
|
|
103
|
+
return result;
|
|
94
104
|
}
|
|
95
105
|
/**
|
|
96
106
|
* Summary of a {@link tobit} fit: the Wald table with the scale and the Wald test of the regression. Equivalent to
|
|
@@ -107,8 +117,9 @@ export function tobitSummary(fit) {
|
|
|
107
117
|
const keep = fit.coefNames.map((nm, j) => (nm === "(Intercept)" ? -1 : j)).filter((j) => j >= 0 && Number.isFinite(fit.coefficients[j]));
|
|
108
118
|
let wald = null;
|
|
109
119
|
if (keep.length > 0 && p > 1) {
|
|
110
|
-
const
|
|
111
|
-
const
|
|
120
|
+
const st = waldState.get(fit);
|
|
121
|
+
const V = st ? keep.map((a) => keep.map((b) => st.V[a][b])) : keep.map((a) => keep.map((b) => fit.var[a][b]));
|
|
122
|
+
const b = st ? keep.map((j) => ldexpWide(st.b[j], st.exponent[j])) : keep.map((j) => fit.coefficients[j]);
|
|
112
123
|
const sol = solveSymmetric(V, b);
|
|
113
124
|
const statistic = b.reduce((s, v, i) => s + v * sol[i], 0);
|
|
114
125
|
const df = p - 1;
|