@numero-uno-jpn/rstats 1.16.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 +34 -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-J74CELYL.js → chunk-2JB7F646.js} +2 -2
- package/dist/chunks/{chunk-K23MXTLC.js → chunk-3JFRDXN7.js} +2 -2
- package/dist/chunks/chunk-53WQDB3C.js +2 -0
- package/dist/chunks/{chunk-DP6TE35N.js → chunk-5CTWYFMB.js} +2 -2
- package/dist/chunks/chunk-6I23C2YJ.js +2 -0
- package/dist/chunks/{chunk-57BGTHS7.js → chunk-CTZUYKVL.js} +2 -2
- package/dist/chunks/{chunk-UMXY4R4G.js → chunk-EC77KAAM.js} +2 -2
- package/dist/chunks/{chunk-37YHUVXL.js → chunk-FLFNMSHI.js} +2 -2
- package/dist/chunks/{chunk-FCE6N6PI.js → chunk-GEHMND3C.js} +2 -2
- package/dist/chunks/{chunk-W5D6CIZM.js → chunk-GIK34P23.js} +2 -2
- package/dist/chunks/chunk-H6Z7JVSD.js +2 -0
- package/dist/chunks/{chunk-HOH5KGSU.js → chunk-HG4LJBNV.js} +2 -2
- package/dist/chunks/chunk-HGAEVPVS.js +2 -0
- package/dist/chunks/{chunk-ISOLPXQV.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-6DP2U23T.js → chunk-IKMW63BE.js} +2 -2
- package/dist/chunks/{chunk-KSN6A4OK.js → chunk-IOJVFYHW.js} +2 -2
- package/dist/chunks/chunk-IW4S634O.js +2 -0
- package/dist/chunks/{chunk-ZZ6KYMBW.js → chunk-JF4PXFJE.js} +2 -2
- package/dist/chunks/{chunk-NQWFURFV.js → chunk-JPWYGTUN.js} +2 -2
- package/dist/chunks/{chunk-XMA2NWYX.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-JYE3T7FS.js → chunk-MKZH65DK.js} +2 -2
- package/dist/chunks/{chunk-B5QE2FDM.js → chunk-MVPHISOV.js} +1 -1
- package/dist/chunks/chunk-MXZ64QME.js +2 -0
- package/dist/chunks/{chunk-XAMWBGTP.js → chunk-N7BUE54L.js} +2 -2
- package/dist/chunks/{chunk-244M5C2B.js → chunk-NDZVVNBB.js} +2 -2
- package/dist/chunks/{chunk-AC22FPFB.js → chunk-NOTJ45G3.js} +2 -2
- package/dist/chunks/{chunk-MNPZUMPL.js → chunk-QUD3374N.js} +2 -2
- package/dist/chunks/{chunk-AIII5VRA.js → chunk-RXYZQ3UX.js} +2 -2
- package/dist/chunks/{chunk-LHMG6Q5C.js → chunk-SCFFHEDZ.js} +2 -2
- package/dist/chunks/{chunk-BHNDCNWM.js → chunk-V6FMGGUV.js} +2 -2
- package/dist/chunks/{chunk-FHHI3PYN.js → chunk-VATAUY7N.js} +2 -2
- package/dist/chunks/chunk-W5M3R4NH.js +2 -0
- package/dist/chunks/{chunk-H6WBOIFZ.js → chunk-WYVUCQO3.js} +1 -1
- package/dist/chunks/{chunk-7MFMRNMT.js → chunk-XQCHC3SH.js} +1 -1
- package/dist/chunks/{chunk-IPMC3VOC.js → chunk-XUMVTGMM.js} +2 -2
- package/dist/chunks/{chunk-6MHLWTBF.js → chunk-YXMHWS5R.js} +2 -2
- package/dist/chunks/{chunk-K5IP4ZJ5.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 +4 -0
- package/dist/entries/regression.js +8 -0
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +2 -2
- package/dist/models/betareg.d.ts +278 -0
- package/dist/models/betareg.js +600 -0
- package/dist/models/bradleyterry.d.ts +188 -0
- package/dist/models/bradleyterry.js +533 -0
- package/dist/models/loglin.d.ts +186 -0
- package/dist/models/loglin.js +349 -0
- package/dist/models/survreg.d.ts +48 -0
- package/dist/models/survreg.js +29 -6
- package/dist/models/tobit.d.ts +132 -0
- package/dist/models/tobit.js +183 -0
- 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 +15 -15
- package/dist/timeseries.js +2 -2
- package/package.json +1 -1
- package/dist/chunks/chunk-3L333CTJ.js +0 -2
- package/dist/chunks/chunk-3RO5FWJ5.js +0 -2
- package/dist/chunks/chunk-3VKN6K3P.js +0 -2
- package/dist/chunks/chunk-7IU5OE5I.js +0 -2
- package/dist/chunks/chunk-GKDA5W53.js +0 -2
- package/dist/chunks/chunk-IVJTWTGV.js +0 -2
- package/dist/chunks/chunk-NCVEJDRI.js +0 -2
- package/dist/chunks/chunk-P3Q6IJMR.js +0 -2
- package/dist/chunks/chunk-PIWXBWMD.js +0 -2
- package/dist/chunks/chunk-QBY63DGM.js +0 -2
- package/dist/chunks/chunk-RV4SUKXV.js +0 -2
- package/dist/chunks/chunk-SALMA4XX.js +0 -2
- package/dist/chunks/chunk-ZTZX2UYP.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
|
+
}
|