@numero-uno-jpn/rstats 1.4.0 → 1.6.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.
Files changed (59) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.ja.md +13 -6
  3. package/README.md +13 -6
  4. package/dist/chunks/{chunk-GEF2YRBV.js → chunk-2I7Z7L5J.js} +2 -2
  5. package/dist/chunks/{chunk-F6Z3GLWA.js → chunk-2TVHT4PF.js} +2 -2
  6. package/dist/chunks/{chunk-GBSMRVUY.js → chunk-3PCHPKBD.js} +2 -2
  7. package/dist/chunks/{chunk-TEHMTQNB.js → chunk-55XSRONZ.js} +2 -2
  8. package/dist/chunks/{chunk-5SW3L6J3.js → chunk-5AITXV3T.js} +2 -2
  9. package/dist/chunks/{chunk-GLGOV3A5.js → chunk-7ZNFRZO4.js} +2 -2
  10. package/dist/chunks/{chunk-56GFP4UU.js → chunk-ABSUQPOG.js} +2 -2
  11. package/dist/chunks/{chunk-RUZATICF.js → chunk-AHFMBHZW.js} +1 -1
  12. package/dist/chunks/chunk-BJTGQ52J.js +2 -0
  13. package/dist/chunks/{chunk-SVS54D6Z.js → chunk-BMEO5X5F.js} +2 -2
  14. package/dist/chunks/chunk-F7G74UNI.js +3 -0
  15. package/dist/chunks/{chunk-HWB7XRX2.js → chunk-FLITCXLY.js} +2 -2
  16. package/dist/chunks/{chunk-PZ66PUWC.js → chunk-KAAUNR3G.js} +1 -1
  17. package/dist/chunks/chunk-KND2BFD5.js +2 -0
  18. package/dist/chunks/{chunk-ZRFZ5UIB.js → chunk-N2PNW4HR.js} +2 -2
  19. package/dist/chunks/{chunk-V2KVTAVV.js → chunk-NVIJXWS6.js} +2 -2
  20. package/dist/chunks/{chunk-J72MLFUG.js → chunk-O5CMNUJL.js} +2 -2
  21. package/dist/chunks/{chunk-WWJGCBWH.js → chunk-OZLDZOOA.js} +1 -1
  22. package/dist/chunks/chunk-RSTU6CX7.js +2 -0
  23. package/dist/chunks/{chunk-GIER5WMB.js → chunk-SFZF44G6.js} +2 -2
  24. package/dist/chunks/{chunk-ZQSOMEIM.js → chunk-TPBVVP32.js} +2 -2
  25. package/dist/chunks/{chunk-S2YCFUCA.js → chunk-WAMHZ47G.js} +2 -2
  26. package/dist/chunks/chunk-XNWSQVXS.js +2 -0
  27. package/dist/chunks/{chunk-X7K6EF7S.js → chunk-Z2XN4NN7.js} +2 -2
  28. package/dist/chunks/{chunk-RY7CCWVU.js → chunk-ZL7EAPO5.js} +1 -1
  29. package/dist/descriptive.js +2 -2
  30. package/dist/distributions.js +2 -2
  31. package/dist/entries/mixed.d.ts +2 -0
  32. package/dist/entries/mixed.js +2 -0
  33. package/dist/entries/tests.d.ts +2 -0
  34. package/dist/entries/tests.js +2 -0
  35. package/dist/htest/sampleSize.d.ts +290 -0
  36. package/dist/htest/sampleSize.js +625 -0
  37. package/dist/linalg.js +2 -2
  38. package/dist/mixed.js +5 -5
  39. package/dist/models/competingRisks.d.ts +1 -1
  40. package/dist/models/competingRisks.js +42 -30
  41. package/dist/models/metaAnalysis.d.ts +207 -0
  42. package/dist/models/metaAnalysis.js +696 -0
  43. package/dist/models/mixedConfint.d.ts +42 -0
  44. package/dist/models/mixedConfint.js +573 -0
  45. package/dist/models/mixedSimulate.d.ts +36 -0
  46. package/dist/models/mixedSimulate.js +232 -0
  47. package/dist/numerics.js +2 -2
  48. package/dist/rstats.js +19 -16
  49. package/dist/special.js +2 -2
  50. package/dist/tests.js +16 -13
  51. package/llms.txt +8 -3
  52. package/package.json +1 -1
  53. package/dist/chunks/chunk-27VFB3SA.js +0 -2
  54. package/dist/chunks/chunk-6FZAJQ4H.js +0 -2
  55. package/dist/chunks/chunk-BQJFFGYP.js +0 -2
  56. package/dist/chunks/chunk-H72MW7YP.js +0 -2
  57. package/dist/chunks/chunk-UMMCVF53.js +0 -2
  58. package/dist/chunks/chunk-UNP4HBPP.js +0 -3
  59. package/dist/chunks/chunk-YBOSCQF2.js +0 -2
