@numero-uno-jpn/rstats 1.6.0 → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +33 -0
- package/README.ja.md +11 -9
- package/README.md +12 -9
- package/dist/chunks/{chunk-O5CMNUJL.js → chunk-2X6PE6JF.js} +2 -2
- package/dist/chunks/{chunk-KAAUNR3G.js → chunk-2ZQ2TSZS.js} +1 -1
- package/dist/chunks/{chunk-F7G74UNI.js → chunk-3DO726WZ.js} +2 -2
- package/dist/chunks/{chunk-WAMHZ47G.js → chunk-45HUI3M4.js} +2 -2
- package/dist/chunks/{chunk-ABSUQPOG.js → chunk-52RWDNO6.js} +2 -2
- package/dist/chunks/chunk-53OM63EU.js +2 -0
- package/dist/chunks/{chunk-2I7Z7L5J.js → chunk-73IRLCTF.js} +2 -2
- package/dist/chunks/chunk-7ODUCEGX.js +2 -0
- package/dist/chunks/{chunk-55XSRONZ.js → chunk-ANZUXEMH.js} +2 -2
- package/dist/chunks/chunk-BHQGMZTI.js +2 -0
- package/dist/chunks/{chunk-3PCHPKBD.js → chunk-D3LKPD4H.js} +2 -2
- package/dist/chunks/chunk-DG2RTNIR.js +2 -0
- package/dist/chunks/{chunk-Z2XN4NN7.js → chunk-GRTQ7FYQ.js} +2 -2
- package/dist/chunks/chunk-HXYH5ZMB.js +2 -0
- package/dist/chunks/{chunk-NVIJXWS6.js → chunk-HYJ4MIZE.js} +2 -2
- package/dist/chunks/{chunk-ZL7EAPO5.js → chunk-IJST2ZGT.js} +1 -1
- package/dist/chunks/{chunk-2TVHT4PF.js → chunk-JIAFWEED.js} +2 -2
- package/dist/chunks/{chunk-7ZNFRZO4.js → chunk-JXJDCQYE.js} +2 -2
- package/dist/chunks/{chunk-FLITCXLY.js → chunk-LZB43TUL.js} +2 -2
- package/dist/chunks/chunk-MLNWWGGE.js +2 -0
- package/dist/chunks/{chunk-OZLDZOOA.js → chunk-QQHF5T2A.js} +1 -1
- package/dist/chunks/chunk-RWZ6ICYN.js +2 -0
- package/dist/chunks/{chunk-RSTU6CX7.js → chunk-TQM6KGKT.js} +2 -2
- package/dist/chunks/chunk-TUL6UFLQ.js +2 -0
- package/dist/chunks/{chunk-BMEO5X5F.js → chunk-TYMC2D5I.js} +2 -2
- package/dist/chunks/chunk-V7ECXPWY.js +2 -0
- package/dist/chunks/chunk-VB6PVRSN.js +2 -0
- package/dist/chunks/chunk-Y4KNH43T.js +2 -0
- package/dist/chunks/{chunk-AHFMBHZW.js → chunk-YD4U3QZ3.js} +1 -1
- package/dist/chunks/{chunk-SFZF44G6.js → chunk-YT62DNDS.js} +2 -2
- package/dist/descriptive.js +2 -2
- package/dist/distributions.js +2 -2
- package/dist/entries/regression.d.ts +7 -0
- package/dist/entries/regression.js +12 -0
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +2 -2
- package/dist/models/gee.d.ts +280 -0
- package/dist/models/gee.js +704 -0
- package/dist/models/glmnet.d.ts +259 -0
- package/dist/models/glmnet.js +1112 -0
- package/dist/models/modelMatrix.d.ts +2 -0
- package/dist/models/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/models/rq.d.ts +203 -0
- package/dist/models/rq.js +1089 -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 +15 -15
- package/llms.txt +8 -1
- package/package.json +6 -1
- 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-TPBVVP32.js +0 -2
- package/dist/chunks/chunk-XNWSQVXS.js +0 -2
|
@@ -0,0 +1,704 @@
|
|
|
1
|
+
// Generalized estimating equations from Liang and Zeger (1986), Prentice (1988),
|
|
2
|
+
// Halekoh, Højsgaard and Yan (2006), and the public-output specification in oracle/gee-behaviour.md.
|
|
3
|
+
// No geepack or R implementation code is used.
|
|
4
|
+
import { pnorm } from "../distributions/normal.js";
|
|
5
|
+
import { pchisq } from "../distributions/chisq.js";
|
|
6
|
+
import { reported, Warnings, withWarnings, unreported } from "../internal/warnings.js";
|
|
7
|
+
import { glm } from "./glm.js";
|
|
8
|
+
import { makeFamily } from "./glmFamily.js";
|
|
9
|
+
import { design } from "./modelMatrix.js";
|
|
10
|
+
import { parseFormula } from "./formula.js";
|
|
11
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
12
|
+
import { checkOptions, nestedOptions } from "../internal/checkOptions.js";
|
|
13
|
+
const GEEGLM_KEYS = /* @__PURE__ */ new Set([
|
|
14
|
+
"id", "waves", "family", "link", "corstr", "std.err", "zcor", "weights", "offset", "scale.fix", "scale.value",
|
|
15
|
+
"epsilon", "maxit",
|
|
16
|
+
]);
|
|
17
|
+
const GEEGLM_FAMILY_KEYS = ["family", "link", "variance"];
|
|
18
|
+
const GEEGLM_FAMILY_LINK_KEYS = ["power"];
|
|
19
|
+
const GEE_VCOV_KEYS = ["type"];
|
|
20
|
+
const GEE_PREDICT_KEYS = ["newdata", "type", "newoffset"];
|
|
21
|
+
const GEE_ANOVA_KEYS = ["test"];
|
|
22
|
+
function splitOffsets(formula) {
|
|
23
|
+
const pattern = /offset\s*\(\s*(?:log\s*\(\s*([A-Za-z_.][A-Za-z0-9_.]*)\s*\)|([A-Za-z_.][A-Za-z0-9_.]*))\s*\)/g;
|
|
24
|
+
const terms = [];
|
|
25
|
+
for (const match of formula.matchAll(pattern)) {
|
|
26
|
+
const logVariable = match[1];
|
|
27
|
+
const variable = logVariable ?? match[2];
|
|
28
|
+
if (variable === undefined)
|
|
29
|
+
continue;
|
|
30
|
+
terms.push({ variable, log: logVariable !== undefined });
|
|
31
|
+
}
|
|
32
|
+
let meanFormula = formula.replace(pattern, "");
|
|
33
|
+
meanFormula = meanFormula.replace(/~\s*\+/g, "~ ").replace(/\+\s*\+/g, "+").replace(/\+\s*$/g, "").trim();
|
|
34
|
+
if (/~\s*$/.test(meanFormula))
|
|
35
|
+
meanFormula += " 1";
|
|
36
|
+
if (terms.length > 0 && meanFormula.endsWith("~"))
|
|
37
|
+
meanFormula += " 1";
|
|
38
|
+
return { meanFormula, terms };
|
|
39
|
+
}
|
|
40
|
+
function zeros(n, m) {
|
|
41
|
+
return Array.from({ length: n }, () => new Array(m).fill(0));
|
|
42
|
+
}
|
|
43
|
+
function identity(n) {
|
|
44
|
+
const a = zeros(n, n);
|
|
45
|
+
for (let i = 0; i < n; i++)
|
|
46
|
+
a[i][i] = 1;
|
|
47
|
+
return a;
|
|
48
|
+
}
|
|
49
|
+
function transpose(a) {
|
|
50
|
+
if (a.length === 0)
|
|
51
|
+
return [];
|
|
52
|
+
return Array.from({ length: a[0].length }, (_, j) => a.map((r) => r[j]));
|
|
53
|
+
}
|
|
54
|
+
function multiply(a, b) {
|
|
55
|
+
const n = a.length, k = n ? a[0].length : 0, m = b.length ? b[0].length : 0;
|
|
56
|
+
if (k !== b.length)
|
|
57
|
+
throw new RangeError("non-conformable matrices");
|
|
58
|
+
const out = zeros(n, m);
|
|
59
|
+
for (let i = 0; i < n; i++)
|
|
60
|
+
for (let q = 0; q < k; q++) {
|
|
61
|
+
const v = a[i][q];
|
|
62
|
+
for (let j = 0; j < m; j++)
|
|
63
|
+
out[i][j] = out[i][j] + v * b[q][j];
|
|
64
|
+
}
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
67
|
+
function inverse(input) {
|
|
68
|
+
const n = input.length;
|
|
69
|
+
if (n === 0 || input.some((row) => row.length !== n))
|
|
70
|
+
throw new RangeError("the matrix must be square and nonempty");
|
|
71
|
+
const scale = input.map((row, i) => Math.sqrt(Math.abs(row[i])));
|
|
72
|
+
if (scale.some((value) => !(value > 0) || !Number.isFinite(value)))
|
|
73
|
+
throw new Error("singular working information matrix");
|
|
74
|
+
const eye = identity(n);
|
|
75
|
+
const a = input.map((row, i) => [...row.map((value, j) => value / scale[i] / scale[j]), ...eye[i]]);
|
|
76
|
+
for (let j = 0; j < n; j++) {
|
|
77
|
+
let pivot = j;
|
|
78
|
+
for (let i = j + 1; i < n; i++)
|
|
79
|
+
if (Math.abs(a[i][j]) > Math.abs(a[pivot][j]))
|
|
80
|
+
pivot = i;
|
|
81
|
+
let rowMax = 0;
|
|
82
|
+
for (let k = 0; k < n; k++)
|
|
83
|
+
rowMax = Math.max(rowMax, Math.abs(a[pivot][k]));
|
|
84
|
+
if (!(rowMax > 0) || !(Math.abs(a[pivot][j]) > Number.EPSILON * rowMax))
|
|
85
|
+
throw new Error("singular working information matrix");
|
|
86
|
+
[a[j], a[pivot]] = [a[pivot], a[j]];
|
|
87
|
+
const d = a[j][j];
|
|
88
|
+
for (let k = 0; k < 2 * n; k++)
|
|
89
|
+
a[j][k] = a[j][k] / d;
|
|
90
|
+
for (let i = 0; i < n; i++)
|
|
91
|
+
if (i !== j) {
|
|
92
|
+
const f = a[i][j];
|
|
93
|
+
for (let k = 0; k < 2 * n; k++)
|
|
94
|
+
a[i][k] = a[i][k] - f * a[j][k];
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return a.map((row, i) => row.slice(n).map((value, j) => value / scale[i] / scale[j]));
|
|
98
|
+
}
|
|
99
|
+
function dot(a, b) {
|
|
100
|
+
let s = 0;
|
|
101
|
+
for (let i = 0; i < a.length; i++)
|
|
102
|
+
s += a[i] * b[i];
|
|
103
|
+
return s;
|
|
104
|
+
}
|
|
105
|
+
function solve(a, b) {
|
|
106
|
+
return multiply(inverse(a), b.map((v) => [v])).map((r) => r[0]);
|
|
107
|
+
}
|
|
108
|
+
function getColumn(data, name) {
|
|
109
|
+
const col = data[name];
|
|
110
|
+
if (col === undefined || typeof col === "string")
|
|
111
|
+
throw new RangeError("object '" + name + "' not found");
|
|
112
|
+
return Array.from(col);
|
|
113
|
+
}
|
|
114
|
+
function vector(value, data, rows, n, fallback, label) {
|
|
115
|
+
if (value === undefined)
|
|
116
|
+
return rows.map(() => fallback);
|
|
117
|
+
const raw = typeof value === "string" ? getColumn(data, value) : Array.from(value);
|
|
118
|
+
if (raw.length !== n)
|
|
119
|
+
throw new RangeError("variable lengths differ (found for '" + label + "')");
|
|
120
|
+
return rows.map((i) => {
|
|
121
|
+
const v = raw[i];
|
|
122
|
+
if (typeof v !== "number" || !Number.isFinite(v))
|
|
123
|
+
throw new RangeError("'" + label + "' must contain finite numbers");
|
|
124
|
+
return v;
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
function clusterVector(value, data, rows, n) {
|
|
128
|
+
const raw = typeof value === "string" ? getColumn(data, value) : Array.from(value);
|
|
129
|
+
if (raw.length !== n)
|
|
130
|
+
throw new RangeError("variable lengths differ (found for 'id')");
|
|
131
|
+
return rows.map((i) => {
|
|
132
|
+
const v = raw[i];
|
|
133
|
+
if ((typeof v !== "number" && typeof v !== "string" && typeof v !== "boolean") || v === null ||
|
|
134
|
+
(typeof v === "number" && !Number.isFinite(v)))
|
|
135
|
+
throw new RangeError("missing or non-finite cluster id");
|
|
136
|
+
return v;
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
function groups(ids) {
|
|
140
|
+
const map = new Map();
|
|
141
|
+
const out = [];
|
|
142
|
+
for (let i = 0; i < ids.length; i++) {
|
|
143
|
+
const key = typeof ids[i] + ":" + String(ids[i]);
|
|
144
|
+
let k = map.get(key);
|
|
145
|
+
if (k === undefined) {
|
|
146
|
+
k = out.length;
|
|
147
|
+
map.set(key, k);
|
|
148
|
+
out.push([]);
|
|
149
|
+
}
|
|
150
|
+
out[k].push(i);
|
|
151
|
+
}
|
|
152
|
+
return out;
|
|
153
|
+
}
|
|
154
|
+
function correlationMatrix(size, structure, alpha, waves, zcor, pairOffset) {
|
|
155
|
+
const r = identity(size);
|
|
156
|
+
let pair = 0;
|
|
157
|
+
for (let j = 0; j < size; j++)
|
|
158
|
+
for (let k = 0; k < j; k++) {
|
|
159
|
+
let v = 0;
|
|
160
|
+
if (structure === "exchangeable")
|
|
161
|
+
v = alpha[0] ?? 0;
|
|
162
|
+
else if (structure === "ar1")
|
|
163
|
+
v = (alpha[0] ?? 0) ** Math.abs(waves[j] - waves[k]);
|
|
164
|
+
else if (structure === "unstructured")
|
|
165
|
+
v = alpha[pair] ?? 0;
|
|
166
|
+
else if (structure === "userdefined")
|
|
167
|
+
v = dot(zcor?.[pairOffset + pair] ?? [], alpha);
|
|
168
|
+
else if (structure === "fixed")
|
|
169
|
+
v = zcor?.[pairOffset + pair]?.[0] ?? 0;
|
|
170
|
+
r[j][k] = v;
|
|
171
|
+
r[k][j] = v;
|
|
172
|
+
pair++;
|
|
173
|
+
}
|
|
174
|
+
return r;
|
|
175
|
+
}
|
|
176
|
+
function pairMoments(residuals, clusterGroups, waves, structure, scale, zcor) {
|
|
177
|
+
if (structure === "exchangeable") {
|
|
178
|
+
let total = 0, count = 0;
|
|
179
|
+
for (const g of clusterGroups)
|
|
180
|
+
for (let j = 0; j < g.length; j++)
|
|
181
|
+
for (let k = 0; k < j; k++) {
|
|
182
|
+
total += residuals[g[j]] * residuals[g[k]] / scale;
|
|
183
|
+
count++;
|
|
184
|
+
}
|
|
185
|
+
return [count ? total / count : 0];
|
|
186
|
+
}
|
|
187
|
+
if (structure === "ar1") {
|
|
188
|
+
const sums = new Map();
|
|
189
|
+
for (const g of clusterGroups)
|
|
190
|
+
for (let j = 0; j < g.length; j++)
|
|
191
|
+
for (let k = 0; k < j; k++) {
|
|
192
|
+
const lag = Math.abs(waves[g[j]] - waves[g[k]]);
|
|
193
|
+
if (lag === 0)
|
|
194
|
+
continue;
|
|
195
|
+
const z = sums.get(lag) ?? { sum: 0, n: 0 };
|
|
196
|
+
z.sum += residuals[g[j]] * residuals[g[k]] / scale;
|
|
197
|
+
z.n++;
|
|
198
|
+
sums.set(lag, z);
|
|
199
|
+
}
|
|
200
|
+
let best = 0, bestLoss = Infinity;
|
|
201
|
+
for (let t = -0.99; t <= 0.9900001; t += 0.002) {
|
|
202
|
+
let loss = 0;
|
|
203
|
+
for (const [lag, z] of sums)
|
|
204
|
+
loss += z.n * (z.sum / z.n - t ** lag) ** 2;
|
|
205
|
+
if (loss < bestLoss) {
|
|
206
|
+
best = t;
|
|
207
|
+
bestLoss = loss;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
let lo = Math.max(-0.9999, best - 0.003), hi = Math.min(0.9999, best + 0.003);
|
|
211
|
+
const loss = (t) => {
|
|
212
|
+
let v = 0;
|
|
213
|
+
for (const [lag, z] of sums)
|
|
214
|
+
v += z.n * (z.sum / z.n - t ** lag) ** 2;
|
|
215
|
+
return v;
|
|
216
|
+
};
|
|
217
|
+
for (let i = 0; i < 70; i++) {
|
|
218
|
+
const m1 = lo + (hi - lo) / 3, m2 = hi - (hi - lo) / 3;
|
|
219
|
+
if (loss(m1) < loss(m2))
|
|
220
|
+
hi = m2;
|
|
221
|
+
else
|
|
222
|
+
lo = m1;
|
|
223
|
+
}
|
|
224
|
+
return [(lo + hi) / 2];
|
|
225
|
+
}
|
|
226
|
+
if (structure === "unstructured") {
|
|
227
|
+
const sums = [], counts = [];
|
|
228
|
+
for (const g of clusterGroups)
|
|
229
|
+
for (let j = 0; j < g.length; j++)
|
|
230
|
+
for (let k = 0; k < j; k++) {
|
|
231
|
+
const ix = j * (j - 1) / 2 + k;
|
|
232
|
+
sums[ix] = (sums[ix] ?? 0) + residuals[g[j]] * residuals[g[k]] / scale;
|
|
233
|
+
counts[ix] = (counts[ix] ?? 0) + 1;
|
|
234
|
+
}
|
|
235
|
+
return sums.map((v, i) => v / counts[i]);
|
|
236
|
+
}
|
|
237
|
+
if (structure === "userdefined") {
|
|
238
|
+
if (zcor === undefined)
|
|
239
|
+
throw new TypeError("zcor is required for userdefined correlation");
|
|
240
|
+
const rows = [];
|
|
241
|
+
const target = [];
|
|
242
|
+
let pair = 0;
|
|
243
|
+
for (const g of clusterGroups)
|
|
244
|
+
for (let j = 0; j < g.length; j++)
|
|
245
|
+
for (let k = 0; k < j; k++) {
|
|
246
|
+
const designRow = zcor[pair];
|
|
247
|
+
if (designRow === undefined || designRow.length === 0)
|
|
248
|
+
throw new RangeError("zcor must have one nonempty row per within-cluster pair");
|
|
249
|
+
rows.push(Array.from(designRow));
|
|
250
|
+
target.push(residuals[g[j]] * residuals[g[k]] / scale);
|
|
251
|
+
pair++;
|
|
252
|
+
}
|
|
253
|
+
if (zcor.length !== rows.length)
|
|
254
|
+
throw new RangeError("zcor must have one row per within-cluster pair");
|
|
255
|
+
const zt = transpose(rows);
|
|
256
|
+
return solve(multiply(zt, rows), multiply(zt, target.map((v) => [v])).map((r) => r[0]));
|
|
257
|
+
}
|
|
258
|
+
return [];
|
|
259
|
+
}
|
|
260
|
+
function evaluate(x, y, beta, offset, family, weights) {
|
|
261
|
+
const eta = x.map((row, i) => dot(row, beta) + offset[i]);
|
|
262
|
+
const mu = eta.map((v) => family.linkinv(v));
|
|
263
|
+
const residuals = y.map((v, i) => v - mu[i]);
|
|
264
|
+
const pearson = residuals.map((v, i) => v * Math.sqrt(weights[i]) / Math.sqrt(family.variance(mu[i])));
|
|
265
|
+
const derivative = eta.map((v) => family.muEta(v));
|
|
266
|
+
return { eta, mu, residuals, pearson, derivative };
|
|
267
|
+
}
|
|
268
|
+
function geeStep(x, y, beta, offset, weights, family, clusterGroups, waves, corstr, alpha, scale, zcor) {
|
|
269
|
+
const ev = evaluate(x, y, beta, offset, family, weights);
|
|
270
|
+
const p = beta.length, bread = zeros(p, p), meat = zeros(p, p), score = new Array(p).fill(0);
|
|
271
|
+
let pairOffset = 0;
|
|
272
|
+
for (const rows of clusterGroups) {
|
|
273
|
+
const a = rows.map((i) => Math.sqrt(family.variance(ev.mu[i]) / weights[i]));
|
|
274
|
+
const R = correlationMatrix(rows.length, corstr, alpha, rows.map((i) => waves[i]), zcor, pairOffset);
|
|
275
|
+
pairOffset += rows.length * (rows.length - 1) / 2;
|
|
276
|
+
const V = R.map((r, j) => r.map((v, k) => scale * a[j] * v * a[k]));
|
|
277
|
+
const Vi = inverse(V);
|
|
278
|
+
const D = rows.map((i) => x[i].map((v) => v * ev.derivative[i]));
|
|
279
|
+
const residual = rows.map((i) => ev.residuals[i]);
|
|
280
|
+
const ViR = multiply(Vi, residual.map((v) => [v])).map((r) => r[0]);
|
|
281
|
+
const localScore = multiply(transpose(D), ViR.map((v) => [v])).map((r) => r[0]);
|
|
282
|
+
for (let j = 0; j < p; j++)
|
|
283
|
+
score[j] += localScore[j];
|
|
284
|
+
const localBread = multiply(multiply(transpose(D), Vi), D);
|
|
285
|
+
for (let j = 0; j < p; j++)
|
|
286
|
+
for (let k = 0; k < p; k++)
|
|
287
|
+
bread[j][k] = bread[j][k] + localBread[j][k];
|
|
288
|
+
for (let j = 0; j < p; j++)
|
|
289
|
+
for (let k = 0; k < p; k++)
|
|
290
|
+
meat[j][k] = meat[j][k] + localScore[j] * localScore[k];
|
|
291
|
+
}
|
|
292
|
+
return { delta: solve(bread, score), bread, meat, eval: ev };
|
|
293
|
+
}
|
|
294
|
+
/** Fit the independence working-correlation model used to construct Omega_I in QIC. */
|
|
295
|
+
function fitIndependenceForQIC(x, y, startBeta, offset, weights, family, clusterGroups, waves, scaleFix, scaleValue, epsilon, maxit) {
|
|
296
|
+
let beta = Array.from(startBeta), scale = scaleFix ? scaleValue : 1;
|
|
297
|
+
for (let iteration = 1; iteration <= maxit; iteration++) {
|
|
298
|
+
const step = geeStep(x, y, beta, offset, weights, family, clusterGroups, waves, "independence", [], scale, undefined);
|
|
299
|
+
const next = beta.map((v, j) => v + step.delta[j]);
|
|
300
|
+
if (next.some((v) => !Number.isFinite(v)))
|
|
301
|
+
throw new Error("non-finite coefficient in independence GEE iteration");
|
|
302
|
+
let diff = 0;
|
|
303
|
+
for (let j = 0; j < beta.length; j++)
|
|
304
|
+
diff = Math.max(diff, Math.abs(next[j] - beta[j]));
|
|
305
|
+
beta = next;
|
|
306
|
+
const ev = evaluate(x, y, beta, offset, family, weights);
|
|
307
|
+
const oldScale = scale;
|
|
308
|
+
if (!scaleFix)
|
|
309
|
+
scale = ev.pearson.reduce((s, v) => s + v * v, 0) / y.length;
|
|
310
|
+
diff = Math.max(diff, Math.abs(scale - oldScale));
|
|
311
|
+
let betaScale = 1;
|
|
312
|
+
for (const value of beta)
|
|
313
|
+
betaScale = Math.max(betaScale, Math.abs(value));
|
|
314
|
+
if (diff <= epsilon * betaScale)
|
|
315
|
+
break;
|
|
316
|
+
}
|
|
317
|
+
return { beta, scale: scaleFix ? scaleValue : scale };
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* Fit a marginal generalized estimating equation model.
|
|
321
|
+
* Equivalent to `geepack::geeglm()` in R.
|
|
322
|
+
* @category Regression
|
|
323
|
+
*/
|
|
324
|
+
export function geeglm(formula, data, options) {
|
|
325
|
+
checkOptions(options, GEEGLM_KEYS, "geeglm"); // generated: option-keys.mjs
|
|
326
|
+
checkOptions(nestedOptions(options, "family"), GEEGLM_FAMILY_KEYS, "geeglm", "family"); // generated: option-keys.mjs
|
|
327
|
+
checkOptions(nestedOptions(options, "family.link"), GEEGLM_FAMILY_LINK_KEYS, "geeglm", "family.link"); // generated: option-keys.mjs
|
|
328
|
+
checkOptions(nestedOptions(options, "link"), GEEGLM_FAMILY_LINK_KEYS, "geeglm", "link"); // generated: option-keys.mjs
|
|
329
|
+
if (options.id === undefined)
|
|
330
|
+
throw new TypeError("id is required");
|
|
331
|
+
const corstr = options.corstr ?? "independence";
|
|
332
|
+
if (!["independence", "exchangeable", "ar1", "unstructured", "userdefined", "fixed"].includes(corstr))
|
|
333
|
+
throw new RangeError("unknown working correlation");
|
|
334
|
+
const requestedStdErr = options["std.err"];
|
|
335
|
+
if (requestedStdErr !== undefined && requestedStdErr !== "san.se")
|
|
336
|
+
throw new RangeError(`std.err = "${requestedStdErr}" is not supported yet; use "san.se"`);
|
|
337
|
+
const stdErr = requestedStdErr ?? "san.se";
|
|
338
|
+
const epsilon = options.epsilon ?? 1e-4, maxit = options.maxit ?? 25;
|
|
339
|
+
if (!(epsilon > 0) || !Number.isFinite(epsilon) || !Number.isInteger(maxit) || maxit < 1)
|
|
340
|
+
throw new RangeError("invalid convergence controls");
|
|
341
|
+
const split = splitOffsets(formula);
|
|
342
|
+
const inputN = Object.values(data)[0]?.length ?? 0;
|
|
343
|
+
const frameData = { ...data };
|
|
344
|
+
const extras = split.terms.map((t) => t.variable);
|
|
345
|
+
const addVectorColumn = (base, values) => {
|
|
346
|
+
let name = "__gee_" + base;
|
|
347
|
+
while (name in frameData)
|
|
348
|
+
name += "_";
|
|
349
|
+
frameData[name] = Array.from(values);
|
|
350
|
+
extras.push(name);
|
|
351
|
+
};
|
|
352
|
+
if (typeof options.id === "string")
|
|
353
|
+
extras.push(options.id);
|
|
354
|
+
else
|
|
355
|
+
addVectorColumn("id", options.id);
|
|
356
|
+
if (typeof options.waves === "string")
|
|
357
|
+
extras.push(options.waves);
|
|
358
|
+
else if (options.waves !== undefined)
|
|
359
|
+
addVectorColumn("waves", options.waves);
|
|
360
|
+
if (typeof options.weights === "string")
|
|
361
|
+
extras.push(options.weights);
|
|
362
|
+
if (typeof options.offset === "string")
|
|
363
|
+
extras.push(options.offset);
|
|
364
|
+
else if (options.offset !== undefined)
|
|
365
|
+
addVectorColumn("offset", options.offset);
|
|
366
|
+
const d = design(parseFormula(split.meanFormula), frameData, {
|
|
367
|
+
extraVariables: extras, ...(options.weights === undefined ? {} : { weights: options.weights }),
|
|
368
|
+
});
|
|
369
|
+
if (d.y === undefined)
|
|
370
|
+
throw new TypeError("formula must have a response");
|
|
371
|
+
const frameRows = d.frame.rows, frameN = frameRows.length, p = d.colNames.length;
|
|
372
|
+
if (frameN === 0 || p === 0)
|
|
373
|
+
throw new RangeError("no observations or no model columns");
|
|
374
|
+
const frameIds = clusterVector(options.id, data, frameRows, inputN);
|
|
375
|
+
const frameWaves = options.waves === undefined ? frameRows.map((_, i) => i) : vector(options.waves, data, frameRows, inputN, 0, "waves");
|
|
376
|
+
const frameWeights = d.frame.weights ?? new Array(frameN).fill(1);
|
|
377
|
+
if (frameWeights.some((v) => v < 0))
|
|
378
|
+
throw new RangeError("weights must be nonnegative");
|
|
379
|
+
if (frameWeights.some((v) => !Number.isFinite(v)))
|
|
380
|
+
throw new RangeError("weights must be finite");
|
|
381
|
+
const frameOffset = vector(options.offset, data, frameRows, inputN, 0, "offset");
|
|
382
|
+
for (const term of split.terms) {
|
|
383
|
+
const values = vector(term.variable, data, frameRows, inputN, 0, "offset");
|
|
384
|
+
for (let i = 0; i < frameOffset.length; i++)
|
|
385
|
+
frameOffset[i] = frameOffset[i] + (term.log ? Math.log(values[i]) : values[i]);
|
|
386
|
+
}
|
|
387
|
+
const active = [];
|
|
388
|
+
for (let i = 0; i < frameN; i++)
|
|
389
|
+
if (frameWeights[i] > 0)
|
|
390
|
+
active.push(i);
|
|
391
|
+
if (active.length === 0)
|
|
392
|
+
throw new RangeError("no observations with positive weight");
|
|
393
|
+
const rows = active.map((i) => frameRows[i]);
|
|
394
|
+
const n = rows.length;
|
|
395
|
+
const x = active.map((i) => d.x[i]);
|
|
396
|
+
const y = active.map((i) => d.y[i]);
|
|
397
|
+
const ids = active.map((i) => frameIds[i]);
|
|
398
|
+
let waves = active.map((i) => frameWaves[i]);
|
|
399
|
+
const weights = active.map((i) => frameWeights[i]);
|
|
400
|
+
const offset = active.map((i) => frameOffset[i]);
|
|
401
|
+
if (x.some((row) => row.some((v) => !Number.isFinite(v))))
|
|
402
|
+
throw new RangeError("NA/NaN/Inf in 'x'");
|
|
403
|
+
if (y.some((v) => !Number.isFinite(v)))
|
|
404
|
+
throw new RangeError("NA/NaN/Inf in 'y'");
|
|
405
|
+
if (offset.some((v) => !Number.isFinite(v)))
|
|
406
|
+
throw new RangeError("offset must be finite");
|
|
407
|
+
const clusterGroups = groups(ids);
|
|
408
|
+
if (options.waves === undefined) {
|
|
409
|
+
waves = new Array(n).fill(0);
|
|
410
|
+
for (const g of clusterGroups)
|
|
411
|
+
for (let j = 0; j < g.length; j++)
|
|
412
|
+
waves[g[j]] = j;
|
|
413
|
+
}
|
|
414
|
+
const family = makeFamily(options.family ?? "gaussian", options.link);
|
|
415
|
+
if (options.zcor !== undefined) {
|
|
416
|
+
if (!Array.isArray(options.zcor))
|
|
417
|
+
throw new TypeError("zcor must be a matrix or numeric vector");
|
|
418
|
+
const raw = options.zcor;
|
|
419
|
+
const isVector = raw.every((value) => typeof value === "number");
|
|
420
|
+
const isMatrix = raw.every((row) => Array.isArray(row));
|
|
421
|
+
if (!isVector && !isMatrix)
|
|
422
|
+
throw new TypeError("zcor must be a matrix or numeric vector");
|
|
423
|
+
}
|
|
424
|
+
if ((corstr === "userdefined" || corstr === "fixed") && options.zcor === undefined)
|
|
425
|
+
throw new TypeError("zcor is required for userdefined and fixed working correlations");
|
|
426
|
+
let zcor;
|
|
427
|
+
if (options.zcor !== undefined) {
|
|
428
|
+
const rawZcor = Array.from(options.zcor);
|
|
429
|
+
zcor = typeof rawZcor[0] === "number"
|
|
430
|
+
? rawZcor.map((v) => [v])
|
|
431
|
+
: rawZcor.map((r) => Array.from(r));
|
|
432
|
+
}
|
|
433
|
+
if (zcor?.some((r) => r.some((v) => !Number.isFinite(v))))
|
|
434
|
+
throw new RangeError("zcor must contain finite numbers");
|
|
435
|
+
if (zcor !== undefined) {
|
|
436
|
+
let pairCount = 0;
|
|
437
|
+
for (const g of clusterGroups)
|
|
438
|
+
pairCount += g.length * (g.length - 1) / 2;
|
|
439
|
+
if (zcor.length !== pairCount)
|
|
440
|
+
throw new RangeError("zcor must have one row per within-cluster pair");
|
|
441
|
+
const columns = zcor[0]?.length ?? 0;
|
|
442
|
+
if (columns === 0 || zcor.some((r) => r.length !== columns))
|
|
443
|
+
throw new RangeError("zcor rows must have the same positive number of columns");
|
|
444
|
+
if (corstr === "fixed" && (columns !== 1 || zcor.some((r) => Math.abs(r[0]) > 1))) {
|
|
445
|
+
throw new RangeError("fixed zcor must be a one-column matrix of correlations in [-1, 1]");
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
const warnings = new Warnings();
|
|
449
|
+
return withWarnings(warnings, () => {
|
|
450
|
+
const startFit = unreported(() => glm(x, y, {
|
|
451
|
+
family: options.family ?? "gaussian",
|
|
452
|
+
...(options.link === undefined ? {} : { link: options.link }),
|
|
453
|
+
weights, offset, intercept: false, epsilon, maxit,
|
|
454
|
+
}));
|
|
455
|
+
let beta = startFit.coefficients.slice();
|
|
456
|
+
let scale = options["scale.fix"] ? (options["scale.value"] ?? 1) : 1;
|
|
457
|
+
if (!(scale > 0) || !Number.isFinite(scale))
|
|
458
|
+
throw new RangeError("scale.value must be positive and finite");
|
|
459
|
+
let maxPairs = 0;
|
|
460
|
+
for (const g of clusterGroups)
|
|
461
|
+
maxPairs = Math.max(maxPairs, g.length * (g.length - 1) / 2);
|
|
462
|
+
let alpha = corstr === "exchangeable" || corstr === "ar1" ? [0] :
|
|
463
|
+
corstr === "unstructured" ? new Array(maxPairs).fill(0) :
|
|
464
|
+
corstr === "userdefined" ? new Array(zcor?.[0]?.length ?? 0).fill(0) : [];
|
|
465
|
+
let bread = identity(p), meat = identity(p), converged = false, iteration = 0;
|
|
466
|
+
for (iteration = 1; iteration <= maxit; iteration++) {
|
|
467
|
+
const step = geeStep(x, y, beta, offset, weights, family, clusterGroups, waves, corstr, alpha, scale, zcor);
|
|
468
|
+
const next = beta.map((v, j) => v + step.delta[j]);
|
|
469
|
+
if (next.some((v) => !Number.isFinite(v)))
|
|
470
|
+
throw new Error("non-finite coefficient in GEE iteration");
|
|
471
|
+
let diff = 0;
|
|
472
|
+
for (let j = 0; j < p; j++)
|
|
473
|
+
diff = Math.max(diff, Math.abs(next[j] - beta[j]));
|
|
474
|
+
const oldAlpha = alpha.slice();
|
|
475
|
+
const oldScale = scale;
|
|
476
|
+
beta = next;
|
|
477
|
+
bread = step.bread;
|
|
478
|
+
meat = step.meat;
|
|
479
|
+
const ev = evaluate(x, y, beta, offset, family, weights);
|
|
480
|
+
if (!options["scale.fix"])
|
|
481
|
+
scale = ev.pearson.reduce((s, v) => s + v * v, 0) / n;
|
|
482
|
+
if (corstr === "exchangeable" || corstr === "ar1" || corstr === "unstructured" || corstr === "userdefined") {
|
|
483
|
+
alpha = pairMoments(ev.pearson, clusterGroups, waves, corstr, scale, zcor).map((v) => Math.max(-0.99, Math.min(0.99, v)));
|
|
484
|
+
}
|
|
485
|
+
for (let j = 0; j < alpha.length; j++)
|
|
486
|
+
diff = Math.max(diff, Math.abs(alpha[j] - (oldAlpha[j] ?? 0)));
|
|
487
|
+
diff = Math.max(diff, Math.abs(scale - oldScale));
|
|
488
|
+
let betaScale = 1;
|
|
489
|
+
for (const v of beta)
|
|
490
|
+
betaScale = Math.max(betaScale, Math.abs(v));
|
|
491
|
+
if (diff <= epsilon * betaScale) {
|
|
492
|
+
converged = true;
|
|
493
|
+
break;
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
if (!converged)
|
|
497
|
+
warnings.add("geeglm did not converge in " + maxit + " iterations");
|
|
498
|
+
const finalStep = geeStep(x, y, beta, offset, weights, family, clusterGroups, waves, corstr, alpha, scale, zcor);
|
|
499
|
+
bread = finalStep.bread;
|
|
500
|
+
meat = finalStep.meat;
|
|
501
|
+
const breadInv = inverse(bread);
|
|
502
|
+
let covariance = multiply(multiply(breadInv, meat), breadInv);
|
|
503
|
+
const modelCovariance = breadInv.map((r) => r.slice());
|
|
504
|
+
const independentFit = corstr === "independence" ? { beta, scale } :
|
|
505
|
+
fitIndependenceForQIC(x, y, startFit.coefficients, offset, weights, family, clusterGroups, waves, options["scale.fix"] ?? false, options["scale.value"] ?? 1, epsilon, maxit);
|
|
506
|
+
const independentStep = geeStep(x, y, independentFit.beta, offset, weights, family, clusterGroups, waves, "independence", [], independentFit.scale, undefined);
|
|
507
|
+
const independenceCovariance = inverse(independentStep.bread);
|
|
508
|
+
const ev = evaluate(x, y, beta, offset, family, weights);
|
|
509
|
+
const fitted = new Array(inputN).fill(NaN), linear = fitted.slice(), residuals = fitted.slice(), pearson = fitted.slice();
|
|
510
|
+
rows.forEach((r, i) => { fitted[r] = ev.mu[i]; linear[r] = ev.eta[i]; residuals[r] = ev.residuals[i]; pearson[r] = ev.pearson[i]; });
|
|
511
|
+
const result = {
|
|
512
|
+
coefficients: beta, fittedValues: fitted, linearPredictors: linear, residuals, pearsonResiduals: pearson,
|
|
513
|
+
covariance, modelCovariance, independenceCovariance, alpha, scale, iterations: converged ? iteration : maxit, converged, family: family.family,
|
|
514
|
+
link: family.name, corstr, stdErr, columnNames: d.colNames, rows, clusterIds: ids, waves,
|
|
515
|
+
warnings: warnings.list.slice(),
|
|
516
|
+
model: { formula, meanFormula: split.meanFormula, offsetTerms: split.terms,
|
|
517
|
+
offsetOptionColumn: typeof options.offset === "string" ? options.offset : undefined,
|
|
518
|
+
hasExternalOffset: options.offset !== undefined, termAssign: d.assign.slice(),
|
|
519
|
+
termLabels: d.terms.termLabels.slice(), responseVariable: d.terms.variables[d.terms.response],
|
|
520
|
+
intercept: d.terms.intercept, x: x, y, ids, waves, weights, offset, family: options.family ?? "gaussian",
|
|
521
|
+
link: options.link, corstr, scaleFix: options["scale.fix"] ?? false, scaleValue: options["scale.value"] ?? 1, epsilon, maxit,
|
|
522
|
+
zcor, data },
|
|
523
|
+
};
|
|
524
|
+
return reported("geeglm", result);
|
|
525
|
+
});
|
|
526
|
+
}
|
|
527
|
+
/**
|
|
528
|
+
* Return robust or model-based coefficient covariance.
|
|
529
|
+
* Equivalent to R's `vcov()`.
|
|
530
|
+
* @category Regression
|
|
531
|
+
*/
|
|
532
|
+
export function geeVcov(fit, options = {}) {
|
|
533
|
+
checkOptions(options, GEE_VCOV_KEYS, "geeVcov"); // generated: option-keys.mjs
|
|
534
|
+
const a = options.type === "naive" ? fit.modelCovariance : fit.covariance;
|
|
535
|
+
return { rows: fit.columnNames, columns: fit.columnNames, values: a.map((r) => r.slice()) };
|
|
536
|
+
}
|
|
537
|
+
/**
|
|
538
|
+
* Summarize the coefficient estimates of a GEE fit.
|
|
539
|
+
* Equivalent to R's `summary.geeglm()`.
|
|
540
|
+
* @category Regression
|
|
541
|
+
*/
|
|
542
|
+
export function geeSummary(fit, options = {}) {
|
|
543
|
+
const values = fit.coefficients.map((estimate, i) => {
|
|
544
|
+
const se = Math.sqrt(fit.covariance[i][i]);
|
|
545
|
+
const z = estimate / se;
|
|
546
|
+
return [estimate, se, z * z, 2 * (1 - pnorm(Math.abs(z)))];
|
|
547
|
+
});
|
|
548
|
+
return reported("geeSummary", { rows: fit.columnNames, columns: ["Estimate", "Std. Error", "Wald", "Pr(>|W|)"],
|
|
549
|
+
values, scale: fit.scale, correlation: { rows: fit.alpha.map((_, i) => "alpha" + (i + 1)), estimate: fit.alpha.slice() },
|
|
550
|
+
warnings: fit.warnings.slice() }, fit);
|
|
551
|
+
}
|
|
552
|
+
/**
|
|
553
|
+
* Predict marginal means on the link or response scale.
|
|
554
|
+
* Equivalent to R's `predict.geeglm()`.
|
|
555
|
+
* @category Regression
|
|
556
|
+
*/
|
|
557
|
+
export function geePredict(fit, options = {}) {
|
|
558
|
+
checkOptions(options, GEE_PREDICT_KEYS, "geePredict"); // generated: option-keys.mjs
|
|
559
|
+
if (options.newdata === undefined && options.newoffset === undefined) {
|
|
560
|
+
return options.type === "response" ? fit.fittedValues.slice() : fit.linearPredictors.slice();
|
|
561
|
+
}
|
|
562
|
+
const newdata = options.newdata ?? fit.model.data;
|
|
563
|
+
const predictionData = { ...newdata };
|
|
564
|
+
const predictionLength = Object.values(newdata)[0]?.length ?? 0;
|
|
565
|
+
if (!(fit.model.responseVariable in predictionData))
|
|
566
|
+
predictionData[fit.model.responseVariable] = new Array(predictionLength).fill(0);
|
|
567
|
+
const d = design(parseFormula(fit.model.meanFormula), predictionData, {
|
|
568
|
+
extraVariables: [...fit.model.offsetTerms.map((t) => t.variable), ...(fit.model.offsetOptionColumn === undefined ? [] : [fit.model.offsetOptionColumn])],
|
|
569
|
+
});
|
|
570
|
+
const family = makeFamily(fit.model.family, fit.model.link);
|
|
571
|
+
const n = d.x.length;
|
|
572
|
+
const offset = options.newoffset === undefined ? new Array(n).fill(0) : Array.from(options.newoffset);
|
|
573
|
+
if (offset.length !== n)
|
|
574
|
+
throw new RangeError("newoffset must have one value per retained row");
|
|
575
|
+
for (const term of fit.model.offsetTerms) {
|
|
576
|
+
const raw = getColumn(predictionData, term.variable);
|
|
577
|
+
for (let i = 0; i < n; i++) {
|
|
578
|
+
const v = raw[d.frame.rows[i]];
|
|
579
|
+
if (typeof v !== "number" || !Number.isFinite(v))
|
|
580
|
+
throw new RangeError("offset variable must contain finite numbers");
|
|
581
|
+
offset[i] = offset[i] + (term.log ? Math.log(v) : v);
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
if (fit.model.offsetOptionColumn !== undefined) {
|
|
585
|
+
const raw = getColumn(predictionData, fit.model.offsetOptionColumn);
|
|
586
|
+
for (let i = 0; i < n; i++) {
|
|
587
|
+
const v = raw[d.frame.rows[i]];
|
|
588
|
+
if (typeof v !== "number" || !Number.isFinite(v))
|
|
589
|
+
throw new RangeError("offset variable must contain finite numbers");
|
|
590
|
+
offset[i] = offset[i] + v;
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
else if (fit.model.hasExternalOffset && options.newoffset === undefined) {
|
|
594
|
+
throw new RangeError("newoffset is required when the fit used a vector offset");
|
|
595
|
+
}
|
|
596
|
+
const eta = d.x.map((r, i) => dot(r, fit.coefficients) + offset[i]);
|
|
597
|
+
return options.type === "response" ? eta.map((v) => family.linkinv(v)) : eta;
|
|
598
|
+
}
|
|
599
|
+
function isGeeResult(value) {
|
|
600
|
+
return typeof value === "object" && value !== null &&
|
|
601
|
+
Array.isArray(value.coefficients) && Array.isArray(value.covariance);
|
|
602
|
+
}
|
|
603
|
+
function waldBlock(fit, indices) {
|
|
604
|
+
if (indices.length === 0)
|
|
605
|
+
throw new RangeError("the model comparison adds no coefficients");
|
|
606
|
+
const beta = indices.map((i) => fit.coefficients[i]);
|
|
607
|
+
const covariance = indices.map((i) => indices.map((j) => fit.covariance[i][j]));
|
|
608
|
+
const statistic = dot(beta, multiply(inverse(covariance), beta.map((v) => [v])).map((r) => r[0]));
|
|
609
|
+
return { df: indices.length, statistic, p: pchisq(statistic, indices.length, { lowerTail: false }) };
|
|
610
|
+
}
|
|
611
|
+
function refitForAnova(fit, formula) {
|
|
612
|
+
const rows = fit.rows;
|
|
613
|
+
const columns = Object.entries(fit.model.data).map(([name, column]) => [name, Array.from(column)]);
|
|
614
|
+
const data = Object.fromEntries(columns.map(([name, column]) => [name, rows.map((r) => column[r])]));
|
|
615
|
+
const options = {
|
|
616
|
+
id: fit.model.ids, waves: fit.model.waves, family: fit.model.family,
|
|
617
|
+
...(fit.model.link === undefined ? {} : { link: fit.model.link }),
|
|
618
|
+
corstr: fit.model.corstr, "std.err": "san.se", weights: fit.model.weights, offset: fit.model.offset,
|
|
619
|
+
"scale.fix": fit.model.scaleFix, "scale.value": fit.model.scaleValue, epsilon: fit.model.epsilon, maxit: fit.model.maxit,
|
|
620
|
+
...(fit.model.zcor === undefined ? {} : { zcor: fit.model.zcor }),
|
|
621
|
+
};
|
|
622
|
+
return geeglm(formula, data, options);
|
|
623
|
+
}
|
|
624
|
+
/**
|
|
625
|
+
* Compare GEE terms or nested models using Wald tests.
|
|
626
|
+
* Equivalent to R's `anova()`.
|
|
627
|
+
* @category Regression
|
|
628
|
+
*/
|
|
629
|
+
export function geeAnova(fit, options = {}) {
|
|
630
|
+
if (!isGeeResult(options))
|
|
631
|
+
checkOptions(options, GEE_ANOVA_KEYS, "geeAnova"); // generated: option-keys.mjs
|
|
632
|
+
if (isGeeResult(options)) {
|
|
633
|
+
const reduced = options;
|
|
634
|
+
if (fit.rows.length !== reduced.rows.length || fit.rows.some((r, i) => r !== reduced.rows[i]) ||
|
|
635
|
+
fit.clusterIds.length !== reduced.clusterIds.length ||
|
|
636
|
+
fit.clusterIds.some((v, i) => v !== reduced.clusterIds[i])) {
|
|
637
|
+
throw new RangeError("models must use the same observations and cluster identifiers");
|
|
638
|
+
}
|
|
639
|
+
const oldTerms = reduced.model.termLabels;
|
|
640
|
+
if (oldTerms.length >= fit.model.termLabels.length ||
|
|
641
|
+
oldTerms.some((term, i) => fit.model.termLabels[i] !== term)) {
|
|
642
|
+
throw new RangeError("the second model must be a nested prefix of the first model");
|
|
643
|
+
}
|
|
644
|
+
const indices = fit.model.termAssign.map((a, i) => a > oldTerms.length ? i : -1).filter((i) => i >= 0);
|
|
645
|
+
const test = waldBlock(fit, indices);
|
|
646
|
+
return reported("geeAnova", { rows: [fit.model.formula], columns: ["Df", "X2", "Pr(>Chi)"],
|
|
647
|
+
values: [[test.df, test.statistic, test.p]], warnings: [] }, fit, reduced);
|
|
648
|
+
}
|
|
649
|
+
if (options.test !== undefined && options.test !== "Wald")
|
|
650
|
+
throw new RangeError("only Wald tests are available");
|
|
651
|
+
const labels = fit.model.termLabels;
|
|
652
|
+
if (labels.length === 0) {
|
|
653
|
+
const test = waldBlock(fit, fit.coefficients.map((_, i) => i));
|
|
654
|
+
return reported("geeAnova", { rows: ["Model"], columns: ["Df", "X2", "Pr(>Chi)"],
|
|
655
|
+
values: [[test.df, test.statistic, test.p]], warnings: [] }, fit);
|
|
656
|
+
}
|
|
657
|
+
const rows = [], values = [];
|
|
658
|
+
for (let j = 0; j < labels.length; j++) {
|
|
659
|
+
const prefix = labels.slice(0, j + 1);
|
|
660
|
+
const rhs = (fit.model.intercept ? "" : "0 + ") + prefix.join(" + ");
|
|
661
|
+
const formula = fit.model.responseVariable + " ~ " + rhs;
|
|
662
|
+
const prefixFit = j === labels.length - 1 ? fit : refitForAnova(fit, formula);
|
|
663
|
+
const indices = prefixFit.model.termAssign.map((a, i) => a === j + 1 ? i : -1).filter((i) => i >= 0);
|
|
664
|
+
const test = waldBlock(prefixFit, indices);
|
|
665
|
+
rows.push(labels[j]);
|
|
666
|
+
values.push([test.df, test.statistic, test.p]);
|
|
667
|
+
}
|
|
668
|
+
return reported("geeAnova", { rows, columns: ["Df", "X2", "Pr(>Chi)"], values, warnings: [] }, fit);
|
|
669
|
+
}
|
|
670
|
+
/**
|
|
671
|
+
* Calculate quasi-likelihood information criteria for a GEE fit (Pan, 2001).
|
|
672
|
+
* Equivalent to `geepack::QIC()` in R.
|
|
673
|
+
* @category Regression
|
|
674
|
+
*/
|
|
675
|
+
export function geeQIC(fit) {
|
|
676
|
+
const family = makeFamily(fit.model.family, fit.model.link);
|
|
677
|
+
let q = 0;
|
|
678
|
+
for (let i = 0; i < fit.model.y.length; i++) {
|
|
679
|
+
const y = fit.model.y[i], mu = fit.fittedValues[fit.rows[i]], w = fit.model.weights[i];
|
|
680
|
+
// R's quasi-likelihood for the gaussian family is -RSS / 2 (not divided by the scale)
|
|
681
|
+
if (family.family === "gaussian")
|
|
682
|
+
q -= 0.5 * w * (y - mu) ** 2;
|
|
683
|
+
else if (family.family === "binomial")
|
|
684
|
+
q += w * (y * Math.log(mu) + (1 - y) * Math.log(1 - mu));
|
|
685
|
+
else if (family.family === "poisson")
|
|
686
|
+
q += w * (y * Math.log(mu) - mu);
|
|
687
|
+
else if (family.family === "Gamma")
|
|
688
|
+
q += w * (-y / mu - Math.log(mu));
|
|
689
|
+
}
|
|
690
|
+
const p = fit.coefficients.length;
|
|
691
|
+
// CIC = trace(Omega_I V_R) (Pan 2001): Omega_I is the information of the independence model, the inverse of its
|
|
692
|
+
// model-based covariance, and V_R the robust covariance
|
|
693
|
+
const cicMatrix = multiply(inverse(fit.independenceCovariance), fit.covariance);
|
|
694
|
+
let cic = 0;
|
|
695
|
+
for (let i = 0; i < cicMatrix.length; i++)
|
|
696
|
+
cic += cicMatrix[i][i];
|
|
697
|
+
const qic = -2 * q + 2 * cic;
|
|
698
|
+
const qicu = -2 * q + 2 * p;
|
|
699
|
+
const k = new Set(fit.clusterIds.map((v) => String(v))).size;
|
|
700
|
+
// The finite-sample correction counts both mean-model and estimated working-correlation parameters.
|
|
701
|
+
const totalParams = p + fit.alpha.length;
|
|
702
|
+
return { QIC: qic, QICu: qicu, Q: q, CIC: cic, params: p, QICC: k > totalParams + 1
|
|
703
|
+
? qic + 2 * totalParams * (totalParams + 1) / (k - totalParams - 1) : NaN };
|
|
704
|
+
}
|