@@ -0,0 +1,696 @@
1
+ // Meta-analysis and effect sizes.
2
+ // Written for rStats.js (no ported code), from oracle/meta-behaviour.md, the published references listed there,
3
+ // and the public-API fixtures. The calculations below are derived from the documented weighted least-squares,
4
+ // likelihood, and moment equations; no R or package implementation is used.
5
+ import { pchisq, qchisq } from "../distributions/chisq.js";
6
+ import { pnorm, qnorm } from "../distributions/normal.js";
7
+ import { pf } from "../distributions/f.js";
8
+ import { pt, qt } from "../distributions/t.js";
9
+ import { solve } from "../linalg/solve.js";
10
+ import { reported } from "../internal/warnings.js";
11
+ import { parseFormula } from "./formula.js";
12
+ import { design } from "./modelMatrix.js";
13
+ import { ddDiv, ddMul, ddSub, twoProd, twoSum } from "../special/dd.js";
14
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
15
+ import { checkOptions, nestedOptions } from "../internal/checkOptions.js";
16
+ import { isOptionsObject } from "../internal/optionalArgs.js";
17
+ const ESCALC_KEYS = /* @__PURE__ */ new Set([
18
+ "ai", "bi", "ci", "di", "m1i", "sd1i", "n1i", "m2i", "sd2i", "n2i", "ri", "ni", "add", "to", "drop00",
19
+ ]);
20
+ const RMA_KEYS = ["method", "mods", "data", "intercept", "test", "level", "control"];
21
+ const RMA_CONTROL_KEYS = ["tau2Init", "threshold", "maxiter", "stepadj", "tol", "tau2Max"];
22
+ const CONFINT_RMA_KEYS = ["type", "level"];
23
+ const PREDICT_RMA_KEYS = ["newmods", "predtype", "level"];
24
+ const REGTEST_KEYS = ["model", "predictor", "retFit", "level"];
25
+ const scalar = (x) => x.length === 1 ? x[0] : x;
26
+ const dot = (a, b) => a.reduce((s, x, i) => s + x * b[i], 0);
27
+ const matVec = (a, x) => a.map(r => dot(r, x));
28
+ const identity = (n) => Array.from({ length: n }, (_, i) => Array.from({ length: n }, (_, j) => i === j ? 1 : 0));
29
+ const root = (f, lo, hi, tol = 1e-14) => {
30
+ let fl = f(lo), fh = f(hi);
31
+ if (fl === 0)
32
+ return lo;
33
+ if (fh === 0)
34
+ return hi;
35
+ if (!(fl * fh < 0))
36
+ return NaN;
37
+ for (let i = 0; i < 180; i++) {
38
+ const mid = lo + (hi - lo) / 2, fm = f(mid);
39
+ if (!Number.isFinite(fm)) {
40
+ hi = mid;
41
+ continue;
42
+ }
43
+ if (Math.abs(hi - lo) <= tol * Math.max(1, Math.abs(mid)) || fm === 0)
44
+ return mid;
45
+ if (fl * fm <= 0) {
46
+ hi = mid;
47
+ fh = fm;
48
+ }
49
+ else {
50
+ lo = mid;
51
+ fl = fm;
52
+ }
53
+ }
54
+ return lo + (hi - lo) / 2;
55
+ };
56
+ const upperRoot = (f, start) => {
57
+ let hi = Math.max(start, 1e-8), value = f(hi);
58
+ for (let i = 0; i < 80 && value > 0; i++) {
59
+ hi *= 2;
60
+ value = f(hi);
61
+ }
62
+ return value <= 0 ? root(f, 0, hi) : NaN;
63
+ };
64
+ function weightedFit(y, v, X, tau2) {
65
+ const k = y.length, p = X[0].length, variance = v.map(z => z + tau2);
66
+ // Work with weights relative to the smallest variance. This keeps X'WX and the
67
+ // projection matrix finite when 1/vi or sum(1/vi) would overflow.
68
+ const minVariance = variance.reduce((a, z) => Math.min(a, z), Infinity);
69
+ const weights = variance.map(z => minVariance / z);
70
+ const sumWeights = weights.reduce((a, z) => a + z, 0);
71
+ const xtwx = Array.from({ length: p }, (_, a) => Array.from({ length: p }, (_, b) => X.reduce((s, row, i) => s + weights[i] * row[a] * row[b], 0)));
72
+ const xtwy = Array.from({ length: p }, (_, a) => X.reduce((s, row, i) => s + weights[i] * row[a] * y[i], 0));
73
+ let covNorm;
74
+ try {
75
+ covNorm = solve(xtwx, identity(p));
76
+ }
77
+ catch {
78
+ throw new RangeError("Model matrix is not full rank.");
79
+ }
80
+ const beta = matVec(covNorm, xtwy);
81
+ const fitted = matVec(X, beta);
82
+ const residuals = y.map((z, i) => z - fitted[i]);
83
+ const qeScaled = y.every(z => z === y[0]) ? 0 : residuals.reduce((s, z, i) => s + weights[i] * z * z, 0);
84
+ const qe = qeScaled / minVariance;
85
+ const P = Array.from({ length: k }, (_, i) => Array.from({ length: k }, (_, j) => (i === j ? weights[i] : 0) - weights[i] * dot(X[i], matVec(covNorm, X[j]).map((z) => z * weights[j]))));
86
+ const tracePNorm = P.reduce((s, row, i) => s + row[i], 0);
87
+ const traceP = tracePNorm / minVariance;
88
+ const traceP2Norm = P.reduce((s, row, i) => s + row.reduce((t, z, j) => t + z * P[j][i], 0), 0);
89
+ const traceP2 = traceP2Norm / minVariance / minVariance;
90
+ const py = P.map(row => dot(row, y));
91
+ // score and information share the omitted 1/minVariance^2 factor, so their
92
+ // ratio (the Newton step) is evaluated without forming that potentially infinite factor.
93
+ const score = 0.5 * (dot(py, py) - minVariance * tracePNorm);
94
+ const mlScore = 0.5 * (residuals.reduce((s, z, i) => s + z * z * weights[i] * weights[i], 0) - minVariance * weights.reduce((s, z) => s + z, 0));
95
+ const sumWeightSquaredNorm = weights.reduce((s, z) => s + z * z, 0);
96
+ const mlInfo = 0.5 * sumWeightSquaredNorm;
97
+ const logdetNorm = xtwx.length === 1 ? Math.log(xtwx[0][0]) : Math.log(Math.abs(determinantSmall(xtwx)));
98
+ const logLik = -0.5 * (variance.reduce((s, z) => s + Math.log(z), 0) + logdetNorm - p * Math.log(minVariance) + qe);
99
+ const cov = covNorm.map(row => row.map(z => z * minVariance));
100
+ const se = covNorm.map((row, i) => Math.sqrt(Math.max(0, row[i])) * Math.sqrt(minVariance));
101
+ return { beta, cov, se, fitted, residuals, qe, qeScaled, weights, minVariance, P, traceP, tracePNorm, traceP2, traceP2Norm,
102
+ score, mlScore, mlInfo, logLik, sumWeightsNorm: sumWeights, sumWeightSquaredNorm };
103
+ }
104
+ function determinantSmall(a) {
105
+ const n = a.length, m = a.map(r => r.slice());
106
+ let d = 1;
107
+ for (let j = 0; j < n; j++) {
108
+ let p = j;
109
+ for (let i = j + 1; i < n; i++)
110
+ if (Math.abs(m[i][j]) > Math.abs(m[p][j]))
111
+ p = i;
112
+ if (m[p][j] === 0)
113
+ return 0;
114
+ if (p !== j) {
115
+ [m[p], m[j]] = [m[j], m[p]];
116
+ d = -d;
117
+ }
118
+ const q = m[j][j];
119
+ d *= q;
120
+ for (let i = j + 1; i < n; i++) {
121
+ const z = m[i][j] / q;
122
+ for (let c = j + 1; c < n; c++)
123
+ m[i][c] -= z * m[j][c];
124
+ }
125
+ }
126
+ return d;
127
+ }
128
+ function tracePVPV(P, V) {
129
+ // P is the projection matrix normalized by the common inverse-weight scale.
130
+ // The omitted 1/minVariance^2 cancels in the DL/HS standard-error ratios.
131
+ return P.reduce((s, row, i) => s + row.reduce((a, z, j) => a + z * V[j] * P[j][i] * V[i], 0), 0);
132
+ }
133
+ function tau2StandardError(y, v, X, method, tau2, fit, base) {
134
+ const k = y.length, df = k - X[0].length, V = v.map(z => z + tau2);
135
+ if (method === "EE" || method === "FE")
136
+ return NaN;
137
+ if (method === "REML")
138
+ return fit.traceP2Norm > 0 ? fit.minVariance * Math.sqrt(2 / fit.traceP2Norm) : NaN;
139
+ if (method === "ML")
140
+ return fit.sumWeightSquaredNorm > 0 ? fit.minVariance * Math.sqrt(2 / fit.sumWeightSquaredNorm) : NaN;
141
+ if (method === "DL" || method === "HS" || method === "HSk") {
142
+ const numerator = Math.sqrt(2 * tracePVPV(base.P, V));
143
+ const denominator = method === "DL" ? base.tracePNorm : method === "HS" ? base.sumWeightsNorm : (base.sumWeightsNorm * (k - 1) / k);
144
+ return denominator > 0 ? numerator / denominator : NaN;
145
+ }
146
+ if (method === "HE") {
147
+ const unweighted = weightedFit(y, Array(k).fill(1), X, 0);
148
+ return df > 0 ? Math.sqrt(2 * tracePVPV(unweighted.P, V)) / df : NaN;
149
+ }
150
+ if (method === "SJ") {
151
+ const unweighted = weightedFit(y, Array(k).fill(1), X, 0), initial = unweighted.residuals.reduce((s, z) => s + z * z, 0) / k;
152
+ if (!(initial > 0) || df <= 0)
153
+ return NaN;
154
+ const initialFit = weightedFit(y, v, X, initial);
155
+ return initial / df * Math.sqrt(2 * tracePVPV(initialFit.P, V)) / initialFit.minVariance;
156
+ }
157
+ // First-order delta method for Q(tau^2)=df. The normalized weights avoid forming w_i^2.
158
+ const denominator = fit.residuals.reduce((s, z, i) => s + fit.weights[i] * fit.weights[i] * z * z, 0);
159
+ return denominator > 0 && df > 0 ? Math.sqrt(2 * df) * fit.minVariance * fit.minVariance / denominator : NaN;
160
+ }
161
+ function tauEstimate(y, v, X, method, control) {
162
+ const k = y.length, p = X[0].length, df = k - p;
163
+ const base = weightedFit(y, v, X, 0);
164
+ if (method === "EE" || method === "FE")
165
+ return 0;
166
+ if (method === "DL")
167
+ return Math.max(0, (base.qeScaled - df * base.minVariance) / base.tracePNorm);
168
+ if (method === "HS")
169
+ return Math.max(0, (base.qeScaled - k * base.minVariance) / base.sumWeightsNorm);
170
+ if (method === "HSk")
171
+ return Math.max(0, ((k / (k - 1)) * base.qeScaled - k * base.minVariance) / base.sumWeightsNorm);
172
+ const unweighted = weightedFit(y, Array(k).fill(1), X, 0);
173
+ const raw = unweighted.residuals.reduce((s, z) => s + z * z, 0);
174
+ const he = Math.max(0, (raw - v.reduce((s, z, i) => s + unweighted.P[i][i] * z, 0)) / Math.max(1, df));
175
+ if (method === "HE")
176
+ return he;
177
+ if (method === "SJ") {
178
+ const initial = raw / k;
179
+ const fit = weightedFit(y, v, X, initial);
180
+ const a = v.map(z => initial / (z + initial));
181
+ return Math.max(0, a.reduce((s, z, i) => s + z * fit.residuals[i] * fit.residuals[i], 0) / Math.max(1, df));
182
+ }
183
+ const qFunction = (t) => weightedFit(y, v, X, t).qe - df;
184
+ if (method === "EB") {
185
+ const hi = control.tau2Max ?? Math.max(100, 10 * raw / k);
186
+ return Math.max(0, root(qFunction, 0, hi, 1e-14));
187
+ }
188
+ if (method === "PM") {
189
+ let hi = control.tau2Max ?? Math.max(100, 10 * raw / k);
190
+ while (qFunction(hi) > 0 && hi < Number.MAX_VALUE / 4)
191
+ hi *= 2;
192
+ const tol = control.tol ?? 1e-14;
193
+ return Math.max(0, root(qFunction, 0, hi, tol));
194
+ }
195
+ let tau2 = Math.max(0, control.tau2Init ?? he);
196
+ const maxiter = control.maxiter ?? 100, threshold = control.threshold ?? 1e-5, stepadj = control.stepadj ?? 1;
197
+ if (maxiter <= 1)
198
+ return tau2;
199
+ for (let i = 0; i < maxiter; i++) {
200
+ const fit = weightedFit(y, v, X, tau2);
201
+ const score = method === "REML" ? fit.score : fit.mlScore;
202
+ const information = method === "REML" ? 0.5 * fit.traceP2Norm : fit.mlInfo;
203
+ if (!(information > 0) || !Number.isFinite(information))
204
+ return tau2;
205
+ const next = Math.max(0, tau2 + stepadj * score / information);
206
+ if (!Number.isFinite(next))
207
+ return tau2;
208
+ if (Math.abs(next - tau2) < threshold)
209
+ return next;
210
+ tau2 = next;
211
+ }
212
+ return tau2;
213
+ }
214
+ function independentColumnIndices(rows) {
215
+ if (rows.length === 0 || rows[0].length === 0)
216
+ return [];
217
+ const keep = [], basis = [];
218
+ for (let j = 0; j < rows[0].length; j++) {
219
+ const v = rows.map(r => r[j]);
220
+ const original = Math.sqrt(dot(v, v));
221
+ let residual = v.slice();
222
+ for (const q of basis) {
223
+ const a = dot(residual, q);
224
+ residual = residual.map((z, i) => z - a * q[i]);
225
+ }
226
+ const norm = Math.sqrt(dot(residual, residual));
227
+ if (original > 0 && norm > 1e-10 * original) {
228
+ keep.push(j);
229
+ basis.push(residual.map(z => z / norm));
230
+ }
231
+ }
232
+ return keep;
233
+ }
234
+ function buildDesign(k, mods, intercept, data) {
235
+ let rows, names = [], explicitNames = false, rawModeratorCount = 0;
236
+ if (typeof mods === "string") {
237
+ if (data === undefined)
238
+ throw new TypeError("data is required when mods is a formula");
239
+ const f = mods.includes("~") ? mods : `~ ${mods}`;
240
+ const d = design(parseFormula(f), data, { intercept });
241
+ rows = d.x;
242
+ names = d.colNames.map(n => n === "(Intercept)" ? "intrcpt" : n);
243
+ if (d.frame.rows.length !== k)
244
+ throw new RangeError("variable lengths differ between yi and mods");
245
+ if (rows[0].length > k)
246
+ throw new Error("Number of parameters to be estimated is larger than the number of observations.");
247
+ const keep = independentColumnIndices(rows);
248
+ return { x: rows.map(r => keep.map(j => r[j])), names: keep.map(j => names[j] ?? ""), warnings: keep.length < rows[0].length ? ["Redundant predictors dropped from the model."] : [] };
249
+ }
250
+ else if (mods === undefined) {
251
+ rows = Array.from({ length: k }, () => []);
252
+ }
253
+ else if (Array.isArray(mods)) {
254
+ if (mods.length === 0)
255
+ rows = Array.from({ length: k }, () => []);
256
+ else if (typeof mods[0] === "number") {
257
+ const v = Array.from(mods, Number);
258
+ if (v.length !== k)
259
+ throw new RangeError("variable lengths differ (found for 'mods')");
260
+ rows = v.map(z => [z]);
261
+ rawModeratorCount = 1;
262
+ }
263
+ else {
264
+ const matrix = mods;
265
+ if (matrix.length === k) {
266
+ rows = Array.from(matrix, r => Array.from(r, Number));
267
+ rawModeratorCount = rows[0]?.length ?? 0;
268
+ }
269
+ else if (matrix.every(col => col.length === k)) {
270
+ rawModeratorCount = matrix.length;
271
+ rows = Array.from({ length: k }, (_, i) => matrix.map(col => Number(col[i])));
272
+ }
273
+ else
274
+ throw new RangeError("variable lengths differ (found for 'mods')");
275
+ }
276
+ }
277
+ else {
278
+ const m = mods;
279
+ if (m.rows !== undefined) {
280
+ const first = m.rows[0];
281
+ if (first !== undefined && first !== null && typeof first === "object" && !Array.isArray(first)) {
282
+ const keys = typeof m.colNames === "string" ? [m.colNames] : m.colNames === undefined || m.colNames === null ? Object.keys(first) : Array.from(m.colNames);
283
+ rows = m.rows.map(r => keys.map(name => Number(r[name])));
284
+ names = keys.map(n => n === "(Intercept)" ? "intrcpt" : n);
285
+ explicitNames = true;
286
+ rawModeratorCount = keys.length;
287
+ }
288
+ else {
289
+ rows = m.rows.map(r => Array.from(r, Number));
290
+ rawModeratorCount = rows[0]?.length ?? 0;
291
+ }
292
+ }
293
+ else if (m.columns !== undefined) {
294
+ rawModeratorCount = m.columns.length;
295
+ rows = Array.from({ length: k }, (_, i) => m.columns.map(col => Number(col[i])));
296
+ }
297
+ else
298
+ throw new TypeError("mods matrix must have rows or columns");
299
+ if (rows.length !== k)
300
+ throw new RangeError("variable lengths differ (found for 'mods')");
301
+ if (m.colNames !== undefined && m.colNames !== null) {
302
+ names = (typeof m.colNames === "string" ? [m.colNames] : Array.from(m.colNames)).map(n => n === "(Intercept)" ? "intrcpt" : n);
303
+ explicitNames = true;
304
+ }
305
+ }
306
+ if (rows.some(r => r.length !== rows[0].length))
307
+ throw new TypeError("all rows of the moderator matrix must have the same length");
308
+ if (!explicitNames)
309
+ names = Array.from({ length: rawModeratorCount }, (_, j) => rawModeratorCount > 1 ? `.${j + 1}` : "");
310
+ if (intercept) {
311
+ rows = rows.map(r => [1, ...r]);
312
+ names = ["intrcpt", ...names];
313
+ }
314
+ if (rows[0].length > k)
315
+ throw new Error("Number of parameters to be estimated is larger than the number of observations.");
316
+ const keep = independentColumnIndices(rows), dropped = keep.length < rows[0].length;
317
+ if (dropped && !explicitNames && rawModeratorCount > 0) {
318
+ for (let j = 0; j < keep.length; j++)
319
+ if (keep[j] !== 0 || !intercept) {
320
+ names[keep[j]] = "";
321
+ break;
322
+ }
323
+ }
324
+ return { x: rows.map(r => keep.map(j => r[j])), names: keep.map(j => names[j] ?? ""), warnings: keep.length < rows[0].length ? ["Redundant predictors dropped from the model."] : [] };
325
+ }
326
+ /** Natural logarithm of the gamma function (Lanczos approximation). */
327
+ function logGamma(x) {
328
+ const coefficients = [676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7];
329
+ if (x < 0.5)
330
+ return Math.log(Math.PI) - Math.log(Math.sin(Math.PI * x)) - logGamma(1 - x);
331
+ const z = x - 1;
332
+ let a = 0.99999999999980993;
333
+ for (let i = 0; i < coefficients.length; i++)
334
+ a += coefficients[i] / (z + i + 1);
335
+ const t = z + 7.5;
336
+ return 0.9189385332046727 + (z + 0.5) * Math.log(t) - t + Math.log(a);
337
+ }
338
+ function countScale(a, b, c, d) {
339
+ const max = Math.max(a, b, c, d);
340
+ return max === 0 ? 0 : 2 ** Math.floor(Math.log2(max));
341
+ }
342
+ /** A cross-product difference divided by the measure-specific denominator, without
343
+ * rounding two nearly equal products to the same binary64 value. Counts are first scaled
344
+ * by their maximum so the products stay in range; double-double arithmetic retains the
345
+ * small determinant (a*d - b*c).
346
+ */
347
+ function crossProductRatio(a, b, c, d, measure) {
348
+ const scale = countScale(a, b, c, d);
349
+ if (scale === 0)
350
+ return NaN;
351
+ const an = a / scale, bn = b / scale, cn = c / scale, dn = d / scale;
352
+ const numerator = ddSub(twoProd(an, dn), twoProd(bn, cn));
353
+ const ab = twoSum(an, bn), cd = twoSum(cn, dn);
354
+ const denominator = measure === "RR" ? ddMul([cn, 0], ab) : measure === "OR" ? twoProd(bn, cn) : ddMul(ab, cd);
355
+ const quotient = ddDiv(numerator, denominator);
356
+ return quotient[0] + quotient[1];
357
+ }
358
+ /** Hedges' small-sample correction J(df) = Gamma(df/2) / (sqrt(df/2) Gamma((df-1)/2)).
359
+ * The gamma-log difference loses several digits when df is very large; use its asymptotic
360
+ * log-ratio expansion in inverse powers of x=df/2 in that range.
361
+ */
362
+ function hedgesCorrection(df) {
363
+ const x = df / 2;
364
+ if (x > 1000) {
365
+ const u = 1 / x, u2 = u * u, u3 = u2 * u, u4 = u2 * u2, u5 = u4 * u, u6 = u3 * u3, u7 = u6 * u, u8 = u4 * u4;
366
+ const logJ = -(3 / 8) * u - (1 / 8) * u2 - (3 / 64) * u3 - (1 / 64) * u4 - (3 / 640) * u5 - (1 / 384) * u6 - (33 / 14336) * u7 - (1 / 2048) * u8;
367
+ return Math.exp(logJ);
368
+ }
369
+ return Math.exp(logGamma(x) - 0.5 * Math.log(x) - logGamma(x - 0.5));
370
+ }
371
+ /**
372
+ * Computes study-level effect sizes and sampling variances. Equivalent to `metafor::escalc()` in R.
373
+ *
374
+ * @param measure One of RR, OR, RD, MD, SMD or ZCOR.
375
+ * @param options Study-level counts, means, standard deviations, sample sizes or correlations.
376
+ * @returns The estimates yi and sampling variances vi.
377
+ * @category Meta-analysis
378
+ */
379
+ export function escalc(measure, options) {
380
+ checkOptions(options, ESCALC_KEYS, "escalc"); // generated: option-keys.mjs
381
+ const warnings = [];
382
+ const get = (key) => options[key] === undefined ? undefined : Array.from(options[key]);
383
+ const keys = {
384
+ RR: ["ai", "bi", "ci", "di"], OR: ["ai", "bi", "ci", "di"], RD: ["ai", "bi", "ci", "di"],
385
+ MD: ["m1i", "sd1i", "n1i", "m2i", "sd2i", "n2i"], SMD: ["m1i", "sd1i", "n1i", "m2i", "sd2i", "n2i"], ZCOR: ["ri", "ni"]
386
+ };
387
+ const data = keys[measure].map(k => get(k));
388
+ const anyZero = data.slice(0, 4).some(x => x.some(z => z === 0));
389
+ if (data.some(x => x === undefined))
390
+ throw new TypeError(`missing required arguments for measure ${measure}`);
391
+ const n = data[0].length;
392
+ if (data.some(x => x.length !== n))
393
+ throw new RangeError("variable lengths differ");
394
+ const yi = [], vi = [];
395
+ for (let i = 0; i < n; i++) {
396
+ let y = NaN, v = NaN;
397
+ if (measure === "ZCOR") {
398
+ const r = data[0][i], size = data[1][i];
399
+ if (Math.abs(r) > 1)
400
+ throw new RangeError("One or more correlations are > 1 or < -1.");
401
+ if (!(size > 3)) {
402
+ warnings.push("Cannot estimate the sampling variance when ni <= 3.");
403
+ y = Math.atanh(r);
404
+ v = NaN;
405
+ }
406
+ else {
407
+ y = Math.atanh(r);
408
+ v = 1 / (size - 3);
409
+ }
410
+ }
411
+ else if (measure === "MD" || measure === "SMD") {
412
+ const m1 = data[0][i], sd1 = data[1][i], n1 = data[2][i], m2 = data[3][i], sd2 = data[4][i], n2 = data[5][i];
413
+ if (!(n1 > 1 && n2 > 1 && sd1 >= 0 && sd2 >= 0))
414
+ throw new RangeError("invalid means, standard deviations, or sample sizes");
415
+ if (measure === "MD") {
416
+ y = m1 - m2;
417
+ v = sd1 * sd1 / n1 + sd2 * sd2 / n2;
418
+ }
419
+ else {
420
+ const df = n1 + n2 - 2, sp2 = ((n1 - 1) * sd1 * sd1 + (n2 - 1) * sd2 * sd2) / df;
421
+ const d = (m1 - m2) / Math.sqrt(sp2);
422
+ const J = hedgesCorrection(df);
423
+ y = J * d;
424
+ v = (n1 + n2) / (n1 * n2) + y * y / (2 * (n1 + n2));
425
+ }
426
+ }
427
+ else {
428
+ const a0 = data[0][i], b0 = data[1][i], c0 = data[2][i], d0 = data[3][i];
429
+ let a = a0, b = b0, c = c0, d = d0;
430
+ const correction = options.add ?? 0.5, to = options.to ?? "only0";
431
+ const zero = [a, b, c, d].some(z => z === 0);
432
+ const apply = to === "all" || (to === "only0" && zero) || (to === "if0all" && anyZero);
433
+ if (measure !== "RD" && apply) {
434
+ a += correction;
435
+ b += correction;
436
+ c += correction;
437
+ d += correction;
438
+ }
439
+ if (measure === "RD" && apply) {
440
+ a += correction;
441
+ b += correction;
442
+ c += correction;
443
+ d += correction;
444
+ }
445
+ if (options.drop00 && (a0 === 0 && c0 === 0 || b0 === 0 && d0 === 0)) {
446
+ yi.push(NaN);
447
+ vi.push(NaN);
448
+ continue;
449
+ }
450
+ const scale = countScale(a, b, c, d), an = a / scale, bn = b / scale, cn = c / scale, dn = d / scale;
451
+ const ab = an + bn, cd = cn + dn, invScale = 1 / scale;
452
+ if (measure === "RR") {
453
+ y = Math.log1p(crossProductRatio(a, b, c, d, "RR"));
454
+ v = invScale * (bn / (an * ab) + dn / (cn * cd));
455
+ }
456
+ else if (measure === "OR") {
457
+ y = Math.log1p(crossProductRatio(a, b, c, d, "OR"));
458
+ v = invScale * (1 / an + 1 / bn + 1 / cn + 1 / dn);
459
+ }
460
+ else {
461
+ y = crossProductRatio(a, b, c, d, "RD");
462
+ v = invScale * (an * bn / (ab * ab * ab) + cn * dn / (cd * cd * cd));
463
+ }
464
+ }
465
+ yi.push(y);
466
+ vi.push(v);
467
+ }
468
+ return reported("escalc", { yi, vi, measure, warnings });
469
+ }
470
+ /**
471
+ * Fits an equal-effects or random-effects meta-analysis, including meta-regression. Equivalent to `metafor::rma.uni()` in R.
472
+ *
473
+ * @param yi Study effect estimates, or the result of {@link escalc}.
474
+ * @param vi Sampling variances (omitted when yi is an escalc result).
475
+ * @param options Estimator, moderators, inference and iteration controls.
476
+ * @returns Coefficients, heterogeneity statistics, tests and model metadata.
477
+ * @category Meta-analysis
478
+ */
479
+ export function rma(yi, viOrOptions, maybeOptions = {}) {
480
+ if (isOptionsObject(viOrOptions))
481
+ checkOptions(viOrOptions, RMA_KEYS, "rma"); // generated: option-keys.mjs
482
+ if (isOptionsObject(viOrOptions))
483
+ checkOptions(nestedOptions(viOrOptions, "control"), RMA_CONTROL_KEYS, "rma", "control"); // generated: option-keys.mjs
484
+ checkOptions(maybeOptions, RMA_KEYS, "rma"); // generated: option-keys.mjs
485
+ checkOptions(nestedOptions(maybeOptions, "control"), RMA_CONTROL_KEYS, "rma", "control"); // generated: option-keys.mjs
486
+ const isEscalc = typeof yi === "object" && "yi" in yi;
487
+ const y = Array.from(isEscalc ? yi.yi : yi);
488
+ const opts = (isEscalc ? viOrOptions : maybeOptions) ?? {};
489
+ const v = Array.from(isEscalc ? yi.vi : viOrOptions ?? []);
490
+ if (y.length === 0 || v.length !== y.length)
491
+ throw new RangeError("yi and vi must have the same positive length");
492
+ if (y.some(z => !Number.isFinite(z)))
493
+ throw new Error("NA/NaN/Inf in foreign function call (arg 1)");
494
+ if (v.some(z => !Number.isFinite(z)))
495
+ throw new Error("NA/NaN/Inf in foreign function call (arg 1)");
496
+ if (opts.method === "DL" && v.some(z => z <= 0))
497
+ throw new Error("DL estimator cannot be used when there are non-positive sampling variances in the data.");
498
+ if (v.some(z => z < 0))
499
+ throw new RangeError("sampling variances must be non-negative");
500
+ if (v.some(z => z === 0) && !["EE", "FE"].includes(opts.method ?? "REML")) {
501
+ throw new RangeError("random-effects estimators require positive sampling variances");
502
+ }
503
+ const method = opts.method ?? "REML", test = opts.test ?? "z", level = opts.level ?? 95, intercept = opts.intercept ?? true;
504
+ const built = buildDesign(y.length, opts.mods, intercept, opts.data), X = built.x;
505
+ const p = X[0].length, k = y.length, df = k - p, hasIntercept = built.names[0] === "intrcpt" || (!intercept && X.every(r => r[0] === 1));
506
+ if (p === 0)
507
+ throw new RangeError("the model must contain at least one coefficient");
508
+ if (k < p)
509
+ throw new Error("Number of parameters to be estimated is larger than the number of observations.");
510
+ if (!(level > 0 && level < 100))
511
+ throw new RangeError("level must be between 0 and 100");
512
+ if (!["EE", "FE", "DL", "HE", "HS", "HSk", "SJ", "ML", "REML", "EB", "PM"].includes(method))
513
+ throw new RangeError(`unknown method '${method}'`);
514
+ if (!["z", "t", "knha"].includes(test))
515
+ throw new RangeError(`unknown test '${test}'`);
516
+ if (method === "DL" && !Number.isFinite(weightedFit(y, v, X, 0).qe))
517
+ throw new Error("NA/NaN/Inf in foreign function call (arg 1)");
518
+ const baseFit = weightedFit(y, v, X, 0);
519
+ const tau2 = tauEstimate(y, v, X, method, opts.control ?? {});
520
+ const fit = weightedFit(y, v, X, tau2);
521
+ const tau2Null = opts.mods === undefined ? tau2 : tauEstimate(y, v, Array.from({ length: k }, () => [1]), method, opts.control ?? {});
522
+ const kh = test === "knha" && df > 0 ? Math.max(1, fit.qe / df) : 1;
523
+ const covariance = fit.cov.map(row => row.map(z => z * kh));
524
+ const se = fit.se.map(z => z * Math.sqrt(kh));
525
+ const stat = fit.beta.map((b, i) => b / se[i]);
526
+ const crit = test === "z" ? qnorm(1 - (1 - level / 100) / 2) : qt(1 - (1 - level / 100) / 2, df);
527
+ const pv = stat.map(z => 2 * (test === "z" ? pnorm(-Math.abs(z)) : pt(-Math.abs(z), df)));
528
+ const lower = fit.beta.map((b, i) => b - crit * se[i]);
529
+ const upper = fit.beta.map((b, i) => b + crit * se[i]);
530
+ const start = hasIntercept ? 1 : 0, m = p === 1 ? 1 : Math.max(1, p - start);
531
+ let qm = 0, qmp = 1;
532
+ if (p === 1) {
533
+ qm = stat[0] * stat[0];
534
+ qmp = test === "z" ? pchisq(qm, 1, { lowerTail: false }) : pf(qm, 1, df, { lowerTail: false });
535
+ }
536
+ else {
537
+ const b = fit.beta.slice(start), c = covariance.slice(start).map(row => row.slice(start));
538
+ try {
539
+ qm = dot(b, solve(c, b));
540
+ }
541
+ catch {
542
+ qm = NaN;
543
+ }
544
+ qmp = test === "z" ? pchisq(qm, m, { lowerTail: false }) : pf(qm / m, m, df, { lowerTail: false });
545
+ }
546
+ const residualPrecision = baseFit.tracePNorm;
547
+ const vtilde = df > 0 ? df * baseFit.minVariance / residualPrecision : 0;
548
+ const I2 = method === "EE" || method === "FE"
549
+ ? (baseFit.qe > 0 ? 100 * Math.max(0, (baseFit.qe - df) / baseFit.qe) : 0)
550
+ : (tau2 === 0 ? 0 : 100 * tau2 / (tau2 + vtilde));
551
+ const H2 = method === "EE" || method === "FE"
552
+ ? (df > 0 ? Math.max(1, baseFit.qe / df) : 1)
553
+ : (tau2 === 0 ? 1 : (tau2 + vtilde) / vtilde);
554
+ const R2 = opts.mods === undefined || p === 1 ? null : (tau2Null > 0 ? 100 * Math.max(0, (tau2Null - tau2) / tau2Null) : 0);
555
+ const info = tau2StandardError(y, v, X, method, tau2, fit, baseFit);
556
+ return reported("rma", { beta: { dim: [p, 1], rowNames: p === 1 ? (built.names[0] ?? "intrcpt") : built.names, colNames: null, rows: fit.beta.map(z => [z]) }, se: scalar(se), zval: scalar(stat), pval: scalar(pv),
557
+ "ci.lb": scalar(lower), "ci.ub": scalar(upper), tau2, "se.tau2": info, QE: baseFit.qe, QEp: df === 0 ? 1 : pchisq(baseFit.qe, df, { lowerTail: false }),
558
+ QM: qm, QMp: qmp, R2, p, m, I2, H2, k, yi: y, vi: v, mods: X, intercept: hasIntercept, method, test, level, warnings: built.warnings, covariance, tau2Null });
559
+ }
560
+ /** Computes heterogeneity confidence intervals. Equivalent to `metafor::confint.rma()` in R.
561
+ * @category Meta-analysis
562
+ */
563
+ export function confintRma(object, options = {}) {
564
+ checkOptions(options, CONFINT_RMA_KEYS, "confintRma"); // generated: option-keys.mjs
565
+ const type = options.type ?? "QP", level = options.level ?? object.level, alpha = 1 - level / 100;
566
+ if (type !== "QP" && type !== "PL")
567
+ throw new RangeError("type must be 'QP' or 'PL'");
568
+ const fit = weightedFit(object.yi, object.vi, object.mods, object.tau2), df = object.k - object.mods[0].length;
569
+ let lo = 0, hi = NaN;
570
+ if (type === "QP") {
571
+ const base = weightedFit(object.yi, object.vi, object.mods, 0);
572
+ const qUpper = qchisq(1 - alpha / 2, df), qLower = qchisq(alpha / 2, df);
573
+ const qAtZero = base.qe;
574
+ const qAt = (t) => weightedFit(object.yi, object.vi, object.mods, t).qe;
575
+ lo = qAtZero <= qUpper ? 0 : upperRoot(t => qAt(t) - qUpper, Math.max(object.tau2, 1e-8));
576
+ hi = qAtZero <= qLower ? NaN : upperRoot(t => qAt(t) - qLower, Math.max(object.tau2, 1e-8));
577
+ }
578
+ else {
579
+ const cutoff = qchisq(level / 100, 1);
580
+ const ll = (t) => weightedFit(object.yi, object.vi, object.mods, t).logLik;
581
+ const target = (t) => 2 * (fit.logLik - ll(t)) - cutoff;
582
+ if (object.tau2 > 0) {
583
+ // If tau²=0 is inside the likelihood-ratio confidence set, the lower
584
+ // endpoint is the boundary itself, not a root between 0 and the estimate.
585
+ lo = target(0) <= 0 ? 0 : root(target, 0, object.tau2);
586
+ let upper = Math.max(object.tau2 * 2, 1e-8), value = target(upper);
587
+ for (let i = 0; i < 80 && value < 0; i++) {
588
+ upper *= 2;
589
+ value = target(upper);
590
+ }
591
+ hi = value >= 0 ? root(target, object.tau2, upper) : NaN;
592
+ }
593
+ else {
594
+ let upper = 1e-8, value = target(upper);
595
+ for (let i = 0; i < 80 && value < 0; i++) {
596
+ upper *= 2;
597
+ value = target(upper);
598
+ }
599
+ hi = value >= 0 ? root(target, 0, upper) : NaN;
600
+ }
601
+ }
602
+ const base = weightedFit(object.yi, object.vi, object.mods, 0);
603
+ const vtilde = df > 0 ? df * base.minVariance / base.tracePNorm : 0;
604
+ const transform = (t) => [
605
+ t, Math.sqrt(t), 100 * t / (t + vtilde), (t + vtilde) / vtilde
606
+ ];
607
+ const est = transform(object.tau2), low = transform(lo), up = transform(hi);
608
+ const labels = ["tau^2", "tau", "I^2(%)", "H^2"];
609
+ return { random: { dim: [4, 3], rowNames: labels, colNames: ["estimate", "ci.lb", "ci.ub"],
610
+ rows: labels.map((_, i) => ({ estimate: est[i], "ci.lb": low[i], "ci.ub": up[i] })) },
611
+ digits: { est: "4", se: "4", test: "4", pval: "4", ci: "4", var: "4", sevar: "4", fit: "4", het: "4" },
612
+ "ci.null": false, "lb.sign": "", "ub.sign": "", "tau2.min": "0" };
613
+ }
614
+ /** Predicts the mean effect and its prediction interval at moderator values. Equivalent to `metafor::predict.rma()` in R.
615
+ * @category Meta-analysis
616
+ */
617
+ export function predictRma(object, options = {}) {
618
+ checkOptions(options, PREDICT_RMA_KEYS, "predictRma"); // generated: option-keys.mjs
619
+ const level = options.level ?? object.level, alpha = 1 - level / 100, p = object.mods[0].length;
620
+ let rows;
621
+ if (options.newmods === undefined) {
622
+ const moderators = p - (object.intercept ? 1 : 0);
623
+ rows = moderators === 0 ? [object.intercept ? [1] : []] : object.mods.map(r => r.slice());
624
+ }
625
+ else {
626
+ const n = options.newmods;
627
+ if (n.length > 0 && typeof n[0] === "number")
628
+ rows = Array.from(n, z => object.intercept ? [1, z] : [z]);
629
+ else
630
+ rows = Array.from(n, r => Array.from(r));
631
+ if (rows.some(r => r.length === p - (object.intercept ? 1 : 0)))
632
+ rows = rows.map(r => object.intercept ? [1, ...r] : r);
633
+ if (rows.some(r => r.length !== p))
634
+ throw new RangeError("newmods has the wrong number of columns");
635
+ }
636
+ const beta = object.beta.rows.map(r => r[0]);
637
+ const pred = rows.map(r => dot(r, beta));
638
+ const se = rows.map(r => Math.sqrt(Math.max(0, dot(r, matVec(object.covariance, r)))));
639
+ const crit = object.test === "z" ? qnorm(1 - alpha / 2) : qt(1 - alpha / 2, object.k - p);
640
+ const piCrit = options.predtype === "riley" ? qt(1 - alpha / 2, object.k - p - 1) : crit;
641
+ const piScale = rows.map((_, i) => Math.sqrt(se[i] ** 2 + object.tau2));
642
+ return { pred: scalar(pred), se: scalar(se), "ci.lb": scalar(pred.map((z, i) => z - crit * se[i])),
643
+ "ci.ub": scalar(pred.map((z, i) => z + crit * se[i])), "pi.lb": scalar(pred.map((z, i) => z - piCrit * piScale[i])),
644
+ "pi.ub": scalar(pred.map((z, i) => z + piCrit * piScale[i])) };
645
+ }
646
+ /** Tests for funnel-plot asymmetry using a regression model. Equivalent to `metafor::regtest()` in R.
647
+ * @category Meta-analysis
648
+ */
649
+ export function regtest(x, viOrOptions, maybeOptions = {}) {
650
+ if (isOptionsObject(viOrOptions))
651
+ checkOptions(viOrOptions, REGTEST_KEYS, "regtest"); // generated: option-keys.mjs
652
+ checkOptions(maybeOptions, REGTEST_KEYS, "regtest"); // generated: option-keys.mjs
653
+ const isFit = typeof x === "object" && "beta" in x;
654
+ const options = (isFit ? viOrOptions : maybeOptions) ?? {};
655
+ const model = options.model ?? "rma", predictor = options.predictor ?? "sei", level = options.level ?? 95;
656
+ const y = Array.from(isFit ? x.yi : x);
657
+ const v = Array.from(isFit ? x.vi : viOrOptions ?? []);
658
+ if (y.length !== v.length || y.length < 2)
659
+ throw new RangeError("yi and vi must have equal lengths and at least two studies");
660
+ const sei = v.map(z => Math.sqrt(z));
661
+ const z = predictor === "sei" ? sei : predictor === "vi" ? v : v.map((_, i) => 1 / (i + 1));
662
+ let est, se, stat, df, pv;
663
+ let fitted;
664
+ if (model === "lm") {
665
+ const xx = z.map((a, i) => [1, 1 / a]), yy = y.map((a, i) => a / sei[i]);
666
+ const fit = linearRegression(xx, yy);
667
+ est = fit.beta[1];
668
+ const seTest = Math.sqrt(fit.cov[0][0] * fit.sigma2), seLimit = Math.sqrt(fit.cov[1][1] * fit.sigma2);
669
+ stat = fit.beta[0] / seTest;
670
+ se = seLimit;
671
+ df = y.length - 2;
672
+ pv = 2 * pt(-Math.abs(stat), df);
673
+ }
674
+ else {
675
+ fitted = rma(y, v, { method: "REML", mods: z, intercept: true, test: "z" });
676
+ est = fitted.beta.rows[0][0];
677
+ se = Array.isArray(fitted.se) ? fitted.se[0] : fitted.se;
678
+ const moderatorZ = Array.isArray(fitted.zval) ? fitted.zval[1] : NaN;
679
+ const moderatorP = Array.isArray(fitted.pval) ? fitted.pval[1] : NaN;
680
+ stat = moderatorZ;
681
+ df = NaN;
682
+ pv = moderatorP;
683
+ }
684
+ const crit = model === "lm" ? qt(1 - (1 - level / 100) / 2, df) : qnorm(1 - (1 - level / 100) / 2);
685
+ const warnings = [];
686
+ if (model === "lm" && (!Number.isFinite(stat) || !Number.isFinite(pv) || !Number.isFinite(se)))
687
+ warnings.push("NaNs produced");
688
+ const out = { model, predictor, zval: stat, pval: pv, dfs: df, est, "ci.lb": est - crit * se, "ci.ub": est + crit * se, warnings };
689
+ return reported("regtest", options.retFit && fitted !== undefined ? { ...out, fit: fitted } : out);
690
+ }
691
+ function linearRegression(X, y) {
692
+ const xtx = Array.from({ length: 2 }, (_, a) => Array.from({ length: 2 }, (_, b) => X.reduce((s, r, i) => s + r[a] * r[b], 0)));
693
+ const inv = solve(xtx, identity(2)), beta = matVec(inv, Array.from({ length: 2 }, (_, a) => X.reduce((s, r, i) => s + r[a] * y[i], 0)));
694
+ const res = y.map((v, i) => v - dot(X[i], beta)), sigma2 = y.length > 2 ? res.reduce((s, z) => s + z * z, 0) / (y.length - 2) : NaN;
695
+ return { beta, cov: inv, sigma2 };
696
+ }